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 |
|---|---|---|---|---|---|---|---|---|---|---|
64abbdd6f274333fbdc3d6a51b2876c3110986d6 | flink-runtime-web/web-dashboard/src/app/app.config.ts | flink-runtime-web/web-dashboard/src/app/app.config.ts | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 const BASE_URL = '.';
export const COLOR_MAP = {
TOTAL: '#112641',
RUNNING: '#52c41a',
FAILED: '#f5222d',
FINISHED: '#1890ff',
CANCELED: '#fa8c16',
CANCELING: '#faad14',
CREATED: '#2f54eb',
DEPLOYING: '#13c2c2',
RECONCILING: '#eb2f96',
IN_PROGRESS: '#faad14',
SCHEDULED: '#722ed1',
COMPLETED : '#1890ff'
};
export const LONG_MIN_VALUE = -9223372036854776000;
| /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 const BASE_URL = '.';
export const COLOR_MAP = {
TOTAL: '#112641',
RUNNING: '#52c41a',
FAILED: '#f5222d',
FINISHED: '#1890ff',
CANCELED: '#fa8c16',
CANCELING: '#faad14',
CREATED: '#2f54eb',
DEPLOYING: '#13c2c2',
RECONCILING: '#eb2f96',
IN_PROGRESS: '#faad14',
SCHEDULED: '#722ed1',
COMPLETED: '#1890ff',
RESTARTING: '#13c2c2'
};
export const LONG_MIN_VALUE = -9223372036854776000;
| Fix color of RESTARTING status in Web UI | [FLINK-15953][web] Fix color of RESTARTING status in Web UI
This closes #11433.
| TypeScript | apache-2.0 | zentol/flink,rmetzger/flink,greghogan/flink,StephanEwen/incubator-flink,sunjincheng121/flink,zjureel/flink,kaibozhou/flink,kl0u/flink,GJL/flink,godfreyhe/flink,tony810430/flink,tillrohrmann/flink,apache/flink,xccui/flink,godfreyhe/flink,twalthr/flink,xccui/flink,greghogan/flink,zjureel/flink,clarkyzl/flink,hequn8128/flink,zentol/flink,lincoln-lil/flink,kaibozhou/flink,darionyaphet/flink,darionyaphet/flink,kl0u/flink,wwjiang007/flink,clarkyzl/flink,clarkyzl/flink,zjureel/flink,kl0u/flink,apache/flink,bowenli86/flink,tony810430/flink,xccui/flink,StephanEwen/incubator-flink,greghogan/flink,sunjincheng121/flink,greghogan/flink,zjureel/flink,gyfora/flink,hequn8128/flink,tony810430/flink,sunjincheng121/flink,lincoln-lil/flink,wwjiang007/flink,aljoscha/flink,tony810430/flink,rmetzger/flink,tillrohrmann/flink,apache/flink,jinglining/flink,xccui/flink,apache/flink,rmetzger/flink,godfreyhe/flink,hequn8128/flink,StephanEwen/incubator-flink,lincoln-lil/flink,hequn8128/flink,jinglining/flink,greghogan/flink,wwjiang007/flink,bowenli86/flink,aljoscha/flink,godfreyhe/flink,jinglining/flink,tillrohrmann/flink,hequn8128/flink,wwjiang007/flink,GJL/flink,apache/flink,xccui/flink,zjureel/flink,kaibozhou/flink,apache/flink,godfreyhe/flink,tzulitai/flink,aljoscha/flink,rmetzger/flink,zentol/flink,tony810430/flink,tillrohrmann/flink,darionyaphet/flink,sunjincheng121/flink,lincoln-lil/flink,GJL/flink,twalthr/flink,lincoln-lil/flink,GJL/flink,twalthr/flink,StephanEwen/incubator-flink,greghogan/flink,wwjiang007/flink,kl0u/flink,jinglining/flink,darionyaphet/flink,kl0u/flink,gyfora/flink,lincoln-lil/flink,zentol/flink,twalthr/flink,StephanEwen/incubator-flink,tony810430/flink,rmetzger/flink,xccui/flink,aljoscha/flink,darionyaphet/flink,hequn8128/flink,tzulitai/flink,bowenli86/flink,tillrohrmann/flink,zjureel/flink,kaibozhou/flink,tillrohrmann/flink,kaibozhou/flink,StephanEwen/incubator-flink,tzulitai/flink,gyfora/flink,gyfora/flink,clarkyzl/flink,clarkyzl/flink,bowenli86/flink,godfreyhe/flink,GJL/flink,sunjincheng121/flink,lincoln-lil/flink,rmetzger/flink,wwjiang007/flink,zentol/flink,tillrohrmann/flink,gyfora/flink,gyfora/flink,zjureel/flink,tzulitai/flink,sunjincheng121/flink,kl0u/flink,zentol/flink,jinglining/flink,jinglining/flink,gyfora/flink,aljoscha/flink,twalthr/flink,kaibozhou/flink,bowenli86/flink,tzulitai/flink,twalthr/flink,xccui/flink,godfreyhe/flink,GJL/flink,apache/flink,bowenli86/flink,wwjiang007/flink,twalthr/flink,tony810430/flink,tzulitai/flink,aljoscha/flink,zentol/flink,rmetzger/flink | ---
+++
@@ -29,6 +29,7 @@
RECONCILING: '#eb2f96',
IN_PROGRESS: '#faad14',
SCHEDULED: '#722ed1',
- COMPLETED : '#1890ff'
+ COMPLETED: '#1890ff',
+ RESTARTING: '#13c2c2'
};
export const LONG_MIN_VALUE = -9223372036854776000; |
5c373c9baf6a0abfab09025d35d4b2deeb37baca | src/app/utilities/download-helper.ts | src/app/utilities/download-helper.ts | /**
* Copyright 2017 - 2018 The Hyve B.V.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import * as sanitize from 'sanitize-filename';
export class DownloadHelper {
public static downloadJSON(dataObject: object, fileName: string) {
if (dataObject === null) {
throw new Error('No data to download.');
}
if (fileName === null) {
throw new Error('Missing file name.');
}
fileName = sanitize(fileName.trim());
if (fileName.length === 0) {
throw new Error('Empty file name.');
}
let data = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(dataObject));
let el = document.createElement('a');
el.setAttribute('href', data);
el.setAttribute('download', fileName + '.json');
el.style.display = 'none';
document.body.appendChild(el);
el.click();
document.body.removeChild(el);
}
}
| /**
* Copyright 2017 - 2018 The Hyve B.V.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import * as sanitize from 'sanitize-filename';
import {saveAs} from 'file-saver';
export class DownloadHelper {
public static downloadJSON(dataObject: object, fileName: string) {
if (dataObject === null) {
throw new Error('No data to download.');
}
if (fileName === null) {
throw new Error('Missing file name.');
}
fileName = sanitize(fileName.trim());
if (fileName.length === 0) {
throw new Error('Empty file name.');
}
const blob = new Blob([JSON.stringify(dataObject)], {type: 'text/json'});
saveAs(blob, `${fileName}.json`, true);
}
}
| Fix cohort download in Edge. | Fix cohort download in Edge.
| TypeScript | mpl-2.0 | thehyve/glowing-bear,thehyve/glowing-bear,thehyve/glowing-bear,thehyve/glowing-bear | ---
+++
@@ -7,6 +7,7 @@
*/
import * as sanitize from 'sanitize-filename';
+import {saveAs} from 'file-saver';
export class DownloadHelper {
@@ -21,14 +22,8 @@
if (fileName.length === 0) {
throw new Error('Empty file name.');
}
- let data = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(dataObject));
- let el = document.createElement('a');
- el.setAttribute('href', data);
- el.setAttribute('download', fileName + '.json');
- el.style.display = 'none';
- document.body.appendChild(el);
- el.click();
- document.body.removeChild(el);
+ const blob = new Blob([JSON.stringify(dataObject)], {type: 'text/json'});
+ saveAs(blob, `${fileName}.json`, true);
}
} |
7a09f4c63608995029caa8fa3fee644b05ea264a | src/app/product/product.reducer.ts | src/app/product/product.reducer.ts | import { Action, ActionReducer } from '@ngrx/store';
import { ProductActions } from './product.actions';
export const ProductReducer: ActionReducer<any> = (state: any = [], { payload, type }) => {
switch (type) {
case ProductActions.FETCH_PRODUCT:
console.log('product')
return state[0];
case ProductActions.FETCH_PRODUCTS_FULFILLED:
return payload.products || [];
default:
return state;
}
} | import { Action, ActionReducer } from '@ngrx/store';
import { ProductActions } from './product.actions';
export const ProductReducer: ActionReducer<any> = (state: any = [], { payload, type }) => {
switch (type) {
case ProductActions.FETCH_PRODUCT:
console.log('product')
return state;
case ProductActions.FETCH_PRODUCTS_FULFILLED:
return payload.products || [];
default:
return state;
}
} | Revert code that not ready to implement | Revert code that not ready to implement
| TypeScript | mit | dl988/quedro,dl988/quedro,dl988/quedro | ---
+++
@@ -5,7 +5,7 @@
switch (type) {
case ProductActions.FETCH_PRODUCT:
console.log('product')
- return state[0];
+ return state;
case ProductActions.FETCH_PRODUCTS_FULFILLED:
return payload.products || []; |
1c7623648e647218f02f2000402ff08c5e4b9f19 | app/src/ui/open-pull-request/pull-request-merge-status.tsx | app/src/ui/open-pull-request/pull-request-merge-status.tsx | import * as React from 'react'
import { MergeTreeResult } from '../../models/merge'
interface IPullRequestMergeStatusProps {
/** The result of merging the pull request branch into the base branch */
readonly mergeStatus: MergeTreeResult | null
}
/** The component to display message about the result of merging the pull
* request. */
export class PullRequestMergeStatus extends React.Component<IPullRequestMergeStatusProps> {
public render() {
return <div className="pull-request-merge-status">Merge Status</div>
}
}
| import * as React from 'react'
import { assertNever } from '../../lib/fatal-error'
import { ComputedAction } from '../../models/computed-action'
import { MergeTreeResult } from '../../models/merge'
import { Octicon } from '../octicons'
import * as OcticonSymbol from '../octicons/octicons.generated'
interface IPullRequestMergeStatusProps {
/** The result of merging the pull request branch into the base branch */
readonly mergeStatus: MergeTreeResult | null
}
/** The component to display message about the result of merging the pull
* request. */
export class PullRequestMergeStatus extends React.Component<IPullRequestMergeStatusProps> {
private getMergeStatusDescription = () => {
const { mergeStatus } = this.props
if (mergeStatus === null) {
return ''
}
const { kind } = mergeStatus
switch (kind) {
case ComputedAction.Loading:
return (
<span className="pr-merge-status-loading">
<strong>Checking mergeability…</strong> Don’t worry, you can
still create the pull request.
</span>
)
case ComputedAction.Invalid:
return (
<span className="pr-merge-status-invalid">
<strong>Error checking merge status.</strong> Don’t worry, you can
still create the pull request.
</span>
)
case ComputedAction.Clean:
return (
<span className="pr-merge-status-clean">
<strong>
<Octicon symbol={OcticonSymbol.check} /> Able to merge.
</strong>{' '}
These branches can be automatically merged.
</span>
)
case ComputedAction.Conflicts:
return (
<span className="pr-merge-status-conflicts">
<strong>
<Octicon symbol={OcticonSymbol.x} /> Can't automatically merge.
</strong>{' '}
Don’t worry, you can still create the pull request.
</span>
)
default:
return assertNever(kind, `Unknown merge status kind of ${kind}.`)
}
}
public render() {
return (
<div className="pull-request-merge-status">
{this.getMergeStatusDescription()}
</div>
)
}
}
| Add messages for each merge status kind | Add messages for each merge status kind
Copying dotcom verbiage
| TypeScript | mit | shiftkey/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,desktop/desktop | ---
+++
@@ -1,5 +1,9 @@
import * as React from 'react'
+import { assertNever } from '../../lib/fatal-error'
+import { ComputedAction } from '../../models/computed-action'
import { MergeTreeResult } from '../../models/merge'
+import { Octicon } from '../octicons'
+import * as OcticonSymbol from '../octicons/octicons.generated'
interface IPullRequestMergeStatusProps {
/** The result of merging the pull request branch into the base branch */
@@ -9,7 +13,56 @@
/** The component to display message about the result of merging the pull
* request. */
export class PullRequestMergeStatus extends React.Component<IPullRequestMergeStatusProps> {
+ private getMergeStatusDescription = () => {
+ const { mergeStatus } = this.props
+ if (mergeStatus === null) {
+ return ''
+ }
+
+ const { kind } = mergeStatus
+ switch (kind) {
+ case ComputedAction.Loading:
+ return (
+ <span className="pr-merge-status-loading">
+ <strong>Checking mergeability…</strong> Don’t worry, you can
+ still create the pull request.
+ </span>
+ )
+ case ComputedAction.Invalid:
+ return (
+ <span className="pr-merge-status-invalid">
+ <strong>Error checking merge status.</strong> Don’t worry, you can
+ still create the pull request.
+ </span>
+ )
+ case ComputedAction.Clean:
+ return (
+ <span className="pr-merge-status-clean">
+ <strong>
+ <Octicon symbol={OcticonSymbol.check} /> Able to merge.
+ </strong>{' '}
+ These branches can be automatically merged.
+ </span>
+ )
+ case ComputedAction.Conflicts:
+ return (
+ <span className="pr-merge-status-conflicts">
+ <strong>
+ <Octicon symbol={OcticonSymbol.x} /> Can't automatically merge.
+ </strong>{' '}
+ Don’t worry, you can still create the pull request.
+ </span>
+ )
+ default:
+ return assertNever(kind, `Unknown merge status kind of ${kind}.`)
+ }
+ }
+
public render() {
- return <div className="pull-request-merge-status">Merge Status</div>
+ return (
+ <div className="pull-request-merge-status">
+ {this.getMergeStatusDescription()}
+ </div>
+ )
}
} |
0d8de7de0b4e847bfa2c3ea75af7493627f8f2d1 | tests/custom_decorator.spec.ts | tests/custom_decorator.spec.ts | import {
getType,
mustGetType
} from '../src';
function UserDecorator(target: any) { }
function OtherDecorator(target: any) { }
@UserDecorator
export class MyClassA {
a: string;
}
@OtherDecorator
export class MyClassB {
a: string;
}
describe('Custom Decorators', () => {
// Note UserDecorator is configured in webpack.test.js
it('should allow UserDecorator', () => {
const clsType = getType(MyClassA);
expect(clsType).not.toBeNull();
});
it('should throw on non-decorated', () => {
expect(() => {
mustGetType(MyClassB);
}).toThrow();
});
});
| import {
getType,
mustGetType
} from '../src';
function UserDecorator(target: any) {
// Verifies that tsruntime decorations are
// available before user decorator is applied.
const clsType = mustGetType(target);
}
function OtherDecorator(target: any) { }
@UserDecorator
export class MyClassA {
a: string;
}
@OtherDecorator
export class MyClassB {
a: string;
}
describe('Custom Decorators', () => {
// Note UserDecorator is configured in webpack.test.js
it('should allow UserDecorator', () => {
const clsType = getType(MyClassA);
expect(clsType).not.toBeNull();
});
it('should throw on non-decorated', () => {
expect(() => {
mustGetType(MyClassB);
}).toThrow();
});
});
| Add a test to check the decorator ordering. | Add a test to check the decorator ordering.
This makes sure we have runtime information while the decorators
are executing.
| TypeScript | mit | goloveychuk/tsruntime,goloveychuk/tsruntime | ---
+++
@@ -4,7 +4,11 @@
} from '../src';
-function UserDecorator(target: any) { }
+function UserDecorator(target: any) {
+ // Verifies that tsruntime decorations are
+ // available before user decorator is applied.
+ const clsType = mustGetType(target);
+}
function OtherDecorator(target: any) { }
|
5befd67eabb90ec9bd3308ca4319aae6d3c6ac08 | types/saywhen/saywhen-tests.ts | types/saywhen/saywhen-tests.ts | import when = require('saywhen');
when(jasmine.createSpy('test')); // $ExpectType CallHandler<Spy>
when(jasmine.createSpy('test')).isCalled; // $ExpectType Proxy<Spy>
when.captor(); // $ExpectType MatcherProxy<{}>
when.captor(jasmine.any(Number)); // $ExpectType MatcherProxy<Any>
when.noConflict(); // $ExpectType void
| import when = require('saywhen');
// This interface is needed to get around the fact that the new jasmine
// `createSpy` method takes a generic type while the old typings don't.
// That means that in Typescript 3.0 the spy will be `Spy` and in 3.1 it
// will be `Spy<InferableFunction>`. This interface matches both and is
// what dtslint will expect the type to be.
interface JasmineSpy extends jasmine.Spy {
(...params: any[]): any;
}
const spy: JasmineSpy = jasmine.createSpy('test');
when(spy); // $ExpectType CallHandler<JasmineSpy>
when(spy).isCalled; // $ExpectType Proxy<JasmineSpy>
when.captor(); // $ExpectType MatcherProxy<{}>
when.captor(jasmine.any(Number)); // $ExpectType MatcherProxy<Any>
when.noConflict(); // $ExpectType void
| Fix the build with a hack | Fix the build with a hack
| TypeScript | mit | georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped | ---
+++
@@ -1,7 +1,17 @@
import when = require('saywhen');
-when(jasmine.createSpy('test')); // $ExpectType CallHandler<Spy>
-when(jasmine.createSpy('test')).isCalled; // $ExpectType Proxy<Spy>
+// This interface is needed to get around the fact that the new jasmine
+// `createSpy` method takes a generic type while the old typings don't.
+// That means that in Typescript 3.0 the spy will be `Spy` and in 3.1 it
+// will be `Spy<InferableFunction>`. This interface matches both and is
+// what dtslint will expect the type to be.
+interface JasmineSpy extends jasmine.Spy {
+ (...params: any[]): any;
+}
+const spy: JasmineSpy = jasmine.createSpy('test');
+
+when(spy); // $ExpectType CallHandler<JasmineSpy>
+when(spy).isCalled; // $ExpectType Proxy<JasmineSpy>
when.captor(); // $ExpectType MatcherProxy<{}>
when.captor(jasmine.any(Number)); // $ExpectType MatcherProxy<Any> |
204ea22674a737f75babdf3c3488a5a814769131 | types/react-toggle/react-toggle-tests.tsx | types/react-toggle/react-toggle-tests.tsx | import * as React from "react";
import Toggle, { ToggleIcons } from "react-toggle";
class Test extends React.Component {
handleEvent = (e: any) => {};
render() {
const icons: ToggleIcons = {
checked : (<div />),
unchecked : (<div />),
};
return (
<div>
<Toggle
checked
defaultChecked
onChange={ this.handleEvent }
onFocus={ this.handleEvent }
onBlur={ this.handleEvent }
name="toggle"
value="value"
id="toggle"
icons={ icons }
aria-labelby="test"
aria-label="test"
disabled
/>
<Toggle
icons={ false }
/>
</div>
);
}
}
| import * as React from "react";
import { SyntheticEvent } from "react";
import Toggle, { ToggleIcons } from "react-toggle";
class Test extends React.Component {
handleEvent = (e: SyntheticEvent<HTMLInputElement>) => {};
render() {
const icons: ToggleIcons = {
checked : (<div />),
unchecked : (<div />),
};
return (
<div>
<Toggle
checked
defaultChecked
onChange={ this.handleEvent }
onFocus={ this.handleEvent }
onBlur={ this.handleEvent }
name="toggle"
value="value"
id="toggle"
icons={ icons }
aria-labelby="test"
aria-label="test"
disabled
/>
<Toggle
icons={ false }
/>
</div>
);
}
}
| Add type for hendler event in tests | Add type for hendler event in tests
| TypeScript | mit | dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,one-pieces/DefinitelyTyped,amir-arad/DefinitelyTyped,arusakov/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,magny/DefinitelyTyped,mcliment/DefinitelyTyped,magny/DefinitelyTyped,nycdotnet/DefinitelyTyped,chrootsu/DefinitelyTyped,abbasmhd/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,minodisk/DefinitelyTyped,benishouga/DefinitelyTyped,minodisk/DefinitelyTyped,dsebastien/DefinitelyTyped,aciccarello/DefinitelyTyped,arusakov/DefinitelyTyped,jimthedev/DefinitelyTyped,alexdresko/DefinitelyTyped,jimthedev/DefinitelyTyped,benishouga/DefinitelyTyped,georgemarshall/DefinitelyTyped,ashwinr/DefinitelyTyped,markogresak/DefinitelyTyped,borisyankov/DefinitelyTyped,ashwinr/DefinitelyTyped,georgemarshall/DefinitelyTyped,arusakov/DefinitelyTyped,abbasmhd/DefinitelyTyped,georgemarshall/DefinitelyTyped,alexdresko/DefinitelyTyped,zuzusik/DefinitelyTyped,benliddicott/DefinitelyTyped,jimthedev/DefinitelyTyped,borisyankov/DefinitelyTyped,nycdotnet/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,chrootsu/DefinitelyTyped,rolandzwaga/DefinitelyTyped,QuatroCode/DefinitelyTyped,AgentME/DefinitelyTyped,QuatroCode/DefinitelyTyped,benishouga/DefinitelyTyped,georgemarshall/DefinitelyTyped,aciccarello/DefinitelyTyped,zuzusik/DefinitelyTyped,AgentME/DefinitelyTyped,aciccarello/DefinitelyTyped | ---
+++
@@ -1,8 +1,9 @@
import * as React from "react";
+import { SyntheticEvent } from "react";
import Toggle, { ToggleIcons } from "react-toggle";
class Test extends React.Component {
- handleEvent = (e: any) => {};
+ handleEvent = (e: SyntheticEvent<HTMLInputElement>) => {};
render() {
const icons: ToggleIcons = { |
3d89cf9acedf37c8d6c978cad684cc3a694b2268 | src/data/defaults.ts | src/data/defaults.ts | const defaults = {
config: {
"app": {
"environment": "prod",
"port": 3000
},
"slack": {
"token": ""
},
"cwmanage": {
"companyId": "",
"companyUrl": "api-na.myconnectwise.net",
"publicKey": "",
"privateKey": "",
"timeout": 5000
}
}
};
export default defaults; | const defaults = {
config: {
"app": {
"environment": "prod",
"port": 80
},
"slack": {
"token": ""
},
"cwmanage": {
"companyId": "",
"companyUrl": "api-na.myconnectwise.net",
"publicKey": "",
"privateKey": "",
"timeout": 5000
}
}
};
export default defaults; | Change default port to 80 | Change default port to 80
| TypeScript | mit | sgtoj/cw-manage-slack-bot,sgtoj/cw-manage-slack-bot | ---
+++
@@ -2,7 +2,7 @@
config: {
"app": {
"environment": "prod",
- "port": 3000
+ "port": 80
},
"slack": {
"token": "" |
b167115e743d00d6d62133e3ee84a5d082bc5ad9 | app/app.component.ts | app/app.component.ts | import { Component } from '@angular/core';
export class Hero{
id:number;
name:string;
}
@Component({
selector: 'my-app',
template:`
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input value = "{{hero.name}}"placeholder = "name">
<div>
`
})
export class AppComponent {
title = 'Tour of heroes';
hero: Hero = {
id: 1,
name:'Spiderman' };
}
| import { Component } from '@angular/core';
export class Hero{
id:number;
name:string;
}
@Component({
selector: 'my-app',
template:`
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)] = "hero.name"placeholder = "name">
<div>
`
})
export class AppComponent {
title = 'Tour of heroes';
hero: Hero = {
id: 1,
name:'Spiderman' };
}
| Add ngModel - inbuilt for Two way data binding | Add ngModel - inbuilt for Two way data binding
| TypeScript | mit | amalshehu/angular-tour-of-heroes,amalshehu/angular-tour-of-heroes,amalshehu/angular-tour-of-heroes | ---
+++
@@ -12,7 +12,7 @@
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
- <input value = "{{hero.name}}"placeholder = "name">
+ <input [(ngModel)] = "hero.name"placeholder = "name">
<div>
`
}) |
93ec9eed7ab041cb46b83d195b20632277da2aab | demo/14-page-numbers.ts | demo/14-page-numbers.ts | // Page numbers
// Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs";
import { AlignmentType, Document, Header, Packer, PageBreak, PageNumber, Paragraph, TextRun } from "../build";
const doc = new Document();
doc.addSection({
headers: {
default: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("My Title "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
first: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("First Page Header "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
},
children: [
new Paragraph({
children: [new TextRun("First Page"), new PageBreak()],
}),
new Paragraph("Second Page"),
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
| // Page numbers
// Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs";
import { AlignmentType, Document, Footer, Header, Packer, PageBreak, PageNumber, Paragraph, TextRun } from "../build";
const doc = new Document();
doc.addSection({
properties: {
titlePage: true,
},
headers: {
default: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("My Title "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
first: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("First Page Header "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
},
footers: {
default: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("My Title "),
new TextRun({
children: ["Footer - Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
first: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("First Page Footer "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
},
children: [
new Paragraph({
children: [new TextRun("First Page"), new PageBreak()],
}),
new Paragraph("Second Page"),
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
| Add titlePage to first page header | Add titlePage to first page header
| TypeScript | mit | dolanmiu/docx,dolanmiu/docx,dolanmiu/docx | ---
+++
@@ -1,11 +1,14 @@
// Page numbers
// Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs";
-import { AlignmentType, Document, Header, Packer, PageBreak, PageNumber, Paragraph, TextRun } from "../build";
+import { AlignmentType, Document, Footer, Header, Packer, PageBreak, PageNumber, Paragraph, TextRun } from "../build";
const doc = new Document();
doc.addSection({
+ properties: {
+ titlePage: true,
+ },
headers: {
default: new Header({
children: [
@@ -34,6 +37,34 @@
],
}),
},
+ footers: {
+ default: new Footer({
+ children: [
+ new Paragraph({
+ alignment: AlignmentType.RIGHT,
+ children: [
+ new TextRun("My Title "),
+ new TextRun({
+ children: ["Footer - Page ", PageNumber.CURRENT],
+ }),
+ ],
+ }),
+ ],
+ }),
+ first: new Footer({
+ children: [
+ new Paragraph({
+ alignment: AlignmentType.RIGHT,
+ children: [
+ new TextRun("First Page Footer "),
+ new TextRun({
+ children: ["Page ", PageNumber.CURRENT],
+ }),
+ ],
+ }),
+ ],
+ }),
+ },
children: [
new Paragraph({
children: [new TextRun("First Page"), new PageBreak()], |
e2d1e3ac48f8cc3b3bfc0193cacd8ee0a969f9af | framework/src/JovoRequest.ts | framework/src/JovoRequest.ts | import { EntityMap, NluData } from './interfaces';
import { JovoRequestType } from './Jovo';
import { JovoSession } from './JovoSession';
export abstract class JovoRequest {
[key: string]: unknown;
abstract getEntities(): EntityMap | undefined;
abstract getIntentName(): string | undefined;
abstract getLocale(): string | undefined;
abstract getRawText(): string | undefined;
abstract getRequestType(): JovoRequestType | undefined;
abstract getSession(): JovoSession | undefined;
getNluData(): NluData | undefined {
const intentName = this.getIntentName();
const entities = this.getEntities();
return {
intent: intentName ? { name: intentName } : undefined,
entities,
};
}
}
| import { EntityMap, NluData } from './interfaces';
import { JovoRequestType } from './Jovo';
import { JovoSession } from './JovoSession';
export abstract class JovoRequest {
[key: string]: unknown;
abstract getEntities(): EntityMap | undefined;
abstract getIntentName(): string | undefined;
abstract getLocale(): string | undefined;
abstract getRawText(): string | undefined;
abstract getRequestType(): JovoRequestType | undefined;
abstract getSession(): JovoSession | undefined;
getNluData(): NluData | undefined {
const nluData: NluData = {};
const intentName = this.getIntentName();
const entities = this.getEntities();
if (intentName) {
nluData.intent = {
name: intentName,
};
}
if (entities) {
nluData.entities = entities;
}
return nluData;
}
}
| Change getNluData to not have an entities or intent-key if those are not defined | :recycle: Change getNluData to not have an entities or intent-key if those are not defined
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -18,11 +18,17 @@
abstract getSession(): JovoSession | undefined;
getNluData(): NluData | undefined {
+ const nluData: NluData = {};
const intentName = this.getIntentName();
const entities = this.getEntities();
- return {
- intent: intentName ? { name: intentName } : undefined,
- entities,
- };
+ if (intentName) {
+ nluData.intent = {
+ name: intentName,
+ };
+ }
+ if (entities) {
+ nluData.entities = entities;
+ }
+ return nluData;
}
} |
cc2eec0dde8920fb68398cb9490237e5af791c59 | app/src/main-process/menu/menu-ids.ts | app/src/main-process/menu/menu-ids.ts | export type MenuIDs =
| 'rename-branch'
| 'delete-branch'
| 'preferences'
| 'update-branch'
| 'merge-branch'
| 'view-repository-on-github'
| 'compare-on-github'
| 'open-in-shell'
| 'push'
| 'pull'
| 'branch'
| 'repository'
| 'create-branch'
| 'create-commit'
| 'show-history'
| 'show-repository-list'
| 'show-branches-list'
| 'open-working-directory'
| 'show-repository-settings'
| 'open-external-editor'
| 'remove-repository'
| 'new-repository'
| 'add-local-repository'
| 'clone-repository'
| 'about'
| 'create-pull-request'
| export type MenuIDs =
| 'rename-branch'
| 'delete-branch'
| 'preferences'
| 'update-branch'
| 'merge-branch'
| 'view-repository-on-github'
| 'compare-on-github'
| 'open-in-shell'
| 'push'
| 'pull'
| 'branch'
| 'repository'
| 'create-branch'
| 'create-commit'
| 'show-history'
| 'show-repository-list'
| 'show-branches-list'
| 'open-working-directory'
| 'show-repository-settings'
| 'open-external-editor'
| 'remove-repository'
| 'new-repository'
| 'add-local-repository'
| 'clone-repository'
| 'about'
| 'create-pull-request'
| 'compare-to-branch'
| Add menu id to list of menu ids | Add menu id to list of menu ids
| TypeScript | mit | kactus-io/kactus,say25/desktop,desktop/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,say25/desktop,j-f1/forked-desktop | ---
+++
@@ -25,3 +25,4 @@
| 'clone-repository'
| 'about'
| 'create-pull-request'
+ | 'compare-to-branch' |
df4607827430b8d34323de25e4b0bca8f46d0958 | app/core/services/load/index.ts | app/core/services/load/index.ts | import { Service } from 'typedi';
import { action } from 'mobx';
import { range } from 'lodash';
import { ClipActions } from 'core/actions/clip';
import { TrackStore } from 'core/state/stores/tracks';
import { TimelineVector } from '../../primitives/timeline-vector';
@Service()
export class LoadService {
constructor(private clipActions: ClipActions, private trackStore: TrackStore) {}
@action
loadSession() {
const tracks = range(3).map(() => this.trackStore.createTrack());
const clip = this.clipActions.createClip({
trackId: tracks[0].id,
length: new TimelineVector(2),
position: new TimelineVector(4),
});
this.clipActions.editClip(clip.id);
}
}
| import { Service } from 'typedi';
import { action } from 'mobx';
import { range } from 'lodash';
import { ClipActions } from 'core/actions/clip';
import { TrackStore } from 'core/state/stores/tracks';
import { TimelineVector } from '../../primitives/timeline-vector';
@Service()
export class LoadService {
constructor(private clipActions: ClipActions, private trackStore: TrackStore) {}
@action
loadSession() {
const tracks = range(8).map(() => this.trackStore.createTrack());
const clip = this.clipActions.createClip({
trackId: tracks[0].id,
length: new TimelineVector(2),
position: new TimelineVector(4),
});
this.clipActions.editClip(clip.id);
}
}
| Load 8 tracks instead of 3 | Load 8 tracks instead of 3
| TypeScript | mit | cannoneyed/fiddle,cannoneyed/fiddle,cannoneyed/fiddle | ---
+++
@@ -12,7 +12,7 @@
@action
loadSession() {
- const tracks = range(3).map(() => this.trackStore.createTrack());
+ const tracks = range(8).map(() => this.trackStore.createTrack());
const clip = this.clipActions.createClip({
trackId: tracks[0].id,
length: new TimelineVector(2), |
60fe4b675e9cf78821f8646db479b9cc578a05ac | tools/env/prod.ts | tools/env/prod.ts | import {EnvConfig} from './env-config.interface';
const ProdConfig: EnvConfig = {
ENV: 'PROD',
API: 'https://kd32ih1imd.execute-api.us-east-1.amazonaws.com/dev'
};
export = ProdConfig;
| import {EnvConfig} from './env-config.interface';
const ProdConfig: EnvConfig = {
ENV: 'PROD',
API: 'https://kd32ih1imd.execute-api.us-east-1.amazonaws.com/test'
};
export = ProdConfig;
| Update Prod Test API URL | Update Prod Test API URL
| TypeScript | mit | formigio/angular-frontend,formigio/angular-frontend,formigio/angular-frontend | ---
+++
@@ -2,7 +2,7 @@
const ProdConfig: EnvConfig = {
ENV: 'PROD',
- API: 'https://kd32ih1imd.execute-api.us-east-1.amazonaws.com/dev'
+ API: 'https://kd32ih1imd.execute-api.us-east-1.amazonaws.com/test'
};
export = ProdConfig; |
fe8225bbfcb63e6db0ecd4227a61dde226a369b7 | applications/calendar/src/app/helpers/timezoneSuggestion.ts | applications/calendar/src/app/helpers/timezoneSuggestion.ts | import { SHA256, binaryStringToArray, arrayToHexString } from 'pmcrypto';
const DAY_IN_MILLISECONDS = 86400000;
const LOCALSTORAGE_TZ_KEY = 'tzSuggestion';
export const getTimezoneSuggestionKey = async (userID: string) => {
const value = await SHA256(binaryStringToArray(`${LOCALSTORAGE_TZ_KEY}${userID}`));
return arrayToHexString(value);
};
export const getLastTimezoneSuggestion = (key: string) => {
const defaultDate = new Date(2000, 0, 1);
try {
const lastSuggestion = parseInt(`${window.localStorage.getItem(key)}`, 10);
const date = new Date(lastSuggestion);
if (Number.isNaN(+date)) {
return defaultDate;
}
return date;
} catch (e) {
return defaultDate;
}
};
export const saveLastTimezoneSuggestion = (key: string) => {
try {
const timestamp = +new Date();
window.localStorage.setItem(key, `${timestamp}`);
// eslint-disable-next-line no-empty
} catch (e) {}
};
export const canAskTimezoneSuggestion = (key: string) => {
return Date.now() - +getLastTimezoneSuggestion(key) >= DAY_IN_MILLISECONDS;
};
| import { getSHA256String } from 'proton-shared/lib/helpers/hash';
const DAY_IN_MILLISECONDS = 86400000;
const LOCALSTORAGE_TZ_KEY = 'tzSuggestion';
export const getTimezoneSuggestionKey = async (userID: string) => {
return getSHA256String(`${LOCALSTORAGE_TZ_KEY}${userID}`);
};
export const getLastTimezoneSuggestion = (key: string) => {
const defaultDate = new Date(2000, 0, 1);
try {
const lastSuggestion = parseInt(`${window.localStorage.getItem(key)}`, 10);
const date = new Date(lastSuggestion);
if (Number.isNaN(+date)) {
return defaultDate;
}
return date;
} catch (e) {
return defaultDate;
}
};
export const saveLastTimezoneSuggestion = (key: string) => {
try {
const timestamp = +new Date();
window.localStorage.setItem(key, `${timestamp}`);
// eslint-disable-next-line no-empty
} catch (e) {}
};
export const canAskTimezoneSuggestion = (key: string) => {
return Date.now() - +getLastTimezoneSuggestion(key) >= DAY_IN_MILLISECONDS;
};
| Use sha256 helper from proton-shared | Use sha256 helper from proton-shared
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,11 +1,10 @@
-import { SHA256, binaryStringToArray, arrayToHexString } from 'pmcrypto';
+import { getSHA256String } from 'proton-shared/lib/helpers/hash';
const DAY_IN_MILLISECONDS = 86400000;
const LOCALSTORAGE_TZ_KEY = 'tzSuggestion';
export const getTimezoneSuggestionKey = async (userID: string) => {
- const value = await SHA256(binaryStringToArray(`${LOCALSTORAGE_TZ_KEY}${userID}`));
- return arrayToHexString(value);
+ return getSHA256String(`${LOCALSTORAGE_TZ_KEY}${userID}`);
};
export const getLastTimezoneSuggestion = (key: string) => { |
52bf60a0220746c97dd238f87682d3c929eb303d | src/webauthn-json/schema-format.ts | src/webauthn-json/schema-format.ts | type SchemaLeaf = "copy" | "convert";
export interface SchemaProperty {
required: boolean;
schema: Schema;
derive?(v: any): any;
}
interface SchemaObject {
[property: string]: SchemaProperty;
}
type SchemaArray = [SchemaObject] | [SchemaLeaf];
export type Schema = SchemaLeaf | SchemaArray | SchemaObject;
| type SchemaLeaf = "copy" | "convert";
export interface SchemaProperty {
required: boolean;
schema: Schema;
derive?: (v: any) => any;
}
interface SchemaObject {
[property: string]: SchemaProperty;
}
type SchemaArray = [SchemaObject] | [SchemaLeaf];
export type Schema = SchemaLeaf | SchemaArray | SchemaObject;
| Use standalone function type for `derive` in the schema format declaration. | Use standalone function type for `derive` in the schema format declaration.
| TypeScript | mit | github/webauthn-json,github/webauthn-json,github/webauthn-json | ---
+++
@@ -2,7 +2,7 @@
export interface SchemaProperty {
required: boolean;
schema: Schema;
- derive?(v: any): any;
+ derive?: (v: any) => any;
}
interface SchemaObject {
[property: string]: SchemaProperty; |
2cd2b3acd327e4ac641acb124d9b0e8ab992a006 | config.service.ts | config.service.ts | export class HsConfig {
cesiumTime: any;
componentsEnabled: any;
mapInteractionsEnabled: boolean;
allowAddExternalDatasets: boolean;
sidebarClosed: boolean;
layer_order: string;
box_layers: Array<any>;
senslog: any;
cesiumdDebugShowFramesPerSecond: boolean;
cesiumShadows: number;
cesiumBase: string;
createWorldTerrainOptions: any;
terrain_provider: any;
cesiumTimeline: boolean;
cesiumAnimation: boolean;
creditContainer: any;
cesiumInfoBox: any;
imageryProvider: any;
terrainExaggeration: number;
cesiumBingKey: string;
newTerrainProviderOptions: any;
terrain_providers: any;
cesiumAccessToken: string;
constructor() {}
}
| export class HsConfig {
cesiumTime: any;
componentsEnabled: any;
mapInteractionsEnabled: boolean;
allowAddExternalDatasets: boolean;
sidebarClosed: boolean;
layer_order: string;
box_layers: Array<any>;
senslog: any;
cesiumdDebugShowFramesPerSecond: boolean;
cesiumShadows: number;
cesiumBase: string;
createWorldTerrainOptions: any;
terrain_provider: any;
cesiumTimeline: boolean;
cesiumAnimation: boolean;
creditContainer: any;
cesiumInfoBox: any;
imageryProvider: any;
terrainExaggeration: number;
cesiumBingKey: string;
newTerrainProviderOptions: any;
terrain_providers: any;
cesiumAccessToken: string;
proxyPrefix: string;
constructor() {}
}
| Add proxy prefix to HsConfig | Add proxy prefix to HsConfig
| TypeScript | mit | hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng | ---
+++
@@ -22,5 +22,6 @@
newTerrainProviderOptions: any;
terrain_providers: any;
cesiumAccessToken: string;
+ proxyPrefix: string;
constructor() {}
} |
1ef9d4fb03211f97c2ae342eb7ecfea67eff9502 | app/src/ui/cli-installed/cli-installed.tsx | app/src/ui/cli-installed/cli-installed.tsx | import * as React from 'react'
import { Button } from '../lib/button'
import { ButtonGroup } from '../lib/button-group'
import { Dialog, DialogContent, DialogFooter } from '../dialog'
import { InstalledCLIPath } from '../lib/install-cli'
interface ICLIInstalledProps {
/** Called when the popup should be dismissed. */
readonly onDismissed: () => void
}
/** Tell the user the CLI tool was successfully installed. */
export class CLIInstalled extends React.Component<ICLIInstalledProps, {}> {
private onDismissed() {}
public render() {
return (
<Dialog
title={
__DARWIN__
? 'Command Line Tool Installed'
: 'Command line tool installed'
}
onDismissed={this.props.onDismissed}
onSubmit={this.onDismissed}
>
<DialogContent>
<div>
The command line tool has been installed at{' '}
<strong>{InstalledCLIPath}</strong>.
</div>
</DialogContent>
<DialogFooter>
<ButtonGroup>
<Button type="submit">OK</Button>
</ButtonGroup>
</DialogFooter>
</Dialog>
)
}
}
| import * as React from 'react'
import { Button } from '../lib/button'
import { ButtonGroup } from '../lib/button-group'
import { Dialog, DialogContent, DialogFooter } from '../dialog'
import { InstalledCLIPath } from '../lib/install-cli'
interface ICLIInstalledProps {
/** Called when the popup should be dismissed. */
readonly onDismissed: () => void
}
/** Tell the user the CLI tool was successfully installed. */
export class CLIInstalled extends React.Component<ICLIInstalledProps, {}> {
public render() {
return (
<Dialog
title={
__DARWIN__
? 'Command Line Tool Installed'
: 'Command line tool installed'
}
onDismissed={this.props.onDismissed}
onSubmit={this.props.onDismissed}
>
<DialogContent>
<div>
The command line tool has been installed at{' '}
<strong>{InstalledCLIPath}</strong>.
</div>
</DialogContent>
<DialogFooter>
<ButtonGroup>
<Button type="submit">OK</Button>
</ButtonGroup>
</DialogFooter>
</Dialog>
)
}
}
| Revert "add a tslint failure" | Revert "add a tslint failure"
This reverts commit 15e66191f45d1fbdb8f28a55071b064955c3eb91.
| TypeScript | mit | artivilla/desktop,say25/desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,say25/desktop,desktop/desktop,desktop/desktop | ---
+++
@@ -11,7 +11,6 @@
/** Tell the user the CLI tool was successfully installed. */
export class CLIInstalled extends React.Component<ICLIInstalledProps, {}> {
- private onDismissed() {}
public render() {
return (
<Dialog
@@ -21,7 +20,7 @@
: 'Command line tool installed'
}
onDismissed={this.props.onDismissed}
- onSubmit={this.onDismissed}
+ onSubmit={this.props.onDismissed}
>
<DialogContent>
<div> |
68a7661f08b851999bb0c7deff1d7553af904fb4 | src/remote/activitypub/renderer/create.ts | src/remote/activitypub/renderer/create.ts | import config from '../../../config';
import { INote } from '../../../models/note';
export default (object: any, note: INote) => {
return {
id: `${config.url}/notes/${note._id}/activity`,
actor: `${config.url}/users/${note.userId}`,
type: 'Create',
published: note.createdAt.toISOString(),
object
};
};
| import config from '../../../config';
import { INote } from '../../../models/note';
export default (object: any, note: INote) => {
const activity = {
id: `${config.url}/notes/${note._id}/activity`,
actor: `${config.url}/users/${note.userId}`,
type: 'Create',
published: note.createdAt.toISOString(),
object
} as any;
if (object.to) activity.to = object.to;
if (object.cc) activity.cc = object.cc;
return activity;
};
| Create Note activity にも toとcc | Create Note activity にも toとcc
| TypeScript | mit | syuilo/Misskey,syuilo/Misskey | ---
+++
@@ -2,11 +2,16 @@
import { INote } from '../../../models/note';
export default (object: any, note: INote) => {
- return {
+ const activity = {
id: `${config.url}/notes/${note._id}/activity`,
actor: `${config.url}/users/${note.userId}`,
type: 'Create',
published: note.createdAt.toISOString(),
object
- };
+ } as any;
+
+ if (object.to) activity.to = object.to;
+ if (object.cc) activity.cc = object.cc;
+
+ return activity;
}; |
2750a7b661686e13245fed396cf93317fed8ee58 | src/main/ts/ephox/echo/api/AriaFocus.ts | src/main/ts/ephox/echo/api/AriaFocus.ts | import { Option } from '@ephox/katamari';
import { Compare } from '@ephox/sugar';
import { Focus } from '@ephox/sugar';
import { PredicateFind } from '@ephox/sugar';
import { Traverse } from '@ephox/sugar';
var preserve = function (f, container) {
var ownerDoc = Traverse.owner(container);
var refocus = Focus.active(ownerDoc).bind(function (focused) {
var hasFocus = function (elem) {
return Compare.eq(focused, elem);
};
return hasFocus(container) ? Option.some(container) : PredicateFind.descendant(container, hasFocus);
});
var result = f(container);
// If there is a focussed element, the F function may cause focus to be lost (such as by hiding elements). Restore it afterwards.
refocus.each(function (oldFocus) {
Focus.active(ownerDoc).filter(function (newFocus) {
return Compare.eq(newFocus, oldFocus);
}).orThunk(function () {
// Only refocus if the focus has changed, otherwise we break IE
Focus.focus(oldFocus);
});
});
return result;
};
export default <any> {
preserve: preserve
}; | import { Option } from '@ephox/katamari';
import { Compare } from '@ephox/sugar';
import { Focus } from '@ephox/sugar';
import { PredicateFind } from '@ephox/sugar';
import { Traverse } from '@ephox/sugar';
var preserve = function (f, container) {
var ownerDoc = Traverse.owner(container);
var refocus = Focus.active(ownerDoc).bind(function (focused) {
var hasFocus = function (elem) {
return Compare.eq(focused, elem);
};
return hasFocus(container) ? Option.some(container) : PredicateFind.descendant(container, hasFocus);
});
var result = f(container);
// If there is a focussed element, the F function may cause focus to be lost (such as by hiding elements). Restore it afterwards.
refocus.each(function (oldFocus) {
const shouldFocus = Focus.active(ownerDoc).filter(function (newFocus) {
return Compare.eq(newFocus, oldFocus);
}).isNone();
if (shouldFocus) {
// Only refocus if the focus has changed, otherwise we break IE
Focus.focus(oldFocus);
}
});
return result;
};
export default <any> {
preserve: preserve
}; | Correct error picked up by sugar types | TINY-1600: Correct error picked up by sugar types
| TypeScript | lgpl-2.1 | FernCreek/tinymce,FernCreek/tinymce,TeamupCom/tinymce,tinymce/tinymce,TeamupCom/tinymce,tinymce/tinymce,FernCreek/tinymce,tinymce/tinymce | ---
+++
@@ -18,12 +18,13 @@
// If there is a focussed element, the F function may cause focus to be lost (such as by hiding elements). Restore it afterwards.
refocus.each(function (oldFocus) {
- Focus.active(ownerDoc).filter(function (newFocus) {
+ const shouldFocus = Focus.active(ownerDoc).filter(function (newFocus) {
return Compare.eq(newFocus, oldFocus);
- }).orThunk(function () {
+ }).isNone();
+ if (shouldFocus) {
// Only refocus if the focus has changed, otherwise we break IE
Focus.focus(oldFocus);
- });
+ }
});
return result;
}; |
b3762241eee70539835c701a626182f07771f8ac | types/koa-html-minifier/index.d.ts | types/koa-html-minifier/index.d.ts | // Type definitions for koa-html-minifier 1.0
// Project: https://github.com/koajs/html-minifier
// Definitions by: Romain Faust <https://github.com/romain-faust>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { Options as HtmlMinifierOptions } from 'html-minifier';
import { Middleware } from 'koa';
declare function KoaHtmlMinifier(options?: KoaHtmlMinifier.Options): Middleware;
declare namespace KoaHtmlMinifier {
type Options = HtmlMinifierOptions;
}
export = KoaHtmlMinifier;
| // Type definitions for koa-html-minifier 1.0
// Project: https://github.com/koajs/html-minifier
// Definitions by: Romain Faust <https://github.com/romain-faust>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { Options as HtmlMinifierOptions } from 'html-minifier';
import { Middleware } from 'koa';
declare function koaHtmlMinifier(options?: koaHtmlMinifier.Options): Middleware;
declare namespace koaHtmlMinifier {
type Options = HtmlMinifierOptions;
}
export = koaHtmlMinifier;
| Change the export case to be more semantically correct | Change the export case to be more semantically correct
| TypeScript | mit | AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped | ---
+++
@@ -7,10 +7,10 @@
import { Options as HtmlMinifierOptions } from 'html-minifier';
import { Middleware } from 'koa';
-declare function KoaHtmlMinifier(options?: KoaHtmlMinifier.Options): Middleware;
+declare function koaHtmlMinifier(options?: koaHtmlMinifier.Options): Middleware;
-declare namespace KoaHtmlMinifier {
+declare namespace koaHtmlMinifier {
type Options = HtmlMinifierOptions;
}
-export = KoaHtmlMinifier;
+export = koaHtmlMinifier; |
ce3fa746d1f00a4690fbab03932a49bf3e46c029 | main.ts | main.ts | import express = require('express');
import plugin = require('./core/plugin');
let app = express();
plugin.initialize();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.get('/plugin/:name/:action', function (req, res) {
let name = req.params.name;
let action = req.params.action;
plugin.get(name).handle(action, function (err, resObj) {
if (err) {
res.status(404).send(`No plugin named ${name}.`);
} else {
res.json(resObj);
}
});
});
let server = app.listen(3000, function () {
let host = server.address().address;
let port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
| import express = require('express');
import plugin = require('./core/plugin');
let app = express();
plugin.initialize();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.get('/plugin/:name/:action', function (req, res) {
let name = req.params.name;
let action = req.params.action;
plugin.get(name).handle(action, function (err, resObj) {
if (err) {
res.status(404).send(`No plugin named ${name}.`);
} else {
res.json(resObj);
}
});
});
let server = app.listen(9000, function () {
let host = server.address().address;
let port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
| Change default port to 9000. | Change default port to 9000.
| TypeScript | apache-2.0 | murmur76/beyond.ts,sgkim126/beyond.ts,murmur76/beyond.js,murmur76/beyond.js,noraesae/beyond.ts,sgkim126/beyond.ts,SollmoStudio/beyond.ts,noraesae/beyond.ts,SollmoStudio/beyond.ts,murmur76/beyond.ts | ---
+++
@@ -22,7 +22,7 @@
});
});
-let server = app.listen(3000, function () {
+let server = app.listen(9000, function () {
let host = server.address().address;
let port = server.address().port;
|
53d0a1d0d2ed6af3b84cff1ddf2f370ce10f18bf | WorkingWithTypeScript/app.ts | WorkingWithTypeScript/app.ts | class Greeter {
element: HTMLElement;
span: any;
timerToken: number;
constructor(element: HTMLElement) {
this.element = element;
this.element.innerHTML += "The time is: ";
this.span = document.createElement('span');
this.element.appendChild(this.span);
this.span.innerText = new Date().toUTCString();
}
start() {
this.timerToken = setInterval(() => this.span.innerHTML = new Date().toUTCString(), 500);
}
stop() {
clearTimeout(this.timerToken);
}
}
window.onload = () => {
var el = document.getElementById('content');
var greeter = new Greeter(el);
greeter.start();
}; | class Greeter {
element: HTMLElement;
span: HTMLSpanElement;
timerToken: number;
constructor(element: HTMLElement) {
this.element = element;
this.element.innerHTML += "The time is: ";
this.span = document.createElement('span');
this.element.appendChild(this.span);
this.span.innerText = new Date().toUTCString();
}
start() {
this.timerToken = setInterval(() => this.span.innerHTML = new Date().toUTCString(), 500);
}
stop() {
clearTimeout(this.timerToken);
}
}
window.onload = () => {
var el = document.getElementById('content');
var greeter = new Greeter(el);
greeter.start();
}; | Change the span member to HTMLSpanElement | Change the span member to HTMLSpanElement
Again, the JavaScript does not change. But now, the TypeScript compiler
ensures that the object span references is actually a span element. (See
next commit)
| TypeScript | mit | BillWagner/WorkingWithTypeScript,BillWagner/WorkingWithTypeScript,BillWagner/WorkingWithTypeScript | ---
+++
@@ -1,6 +1,6 @@
class Greeter {
element: HTMLElement;
- span: any;
+ span: HTMLSpanElement;
timerToken: number;
constructor(element: HTMLElement) { |
7a26032665522773672feb2cb8c2c89239619dc8 | src/Components/Search/Previews/index.tsx | src/Components/Search/Previews/index.tsx | import React, { SFC } from "react"
import { Media } from "Utils/Responsive"
import { ArtistSearchPreviewQueryRenderer as ArtistSearchPreview } from "./Grids/ArtistSearch"
import { MerchandisableArtworksPreviewQueryRenderer as MerchandisableArtworksPreview } from "./Grids/MerchandisableArtworks"
export interface SearchPreviewProps {
entityID: string
entityType: string
}
const map = {
Artist: ArtistSearchPreview,
default: MerchandisableArtworksPreview
}
export const SearchPreview: SFC<SearchPreviewProps> = ({
entityID,
entityType,
}) => {
const Preview = map[entityType] || map.default
return (
<Media greaterThan="xs">
<Preview entityID={entityID} />
</Media>
)
}
| import React, { SFC } from "react"
import { Media } from "Utils/Responsive"
import { ArtistSearchPreviewQueryRenderer as ArtistSearchPreview } from "./Grids/ArtistSearch"
import { MerchandisableArtworksPreviewQueryRenderer as MerchandisableArtworksPreview } from "./Grids/MerchandisableArtworks"
export interface SearchPreviewProps {
entityID: string
entityType: string
}
const previewComponents = {
Artist: ArtistSearchPreview,
default: MerchandisableArtworksPreview
}
export const SearchPreview: SFC<SearchPreviewProps> = ({
entityID,
entityType,
}) => {
const Preview = previewComponents[entityType] || previewComponents.default
return (
<Media greaterThan="xs">
<Preview entityID={entityID} />
</Media>
)
}
| Improve name of component map | Improve name of component map
| TypeScript | mit | xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,artsy/reaction,artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction | ---
+++
@@ -8,7 +8,7 @@
entityType: string
}
-const map = {
+const previewComponents = {
Artist: ArtistSearchPreview,
default: MerchandisableArtworksPreview
}
@@ -17,7 +17,7 @@
entityID,
entityType,
}) => {
- const Preview = map[entityType] || map.default
+ const Preview = previewComponents[entityType] || previewComponents.default
return (
<Media greaterThan="xs"> |
c1f1ca41081f9e569dda7da68ebaa8d51736922f | packages/markdown/src/index.tsx | packages/markdown/src/index.tsx | import * as MathJax from "@nteract/mathjax";
import React from "react";
import ReactMarkdown from "react-markdown";
import RemarkMathPlugin from "./remark-math";
const math = (props: { value: string }): React.ReactNode => (
<MathJax.Node>{props.value}</MathJax.Node>
);
const inlineMath = (props: { value: string }): React.ReactNode => (
<MathJax.Node inline>{props.value}</MathJax.Node>
);
const MarkdownRender = (props: ReactMarkdown.ReactMarkdownProps) => {
const newProps = {
// https://github.com/rexxars/react-markdown#options
...props,
escapeHtml: false,
plugins: [RemarkMathPlugin],
renderers: {
...props.renderers,
math,
inlineMath
} as any
};
return <ReactMarkdown {...newProps} />;
};
export default MarkdownRender;
| import * as MathJax from "@nteract/mathjax";
import { Source } from "@nteract/presentational-components";
import React from "react";
import ReactMarkdown from "react-markdown";
import RemarkMathPlugin from "./remark-math";
const math = (props: { value: string }): React.ReactNode => (
<MathJax.Node>{props.value}</MathJax.Node>
);
const inlineMath = (props: { value: string }): React.ReactNode => (
<MathJax.Node inline>{props.value}</MathJax.Node>
);
const code = (props: { language: string; value: string }): React.ReactNode => (
<Source language={props.language}>{props.value}</Source>
);
const MarkdownRender = (props: ReactMarkdown.ReactMarkdownProps) => {
const newProps = {
// https://github.com/rexxars/react-markdown#options
...props,
escapeHtml: false,
plugins: [RemarkMathPlugin],
renderers: {
...props.renderers,
math,
inlineMath,
code
} as any
};
return <ReactMarkdown {...newProps} />;
};
export default MarkdownRender;
| Fix syntax highlighting on Markdown previews | Fix syntax highlighting on Markdown previews
| TypeScript | bsd-3-clause | nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract,nteract/composition,nteract/composition | ---
+++
@@ -1,4 +1,5 @@
import * as MathJax from "@nteract/mathjax";
+import { Source } from "@nteract/presentational-components";
import React from "react";
import ReactMarkdown from "react-markdown";
@@ -12,6 +13,10 @@
<MathJax.Node inline>{props.value}</MathJax.Node>
);
+const code = (props: { language: string; value: string }): React.ReactNode => (
+ <Source language={props.language}>{props.value}</Source>
+);
+
const MarkdownRender = (props: ReactMarkdown.ReactMarkdownProps) => {
const newProps = {
// https://github.com/rexxars/react-markdown#options
@@ -21,7 +26,8 @@
renderers: {
...props.renderers,
math,
- inlineMath
+ inlineMath,
+ code
} as any
};
|
f0f598e2037d0f28f95759b656243cb6cb4e0fa8 | packages/schematics/src/scam/index.ts | packages/schematics/src/scam/index.ts | import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: Rule = (tree, context) => {
return tree;
};
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList,
_mergeModuleIntoComponentFile
];
}
return chain(ruleList);
}
| import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
import { findModuleFromOptions } from '@schematics/angular/utility/find-module';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => {
return tree;
};
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList,
_mergeModuleIntoComponentFile(options)
];
}
return chain(ruleList);
}
| Merge module and component as default behavior. | @wishtack/schematics:scam: Merge module and component as default behavior.
| TypeScript | mit | wishtack/wishtack-steroids,wishtack/wishtack-steroids,wishtack/ng-steroids,wishtack/ng-steroids,wishtack/wishtack-steroids | ---
+++
@@ -1,11 +1,12 @@
import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
+import { findModuleFromOptions } from '@schematics/angular/utility/find-module';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
-export const _mergeModuleIntoComponentFile: Rule = (tree, context) => {
+export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => {
return tree;
};
@@ -23,7 +24,7 @@
if (!options.separateModule) {
ruleList = [
...ruleList,
- _mergeModuleIntoComponentFile
+ _mergeModuleIntoComponentFile(options)
];
}
|
9fbb7e921fe7eaa5d8952028a48461cd15a34144 | public_src/services/config.service.ts | public_src/services/config.service.ts | import {Injectable} from "@angular/core";
const p = require("../../package.json");
@Injectable()
export class ConfigService {
public cfgFilterLines: boolean = true;
static overpassUrl = "https://overpass-api.de/api/interpreter";
static baseOsmUrl = "https://www.openstreetmap.org";
static apiUrl = "https://api.openstreetmap.org/api/0.6";
static apiConsumerSecret = "vFXps19FPNhWzzGmWbrhNpMv3RYiI1RFL4oK8NPz";
static apiConsumerKey = "rPEtcWkEykSKlLccsDS0FaZ9DpGAVPoJfQXWubXl";
static apiTestUrl = "https://master.apis.dev.openstreetmap.org";
static apiTestConsumerKey = "myPQ4WewlhUBa5zRs00zwHjWV4nEIsrg6SAF9zat";
static apiTestConsumerSecret = "7hAymlaBzyUqGU0ecbdUqXgYt4w59ru3t3JIM9xp";
static appName = p["name"] + " v" + p["version"];
public minDownloadZoom = 15;
public minDownloadDistance = 5000;
}
| import {Injectable} from "@angular/core";
const p = require("../../package.json");
@Injectable()
export class ConfigService {
public cfgFilterLines: boolean = true;
static overpassUrl = "https://overpass-api.de/api/interpreter";
static baseOsmUrl = "https://www.openstreetmap.org";
static apiUrl = "https://api.openstreetmap.org/api/0.6";
static apiConsumerSecret = "vFXps19FPNhWzzGmWbrhNpMv3RYiI1RFL4oK8NPz";
static apiConsumerKey = "rPEtcWkEykSKlLccsDS0FaZ9DpGAVPoJfQXWubXl";
static apiTestUrl = "https://master.apis.dev.openstreetmap.org";
static apiTestConsumerKey = "myPQ4WewlhUBa5zRs00zwHjWV4nEIsrg6SAF9zat";
static apiTestConsumerSecret = "7hAymlaBzyUqGU0ecbdUqXgYt4w59ru3t3JIM9xp";
static appName = p["name"] + " v" + p["version"];
public minDownloadZoom = 15;
public minDownloadDistance = 600;
}
| Change config to download data more often | Change config to download data more often
| TypeScript | mit | dkocich/osm-pt-ngx-leaflet,dkocich/osm-pt-ngx-leaflet,dkocich/osm-pt-ngx-leaflet | ---
+++
@@ -19,5 +19,5 @@
static appName = p["name"] + " v" + p["version"];
public minDownloadZoom = 15;
- public minDownloadDistance = 5000;
+ public minDownloadDistance = 600;
} |
5625e639ab00979014a0eea183c38607ebe73ac2 | types/imagemin/imagemin-tests.ts | types/imagemin/imagemin-tests.ts | import * as Imagemin from 'imagemin';
const input = ['fileA.jpg', 'fileB.png'];
const output = 'output';
const options = { plugins: [] };
Imagemin(input);
Imagemin(input, output);
Imagemin(input, options);
Imagemin(input, output, options);
| import * as Imagemin from 'imagemin';
const buffer = Buffer.from('Hello World!');
const input = ['fileA.jpg', 'fileB.png'];
const output = 'output';
const options = { plugins: [] };
Imagemin(input);
Imagemin(input, output);
Imagemin(input, options);
Imagemin(input, output, options);
Imagemin.buffer(buffer);
Imagemin.buffer(buffer, options);
| Add missing tests for imagemin.buffer | Add missing tests for imagemin.buffer
| TypeScript | mit | AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,magny/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped | ---
+++
@@ -1,5 +1,6 @@
import * as Imagemin from 'imagemin';
+const buffer = Buffer.from('Hello World!');
const input = ['fileA.jpg', 'fileB.png'];
const output = 'output';
const options = { plugins: [] };
@@ -8,3 +9,6 @@
Imagemin(input, output);
Imagemin(input, options);
Imagemin(input, output, options);
+
+Imagemin.buffer(buffer);
+Imagemin.buffer(buffer, options); |
0baf99f6842eb272f21a3b862612b2711ee15ce9 | src/v2/Components/RouteTabs.tsx | src/v2/Components/RouteTabs.tsx | import React from "react"
import { RouterLink, RouterLinkProps } from "v2/Artsy/Router/RouterLink"
import { BaseTab, BaseTabs, BaseTabProps, BaseTabsProps } from "@artsy/palette"
import { useIsRouteActive } from "v2/Artsy/Router/useRouter"
export const RouteTab: React.FC<BaseTabProps & RouterLinkProps> = ({
children,
to,
...rest
}) => {
return (
// @ts-ignore
<BaseTab as={RouterLink} to={to} active={useIsRouteActive(to)} {...rest}>
{children}
</BaseTab>
)
}
RouteTab.displayName = "RouteTab"
export const RouteTabs: React.FC<BaseTabsProps> = props => {
return <BaseTabs mx={[-2, 0]} px={[2, 0]} {...props} />
}
RouteTabs.displayName = "RouteTabs"
| import React from "react"
import { RouterLink, RouterLinkProps } from "v2/Artsy/Router/RouterLink"
import { BaseTab, BaseTabs, BaseTabProps, BaseTabsProps } from "@artsy/palette"
import { useIsRouteActive } from "v2/Artsy/Router/useRouter"
export const RouteTab: React.FC<BaseTabProps & RouterLinkProps> = ({
children,
to,
...rest
}) => {
const options = {
exact: rest.exact !== undefined ? rest.exact : true,
}
return (
<BaseTab
as={RouterLink}
// @ts-ignore
to={to}
active={useIsRouteActive(to, options)}
{...rest}
>
{children}
</BaseTab>
)
}
RouteTab.displayName = "RouteTab"
export const RouteTabs: React.FC<BaseTabsProps> = props => {
return <BaseTabs mx={[-2, 0]} px={[2, 0]} {...props} />
}
RouteTabs.displayName = "RouteTabs"
| Use exact value to define is active tab | Use exact value to define is active tab
| TypeScript | mit | artsy/force-public,artsy/force,artsy/force,artsy/force,joeyAghion/force,joeyAghion/force,artsy/force,joeyAghion/force,joeyAghion/force,artsy/force-public | ---
+++
@@ -8,9 +8,18 @@
to,
...rest
}) => {
+ const options = {
+ exact: rest.exact !== undefined ? rest.exact : true,
+ }
+
return (
- // @ts-ignore
- <BaseTab as={RouterLink} to={to} active={useIsRouteActive(to)} {...rest}>
+ <BaseTab
+ as={RouterLink}
+ // @ts-ignore
+ to={to}
+ active={useIsRouteActive(to, options)}
+ {...rest}
+ >
{children}
</BaseTab>
) |
0269065a85d96d0e31f209fe87b86594149f7f9c | src/client/client-config.service.ts | src/client/client-config.service.ts | import { Injectable } from "@angular/core";
import { DEFAULT_BASE_URL } from "./client-constants";
import { TokenStorage } from "../token/token-storage";
import { TokenStorageProvider } from "../token/token-storage-provider.service";
@Injectable()
export class ClientConfig {
private _baseUrl: string = DEFAULT_BASE_URL;
constructor(private _tokenStorageProvider: TokenStorageProvider) { }
public set tokenStorage(tokenStorage: TokenStorage) {
this._tokenStorageProvider.tokenStorage = tokenStorage;
}
public set baseUrl(baseUrl: string) {
this._baseUrl = baseUrl;
}
public get baseUrl(): string {
return this._baseUrl;
}
}
| import { Injectable } from "@angular/core";
import { DEFAULT_BASE_URL } from "./client-constants";
import { TokenStorage } from "../token/token-storage";
import { TokenStorageProvider } from "../token/token-storage-provider.service";
@Injectable()
export class ClientConfig {
private _baseUrl: string = DEFAULT_BASE_URL;
constructor(private _tokenStorageProvider: TokenStorageProvider) { }
public set tokenStorage(tokenStorage: TokenStorage) {
this._tokenStorageProvider.tokenStorage = tokenStorage;
}
public set baseUrl(baseUrl: string) {
const lastSlash: number = baseUrl.lastIndexOf('/');
if (lastSlash === baseUrl.length - 1) {
baseUrl = baseUrl.substring(0, lastSlash);
}
this._baseUrl = baseUrl;
}
public get baseUrl(): string {
return this._baseUrl;
}
}
| Check trailing slash in client config | Check trailing slash in client config
| TypeScript | mit | cookingfox/stibble-api-client-angular,cookingfox/stibble-api-client-angular,cookingfox/stibble-api-client-angular | ---
+++
@@ -16,6 +16,12 @@
}
public set baseUrl(baseUrl: string) {
+ const lastSlash: number = baseUrl.lastIndexOf('/');
+
+ if (lastSlash === baseUrl.length - 1) {
+ baseUrl = baseUrl.substring(0, lastSlash);
+ }
+
this._baseUrl = baseUrl;
}
|
25f95c40d65cf071d1e551c5185a008519ea3075 | src/lib/disable-infinite-scroll.ts | src/lib/disable-infinite-scroll.ts | /**
* Intercept the scroll event and kill it to prevent the
* infinite scroll algorithm triggering.
*/
import isEnabled from './is-enabled';
const maybeBlock = ( event ) => {
if ( isEnabled() ) {
event.stopImmediatePropagation();
return false;
}
}
export default function() {
window.addEventListener('scroll', maybeBlock, true);
window.addEventListener('mousewheel', maybeBlock, true);
}
| /**
* Intercept the scroll event and kill it to prevent the
* infinite scroll algorithm triggering.
*/
import isEnabled from './is-enabled';
// Check if the event target is a chat conversation
let isConversation = ( target ) => {
if ( ! target || ! target.matches ) {
return false;
}
if ( target.matches( '.conversation' ) || target.matches( '#ChatTabsPagelet' ) ) {
return true;
}
if ( ! target.parentNode ) {
return false;
}
return isConversation( target.parentElement );
}
const maybeBlock = ( event: MouseWheelEvent ) => {
if ( ! isEnabled() ) {
return false;
}
// Allow infinite scrolling of chats on the home page
if ( isConversation( event.target ) ) {
return false;
}
event.stopImmediatePropagation();
return true;
}
export default function() {
window.addEventListener('scroll', maybeBlock, true);
window.addEventListener('mousewheel', maybeBlock, true);
}
| Fix infinite scrolling in chat popups on home page | Fix infinite scrolling in chat popups on home page
Closes #30
| TypeScript | mit | jordwest/news-feed-eradicator,jordwest/news-feed-eradicator,jordwest/news-feed-eradicator | ---
+++
@@ -5,11 +5,35 @@
import isEnabled from './is-enabled';
-const maybeBlock = ( event ) => {
- if ( isEnabled() ) {
- event.stopImmediatePropagation();
+// Check if the event target is a chat conversation
+let isConversation = ( target ) => {
+ if ( ! target || ! target.matches ) {
return false;
}
+
+ if ( target.matches( '.conversation' ) || target.matches( '#ChatTabsPagelet' ) ) {
+ return true;
+ }
+
+ if ( ! target.parentNode ) {
+ return false;
+ }
+
+ return isConversation( target.parentElement );
+}
+
+const maybeBlock = ( event: MouseWheelEvent ) => {
+ if ( ! isEnabled() ) {
+ return false;
+ }
+
+ // Allow infinite scrolling of chats on the home page
+ if ( isConversation( event.target ) ) {
+ return false;
+ }
+
+ event.stopImmediatePropagation();
+ return true;
}
export default function() { |
3edc988395a7724e10f65ea8121c494cb7961c17 | src/OptionsParser.ts | src/OptionsParser.ts | import { ParsedArgs } from "minimist";
import * as path from "path";
import * as shelljs from "shelljs";
import * as OptionsParserInterfaces from "./OptionsParser.interfaces";
export abstract class OptionsParser {
protected static HELP_MESSAGE_PATH: string = path.join(__dirname, "help");
protected options: OptionsParserInterfaces.IBuilderOptions = {
minified: false,
noConflict: true,
out: path.join(process.cwd(), "vendor", "ace"),
repository: "https://github.com/ajaxorg/ace-builds",
};
public constructor(args: OptionsParserInterfaces.IArgs) {
this.checkForGit();
}
private checkForGit(): void {
// Literally pulled from the docs. Also it"s perfect.
if (!shelljs.which("git")) {
this.exit(1, "Sorry, this script requires git");
}
}
private help(args: OptionsParserInterfaces.IArgsHelp) {
if (args && args.help) {
shelljs.cat(OptionsParser.HELP_MESSAGE_PATH);
this.exit(0);
}
}
private exit(code: number = 0, message?: string) {
if (message && message.length > 0) {
shelljs.echo(message);
}
shelljs.exit(code);
}
}
| import { ParsedArgs } from "minimist";
import * as path from "path";
import * as shelljs from "shelljs";
import * as OptionsParserInterfaces from "./OptionsParser.interfaces";
export abstract class OptionsParser {
protected static HELP_MESSAGE_PATH: string = path.join(__dirname, "help");
protected options: OptionsParserInterfaces.IBuilderOptions = {
minified: false,
noConflict: true,
out: path.join(process.cwd(), "vendor", "ace"),
repository: "https://github.com/ajaxorg/ace-builds",
};
public constructor(args: OptionsParserInterfaces.IArgs) {
this.checkForGit();
}
protected exit(code: number = 0, message?: string) {
if (message && message.length > 0) {
shelljs.echo(message);
}
shelljs.exit(code);
}
private checkForGit(): void {
// Literally pulled from the docs. Also it"s perfect.
if (!shelljs.which("git")) {
this.exit(1, "Sorry, this script requires git");
}
}
private help(args: OptionsParserInterfaces.IArgsHelp) {
if (args && args.help) {
shelljs.cat(OptionsParser.HELP_MESSAGE_PATH);
this.exit(0);
}
}
}
| Change exit permissions to protected | Change exit permissions to protected
| TypeScript | isc | thecjharries/slim-ace,thecjharries/slim-ace | ---
+++
@@ -18,6 +18,13 @@
this.checkForGit();
}
+ protected exit(code: number = 0, message?: string) {
+ if (message && message.length > 0) {
+ shelljs.echo(message);
+ }
+ shelljs.exit(code);
+ }
+
private checkForGit(): void {
// Literally pulled from the docs. Also it"s perfect.
if (!shelljs.which("git")) {
@@ -31,11 +38,4 @@
this.exit(0);
}
}
-
- private exit(code: number = 0, message?: string) {
- if (message && message.length > 0) {
- shelljs.echo(message);
- }
- shelljs.exit(code);
- }
} |
d93376e74d695c3636ab81a2c3e4934ab3671ae0 | src/openstack/openstack-volume/actions/AttachAction.ts | src/openstack/openstack-volume/actions/AttachAction.ts | import { getAll } from '@waldur/core/api';
import { translate } from '@waldur/i18n';
import { validateRuntimeState } from '@waldur/resource/actions/base';
import { ResourceAction, ActionContext } from '@waldur/resource/actions/types';
import { Volume, VirtualMachine } from '@waldur/resource/types';
export default function createAction(ctx: ActionContext<Volume>): ResourceAction {
return {
name: 'attach',
type: 'form',
method: 'POST',
title: translate('Attach'),
validators: [
validateRuntimeState('available'),
],
init: async (resource, _, action) => {
const params = {
service_uuid: ctx.resource.service_uuid,
availability_zone_name: resource.availability_zone_name,
};
const instances = await getAll<VirtualMachine>('/openstacktenant-instances/', {params});
action.fields.instance.choices = instances.map(choice => ({
value: choice.url,
display_name: choice.name,
}));
},
fields: [
{
name: 'instance',
label: translate('Instance'),
type: 'select',
required: true,
},
{
name: 'device',
label: translate('Device'),
type: 'string',
help_text: translate('Name of volume as instance device e.g. /dev/vdb.'),
required: false,
},
],
};
}
| import { getAll } from '@waldur/core/api';
import { translate } from '@waldur/i18n';
import { validateRuntimeState } from '@waldur/resource/actions/base';
import { ResourceAction, ActionContext } from '@waldur/resource/actions/types';
import { Volume, VirtualMachine } from '@waldur/resource/types';
export default function createAction(ctx: ActionContext<Volume>): ResourceAction {
return {
name: 'attach',
type: 'form',
method: 'POST',
title: translate('Attach'),
validators: [
validateRuntimeState('available'),
],
init: async (resource, _, action) => {
const params = {
attach_volume_uuid: resource.uuid,
field: ['url', 'name'],
};
const instances = await getAll<VirtualMachine>('/openstacktenant-instances/', {params});
action.fields.instance.choices = instances.map(choice => ({
value: choice.url,
display_name: choice.name,
}));
},
fields: [
{
name: 'instance',
label: translate('Instance'),
type: 'select',
required: true,
},
{
name: 'device',
label: translate('Device'),
type: 'string',
help_text: translate('Name of volume as instance device e.g. /dev/vdb.'),
required: false,
},
],
};
}
| Use filter for instances that could be attached to the volume | Use filter for instances that could be attached to the volume [WAL-2414]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -15,8 +15,8 @@
],
init: async (resource, _, action) => {
const params = {
- service_uuid: ctx.resource.service_uuid,
- availability_zone_name: resource.availability_zone_name,
+ attach_volume_uuid: resource.uuid,
+ field: ['url', 'name'],
};
const instances = await getAll<VirtualMachine>('/openstacktenant-instances/', {params});
action.fields.instance.choices = instances.map(choice => ({ |
3192792ee3a823b23db40e69751cc65df7e9b862 | app/src/lib/dispatcher/error-handlers.ts | app/src/lib/dispatcher/error-handlers.ts | import { Dispatcher } from './index'
import { GitError } from '../git/core'
import { GitError as GitErrorType } from 'git-kitchen-sink'
import { PopupType as popupType } from '../app-state'
/** Handle errors by presenting them. */
export async function defaultErrorHandler(error: Error, dispatcher: Dispatcher): Promise<Error | null> {
await dispatcher.presentError(error)
return null
}
//** Handle errors by giving user actions to complete. */
export async function performGitActionErrorHandler(error: Error, dispatcher: Dispatcher): Promise<Error | null> {
if (error instanceof GitError) {
switch (error.result.gitError) {
case GitErrorType.HTTPSAuthenticationFailed: {
await dispatcher.showPopup({ type: popupType.Signin })
break
}
}
return null
}
return error
}
| import { Dispatcher } from './index'
import { GitError } from '../git/core'
import { GitError as GitErrorType } from 'git-kitchen-sink'
import { PopupType as popupType } from '../app-state'
/** Handle errors by presenting them. */
export async function defaultErrorHandler(error: Error, dispatcher: Dispatcher): Promise<Error | null> {
await dispatcher.presentError(error)
return null
}
//** Handle errors by giving user actions to complete. */
export async function performGitActionErrorHandler(error: Error, dispatcher: Dispatcher): Promise<Error | null> {
if (error instanceof GitError) {
switch (error.result.gitError) {
case GitErrorType.HTTPSAuthenticationFailed: {
await dispatcher.showPopup({ type: popupType.Preferences })
break
}
}
return null
}
return error
}
| Update popup type for error handler | Update popup type for error handler
| TypeScript | mit | artivilla/desktop,shiftkey/desktop,artivilla/desktop,hjobrien/desktop,artivilla/desktop,shiftkey/desktop,BugTesterTest/desktops,BugTesterTest/desktops,hjobrien/desktop,say25/desktop,desktop/desktop,BugTesterTest/desktops,gengjiawen/desktop,shiftkey/desktop,gengjiawen/desktop,j-f1/forked-desktop,gengjiawen/desktop,gengjiawen/desktop,desktop/desktop,say25/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,desktop/desktop,say25/desktop,hjobrien/desktop,artivilla/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,kactus-io/kactus,hjobrien/desktop,BugTesterTest/desktops,j-f1/forked-desktop | ---
+++
@@ -15,7 +15,7 @@
if (error instanceof GitError) {
switch (error.result.gitError) {
case GitErrorType.HTTPSAuthenticationFailed: {
- await dispatcher.showPopup({ type: popupType.Signin })
+ await dispatcher.showPopup({ type: popupType.Preferences })
break
}
} |
573657f6fe5c704f952bb5b41ceafc137c480775 | src/main/ts/app.ts | src/main/ts/app.ts | import EventLoader from './event/event'
import $ from "jquery";
let eventLoader = new EventLoader();
class MixitApp{
bootstrap(){
eventLoader.loadEvent('mixit16')
.then(response => response.json())
.then(event => console.log(event))
$(document).foundation();
}
}
new MixitApp().bootstrap();
| import EventLoader from './event/event'
import * as $ from 'jquery';
window['jQuery'] = $;
import 'foundation-sites';
let eventLoader = new EventLoader();
class MixitApp{
bootstrap(){
eventLoader.loadEvent('mixit16')
.then(response => response.json())
.then(event => console.log(event));
}
}
new MixitApp().bootstrap();
$(() => {
$(document).foundation();
}); | Fix Foundation invocation from TypeScript | Fix Foundation invocation from TypeScript
| TypeScript | apache-2.0 | sdeleuze/mixit,sdeleuze/mixit,sdeleuze/mixit,sdeleuze/mixit,mixitconf/mixit,mixitconf/mixit,mix-it/mixit,mixitconf/mixit,mix-it/mixit,mix-it/mixit,mix-it/mixit,mix-it/mixit,mixitconf/mixit | ---
+++
@@ -1,5 +1,7 @@
import EventLoader from './event/event'
-import $ from "jquery";
+import * as $ from 'jquery';
+window['jQuery'] = $;
+import 'foundation-sites';
let eventLoader = new EventLoader();
@@ -7,9 +9,11 @@
bootstrap(){
eventLoader.loadEvent('mixit16')
.then(response => response.json())
- .then(event => console.log(event))
- $(document).foundation();
+ .then(event => console.log(event));
}
}
new MixitApp().bootstrap();
+$(() => {
+ $(document).foundation();
+}); |
e7c8a816c24293a7f4e93ccd82de863d6abb15b2 | src/fetch.ts | src/fetch.ts | import { ErrorResponse } from "./types";
import { GLOBAL_OPTIONS, searchParams } from "./utils";
import { get } from "https";
export const fetchGet = <T>(
url: string,
data: { [x: string]: string } = {},
signal: any = null
): Promise<T> => {
return new Promise<T>((resolve, error) => {
if (
typeof GLOBAL_OPTIONS.key === "string" &&
GLOBAL_OPTIONS.key.length > 0
) {
data["key"] = GLOBAL_OPTIONS.key;
}
get(`${GLOBAL_OPTIONS.baseUrl}/${url}?${searchParams(data)}`, response => {
let data = "";
response.on("data", chunk => {
data += chunk;
});
response.on("end", () => {
const json = JSON.parse(data);
if (response && response.statusCode) {
if (response.statusCode >= 400) {
error((json as ErrorResponse).error);
}
}
resolve(json);
});
}).on("error", (data: Error) => {
error(data);
});
});
};
| import { ErrorResponse } from "./types";
import { GLOBAL_OPTIONS, searchParams } from "./utils";
import axios, { AxiosError } from 'axios';
import { version } from "./version";
import * as os from 'os';
export const fetchGet = <T>(
url: string,
data: { [x: string]: string } = {},
signal: any = null
): Promise<T> => {
return new Promise<T>((resolve, error) => {
if (
typeof GLOBAL_OPTIONS.key === "string" &&
GLOBAL_OPTIONS.key.length > 0
) {
data["key"] = GLOBAL_OPTIONS.key;
}
var platform = (function(platform) {
switch(platform) {
case 'darwin':
return 'Mac OS X';
case 'win32':
return 'Windows';
case 'linux':
return 'Linux';
}
})(os.platform());
axios.request({
url: `${GLOBAL_OPTIONS.baseUrl}/${url}?${searchParams(data)}`,
headers: {'X-W3W-Wrapper': `what3words-Node/${version} (Node ${process.version}; ${platform} ${os.release()})`}
})
.then((response) => {
if (response && response.status) {
if (response.status >= 400) {
error((response.data as ErrorResponse).error);
}
}
resolve(response.data);
}).catch((data: AxiosError) => {
if (data.response) {
error(data.response.data);
} else {
error(data.message);
}
});
});
};
| Add `X-W3W-Wrapper` head to API requests, and use axios to handle requests to support both http and https | Add `X-W3W-Wrapper` head to API requests, and use axios to handle requests to support both http and https
| TypeScript | mit | what3words/w3w-node-wrapper,OpenCageData/js-geo-what3words,what3words/w3w-node-wrapper | ---
+++
@@ -1,6 +1,8 @@
import { ErrorResponse } from "./types";
import { GLOBAL_OPTIONS, searchParams } from "./utils";
-import { get } from "https";
+import axios, { AxiosError } from 'axios';
+import { version } from "./version";
+import * as os from 'os';
export const fetchGet = <T>(
url: string,
@@ -14,24 +16,35 @@
) {
data["key"] = GLOBAL_OPTIONS.key;
}
- get(`${GLOBAL_OPTIONS.baseUrl}/${url}?${searchParams(data)}`, response => {
- let data = "";
- response.on("data", chunk => {
- data += chunk;
- });
+ var platform = (function(platform) {
+ switch(platform) {
+ case 'darwin':
+ return 'Mac OS X';
+ case 'win32':
+ return 'Windows';
+ case 'linux':
+ return 'Linux';
+ }
+ })(os.platform());
- response.on("end", () => {
- const json = JSON.parse(data);
- if (response && response.statusCode) {
- if (response.statusCode >= 400) {
- error((json as ErrorResponse).error);
+ axios.request({
+ url: `${GLOBAL_OPTIONS.baseUrl}/${url}?${searchParams(data)}`,
+ headers: {'X-W3W-Wrapper': `what3words-Node/${version} (Node ${process.version}; ${platform} ${os.release()})`}
+ })
+ .then((response) => {
+ if (response && response.status) {
+ if (response.status >= 400) {
+ error((response.data as ErrorResponse).error);
}
}
- resolve(json);
+ resolve(response.data);
+ }).catch((data: AxiosError) => {
+ if (data.response) {
+ error(data.response.data);
+ } else {
+ error(data.message);
+ }
});
- }).on("error", (data: Error) => {
- error(data);
- });
});
}; |
aa5e993e931fa3f9e0e77346cef4239302df1ae5 | src/store.ts | src/store.ts | import { createStore, compose, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as immutableTransform from 'redux-persist-transform-immutable';
import { autoRehydrate, persistStore } from 'redux-persist';
import * as localForage from 'localforage';
import { rootReducer } from './reducers';
import rootSaga from './sagas';
// tslint:disable:no-any
// tslint:disable:no-string-literal
const devtools: any = window['__REDUX_DEVTOOLS_EXTENSION__']
? window['__REDUX_DEVTOOLS_EXTENSION__']()
: (f: any) => f;
const sagaMiddleware = createSagaMiddleware();
const store = createStore<any>(
rootReducer,
compose(applyMiddleware(sagaMiddleware), autoRehydrate(), devtools)
);
sagaMiddleware.run(rootSaga);
persistStore(store, {
whitelist: [
'account',
'hitBlocklist',
'hitDatabase',
'requesterBlocklist',
'searchFormActive',
'sortingOption',
'searchOptions',
'topticonSettings',
'watchers',
'audioSettingsV1',
'dailyEarningsGoal'
],
storage: localForage,
transforms: [
immutableTransform({
whitelist: [
'hitBlocklist',
'requesterBlocklist',
'watchers',
'hitDatabase'
]
})
]
});
export default store;
| import { createStore, compose, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as immutableTransform from 'redux-persist-transform-immutable';
import { autoRehydrate, persistStore } from 'redux-persist';
import * as localForage from 'localforage';
import { rootReducer } from './reducers';
import rootSaga from './sagas';
// tslint:disable:no-any
// tslint:disable:no-string-literal
const devtools: any = window['__REDUX_DEVTOOLS_EXTENSION__']
? window['__REDUX_DEVTOOLS_EXTENSION__']()
: (f: any) => f;
const sagaMiddleware = createSagaMiddleware();
const store = createStore<any>(
rootReducer,
compose(applyMiddleware(sagaMiddleware), autoRehydrate(), devtools)
);
sagaMiddleware.run(rootSaga);
persistStore(
store,
{
whitelist: [
'account',
'hitBlocklist',
'hitDatabase',
'requesterBlocklist',
'searchFormActive',
'sortingOption',
'searchOptions',
'topticonSettings',
'watchers',
'audioSettingsV1',
'dailyEarningsGoal'
],
storage: localForage,
transforms: [
immutableTransform({
whitelist: [
'hitBlocklist',
'requesterBlocklist',
'watchers',
'hitDatabase'
]
})
]
},
err =>
err
? console.warn(
`There was an issue retrieving your Mturk Engine settings. Error Log: ` +
err
)
: undefined
);
export default store;
| Add error handler to persistStore. | Add error handler to persistStore.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -21,31 +21,43 @@
sagaMiddleware.run(rootSaga);
-persistStore(store, {
- whitelist: [
- 'account',
- 'hitBlocklist',
- 'hitDatabase',
- 'requesterBlocklist',
- 'searchFormActive',
- 'sortingOption',
- 'searchOptions',
- 'topticonSettings',
- 'watchers',
- 'audioSettingsV1',
- 'dailyEarningsGoal'
- ],
- storage: localForage,
- transforms: [
- immutableTransform({
- whitelist: [
- 'hitBlocklist',
- 'requesterBlocklist',
- 'watchers',
- 'hitDatabase'
- ]
- })
- ]
-});
+persistStore(
+ store,
+ {
+ whitelist: [
+ 'account',
+ 'hitBlocklist',
+ 'hitDatabase',
+ 'requesterBlocklist',
+ 'searchFormActive',
+ 'sortingOption',
+ 'searchOptions',
+ 'topticonSettings',
+ 'watchers',
+ 'audioSettingsV1',
+ 'dailyEarningsGoal'
+ ],
+ storage: localForage,
+ transforms: [
+ immutableTransform({
+ whitelist: [
+ 'hitBlocklist',
+ 'requesterBlocklist',
+ 'watchers',
+ 'hitDatabase'
+ ]
+ })
+ ]
+ },
+ err =>
+ err
+ ? console.warn(
+ `There was an issue retrieving your Mturk Engine settings. Error Log: ` +
+ err
+ )
+ : undefined
+);
+
+
export default store; |
5e57d604cfb28b740bae7e56fe6f424b1c00e12d | src/index.ts | src/index.ts | import { Client, Message } from 'discord.js';
import { isHumanMessage } from './utils/message-utils';
import Dispatcher from './dispatcher';
import { Raider } from './modules/raider';
import config from './config/config';
const client = new Client();
const modules = [ Raider ];
const dispatcher = new Dispatcher(modules);
client.on('ready', () => {
console.log('Bot ready!');
});
client.on('message', (message: Message) => {
if (isHumanMessage(message, client)) {
const responses = dispatcher.dispatchMessage(message);
Promise.all(responses).then(responses => {
responses.forEach(r => {
r.recipient.send(r.content);
});
});
}
});
client.login(config.auth.token);
| import { Client, Message } from 'discord.js';
import { createServer } from 'http';
import { isHumanMessage } from './utils/message-utils';
import Dispatcher from './dispatcher';
import { Raider } from './modules/raider';
import config from './config/config';
const client = new Client();
const modules = [ Raider ];
const dispatcher = new Dispatcher(modules);
client.on('ready', () => {
console.log('Bot ready!');
});
client.on('message', (message: Message) => {
if (isHumanMessage(message, client)) {
const responses = dispatcher.dispatchMessage(message);
Promise.all(responses).then(responses => {
responses.forEach(r => {
r.recipient.send(r.content);
});
});
}
});
client.login(config.auth.token);
// Simple Http server to check the client state
const requestHandler = (_, response) => {
response.end(`Client status: ${client.status}`);
};
const server = createServer(requestHandler);
server.listen(process.env.PORT || 5000, () => {
console.log(`server is listening on ${process.env.PORT || 5000}`);
});
| Add a simple http server to check bot state | Add a simple http server to check bot state
| TypeScript | mit | jchakra/discord-raider | ---
+++
@@ -1,4 +1,5 @@
import { Client, Message } from 'discord.js';
+import { createServer } from 'http';
import { isHumanMessage } from './utils/message-utils';
import Dispatcher from './dispatcher';
@@ -29,3 +30,14 @@
});
client.login(config.auth.token);
+
+// Simple Http server to check the client state
+const requestHandler = (_, response) => {
+ response.end(`Client status: ${client.status}`);
+};
+
+const server = createServer(requestHandler);
+
+server.listen(process.env.PORT || 5000, () => {
+ console.log(`server is listening on ${process.env.PORT || 5000}`);
+}); |
3ee7f529a99d924a5a448d22a5ada1361465a67d | functions/src/__mocks__/firebase-functions.ts | functions/src/__mocks__/firebase-functions.ts | import { Request, Response } from "express";
export function config() {
return {
cors: {
origins: "https://foo.com,http://bar.com",
},
google: {
analytics: {
trackingid: "UA-46057780-3",
},
},
rakuten: {
affiliate: {
id: "1612f82a.a5051d07.1612f82b.6030f61b",
},
id: "1039965413641166178",
},
youtube: {
key: "serverKey",
},
};
}
export const https = {
onRequest: (handler: (request: Request, response: Response) => void) => handler,
};
| import { Request, Response } from "express";
export function config() {
return {
cors: {
origins: "https://foo.com,http://bar.com",
},
google: {
analytics: {
trackingid: "UA-46057780-4",
},
},
rakuten: {
affiliate: {
id: "1612f82a.a5051d07.1612f82b.6030f61b",
},
id: "1039965413641166178",
},
youtube: {
key: "serverKey",
},
};
}
export const https = {
onRequest: (handler: (request: Request, response: Response) => void) => handler,
};
| Use tracking ID for development | Use tracking ID for development
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -7,7 +7,7 @@
},
google: {
analytics: {
- trackingid: "UA-46057780-3",
+ trackingid: "UA-46057780-4",
},
},
rakuten: { |
cc7d3a06402d05bb17582ebe02d0868fe7ab1395 | packages/delir-core/src/Entity/Keyframe.ts | packages/delir-core/src/Entity/Keyframe.ts | import * as uuid from 'uuid'
import AssetPointer from '../Values/AssetPointer'
import ColorRGB from '../Values/ColorRGB'
import ColorRGBA from '../Values/ColorRGBA'
import Expression from '../Values/Expression'
export type KeyframeValueTypes = number | boolean | string | ColorRGB | ColorRGBA | Expression | AssetPointer | null
export default class Keyframe<T extends KeyframeValueTypes = KeyframeValueTypes> {
public id: string
public value: T
public frameOnClip: number
public easeInParam: [number, number]
public easeOutParam: [number, number]
constructor() {
this.id = uuid.v4()
}
}
| import * as uuid from 'uuid'
import AssetPointer from '../Values/AssetPointer'
import ColorRGB from '../Values/ColorRGB'
import ColorRGBA from '../Values/ColorRGBA'
import Expression from '../Values/Expression'
export type KeyframeValueTypes = number | boolean | string | ColorRGB | ColorRGBA | Expression | AssetPointer | null
export default class Keyframe<T extends KeyframeValueTypes = KeyframeValueTypes> {
public id: string
public value: T
public frameOnClip: number
/**
* right top is [1, 1]
* ◇ < previous keyframe to this keyframe
* ◇───┘ < ease-in
*/
public easeInParam: [number, number] = [1, 1]
/**
* left bottom is [0, 0]
* ◇ < next keyframe
* ◇───┘ < this keyframe to next keyframe, ease-out
*/
public easeOutParam: [number, number] = [0, 0]
constructor() {
this.id = uuid.v4()
}
}
| Comment detail for keyframe easing handle position | Comment detail for keyframe easing handle position
| TypeScript | mit | Ragg-/Delir,Ragg-/Delir,Ragg-/Delir,Ragg-/Delir | ---
+++
@@ -11,8 +11,20 @@
public id: string
public value: T
public frameOnClip: number
- public easeInParam: [number, number]
- public easeOutParam: [number, number]
+
+ /**
+ * right top is [1, 1]
+ * ◇ < previous keyframe to this keyframe
+ * ◇───┘ < ease-in
+ */
+ public easeInParam: [number, number] = [1, 1]
+
+ /**
+ * left bottom is [0, 0]
+ * ◇ < next keyframe
+ * ◇───┘ < this keyframe to next keyframe, ease-out
+ */
+ public easeOutParam: [number, number] = [0, 0]
constructor() {
this.id = uuid.v4() |
74b148bab9c61510ca08b7b616cb92c84c291cfc | test/index.ts | test/index.ts | import * as bootstrap from './bootstrap';
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string, clb: (error:Error) => void) that the extension
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
var testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = {
run: function(testsRoot:string, callback: (error:Error) => void) {
testRunner.run(testsRoot, (error) => {
bootstrap.callback();
callback(error);
});
}
};
| import * as bootstrap from './bootstrap';
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string, clb: (error:Error) => void) that the extension
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
var testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = {
run: function(testsRoot:string, callback: (error:Error) => void) {
testRunner.run(testsRoot, (e, failures) => {
bootstrap.callback();
callback(e);
if (failures > 0) {
process.exitCode = 1;
}
});
}
};
| Fix error reports from travis | Fix error reports from travis
| TypeScript | mit | neild3r/vscode-php-docblocker | ---
+++
@@ -23,9 +23,12 @@
module.exports = {
run: function(testsRoot:string, callback: (error:Error) => void) {
- testRunner.run(testsRoot, (error) => {
+ testRunner.run(testsRoot, (e, failures) => {
bootstrap.callback();
- callback(error);
+ callback(e);
+ if (failures > 0) {
+ process.exitCode = 1;
+ }
});
}
}; |
5649fad514542896d0911a7b13cdd34102ce5e91 | AzureFunctions.Client/app/models/constants.ts | AzureFunctions.Client/app/models/constants.ts | export class Constants {
public static latestExtensionVersion = "~0.2";
public static extensionVersionAppSettingName = "FUNCTIONS_EXTENSION_VERSION";
}
| export class Constants {
public static latestExtensionVersion = "~0.3";
public static extensionVersionAppSettingName = "FUNCTIONS_EXTENSION_VERSION";
}
| Update latest extension version to "~0.3" | Update latest extension version to "~0.3"
| TypeScript | apache-2.0 | chunye/azure-functions-ux,projectkudu/WebJobsPortal,chunye/azure-functions-ux,projectkudu/WebJobsPortal,agruning/azure-functions-ux,agruning/azure-functions-ux,projectkudu/WebJobsPortal,projectkudu/WebJobsPortal,agruning/azure-functions-ux,projectkudu/AzureFunctions,chunye/azure-functions-ux,chunye/azure-functions-ux,agruning/azure-functions-ux,projectkudu/AzureFunctions,chunye/azure-functions-ux,projectkudu/AzureFunctions,agruning/azure-functions-ux,projectkudu/AzureFunctions | ---
+++
@@ -1,4 +1,4 @@
export class Constants {
- public static latestExtensionVersion = "~0.2";
+ public static latestExtensionVersion = "~0.3";
public static extensionVersionAppSettingName = "FUNCTIONS_EXTENSION_VERSION";
} |
89fe9e04064f76918d0a00084a16839c69b46861 | app/src/lib/is-application-bundle.ts | app/src/lib/is-application-bundle.ts | import getFileMetadata from 'file-metadata'
/**
* Attempts to determine if the provided path is an application bundle or not.
*
* macOS differs from the other platforms we support in that a directory can
* also be an application and therefore executable making it unsafe to open
* directories on macOS as we could conceivably end up launching an application.
*
* This application uses file metadata (the `mdls` tool to be exact) to
* determine whether a path is actually an application bundle or otherwise
* executable.
*
* NOTE: This method will always return false when not running on macOS.
*/
export async function isApplicationBundle(path: string): Promise<boolean> {
if (process.platform !== 'darwin') {
return false
}
const metadata = await getFileMetadata(path)
if (metadata['contentType'] === 'com.apple.application-bundle') {
return true
}
const contentTypeTree = metadata['contentTypeTree']
if (Array.isArray(contentTypeTree)) {
for (const contentType of contentTypeTree) {
switch (contentType) {
case 'com.apple.application-bundle':
case 'com.apple.application':
case 'public.executable':
return true
}
}
}
return false
}
| import { execFile } from 'child_process'
import { promisify } from 'util'
const execFileP = promisify(execFile)
/**
* Attempts to determine if the provided path is an application bundle or not.
*
* macOS differs from the other platforms we support in that a directory can
* also be an application and therefore executable making it unsafe to open
* directories on macOS as we could conceivably end up launching an application.
*
* This application uses file metadata (the `mdls` tool to be exact) to
* determine whether a path is actually an application bundle or otherwise
* executable.
*
* NOTE: This method will always return false when not running on macOS.
*/
export async function isApplicationBundle(path: string): Promise<boolean> {
if (process.platform !== 'darwin') {
return false
}
// Expected output for an application bundle:
// $ mdls -name kMDItemContentType -name kMDItemContentTypeTree /Applications/GitHub\ Desktop.app
// kMDItemContentType = "com.apple.application-bundle"
// kMDItemContentTypeTree = (
// "com.apple.application-bundle",
// "com.apple.application",
// "public.executable",
// "com.apple.localizable-name-bundle",
// "com.apple.bundle",
// "public.directory",
// "public.item",
// "com.apple.package"
// )
const { stdout: xml } = await execFileP('mdls', [
...['-name', 'kMDItemContentType'],
...['-name', 'kMDItemContentTypeTree'],
path,
])
const probableBundleIdentifiers = [
'com.apple.application-bundle',
'com.apple.application',
'public.executable',
]
return probableBundleIdentifiers.some(id => xml.includes(`"${id}"`))
}
| Replace file-metadata with custom execFile implementatation | Replace file-metadata with custom execFile implementatation
| TypeScript | mit | desktop/desktop,desktop/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop | ---
+++
@@ -1,4 +1,7 @@
-import getFileMetadata from 'file-metadata'
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+
+const execFileP = promisify(execFile)
/**
* Attempts to determine if the provided path is an application bundle or not.
@@ -18,24 +21,30 @@
return false
}
- const metadata = await getFileMetadata(path)
+ // Expected output for an application bundle:
+ // $ mdls -name kMDItemContentType -name kMDItemContentTypeTree /Applications/GitHub\ Desktop.app
+ // kMDItemContentType = "com.apple.application-bundle"
+ // kMDItemContentTypeTree = (
+ // "com.apple.application-bundle",
+ // "com.apple.application",
+ // "public.executable",
+ // "com.apple.localizable-name-bundle",
+ // "com.apple.bundle",
+ // "public.directory",
+ // "public.item",
+ // "com.apple.package"
+ // )
+ const { stdout: xml } = await execFileP('mdls', [
+ ...['-name', 'kMDItemContentType'],
+ ...['-name', 'kMDItemContentTypeTree'],
+ path,
+ ])
- if (metadata['contentType'] === 'com.apple.application-bundle') {
- return true
- }
+ const probableBundleIdentifiers = [
+ 'com.apple.application-bundle',
+ 'com.apple.application',
+ 'public.executable',
+ ]
- const contentTypeTree = metadata['contentTypeTree']
-
- if (Array.isArray(contentTypeTree)) {
- for (const contentType of contentTypeTree) {
- switch (contentType) {
- case 'com.apple.application-bundle':
- case 'com.apple.application':
- case 'public.executable':
- return true
- }
- }
- }
-
- return false
+ return probableBundleIdentifiers.some(id => xml.includes(`"${id}"`))
} |
4a3df925c4d8195ffcf738c2888011f7b8836847 | script/renderFormResponseChangeGroup.tsx | script/renderFormResponseChangeGroup.tsx | import ReactDOMServer from 'react-dom/server';
import SourceMapSupport from 'source-map-support';
import { I18nextProvider } from 'react-i18next';
import FormItemChangeGroup from '../app/javascript/FormPresenter/ItemChangeDisplays/FormItemChangeGroup';
import AppRootContext, { appRootContextDefaultValue } from '../app/javascript/AppRootContext';
import { timezoneNameForConvention } from '../app/javascript/TimeUtils';
import getI18n from '../app/javascript/setupI18Next';
SourceMapSupport.install();
const props = JSON.parse(process.argv[2]);
async function render() {
const i18n = await getI18n();
ReactDOMServer.renderToStaticNodeStream(
<AppRootContext.Provider
value={{
...appRootContextDefaultValue,
language: props.convention.language,
timezoneName: timezoneNameForConvention(props.convention),
}}
>
<I18nextProvider i18n={i18n}>
<FormItemChangeGroup {...props} />
</I18nextProvider>
</AppRootContext.Provider>,
).pipe(process.stdout);
}
render();
| import 'regenerator-runtime/runtime';
import ReactDOMServer from 'react-dom/server';
import SourceMapSupport from 'source-map-support';
import { I18nextProvider } from 'react-i18next';
import FormItemChangeGroup from '../app/javascript/FormPresenter/ItemChangeDisplays/FormItemChangeGroup';
import AppRootContext, { appRootContextDefaultValue } from '../app/javascript/AppRootContext';
import { timezoneNameForConvention } from '../app/javascript/TimeUtils';
import getI18n from '../app/javascript/setupI18Next';
SourceMapSupport.install();
const props = JSON.parse(process.argv[2]);
async function render() {
const i18n = await getI18n();
ReactDOMServer.renderToStaticNodeStream(
<AppRootContext.Provider
value={{
...appRootContextDefaultValue,
language: props.convention.language,
timezoneName: timezoneNameForConvention(props.convention),
}}
>
<I18nextProvider i18n={i18n}>
<FormItemChangeGroup {...props} />
</I18nextProvider>
</AppRootContext.Provider>,
).pipe(process.stdout);
}
render();
| Load regenerator-runtime explicitly in CLI util that needs it | Load regenerator-runtime explicitly in CLI util that needs it
| TypeScript | mit | neinteractiveliterature/intercode,neinteractiveliterature/intercode,neinteractiveliterature/intercode,neinteractiveliterature/intercode,neinteractiveliterature/intercode | ---
+++
@@ -1,3 +1,5 @@
+import 'regenerator-runtime/runtime';
+
import ReactDOMServer from 'react-dom/server';
import SourceMapSupport from 'source-map-support';
|
c774c4b5caea6173d73a2696ce8bfd537876212e | functions/src/search/index-contents.ts | functions/src/search/index-contents.ts | import * as algoliasearch from 'algoliasearch'
import { Request, Response } from 'express'
import { FirebaseApp } from '../firebase'
import { AlgoliaConfig } from './config'
import { indexEvents } from './index-events'
import { indexSpeakers } from './index-speakers'
export const indexContent =
(firebaseApp: FirebaseApp, algoliaConfig: AlgoliaConfig) => (_: Request, response: Response) => {
const algolia = algoliasearch(
algoliaConfig.application_id,
algoliaConfig.api_key
)
const indexPrefix = algoliaConfig.index_prefix.replace(/[^\w]/, '_')
Promise.all([
indexSpeakers(firebaseApp, algolia, indexPrefix),
indexEvents(firebaseApp, algolia, indexPrefix)
]).then(() => {
response.status(200).send('Yay!')
}).catch(error => {
console.error(error)
response.status(500).send('Nay!')
})
}
const replaceNonWordCharsWithUnderscores = (original: string): string => {
original.replace(/[^\w]/, '_')
} | import * as algoliasearch from 'algoliasearch'
import { Request, Response } from 'express'
import { FirebaseApp } from '../firebase'
import { AlgoliaConfig } from './config'
import { indexEvents } from './index-events'
import { indexSpeakers } from './index-speakers'
export const indexContent =
(firebaseApp: FirebaseApp, algoliaConfig: AlgoliaConfig) => (_: Request, response: Response) => {
const algolia = algoliasearch(
algoliaConfig.application_id,
algoliaConfig.api_key
)
const indexPrefix = replaceNonWordCharsWithUnderscores(algoliaConfig.index_prefix)
Promise.all([
indexSpeakers(firebaseApp, algolia, indexPrefix),
indexEvents(firebaseApp, algolia, indexPrefix)
]).then(() => {
response.status(200).send('Yay!')
}).catch(error => {
console.error(error)
response.status(500).send('Nay!')
})
}
const replaceNonWordCharsWithUnderscores = (original: string): string => {
return original.replace(/[^\w]/, '_')
}
| Add missing empty line at EOF | Add missing empty line at EOF
| TypeScript | apache-2.0 | squanchy-dev/squanchy-firebase,squanchy-dev/squanchy-firebase | ---
+++
@@ -13,7 +13,7 @@
algoliaConfig.api_key
)
- const indexPrefix = algoliaConfig.index_prefix.replace(/[^\w]/, '_')
+ const indexPrefix = replaceNonWordCharsWithUnderscores(algoliaConfig.index_prefix)
Promise.all([
indexSpeakers(firebaseApp, algolia, indexPrefix),
indexEvents(firebaseApp, algolia, indexPrefix)
@@ -26,5 +26,5 @@
}
const replaceNonWordCharsWithUnderscores = (original: string): string => {
- original.replace(/[^\w]/, '_')
+ return original.replace(/[^\w]/, '_')
} |
b4771305d32bbbb53099da8722e627f3421b39fb | step-release-vis/src/app/services/candidate.ts | step-release-vis/src/app/services/candidate.ts | import {Injectable} from '@angular/core';
import {Candidate} from '../models/Candidate';
import {Polygon} from '../models/Polygon';
@Injectable({
providedIn: 'root',
})
export class CandidateService {
cands: Map<string, Candidate>;
constructor() {}
// TODO(#169): addCandidate(color, name) + addPolygons(polygons)
polygonHovered(polygon: Polygon): void {
this.cands.get(polygon.candName).polygonHovered();
}
polygonUnhovered(polugon: Polygon): void {
this.cands.get(polugon.candName).polygonUnhovered();
}
}
| import {Injectable} from '@angular/core';
import {Candidate} from '../models/Candidate';
import {Polygon} from '../models/Polygon';
@Injectable({
providedIn: 'root',
})
export class CandidateService {
cands: Map<string, Candidate>;
constructor() {}
addCandidate(color: number, name: string): void {
this.cands.set(name, new Candidate(name, color));
}
polygonHovered(polygon: Polygon): void {
this.cands.get(polygon.candName).polygonHovered();
}
polygonUnhovered(polugon: Polygon): void {
this.cands.get(polugon.candName).polygonUnhovered();
}
}
| Implement addCandidate function for CandidateService. | Implement addCandidate function for CandidateService.
| 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,9 @@
constructor() {}
- // TODO(#169): addCandidate(color, name) + addPolygons(polygons)
+ addCandidate(color: number, name: string): void {
+ this.cands.set(name, new Candidate(name, color));
+ }
polygonHovered(polygon: Polygon): void {
this.cands.get(polygon.candName).polygonHovered(); |
5fe79b3091558941cb2b94ef0882575cfaef21be | projects/ng-diff-match-patch/src/lib/diffMatchPatch.service.ts | projects/ng-diff-match-patch/src/lib/diffMatchPatch.service.ts | import { Injectable } from '@angular/core';
import { DiffMatchPatch, DiffOp } from './diffMatchPatch';
@Injectable()
export class DiffMatchPatchService {
constructor(private dmp: DiffMatchPatch) { }
ngOnInit () {
}
getDiff(left: string, right: string) {
return this.dmp.diff_main(left, right);
}
getSemanticDiff(left: string, right: string) {
const diffs = this.dmp.diff_main(left, right);
this.dmp.diff_cleanupSemantic(diffs);
return diffs;
}
getProcessingDiff(left: string, right: string) {
const diffs = this.dmp.diff_main(left, right);
this.dmp.diff_cleanupEfficiency(diffs);
return diffs;
}
getLineDiff(left: string, right: string) {
const chars = this.dmp.diff_linesToChars_(left, right);
const diffs = this.dmp.diff_main(chars.chars1, chars.chars2, false);
this.dmp.diff_charsToLines_(diffs, chars.lineArray);
return diffs;
}
getDmp() {
return this.dmp;
}
}
| import { Injectable, OnInit } from '@angular/core';
import { DiffMatchPatch, DiffOp } from './diffMatchPatch';
@Injectable()
export class DiffMatchPatchService implements OnInit {
constructor(private dmp: DiffMatchPatch) { }
ngOnInit () {
}
getDiff(left: string, right: string) {
return this.dmp.diff_main(left, right);
}
getSemanticDiff(left: string, right: string) {
const diffs = this.dmp.diff_main(left, right);
this.dmp.diff_cleanupSemantic(diffs);
return diffs;
}
getProcessingDiff(left: string, right: string) {
const diffs = this.dmp.diff_main(left, right);
this.dmp.diff_cleanupEfficiency(diffs);
return diffs;
}
getLineDiff(left: string, right: string) {
const chars = this.dmp.diff_linesToChars_(left, right);
const diffs = this.dmp.diff_main(chars.chars1, chars.chars2, false);
this.dmp.diff_charsToLines_(diffs, chars.lineArray);
return diffs;
}
getDmp() {
return this.dmp;
}
}
| Add "implements OnInit" for class DiffMatchPatchService | Add "implements OnInit" for class DiffMatchPatchService
| TypeScript | mit | elliotforbes/ng-diff-match-patch,elliotforbes/ng-diff-match-patch,elliotforbes/ng-diff-match-patch | ---
+++
@@ -1,13 +1,13 @@
-import { Injectable } from '@angular/core';
+import { Injectable, OnInit } from '@angular/core';
import { DiffMatchPatch, DiffOp } from './diffMatchPatch';
@Injectable()
-export class DiffMatchPatchService {
+export class DiffMatchPatchService implements OnInit {
constructor(private dmp: DiffMatchPatch) { }
ngOnInit () {
-
+
}
getDiff(left: string, right: string) { |
123735eeb1d4d558fec9077257de5857ba786e62 | packages/angular/cli/commands/e2e-impl.ts | packages/angular/cli/commands/e2e-impl.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ArchitectCommand } from '../models/architect-command';
import { Arguments } from '../models/interface';
import { Schema as E2eCommandSchema } from './e2e';
export class E2eCommand extends ArchitectCommand<E2eCommandSchema> {
public readonly target = 'e2e';
public readonly multiTarget = true;
public readonly missingTargetError = `
Cannot find "e2e" target for the specified project.
You should add a package that implements end-to-end testing capabilities.
For example:
WebdriverIO: ng add @wdio/schematics
More options will be added to the list as they become available.
`;
async initialize(options: E2eCommandSchema & Arguments) {
if (!options.help) {
return super.initialize(options);
}
}
}
| /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ArchitectCommand } from '../models/architect-command';
import { Arguments } from '../models/interface';
import { Schema as E2eCommandSchema } from './e2e';
export class E2eCommand extends ArchitectCommand<E2eCommandSchema> {
public readonly target = 'e2e';
public readonly multiTarget = true;
public readonly missingTargetError = `
Cannot find "e2e" target for the specified project.
You should add a package that implements end-to-end testing capabilities.
For example:
Cypress: ng add @cypress/schematic
WebdriverIO: ng add @wdio/schematics
More options will be added to the list as they become available.
`;
async initialize(options: E2eCommandSchema & Arguments) {
if (!options.help) {
return super.initialize(options);
}
}
}
| Add Cypress schematic to e2e command | docs(@angular/cli): Add Cypress schematic to e2e command
Add Cypress schematic/builder, see
https://github.com/cypress-io/cypress/tree/master/npm/cypress-schematic
and
https:1a94db227b83d9e7ff09a0653dff3a00dcc5f32a@cypress/schematic
| TypeScript | mit | catull/angular-cli,angular/angular-cli,geofffilippi/angular-cli,catull/angular-cli,catull/angular-cli,ocombe/angular-cli,catull/angular-cli,ocombe/angular-cli,Brocco/angular-cli,angular/angular-cli,clydin/angular-cli,ocombe/angular-cli,ocombe/angular-cli,ocombe/angular-cli,angular/angular-cli,clydin/angular-cli,Brocco/angular-cli,Brocco/angular-cli,angular/angular-cli,clydin/angular-cli,geofffilippi/angular-cli,Brocco/angular-cli,geofffilippi/angular-cli,geofffilippi/angular-cli,clydin/angular-cli,Brocco/angular-cli | ---
+++
@@ -19,6 +19,7 @@
You should add a package that implements end-to-end testing capabilities.
For example:
+ Cypress: ng add @cypress/schematic
WebdriverIO: ng add @wdio/schematics
More options will be added to the list as they become available. |
c3cd88304f566d0f9caa6b6bb3ca91fad66de52f | packages/react-sequential-id/src/index.ts | packages/react-sequential-id/src/index.ts | import {
Component,
ComponentElement,
ConsumerProps,
createContext,
createElement as r,
Props,
ProviderProps,
ReactElement,
ReactPortal,
SFC,
SFCElement,
} from 'react'
import uniqueid = require('uniqueid')
export interface IIdProviderProps {
factory?: () => string
}
export interface ISequentialIdProps {
children?: (id: string) => ReactElement<any> | null
}
export {
Component,
ComponentElement,
ConsumerProps,
ProviderProps,
ReactPortal,
SFCElement,
}
const IdContext = createContext(createIdFactory())
export function IdProvider(props: IIdProviderProps & Props<{}>) {
const { children, factory = createIdFactory() } = props
return r(IdContext.Provider, { value: factory }, children)
}
export const SequentialId: SFC<ISequentialIdProps> = props => {
const { children = () => null } = props
if (typeof children !== 'function') {
return null
}
return r(IdContext.Consumer, {
children: (factory: () => string) => children(factory()),
})
}
export function createIdFactory() {
return uniqueid('i')
}
export default SequentialId
| import {
Component,
ComponentElement,
ConsumerProps,
createContext,
createElement as r,
Props,
ProviderProps,
ReactElement,
ReactPortal,
SFC,
SFCElement,
} from 'react'
import uniqueid = require('uniqueid')
export interface IIdProviderProps {
factory?: () => string
}
export interface ISequentialIdProps {
children?: (id: string) => ReactElement<any> | null
}
export {
Component,
ComponentElement,
ConsumerProps,
ProviderProps,
ReactPortal,
SFCElement,
}
const IdContext = createContext(createIdFactory())
export function IdProvider(props: IIdProviderProps & Props<{}>) {
const { children, factory = createIdFactory() } = props
return r(IdContext.Provider, { value: factory }, children)
}
export const SequentialId: SFC<ISequentialIdProps> = function SequentialId({
children = () => null,
}) {
if (typeof children !== 'function') {
return null
}
return r(IdContext.Consumer, {
children: (factory: () => string) => children(factory()),
})
}
export function createIdFactory() {
return uniqueid('i')
}
export default SequentialId
| Use both named function and const | Use both named function and const
| TypeScript | mit | thirdhand/components,thirdhand/components | ---
+++
@@ -37,8 +37,9 @@
return r(IdContext.Provider, { value: factory }, children)
}
-export const SequentialId: SFC<ISequentialIdProps> = props => {
- const { children = () => null } = props
+export const SequentialId: SFC<ISequentialIdProps> = function SequentialId({
+ children = () => null,
+}) {
if (typeof children !== 'function') {
return null
} |
4d941be083a990707df71118ecefa012d62237a2 | client/app/app-routing.module.ts | client/app/app-routing.module.ts | import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NotFoundComponent } from './not-found.component';
const routes: Routes = [
{ path: '', redirectTo: '/forms', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
| import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NotFoundComponent } from './not-found.component';
const routes: Routes = [
{ path: '', redirectTo: '/tables', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
| Change default route to /tables | Change default route to /tables
| TypeScript | mit | mattbdean/Helium,mattbdean/Helium,mattbdean/Helium,mattbdean/Helium | ---
+++
@@ -4,7 +4,7 @@
import { NotFoundComponent } from './not-found.component';
const routes: Routes = [
- { path: '', redirectTo: '/forms', pathMatch: 'full' },
+ { path: '', redirectTo: '/tables', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent }
];
|
cb9a6d55a39bdd855863884e9bc2602856a95ca4 | layouts/main.tsx | layouts/main.tsx | import Header from "../components/Header"
import { Fragment, PropsWithChildren, FunctionComponent } from "react"
import Footer from "../components/Footer"
const Index: FunctionComponent = ({ children }: PropsWithChildren<unknown>) => (
<Fragment>
<Header />
<main>{children}</main>
<Footer />
<style jsx>{`
main {
width: var(--content-width);
margin: 0 auto;
flex: 1;
}
`}</style>
</Fragment>
)
export default Index
| import Header from "../components/Header"
import { Fragment, PropsWithChildren, FunctionComponent } from "react"
import Footer from "../components/Footer"
const Index: FunctionComponent = ({ children }: PropsWithChildren<unknown>) => (
<Fragment>
<a id="skip-to-content" href="#main">
Skip to content
</a>
<Header />
<main id="main">{children}</main>
<Footer />
<style jsx>{`
#skip-to-content {
background: var(--secondary-background);
padding: 8px;
position: absolute;
transform: translateY(-100%);
border-bottom-right-radius: 6px;
}
#skip-to-content:focus {
transform: translateY(0%);
}
main {
width: var(--content-width);
margin: 0 auto;
flex: 1;
}
`}</style>
</Fragment>
)
export default Index
| Add "Skip to content" link | Add "Skip to content" link
Closes issue #1
| TypeScript | mit | JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk | ---
+++
@@ -4,10 +4,25 @@
const Index: FunctionComponent = ({ children }: PropsWithChildren<unknown>) => (
<Fragment>
+ <a id="skip-to-content" href="#main">
+ Skip to content
+ </a>
<Header />
- <main>{children}</main>
+ <main id="main">{children}</main>
<Footer />
<style jsx>{`
+ #skip-to-content {
+ background: var(--secondary-background);
+ padding: 8px;
+ position: absolute;
+ transform: translateY(-100%);
+ border-bottom-right-radius: 6px;
+ }
+
+ #skip-to-content:focus {
+ transform: translateY(0%);
+ }
+
main {
width: var(--content-width);
margin: 0 auto; |
e0111010c7acd77602b8b33a9a19663f1bf61d0e | ui/test/kapacitor/components/KapacitorRules.test.tsx | ui/test/kapacitor/components/KapacitorRules.test.tsx | import React from 'react'
import {shallow} from 'enzyme'
import KapacitorRules from 'src/kapacitor/components/KapacitorRules'
import {source, kapacitorRules} from 'test/resources'
jest.mock('src/shared/apis', () => require('mocks/shared/apis'))
const setup = (override = {}) => {
const props = {
source,
rules: kapacitorRules,
hasKapacitor: true,
loading: false,
onDelete: () => {},
onChangeRuleStatus: () => {},
}
const wrapper = shallow(<KapacitorRules {...props} />)
return {
wrapper,
props,
}
}
describe('Kapacitor.Containers.KapacitorRules', () => {
afterEach(() => {
jest.clearAllMocks()
})
describe('rendering', () => {
it('renders the KapacitorRules', () => {
const {wrapper} = setup()
expect(wrapper.exists()).toBe(true)
})
})
})
| import React from 'react'
import {shallow} from 'enzyme'
import KapacitorRules from 'src/kapacitor/components/KapacitorRules'
import {source, kapacitorRules} from 'test/resources'
jest.mock('src/shared/apis', () => require('mocks/shared/apis'))
const setup = (override = {}) => {
const props = {
source,
rules: kapacitorRules,
hasKapacitor: true,
loading: false,
onDelete: () => {},
onChangeRuleStatus: () => {},
}
const wrapper = shallow(<KapacitorRules {...props} />)
return {
wrapper,
props,
}
}
describe('Kapacitor.Containers.KapacitorRules', () => {
afterEach(() => {
jest.clearAllMocks()
})
describe('rendering', () => {
it('renders the KapacitorRules', () => {
const {wrapper} = setup()
expect(wrapper.exists()).toBe(true)
})
it('renders two tables', () => {
const {wrapper} = setup()
expect(wrapper.find('.panel-body').length).toEqual(2)
})
})
})
| Test KapacitorRules to render two tables | Test KapacitorRules to render two tables
| TypeScript | mit | influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdata/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,li-ang/influxdb,nooproblem/influxdb | ---
+++
@@ -35,5 +35,10 @@
const {wrapper} = setup()
expect(wrapper.exists()).toBe(true)
})
+
+ it('renders two tables', () => {
+ const {wrapper} = setup()
+ expect(wrapper.find('.panel-body').length).toEqual(2)
+ })
})
}) |
48caf8d9fc37b843db0acedd56e30b8b16a5ef62 | packages/fs-kernels/src/kernel.ts | packages/fs-kernels/src/kernel.ts | import { launch, launchSpec, LaunchedKernel, cleanup } from "./spawnteract";
import pidusage from "pidusage";
import { KernelSpec } from "./kernelspecs";
export default class Kernel {
name?: string;
kernelSpec?: KernelSpec;
launchedKernel: LaunchedKernel;
constructor(input: string | KernelSpec) {
if (typeof input === "string") {
this.name = input;
} else {
this.kernelSpec = input;
}
}
async launch() {
let launchedKernel;
if (this.name && !this.kernelSpec) {
launchedKernel = await launch(this.name);
} else {
launchedKernel = await launchSpec(this.kernelSpec);
}
this.launchedKernel = launchedKernel;
}
async shutdown() {
this.launchedKernel.spawn.kill();
cleanup(this.launchedKernel.connectionFile);
this.launchedKernel = undefined;
}
async getUsage() {
const pid = this.launchedKernel.spawn.pid;
return await pidusage(pid);
}
}
| import { launch, launchSpec, LaunchedKernel, cleanup } from "./spawnteract";
import pidusage from "pidusage";
import { KernelSpec } from "./kernelspecs";
export default class Kernel {
name?: string;
kernelSpec?: KernelSpec;
launchedKernel?: LaunchedKernel;
constructor(input: string | KernelSpec) {
if (typeof input === "string") {
this.name = input;
} else {
this.kernelSpec = input;
}
}
async launch() {
let launchedKernel;
if (this.name && !this.kernelSpec) {
launchedKernel = await launch(this.name);
} else if (this.kernelSpec && !this.name) {
launchedKernel = await launchSpec(this.kernelSpec);
}
this.launchedKernel = launchedKernel;
}
async shutdown() {
if (this.launchedKernel) {
this.launchedKernel.spawn.kill();
cleanup(this.launchedKernel.connectionFile);
this.launchedKernel = undefined;
}
}
async getUsage() {
if (this.launchedKernel) {
const pid = this.launchedKernel.spawn.pid;
return await pidusage(pid);
}
}
}
| Fix types on Kernel class properties | Fix types on Kernel class properties
| TypeScript | bsd-3-clause | nteract/composition,nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract | ---
+++
@@ -5,7 +5,7 @@
export default class Kernel {
name?: string;
kernelSpec?: KernelSpec;
- launchedKernel: LaunchedKernel;
+ launchedKernel?: LaunchedKernel;
constructor(input: string | KernelSpec) {
if (typeof input === "string") {
@@ -19,7 +19,7 @@
let launchedKernel;
if (this.name && !this.kernelSpec) {
launchedKernel = await launch(this.name);
- } else {
+ } else if (this.kernelSpec && !this.name) {
launchedKernel = await launchSpec(this.kernelSpec);
}
@@ -27,13 +27,17 @@
}
async shutdown() {
- this.launchedKernel.spawn.kill();
- cleanup(this.launchedKernel.connectionFile);
- this.launchedKernel = undefined;
+ if (this.launchedKernel) {
+ this.launchedKernel.spawn.kill();
+ cleanup(this.launchedKernel.connectionFile);
+ this.launchedKernel = undefined;
+ }
}
async getUsage() {
- const pid = this.launchedKernel.spawn.pid;
- return await pidusage(pid);
+ if (this.launchedKernel) {
+ const pid = this.launchedKernel.spawn.pid;
+ return await pidusage(pid);
+ }
}
} |
c8e5746dded9b423f089043b3409d493de4e9793 | cli/introspection/src/prompt/utils/templates/printSchema.ts | cli/introspection/src/prompt/utils/templates/printSchema.ts | import { credentialsToUri, DatabaseCredentials } from '@prisma/sdk'
export const printSchema = ({
usePhoton,
credentials,
}: {
usePhoton: boolean
credentials: DatabaseCredentials
}) => `${printCredentials(credentials)}
${
usePhoton
? `
generator photon {
provider = "photonjs"
}`
: ''
}
model User {
id String @default(cuid()) @id @unique
email String @unique
name String?
posts Post[]
}
model Post {
id String @default(cuid()) @id @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean
title String
content String?
author User?
}`
const printCredentials = (credentials: DatabaseCredentials) => `datasource db {
provider = "${prettyPrintType(credentials.type)}"
url = "${credentialsToUri(credentials)}"
}`
function prettyPrintType(type) {
if (type === 'postgres') {
return 'postgresql'
}
return type
}
| import { credentialsToUri, DatabaseCredentials } from '@prisma/sdk'
export const printSchema = ({
usePhoton,
credentials,
}: {
usePhoton: boolean
credentials: DatabaseCredentials
}) => `${printCredentials(credentials)}
${
usePhoton
? `
generator photon {
provider = "photonjs"
}`
: ''
}
model User {
id String @default(cuid()) @id
email String @unique
name String?
posts Post[]
}
model Post {
id String @default(cuid()) @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean
title String
content String?
author User?
}`
const printCredentials = (credentials: DatabaseCredentials) => `datasource db {
provider = "${prettyPrintType(credentials.type)}"
url = "${credentialsToUri(credentials)}"
}`
function prettyPrintType(type) {
if (type === 'postgres') {
return 'postgresql'
}
return type
}
| Remove @unique from basic schema example | Remove @unique from basic schema example | TypeScript | apache-2.0 | prisma/prisma,prisma/prisma,prisma/prisma | ---
+++
@@ -17,14 +17,14 @@
}
model User {
- id String @default(cuid()) @id @unique
+ id String @default(cuid()) @id
email String @unique
name String?
posts Post[]
}
model Post {
- id String @default(cuid()) @id @unique
+ id String @default(cuid()) @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean |
efb984912e8f3bf174b5d219951ab255c6913aa5 | index.ts | index.ts | export interface IOptions {
debug?: boolean;
}
const defaultOptions: IOptions = {
debug: false,
};
export function* sinergia(
iterable: Iterable<any>,
task: (accumulator: any, item: any) => any,
initialValue: any,
options: IOptions = {},
) {
const actualOptions = { ...defaultOptions, ...options };
let accumulator: any = initialValue;
let animToken: number;
try {
for (const item of iterable) {
const itemIterator: IterableIterator<any> = task(accumulator, item);
yield new Promise(resolve => {
const step = () => {
const iteration = itemIterator.next();
if (iteration.done) {
if (actualOptions.debug) console.log(`item task is done with latest iteration`, iteration);
accumulator = iteration.value;
resolve();
}
else {
requestAnimationFrame(step);
}
};
animToken = requestAnimationFrame(step);
});
}
return { value: accumulator };
} finally {
// This block is called when sinergia is interrupted with `.return()`
if (animToken) cancelAnimationFrame(animToken);
yield { value: accumulator };
}
}
| export interface IOptions {
debug?: boolean;
}
const defaultOptions: IOptions = {
debug: false,
};
export function* sinergia(
iterable: Iterable<any>,
task: (accumulator: any, item: any) => any,
initialValue: any,
options: IOptions = {},
) {
const actualOptions = { ...defaultOptions, ...options };
let accumulator: any = initialValue;
let animToken: number;
try {
for (const item of iterable) {
const itemIterator: IterableIterator<any> = task(accumulator, item);
yield new Promise(resolve => {
const step = () => {
const iteration = itemIterator.next();
if (iteration.done) {
if (actualOptions.debug) console.log(`item task is done with latest iteration`, iteration);
accumulator = iteration.value;
resolve();
}
else {
animToken = requestAnimationFrame(step);
}
};
animToken = requestAnimationFrame(step);
});
}
return { value: accumulator };
} finally {
// This block is called when sinergia is interrupted with `.return()`
if (animToken) cancelAnimationFrame(animToken);
yield { value: accumulator };
}
}
| Add missing animToken inside step | Add missing animToken inside step
| TypeScript | mit | jiayihu/sinergia,jiayihu/sinergia | ---
+++
@@ -30,7 +30,7 @@
resolve();
}
else {
- requestAnimationFrame(step);
+ animToken = requestAnimationFrame(step);
}
};
|
82bd8b4ff27bb737e9787a45a61b61b4108ac99b | src/lib/tubular-settings.service.ts | src/lib/tubular-settings.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class TubularSettingsService {
constructor() {
}
public put(id: string, value: string) {
localStorage.setItem(id, JSON.stringify(value));
}
public get(key: string): any {
return JSON.parse(localStorage.getItem(key)) || false;
}
public delete(key: string): any {
localStorage.removeItem(key);
}
}
| import { Injectable } from '@angular/core';
export interface ITubularSettingsProvider {
put(id: string, value: string): void;
get(key: string): any;
delete(key: string): void;
}
@Injectable()
export class TubularSettingsService {
constructor() {
}
public put(id: string, value: string) {
localStorage.setItem(id, JSON.stringify(value));
}
public get(key: string): any {
return JSON.parse(localStorage.getItem(key)) || false;
}
public delete(key: string) {
localStorage.removeItem(key);
}
}
| Add interface for settings provider | Add interface for settings provider
| TypeScript | mit | unosquare/tubular2,unosquare/tubular2,unosquare/tubular2,unosquare/tubular2 | ---
+++
@@ -1,4 +1,10 @@
import { Injectable } from '@angular/core';
+
+export interface ITubularSettingsProvider {
+ put(id: string, value: string): void;
+ get(key: string): any;
+ delete(key: string): void;
+}
@Injectable()
export class TubularSettingsService {
@@ -14,7 +20,7 @@
return JSON.parse(localStorage.getItem(key)) || false;
}
- public delete(key: string): any {
+ public delete(key: string) {
localStorage.removeItem(key);
}
} |
731a915baa665a9e2b06bc68c2c97d0c058a2454 | src/components/Calendar/SelectedHitDate/HitDbEntryCollapsible.tsx | src/components/Calendar/SelectedHitDate/HitDbEntryCollapsible.tsx | import * as React from 'react';
import { Collapsible, Card, Stack, TextStyle, Caption } from '@shopify/polaris';
import { HitDatabaseEntry } from '../../../types';
import EditBonusButton from './EditBonusButton';
export interface Props {
readonly open: boolean;
readonly hit: HitDatabaseEntry;
}
class HitDbEntryCollapsible extends React.PureComponent<Props, never> {
public render() {
const { open, hit: { id, feedback, requester, bonus } } = this.props;
return (
<Collapsible open={open}>
<Card.Section>
<Stack vertical spacing="loose" distribution="equalSpacing">
<Caption>
Hit ID: <TextStyle variation="subdued">{id}</TextStyle>
</Caption>
<Caption>
Requester: {' '}
<TextStyle variation="subdued">{requester.name}</TextStyle>
</Caption>
<Caption>
Feedback: {' '}
<TextStyle variation="subdued">
{feedback || 'No feedback given.'}
</TextStyle>
</Caption>
<EditBonusButton hitId={id} bonus={bonus} />
</Stack>
</Card.Section>
</Collapsible>
);
}
}
export default HitDbEntryCollapsible;
| import * as React from 'react';
import { Collapsible, Card, Stack, TextStyle, Caption } from '@shopify/polaris';
import { HitDatabaseEntry } from '../../../types';
import EditBonusButton from './EditBonusButton';
export interface Props {
readonly open: boolean;
readonly hit: HitDatabaseEntry;
}
class HitDbEntryCollapsible extends React.PureComponent<Props, never> {
public render() {
const { open, hit: { id, feedback, requester, bonus } } = this.props;
return (
<Collapsible open={open}>
<Card.Section>
<Stack vertical spacing="loose" distribution="equalSpacing">
<Caption>
Hit ID: <TextStyle variation="strong">{id}</TextStyle>
</Caption>
<Caption>
Requester: {' '}
<TextStyle variation="strong">{requester.name}</TextStyle>
</Caption>
<Caption>
Feedback: {' '}
<TextStyle variation="strong">
{feedback || 'No feedback given.'}
</TextStyle>
</Caption>
<EditBonusButton hitId={id} bonus={bonus} />
</Stack>
</Card.Section>
</Collapsible>
);
}
}
export default HitDbEntryCollapsible;
| Change subdued textStyle to strong. | Change subdued textStyle to strong.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -16,15 +16,15 @@
<Card.Section>
<Stack vertical spacing="loose" distribution="equalSpacing">
<Caption>
- Hit ID: <TextStyle variation="subdued">{id}</TextStyle>
+ Hit ID: <TextStyle variation="strong">{id}</TextStyle>
</Caption>
<Caption>
Requester: {' '}
- <TextStyle variation="subdued">{requester.name}</TextStyle>
+ <TextStyle variation="strong">{requester.name}</TextStyle>
</Caption>
<Caption>
Feedback: {' '}
- <TextStyle variation="subdued">
+ <TextStyle variation="strong">
{feedback || 'No feedback given.'}
</TextStyle>
</Caption> |
0c0287a926ce7f720ddf09da72beeeac48cd122e | src/services/vuestic-ui/index.ts | src/services/vuestic-ui/index.ts | // @ts-ignore
// import { ColorThemeActionsMixin } from 'vuestic-ui/src/services/ColorThemePlugin' // TODO
// // import { ColorThemeMixin, ColorThemeActionsMixin } from 'vuestic-ui/src/services/ColorThemePlugin'
// // import { getHoverColor, getGradientBackground, hex2rgb, hex2hsl } from 'vuestic-ui/src/services/color-functions'
// // import { ColorThemePlugin, ColorThemeMixin } from 'vuestic-ui-next/src/services/ColorThemePlugin.ts'
// import { ColorThemePlugin, ColorThemeMixin } from 'vuestic-ui/src/services/ColorThemePlugin'
// import {
// getHoverColor,
// getGradientBackground,
// shiftHslColor,
// colorToRgba,
// } from 'vuestic-ui-next/src/services/color-functions'
// import { ContextPlugin } from 'vuestic-ui-next/src/components/context-test/context-provide/ContextPlugin'
export {
// ColorThemePlugin,
// ColorThemeMixin,
// ColorThemeActionsMixin,
// getHoverColor,
// getGradientBackground,
// colorToRgba,
// shiftHslColor,
// ContextPlugin,
}
| // @ts-ignore
// import { ColorThemeActionsMixin } from 'vuestic-ui/src/services/ColorThemePlugin' // TODO
// import { ColorThemeMixin, ColorThemeActionsMixin } from 'vuestic-ui/src/services/ColorThemePlugin'
// // import { getHoverColor, getGradientBackground, hex2rgb, hex2hsl } from 'vuestic-ui/src/services/color-functions'
// // import { ColorThemePlugin, ColorThemeMixin } from 'vuestic-ui-next/src/services/ColorThemePlugin.ts'
// import { ColorThemePlugin, ColorThemeMixin } from 'vuestic-ui/src/services/ColorThemePlugin'
// import {
// getHoverColor,
// getGradientBackground,
// shiftHslColor,
// colorToRgba,
// } from 'vuestic-ui-next/src/services/color-functions'
// import { ContextPlugin } from 'vuestic-ui-next/src/components/context-test/context-provide/ContextPlugin'
export {
// ColorThemePlugin,
// ColorThemeMixin,
// ColorThemeActionsMixin,
// getHoverColor,
// getGradientBackground,
// colorToRgba,
// shiftHslColor,
// ContextPlugin,
}
| Comment broken import from vuestic 0.2.2. | Comment broken import from vuestic 0.2.2.
| TypeScript | mit | epicmaxco/vuestic-admin,epicmaxco/vuestic-admin,epicmaxco/vuestic-admin,epicmaxco/vuestic-admin | ---
+++
@@ -1,6 +1,6 @@
// @ts-ignore
// import { ColorThemeActionsMixin } from 'vuestic-ui/src/services/ColorThemePlugin' // TODO
-// // import { ColorThemeMixin, ColorThemeActionsMixin } from 'vuestic-ui/src/services/ColorThemePlugin'
+// import { ColorThemeMixin, ColorThemeActionsMixin } from 'vuestic-ui/src/services/ColorThemePlugin'
// // import { getHoverColor, getGradientBackground, hex2rgb, hex2hsl } from 'vuestic-ui/src/services/color-functions'
// // import { ColorThemePlugin, ColorThemeMixin } from 'vuestic-ui-next/src/services/ColorThemePlugin.ts'
// import { ColorThemePlugin, ColorThemeMixin } from 'vuestic-ui/src/services/ColorThemePlugin'
@@ -14,7 +14,7 @@
export {
// ColorThemePlugin,
-// ColorThemeMixin,
+ // ColorThemeMixin,
// ColorThemeActionsMixin,
// getHoverColor,
// getGradientBackground, |
e35355712396af740d94441419320d424db99a9f | src/marketplace/offerings/create/AccountingStepContainer.tsx | src/marketplace/offerings/create/AccountingStepContainer.tsx | import { connect } from 'react-redux';
import { compose } from 'redux';
import { withTranslation } from '@waldur/i18n';
import { showComponentsList } from '@waldur/marketplace/common/registry';
import { removeOfferingComponent, removeOfferingQuotas } from '../store/actions';
import { getType, getOfferingComponents } from '../store/selectors';
import { AccountingStep } from './AccountingStep';
const mapStateToProps = state => {
const type = getType(state);
const showComponents = type && showComponentsList(type);
const builtinComponents = getOfferingComponents(state, type);
return {showComponents, type, builtinComponents};
};
const mapStateToDispatch = {
removeOfferingComponent,
removeOfferingQuotas,
};
const connector = compose(connect(mapStateToProps, mapStateToDispatch), withTranslation);
export const AccountingStepContainer = connector(AccountingStep);
| import { connect } from 'react-redux';
import { compose } from 'redux';
import { withTranslation } from '@waldur/i18n';
import { showComponentsList } from '@waldur/marketplace/common/registry';
import { removeOfferingComponent, removeOfferingQuotas } from '../store/actions';
import { getType, getOfferingComponents } from '../store/selectors';
import { AccountingStep } from './AccountingStep';
const mapStateToProps = state => {
const type = getType(state);
const showComponents = type && showComponentsList(type);
const builtinComponents = type && getOfferingComponents(state, type);
return {showComponents, type, builtinComponents};
};
const mapStateToDispatch = {
removeOfferingComponent,
removeOfferingQuotas,
};
const connector = compose(connect(mapStateToProps, mapStateToDispatch), withTranslation);
export const AccountingStepContainer = connector(AccountingStep);
| Fix marketplace offering creation form. | Fix marketplace offering creation form.
Skip components selector unless offering type is selected.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -11,7 +11,7 @@
const mapStateToProps = state => {
const type = getType(state);
const showComponents = type && showComponentsList(type);
- const builtinComponents = getOfferingComponents(state, type);
+ const builtinComponents = type && getOfferingComponents(state, type);
return {showComponents, type, builtinComponents};
};
|
ff74c2839477ef9e4836f4eebde037f2390338e4 | src/emitter/declarations.ts | 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 | AmnisIO/typewriter,AmnisIO/typewriter,AmnisIO/typewriter | ---
+++
@@ -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)}`
+ }
+}; |
d4a8828dc669a2f4691031a57f90fa9aac9c040e | src/components/treeView/leafNode.tsx | src/components/treeView/leafNode.tsx | import * as React from 'react';
import { CommonNodeProps } from './commonNodeProps';
import {NodeRenderStrategy} from './nodeRenderStrategy';
import {TreeViewNavigationUtils} from './treeViewNavigationUtils';
export interface LeafNodeProps extends CommonNodeProps {
node: NodeRenderStrategy;
}
export class LeafNode extends React.Component<LeafNodeProps, {}> {
onKeyDown(event: KeyboardEvent) {
TreeViewNavigationUtils.normalizeKeyboardEventBehaviour(event);
TreeViewNavigationUtils.handleMovementKeyboardEvent(this.props.id, this.props.treeViewId, event);
switch (event.keyCode) {
case 13:
// Enter
this.props.node.onClickBinded();
break;
default:
break;
}
}
render() {
return (
<li role='treeitem'>
<a onClick={this.props.node.onClickBinded} data-treeviewid={this.props.treeViewId}
data-id={this.props.id} tabIndex={this.props.tabbable ? 0 : -1}>
{this.props.node.element()}
</a>
</li>);
}
}
| import * as React from 'react';
import { CommonNodeProps } from './commonNodeProps';
import {NodeRenderStrategy} from './nodeRenderStrategy';
import {TreeViewNavigationUtils} from './treeViewNavigationUtils';
export interface LeafNodeProps extends CommonNodeProps {
node: NodeRenderStrategy;
}
export class LeafNode extends React.Component<LeafNodeProps, {}> {
onKeyDown(event: KeyboardEvent) {
TreeViewNavigationUtils.normalizeKeyboardEventBehaviour(event);
TreeViewNavigationUtils.handleMovementKeyboardEvent(this.props.id, this.props.treeViewId, event);
switch (event.keyCode) {
case 13:
// Enter
this.props.node.onClickBinded();
break;
default:
break;
}
}
render() {
return (
<li role='treeitem'>
<a onClick={this.props.node.onClickBinded} onKeyDown={this.onKeyDown.bind(this)}
data-treeviewid={this.props.treeViewId} data-id={this.props.id} tabIndex={this.props.tabbable ? 0 : -1}>
{this.props.node.element()}
</a>
</li>);
}
}
| Add keydown listener to leaf nodes | Add keydown listener to leaf nodes
| TypeScript | mit | OneNoteDev/OneNotePicker-JS,OneNoteDev/OneNotePicker-JS,OneNoteDev/OneNotePicker-JS | ---
+++
@@ -27,8 +27,8 @@
render() {
return (
<li role='treeitem'>
- <a onClick={this.props.node.onClickBinded} data-treeviewid={this.props.treeViewId}
- data-id={this.props.id} tabIndex={this.props.tabbable ? 0 : -1}>
+ <a onClick={this.props.node.onClickBinded} onKeyDown={this.onKeyDown.bind(this)}
+ data-treeviewid={this.props.treeViewId} data-id={this.props.id} tabIndex={this.props.tabbable ? 0 : -1}>
{this.props.node.element()}
</a>
</li>); |
dd96c06b027cd25d13c9529e9c577e0bc7b7efa3 | src/lib/card/card-title.directive.ts | src/lib/card/card-title.directive.ts | import {
Directive,
HostBinding,
Input
} from '@angular/core';
@Directive({
selector: '[mdc-card-title], mdc-card-title'
})
export class CardTitleDirective {
@Input() titleLarge: boolean = true;
@HostBinding('class.mdc-card__title') className: string = 'mdc-card__title';
@HostBinding('class.mdc-card__title--large') get classTitleLarge(): string {
return this.titleLarge ? 'mdc-card__title--large' : '';
}
} | import {
Directive,
HostBinding,
Input
} from '@angular/core';
@Directive({
selector: '[mdc-card-title], mdc-card-title'
})
export class CardTitleDirective {
@Input() large: boolean = true;
@HostBinding('class.mdc-card__title') className: string = 'mdc-card__title';
@HostBinding('class.mdc-card__title--large') get classTitleLarge(): string {
return this.large ? 'mdc-card__title--large' : '';
}
} | Rename ambiguous Input from titleLarge to large. | fix(card): Rename ambiguous Input from titleLarge to large.
BREAKING CHANGE: Input `titleLarge` has been renamed to `large`. Please update your code
accordingly.
| TypeScript | mit | trimox/angular-mdc-web,trimox/angular-mdc-web | ---
+++
@@ -8,9 +8,9 @@
selector: '[mdc-card-title], mdc-card-title'
})
export class CardTitleDirective {
- @Input() titleLarge: boolean = true;
+ @Input() large: boolean = true;
@HostBinding('class.mdc-card__title') className: string = 'mdc-card__title';
@HostBinding('class.mdc-card__title--large') get classTitleLarge(): string {
- return this.titleLarge ? 'mdc-card__title--large' : '';
+ return this.large ? 'mdc-card__title--large' : '';
}
} |
2c66b19dd2fe5dccb41d4191d6c6c0a4a8380033 | packages/common/src/context/ApolloConsumer.tsx | packages/common/src/context/ApolloConsumer.tsx | import React from 'react';
import ApolloClient from 'apollo-client';
import { InvariantError } from 'ts-invariant';
import { getApolloContext } from './ApolloContext';
export interface ApolloConsumerProps {
children: (client: ApolloClient<object>) => React.ReactChild | null;
}
export const ApolloConsumer: React.FC<ApolloConsumerProps> = props => {
const ApolloContext = getApolloContext();
return (
<ApolloContext.Consumer>
{(context: any) => {
if (!context || !context.client) {
throw new InvariantError(
'Could not find "client" in the context of ApolloConsumer. ' +
'Wrap the root component in an <ApolloProvider>.'
);
}
return props.children(context.client);
}}
</ApolloContext.Consumer>
);
};
| import React from 'react';
import ApolloClient from 'apollo-client';
import { invariant } from 'ts-invariant';
import { getApolloContext } from './ApolloContext';
export interface ApolloConsumerProps {
children: (client: ApolloClient<object>) => React.ReactChild | null;
}
export const ApolloConsumer: React.FC<ApolloConsumerProps> = props => {
const ApolloContext = getApolloContext();
return (
<ApolloContext.Consumer>
{(context: any) => {
invariant(
context && context.client,
'Could not find "client" in the context of ApolloConsumer. ' +
'Wrap the root component in an <ApolloProvider>.'
);
return props.children(context.client);
}}
</ApolloContext.Consumer>
);
};
| Use `invariant` instead of `InvariantError` for clarity | Use `invariant` instead of `InvariantError` for clarity
| TypeScript | mit | apollostack/react-apollo,apollographql/react-apollo,apollographql/react-apollo,apollostack/react-apollo | ---
+++
@@ -1,6 +1,6 @@
import React from 'react';
import ApolloClient from 'apollo-client';
-import { InvariantError } from 'ts-invariant';
+import { invariant } from 'ts-invariant';
import { getApolloContext } from './ApolloContext';
@@ -13,12 +13,11 @@
return (
<ApolloContext.Consumer>
{(context: any) => {
- if (!context || !context.client) {
- throw new InvariantError(
- 'Could not find "client" in the context of ApolloConsumer. ' +
- 'Wrap the root component in an <ApolloProvider>.'
- );
- }
+ invariant(
+ context && context.client,
+ 'Could not find "client" in the context of ApolloConsumer. ' +
+ 'Wrap the root component in an <ApolloProvider>.'
+ );
return props.children(context.client);
}}
</ApolloContext.Consumer> |
dc6cc1968a400de1d31ec316a40325918e456154 | test/baconToNode.ts | test/baconToNode.ts | import 'mocha'
import * as assert from 'assert'
import * as Bacon from 'baconjs'
import * as Bluebird from 'bluebird'
import {baconToReadable} from '../dist/index'
describe('Converting Bacon streams to Node streams', function() {
it('should include events in the node stream from the Bacon stream', () => {
const testData = [7, 3, 2, 7, 6]
const nodeStream = baconToReadable(Bacon.fromArray(testData), {objectMode: true})
return new Bluebird((resolve, reject) => {
let results: number[] = []
nodeStream.on('data', (value: any) => {
results.push(value)
})
nodeStream.on('end', () => resolve(results))
nodeStream.on('close', () => resolve(results))
nodeStream.on('error', err => reject(err))
}).tap(results => {
assert.deepEqual(results, testData)
})
})
}) | import 'mocha'
import * as assert from 'assert'
import * as Bacon from 'baconjs'
import * as Bluebird from 'bluebird'
import {baconToReadable} from '../dist/index'
describe('Converting Bacon streams to Node streams', function() {
it('should include events in the node stream from the Bacon stream', () => {
const testData = [7, 3, 2, 7, 6]
const nodeStream = baconToReadable(Bacon.fromArray(testData), {objectMode: true})
return new Bluebird((resolve, reject) => {
let results: number[] = []
nodeStream.on('data', (value: any) => {
results.push(value)
})
nodeStream.on('end', () => resolve(results))
nodeStream.on('close', () => resolve(results))
nodeStream.on('error', err => reject(err))
}).tap(results => {
assert.deepEqual(results, testData)
})
})
it('should buffer while the stream is paused', function() {
this.timeout(20000)
const testData = ['hey', 'ho', 'let\'s go', 'ey', 'o', 'letsgo']
const baconStream = Bacon.sequentially(500, testData)
const nodeStream = baconToReadable(baconStream, { objectMode: true })
return new Bluebird((resolve, reject) => {
let shouldPauseNext = true
const results: string[] = []
nodeStream.on('data', (value: any) => {
results.push(value)
if (shouldPauseNext) {
nodeStream.pause()
shouldPauseNext = false
setTimeout(() => {
nodeStream.resume()
}, 3000)
} else {
shouldPauseNext = true
}
})
nodeStream.on('end', () => resolve(results))
nodeStream.on('close', () => resolve(results))
nodeStream.on('error', err => reject(err))
}).tap(results => {
assert.deepEqual(results, testData)
})
})
}) | Test that pausing readables from Bacon works | Test that pausing readables from Bacon works
| TypeScript | mit | jliuhtonen/bacon-node-stream | ---
+++
@@ -23,4 +23,35 @@
assert.deepEqual(results, testData)
})
})
+
+ it('should buffer while the stream is paused', function() {
+ this.timeout(20000)
+ const testData = ['hey', 'ho', 'let\'s go', 'ey', 'o', 'letsgo']
+ const baconStream = Bacon.sequentially(500, testData)
+ const nodeStream = baconToReadable(baconStream, { objectMode: true })
+
+ return new Bluebird((resolve, reject) => {
+ let shouldPauseNext = true
+ const results: string[] = []
+
+ nodeStream.on('data', (value: any) => {
+ results.push(value)
+ if (shouldPauseNext) {
+ nodeStream.pause()
+ shouldPauseNext = false
+ setTimeout(() => {
+ nodeStream.resume()
+ }, 3000)
+ } else {
+ shouldPauseNext = true
+ }
+ })
+
+ nodeStream.on('end', () => resolve(results))
+ nodeStream.on('close', () => resolve(results))
+ nodeStream.on('error', err => reject(err))
+ }).tap(results => {
+ assert.deepEqual(results, testData)
+ })
+ })
}) |
51d27efb11de396fe5ca58e2008c38b3adfb2da7 | components/comment/video/video-model.ts | components/comment/video/video-model.ts | import { Injectable } from 'ng-metadata/core';
import { Model } from './../../model/model-service';
import { Comment } from './../comment-model';
export function Comment_VideoFactory( Model, $injector, Game )
{
return Model.create( Comment_Video, {
$injector,
Game,
} );
}
@Injectable()
export class Comment_Video extends Model
{
comment: Comment;
game: any;
static $injector: any;
static Game: any;
constructor( data?: any )
{
const comment: typeof Comment = Comment_Video.$injector.get( 'Comment' );
super( data );
if ( data && data.comment ) {
this.comment = new comment( data.comment );
}
if ( data && data.game ) {
this.game = new Comment_Video.Game( data.game );
}
}
}
| import { Injectable } from 'ng-metadata/core';
import { Model } from './../../model/model-service';
import { Comment } from './../comment-model';
export function Comment_VideoFactory( Model, $injector, Game )
{
return Model.create( Comment_Video, {
$injector,
Game,
} );
}
@Injectable()
export class Comment_Video extends Model
{
provider: string;
provider_video_id: string;
img_thumbnail: string;
youtube_channel: string;
comment: Comment;
game: any;
static $injector: any;
static Game: any;
constructor( data?: any )
{
super( data );
const comment: typeof Comment = Comment_Video.$injector.get( 'Comment' );
if ( data && data.comment ) {
this.comment = new comment( data.comment );
}
if ( data && data.game ) {
this.game = new Comment_Video.Game( data.game );
}
}
}
| Add some params in for comment videos. | Add some params in for comment videos.
| TypeScript | mit | gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib | ---
+++
@@ -13,6 +13,11 @@
@Injectable()
export class Comment_Video extends Model
{
+ provider: string;
+ provider_video_id: string;
+ img_thumbnail: string;
+ youtube_channel: string;
+
comment: Comment;
game: any;
@@ -21,9 +26,9 @@
constructor( data?: any )
{
+ super( data );
+
const comment: typeof Comment = Comment_Video.$injector.get( 'Comment' );
-
- super( data );
if ( data && data.comment ) {
this.comment = new comment( data.comment ); |
259f4d28da141fa72dfd5f2b4abb0c1f30277a53 | src/typings/node.processEnv-ext.d.ts | src/typings/node.processEnv-ext.d.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare namespace NodeJS {
export interface Process {
/**
* The lazy enviroment is a promise that resolves to `process.env`
* once the process is resolved. The use-case is VS Code running
* on Linux/macOS when being launched via a launcher. Then the env
* (as defined in .bashrc etc) isn't properly set and needs to be
* resolved lazy.
*/
lazyEnv: Thenable<typeof process.env> | undefined;
}
}
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare namespace NodeJS {
export interface Process {
/**
* The lazy environment is a promise that resolves to `process.env`
* once the process is resolved. The use-case is VS Code running
* on Linux/macOS when being launched via a launcher. Then the env
* (as defined in .bashrc etc) isn't properly set and needs to be
* resolved lazy.
*/
lazyEnv: Thenable<typeof process.env> | undefined;
}
}
| Fix typo 'enviroment' to 'environment' | Fix typo 'enviroment' to 'environment'
* comment | TypeScript | mit | Krzysztof-Cieslak/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode | ---
+++
@@ -8,7 +8,7 @@
export interface Process {
/**
- * The lazy enviroment is a promise that resolves to `process.env`
+ * The lazy environment is a promise that resolves to `process.env`
* once the process is resolved. The use-case is VS Code running
* on Linux/macOS when being launched via a launcher. Then the env
* (as defined in .bashrc etc) isn't properly set and needs to be |
898b3cb29e7bbebc0624dbea640abdf2ecdd1418 | packages/lesswrong/components/walledGarden/GardenCodesList.tsx | packages/lesswrong/components/walledGarden/GardenCodesList.tsx | import React from 'react';
import { useMulti } from '../../lib/crud/withMulti';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useCurrentUser } from '../common/withUser';
export const GardenCodesList = ({classes, terms}:{classes:ClassesType, terms: GardenCodesViewTerms}) => {
const { GardenCodesItem } = Components
const currentUser = useCurrentUser()
const { results } = useMulti({
terms: {
userId: currentUser?._id,
enableTotal: false,
fetchPolicy: 'cache-and-network',
...terms
},
collectionName: "GardenCodes",
fragmentName: 'GardenCodeFragment'
});
return <div>
{results?.map(code=><GardenCodesItem key={code._id} gardenCode={code}/>)}
</div>
}
const GardenCodesListComponent = registerComponent('GardenCodesList', GardenCodesList);
declare global {
interface ComponentTypes {
GardenCodesList: typeof GardenCodesListComponent
}
}
| import React from 'react';
import { useMulti } from '../../lib/crud/withMulti';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useCurrentUser } from '../common/withUser';
export const GardenCodesList = ({classes, terms}:{classes:ClassesType, terms: GardenCodesViewTerms}) => {
const { GardenCodesItem } = Components
const currentUser = useCurrentUser()
const { results } = useMulti({
terms: {
userId: currentUser?._id,
...terms
},
enableTotal: false,
fetchPolicy: 'cache-and-network',
collectionName: "GardenCodes",
fragmentName: 'GardenCodeFragment'
});
return <div>
{results?.map(code=><GardenCodesItem key={code._id} gardenCode={code}/>)}
</div>
}
const GardenCodesListComponent = registerComponent('GardenCodesList', GardenCodesList);
declare global {
interface ComponentTypes {
GardenCodesList: typeof GardenCodesListComponent
}
}
| Fix some useMulti parameters accidentally being passed as view terms | Fix some useMulti parameters accidentally being passed as view terms
| TypeScript | mit | Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2 | ---
+++
@@ -9,10 +9,10 @@
const { results } = useMulti({
terms: {
userId: currentUser?._id,
- enableTotal: false,
- fetchPolicy: 'cache-and-network',
...terms
},
+ enableTotal: false,
+ fetchPolicy: 'cache-and-network',
collectionName: "GardenCodes",
fragmentName: 'GardenCodeFragment'
}); |
89bd7ceaa3bd47a3f697761c1f3f847550ae0eeb | src/bin/circleci-job-chain.ts | src/bin/circleci-job-chain.ts | #!/usr/bin/env node
import { poller, IOptions } from '../lib/poller'
import * as argv from 'yargs'
let cliArgs = argv.demandOption(['organization','project','circle-token'])
.argv
const options: IOptions = {
organization: cliArgs.organization,
project: cliArgs.project,
branch: cliArgs.branch,
circleToken: cliArgs ['circle-token'],
pollInterval: cliArgs ['poll-interval'],
buildOptions: cliArgs.buildOptions
}
poller(options).catch(console.log)
| #!/usr/bin/env node
import { poller, IOptions } from '../lib/poller'
import * as argv from 'yargs'
let cliArgs = argv.demandOption(['organization','project','circle-token'])
.argv
const options: IOptions = {
organization: cliArgs.organization,
project: cliArgs.project,
branch: cliArgs.branch || 'master',
circleToken: cliArgs ['circle-token'],
pollInterval: cliArgs ['poll-interval'],
buildOptions: cliArgs.buildOptions
}
poller(options).catch(console.log)
| Update default branch to master | Update default branch to master
| TypeScript | mit | riltsken/circleci-job-chain,riltsken/circleci-job-chain | ---
+++
@@ -9,7 +9,7 @@
const options: IOptions = {
organization: cliArgs.organization,
project: cliArgs.project,
- branch: cliArgs.branch,
+ branch: cliArgs.branch || 'master',
circleToken: cliArgs ['circle-token'],
pollInterval: cliArgs ['poll-interval'],
buildOptions: cliArgs.buildOptions |
dcdbd42f18faa07b96b4b3099c4f427c742e4254 | docs/utils/helpers.ts | docs/utils/helpers.ts | import dayjs, { Dayjs } from 'dayjs';
import moment, { Moment } from 'moment';
import { DateTime } from 'luxon';
export function cloneCrossUtils(date: Date | Moment | DateTime | Dayjs) {
if (date instanceof dayjs) {
return (date as Dayjs).clone().toDate();
}
if (date instanceof moment) {
return (date as Moment).clone().toDate();
}
if (date instanceof DateTime) {
return date.toJSDate();
}
if (date instanceof Date) {
return new Date(date.getTime());
}
throw new Error('Cannot properly parse argument passed to cloneCrossUtils');
}
export function copy(text: string) {
return window.navigator.permissions.query({ name: 'clipboard-write' }).then(result => {
if (result.state == 'granted' || result.state == 'prompt') {
return navigator.clipboard.writeText(text);
}
return Promise.reject();
});
}
export function loadScript(src: string, position: Element) {
const script = document.createElement('script');
script.setAttribute('async', '');
script.src = src;
position.appendChild(script);
return script;
}
| import dayjs, { Dayjs } from 'dayjs';
import moment, { Moment } from 'moment';
import { DateTime } from 'luxon';
export function cloneCrossUtils(date: Date | Moment | DateTime | Dayjs) {
if (date instanceof dayjs) {
return (date as Dayjs).clone().toDate();
}
if (moment.isMoment(date)) {
return (date as Moment).clone().toDate();
}
if (date instanceof DateTime) {
return date.toJSDate();
}
if (date instanceof Date) {
return new Date(date.getTime());
}
throw new Error('Cannot properly parse argument passed to cloneCrossUtils');
}
export function copy(text: string) {
return window.navigator.permissions.query({ name: 'clipboard-write' }).then(result => {
if (result.state == 'granted' || result.state == 'prompt') {
return navigator.clipboard.writeText(text);
}
return Promise.reject();
});
}
export function loadScript(src: string, position: Element) {
const script = document.createElement('script');
script.setAttribute('async', '');
script.src = src;
position.appendChild(script);
return script;
}
| Fix crashing using moment utils on datepicker page | [docs] Fix crashing using moment utils on datepicker page
| TypeScript | mit | callemall/material-ui,rscnt/material-ui,mbrookes/material-ui,mui-org/material-ui,mui-org/material-ui,dmtrKovalenko/material-ui-pickers,dmtrKovalenko/material-ui-pickers,oliviertassinari/material-ui,callemall/material-ui,rscnt/material-ui,rscnt/material-ui,callemall/material-ui,oliviertassinari/material-ui,oliviertassinari/material-ui,callemall/material-ui,mbrookes/material-ui,mbrookes/material-ui,mui-org/material-ui | ---
+++
@@ -7,7 +7,7 @@
return (date as Dayjs).clone().toDate();
}
- if (date instanceof moment) {
+ if (moment.isMoment(date)) {
return (date as Moment).clone().toDate();
}
|
6d8bf659ef8b5561355ad69c4833d979530f79a8 | app/src/lib/stores/updates/update-remote-url.ts | app/src/lib/stores/updates/update-remote-url.ts | import { Repository } from '../../../models/repository'
import { IAPIRepository } from '../../api'
import { GitStore } from '../git-store'
export async function updateRemoteUrl(
gitStore: GitStore,
repository: Repository,
apiRepo: IAPIRepository
): Promise<void> {
// I'm not sure when these early exit conditions would be met. But when they are
// we don't have enough information to continue so exit early!
if (!gitStore.currentRemote) {
return
}
if (!repository.gitHubRepository) {
return
}
const remoteUrl = gitStore.currentRemote.url
const updatedRemoteUrl = apiRepo.clone_url
const isProtocolHttps = remoteUrl && remoteUrl.startsWith('https://')
const usingDefaultRemote =
gitStore.defaultRemote &&
gitStore.defaultRemote.url === repository.gitHubRepository.cloneURL
if (isProtocolHttps && usingDefaultRemote && remoteUrl !== updatedRemoteUrl) {
await gitStore.setRemoteURL(gitStore.currentRemote.name, updatedRemoteUrl)
}
}
| import { Repository } from '../../../models/repository'
import { IAPIRepository } from '../../api'
import { GitStore } from '../git-store'
import * as URL from 'url'
export async function updateRemoteUrl(
gitStore: GitStore,
repository: Repository,
apiRepo: IAPIRepository
): Promise<void> {
// I'm not sure when these early exit conditions would be met. But when they are
// we don't have enough information to continue so exit early!
if (!gitStore.currentRemote) {
return
}
if (!repository.gitHubRepository) {
return
}
const remoteUrl = gitStore.currentRemote.url
const updatedRemoteUrl = apiRepo.clone_url
const protocolEquals =
URL.parse(remoteUrl).protocol === URL.parse(updatedRemoteUrl).protocol
const usingDefaultRemote =
gitStore.defaultRemote &&
gitStore.defaultRemote.url === repository.gitHubRepository.cloneURL
if (protocolEquals && usingDefaultRemote && remoteUrl !== updatedRemoteUrl) {
await gitStore.setRemoteURL(gitStore.currentRemote.name, updatedRemoteUrl)
}
}
| Update only if protocol of the current remote url matches that of the new clone url | Update only if protocol of the current remote url matches that of the new clone url
See https://github.com/desktop/desktop/pull/8132/files#r325741434
Co-Authored-By: Markus Olsson <c00736d1ddeb2cd1f4e803cdc39630b5b2784893@users.noreply.github.com>
| TypeScript | mit | j-f1/forked-desktop,say25/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,kactus-io/kactus,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,desktop/desktop,say25/desktop,artivilla/desktop | ---
+++
@@ -1,6 +1,7 @@
import { Repository } from '../../../models/repository'
import { IAPIRepository } from '../../api'
import { GitStore } from '../git-store'
+import * as URL from 'url'
export async function updateRemoteUrl(
gitStore: GitStore,
@@ -18,12 +19,14 @@
const remoteUrl = gitStore.currentRemote.url
const updatedRemoteUrl = apiRepo.clone_url
- const isProtocolHttps = remoteUrl && remoteUrl.startsWith('https://')
+ const protocolEquals =
+ URL.parse(remoteUrl).protocol === URL.parse(updatedRemoteUrl).protocol
+
const usingDefaultRemote =
gitStore.defaultRemote &&
gitStore.defaultRemote.url === repository.gitHubRepository.cloneURL
- if (isProtocolHttps && usingDefaultRemote && remoteUrl !== updatedRemoteUrl) {
+ if (protocolEquals && usingDefaultRemote && remoteUrl !== updatedRemoteUrl) {
await gitStore.setRemoteURL(gitStore.currentRemote.name, updatedRemoteUrl)
}
} |
01bce6ca39b7dc06ae342b8c0772136ff51ef671 | src/schema/partner_show_event.ts | src/schema/partner_show_event.ts | import date from "./fields/date"
import { GraphQLString, GraphQLObjectType } from "graphql"
import { ResolverContext } from "types/graphql"
import { exhibitionPeriod } from "lib/date"
const PartnerShowEventType = new GraphQLObjectType<any, ResolverContext>({
name: "PartnerShowEventType",
fields: {
event_type: {
type: GraphQLString,
resolve: ({ event_type }) => {
return event_type === "Other" ? "Event" : event_type
},
},
description: {
type: GraphQLString,
},
title: {
type: GraphQLString,
},
start_at: date,
end_at: date,
exhibitionPeriod: {
type: GraphQLString,
description: "A formatted description of the start to end dates",
resolve: ({ start_at, end_at }) => exhibitionPeriod(start_at, end_at),
},
},
})
export default PartnerShowEventType
| import dateField, { date, DateSource } from "./fields/date"
import { GraphQLString, GraphQLObjectType, GraphQLFieldConfig } from "graphql"
import { ResolverContext } from "types/graphql"
import { exhibitionPeriod } from "lib/date"
const checkUserAgent = (userAgent): boolean =>
userAgent!.indexOf("Artsy-Mobile/4") > 0 ||
userAgent!.indexOf("Artsy-Mobile/5.0.0") > 0 ||
userAgent!.indexOf("Artsy-Mobile/5.0.1") > 0
const isOlderEmissionVersion = (userAgent): boolean => {
let result = false
if (typeof userAgent === "string") {
result = checkUserAgent(userAgent)
} else if (Array.isArray(userAgent)) {
result = userAgent.some(ua => checkUserAgent(ua))
}
return result
}
const dateFieldForPartnerShowEvent: GraphQLFieldConfig<
DateSource,
ResolverContext
> = {
...dateField,
resolve: (
obj,
{ format, timezone },
{ defaultTimezone, userAgent },
{ fieldName }
) => {
const rawDate = obj[fieldName]
if (userAgent && isOlderEmissionVersion(userAgent)) {
const dateWithoutOffset = rawDate.replace(/[-+]\d\d:\d\d$/g, "")
return dateWithoutOffset
}
const timezoneString = timezone ? timezone : defaultTimezone
return date(rawDate, format, timezoneString)
},
}
const PartnerShowEventType = new GraphQLObjectType<any, ResolverContext>({
name: "PartnerShowEventType",
fields: {
event_type: {
type: GraphQLString,
resolve: ({ event_type }) => {
return event_type === "Other" ? "Event" : event_type
},
},
description: {
type: GraphQLString,
},
title: {
type: GraphQLString,
},
start_at: dateFieldForPartnerShowEvent,
end_at: dateFieldForPartnerShowEvent,
exhibitionPeriod: {
type: GraphQLString,
description: "A formatted description of the start to end dates",
resolve: ({ start_at, end_at }) => exhibitionPeriod(start_at, end_at),
},
},
})
export default PartnerShowEventType
| Add a custom resolver for partner show events' datetimes | Add a custom resolver for partner show events' datetimes
Signed-off-by: Kieran Gillen <d6dff3e61e518dd564d939f356cbccdde8cf92af@gmail.com>
| TypeScript | mit | mzikherman/metaphysics-1,mzikherman/metaphysics-1,artsy/metaphysics,artsy/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1 | ---
+++
@@ -1,7 +1,45 @@
-import date from "./fields/date"
-import { GraphQLString, GraphQLObjectType } from "graphql"
+import dateField, { date, DateSource } from "./fields/date"
+import { GraphQLString, GraphQLObjectType, GraphQLFieldConfig } from "graphql"
import { ResolverContext } from "types/graphql"
import { exhibitionPeriod } from "lib/date"
+
+const checkUserAgent = (userAgent): boolean =>
+ userAgent!.indexOf("Artsy-Mobile/4") > 0 ||
+ userAgent!.indexOf("Artsy-Mobile/5.0.0") > 0 ||
+ userAgent!.indexOf("Artsy-Mobile/5.0.1") > 0
+
+const isOlderEmissionVersion = (userAgent): boolean => {
+ let result = false
+ if (typeof userAgent === "string") {
+ result = checkUserAgent(userAgent)
+ } else if (Array.isArray(userAgent)) {
+ result = userAgent.some(ua => checkUserAgent(ua))
+ }
+ return result
+}
+
+const dateFieldForPartnerShowEvent: GraphQLFieldConfig<
+ DateSource,
+ ResolverContext
+> = {
+ ...dateField,
+ resolve: (
+ obj,
+ { format, timezone },
+ { defaultTimezone, userAgent },
+ { fieldName }
+ ) => {
+ const rawDate = obj[fieldName]
+
+ if (userAgent && isOlderEmissionVersion(userAgent)) {
+ const dateWithoutOffset = rawDate.replace(/[-+]\d\d:\d\d$/g, "")
+ return dateWithoutOffset
+ }
+
+ const timezoneString = timezone ? timezone : defaultTimezone
+ return date(rawDate, format, timezoneString)
+ },
+}
const PartnerShowEventType = new GraphQLObjectType<any, ResolverContext>({
name: "PartnerShowEventType",
@@ -18,8 +56,8 @@
title: {
type: GraphQLString,
},
- start_at: date,
- end_at: date,
+ start_at: dateFieldForPartnerShowEvent,
+ end_at: dateFieldForPartnerShowEvent,
exhibitionPeriod: {
type: GraphQLString,
description: "A formatted description of the start to end dates", |
dd1d7442abb399aca4ce4963f06b6b219b2ae0c3 | server/src/main/typescript/timing/app.routes.ts | server/src/main/typescript/timing/app.routes.ts | import { Routes, RouterModule } from '@angular/router';
import { LandingComponent } from './landing';
import { NoContentComponent } from './no-content';
import { TimingComponent } from './time_entry';
export const ROUTES: Routes = [
{ path: '', component: LandingComponent },
{ path: 'race/:raceId', component: TimingComponent },
{ path: '**', component: NoContentComponent }
];
| import { ModuleWithProviders } from '@angular/core'
import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
import { LandingComponent } from './landing';
import { NoContentComponent } from './no-content';
import { TimingComponent } from './time_entry';
const ROUTES: Routes = [
{ path: '', component: LandingComponent },
{ path: 'race/:raceId', component: TimingComponent },
{ path: '**', component: NoContentComponent }
];
export const appRouting: ModuleWithProviders = RouterModule.forRoot(ROUTES, { preloadingStrategy: PreloadAllModules }); | Remove hash routing option as it defaults to html5 | Remove hash routing option as it defaults to html5
Change-Id: Id66176f4426884cc5aa31c9fe89547eadc33181d
| TypeScript | mit | PloughingAByteField/tiatus,PloughingAByteField/tiatus,PloughingAByteField/tiatus,PloughingAByteField/tiatus,PloughingAByteField/tiatus | ---
+++
@@ -1,10 +1,13 @@
-import { Routes, RouterModule } from '@angular/router';
+import { ModuleWithProviders } from '@angular/core'
+import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
import { LandingComponent } from './landing';
import { NoContentComponent } from './no-content';
import { TimingComponent } from './time_entry';
-export const ROUTES: Routes = [
+const ROUTES: Routes = [
{ path: '', component: LandingComponent },
{ path: 'race/:raceId', component: TimingComponent },
{ path: '**', component: NoContentComponent }
];
+
+export const appRouting: ModuleWithProviders = RouterModule.forRoot(ROUTES, { preloadingStrategy: PreloadAllModules }); |
2e41410d61925a4eeca69bb6b348fb7664b8d585 | app/src/ui/lib/tooltipped-content.tsx | app/src/ui/lib/tooltipped-content.tsx | import * as React from 'react'
import { ITooltipProps, Tooltip } from './tooltip'
import { createObservableRef } from './observable-ref'
interface ITooltippedContentProps
extends Omit<ITooltipProps<HTMLElement>, 'target'> {
readonly tooltip: JSX.Element | string
readonly wrapperElement?: 'span' | 'div'
}
/**
* A less complicated version of the Tooltip component for when it's acceptable
* to add a wrapping element around the content. supports all the options that
* the Tooltip component does without having to worry about refs.
**/
export class TooltippedContent extends React.Component<
ITooltippedContentProps
> {
private wrapperRef = createObservableRef<HTMLElement>()
public render() {
const { tooltip, wrapperElement, children, ...rest } = this.props
return React.createElement(wrapperElement ?? 'span', {
ref: this.wrapperRef,
children: (
<>
<Tooltip target={this.wrapperRef} {...rest}>
{tooltip}
</Tooltip>
{children}
</>
),
})
}
}
| import * as React from 'react'
import { ITooltipProps, Tooltip } from './tooltip'
import { createObservableRef } from './observable-ref'
interface ITooltippedContentProps
extends Omit<ITooltipProps<HTMLElement>, 'target'> {
readonly tooltip: JSX.Element | string | undefined
readonly wrapperElement?: 'span' | 'div'
}
/**
* A less complicated version of the Tooltip component for when it's acceptable
* to add a wrapping element around the content. supports all the options that
* the Tooltip component does without having to worry about refs.
**/
export class TooltippedContent extends React.Component<
ITooltippedContentProps
> {
private wrapperRef = createObservableRef<HTMLElement>()
public render() {
const { tooltip, wrapperElement, children, ...rest } = this.props
return React.createElement(wrapperElement ?? 'span', {
ref: this.wrapperRef,
children: (
<>
{tooltip !== undefined && (
<Tooltip target={this.wrapperRef} {...rest}>
{tooltip}
</Tooltip>
)}
{children}
</>
),
})
}
}
| Support disabling tooltip by setting tooltip prop to undefined | Support disabling tooltip by setting tooltip prop to undefined
| TypeScript | mit | j-f1/forked-desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,artivilla/desktop,artivilla/desktop,desktop/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,j-f1/forked-desktop,desktop/desktop | ---
+++
@@ -4,7 +4,7 @@
interface ITooltippedContentProps
extends Omit<ITooltipProps<HTMLElement>, 'target'> {
- readonly tooltip: JSX.Element | string
+ readonly tooltip: JSX.Element | string | undefined
readonly wrapperElement?: 'span' | 'div'
}
@@ -25,9 +25,11 @@
ref: this.wrapperRef,
children: (
<>
- <Tooltip target={this.wrapperRef} {...rest}>
- {tooltip}
- </Tooltip>
+ {tooltip !== undefined && (
+ <Tooltip target={this.wrapperRef} {...rest}>
+ {tooltip}
+ </Tooltip>
+ )}
{children}
</>
), |
889e0c80229a7f4810d0b1e26a1c40497130bd14 | src/utils/get-is-python-installed.ts | src/utils/get-is-python-installed.ts | import { spawnSync } from 'child_process';
let _isPythonInstalled: string | null | undefined;
export function getIsPythonInstalled() {
if (_isPythonInstalled !== undefined) return _isPythonInstalled;
try {
const options = { windowsHide: true, stdio: null };
const { output } = spawnSync('python', [ '-V' ], options as any);
const version = output.toString().trim().replace(/,/g, '');
if (version && version.includes(' 2.')) {
return _isPythonInstalled = version;
} else {
return _isPythonInstalled = null;
}
} catch (error) {
return _isPythonInstalled = null;
}
}
| import { spawnSync } from 'child_process';
let _isPythonInstalled: string | null | undefined;
export function getIsPythonInstalled() {
if (_isPythonInstalled !== undefined) return _isPythonInstalled;
try {
const options = { windowsHide: true, stdio: null };
const { output } = spawnSync('python', [ '-V' ], options as any);
const version = output.toString().trim().replace(/,/g, '');
if (version && version.includes(' 3.')) {
return _isPythonInstalled = version;
} else {
return _isPythonInstalled = null;
}
} catch (error) {
return _isPythonInstalled = null;
}
}
| Upgrade from Python 2.7.15 --> 3.8.1 | Upgrade from Python 2.7.15 --> 3.8.1 | TypeScript | mit | felixrieseberg/windows-build-tools,felixrieseberg/windows-build-tools | ---
+++
@@ -10,7 +10,7 @@
const { output } = spawnSync('python', [ '-V' ], options as any);
const version = output.toString().trim().replace(/,/g, '');
- if (version && version.includes(' 2.')) {
+ if (version && version.includes(' 3.')) {
return _isPythonInstalled = version;
} else {
return _isPythonInstalled = null; |
5aab82b99476ceb92c8b7006cc1d50d3e5180867 | test/test_files/strict_null_checks/unassignable_argument_type.ts | test/test_files/strict_null_checks/unassignable_argument_type.ts | // Test: Pass null value to function
function doesNotExpectNull(n: number) {}
function passesNullValue() {
const n: number | null = null;
// Fix: doesNotExpectNull(n!);
doesNotExpectNull(n);
}
// Test: Pass null and undefined value to function
function doesNotExpectNullUndefined(n: number) {}
function passesNullVariable() {
const n: number | null = null;
// Fix: doesNotExpectNullUndefined(n!);
doesNotExpectNullUndefined(n);
}
function passesUndefinedVariable() {
const n: number | undefined = undefined;
// Fix: doesNotExpectNullUndefined(n!);
doesNotExpectNullUndefined(n);
}
// Test: Add element to empty list
function addToEmptyList() {
// Fix: const emptyList: any[] = [];
const emptyList = [];
emptyList.push(5);
}
| // Test: Pass null value to function
function doesNotExpectNull(n: number) {}
function passesNullValue() {
const n: number | null = null;
// Fix: doesNotExpectNull(n!);
doesNotExpectNull(n);
}
// Test: Pass null and undefined value to function
function doesNotExpectNullUndefined(n: number) {}
function passesNullVariable() {
const n: number | null = null;
// Fix: doesNotExpectNullUndefined(n!);
doesNotExpectNullUndefined(n);
}
function passesUndefinedVariable() {
const n: number | undefined = undefined;
// Fix: doesNotExpectNullUndefined(n!);
doesNotExpectNullUndefined(n);
}
// Test: Add element to empty list
function addToEmptyList() {
// Fix: const emptyList: any[] = [];
const emptyList = [];
emptyList.push(5);
}
// Test: No overload matches
function noOverloadMatches(n: number | undefined) {
// Fix: new Date(n!);
new Date(n);
}
| Add test case to strictNullChecks test files | Add test case to strictNullChecks test files
| TypeScript | apache-2.0 | googleinterns/typescript-flag-upgrade,googleinterns/typescript-flag-upgrade,googleinterns/typescript-flag-upgrade | ---
+++
@@ -28,3 +28,9 @@
const emptyList = [];
emptyList.push(5);
}
+
+// Test: No overload matches
+function noOverloadMatches(n: number | undefined) {
+ // Fix: new Date(n!);
+ new Date(n);
+} |
3a47a01c40396ce217c0d4825dc5018bd60d51ec | packages/react-scripts/template/src/App.tsx | packages/react-scripts/template/src/App.tsx | import * as React from 'react';
import './App.css';
const logo = require('./logo.svg');
class App extends React.Component<null, null> {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
</div>
);
}
}
export default App;
| import * as React from 'react';
import './App.css';
const logo = require('./logo.svg');
class App extends React.Component<{}, null> {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
</div>
);
}
}
export default App;
| Fix Generic Typings For react@15.5.x | Fix Generic Typings For react@15.5.x
| TypeScript | bsd-3-clause | devex-web-frontend/create-react-app-dx,Place1/create-react-app-typescript,Place1/create-react-app-typescript,devex-web-frontend/create-react-app-dx,Place1/create-react-app-typescript,devex-web-frontend/create-react-app-dx,devex-web-frontend/create-react-app-dx,Place1/create-react-app-typescript | ---
+++
@@ -3,7 +3,7 @@
const logo = require('./logo.svg');
-class App extends React.Component<null, null> {
+class App extends React.Component<{}, null> {
render() {
return (
<div className="App"> |
525f7b6faa71dce18b50e30c612344077270c1ad | lib/src/hooks/useStretchyAnimation.ts | lib/src/hooks/useStretchyAnimation.ts | import {
Animated,
NativeScrollEvent,
NativeSyntheticEvent,
} from 'react-native';
import { useState, useCallback } from 'react';
export type UseStretchyAnimation = (
listener?: (offsetY: number) => void,
) => {
animation: Animated.Value;
onAnimationEvent: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
};
export const useStretchyAnimation: UseStretchyAnimation = (listener) => {
const [animation] = useState(new Animated.Value(1));
const onAnimationEvent = useCallback(
Animated.event<NativeScrollEvent>(
[
{
nativeEvent: {
contentOffset: { y: animation },
},
},
],
{
useNativeDriver: true,
listener: ({ nativeEvent: { contentOffset } }) =>
listener && listener(contentOffset.y),
},
),
[],
);
return { animation, onAnimationEvent };
};
| import {
Animated,
NativeScrollEvent,
NativeSyntheticEvent,
} from 'react-native';
import { useState, useCallback } from 'react';
export type UseStretchyAnimation = (
listener?: (offsetY: number) => void,
) => {
animation: Animated.Value;
onAnimationEvent: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
};
export const useStretchyAnimation: UseStretchyAnimation = (listener) => {
const [animation] = useState(new Animated.Value(1));
const onAnimationEvent = useCallback(
Animated.event<NativeScrollEvent>(
[
{
nativeEvent: {
contentOffset: { y: animation },
},
},
],
{
useNativeDriver: true,
listener: ({ nativeEvent: { contentOffset } }) =>
listener && listener(contentOffset.y),
},
),
[listener],
);
return { animation, onAnimationEvent };
};
| Add listener as an input of onAnimationEvent | Add listener as an input of onAnimationEvent
| TypeScript | mit | hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy | ---
+++
@@ -30,7 +30,7 @@
listener && listener(contentOffset.y),
},
),
- [],
+ [listener],
);
return { animation, onAnimationEvent }; |
b55cb6197ad81250d9f2dded25b74da2a2d2c587 | app/src/component/PagesMenu.tsx | app/src/component/PagesMenu.tsx | import * as React from "react";
import { connect } from "react-redux";
import { actionCreators, Page, pages } from "../redux/pages";
import PageButton from "./PageButton";
import "./style/PagesMenu.css";
interface IProps {
currentPage: Page;
setCurrentPage: (page: Page) => void;
}
interface IState {
showMenu: boolean;
}
class PagesMenu extends React.Component<IProps, IState> {
public state: IState = { showMenu: false };
public render() {
const { currentPage, setCurrentPage } = this.props;
const { showMenu } = this.state;
return (
<div className="PagesMenu-container">
<PageButton
className="PagesMenu-current-button"
page={currentPage}
onClick={() => this.setState({ showMenu: !showMenu })}
/>
<div
className={"PagesMenu-background" + (showMenu ? "" : "-hidden")}
onClick={() => this.setState({ showMenu: false })}
/>
<div className={"PagesMenu-box" + (showMenu ? "" : "-hidden")}>
{pages.map((page) =>
<PageButton
key={page}
className={page === currentPage && "PagesMenu-disabled-button"}
page={page}
onClick={() => {
setCurrentPage(page);
this.setState({ showMenu: false });
}}
/>)}
</div>
</div>
);
}
}
export default connect(({ pages }) => pages, actionCreators)(PagesMenu);
| import * as React from "react";
import { connect } from "react-redux";
import { actionCreators, Page, pages } from "../redux/pages";
import PageButton from "./PageButton";
import "./style/PagesMenu.css";
interface IProps {
currentPage: Page;
closed?: boolean;
setCurrentPage: (page: Page) => void;
}
interface IState {
opened: boolean;
}
class PagesMenu extends React.Component<IProps, IState> {
public state: IState = { opened: false };
public render() {
const { currentPage, closed, setCurrentPage } = this.props;
const opened = !closed && this.state.opened;
return (
<div className="PagesMenu-container">
<PageButton
className="PagesMenu-current-button"
page={currentPage}
onClick={() => this.setState({ opened: !this.state.opened })}
/>
<div
className={"PagesMenu-background" + (opened ? "" : "-hidden")}
onClick={() => this.setState({ opened: false })}
/>
<div className={"PagesMenu-box" + (opened ? "" : "-hidden")}>
{pages.map((page) =>
<PageButton
key={page}
className={page === currentPage && "PagesMenu-disabled-button"}
page={page}
onClick={() => {
setCurrentPage(page);
this.setState({ opened: false });
}}
/>)}
</div>
</div>
);
}
}
export default connect(({ pages }) => pages, actionCreators)(PagesMenu);
| Add closed option to pages menu | Add closed option to pages menu
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -7,32 +7,33 @@
interface IProps {
currentPage: Page;
+ closed?: boolean;
setCurrentPage: (page: Page) => void;
}
interface IState {
- showMenu: boolean;
+ opened: boolean;
}
class PagesMenu extends React.Component<IProps, IState> {
- public state: IState = { showMenu: false };
+ public state: IState = { opened: false };
public render() {
- const { currentPage, setCurrentPage } = this.props;
- const { showMenu } = this.state;
+ const { currentPage, closed, setCurrentPage } = this.props;
+ const opened = !closed && this.state.opened;
return (
<div className="PagesMenu-container">
<PageButton
className="PagesMenu-current-button"
page={currentPage}
- onClick={() => this.setState({ showMenu: !showMenu })}
+ onClick={() => this.setState({ opened: !this.state.opened })}
/>
<div
- className={"PagesMenu-background" + (showMenu ? "" : "-hidden")}
- onClick={() => this.setState({ showMenu: false })}
+ className={"PagesMenu-background" + (opened ? "" : "-hidden")}
+ onClick={() => this.setState({ opened: false })}
/>
- <div className={"PagesMenu-box" + (showMenu ? "" : "-hidden")}>
+ <div className={"PagesMenu-box" + (opened ? "" : "-hidden")}>
{pages.map((page) =>
<PageButton
key={page}
@@ -40,7 +41,7 @@
page={page}
onClick={() => {
setCurrentPage(page);
- this.setState({ showMenu: false });
+ this.setState({ opened: false });
}}
/>)}
</div> |
18cf1f85354d2e8069657b76628b4108da0a5787 | web/components/ProductChip/index.tsx | web/components/ProductChip/index.tsx | import { Avatar, Chip } from "@material-ui/core";
import { useTranslation } from "../../hooks/useTranslation";
type Product = {
name: string;
icon: string;
url: string;
};
const products: { [key: string]: Product } = {
"speech-to-text": {
name: "Cloud Speech-to-Text",
icon: "/images/speech-to-text-512-color.svg",
url: "https://cloud.google.com/speech-to-text",
},
"natural-language-api": {
name: "Cloud Natural Language API",
icon: "/images/cloud-natural-language-api-512-color.svg",
url: "https://cloud.google.com/natural-language",
},
};
type Props = {
productId: string;
};
const ProductChip: React.FC<Props> = ({ productId }) => {
const { locale } = useTranslation();
const product = products[productId];
const onClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
e.stopPropagation();
window.open(`${product.url}?hl=${locale}`, "_blank");
};
return (
<Chip
label={product.name}
variant="outlined"
avatar={<Avatar alt={product.name} src={product.icon} />}
onClick={onClick}
/>
);
};
export default ProductChip;
| import {
Avatar,
Chip,
createStyles,
makeStyles,
Theme,
} from "@material-ui/core";
import { useTranslation } from "../../hooks/useTranslation";
type Product = {
name: string;
icon: string;
url: string;
};
const products: { [key: string]: Product } = {
"speech-to-text": {
name: "Cloud Speech-to-Text",
icon: "/images/speech-to-text-512-color.svg",
url: "https://cloud.google.com/speech-to-text",
},
"natural-language-api": {
name: "Cloud Natural Language API",
icon: "/images/cloud-natural-language-api-512-color.svg",
url: "https://cloud.google.com/natural-language",
},
};
type Props = {
productId: string;
};
const useStyles = makeStyles((theme: Theme) =>
createStyles({
chip: {
backgroundColor: theme.palette.background.paper,
},
})
);
const ProductChip: React.FC<Props> = ({ productId }) => {
const classes = useStyles();
const { locale } = useTranslation();
const product = products[productId];
const onClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
e.stopPropagation();
window.open(`${product.url}?hl=${locale}`, "_blank");
};
return (
<Chip
label={product.name}
variant="outlined"
avatar={<Avatar alt={product.name} src={product.icon} />}
onClick={onClick}
className={classes.chip}
/>
);
};
export default ProductChip;
| Fix background color for ProductChip | Fix background color for ProductChip
| TypeScript | apache-2.0 | GoogleCloudPlatform/appengine-cloud-demo-portal,GoogleCloudPlatform/appengine-cloud-demo-portal,GoogleCloudPlatform/appengine-cloud-demo-portal,GoogleCloudPlatform/appengine-cloud-demo-portal | ---
+++
@@ -1,4 +1,10 @@
-import { Avatar, Chip } from "@material-ui/core";
+import {
+ Avatar,
+ Chip,
+ createStyles,
+ makeStyles,
+ Theme,
+} from "@material-ui/core";
import { useTranslation } from "../../hooks/useTranslation";
type Product = {
@@ -24,7 +30,16 @@
productId: string;
};
+const useStyles = makeStyles((theme: Theme) =>
+ createStyles({
+ chip: {
+ backgroundColor: theme.palette.background.paper,
+ },
+ })
+);
+
const ProductChip: React.FC<Props> = ({ productId }) => {
+ const classes = useStyles();
const { locale } = useTranslation();
const product = products[productId];
@@ -39,6 +54,7 @@
variant="outlined"
avatar={<Avatar alt={product.name} src={product.icon} />}
onClick={onClick}
+ className={classes.chip}
/>
);
}; |
079e56f1e109a58f89d47edd2a386fb9450dd9ee | src/index.ts | src/index.ts | declare module '@webcomponents/custom-elements';
function init() {
require('./init-app.tsx');
}
if (!('customElements' in self)) {
import(
/* webpackChunkName: "wc-polyfill" */
'@webcomponents/custom-elements').then(init);
} else {
init();
}
if (typeof PRERENDER === 'undefined') {
window.ga = window.ga || ((...args) => (ga.q = ga.q || []).push(args));
ga('create', 'UA-128752250-1', 'auto');
ga('set', 'transport', 'beacon');
ga('send', 'pageview');
// Load the GA script
const s = document.createElement('script');
s.src = 'https://www.google-analytics.com/analytics.js';
document.head!.appendChild(s);
}
| declare module '@webcomponents/custom-elements';
function init() {
require('./init-app.tsx');
}
if (!('customElements' in self)) {
import(
/* webpackChunkName: "wc-polyfill" */
'@webcomponents/custom-elements').then(init);
} else {
init();
}
if (typeof PRERENDER === 'undefined') {
// Determine the current display mode.
let displayMode = 'browser';
const mqStandAlone = '(display-mode: standalone)';
if (navigator.standalone || window.matchMedia(mqStandAlone).matches) {
displayMode = 'standalone';
}
// Setup analytics
window.ga = window.ga || ((...args) => (ga.q = ga.q || []).push(args));
ga('create', 'UA-128752250-1', 'auto');
ga('set', 'transport', 'beacon');
ga('set', 'dimensionX', displayMode);
ga('send', 'pageview');
// Load the GA script
const s = document.createElement('script');
s.src = 'https://www.google-analytics.com/analytics.js';
document.head!.appendChild(s);
}
| Use a dimension to note how the user opened squoosh | Use a dimension to note how the user opened squoosh
| TypeScript | apache-2.0 | GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh | ---
+++
@@ -13,11 +13,19 @@
}
if (typeof PRERENDER === 'undefined') {
+ // Determine the current display mode.
+ let displayMode = 'browser';
+ const mqStandAlone = '(display-mode: standalone)';
+ if (navigator.standalone || window.matchMedia(mqStandAlone).matches) {
+ displayMode = 'standalone';
+ }
+ // Setup analytics
window.ga = window.ga || ((...args) => (ga.q = ga.q || []).push(args));
ga('create', 'UA-128752250-1', 'auto');
ga('set', 'transport', 'beacon');
+ ga('set', 'dimensionX', displayMode);
ga('send', 'pageview');
- // Load the GA script
+ // Load the GA script
const s = document.createElement('script');
s.src = 'https://www.google-analytics.com/analytics.js';
document.head!.appendChild(s); |
0cb5f0b0e633e452cae1ec1eaf84796349e77acd | src/app/exporter/exporter.component.ts | src/app/exporter/exporter.component.ts | import { Component } from '@angular/core';
import { ChartFileExporterService } from '../chart-file/exporter/chart-file-exporter.service';
@Component({
selector: 'app-exporter',
templateUrl: './exporter.component.html',
styleUrls: ['./exporter.component.css'],
})
export class ExporterComponent {
constructor(public chartFileExporter: ChartFileExporterService) {
}
exportChart() {
const chartString = this.chartFileExporter.export();
const filename = 'notes.chart';
const chart = new File([chartString], filename, { type: 'text/plain' });
const url = window.URL.createObjectURL(chart);
const link = document.createElement('a');
link.setAttribute('style', 'display: none');
link.setAttribute('href', url);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
}
}
| import { Component } from '@angular/core';
import { ChartFileExporterService } from '../chart-file/exporter/chart-file-exporter.service';
@Component({
selector: 'app-exporter',
templateUrl: './exporter.component.html',
styleUrls: ['./exporter.component.css'],
})
export class ExporterComponent {
constructor(public chartFileExporter: ChartFileExporterService) {
}
exportChart() {
const chartString = this.chartFileExporter.export();
const datetime = new Date()
.toISOString()
.replace(/:/g, '-')
.split('.')[0];
const filename = `notes-${datetime}.chart`;
const chart = new File([chartString], filename, { type: 'text/plain' });
const url = window.URL.createObjectURL(chart);
const link = document.createElement('a');
link.setAttribute('style', 'display: none');
link.setAttribute('href', url);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
}
}
| Add timestamps to output files | feat: Add timestamps to output files
| TypeScript | mit | nb48/chart-hero,nb48/chart-hero,nb48/chart-hero | ---
+++
@@ -14,7 +14,11 @@
exportChart() {
const chartString = this.chartFileExporter.export();
- const filename = 'notes.chart';
+ const datetime = new Date()
+ .toISOString()
+ .replace(/:/g, '-')
+ .split('.')[0];
+ const filename = `notes-${datetime}.chart`;
const chart = new File([chartString], filename, { type: 'text/plain' });
const url = window.URL.createObjectURL(chart);
const link = document.createElement('a'); |
86cf5f813ab1513d546b3dac6e04211a1bc5fb47 | src/app/components/about.component.spec.ts | src/app/components/about.component.spec.ts | import { TestBed, async } from '@angular/core/testing';
import { AboutComponent } from './about.component';
describe('AboutComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AboutComponent
],
}).compileComponents();
}));
it('should create about component', async(() => {
const fixture = TestBed.createComponent(AboutComponent);
const about = fixture.debugElement.componentInstance;
expect(about).toBeTruthy();
})); | import { TestBed, async } from '@angular/core/testing';
import { AboutComponent } from './about.component';
import { FooterComponent } from './footer.component';
describe('AboutComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AboutComponent,
FooterComponent
],
}).compileComponents();
}));
it('should create about component', async(() => {
const fixture = TestBed.createComponent(AboutComponent);
const about = fixture.debugElement.componentInstance;
expect(about).toBeTruthy();
})); | Include footer component in about component unit test | Include footer component in about component unit test
| TypeScript | mit | family-guy/mathdruck-ng1,family-guy/mathdruck-ng1,family-guy/mathdruck-ng1 | ---
+++
@@ -1,12 +1,14 @@
import { TestBed, async } from '@angular/core/testing';
import { AboutComponent } from './about.component';
+import { FooterComponent } from './footer.component';
describe('AboutComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
- AboutComponent
+ AboutComponent,
+ FooterComponent
],
}).compileComponents();
})); |
ea4b0ea54f2669829c5cddad5131616039dafd93 | engine/core/native-modules/avg-native-path.ts | engine/core/native-modules/avg-native-path.ts | import { PlatformService } from "../platform";
// const path = require("path");
import * as path from "path";
export class AVGNativePath {
public static join(...paths: string[]): string {
// if (PlatformService.isDesktop()) {
// return path.join(paths);
// } else {
var parts = [];
for (var i = 0, l = paths.length; i < l; i++) {
parts = parts.concat(paths[i].split("/"));
}
const newParts = [];
for (i = 0, l = parts.length; i < l; i++) {
const part = parts[i];
if (!part) continue;
if (part === "..") {
newParts.pop();
} else {
newParts.push(part);
}
}
if (parts[0] === "") {
newParts.unshift("");
}
return newParts.join("/") || (newParts.length ? "/" : ".");
}
// }
}
| import { PlatformService } from "../platform";
// const path = require("path");
import * as path from "path";
export class AVGNativePath {
public static join(...paths: string[]): string {
// if (PlatformService.isDesktop()) {
// return path.join(paths);
// } else {
var parts = [];
for (var i = 0, l = paths.length; i < l; i++) {
if (!paths[i]) {
continue;
}
parts = parts.concat(paths[i].split("/"));
}
const newParts = [];
for (i = 0, l = parts.length; i < l; i++) {
const part = parts[i];
if (!part) continue;
if (part === "..") {
newParts.pop();
} else {
newParts.push(part);
}
}
if (parts[0] === "") {
newParts.unshift("");
}
return newParts.join("/") || (newParts.length ? "/" : ".");
}
// }
}
| Fix bug when path is empty | Fix bug when path is empty
| TypeScript | mit | AngryPowman/avg.engine,AngryPowman/avg.engine | ---
+++
@@ -7,27 +7,30 @@
// if (PlatformService.isDesktop()) {
// return path.join(paths);
// } else {
- var parts = [];
- for (var i = 0, l = paths.length; i < l; i++) {
- parts = parts.concat(paths[i].split("/"));
+ var parts = [];
+ for (var i = 0, l = paths.length; i < l; i++) {
+ if (!paths[i]) {
+ continue;
}
+ parts = parts.concat(paths[i].split("/"));
+ }
- const newParts = [];
- for (i = 0, l = parts.length; i < l; i++) {
- const part = parts[i];
- if (!part) continue;
- if (part === "..") {
- newParts.pop();
- } else {
- newParts.push(part);
- }
+ const newParts = [];
+ for (i = 0, l = parts.length; i < l; i++) {
+ const part = parts[i];
+ if (!part) continue;
+ if (part === "..") {
+ newParts.pop();
+ } else {
+ newParts.push(part);
}
+ }
- if (parts[0] === "") {
- newParts.unshift("");
- }
+ if (parts[0] === "") {
+ newParts.unshift("");
+ }
- return newParts.join("/") || (newParts.length ? "/" : ".");
- }
+ return newParts.join("/") || (newParts.length ? "/" : ".");
+ }
// }
} |
45f229ef7c607376b307661d0fc1f319f6bfe33a | src/modules/raider/raids-utils.ts | src/modules/raider/raids-utils.ts | import * as moment from 'moment';
import { Raid } from './raids';
export const formatRaidToDisplay = (raid: Raid): string => (
`\n\`\`\`css
[${moment(raid.date).format('DD MMM, HH:mm')}] ${raid.name} (ID ${raid.id})\norganizer: ${raid.organizer};
Participants: ${(raid.players.length > 0) ? raid.players.map(p => p.name).join(',') : '-'}
Waitings: ${(raid.waitings.length > 0) ? raid.waitings.map(p => p.name).join(',') : '-'}
Absents: ${(raid.absents.length > 0) ? raid.absents.map(p => p.name).join(',') : '-'}
\`\`\``
);
export const generateHelp = (): Promise<string> => new Promise( resolve => resolve(
`\n\`\`\`css
Create an event:
add <event_name> <event_date> <event_description>
- event_name allows spaces if it is between quotes
- event date has to be <YYYY-MM-DDTHH:mm> format
- event description can be anything
-> Returns event_id
Remove an event:
remove <event_id>
List events:
list
Join an event:
join <event_id>
Decline an event:
decline <event_id>
Accept a participant for an event:
accept <event_id> <participant_name>
\`\`\``
));
| import * as moment from 'moment';
import { Raid } from './raids';
export const formatRaidToDisplay = (raid: Raid): string => (
`\n\`\`\`css
[${moment(raid.date).format('DD MMM, HH:mm')}] ${raid.name} (ID ${raid.id})
Organizer: ${raid.organizer};
Description: ${raid.description};
Participants: ${(raid.players.length > 0) ? raid.players.map(p => p.name).join(', ') : '-'}
Waitings: ${(raid.waitings.length > 0) ? raid.waitings.map(p => p.name).join(',') : '-'}
Absents: ${(raid.absents.length > 0) ? raid.absents.map(p => p.name).join(',') : '-'}
\`\`\``
);
export const generateHelp = (): Promise<string> => new Promise( resolve => resolve(
`\n\`\`\`css
Create an event:
add <event_name> <event_date> <event_description>
- event_name allows spaces if it is between quotes
- event date has to be <YYYY-MM-DDTHH:mm> format
- event description can be anything
-> Returns event_id
Remove an event:
remove <event_id>
List events:
list
Join an event:
join <event_id>
Decline an event:
decline <event_id>
Accept a participant for an event:
accept <event_id> <participant_name>
\`\`\``
));
| Add description field in raid display | Add description field in raid display
| TypeScript | mit | jchakra/discord-raider | ---
+++
@@ -4,9 +4,11 @@
export const formatRaidToDisplay = (raid: Raid): string => (
`\n\`\`\`css
-[${moment(raid.date).format('DD MMM, HH:mm')}] ${raid.name} (ID ${raid.id})\norganizer: ${raid.organizer};
+[${moment(raid.date).format('DD MMM, HH:mm')}] ${raid.name} (ID ${raid.id})
+Organizer: ${raid.organizer};
+Description: ${raid.description};
-Participants: ${(raid.players.length > 0) ? raid.players.map(p => p.name).join(',') : '-'}
+Participants: ${(raid.players.length > 0) ? raid.players.map(p => p.name).join(', ') : '-'}
Waitings: ${(raid.waitings.length > 0) ? raid.waitings.map(p => p.name).join(',') : '-'}
Absents: ${(raid.absents.length > 0) ? raid.absents.map(p => p.name).join(',') : '-'}
\`\`\`` |
3b9694412c3d065ad4d7e47b8ab9ac315bfac94c | src/iframe/index.ts | src/iframe/index.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Widget
} from 'phosphor/lib/ui/widget';
/**
* The class name added to an IFrame widget.
*/
const IFRAME_CLASS = 'jp-IFrame';
/**
* A phosphor widget which wraps an IFrame.
*/
export
class IFrame extends Widget {
/**
* Create a new iframe widget.
*/
constructor() {
super({ node: Private.createNode() });
this.addClass(IFRAME_CLASS);
}
/**
* Load a URL into the iframe.
*
* @param url - The URL to load into the iframe widget.
*/
loadURL(url: string): void {
this.node.querySelector('iframe').setAttribute('src', url);
}
}
/**
* A namespace for private data.
*/
namespace Private {
/**
* Create the main content node of an iframe widget.
*/
export
function createNode(): HTMLElement {
let node = document.createElement('div');
let iframe = document.createElement('iframe');
iframe.style.height = '100%';
iframe.style.width = '100%';
node.appendChild(iframe);
return node;
}
}
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Widget
} from 'phosphor/lib/ui/widget';
/**
* The class name added to an IFrame widget.
*/
const IFRAME_CLASS = 'jp-IFrame';
/**
* A phosphor widget which wraps an IFrame.
*/
export
class IFrame extends Widget {
/**
* Create a new IFrame widget.
*/
constructor() {
super({ node: Private.createNode() });
this.addClass(IFRAME_CLASS);
}
/**
* The IFrame's URL.
*/
get url(): string {
return this.node.querySelector('iframe').getAttribute('src');
}
set url(url: string) {
this.node.querySelector('iframe').setAttribute('src', url);
}
}
/**
* A namespace for private data.
*/
namespace Private {
/**
* Create the main content node of an iframe widget.
*/
export
function createNode(): HTMLElement {
let node = document.createElement('div');
let iframe = document.createElement('iframe');
iframe.style.height = '100%';
iframe.style.width = '100%';
node.appendChild(iframe);
return node;
}
}
| Update IFrame interface to use accessors for url. | Update IFrame interface to use accessors for url.
| TypeScript | bsd-3-clause | jupyter/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab | ---
+++
@@ -18,7 +18,7 @@
export
class IFrame extends Widget {
/**
- * Create a new iframe widget.
+ * Create a new IFrame widget.
*/
constructor() {
super({ node: Private.createNode() });
@@ -26,11 +26,12 @@
}
/**
- * Load a URL into the iframe.
- *
- * @param url - The URL to load into the iframe widget.
+ * The IFrame's URL.
*/
- loadURL(url: string): void {
+ get url(): string {
+ return this.node.querySelector('iframe').getAttribute('src');
+ }
+ set url(url: string) {
this.node.querySelector('iframe').setAttribute('src', url);
}
} |
0c08b40043ac65458973bb10382ee31809bbf049 | packages/core/src/customisations/shorthand.ts | packages/core/src/customisations/shorthand.ts | import { IconifyIconCustomisations } from '../customisations';
const separator = /[\s,]+/;
/**
* Additional shorthand customisations
*/
export interface ShorthandIconCustomisations {
// Sets both hFlip and vFlip
flip?: string;
// Sets hAlign, vAlign and slice
align?: string;
}
/**
* Apply "flip" string to icon customisations
*/
export function flipFromString(
custom: IconifyIconCustomisations,
flip: string
): void {
flip.split(separator).forEach(str => {
const value = str.trim();
switch (value) {
case 'horizontal':
custom.hFlip = true;
break;
case 'vertical':
custom.vFlip = true;
break;
}
});
}
/**
* Apply "align" string to icon customisations
*/
export function alignmentFromString(
custom: IconifyIconCustomisations,
align: string
): void {
align.split(separator).forEach(str => {
const value = str.trim();
switch (value) {
case 'left':
case 'center':
case 'right':
custom.hAlign = value;
break;
case 'top':
case 'middle':
case 'bottom':
custom.vAlign = value;
break;
case 'slice':
custom.slice = true;
break;
case 'meet':
custom.slice = false;
}
});
}
| import { IconifyIconCustomisations } from '../customisations';
const separator = /[\s,]+/;
/**
* Additional shorthand customisations
*/
export interface ShorthandIconCustomisations {
// Sets both hFlip and vFlip
flip?: string;
// Sets hAlign, vAlign and slice
align?: string;
}
/**
* Apply "flip" string to icon customisations
*/
export function flipFromString(
custom: IconifyIconCustomisations,
flip: string
): void {
flip.split(separator).forEach((str) => {
const value = str.trim();
switch (value) {
case 'horizontal':
custom.hFlip = true;
break;
case 'vertical':
custom.vFlip = true;
break;
}
});
}
/**
* Apply "align" string to icon customisations
*/
export function alignmentFromString(
custom: IconifyIconCustomisations,
align: string
): void {
align.split(separator).forEach((str) => {
const value = str.trim();
switch (value) {
case 'left':
case 'center':
case 'right':
custom.hAlign = value;
break;
case 'top':
case 'middle':
case 'bottom':
custom.vAlign = value;
break;
case 'slice':
case 'crop':
custom.slice = true;
break;
case 'meet':
custom.slice = false;
}
});
}
| Add 'crop' to alignment keywords for backwards compatibility with Iconify 1 | Add 'crop' to alignment keywords for backwards compatibility with Iconify 1
| TypeScript | mit | simplesvg/simple-svg,simplesvg/simple-svg,simplesvg/simple-svg | ---
+++
@@ -20,7 +20,7 @@
custom: IconifyIconCustomisations,
flip: string
): void {
- flip.split(separator).forEach(str => {
+ flip.split(separator).forEach((str) => {
const value = str.trim();
switch (value) {
case 'horizontal':
@@ -41,7 +41,7 @@
custom: IconifyIconCustomisations,
align: string
): void {
- align.split(separator).forEach(str => {
+ align.split(separator).forEach((str) => {
const value = str.trim();
switch (value) {
case 'left':
@@ -57,6 +57,7 @@
break;
case 'slice':
+ case 'crop':
custom.slice = true;
break;
|
6dabfb452edf0015222b8d6a3f7712d36fb20a04 | src/pages/admin/student/list/components/spec/studentRow.spec.tsx | src/pages/admin/student/list/components/spec/studentRow.spec.tsx | import { expect } from 'chai';
import { shallow } from 'enzyme';
import * as React from 'react';
import { StudentSummary } from '../../../../../../model/studentSummary'
import { StudentRowComponent } from '../studentRow'
describe('StudentRowComponent', () => {
it('should be defined', () => {
// Arrange
const student = new StudentSummary();
student.id = 1;
student.fullname = 'john';
student.email = "mail@mail.com";
// Act
const studentRowComponent = shallow(
<StudentRowComponent student={student}/>
)
// Assert
expect(studentRowComponent).not.to.be.undefined;
});
it('should render the student name', () => {
// Arrange
const student = new StudentSummary();
student.id = 1;
student.fullname = 'john';
student.email = "mail@mail.com";
// Act
const studentRowComponent = shallow(
<StudentRowComponent student={student}/>
)
// Assert
const expectedDomTree = `
<tr>
<td>
<span>
john
</span>
</td>
<td>
<span>
mail@mail.com
</span>
</td>
</tr>
`;
const plainDomTree = expectedDomTree.replace(/(?:\r\n|\r|\n|\s)/g, '')
expect(studentRowComponent.html()).to.be.equal(plainDomTree);
})
});
| import { expect } from 'chai';
import { shallow } from 'enzyme';
import * as React from 'react';
import { StudentSummary } from '../../../../../../model/studentSummary';
import { StudentRowComponent } from '../studentRow';
import {multilineTrim} from '../../../../../../common/parse/multilineTrim';
describe('StudentRowComponent', () => {
it('should be defined', () => {
// Arrange
const student = new StudentSummary();
student.id = 1;
student.fullname = 'john';
student.email = "mail@mail.com";
// Act
const studentRowComponent = shallow(
<StudentRowComponent student={student}/>
)
// Assert
expect(studentRowComponent).not.to.be.undefined;
});
it('should render the student name', () => {
// Arrange
const student = new StudentSummary();
student.id = 1;
student.fullname = 'john';
student.email = "mail@mail.com";
// Act
const studentRowComponent = shallow(
<StudentRowComponent student={student}/>
)
// Assert
const expectedDomTree = `
<tr>
<td>
<span>
john
</span>
</td>
<td>
<span>
mail@mail.com
</span>
</td>
</tr>
`;
expect(studentRowComponent.html()).to.be.equal(multilineTrim(expectedDomTree));
})
});
| Change to call multiline function in common module | Change to call multiline function in common module
| TypeScript | mit | Lemoncode/LeanMood,MasterLemon2016/LeanMood,Lemoncode/LeanMood,MasterLemon2016/LeanMood,MasterLemon2016/LeanMood,Lemoncode/LeanMood | ---
+++
@@ -1,8 +1,9 @@
import { expect } from 'chai';
import { shallow } from 'enzyme';
import * as React from 'react';
-import { StudentSummary } from '../../../../../../model/studentSummary'
-import { StudentRowComponent } from '../studentRow'
+import { StudentSummary } from '../../../../../../model/studentSummary';
+import { StudentRowComponent } from '../studentRow';
+import {multilineTrim} from '../../../../../../common/parse/multilineTrim';
describe('StudentRowComponent', () => {
@@ -51,9 +52,7 @@
</tr>
`;
- const plainDomTree = expectedDomTree.replace(/(?:\r\n|\r|\n|\s)/g, '')
-
- expect(studentRowComponent.html()).to.be.equal(plainDomTree);
+ expect(studentRowComponent.html()).to.be.equal(multilineTrim(expectedDomTree));
})
|
b18f98d4bb193d1db2b4e0d228fccd92bf9c77f9 | packages/node-sass-once-importer/src/index.ts | packages/node-sass-once-importer/src/index.ts | import * as path from 'path';
import {
buildIncludePaths,
resolveUrl,
sassGlobPattern,
} from 'node-sass-magic-importer/dist/toolbox';
export default function onceImporter() {
const contextTemplate = {
store: new Set(),
};
return function importer(url: string, prev: string) {
const nodeSassOptions = this.options;
// Create a context for the current importer run.
// An importer run is different from an importer instance,
// one importer instance can spawn infinite importer runs.
if (!this.nodeSassOnceImporterContext) {
this.nodeSassOnceImporterContext = Object.assign({}, contextTemplate);
}
// Each importer run has it's own new store, otherwise
// files already imported in a previous importer run
// would be detected as multiple imports of the same file.
const store = this.nodeSassOnceImporterContext.store;
const includePaths = buildIncludePaths(
nodeSassOptions.includePaths,
prev,
);
const resolvedUrl = resolveUrl(
url,
includePaths,
);
if (store.has(resolvedUrl)) {
return {
file: ``,
contents: ``,
};
}
store.add(resolvedUrl);
return null;
};
}
| import * as path from 'path';
import {
buildIncludePaths,
resolveUrl,
sassGlobPattern,
} from 'node-sass-magic-importer/dist/toolbox';
const EMPTY_IMPORT = {
file: ``,
contents: ``,
};
export default function onceImporter() {
const contextTemplate = {
store: new Set(),
};
return function importer(url: string, prev: string) {
const nodeSassOptions = this.options;
// Create a context for the current importer run.
// An importer run is different from an importer instance,
// one importer instance can spawn infinite importer runs.
if (!this.nodeSassOnceImporterContext) {
this.nodeSassOnceImporterContext = Object.assign({}, contextTemplate);
}
// Each importer run has it's own new store, otherwise
// files already imported in a previous importer run
// would be detected as multiple imports of the same file.
const store = this.nodeSassOnceImporterContext.store;
const includePaths = buildIncludePaths(
nodeSassOptions.includePaths,
prev,
);
const resolvedUrl = resolveUrl(
url,
includePaths,
);
if (store.has(resolvedUrl)) {
return EMPTY_IMPORT;
}
store.add(resolvedUrl);
return null;
};
}
| Use constant for signaling empty import in once importer | Use constant for signaling empty import in once importer
| TypeScript | mit | maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer | ---
+++
@@ -5,6 +5,11 @@
resolveUrl,
sassGlobPattern,
} from 'node-sass-magic-importer/dist/toolbox';
+
+const EMPTY_IMPORT = {
+ file: ``,
+ contents: ``,
+};
export default function onceImporter() {
const contextTemplate = {
@@ -34,10 +39,7 @@
);
if (store.has(resolvedUrl)) {
- return {
- file: ``,
- contents: ``,
- };
+ return EMPTY_IMPORT;
}
store.add(resolvedUrl); |
ac0a40e2e35b6b347db931b7b17389f06c2b55c9 | source/view/cossapcamerapositioner.ts | source/view/cossapcamerapositioner.ts | declare namespace Explorer3d {
export class CameraPositioner {
onCreate(z: number, radius: number, center: { x, y, z });
onResize(z: number, radius: number, center: { x, y, z });
onExtend(z: number, radius: number, center: { x, y, z });
lookAt(z: number, radius: number, center: { x, y, z });
position(z: number, radius: number, center: { x, y, z });
up(z: number, radius: number, center: { x, y, z });
near(z: number, radius: number, center: { x, y, z });
far(z: number, radius: number, center: { x, y, z });
}
};
export class CossapCameraPositioner extends Explorer3d.CameraPositioner {
constructor() {
super();
}
position(z: number, radius: number, center: { x, y, z }) {
return {
x: center.x,
y: center.y - 0.5 * radius,
z: center.z + 2 * radius
};
}
up(z: number, radius: number, center: { x, y, z }) {
return {
x: 0,
y: 0,
z: 1
};
}
} | declare namespace Explorer3d {
export class CameraPositioner {
onCreate(z: number, radius: number, center: { x, y, z });
onResize(z: number, radius: number, center: { x, y, z });
onExtend(z: number, radius: number, center: { x, y, z });
lookAt(z: number, radius: number, center: { x, y, z });
position(z: number, radius: number, center: { x, y, z });
up(z: number, radius: number, center: { x, y, z });
near(z: number, radius: number, center: { x, y, z });
far(z: number, radius: number, center: { x, y, z });
}
};
export class CossapCameraPositioner extends Explorer3d.CameraPositioner {
constructor() {
super();
}
position(z: number, radius: number, center: { x, y, z }) {
return {
x: center.x,
y: center.y - 2 * radius,
z: center.z + 2 * radius
};
}
up(z: number, radius: number, center: { x, y, z }) {
return {
x: 0,
y: 0,
z: 1
};
}
} | Update the camera on start to be less looking down | Update the camera on start to be less looking down
| TypeScript | apache-2.0 | Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d | ---
+++
@@ -19,7 +19,7 @@
position(z: number, radius: number, center: { x, y, z }) {
return {
x: center.x,
- y: center.y - 0.5 * radius,
+ y: center.y - 2 * radius,
z: center.z + 2 * radius
};
} |
6c1d1e600b0e7557aed1a574abec8ad4e2b66f9f | bin/src/run/timings.ts | bin/src/run/timings.ts | import tc from 'turbocolor';
import { SerializedTimings } from '../../../src/rollup/types';
export function printTimings(timings: SerializedTimings) {
Object.keys(timings).forEach(label => {
let color = tc;
if (label[0] === '#') {
color = color.bold;
if (label[1] !== '#') {
color = color.underline;
}
}
console.info(color(`${label}: ${timings[label].toFixed(0)}ms`));
});
}
| import tc from 'turbocolor';
import { SerializedTimings } from '../../../src/rollup/types';
export function printTimings(timings: SerializedTimings) {
Object.keys(timings).forEach(label => {
const color =
label[0] === '#' ? (label[1] !== '#' ? tc.underline : tc.bold) : (text: string) => text;
console.info(color(`${label}: ${timings[label].toFixed(0)}ms`));
});
}
| Fix typings for turbo color | Fix typings for turbo color
| TypeScript | mit | corneliusweig/rollup | ---
+++
@@ -3,13 +3,8 @@
export function printTimings(timings: SerializedTimings) {
Object.keys(timings).forEach(label => {
- let color = tc;
- if (label[0] === '#') {
- color = color.bold;
- if (label[1] !== '#') {
- color = color.underline;
- }
- }
+ const color =
+ label[0] === '#' ? (label[1] !== '#' ? tc.underline : tc.bold) : (text: string) => text;
console.info(color(`${label}: ${timings[label].toFixed(0)}ms`));
});
} |
195672f182528c9081e7de102216cae855365367 | examples/bmi-typescript/src/LabeledSlider.ts | examples/bmi-typescript/src/LabeledSlider.ts | import xs, {Stream, MemoryStream} from 'xstream';
import {div, span, input, VNode} from '@cycle/dom';
import {DOMSource} from '@cycle/dom/xstream-typings.d.ts';
export interface LabeledSliderProps {
label: string;
unit: string;
min: number;
initial: number;
max: number;
}
export type Sources = {
DOM: DOMSource,
props$: Stream<LabeledSliderProps>,
}
export type Sinks = {
DOM: Stream<VNode>,
value$: MemoryStream<number>,
}
function LabeledSlider(sources: Sources): Sinks {
let props$: Stream<LabeledSliderProps> = sources.props$;
let initialValue$ = props$.map(props => props.initial).take(1);
let el$ = sources.DOM.select('.slider').elements();
let newValue$ = sources.DOM.select('.slider').events('input')
.map(ev => parseInt((<HTMLInputElement> ev.target).value));
let value$ = xs.merge(initialValue$, newValue$).remember();
let vtree$ = xs.combine(
(props, value) =>
div('.labeled-slider', [
span('.label', [ props.label + ' ' + value + props.unit ]),
input('.slider', {
attrs: {type: 'range', min: props.min, max: props.max, value: value}
})
]),
props$, value$
);
return {
DOM: vtree$,
value$: value$,
};
}
export default LabeledSlider;
| import xs, {Stream, MemoryStream} from 'xstream';
import {div, span, input, VNode} from '@cycle/dom';
import {DOMSource} from '@cycle/dom/xstream-typings';
export interface LabeledSliderProps {
label: string;
unit: string;
min: number;
initial: number;
max: number;
}
export type Sources = {
DOM: DOMSource,
props$: Stream<LabeledSliderProps>,
}
export type Sinks = {
DOM: Stream<VNode>,
value$: MemoryStream<number>,
}
function LabeledSlider(sources: Sources): Sinks {
let props$: Stream<LabeledSliderProps> = sources.props$;
let initialValue$ = props$.map(props => props.initial).take(1);
let el$ = sources.DOM.select('.slider').elements();
let newValue$ = sources.DOM.select('.slider').events('input')
.map(ev => parseInt((<HTMLInputElement> ev.target).value));
let value$ = xs.merge(initialValue$, newValue$).remember();
let vtree$ = xs.combine(
(props, value) =>
div('.labeled-slider', [
span('.label', [ props.label + ' ' + value + props.unit ]),
input('.slider', {
attrs: {type: 'range', min: props.min, max: props.max, value: value}
})
]),
props$, value$
);
return {
DOM: vtree$,
value$: value$,
};
}
export default LabeledSlider;
| Improve bmi-typescript example a bit | Improve bmi-typescript example a bit
Use better import of xstream-typings in cycle/dom
| TypeScript | mit | cyclejs/cycle-core,feliciousx-open-source/cyclejs,usm4n/cyclejs,cyclejs/cycle-core,cyclejs/cyclejs,ntilwalli/cyclejs,maskinoshita/cyclejs,usm4n/cyclejs,feliciousx-open-source/cyclejs,maskinoshita/cyclejs,maskinoshita/cyclejs,ntilwalli/cyclejs,staltz/cycle,ntilwalli/cyclejs,usm4n/cyclejs,usm4n/cyclejs,cyclejs/cyclejs,ntilwalli/cyclejs,maskinoshita/cyclejs,cyclejs/cyclejs,feliciousx-open-source/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cyclejs,staltz/cycle | ---
+++
@@ -1,6 +1,6 @@
import xs, {Stream, MemoryStream} from 'xstream';
import {div, span, input, VNode} from '@cycle/dom';
-import {DOMSource} from '@cycle/dom/xstream-typings.d.ts';
+import {DOMSource} from '@cycle/dom/xstream-typings';
export interface LabeledSliderProps {
label: string; |
e6c1b3ba5d7633c9f47191113dab463163a7aa89 | src/app/providers/electron.service.ts | src/app/providers/electron.service.ts | import { Injectable } from '@angular/core';
import { ipcRenderer } from 'electron';
import * as childProcess from 'child_process';
@Injectable()
export class ElectronService {
ipcRenderer: typeof ipcRenderer;
childProcess: typeof childProcess;
constructor() {
if (this.isElectron()) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.childProcess = window.require('child_process');
}
}
isElectron = () => {
return window && window.process && window.process.type;
}
}
| import { Injectable } from '@angular/core';
// If you import a module but never use any of the imported values other than as TypeScript types,
// the resulting javascript file will look as if you never imported the module at all.
import { ipcRenderer } from 'electron';
import * as childProcess from 'child_process';
@Injectable()
export class ElectronService {
ipcRenderer: typeof ipcRenderer;
childProcess: typeof childProcess;
constructor() {
//Conditional imports
if (this.isElectron()) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.childProcess = window.require('child_process');
}
}
isElectron = () => {
return window && window.process && window.process.type;
}
}
| Add comments of how conditional import works | Add comments of how conditional import works
| TypeScript | agpl-3.0 | ineiti/cybermind | ---
+++
@@ -1,5 +1,7 @@
import { Injectable } from '@angular/core';
+// If you import a module but never use any of the imported values other than as TypeScript types,
+// the resulting javascript file will look as if you never imported the module at all.
import { ipcRenderer } from 'electron';
import * as childProcess from 'child_process';
@@ -10,6 +12,7 @@
childProcess: typeof childProcess;
constructor() {
+ //Conditional imports
if (this.isElectron()) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.childProcess = window.require('child_process'); |
8654a04de2480ad0971e9f51b508f6fe219cf957 | lib/components/src/ScrollArea/ScrollArea.tsx | lib/components/src/ScrollArea/ScrollArea.tsx | import React, { Fragment, FunctionComponent } from 'react';
import { styled, Global } from '@storybook/theming';
import { OverlayScrollbarsComponent } from './OverlayScrollbarsComponent';
import { getScrollAreaStyles } from './ScrollAreaStyles';
export interface ScrollProps {
horizontal?: boolean;
vertical?: boolean;
[key: string]: any;
}
const Scroll = styled(({ vertical, horizontal, ...rest }: ScrollProps) => (
<OverlayScrollbarsComponent options={{ scrollbars: { autoHide: 'scroll' } }} {...rest} />
))<ScrollProps>(
({ vertical }) =>
!vertical
? {
overflowY: 'hidden',
}
: {
overflowY: 'auto',
height: '100%',
},
({ horizontal }) =>
!horizontal
? {
overflowX: 'hidden',
}
: {
overflowX: 'auto',
width: '100%',
}
);
export interface ScrollAreaProps {
horizontal?: boolean;
vertical?: boolean;
className?: string;
}
export const ScrollArea: FunctionComponent<ScrollAreaProps> = ({
children,
vertical,
horizontal,
...props
}) => (
<Fragment>
<Global styles={getScrollAreaStyles} />
<Scroll vertical={vertical} horizontal={horizontal} {...props}>
{children}
</Scroll>
</Fragment>
);
ScrollArea.defaultProps = {
horizontal: false,
vertical: false,
};
| import React, { Fragment, FunctionComponent } from 'react';
import { styled, Global } from '@storybook/theming';
import { OverlayScrollbarsComponent } from './OverlayScrollbarsComponent';
import { getScrollAreaStyles } from './ScrollAreaStyles';
export interface ScrollProps {
horizontal?: boolean;
vertical?: boolean;
[key: string]: any;
}
const Scroll = styled(({ vertical, horizontal, ...rest }: ScrollProps) => (
<OverlayScrollbarsComponent options={{ scrollbars: { autoHide: 'leave' } }} {...rest} />
))<ScrollProps>(
({ vertical }) =>
!vertical
? {
overflowY: 'hidden',
}
: {
overflowY: 'auto',
height: '100%',
},
({ horizontal }) =>
!horizontal
? {
overflowX: 'hidden',
}
: {
overflowX: 'auto',
width: '100%',
}
);
export interface ScrollAreaProps {
horizontal?: boolean;
vertical?: boolean;
className?: string;
}
export const ScrollArea: FunctionComponent<ScrollAreaProps> = ({
children,
vertical,
horizontal,
...props
}) => (
<Fragment>
<Global styles={getScrollAreaStyles} />
<Scroll vertical={vertical} horizontal={horizontal} {...props}>
{children}
</Scroll>
</Fragment>
);
ScrollArea.defaultProps = {
horizontal: false,
vertical: false,
};
| CHANGE overlayscrollbar option so the scrollbars are visible on hovering over the scrollable area | CHANGE overlayscrollbar option so the scrollbars are visible on hovering over the scrollable area
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook | ---
+++
@@ -11,7 +11,7 @@
}
const Scroll = styled(({ vertical, horizontal, ...rest }: ScrollProps) => (
- <OverlayScrollbarsComponent options={{ scrollbars: { autoHide: 'scroll' } }} {...rest} />
+ <OverlayScrollbarsComponent options={{ scrollbars: { autoHide: 'leave' } }} {...rest} />
))<ScrollProps>(
({ vertical }) =>
!vertical |
0938ea3964013ec984118e96c7b126cf9db900a5 | src/prelude/string.ts | src/prelude/string.ts | export function concat(xs: string[]): string {
return xs.reduce((a, b) => a + b, '');
}
export function capitalize(s: string): string {
return toUpperCase(s.charAt(0)) + toLowerCase(s.slice(1));
}
export function toUpperCase(s: string): string {
return s.toUpperCase();
}
export function toLowerCase(s: string): string {
return s.toLowerCase();
}
| export function concat(xs: string[]): string {
return xs.join('');
}
export function capitalize(s: string): string {
return toUpperCase(s.charAt(0)) + toLowerCase(s.slice(1));
}
export function toUpperCase(s: string): string {
return s.toUpperCase();
}
export function toLowerCase(s: string): string {
return s.toLowerCase();
}
| Use join instead of reduce | Use join instead of reduce
| TypeScript | mit | syuilo/Misskey,syuilo/Misskey | ---
+++
@@ -1,5 +1,5 @@
export function concat(xs: string[]): string {
- return xs.reduce((a, b) => a + b, '');
+ return xs.join('');
}
export function capitalize(s: string): string { |
49178d4ab4be07295692ac7994a3124b76501ba4 | app/test/integration/launch-test.ts | app/test/integration/launch-test.ts | // This shouldn't be necessary, but without this CI fails on Windows. Seems to
// be a bug in TS itself or ts-node.
/// <reference types="node" />
import { Application } from 'spectron'
import * as path from 'path'
describe('App', function (this: any) {
let app: Application
beforeEach(function () {
let appPath = path.join(
__dirname,
'..',
'..',
'..',
'node_modules',
'.bin',
'electron'
)
if (process.platform === 'win32') {
appPath += '.cmd'
}
const root = path.resolve(__dirname, '..', '..', '..')
app = new Application({
path: appPath,
args: [path.join(root, 'out')],
})
return app.start()
})
afterEach(function () {
if (app && app.isRunning()) {
return app.stop()
}
return Promise.resolve()
})
it('opens a window on launch', async () => {
await app.client.waitUntil(() => app.browserWindow.isVisible(), 5000)
const count = await app.client.getWindowCount()
expect(count).toBe(1)
const window = app.browserWindow
expect(window.isVisible()).resolves.toBe(true)
expect(window.isMinimized()).resolves.toBe(false)
expect(window.isMinimized()).resolves.toBe(false)
const bounds = await window.getBounds()
expect(bounds.width).toBeGreaterThan(0)
expect(bounds.height).toBeGreaterThan(0)
})
})
| // This shouldn't be necessary, but without this CI fails on Windows. Seems to
// be a bug in TS itself or ts-node.
/// <reference types="node" />
import { Application } from 'spectron'
import * as path from 'path'
describe('App', function (this: any) {
let app: Application
beforeEach(function () {
let appPath = path.join(
__dirname,
'..',
'..',
'..',
'node_modules',
'.bin',
'electron'
)
if (process.platform === 'win32') {
appPath += '.cmd'
}
const root = path.resolve(__dirname, '..', '..', '..')
app = new Application({
path: appPath,
args: [path.join(root, 'out')],
})
return app.start()
})
afterEach(function () {
if (app && app.isRunning()) {
return app.stop()
}
return Promise.resolve()
})
it('opens a window on launch', async () => {
await app.client.waitUntil(
() => Promise.resolve(app.browserWindow.isVisible()),
{ timeout: 5000 }
)
const count = await app.client.getWindowCount()
expect(count).toBe(1)
const window = app.browserWindow
expect(window.isVisible()).resolves.toBe(true)
expect(window.isMinimized()).resolves.toBe(false)
expect(window.isMinimized()).resolves.toBe(false)
const bounds = await window.getBounds()
expect(bounds.width).toBeGreaterThan(0)
expect(bounds.height).toBeGreaterThan(0)
})
})
| Fix TypeScript types in integration test | Fix TypeScript types in integration test
| TypeScript | mit | kactus-io/kactus,desktop/desktop,say25/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,say25/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop | ---
+++
@@ -39,7 +39,10 @@
})
it('opens a window on launch', async () => {
- await app.client.waitUntil(() => app.browserWindow.isVisible(), 5000)
+ await app.client.waitUntil(
+ () => Promise.resolve(app.browserWindow.isVisible()),
+ { timeout: 5000 }
+ )
const count = await app.client.getWindowCount()
expect(count).toBe(1) |
d19038ed92d6e3e0ca741655a61774dcec44eea6 | app/test/unit/status-parser-test.ts | app/test/unit/status-parser-test.ts | import * as chai from 'chai'
const expect = chai.expect
import { parsePorcelainStatus } from '../../src/lib/status-parser'
describe('parsePorcelainStatus', () => {
describe('name', () => {
it('parses a standard status', async () => {
const entries = parsePorcelainStatus(' M modified\0?? untracked\0 D deleted\0')
expect(entries.length).to.equal(3)
let i = 0
expect(entries[i].statusCode).to.equal(' M')
expect(entries[i].path).to.equal('modified')
i++
expect(entries[i].statusCode).to.equal('??')
expect(entries[i].path).to.equal('untracked')
i++
expect(entries[i].statusCode).to.equal(' D')
expect(entries[i].path).to.equal('deleted')
i++
})
})
})
| import * as chai from 'chai'
const expect = chai.expect
import { parsePorcelainStatus } from '../../src/lib/status-parser'
describe('parsePorcelainStatus', () => {
describe('name', () => {
it('parses a standard status', async () => {
const entries = parsePorcelainStatus(' M modified\0?? untracked\0 D deleted\0')
expect(entries.length).to.equal(3)
let i = 0
expect(entries[i].statusCode).to.equal(' M')
expect(entries[i].path).to.equal('modified')
i++
expect(entries[i].statusCode).to.equal('??')
expect(entries[i].path).to.equal('untracked')
i++
expect(entries[i].statusCode).to.equal(' D')
expect(entries[i].path).to.equal('deleted')
})
it('parses renames', async () => {
const entries = parsePorcelainStatus('R new\0old\0RM from\0to\0')
expect(entries.length).to.equal(2)
let i = 0
expect(entries[i].statusCode).to.equal('R ')
expect(entries[i].path).to.equal('new')
expect(entries[i].oldPath).to.equal('old')
i++
expect(entries[i].statusCode).to.equal('RM')
expect(entries[i].path).to.equal('from')
expect(entries[i].oldPath).to.equal('to')
})
})
})
| Add a test for renames | Add a test for renames
| TypeScript | mit | shiftkey/desktop,hjobrien/desktop,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop,gengjiawen/desktop,gengjiawen/desktop,kactus-io/kactus,hjobrien/desktop,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,BugTesterTest/desktops,gengjiawen/desktop,say25/desktop,kactus-io/kactus,desktop/desktop,gengjiawen/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,hjobrien/desktop,BugTesterTest/desktops,say25/desktop,BugTesterTest/desktops,artivilla/desktop,artivilla/desktop,BugTesterTest/desktops,desktop/desktop,j-f1/forked-desktop,say25/desktop,hjobrien/desktop,shiftkey/desktop,say25/desktop | ---
+++
@@ -22,7 +22,23 @@
expect(entries[i].statusCode).to.equal(' D')
expect(entries[i].path).to.equal('deleted')
+ })
+
+ it('parses renames', async () => {
+
+ const entries = parsePorcelainStatus('R new\0old\0RM from\0to\0')
+ expect(entries.length).to.equal(2)
+
+ let i = 0
+
+ expect(entries[i].statusCode).to.equal('R ')
+ expect(entries[i].path).to.equal('new')
+ expect(entries[i].oldPath).to.equal('old')
i++
+
+ expect(entries[i].statusCode).to.equal('RM')
+ expect(entries[i].path).to.equal('from')
+ expect(entries[i].oldPath).to.equal('to')
})
})
}) |
808dde3a81902bfac873382de53373d319b298a2 | test/frames/frame-arg-spec.ts | test/frames/frame-arg-spec.ts | import { expect } from "chai";
import { FrameArg, FrameString } from "../../src/frames";
describe("FrameArg", () => {
const frame_arg = FrameArg.here();
it("is created from 'here'", () => {
expect(frame_arg).to.be.instanceOf(FrameArg);
});
it("stringifies to underscore", () => {
expect(frame_arg.toString()).to.equal("_");
});
it ("'in' returns the context", () => {
const context = new FrameString("context", {atom: frame_arg});
expect(FrameArg.here().in(context)).to.equal(context);
});
describe("level", () => {
it("level 1 returns 'here'", () => {
const frame_level = FrameArg.level();
expect(frame_arg).to.equal(frame_level);
});
});
});
| import { expect } from "chai";
import { FrameArg, FrameString } from "../../src/frames";
describe("FrameArg", () => {
const frame_arg = FrameArg.here();
describe("here", () => {
it("is created from 'here'", () => {
expect(frame_arg).to.be.instanceOf(FrameArg);
});
it("stringifies to underscore", () => {
expect(frame_arg.toString()).to.equal("_");
});
it ("evaluates to the context", () => {
const context = new FrameString("context", {atom: frame_arg});
expect(FrameArg.here().in(context)).to.equal(context);
});
});
describe("level", () => {
it("returns 'here' at level 1", () => {
const frame_level = FrameArg.level();
expect(frame_arg).to.equal(frame_level);
});
it("returns the same object at each level", () => {
const level_2 = FrameArg.level(2);
expect(FrameArg.level(2)).to.equal(level_2);
});
});
});
| Refactor spec into 'here' and 'level' | Refactor spec into 'here' and 'level'
| TypeScript | mit | TheSwanFactory/hclang,TheSwanFactory/maml,TheSwanFactory/maml,TheSwanFactory/hclang | ---
+++
@@ -1,27 +1,33 @@
import { expect } from "chai";
import { FrameArg, FrameString } from "../../src/frames";
-
describe("FrameArg", () => {
const frame_arg = FrameArg.here();
- it("is created from 'here'", () => {
- expect(frame_arg).to.be.instanceOf(FrameArg);
+ describe("here", () => {
+ it("is created from 'here'", () => {
+ expect(frame_arg).to.be.instanceOf(FrameArg);
+ });
+
+ it("stringifies to underscore", () => {
+ expect(frame_arg.toString()).to.equal("_");
+ });
+
+ it ("evaluates to the context", () => {
+ const context = new FrameString("context", {atom: frame_arg});
+ expect(FrameArg.here().in(context)).to.equal(context);
+ });
});
- it("stringifies to underscore", () => {
- expect(frame_arg.toString()).to.equal("_");
- });
-
- it ("'in' returns the context", () => {
- const context = new FrameString("context", {atom: frame_arg});
- expect(FrameArg.here().in(context)).to.equal(context);
- });
-
-describe("level", () => {
- it("level 1 returns 'here'", () => {
+ describe("level", () => {
+ it("returns 'here' at level 1", () => {
const frame_level = FrameArg.level();
expect(frame_arg).to.equal(frame_level);
});
+
+ it("returns the same object at each level", () => {
+ const level_2 = FrameArg.level(2);
+ expect(FrameArg.level(2)).to.equal(level_2);
+ });
});
}); |
71881b4d970e9b85cc71e8bdac10bec80506273e | app/src/lib/progress/step-progress.ts | app/src/lib/progress/step-progress.ts | import { parse, IGitProgress } from './parser'
export interface IProgressStep {
title: string
weight: number
}
export interface ICombinedProgress {
percent: number
details: IGitProgress
}
export class StepProgressParser {
private readonly steps: ReadonlyArray<IProgressStep>
private stepIndex = 0
public constructor(steps: ReadonlyArray<IProgressStep>) {
// Scale the step weight so that they're all a percentage
// adjusted to the total weight of all steps.
const totalStepWeight = steps.reduce((sum, step) => sum + step.weight, 0)
this.steps = steps.map(step => ({
title: step.title,
weight: step.weight / totalStepWeight,
}))
}
public parse(line: string): ICombinedProgress | null {
const progress = parse(line)
if (!progress) {
return null
}
let percent = 0
for (let i = this.stepIndex; i < this.steps.length; i++) {
const step = this.steps[i]
if (progress.title === step.title) {
if (progress.total) {
percent += step.weight * (progress.value / progress.total)
}
this.stepIndex = i
return { percent, details: progress }
} else {
percent += step.weight
}
}
return null
}
}
| import { parse, IGitProgress } from './parser'
export interface IProgressStep {
title: string
weight: number
}
export interface ICombinedProgress {
percent: number
details: IGitProgress
}
export class StepProgressParser {
private readonly steps: ReadonlyArray<IProgressStep>
private stepIndex = 0
public constructor(steps: ReadonlyArray<IProgressStep>) {
if (!steps.length) {
throw new Error('must specify at least one step')
}
// Scale the step weight so that they're all a percentage
// adjusted to the total weight of all steps.
const totalStepWeight = steps.reduce((sum, step) => sum + step.weight, 0)
this.steps = steps.map(step => ({
title: step.title,
weight: step.weight / totalStepWeight,
}))
}
public parse(line: string): ICombinedProgress | null {
const progress = parse(line)
if (!progress) {
return null
}
let percent = 0
for (let i = this.stepIndex; i < this.steps.length; i++) {
const step = this.steps[i]
if (progress.title === step.title) {
if (progress.total) {
percent += step.weight * (progress.value / progress.total)
}
this.stepIndex = i
return { percent, details: progress }
} else {
percent += step.weight
}
}
return null
}
}
| Throw an error if no steps are provided | Throw an error if no steps are provided
| TypeScript | mit | gengjiawen/desktop,desktop/desktop,artivilla/desktop,gengjiawen/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,BugTesterTest/desktops,j-f1/forked-desktop,hjobrien/desktop,hjobrien/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,BugTesterTest/desktops,j-f1/forked-desktop,hjobrien/desktop,BugTesterTest/desktops,artivilla/desktop,BugTesterTest/desktops,say25/desktop,say25/desktop,gengjiawen/desktop,hjobrien/desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,gengjiawen/desktop,kactus-io/kactus,kactus-io/kactus,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,say25/desktop,artivilla/desktop | ---
+++
@@ -15,6 +15,10 @@
private stepIndex = 0
public constructor(steps: ReadonlyArray<IProgressStep>) {
+
+ if (!steps.length) {
+ throw new Error('must specify at least one step')
+ }
// Scale the step weight so that they're all a percentage
// adjusted to the total weight of all steps. |
9f6085bdb58a7d023a3aafc2efc7bc03f3da42db | src/lib/theme/helpers/relative-url.ts | src/lib/theme/helpers/relative-url.ts | import * as path from 'path';
import { MarkdownPlugin } from '../../plugin';
export function relativeUrl(absolute: string) {
const urlPrefix: RegExp = /^(http|ftp)s?:\/\//;
if (!MarkdownPlugin.location || urlPrefix.test(absolute)) {
return absolute;
} else {
const relative = path.relative(path.dirname(MarkdownPlugin.location), path.dirname(absolute));
return path.join(relative, path.basename(absolute)).replace(/\\/g, '/');
}
}
| import * as path from 'path';
import { MarkdownPlugin } from '../../plugin';
export function relativeUrl(absolute: string) {
if (!absolute) {
return '';
}
const urlPrefix: RegExp = /^(http|ftp)s?:\/\//;
if (!MarkdownPlugin.location || urlPrefix.test(absolute)) {
return absolute;
} else {
const relative = path.relative(path.dirname(MarkdownPlugin.location), path.dirname(absolute));
return path.join(relative, path.basename(absolute)).replace(/\\/g, '/');
}
}
| Check for undefined absolute path | Check for undefined absolute path
| TypeScript | mit | tgreyuk/typedoc-plugin-markdown,tgreyuk/typedoc-plugin-markdown | ---
+++
@@ -1,7 +1,11 @@
import * as path from 'path';
+
import { MarkdownPlugin } from '../../plugin';
export function relativeUrl(absolute: string) {
+ if (!absolute) {
+ return '';
+ }
const urlPrefix: RegExp = /^(http|ftp)s?:\/\//;
if (!MarkdownPlugin.location || urlPrefix.test(absolute)) {
return absolute; |
eea8946f80c9189cab049c5ac294ecd11ad40b37 | packages/cli-core/src/cli.ts | packages/cli-core/src/cli.ts | import { commands } from "./commands";
import { configure, Logger, getLogger } from "log4js";
import { loggerConfig } from "./defaults";
import { configController } from "./config";
export const initiate = async (process: NodeJS.Process): Promise<void> => {
const cliConfig = await configController.composeCliConfig(process);
configure(loggerConfig);
const logger: Logger = getLogger(cliConfig.logging);
logger.trace(`CLI started with parsed configuration: ${JSON.stringify(cliConfig, null, 2)}`);
return commands
.find((command) => command.name === cliConfig.command)
.action(cliConfig, logger);
};
| import { commands } from "./commands";
import { configure, Logger, getLogger } from "log4js";
import { loggerConfig } from "./defaults";
import { configController } from "./config";
export const initiate = async (process: NodeJS.Process): Promise<void> => {
const cliConfig = await configController.composeCliConfig(process);
configure(loggerConfig);
const logger: Logger = getLogger(cliConfig.logging);
logger.trace(`CLI started with parsed configuration: ${JSON.stringify(cliConfig, null, 2)}`);
// Handle a case where the node process hangs on MacOS.
const isMacOS = process.platform === "darwin";
if (isMacOS) {
process.on("SIGHUP", () => process.exit(0));
}
return commands
.find((command) => command.name === cliConfig.command)
.action(cliConfig, logger);
};
| Fix a bug where the node process hangs on MacOS 🐛 | fix: Fix a bug where the node process hangs on MacOS 🐛
Signed-off-by: Georgi Georgiev <37121d6a39c9149491e77436b3bbc4b8d12a00b9@gmail.com>
| TypeScript | apache-2.0 | StBozov/Core | ---
+++
@@ -11,6 +11,12 @@
logger.trace(`CLI started with parsed configuration: ${JSON.stringify(cliConfig, null, 2)}`);
+ // Handle a case where the node process hangs on MacOS.
+ const isMacOS = process.platform === "darwin";
+ if (isMacOS) {
+ process.on("SIGHUP", () => process.exit(0));
+ }
+
return commands
.find((command) => command.name === cliConfig.command)
.action(cliConfig, logger); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.