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
|
---|---|---|---|---|---|---|---|---|---|---|
6f450d4d82c41258b862ce3147033bfb9701a36f | client/Settings/components/Toggle.tsx | client/Settings/components/Toggle.tsx | import { Field, FieldProps } from "formik";
import * as React from "react";
import { probablyUniqueString } from "../../../common/Toolbox";
interface ToggleProps {
fieldName: string;
}
export class Toggle extends React.Component<ToggleProps> {
private id: string;
public componentWillMount() {
this.id = `toggle_${probablyUniqueString()}`;
}
public render() {
return (
<Field name={this.props.fieldName}>
{(fieldProps: FieldProps) => {
const stateString = fieldProps.field.value ? "on" : "off";
return (
<button
type="button"
className="c-toggle"
onClick={() => this.toggle(fieldProps)}
>
<span className="c-toggle__label">{this.props.children}</span>
<span className={"c-toggle__icon fas fa-toggle-" + stateString} />
</button>
);
}}
</Field>
);
}
private toggle = (fieldProps: FieldProps) =>
fieldProps.form.setFieldValue(
this.props.fieldName,
!fieldProps.field.value
);
}
| import { Field, FieldProps } from "formik";
import * as React from "react";
import { probablyUniqueString } from "../../../common/Toolbox";
interface ToggleProps {
fieldName: string;
}
export class Toggle extends React.Component<ToggleProps> {
private id: string;
public componentWillMount() {
this.id = `toggle_${probablyUniqueString()}`;
}
public render() {
return (
<Field name={this.props.fieldName}>
{(fieldProps: FieldProps) => {
const stateString = fieldProps.field.value ? "on" : "off";
return (
<div className="c-button-with-label">
<label className="c-toggle__label" htmlFor={this.id}>
{this.props.children}
</label>
<button
id={this.id}
type="button"
className="c-toggle"
onClick={() => this.toggle(fieldProps)}
>
<span
className={"c-toggle__icon fas fa-toggle-" + stateString}
/>
</button>
</div>
);
}}
</Field>
);
}
private toggle = (fieldProps: FieldProps) =>
fieldProps.form.setFieldValue(
this.props.fieldName,
!fieldProps.field.value
);
}
| Move buttons to just include toggle icon | Move buttons to just include toggle icon
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -19,14 +19,21 @@
{(fieldProps: FieldProps) => {
const stateString = fieldProps.field.value ? "on" : "off";
return (
- <button
- type="button"
- className="c-toggle"
- onClick={() => this.toggle(fieldProps)}
- >
- <span className="c-toggle__label">{this.props.children}</span>
- <span className={"c-toggle__icon fas fa-toggle-" + stateString} />
- </button>
+ <div className="c-button-with-label">
+ <label className="c-toggle__label" htmlFor={this.id}>
+ {this.props.children}
+ </label>
+ <button
+ id={this.id}
+ type="button"
+ className="c-toggle"
+ onClick={() => this.toggle(fieldProps)}
+ >
+ <span
+ className={"c-toggle__icon fas fa-toggle-" + stateString}
+ />
+ </button>
+ </div>
);
}}
</Field> |
b46cf9c11eb9ec8efd6d05186e39fc44eb612ef8 | test/common/db.ts | test/common/db.ts | import Future = require('sfuture');
import db = require('../../core/db');
export const TestCollectionName = 'beyondTestCollection';
export function connect(): Future<void> {
return db.initialize('mongodb://localhost:27017/beyondTest');
}
export function close(forceClose: boolean): Future<void> {
return db.close(forceClose);
}
export function cleanupCollection(): Future<void> {
let mongoConnection = db.connection();
let mongoCollection = mongoConnection.collection(TestCollectionName);
return Future.denodify<void>(mongoCollection.remove, mongoCollection, { });
}
export function setupData(...docs: any[]): Future<void> {
let mongoConnection = db.connection();
let mongoCollection = mongoConnection.collection(TestCollectionName);
return Future.denodify<void>(mongoCollection.insert, mongoCollection, docs);
}
| import Future = require('sfuture');
import db = require('../../core/db');
export const TestCollectionName = 'beyondTestCollection';
export function connect(): Future<void> {
return db.initialize('mongodb://localhost:27017/beyondTest');
}
export function close(forceClose: boolean): Future<void> {
return db.close(forceClose);
}
export function cleanupCollection(): Future<void> {
let mongoConnection = db.connection();
return Future.denodify<void>(mongoConnection.dropCollection, mongoConnection, TestCollectionName)
.recover(() => {
return;
}).flatMap((): Future<void> => {
return Future.denodify<void>(mongoConnection.createCollection, mongoConnection, TestCollectionName);
});
}
export function setupData(...docs: any[]): Future<void> {
let mongoConnection = db.connection();
let mongoCollection = mongoConnection.collection(TestCollectionName);
return Future.denodify<void>(mongoCollection.insert, mongoCollection, docs);
}
| Drop and recreate collection when flush collection. | Drop and recreate collection when flush collection.
Currently, beyond.ts just remove all documents on test. But now we have to
test index. So this patch makes recreate collection instead of just removing
all documents.
| TypeScript | apache-2.0 | SollmoStudio/beyond.ts,sgkim126/beyond.ts,sgkim126/beyond.ts,SollmoStudio/beyond.ts,noraesae/beyond.ts,noraesae/beyond.ts | ---
+++
@@ -14,8 +14,12 @@
export function cleanupCollection(): Future<void> {
let mongoConnection = db.connection();
- let mongoCollection = mongoConnection.collection(TestCollectionName);
- return Future.denodify<void>(mongoCollection.remove, mongoCollection, { });
+ return Future.denodify<void>(mongoConnection.dropCollection, mongoConnection, TestCollectionName)
+ .recover(() => {
+ return;
+ }).flatMap((): Future<void> => {
+ return Future.denodify<void>(mongoConnection.createCollection, mongoConnection, TestCollectionName);
+ });
}
export function setupData(...docs: any[]): Future<void> { |
4d635068f05d68a2bf2c65af7e5edd81504ea637 | test/src/index.ts | test/src/index.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import expect = require('expect.js');
describe('jupyter-js-editor', () => {
describe('CodeMirrorWidget', () => {
it('should pass', () => {
});
});
});
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import expect = require('expect.js');
import {
EditorWidget, EditorModel
} from '../../lib';
describe('jupyter-js-editor', () => {
describe('CodeMirrorWidget', () => {
it('should always pass', () => {
let model = new EditorModel();
let widget = new EditorWidget(model);
});
});
});
| Make sure the test actually imports the source | Make sure the test actually imports the source
| TypeScript | bsd-3-clause | jupyter/jupyter-js-editor,jupyter/jupyter-js-editor,jupyter/jupyter-js-editor,jupyter/jupyter-js-editor | ---
+++
@@ -4,13 +4,18 @@
import expect = require('expect.js');
+import {
+ EditorWidget, EditorModel
+} from '../../lib';
+
describe('jupyter-js-editor', () => {
describe('CodeMirrorWidget', () => {
- it('should pass', () => {
-
+ it('should always pass', () => {
+ let model = new EditorModel();
+ let widget = new EditorWidget(model);
});
}); |
d41df500b41f8fce63d3c193460f6444a2c7cca0 | Configuration/Typoscript/setup.ts | Configuration/Typoscript/setup.ts | plugin.tx_tevfaqs {
view {
templateRootPath = {$plugin.tx_tevfaqs.view.templateRootPath}
partialRootPath = {$plugin.tx_tevfaqs.view.partialRootPath}
layoutRootPath = {$plugin.tx_tevfaqs.view.layoutRootPath}
}
}
| plugin.tx_tevfaqs {
view {
templateRootPaths {
0 = {$plugin.tx_tevfaqs.view.templateRootPath}
}
partialRootPaths {
0 = {$plugin.tx_tevfaqs.view.partialRootPath}
}
layoutRootPaths {
0 = {$plugin.tx_tevfaqs.view.layoutRootPath}
}
}
}
| Allow template overrides via templateRootPaths | Allow template overrides via templateRootPaths
| TypeScript | mit | 3ev/tev_faqs,3ev/tev_faqs,3ev/tev_faqs | ---
+++
@@ -1,7 +1,15 @@
plugin.tx_tevfaqs {
view {
- templateRootPath = {$plugin.tx_tevfaqs.view.templateRootPath}
- partialRootPath = {$plugin.tx_tevfaqs.view.partialRootPath}
- layoutRootPath = {$plugin.tx_tevfaqs.view.layoutRootPath}
+ templateRootPaths {
+ 0 = {$plugin.tx_tevfaqs.view.templateRootPath}
+ }
+
+ partialRootPaths {
+ 0 = {$plugin.tx_tevfaqs.view.partialRootPath}
+ }
+
+ layoutRootPaths {
+ 0 = {$plugin.tx_tevfaqs.view.layoutRootPath}
+ }
}
} |
9871b1ddab747725dec635db24b410c610742e2e | app/test/setup-test-framework.ts | app/test/setup-test-framework.ts | // set test timeout to 100s
jest.setTimeout(100000)
import 'jest-extended'
import 'jest-localstorage-mock'
| // set test timeout to 10s
jest.setTimeout(10000)
import 'jest-extended'
import 'jest-localstorage-mock'
| Revert setting Jest timeout to 100s | Revert setting Jest timeout to 100s
| TypeScript | mit | j-f1/forked-desktop,artivilla/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,desktop/desktop,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,artivilla/desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,desktop/desktop | ---
+++
@@ -1,5 +1,5 @@
-// set test timeout to 100s
-jest.setTimeout(100000)
+// set test timeout to 10s
+jest.setTimeout(10000)
import 'jest-extended'
import 'jest-localstorage-mock' |
22cc16f5c83d6394003173f79c12ef56737db815 | src/internal/pwnedpasswords/responses.ts | src/internal/pwnedpasswords/responses.ts | /**
* Known potential responses from the remote API.
*
* https://haveibeenpwned.com/API/v2#PwnedPasswords
*
*/
export interface PwnedPasswordsApiResponse {
// eslint-disable-next-line no-restricted-globals
status: number;
data?: string;
}
/** @internal */
export const OK = {
status: 200,
};
/** @internal */
export const BAD_REQUEST = {
status: 400,
data: 'The hash prefix was not in a valid format',
};
| /**
* Known potential responses from the remote API.
*
* https://haveibeenpwned.com/API/v2#PwnedPasswords
*
*/
export interface PwnedPasswordsApiResponse {
status: number;
data?: string;
}
/** @internal */
export const OK = {
status: 200,
};
/** @internal */
export const BAD_REQUEST = {
status: 400,
data: 'The hash prefix was not in a valid format',
};
| Remove unnecessary eslint line exclusion | Remove unnecessary eslint line exclusion
| TypeScript | mit | wKovacs64/hibp,wKovacs64/hibp,wKovacs64/hibp | ---
+++
@@ -6,7 +6,6 @@
*/
export interface PwnedPasswordsApiResponse {
- // eslint-disable-next-line no-restricted-globals
status: number;
data?: string;
} |
91a10b2565c17fe8d02117765060a1eae52cfcec | frontend/src/app/modules/result-selection/services/result-selection.service.ts | frontend/src/app/modules/result-selection/services/result-selection.service.ts | import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from "@angular/common/http";
import {EMPTY, Observable, OperatorFunction} from "rxjs";
import {catchError} from "rxjs/operators";
import {URL} from "../../../enums/url.enum";
import {Caller, ResultSelectionCommand} from "../models/result-selection-command.model";
@Injectable()
export class ResultSelectionService {
constructor(private http: HttpClient) {
}
fetchResultSelectionData<T>(resultSelectionCommand: ResultSelectionCommand, url: URL): Observable<T> {
const params = this.createParamsFromResultSelectionCommand(resultSelectionCommand);
return this.http.get<T>(url, {params: params}).pipe(
this.handleError()
)
}
private createParamsFromResultSelectionCommand(resultSelectionCommand: ResultSelectionCommand) {
let params = new HttpParams()
.set('from', resultSelectionCommand.from.toISOString())
.set('to', resultSelectionCommand.to.toISOString())
.set('caller', Caller[resultSelectionCommand.caller]);
Object.keys(resultSelectionCommand).forEach(key => {
if (key === 'from' || key === 'to' || key === 'caller') {
return;
}
if (resultSelectionCommand[key].length > 0) {
resultSelectionCommand[key].forEach(id => {
params = params.append(key, id.toString())
});
}
});
return params;
}
private handleError(): OperatorFunction<any, any> {
return catchError((error) => {
console.error(error);
return EMPTY;
});
}
}
| import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from "@angular/common/http";
import {EMPTY, Observable, OperatorFunction} from "rxjs";
import {catchError} from "rxjs/operators";
import {URL} from "../../../enums/url.enum";
import {Caller, ResultSelectionCommand} from "../models/result-selection-command.model";
@Injectable()
export class ResultSelectionService {
constructor(private http: HttpClient) {
}
fetchResultSelectionData<T>(resultSelectionCommand: ResultSelectionCommand, url: URL): Observable<T> {
const params = this.createParamsFromResultSelectionCommand(resultSelectionCommand);
return this.http.get<T>(url, {params: params}).pipe(
this.handleError()
)
}
private createParamsFromResultSelectionCommand(resultSelectionCommand: ResultSelectionCommand) {
let params = new HttpParams();
Object.keys(resultSelectionCommand).forEach(key => {
if (resultSelectionCommand[key].length > 0) {
if (key === 'from' || key === 'to') {
params.append(key, resultSelectionCommand[key].toISOString())
} else if (key === 'caller') {
params.append(key, Caller[resultSelectionCommand[key]])
} else {
resultSelectionCommand[key].forEach(id => {
params = params.append(key, id.toString())
});
}
}
});
return params;
}
private handleError(): OperatorFunction<any, any> {
return catchError((error) => {
console.error(error);
return EMPTY;
});
}
}
| Set http request parameter for result selection only if available | [IT-2812] Set http request parameter for result selection only if available
| TypeScript | apache-2.0 | iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor | ---
+++
@@ -18,19 +18,19 @@
}
private createParamsFromResultSelectionCommand(resultSelectionCommand: ResultSelectionCommand) {
- let params = new HttpParams()
- .set('from', resultSelectionCommand.from.toISOString())
- .set('to', resultSelectionCommand.to.toISOString())
- .set('caller', Caller[resultSelectionCommand.caller]);
+ let params = new HttpParams();
Object.keys(resultSelectionCommand).forEach(key => {
- if (key === 'from' || key === 'to' || key === 'caller') {
- return;
- }
if (resultSelectionCommand[key].length > 0) {
- resultSelectionCommand[key].forEach(id => {
- params = params.append(key, id.toString())
- });
+ if (key === 'from' || key === 'to') {
+ params.append(key, resultSelectionCommand[key].toISOString())
+ } else if (key === 'caller') {
+ params.append(key, Caller[resultSelectionCommand[key]])
+ } else {
+ resultSelectionCommand[key].forEach(id => {
+ params = params.append(key, id.toString())
+ });
+ }
}
});
|
cfbfbe6c98c8a017f78a197d53dbc631b1b43569 | packages/@sanity/field/src/validation/index.ts | packages/@sanity/field/src/validation/index.ts | import {SchemaType} from '../diff'
export function getValueError(value: unknown, schemaType: SchemaType) {
const {jsonType} = schemaType
const valueType = typeof value
if (value === null || valueType === 'undefined') {
return undefined
}
if (Array.isArray(value) && jsonType !== 'array') {
return {error: `Value is array, expected ${jsonType}`, value}
}
if (valueType !== jsonType) {
return {error: `Value is ${valueType}, expected ${jsonType}`, value}
}
return undefined
}
| import {SchemaType} from '../diff'
export function getValueError(value: unknown, schemaType: SchemaType) {
const {jsonType} = schemaType
const valueType = Array.isArray(value) ? 'array' : typeof value
if (value === null || valueType === 'undefined') {
return undefined
}
if (valueType !== jsonType) {
return {error: `Value is ${valueType}, expected ${jsonType}`, value}
}
return undefined
}
| Fix error in object/array matching on shapes | [field] Fix error in object/array matching on shapes
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -2,14 +2,10 @@
export function getValueError(value: unknown, schemaType: SchemaType) {
const {jsonType} = schemaType
- const valueType = typeof value
+ const valueType = Array.isArray(value) ? 'array' : typeof value
if (value === null || valueType === 'undefined') {
return undefined
- }
-
- if (Array.isArray(value) && jsonType !== 'array') {
- return {error: `Value is array, expected ${jsonType}`, value}
}
if (valueType !== jsonType) { |
c53acf9b59086a8c3b389c6aeff331292968d433 | src/v2/Apps/Partner/Components/PartnerArtists/PartnerArtistListPlaceholder.tsx | src/v2/Apps/Partner/Components/PartnerArtists/PartnerArtistListPlaceholder.tsx | import React from "react"
import {
Box,
Column,
GridColumns,
SkeletonBox,
SkeletonText,
} from "@artsy/palette"
import { PartnerArtistListContainer } from "./PartnerArtistList"
interface PartnerArtistListPlaceholderProps {
done?: boolean
}
export const PartnerArtistListPlaceholder: React.FC<PartnerArtistListPlaceholderProps> = ({
done = true,
}) => (
<PartnerArtistListContainer>
<GridColumns minWidth={[1100, "auto"]} pr={[2, 0]} gridColumnGap={1}>
<Column span={12}>
<SkeletonText variant="mediumText" done={done}>
Represented Artists
</SkeletonText>
<Box style={{ columnCount: 6 }} mt={2}>
{[...new Array(60)].map((_, i) => {
return (
<SkeletonBox key={i} mb={1} done={done}>
<SkeletonText></SkeletonText>
</SkeletonBox>
)
})}
</Box>
</Column>
</GridColumns>
</PartnerArtistListContainer>
)
| import React from "react"
import { Box, Column, GridColumns, SkeletonText } from "@artsy/palette"
import { PartnerArtistListContainer } from "./PartnerArtistList"
interface PartnerArtistListPlaceholderProps {
done?: boolean
}
const names = [
"xxxxxxxxxxxxxxx",
"xxxxxxxxxx",
"xxxxxxxxxxxxx",
"xxxxxxxxxxxxxxx",
"xxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxx",
"xxxxxxxxxxxxxx",
"xxxxxxxxxxx",
"xxxxxxxxxxxxxxxxx",
"xxxxxxxxxxx",
"xxxxxxxxxxxxxxx",
"xxxxxxxxxx",
"xxxxxxxxxxxxx",
]
function getName(i: number) {
return names[i % names.length]
}
export const PartnerArtistListPlaceholder: React.FC<PartnerArtistListPlaceholderProps> = ({
done = true,
}) => (
<PartnerArtistListContainer>
<GridColumns minWidth={[1100, "auto"]} pr={[2, 0]} gridColumnGap={1}>
<Column span={12}>
<SkeletonText variant="mediumText" done={done}>
Represented Artists
</SkeletonText>
<Box style={{ columnCount: 6 }} mt={2}>
{[...new Array(60)].map((_, i) => {
return (
<SkeletonText key={i} mb={1} done={done}>
{getName(i)}
</SkeletonText>
)
})}
</Box>
</Column>
</GridColumns>
</PartnerArtistListContainer>
)
| Add random width for the placeholder items | Add random width for the placeholder items
| TypeScript | mit | artsy/force-public,joeyAghion/force,artsy/force,joeyAghion/force,artsy/force-public,joeyAghion/force,artsy/force,joeyAghion/force,artsy/force,artsy/force | ---
+++
@@ -1,15 +1,30 @@
import React from "react"
-import {
- Box,
- Column,
- GridColumns,
- SkeletonBox,
- SkeletonText,
-} from "@artsy/palette"
+import { Box, Column, GridColumns, SkeletonText } from "@artsy/palette"
import { PartnerArtistListContainer } from "./PartnerArtistList"
interface PartnerArtistListPlaceholderProps {
done?: boolean
+}
+
+const names = [
+ "xxxxxxxxxxxxxxx",
+ "xxxxxxxxxx",
+ "xxxxxxxxxxxxx",
+ "xxxxxxxxxxxxxxx",
+ "xxxxxxxxxxxxx",
+ "xxxxxxxxxxxxxxxx",
+ "xxxxxxxxxxxxxx",
+ "xxxxxxxxxxxxxx",
+ "xxxxxxxxxxx",
+ "xxxxxxxxxxxxxxxxx",
+ "xxxxxxxxxxx",
+ "xxxxxxxxxxxxxxx",
+ "xxxxxxxxxx",
+ "xxxxxxxxxxxxx",
+]
+
+function getName(i: number) {
+ return names[i % names.length]
}
export const PartnerArtistListPlaceholder: React.FC<PartnerArtistListPlaceholderProps> = ({
@@ -24,9 +39,9 @@
<Box style={{ columnCount: 6 }} mt={2}>
{[...new Array(60)].map((_, i) => {
return (
- <SkeletonBox key={i} mb={1} done={done}>
- <SkeletonText></SkeletonText>
- </SkeletonBox>
+ <SkeletonText key={i} mb={1} done={done}>
+ {getName(i)}
+ </SkeletonText>
)
})}
</Box> |
b1e38df068abe54f85d2d269fe137d7d074e5bbb | src/contexts/index.ts | src/contexts/index.ts | import { context as unoContext } from './arduino-uno';
export interface Context {
[x: string]: string;
}
interface IndexedContexts {
[x: string]: Context;
}
const contexts = {
'arduino-uno': unoContext
};
export const getContext = (key: string) => contexts[key];
| import { context as unoContext } from './arduino-uno';
export interface Context {
[x: string]: string;
run_wrapper: string;
run: string;
}
interface IndexedContexts {
[x: string]: Context;
}
const contexts = {
'arduino-uno': unoContext
};
export const getContext = (key: string) => contexts[key];
| Add run and run_wrapper to context | Add run and run_wrapper to context
| TypeScript | mit | AmnisIO/typewriter,AmnisIO/typewriter,AmnisIO/typewriter | ---
+++
@@ -2,6 +2,8 @@
export interface Context {
[x: string]: string;
+ run_wrapper: string;
+ run: string;
}
interface IndexedContexts { |
40005659dc98f4eb44edabeacbc9b0c37570a6ae | src/extension/sdk/capabilities.ts | src/extension/sdk/capabilities.ts | import { versionIsAtLeast } from "../../shared/utils";
export class DartCapabilities {
public static get empty() { return new DartCapabilities("0.0.0"); }
public version: string;
constructor(dartVersion: string) {
this.version = dartVersion;
}
get supportsDevTools() { return versionIsAtLeast(this.version, "2.1.0"); }
get includesSourceForSdkLibs() { return versionIsAtLeast(this.version, "2.2.1"); }
get handlesBreakpointsInPartFiles() { return versionIsAtLeast(this.version, "2.2.1-edge"); }
get hasDocumentationInCompletions() { return !versionIsAtLeast(this.version, "2.6.0-edge"); }
get handlesPathsEverywhereForBreakpoints() { return versionIsAtLeast(this.version, "2.2.1-edge"); }
get supportsDisableServiceTokens() { return versionIsAtLeast(this.version, "2.2.1-dev.4.2"); }
}
| import { versionIsAtLeast } from "../../shared/utils";
export class DartCapabilities {
public static get empty() { return new DartCapabilities("0.0.0"); }
public version: string;
constructor(dartVersion: string) {
this.version = dartVersion;
}
get supportsDevTools() { return versionIsAtLeast(this.version, "2.1.0"); }
get includesSourceForSdkLibs() { return versionIsAtLeast(this.version, "2.2.1"); }
get handlesBreakpointsInPartFiles() { return versionIsAtLeast(this.version, "2.2.1-edge"); }
get hasDocumentationInCompletions() { return !versionIsAtLeast(this.version, "2.6.0-dev"); }
get handlesPathsEverywhereForBreakpoints() { return versionIsAtLeast(this.version, "2.2.1-edge"); }
get supportsDisableServiceTokens() { return versionIsAtLeast(this.version, "2.2.1-dev.4.2"); }
}
| Include dev builds in no-docs check | Include dev builds in no-docs check
| TypeScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -12,7 +12,7 @@
get supportsDevTools() { return versionIsAtLeast(this.version, "2.1.0"); }
get includesSourceForSdkLibs() { return versionIsAtLeast(this.version, "2.2.1"); }
get handlesBreakpointsInPartFiles() { return versionIsAtLeast(this.version, "2.2.1-edge"); }
- get hasDocumentationInCompletions() { return !versionIsAtLeast(this.version, "2.6.0-edge"); }
+ get hasDocumentationInCompletions() { return !versionIsAtLeast(this.version, "2.6.0-dev"); }
get handlesPathsEverywhereForBreakpoints() { return versionIsAtLeast(this.version, "2.2.1-edge"); }
get supportsDisableServiceTokens() { return versionIsAtLeast(this.version, "2.2.1-dev.4.2"); }
} |
e76257801f758a0ffc6d6ce1814aa6ee8cfac3d1 | src/renderer/colors.ts | src/renderer/colors.ts | import { cyan } from 'material-ui/colors';
export const primary = cyan['500'];
| import { red } from 'material-ui/colors';
export const primary = red['600'];
| Change primary color to red | Change primary color to red
| TypeScript | mit | subnomo/tubetop,subnomo/tubetop,subnomo/tubetop | ---
+++
@@ -1,3 +1,3 @@
-import { cyan } from 'material-ui/colors';
+import { red } from 'material-ui/colors';
-export const primary = cyan['500'];
+export const primary = red['600']; |
a5f8b0b49f09e4399a8176d5cd06cc80c61b07d8 | client/src/app/header/header.component.ts | client/src/app/header/header.component.ts | import { filter, map } from 'rxjs/operators'
import { Component, OnInit } from '@angular/core'
import { NavigationEnd, Router } from '@angular/router'
import { getParameterByName } from '../shared/misc/utils'
@Component({
selector: 'my-header',
templateUrl: './header.component.html',
styleUrls: [ './header.component.scss' ]
})
export class HeaderComponent implements OnInit {
searchValue = ''
constructor (private router: Router) {}
ngOnInit () {
this.router.events
.pipe(
filter(e => e instanceof NavigationEnd),
map(() => getParameterByName('search', window.location.href))
)
.subscribe(searchQuery => this.searchValue = searchQuery || '')
}
doSearch () {
this.router.navigate([ '/search' ], {
queryParams: { search: this.searchValue }
})
}
}
| import { filter, first, map, tap } from 'rxjs/operators'
import { Component, OnInit } from '@angular/core'
import { NavigationEnd, Router } from '@angular/router'
import { getParameterByName } from '../shared/misc/utils'
import { AuthService } from '@app/core'
import { of } from 'rxjs'
@Component({
selector: 'my-header',
templateUrl: './header.component.html',
styleUrls: [ './header.component.scss' ]
})
export class HeaderComponent implements OnInit {
searchValue = ''
constructor (
private router: Router,
private auth: AuthService
) {}
ngOnInit () {
this.router.events
.pipe(
filter(e => e instanceof NavigationEnd),
map(() => getParameterByName('search', window.location.href))
)
.subscribe(searchQuery => this.searchValue = searchQuery || '')
}
doSearch () {
const queryParams: any = {
search: this.searchValue
}
const o = this.auth.isLoggedIn()
? this.loadUserLanguages(queryParams)
: of(true)
o.subscribe(() => this.router.navigate([ '/search' ], { queryParams }))
}
private loadUserLanguages (queryParams: any) {
return this.auth.userInformationLoaded
.pipe(
first(),
tap(() => Object.assign(queryParams, { languageOneOf: this.auth.getUser().videoLanguages }))
)
}
}
| Add language filter in header search | Add language filter in header search
| TypeScript | agpl-3.0 | Green-Star/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube | ---
+++
@@ -1,7 +1,9 @@
-import { filter, map } from 'rxjs/operators'
+import { filter, first, map, tap } from 'rxjs/operators'
import { Component, OnInit } from '@angular/core'
import { NavigationEnd, Router } from '@angular/router'
import { getParameterByName } from '../shared/misc/utils'
+import { AuthService } from '@app/core'
+import { of } from 'rxjs'
@Component({
selector: 'my-header',
@@ -12,7 +14,10 @@
export class HeaderComponent implements OnInit {
searchValue = ''
- constructor (private router: Router) {}
+ constructor (
+ private router: Router,
+ private auth: AuthService
+ ) {}
ngOnInit () {
this.router.events
@@ -24,8 +29,22 @@
}
doSearch () {
- this.router.navigate([ '/search' ], {
- queryParams: { search: this.searchValue }
- })
+ const queryParams: any = {
+ search: this.searchValue
+ }
+
+ const o = this.auth.isLoggedIn()
+ ? this.loadUserLanguages(queryParams)
+ : of(true)
+
+ o.subscribe(() => this.router.navigate([ '/search' ], { queryParams }))
+ }
+
+ private loadUserLanguages (queryParams: any) {
+ return this.auth.userInformationLoaded
+ .pipe(
+ first(),
+ tap(() => Object.assign(queryParams, { languageOneOf: this.auth.getUser().videoLanguages }))
+ )
}
} |
f876a2f522d938d90b3f49be62ca4c54cb0458ad | app/app.component.ts | app/app.component.ts | import {Component} from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }
| import {Component} from '@angular/core';
@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: 'Windstorm'
}
}
export class Hero {
id: number;
name: string;
} | Add hero class and two way data binding for name | Add hero class and two way data binding for name
| TypeScript | mit | Teeohbee/tour_of_heroes,Teeohbee/tour_of_heroes,Teeohbee/tour_of_heroes | ---
+++
@@ -2,6 +2,25 @@
@Component({
selector: 'my-app',
- template: '<h1>My First Angular 2 App</h1>'
+ 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 { }
+export class AppComponent {
+ title = 'Tour of Heroes';
+ hero: Hero = {
+ id: 1,
+ name: 'Windstorm'
+ }
+ }
+
+export class Hero {
+ id: number;
+ name: string;
+} |
acb0649708fb32388bfb27ee26f8e8b409ea03d9 | 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>{{hero.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 value = "{{hero.name}}"placeholder = "name">
<div>
`
})
export class AppComponent {
title = 'Tour of heroes';
hero: Hero = {
id: 1,
name:'Spiderman' };
}
| Add hero name edit textbox | Add hero name edit textbox
| TypeScript | mit | amalshehu/angular-tour-of-heroes,amalshehu/angular-tour-of-heroes,amalshehu/angular-tour-of-heroes | ---
+++
@@ -9,8 +9,11 @@
template:`
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
- <div><label>Id: </label>{{hero.id}}</div>
- <div><label>Name: </label>{{hero.name}}</div>
+ <div><label>id: </label>{{hero.id}}</div>
+ <div>
+ <label>name: </label>
+ <input value = "{{hero.name}}"placeholder = "name">
+ <div>
`
})
export class AppComponent {
@@ -19,5 +22,4 @@
hero: Hero = {
id: 1,
name:'Spiderman' };
-
} |
474072f6beb7b48023cab1f08e6fcacb314d7bda | app/test/fixture-helper.ts | app/test/fixture-helper.ts | import * as path from 'path'
const fs = require('fs-extra')
const temp = require('temp').track()
/**
* Set up the named fixture repository to be used in a test.
*
* @returns The path to the set up fixture repository.
*/
export function setupFixtureRepository(repositoryName: string): string {
const testRepoFixturePath = path.join(__dirname, 'fixtures', repositoryName)
const testRepoPath = temp.mkdirSync('desktop-git-test-')
fs.copySync(testRepoFixturePath, testRepoPath)
fs.renameSync(path.join(testRepoPath, '_git'), path.join(testRepoPath, '.git'))
return testRepoPath
}
| import * as path from 'path'
const fs = require('fs-extra')
const temp = require('temp').track()
import { Repository } from '../src/models/repository'
import { GitProcess } from 'git-kitchen-sink'
/**
* Set up the named fixture repository to be used in a test.
*
* @returns The path to the set up fixture repository.
*/
export function setupFixtureRepository(repositoryName: string): string {
const testRepoFixturePath = path.join(__dirname, 'fixtures', repositoryName)
const testRepoPath = temp.mkdirSync('desktop-git-test-')
fs.copySync(testRepoFixturePath, testRepoPath)
fs.renameSync(path.join(testRepoPath, '_git'), path.join(testRepoPath, '.git'))
return testRepoPath
}
/**
* Initializes a new, empty, git repository at in a temporary location.
*/
export async function setupEmptyRepository(): Promise<Repository> {
const repoPath = temp.mkdirSync('desktop-empty-repo-')
await GitProcess.exec([ 'init' ], repoPath)
return new Repository(repoPath, -1, null)
}
| Add test helper for creating empty git repos | Add test helper for creating empty git repos
| TypeScript | mit | shiftkey/desktop,BugTesterTest/desktops,gengjiawen/desktop,hjobrien/desktop,BugTesterTest/desktops,shiftkey/desktop,artivilla/desktop,artivilla/desktop,desktop/desktop,BugTesterTest/desktops,say25/desktop,gengjiawen/desktop,desktop/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,shiftkey/desktop,hjobrien/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,gengjiawen/desktop,say25/desktop,BugTesterTest/desktops,j-f1/forked-desktop,artivilla/desktop,say25/desktop,hjobrien/desktop,kactus-io/kactus,desktop/desktop,gengjiawen/desktop,kactus-io/kactus,j-f1/forked-desktop,hjobrien/desktop | ---
+++
@@ -2,6 +2,9 @@
const fs = require('fs-extra')
const temp = require('temp').track()
+
+import { Repository } from '../src/models/repository'
+import { GitProcess } from 'git-kitchen-sink'
/**
* Set up the named fixture repository to be used in a test.
@@ -17,3 +20,13 @@
return testRepoPath
}
+
+/**
+ * Initializes a new, empty, git repository at in a temporary location.
+ */
+export async function setupEmptyRepository(): Promise<Repository> {
+ const repoPath = temp.mkdirSync('desktop-empty-repo-')
+ await GitProcess.exec([ 'init' ], repoPath)
+
+ return new Repository(repoPath, -1, null)
+} |
9e04d2718f7eec57b8dbe0ad7c5a0da3197db113 | step-release-vis/src/app/app-routing.module.ts | step-release-vis/src/app/app-routing.module.ts | import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {HomeComponent} from './components/home/home';
import {SvgGridComponent} from './components/grid/svg/svg';
import {CanvasGridComponent} from './components/grid/canvas/canvas';
const routes: Routes = [
{path: '', component: HomeComponent},
{path: 'svg', component: SvgGridComponent},
{path: 'canvas', component: CanvasGridComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
| import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {HomeComponent} from './components/home/home';
import {SvgGridComponent} from './components/grid/svg/svg';
import {CanvasGridComponent} from './components/grid/canvas/canvas';
import {EnvironmentComponent} from './components/environment/environment';
const routes: Routes = [
{path: '', component: HomeComponent},
{path: 'svg', component: SvgGridComponent},
{path: 'canvas', component: CanvasGridComponent},
{path: 'env', component: EnvironmentComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
| Add routing path for EnvironmentComponent. | Add routing path for EnvironmentComponent.
| TypeScript | apache-2.0 | googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020 | ---
+++
@@ -3,11 +3,13 @@
import {HomeComponent} from './components/home/home';
import {SvgGridComponent} from './components/grid/svg/svg';
import {CanvasGridComponent} from './components/grid/canvas/canvas';
+import {EnvironmentComponent} from './components/environment/environment';
const routes: Routes = [
{path: '', component: HomeComponent},
{path: 'svg', component: SvgGridComponent},
{path: 'canvas', component: CanvasGridComponent},
+ {path: 'env', component: EnvironmentComponent},
];
@NgModule({ |
86ab4917aadaebaa1de93c205e9700ed4d115b97 | dashboard/src/app/workspaces/workspace-details/warnings/workspace-warnings.controller.ts | dashboard/src/app/workspaces/workspace-details/warnings/workspace-warnings.controller.ts | /*
* Copyright (c) 2015-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
'use strict';
/**
* This class is handling the controller for the workspace runtime warnings container.
* @author Ann Shumilova
*/
export class WorkspaceWarningsController {
/**
* Workspace is provided by the scope.
*/
workspace: che.IWorkspace;
/**
* List of warnings.
*/
warnings: che.IWorkspaceWarning[];
/**
* Default constructor that is using resource
*/
constructor() {
this.warnings = [];
if (this.workspace && this.workspace.runtime) {
this.warnings = this.warnings.concat(this.workspace.runtime.warnings);
}
}
}
| /*
* Copyright (c) 2015-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
'use strict';
/**
* This class is handling the controller for the workspace runtime warnings container.
* @author Ann Shumilova
*/
export class WorkspaceWarningsController {
/**
* Workspace is provided by the scope.
*/
workspace: che.IWorkspace;
/**
* List of warnings.
*/
warnings: che.IWorkspaceWarning[];
/**
* Default constructor that is using resource
*/
constructor() {
this.warnings = [];
if (this.workspace && this.workspace.runtime && this.workspace.runtime.warnings) {
this.warnings = this.warnings.concat(this.workspace.runtime.warnings);
}
}
}
| Fix empty warning on workspace details page | Fix empty warning on workspace details page
Signed-off-by: Anna Shumilova <[email protected]>
| TypeScript | epl-1.0 | davidfestal/che,codenvy/che,davidfestal/che,davidfestal/che,codenvy/che,davidfestal/che,davidfestal/che,codenvy/che,davidfestal/che,codenvy/che,davidfestal/che,davidfestal/che,davidfestal/che,davidfestal/che | ---
+++
@@ -32,7 +32,7 @@
constructor() {
this.warnings = [];
- if (this.workspace && this.workspace.runtime) {
+ if (this.workspace && this.workspace.runtime && this.workspace.runtime.warnings) {
this.warnings = this.warnings.concat(this.workspace.runtime.warnings);
}
} |
70de342a58a2adb26ae7728f75730be75c973b4a | src/renderer/app/store/overlay.ts | src/renderer/app/store/overlay.ts | import { observable, computed } from 'mobx';
import { Overlay } from '../components/Overlay';
import * as React from 'react';
import { ipcRenderer } from 'electron';
export class OverlayStore {
public ref = React.createRef<Overlay>();
public scrollRef = React.createRef<HTMLDivElement>();
public bsRef: HTMLDivElement;
public inputRef = React.createRef<HTMLInputElement>();
@observable
private _visible = false;
@computed
public get visible() {
return this._visible;
}
public set visible(val: boolean) {
if (val === this._visible) return;
if (!val) {
setTimeout(() => {
ipcRenderer.send('browserview-show');
}, 200);
} else {
this.scrollRef.current.scrollTop = 0;
ipcRenderer.send('browserview-hide');
this.inputRef.current.focus();
}
this._visible = val;
}
}
| import { observable, computed } from 'mobx';
import { Overlay } from '../components/Overlay';
import * as React from 'react';
import { ipcRenderer } from 'electron';
import store from '.';
import { callBrowserViewMethod } from '~/shared/utils/browser-view';
export class OverlayStore {
public ref = React.createRef<Overlay>();
public scrollRef = React.createRef<HTMLDivElement>();
public bsRef: HTMLDivElement;
public inputRef = React.createRef<HTMLInputElement>();
@observable
private _visible = false;
@computed
public get visible() {
return this._visible;
}
public set visible(val: boolean) {
if (val === this._visible) return;
if (!val) {
setTimeout(() => {
ipcRenderer.send('browserview-show');
}, 200);
} else {
this.scrollRef.current.scrollTop = 0;
ipcRenderer.send('browserview-hide');
this.inputRef.current.focus();
callBrowserViewMethod(store.tabsStore.selectedTabId, 'getURL').then(
(url: string) => {
this.inputRef.current.value = url;
this.inputRef.current.select();
},
);
}
this._visible = val;
}
}
| Set input value to the current URL | Set input value to the current URL
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -2,6 +2,8 @@
import { Overlay } from '../components/Overlay';
import * as React from 'react';
import { ipcRenderer } from 'electron';
+import store from '.';
+import { callBrowserViewMethod } from '~/shared/utils/browser-view';
export class OverlayStore {
public ref = React.createRef<Overlay>();
@@ -28,6 +30,13 @@
this.scrollRef.current.scrollTop = 0;
ipcRenderer.send('browserview-hide');
this.inputRef.current.focus();
+
+ callBrowserViewMethod(store.tabsStore.selectedTabId, 'getURL').then(
+ (url: string) => {
+ this.inputRef.current.value = url;
+ this.inputRef.current.select();
+ },
+ );
}
this._visible = val; |
ae574dfcb65ab670a18047e9fb73abacf966cb99 | type/parse.d.ts | type/parse.d.ts | import {IncomingMessage} from "http"
import Body from "./Body"
export interface Options extends busboy.Options {
castTypes?: boolean
/**
* @deprecated Use castTypes option instead
*/
restoreTypes?: boolean
}
/**
* Promise-based wrapper around Busboy. Inspired by async-busboy.
* You'll get exactly what you've sent from your client app.
* All files and other fields in a single object.
*
* @param request HTTP request object
* @param options then-busboy options
*
* @return
*
* @api public
*
* @example
*
* ```js
* // Simplest Koa.js middleware:
* import {parse, Body} from "then-busboy"
*
* const toLowerCase = string => String.prototype.toLowerCase.call(string)
*
* const multipart = () => async (ctx, next) => {
* if (["post", "put"].includes(toLowerCase(ctx.method)) === false) {
* return next()
* }
*
* if (ctx.is("multipart/form-data") === false) {
* return next()
* }
*
* ctx.request.body = await busboy(ctx.req).then(Body.json)
*
* await next()
* }
*
* export default multipart
* ```
*/
export function parse<T extends Record<string, any>>(request: IncomingMessage, options?: Options): Promise<Body<T>>
export default parse
| import {IncomingMessage} from "http"
import Body from "./Body"
export interface Options extends busboy.Options {
castTypes?: boolean
/**
* @deprecated Use castTypes option instead
*/
restoreTypes?: boolean
}
/**
* Promise-based wrapper around Busboy. Inspired by async-busboy.
* You'll get exactly what you've sent from your client app.
* All files and other fields in a single object.
*
* @param request HTTP request object
* @param options then-busboy options
*
* @return
*
* @api public
*
* @example
*
* ```js
* // Simplest Koa.js middleware:
* import {parse, Body} from "then-busboy"
*
* const toLowerCase = string => String.prototype.toLowerCase.call(string)
*
* const multipart = () => async (ctx, next) => {
* if (["post", "put"].includes(toLowerCase(ctx.method)) === false) {
* return next()
* }
*
* if (ctx.is("multipart/form-data") === false) {
* return next()
* }
*
* ctx.request.body = await busboy(ctx.req).then(Body.json)
*
* await next()
* }
*
* export default multipart
* ```
*/
export function parse<T extends Record<string, any> = Record<string, any>>(request: IncomingMessage, options?: Options): Promise<Body<T>>
export default parse
| Make parse returning type parameter optional | Make parse returning type parameter optional
| TypeScript | mit | octet-stream/then-busboy,octet-stream/then-busboy | ---
+++
@@ -48,6 +48,6 @@
* export default multipart
* ```
*/
-export function parse<T extends Record<string, any>>(request: IncomingMessage, options?: Options): Promise<Body<T>>
+export function parse<T extends Record<string, any> = Record<string, any>>(request: IncomingMessage, options?: Options): Promise<Body<T>>
export default parse |
0d6691747590ca1dbe338f00f75e81beb606c7f9 | src/delir-core/src/index.ts | src/delir-core/src/index.ts | // @flow
import * as Project from './project/index'
import Renderer from './renderer/renderer'
import * as Services from './services'
import * as Exceptions from './exceptions'
import Point2D from './values/point-2d'
import Point3D from './values/point-3d'
import Size2D from './values/size-2d'
import Size3D from './values/size-3d'
import ColorRGB from './values/color-rgb'
import ColorRGBA from './values/color-rgba'
import Type, {TypeDescriptor, AnyParameterTypeDescriptor} from './plugin/type-descriptor'
import PluginBase from './plugin/plugin-base'
import RenderRequest from './renderer/render-request'
import PluginPreRenderRequest from './renderer/plugin-pre-rendering-request'
import LayerPluginBase from './plugin/layer-plugin-base'
import EffectPluginBase from './plugin/effect-plugin-base'
import PluginRegistry from './plugin/plugin-registry'
import * as ProjectHelper from './helper/project-helper'
export const Values = {
Point2D,
Point3D,
Size2D,
Size3D,
ColorRGB,
ColorRGBA,
}
export {
// Core
Project,
Renderer,
Services,
Exceptions,
// Structure
ColorRGB,
ColorRGBA,
// Plugins
Type,
TypeDescriptor,
PluginBase,
LayerPluginBase,
EffectPluginBase,
PluginPreRenderRequest,
RenderRequest,
PluginRegistry,
// import shorthand
ProjectHelper,
// Types
AnyParameterTypeDescriptor,
} | // @flow
import * as Project from './project/index'
import Renderer from './renderer/renderer'
import * as Services from './services'
import * as Exceptions from './exceptions'
import * as Values from './values'
import {ColorRGB, ColorRGBA} from './values'
import Type, {TypeDescriptor, AnyParameterTypeDescriptor} from './plugin/type-descriptor'
import PluginBase from './plugin/plugin-base'
import RenderRequest from './renderer/render-request'
import PluginPreRenderRequest from './renderer/plugin-pre-rendering-request'
import LayerPluginBase from './plugin/layer-plugin-base'
import EffectPluginBase from './plugin/effect-plugin-base'
import PluginRegistry from './plugin/plugin-registry'
import * as ProjectHelper from './helper/project-helper'
export {
// Core
Project,
Renderer,
Services,
Exceptions,
// Value Structure
Values,
/** @deprecated deprecated reference */
ColorRGB,
/** @deprecated deprecated reference */
ColorRGBA,
// Plugins
Type,
TypeDescriptor,
PluginBase,
LayerPluginBase,
EffectPluginBase,
PluginPreRenderRequest,
RenderRequest,
PluginRegistry,
// import shorthand
ProjectHelper,
// Types
AnyParameterTypeDescriptor,
} | Fix modules incompatible .Values exporting on delir-core | Fix modules incompatible .Values exporting on delir-core
| TypeScript | mit | Ragg-/Delir,Ragg-/Delir,Ragg-/Delir,Ragg-/Delir | ---
+++
@@ -3,13 +3,8 @@
import Renderer from './renderer/renderer'
import * as Services from './services'
import * as Exceptions from './exceptions'
-
-import Point2D from './values/point-2d'
-import Point3D from './values/point-3d'
-import Size2D from './values/size-2d'
-import Size3D from './values/size-3d'
-import ColorRGB from './values/color-rgb'
-import ColorRGBA from './values/color-rgba'
+import * as Values from './values'
+import {ColorRGB, ColorRGBA} from './values'
import Type, {TypeDescriptor, AnyParameterTypeDescriptor} from './plugin/type-descriptor'
import PluginBase from './plugin/plugin-base'
@@ -21,15 +16,6 @@
import * as ProjectHelper from './helper/project-helper'
-export const Values = {
- Point2D,
- Point3D,
- Size2D,
- Size3D,
- ColorRGB,
- ColorRGBA,
-}
-
export {
// Core
Project,
@@ -37,8 +23,11 @@
Services,
Exceptions,
- // Structure
+ // Value Structure
+ Values,
+ /** @deprecated deprecated reference */
ColorRGB,
+ /** @deprecated deprecated reference */
ColorRGBA,
// Plugins |
62a0bde9c22002a275c61963dcc743d189aa9622 | types/azure-publish-settings.d.ts | types/azure-publish-settings.d.ts | export interface Settings {
name: string;
kudu: {
website: string;
username: string;
password: string;
};
}
export function read(
publishSettingsPath: string,
callback: (err: any, settings: Settings) => void
): void;
export function readAsync(publishSettingsPath: string): Promise<Settings>;
| export interface Settings {
name: string;
kudu: {
website: string;
username: string;
password: string;
};
}
export function read(
publishSettingsPath: string,
callback: (err: unknown, settings: Settings) => void
): void;
export function readAsync(publishSettingsPath: string): Promise<Settings>;
| Convert one more 'any' to 'unknown' | Convert one more 'any' to 'unknown'
| TypeScript | mit | itsananderson/kudu-api,itsananderson/kudu-api | ---
+++
@@ -9,6 +9,6 @@
export function read(
publishSettingsPath: string,
- callback: (err: any, settings: Settings) => void
+ callback: (err: unknown, settings: Settings) => void
): void;
export function readAsync(publishSettingsPath: string): Promise<Settings>; |
0ef53062f084740021d9d076cd68e3be0b26a834 | frontend/src/app/troll-build/champions/champions.page.ts | frontend/src/app/troll-build/champions/champions.page.ts | import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Champion } from '@ltb-model/champion';
import { TitleService } from '@ltb-service/title.service';
import { ChampionsService } from './champions.service';
@Component({
selector: 'ltb-champions',
templateUrl: './champions.page.html',
styleUrls: ['./champions.page.scss']
})
export class ChampionsPage implements OnInit {
champions$: Observable<Champion[]>;
championTags$: Observable<string[]>;
championsSearchName: string;
championsFilterTag: string;
constructor(private championsService: ChampionsService, private title: TitleService) {}
ngOnInit() {
this.setTitle();
this.getChampions();
this.getChampionTags();
}
private setTitle(): void {
this.title.resetTitle();
}
getChampions(): void {
this.champions$ = this.championsService.getChampions();
}
getChampionTags(): void {
this.championTags$ = this.championsService.getChampionTags();
}
setChampionsFilterTag(selectedFilterTag: string): void {
if (this.championsFilterTag === selectedFilterTag) {
this.championsFilterTag = '';
} else {
this.championsFilterTag = selectedFilterTag;
}
}
trackByChampions(index: number, champion: Champion): number {
return champion.id;
}
}
| import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Champion } from '@ltb-model/champion';
import { TitleService } from '@ltb-service/title.service';
import { ChampionsService } from './champions.service';
@Component({
selector: 'ltb-champions',
templateUrl: './champions.page.html',
styleUrls: ['./champions.page.scss']
})
export class ChampionsPage implements OnInit {
champions$: Observable<Champion[]>;
championTags$: Observable<string[]>;
championsSearchName: string;
championsFilterTag: string;
constructor(private championsService: ChampionsService, private title: TitleService) {}
ngOnInit() {
this.setTitle();
this.getChampions();
this.getChampionTags();
}
private setTitle(): void {
this.title.resetTitle();
}
getChampions(): void {
this.champions$ = this.championsService.getChampions();
}
getChampionTags(): void {
this.championTags$ = this.championsService.getChampionTags();
}
setChampionsFilterTag(selectedFilterTag: string): void {
this.championsFilterTag = this.championsFilterTag === selectedFilterTag ? '' : selectedFilterTag;
}
trackByChampions(index: number, champion: Champion): number {
return champion.id;
}
}
| Replace if else with ternary | Replace if else with ternary
| TypeScript | mit | drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild | ---
+++
@@ -39,11 +39,7 @@
}
setChampionsFilterTag(selectedFilterTag: string): void {
- if (this.championsFilterTag === selectedFilterTag) {
- this.championsFilterTag = '';
- } else {
- this.championsFilterTag = selectedFilterTag;
- }
+ this.championsFilterTag = this.championsFilterTag === selectedFilterTag ? '' : selectedFilterTag;
}
trackByChampions(index: number, champion: Champion): number { |
1ae9f4941dc2f3a929acf8baef2c869407d3d7b4 | src/__tests__/database.spec.ts | src/__tests__/database.spec.ts | import { Database, DEFAULT_OPTIONS } from '../database';
import { Collection } from '../collection';
import { MockPersistor, MockPersistorFactory } from '../persistors/__mocks__/persistor.mock';
import { ICollection } from '../';
describe( 'Database', () => {
describe( 'constructor', () => {
it( 'should create a new instance with default options', () => {
const database = new Database();
expect(( database as any )._options ).toBe( DEFAULT_OPTIONS );
});
});
describe( 'collection', () => {
let factory: MockPersistorFactory;
let database: Database;
let collection: ICollection;
beforeEach(() => {
const persistor = new MockPersistor();
factory = { create: jest.fn().mockReturnValue( persistor ) };
database = new Database({ persistorFactory: factory });
collection = database.collection( 'col' );
});
it( 'should create a new collection if one does not exist with given name', () => {
expect( collection instanceof Collection ).toBeTruthy();
});
it( 'should return collection if one exists with given collection name', () => {
expect( database.collection( 'col' )).toBe( collection );
});
it( 'should always return the same collection instance for a given name', () => {
for ( let i = 0; i < 5; i++ ) {
expect( database.collection( 'col' )).toBe( collection );
}
});
it( 'should create a new persister with the collection name', () => {
expect( factory.create ).toHaveBeenCalledWith( 'col' );
});
});
});
| import { Database, DEFAULT_OPTIONS } from '../database';
import { Collection } from '../collection';
import { MockPersistor, MockPersistorFactory } from '../persistors/__mocks__/persistor.mock';
import { ICollection, IPersistorFactory } from '../';
describe( 'Database', () => {
describe( 'constructor', () => {
it( 'should create a new instance with default options', () => {
const database = new Database();
expect(( database as any )._options ).toBe( DEFAULT_OPTIONS );
});
});
describe( 'collection', () => {
let factory: IPersistorFactory;
let database: Database;
let collection: ICollection;
beforeEach(() => {
const persistor = new MockPersistor();
factory = { create: jest.fn().mockReturnValue( persistor ) };
database = new Database({ persistorFactory: factory });
collection = database.collection( 'col' );
});
it( 'should create a new collection if one does not exist with given name', () => {
expect( collection instanceof Collection ).toBeTruthy();
});
it( 'should return collection if one exists with given collection name', () => {
expect( database.collection( 'col' )).toBe( collection );
});
it( 'should always return the same collection instance for a given name', () => {
for ( let i = 0; i < 5; i++ ) {
expect( database.collection( 'col' )).toBe( collection );
}
});
it( 'should create a new persister with the collection name', () => {
expect( factory.create ).toHaveBeenCalledWith( 'col' );
});
});
});
| Use interface type for mock factory | Use interface type for mock factory
| TypeScript | mit | Cinergix/rxdata,Cinergix/rxdata | ---
+++
@@ -1,7 +1,7 @@
import { Database, DEFAULT_OPTIONS } from '../database';
import { Collection } from '../collection';
import { MockPersistor, MockPersistorFactory } from '../persistors/__mocks__/persistor.mock';
-import { ICollection } from '../';
+import { ICollection, IPersistorFactory } from '../';
describe( 'Database', () => {
describe( 'constructor', () => {
@@ -12,7 +12,7 @@
});
describe( 'collection', () => {
- let factory: MockPersistorFactory;
+ let factory: IPersistorFactory;
let database: Database;
let collection: ICollection;
|
36d254626906a89c0c7ba918df0eceb5a8ed8e1d | packages/lesswrong/components/tagging/EditTagsDialog.tsx | packages/lesswrong/components/tagging/EditTagsDialog.tsx | import React from 'react';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
const EditTagsDialog = ({post, onClose }: {
post: PostsBase,
onClose: ()=>void
}) => {
const { FooterTagList } = Components
return <Dialog open={true} onClose={onClose} fullWidth maxWidth="sm" disableEnforceFocus>
<DialogTitle>{post.title}</DialogTitle>
<DialogContent>
<FooterTagList post={post}/>
</DialogContent>
</Dialog>
}
const EditTagsDialogComponent = registerComponent('EditTagsDialog', EditTagsDialog);
declare global {
interface ComponentTypes {
EditTagsDialog: typeof EditTagsDialogComponent
}
}
| import React from 'react';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import { AnalyticsContext } from "../../lib/analyticsEvents";
const EditTagsDialog = ({post, onClose }: {
post: PostsBase,
onClose: ()=>void
}) => {
const { FooterTagList } = Components
return <Dialog open={true} onClose={onClose} fullWidth maxWidth="sm" disableEnforceFocus>
<AnalyticsContext pageSectionContext="editTagsDialog">
<DialogTitle>{post.title}</DialogTitle>
<DialogContent>
<FooterTagList post={post}/>
</DialogContent>
</AnalyticsContext>
</Dialog>
}
const EditTagsDialogComponent = registerComponent('EditTagsDialog', EditTagsDialog);
declare global {
interface ComponentTypes {
EditTagsDialog: typeof EditTagsDialogComponent
}
}
| Add contextTracking to EditTags dialog | Add contextTracking to EditTags dialog
| TypeScript | mit | Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope | ---
+++
@@ -3,17 +3,20 @@
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
+import { AnalyticsContext } from "../../lib/analyticsEvents";
-const EditTagsDialog = ({post, onClose }: {
- post: PostsBase,
+const EditTagsDialog = ({post, onClose }: {
+ post: PostsBase,
onClose: ()=>void
}) => {
const { FooterTagList } = Components
return <Dialog open={true} onClose={onClose} fullWidth maxWidth="sm" disableEnforceFocus>
- <DialogTitle>{post.title}</DialogTitle>
- <DialogContent>
- <FooterTagList post={post}/>
- </DialogContent>
+ <AnalyticsContext pageSectionContext="editTagsDialog">
+ <DialogTitle>{post.title}</DialogTitle>
+ <DialogContent>
+ <FooterTagList post={post}/>
+ </DialogContent>
+ </AnalyticsContext>
</Dialog>
}
|
f4ad9916e6969cc89dd8d48be4b5850c7baf1b4a | test/helper/port-manager.ts | test/helper/port-manager.ts | import getPort, { makeRange } from 'get-port';
/**
* For easier debugging, we increase the port each time
* to ensure that no port is reused in the tests.
*/
let startPort = 18669;
const PORT_MAX = 65535;
/**
* Returns an unused port.
* Used to ensure that different tests
* do not accidentiall use the same port.
*/
export async function nextPort(): Promise<number> {
startPort++;
const port = await getPort({
port: makeRange(startPort, PORT_MAX),
host: '0.0.0.0',
});
return port;
}
| import getPort, { makeRange } from 'get-port';
/**
* For easier debugging, we increase the port each time
* to ensure that no port is reused in the tests.
*/
let startPort = 18669;
const PORT_MAX = 65535;
/**
* Returns an unused port.
* Used to ensure that different tests
* do not accidentiall use the same port.
*/
export async function nextPort(): Promise<number> {
const port = await getPort({
port: makeRange(startPort, PORT_MAX),
host: '0.0.0.0',
});
startPort = port + 1;
return port;
}
| FIX do not reuse port | FIX do not reuse port
| TypeScript | apache-2.0 | pubkey/rxdb,pubkey/rxdb,pubkey/rxdb,pubkey/rxdb,pubkey/rxdb | ---
+++
@@ -14,11 +14,10 @@
* do not accidentiall use the same port.
*/
export async function nextPort(): Promise<number> {
- startPort++;
-
const port = await getPort({
port: makeRange(startPort, PORT_MAX),
host: '0.0.0.0',
});
+ startPort = port + 1;
return port;
} |
331f79629e9eb17259a83ae5ef2e5ae64fc865ff | src/app/shared/services/auth.service.ts | src/app/shared/services/auth.service.ts | import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {JwtHelperService} from '@auth0/angular-jwt';
import {ProfileService} from '@shared/services/profile.service';
@Injectable()
export class AuthService implements CanActivate {
helper = new JwtHelperService();
constructor(private router: Router, private profileService: ProfileService) {
}
async loggedIn() {
const token = localStorage.getItem('id_token');
if (token != null) {
const expired = this.helper.decodeToken(token).expires;
const isNotExpired = new Date().getMilliseconds() < expired;
if (isNotExpired && this.profileService.getProfileFromLocal() == null) {
const profile = await this.profileService.getProfile().toPromise();
this.profileService.setProfile(profile);
}
return isNotExpired;
}
return false;
}
async canActivate() {
if (await this.loggedIn()) {
return true;
} else {
this.router.navigate(['unauthorized']);
return false;
}
}
}
| import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {JwtHelperService} from '@auth0/angular-jwt';
import {ProfileService} from '@shared/services/profile.service';
@Injectable()
export class AuthService implements CanActivate {
helper = new JwtHelperService();
constructor(private router: Router, private profileService: ProfileService) {
}
async loggedIn() {
const token = localStorage.getItem('id_token');
if (token != null) {
const expired = this.helper.decodeToken(token).expires;
const isNotExpired = new Date().getMilliseconds() < expired;
let profile = this.profileService.getProfileFromLocal();
if (isNotExpired && (profile == null || profile.userId == null)) {
profile = await this.profileService.getProfile().toPromise();
this.profileService.setProfile(profile);
}
return isNotExpired;
}
return false;
}
async canActivate() {
if (await this.loggedIn()) {
return true;
} else {
this.router.navigate(['unauthorized']);
return false;
}
}
}
| Fix auth not working with the old cache | Fix auth not working with the old cache
| TypeScript | unknown | BD2K-DDI/ddi-web-app,OmicsDI/ddi-web-app,BD2K-DDI/ddi-web-app,OmicsDI/ddi-web-app,OmicsDI/ddi-web-app | ---
+++
@@ -16,8 +16,9 @@
if (token != null) {
const expired = this.helper.decodeToken(token).expires;
const isNotExpired = new Date().getMilliseconds() < expired;
- if (isNotExpired && this.profileService.getProfileFromLocal() == null) {
- const profile = await this.profileService.getProfile().toPromise();
+ let profile = this.profileService.getProfileFromLocal();
+ if (isNotExpired && (profile == null || profile.userId == null)) {
+ profile = await this.profileService.getProfile().toPromise();
this.profileService.setProfile(profile);
}
return isNotExpired; |
fd65130784bc322ad5bd0ae4010f3de05ba0e90d | src/routeGeneration/tsoa-route.ts | src/routeGeneration/tsoa-route.ts | import { Tsoa } from './../metadataGeneration/tsoa';
/**
* For Swagger, additionalProperties is implicitly allowed. So use this function to clarify that undefined should be associated with allowing additional properties
* @param test if this is undefined then you should interpret it as a "yes"
*/
export function isDefaultForAdditionalPropertiesAllowed(test: TsoaRoute.ModelSchema['additionalProperties']): test is undefined {
return test === undefined;
}
export namespace TsoaRoute {
export interface Models {
[name: string]: ModelSchema;
}
export interface ModelSchema {
enums?: string[] | number[];
properties?: { [name: string]: PropertySchema };
additionalProperties?: boolean | PropertySchema;
}
export type ValidatorSchema = Tsoa.Validators;
export interface PropertySchema {
dataType?: Tsoa.TypeStringLiteral;
ref?: string;
required?: boolean;
array?: PropertySchema;
enums?: string[];
subSchemas?: PropertySchema[];
validators?: ValidatorSchema;
default?: any;
additionalProperties?: boolean | PropertySchema;
nestedProperties?: { [name: string]: PropertySchema };
}
export interface ParameterSchema extends PropertySchema {
name: string;
in: string;
}
export interface Security {
[key: string]: string[];
}
}
| import { Tsoa } from './../metadataGeneration/tsoa';
/**
* For Swagger, additionalProperties is implicitly allowed. So use this function to clarify that undefined should be associated with allowing additional properties
* @param test if this is undefined then you should interpret it as a "yes"
*/
export function isDefaultForAdditionalPropertiesAllowed(test: TsoaRoute.ModelSchema['additionalProperties']): test is undefined {
return test === undefined;
}
export namespace TsoaRoute {
export interface Models {
[name: string]: ModelSchema;
}
export interface ModelSchema {
enums?: string[] | number[];
properties?: { [name: string]: PropertySchema };
additionalProperties?: boolean | PropertySchema;
}
export type ValidatorSchema = Tsoa.Validators;
export interface PropertySchema {
dataType?: Tsoa.TypeStringLiteral;
ref?: string;
required?: boolean;
array?: PropertySchema;
enums?: string[];
subSchemas?: PropertySchema[];
validators?: ValidatorSchema;
default?: any;
additionalProperties?: boolean | PropertySchema;
nestedProperties?: { [name: string]: PropertySchema };
}
export interface ParameterSchema extends PropertySchema {
name: string;
in: string;
}
export interface Security {
[key: string]: string[];
}
}
| Convert tabs to spaces in ModelSchema | Convert tabs to spaces in ModelSchema | TypeScript | mit | lukeautry/tsoa,andreasrueedlinger/tsoa,andreasrueedlinger/tsoa,lukeautry/tsoa | ---
+++
@@ -13,9 +13,9 @@
[name: string]: ModelSchema;
}
- export interface ModelSchema {
- enums?: string[] | number[];
- properties?: { [name: string]: PropertySchema };
+ export interface ModelSchema {
+ enums?: string[] | number[];
+ properties?: { [name: string]: PropertySchema };
additionalProperties?: boolean | PropertySchema;
}
|
96d2669bbbd4bbe4f39ea9f04c543fd823cae1bd | src/chrome/WarningEmployee.tsx | src/chrome/WarningEmployee.tsx | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {styled, FlexColumn, Text, Button, colors} from 'flipper';
import React from 'react';
const Container = styled(FlexColumn)({
height: '100%',
width: '100%',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: colors.light02,
});
const Box = styled(FlexColumn)({
justifyContent: 'center',
alignItems: 'center',
background: colors.white,
borderRadius: 10,
boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
paddingBottom: 16,
});
const Warning = styled(Text)({
fontSize: 24,
fontWeight: 300,
textAlign: 'center',
margin: 16,
});
const AckButton = styled(Button)({
type: 'warning',
});
export default function WarningEmployee(props: {
onClick: (event: React.MouseEvent) => any;
}) {
return (
<Container>
<Box>
<Warning>
You are using the open-source version of Flipper. You will get access
to more plugins. To use the internal version, please install it from
Managed Software Center
</Warning>
<AckButton onClick={props.onClick}>Okay</AckButton>
</Box>
</Container>
);
}
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {styled, FlexColumn, Text, Button, colors} from 'flipper';
import React from 'react';
const Container = styled(FlexColumn)({
height: '100%',
width: '100%',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: colors.light02,
});
const Box = styled(FlexColumn)({
justifyContent: 'center',
alignItems: 'center',
background: colors.white,
borderRadius: 10,
boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
paddingBottom: 16,
});
const Warning = styled(Text)({
fontSize: 24,
fontWeight: 300,
textAlign: 'center',
margin: 16,
});
const AckButton = styled(Button)({
type: 'warning',
});
export default function WarningEmployee(props: {
onClick: (event: React.MouseEvent) => any;
}) {
return (
<Container>
<Box>
<Warning>
You are using the open-source version of Flipper. Install the internal
build from Managed Software Center to get access to more plugins.
</Warning>
<AckButton onClick={props.onClick}>Okay</AckButton>
</Box>
</Container>
);
}
| Improve FB employee version warning | Improve FB employee version warning
Summary: Wording was a bit strange.
Reviewed By: passy
Differential Revision: D18063264
fbshipit-source-id: 29fb6f16ba6246f307d956a0309dbd153878a251
| TypeScript | mit | facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper | ---
+++
@@ -46,9 +46,8 @@
<Container>
<Box>
<Warning>
- You are using the open-source version of Flipper. You will get access
- to more plugins. To use the internal version, please install it from
- Managed Software Center
+ You are using the open-source version of Flipper. Install the internal
+ build from Managed Software Center to get access to more plugins.
</Warning>
<AckButton onClick={props.onClick}>Okay</AckButton>
</Box> |
6377170e30e76852731f38cb83ff27d85301e706 | packages/cli/src/generate/generators/controller/create-controller.ts | packages/cli/src/generate/generators/controller/create-controller.ts | // std
import { existsSync } from 'fs';
// FoalTS
import { Generator, getNames } from '../../utils';
import { registerController } from './register-controller';
export type ControllerType = 'Empty'|'REST';
export function createController({ name, type, register }: { name: string, type: ControllerType, register: boolean }) {
const names = getNames(name);
const fileName = `${names.kebabName}.controller.ts`;
const specFileName = `${names.kebabName}.controller.spec.ts`;
let root = '';
if (existsSync('src/app/controllers')) {
root = 'src/app/controllers';
} else if (existsSync('controllers')) {
root = 'controllers';
}
const generator = new Generator('controller', root)
.renderTemplate(`controller.${type.toLowerCase()}.ts`, names, fileName)
.updateFile('index.ts', content => {
content += `export { ${names.upperFirstCamelName}Controller } from './${names.kebabName}.controller';\n`;
return content;
}, { allowFailure: true });
if (register) {
const path = `/${names.kebabName}${type === 'REST' ? 's' : ''}`;
generator
.updateFile('../app.controller.ts', content => {
return registerController(content, `${names.upperFirstCamelName}Controller`, path);
}, { allowFailure: true });
}
if (type === 'Empty') {
generator
.renderTemplate('controller.spec.empty.ts', names, specFileName);
}
}
| // std
import { existsSync } from 'fs';
// FoalTS
import { Generator, getNames } from '../../utils';
import { registerController } from './register-controller';
export type ControllerType = 'Empty'|'REST'|'GraphQL'|'Login';
export function createController({ name, type, register }: { name: string, type: ControllerType, register: boolean }) {
const names = getNames(name);
const fileName = `${names.kebabName}.controller.ts`;
const specFileName = `${names.kebabName}.controller.spec.ts`;
let root = '';
if (existsSync('src/app/controllers')) {
root = 'src/app/controllers';
} else if (existsSync('controllers')) {
root = 'controllers';
}
const generator = new Generator('controller', root)
.renderTemplate(`controller.${type.toLowerCase()}.ts`, names, fileName)
.updateFile('index.ts', content => {
content += `export { ${names.upperFirstCamelName}Controller } from './${names.kebabName}.controller';\n`;
return content;
}, { allowFailure: true });
if (register) {
const path = `/${names.kebabName}${type === 'REST' ? 's' : ''}`;
generator
.updateFile('../app.controller.ts', content => {
return registerController(content, `${names.upperFirstCamelName}Controller`, path);
}, { allowFailure: true });
}
if (type === 'Empty') {
generator
.renderTemplate('controller.spec.empty.ts', names, specFileName);
}
}
| Revert "[CLI] Remove legacy type" | Revert "[CLI] Remove legacy type"
This reverts commit 4089ae79caf65c5014c75a9b43fe2229ea55b954.
| TypeScript | mit | FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal | ---
+++
@@ -5,7 +5,7 @@
import { Generator, getNames } from '../../utils';
import { registerController } from './register-controller';
-export type ControllerType = 'Empty'|'REST';
+export type ControllerType = 'Empty'|'REST'|'GraphQL'|'Login';
export function createController({ name, type, register }: { name: string, type: ControllerType, register: boolean }) {
const names = getNames(name); |
69508f4a0141f3326a17c3b1dc09c8ab4e35d4d1 | src/server/helpers/check_has_credits.ts | src/server/helpers/check_has_credits.ts | import { NextFunction, Request, Response } from "express";
import { errors, PlanTypes } from "voluble-common";
import { OrgManager } from "../../org-manager";
import { ExpressMiddleware } from "./express_req_res_next";
export function checkHasCredits(credits_required: number): ExpressMiddleware {
return async (req: Request, res: Response, next: NextFunction) => {
const sub_id = req['user'].sub
if (sub_id == `${process.env.AUTH0_TEST_CLIENT_ID}@clients`) {
return next() // test client, let it do everything
} else {
try {
const org = await OrgManager.getOrganizationById(req['user'].organization)
if (org.plan == PlanTypes.PAY_IN_ADVANCE && org.credits >= credits_required) {
return next()
} else {
throw new errors.NotEnoughCreditsError('The Organization does not have enough credits for this operation')
}
} catch (e) {
const serialized_err = req.app.locals.serializer.serializeError(e)
if (e instanceof errors.NotEnoughCreditsError) {
res.status(402).json(serialized_err)
} else { next(e) }
}
}
}
} | import { NextFunction, Request, Response } from "express";
import { errors, PlanTypes } from "voluble-common";
import { OrgManager } from "../../org-manager";
import { ExpressMiddleware } from "./express_req_res_next";
export function checkHasCredits(credits_required: number): ExpressMiddleware {
return async (req: Request, res: Response, next: NextFunction) => {
const sub_id = req['user'].sub
if (sub_id == `${process.env.AUTH0_TEST_CLIENT_ID}@clients`) {
return next() // test client, let it do everything
} else {
try {
const org = await OrgManager.getOrganizationById(req['user'].organization)
if (org.plan == PlanTypes.PAYG && org.credits < credits_required) {
throw new errors.NotEnoughCreditsError('The Organization does not have enough credits for this operation')
} else {
return next()
}
} catch (e) {
const serialized_err = req.app.locals.serializer.serializeError(e)
if (e instanceof errors.NotEnoughCreditsError) {
res.status(402).json(serialized_err)
} else { next(e) }
}
}
}
} | Correct credit-checking behaviour on message send | Correct credit-checking behaviour on message send
| TypeScript | mit | calmcl1/voluble,calmcl1/voluble | ---
+++
@@ -13,10 +13,10 @@
try {
const org = await OrgManager.getOrganizationById(req['user'].organization)
- if (org.plan == PlanTypes.PAY_IN_ADVANCE && org.credits >= credits_required) {
+ if (org.plan == PlanTypes.PAYG && org.credits < credits_required) {
+ throw new errors.NotEnoughCreditsError('The Organization does not have enough credits for this operation')
+ } else {
return next()
- } else {
- throw new errors.NotEnoughCreditsError('The Organization does not have enough credits for this operation')
}
} catch (e) {
const serialized_err = req.app.locals.serializer.serializeError(e) |
ecfda7cccf6d09df0841ab7ed9005d380f1076d6 | src/menu/bookmarks/components/TreeBar/styles.ts | src/menu/bookmarks/components/TreeBar/styles.ts | import styled from 'styled-components';
import opacity from '../../../../shared/defaults/opacity';
export const Root = styled.div`
width: 100%;
height: 56px;
display: flex;
align-items: center;
padding-left: 32px;
border-bottom: 1px solid rgba(0, 0, 0, ${opacity.light.dividers});
`;
| import styled from 'styled-components';
import opacity from '../../../../shared/defaults/opacity';
export const Root = styled.div`
width: 100%;
height: 56px;
display: flex;
align-items: center;
padding-left: 32px;
border-bottom: 1px solid rgba(0, 0, 0, ${opacity.light.dividers});
overflow: hidden;
`;
| Fix text moving out of TreeBar in bookmarks | :sparkles: Fix text moving out of TreeBar in bookmarks
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -9,4 +9,5 @@
align-items: center;
padding-left: 32px;
border-bottom: 1px solid rgba(0, 0, 0, ${opacity.light.dividers});
+ overflow: hidden;
`; |
9a3a59270adf9ee9acc292811637e73a92956039 | app/app.module.ts | app/app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
| import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail.component';
@NgModule({
imports: [ BrowserModule, FormsModule],
declarations: [ AppComponent, HeroDetailComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
| Add HeroDetailComponent to the NgModule | Add HeroDetailComponent to the NgModule
| TypeScript | mit | amalshehu/angular-tour-of-heroes,amalshehu/angular-tour-of-heroes,amalshehu/angular-tour-of-heroes | ---
+++
@@ -2,9 +2,11 @@
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
+import { HeroDetailComponent } from './hero-detail.component';
+
@NgModule({
imports: [ BrowserModule, FormsModule],
- declarations: [ AppComponent ],
+ declarations: [ AppComponent, HeroDetailComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { } |
010938faf45d48325259bc4662311d0d42b81ed1 | app/vue/src/client/preview/types-6-0.ts | app/vue/src/client/preview/types-6-0.ts | import { Component, AsyncComponent } from 'vue';
import { Args as DefaultArgs, Annotations, BaseMeta, BaseStory } from '@storybook/addons';
import { StoryFnVueReturnType } from './types';
export { Args, ArgTypes, Parameters, StoryContext } from '@storybook/addons';
type VueComponent = Component<any, any, any, any> | AsyncComponent<any, any, any, any>;
type VueReturnType = StoryFnVueReturnType;
/**
* Metadata to configure the stories for a component.
*
* @see [Default export](https://storybook.js.org/docs/formats/component-story-format/#default-export)
*/
export type Meta<Args = DefaultArgs> = BaseMeta<VueComponent> & Annotations<Args, VueReturnType>;
/**
* Story function that represents a component example.
*
* @see [Named Story exports](https://storybook.js.org/docs/formats/component-story-format/#named-story-exports)
*/
export type Story<Args = DefaultArgs> = BaseStory<Args, VueReturnType> &
Annotations<Args, VueReturnType>;
| import { Component, AsyncComponent } from 'vue';
import { Args as DefaultArgs, Annotations, BaseMeta, BaseStory } from '@storybook/addons';
import { StoryFnVueReturnType } from './types';
export type { Args, ArgTypes, Parameters, StoryContext } from '@storybook/addons';
type VueComponent = Component<any, any, any, any> | AsyncComponent<any, any, any, any>;
type VueReturnType = StoryFnVueReturnType;
/**
* Metadata to configure the stories for a component.
*
* @see [Default export](https://storybook.js.org/docs/formats/component-story-format/#default-export)
*/
export type Meta<Args = DefaultArgs> = BaseMeta<VueComponent> & Annotations<Args, VueReturnType>;
/**
* Story function that represents a component example.
*
* @see [Named Story exports](https://storybook.js.org/docs/formats/component-story-format/#named-story-exports)
*/
export type Story<Args = DefaultArgs> = BaseStory<Args, VueReturnType> &
Annotations<Args, VueReturnType>;
| Fix type export in vue types | Fix type export in vue types
| TypeScript | mit | kadirahq/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -2,7 +2,7 @@
import { Args as DefaultArgs, Annotations, BaseMeta, BaseStory } from '@storybook/addons';
import { StoryFnVueReturnType } from './types';
-export { Args, ArgTypes, Parameters, StoryContext } from '@storybook/addons';
+export type { Args, ArgTypes, Parameters, StoryContext } from '@storybook/addons';
type VueComponent = Component<any, any, any, any> | AsyncComponent<any, any, any, any>;
type VueReturnType = StoryFnVueReturnType; |
4a1490453d45521f64e5b24cd1af61f61cce6902 | test/site-tests.ts | test/site-tests.ts | require('mocha');
require('chai').should();
import { sites, SiteOptions } from '../';
describe('site', () => {
it('can be retrieved after being created', async () => {
let exists = await sites.exists('TestSite');
if (exists) {
await sites.remove('TestSite');
}
await sites.add({
name: 'TestSite',
protocol: 'http',
host: 'testsiteurl',
port: 12345,
path: 'C:\\inetpub\\wwwroot'
} as SiteOptions);
let site = await sites.get('TestSite');
site.name.should.equal('TestSite');
site.bindings.should.equal('http/*:12345:testsiteurl');
});
});
| require('mocha');
require('chai').should();
import * as uuid from 'uuid';
import { sites, SiteOptions } from '../';
describe('site', () => {
it('can be retrieved after being created', async () => {
let siteName = uuid();
try {
await sites.add({
name: siteName,
protocol: 'http',
host: siteName,
port: 80,
path: 'C:\\inetpub\\wwwroot'
} as SiteOptions);
let site = await sites.get(siteName);
site.name.should.equal(siteName);
site.bindings.should.equal(`http/*:80:${siteName}`);
} finally {
if (await sites.exists(siteName)) {
await sites.remove(siteName);
}
}
});
});
| Make test cleanup after itself | Make test cleanup after itself
| TypeScript | mit | ChristopherHaws/node-iis-manager | ---
+++
@@ -1,25 +1,29 @@
require('mocha');
require('chai').should();
+import * as uuid from 'uuid';
import { sites, SiteOptions } from '../';
describe('site', () => {
it('can be retrieved after being created', async () => {
- let exists = await sites.exists('TestSite');
- if (exists) {
- await sites.remove('TestSite');
+ let siteName = uuid();
+
+ try {
+ await sites.add({
+ name: siteName,
+ protocol: 'http',
+ host: siteName,
+ port: 80,
+ path: 'C:\\inetpub\\wwwroot'
+ } as SiteOptions);
+
+ let site = await sites.get(siteName);
+
+ site.name.should.equal(siteName);
+ site.bindings.should.equal(`http/*:80:${siteName}`);
+ } finally {
+ if (await sites.exists(siteName)) {
+ await sites.remove(siteName);
+ }
}
-
- await sites.add({
- name: 'TestSite',
- protocol: 'http',
- host: 'testsiteurl',
- port: 12345,
- path: 'C:\\inetpub\\wwwroot'
- } as SiteOptions);
-
- let site = await sites.get('TestSite');
-
- site.name.should.equal('TestSite');
- site.bindings.should.equal('http/*:12345:testsiteurl');
});
}); |
5c1541c31ac88a7f38a49e27eb5707756377386b | types/index.d.ts | types/index.d.ts | declare class OrderedMap<T = any> {
private constructor(content: Array<string | T>)
get(key: string): T | undefined
update(key: string, value: T, newKey?: string): OrderedMap<T>
remove(key: string): OrderedMap<T>
addToStart(key: string, value: T): OrderedMap<T>
addToEnd(key: string, value: T): OrderedMap<T>
addBefore(place: string, key: string, value: T): OrderedMap<T>
forEach(fn: (key: string, value: T) => any): void
prepend(map: MapLike<T>): OrderedMap<T>
append(map: MapLike<T>): OrderedMap<T>
subtract(map: MapLike<T>): OrderedMap<T>
readonly size: number
static from<T>(map: MapLike<T>): OrderedMap<T>
}
type MapLike<T = any> = Record<string, T> | OrderedMap<T>
export = OrderedMap
| declare class OrderedMap<T = any> {
private constructor(content: Array<string | T>)
get(key: string): T | undefined
update(key: string, value: T, newKey?: string): OrderedMap<T>
remove(key: string): OrderedMap<T>
addToStart(key: string, value: T): OrderedMap<T>
addToEnd(key: string, value: T): OrderedMap<T>
addBefore(place: string, key: string, value: T): OrderedMap<T>
forEach(fn: (key: string, value: T) => any): void
prepend(map: MapLike<T>): OrderedMap<T>
append(map: MapLike<T>): OrderedMap<T>
subtract(map: MapLike<T>): OrderedMap<T>
readonly size: number
static from<T>(map: MapLike<T>): OrderedMap<T>
}
type MapLike<T = any> = Record<string, T> | OrderedMap<T>
export default OrderedMap
| Use ES-style export in TypeScript file | Use ES-style export in TypeScript file
| TypeScript | mit | marijnh/orderedmap | ---
+++
@@ -28,4 +28,4 @@
type MapLike<T = any> = Record<string, T> | OrderedMap<T>
-export = OrderedMap
+export default OrderedMap |
ec20ef1cf72c24b0e3e0bec29ab3630e900beefb | source/navigation/track.ts | source/navigation/track.ts | import * as Sentry from '@sentry/react-native'
import type {NavigationState} from 'react-navigation'
// gets the current screen from navigation state
function getCurrentRouteName(navigationState: NavigationState): ?string {
if (!navigationState) {
return null
}
const route = navigationState.routes[navigationState.index]
// dive into nested navigators
if (route.routes) {
return getCurrentRouteName(route)
}
return route.routeName
}
export function trackScreenChanges(
prevState: NavigationState,
currentState: NavigationState,
) {
const currentScreen = getCurrentRouteName(currentState)
const prevScreen = getCurrentRouteName(prevState)
if (!currentScreen) {
return
}
if (currentScreen !== prevScreen) {
Sentry.addBreadcrumb({
message: `Navigated to ${currentScreen}`,
category: 'navigation',
data: {
prev: prevScreen,
},
})
}
}
| import * as Sentry from '@sentry/react-native'
import type {NavigationState} from 'react-navigation'
// gets the current screen from navigation state
function getCurrentRouteName(navigationState: NavigationState): ?string {
if (!navigationState) {
return null
}
const route = navigationState.routes[navigationState.index]
// dive into nested navigators
if (route.routes) {
return getCurrentRouteName(route)
}
return route.routeName
}
export function trackScreenChanges(
prevState: NavigationState,
currentState: NavigationState,
): void {
const currentScreen = getCurrentRouteName(currentState)
const prevScreen = getCurrentRouteName(prevState)
if (!currentScreen) {
return
}
if (currentScreen !== prevScreen) {
Sentry.addBreadcrumb({
message: `Navigated to ${currentScreen}`,
category: 'navigation',
data: {
prev: prevScreen,
},
})
}
}
| Add an explicit return type to module boundary function | navigation: Add an explicit return type to module boundary function
Signed-off-by: Kristofer Rye <[email protected]>
| TypeScript | agpl-3.0 | StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native | ---
+++
@@ -17,7 +17,7 @@
export function trackScreenChanges(
prevState: NavigationState,
currentState: NavigationState,
-) {
+): void {
const currentScreen = getCurrentRouteName(currentState)
const prevScreen = getCurrentRouteName(prevState)
|
e2d791cf867327681c0c1211c0967ef7e9683c45 | src/script/player.ts | src/script/player.ts | export class Player {
constructor(protected gameState: Server.GameState, protected client: Server.Client) {
}
get access() {
return this.client.account.access;
}
get location() {
return this.client.character.location;
}
warp(map: number, x: number, y: number) {
this.gameState.managers.player.warp(this.client, { map, x, y });
}
}
| import Location = Odyssey.Location
export class Player {
constructor(protected gameState: Server.GameState, protected client: Server.Client) {
}
get access() {
return this.client.account.access;
}
get location() {
return this.client.character.location;
}
warp(location: Odyssey.Location);
warp(map: number, x: number, y: number);
warp(map: number | Odyssey.Location, x?: number, y?: number) {
if (map instanceof Location) {
this.gameState.managers.player.warp(this.client, <Location>map);
} else if (typeof map === 'number') {
this.gameState.managers.player.warp(this.client, { map, x, y });
}
}
}
| Set Script Warp to take Location or map,x,y | Set Script Warp to take Location or map,x,y
| TypeScript | mit | OdysseyClassicHistoryBook/odyssey-2-server,OdysseyClassicHistoryBook/odyssey-2-server | ---
+++
@@ -1,3 +1,4 @@
+import Location = Odyssey.Location
export class Player {
constructor(protected gameState: Server.GameState, protected client: Server.Client) {
}
@@ -10,7 +11,13 @@
return this.client.character.location;
}
- warp(map: number, x: number, y: number) {
- this.gameState.managers.player.warp(this.client, { map, x, y });
+ warp(location: Odyssey.Location);
+ warp(map: number, x: number, y: number);
+ warp(map: number | Odyssey.Location, x?: number, y?: number) {
+ if (map instanceof Location) {
+ this.gameState.managers.player.warp(this.client, <Location>map);
+ } else if (typeof map === 'number') {
+ this.gameState.managers.player.warp(this.client, { map, x, y });
+ }
}
} |
ac8b2632d2e7adf848399cd8ce5935f963cfdeb6 | src/functions/dPath.ts | src/functions/dPath.ts | import { Path } from '@/types'
interface DebugColours {
[key: string]: string
}
export interface SVGPath {
d: string
'stroke-width'?: number
stroke?: string
}
const debugColours: DebugColours = {
debug0: "blue",
debug1: "red",
}
export function makePaths (
paths: Path[],
): SVGPath[] {
/**
* Converts a list of paths to SVG paths.
*/
return paths.map((pathInfo: Path) => {
const path: SVGPath = { d: pathInfo.d }
if (pathInfo.type.startsWith("debug")) {
path['stroke-width'] = 0.5
path['stroke'] = debugColours[pathInfo.type]
}
return path
})
}
| import { Path } from '@/types'
interface DebugColours {
[key: string]: string
}
export interface SVGPath {
d: string
'stroke-width'?: number
stroke?: string
}
const debugColours: DebugColours = {
debug0: "blue",
debug1: "red",
debug2: "green",
}
export function makePaths (
paths: Path[],
): SVGPath[] {
/**
* Converts a list of paths to SVG paths.
*/
return paths.map((pathInfo: Path) => {
const path: SVGPath = { d: pathInfo.d }
if (pathInfo.type.startsWith("debug")) {
path['stroke-width'] = 0.5
path['stroke'] = debugColours[pathInfo.type]
}
return path
})
}
| Add a third debug option | Add a third debug option
| TypeScript | mit | rossjrw/gallifreyo,rossjrw/gallifreyo,rossjrw/gallifreyo | ---
+++
@@ -13,6 +13,7 @@
const debugColours: DebugColours = {
debug0: "blue",
debug1: "red",
+ debug2: "green",
}
export function makePaths ( |
d221aa4d29fa4ce334844af2ed633407f56187f8 | src/koa/controller.ts | src/koa/controller.ts | import 'reflect-metadata';
import * as _ from 'underscore';
import * as Router from 'koa-router';
import { compose } from './utils';
import { IMetadata, METADATA_KEY } from './declarations';
export class A7Controller {
private $router: Router;
get $koaRouter(): Router {
if (this.$router != null) {
return this.$router;
}
const constructor = this.constructor;
const meta: IMetadata = Reflect.getMetadata(METADATA_KEY, constructor);
if (meta == null) {
return null;
}
this.$router = new Router(meta.routerOptions);
for (const middleware of meta.middlewares) {
this.$router.use(middleware);
}
for (const handler in meta.handlers) {
const handlerMeta = meta.handlers[handler];
let method = (this as any)[handler] || _.identity;
if (handlerMeta.middleware != null) {
method = compose([handlerMeta.middleware, method]);
(this as any)[handler] = method;
}
if (handlerMeta.path != null) {
(this.$router as any)[handlerMeta.method](
handlerMeta.path,
method.bind(this),
);
}
}
return this.$router;
}
get $koaRouterUseArgs(): [Router.IMiddleware, Router.IMiddleware] {
return [this.$koaRouter.routes(), this.$koaRouter.allowedMethods()];
}
}
| import 'reflect-metadata';
import * as _ from 'underscore';
import * as Router from 'koa-router';
import { compose } from './utils';
import { IMetadata, METADATA_KEY } from './declarations';
export class A7Controller {
private $router: Router;
get $koaRouter(): Router {
if (this.$router != null) {
return this.$router;
}
const constructor = this.constructor;
const meta: IMetadata = Reflect.getMetadata(METADATA_KEY, constructor);
if (meta == null) {
return null;
}
this.$router = new Router(meta.routerOptions);
if (_.isEmpty(meta.middlewares)) {
this.$router.use(compose(meta.middlewares));
}
for (const handler in meta.handlers) {
const handlerMeta = meta.handlers[handler];
let method = (this as any)[handler] || _.identity;
if (handlerMeta.middleware != null) {
method = compose([handlerMeta.middleware, method]);
(this as any)[handler] = method;
}
if (handlerMeta.path != null) {
(this.$router as any)[handlerMeta.method](
handlerMeta.path,
method.bind(this),
);
}
}
return this.$router;
}
get $koaRouterUseArgs(): [Router.IMiddleware, Router.IMiddleware] {
return [this.$koaRouter.routes(), this.$koaRouter.allowedMethods()];
}
}
| Use compose for class middlewares. | Use compose for class middlewares.
| TypeScript | apache-2.0 | nodeswork/sbase,nodeswork/sbase | ---
+++
@@ -25,8 +25,8 @@
this.$router = new Router(meta.routerOptions);
- for (const middleware of meta.middlewares) {
- this.$router.use(middleware);
+ if (_.isEmpty(meta.middlewares)) {
+ this.$router.use(compose(meta.middlewares));
}
for (const handler in meta.handlers) { |
62c207bec8046e804f80dcbecfeb6cd0c5242ddf | src/slurm/actions.ts | src/slurm/actions.ts | import { gettext } from '@waldur/i18n';
import { ActionConfigurationRegistry } from '@waldur/resource/actions/action-configuration';
import { DEFAULT_EDIT_ACTION } from '@waldur/resource/actions/constants';
ActionConfigurationRegistry.register('SLURM.Allocation', {
order: ['details', 'pull', 'edit', 'cancel', 'destroy'],
options: {
pull: {
title: gettext('Synchronise'),
},
details: {
title: gettext('Details'),
component: 'slurmAllocationDetailsDialog',
enabled: true,
useResolve: true,
type: 'form',
dialogSize: 'lg',
},
edit: {
...DEFAULT_EDIT_ACTION,
successMessage: gettext('Allocation has been updated.'),
fields: {
cpu_limit: {
type: 'integer',
label: gettext('CPU limit, minutes'),
required: true,
resource_default_value: true,
},
gpu_limit: {
type: 'integer',
label: gettext('GPU limit, minutes'),
required: true,
resource_default_value: true,
},
ram_limit: {
type: 'integer',
label: gettext('RAM limit, MB'),
required: true,
resource_default_value: true,
},
},
},
},
});
| import { gettext } from '@waldur/i18n';
import { ActionConfigurationRegistry } from '@waldur/resource/actions/action-configuration';
import { DEFAULT_EDIT_ACTION } from '@waldur/resource/actions/constants';
ActionConfigurationRegistry.register('SLURM.Allocation', {
order: ['details', 'pull', 'edit', 'cancel', 'destroy'],
options: {
pull: {
title: gettext('Synchronise'),
},
details: {
title: gettext('Details'),
component: 'slurmAllocationDetailsDialog',
enabled: true,
useResolve: true,
type: 'form',
dialogSize: 'lg',
},
edit: {
...DEFAULT_EDIT_ACTION,
successMessage: gettext('Allocation has been updated.'),
},
},
});
| Remove 'limits' fields from 'Edit' form for allocation | Remove 'limits' fields from 'Edit' form for allocation [WAL-3066]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -19,26 +19,6 @@
edit: {
...DEFAULT_EDIT_ACTION,
successMessage: gettext('Allocation has been updated.'),
- fields: {
- cpu_limit: {
- type: 'integer',
- label: gettext('CPU limit, minutes'),
- required: true,
- resource_default_value: true,
- },
- gpu_limit: {
- type: 'integer',
- label: gettext('GPU limit, minutes'),
- required: true,
- resource_default_value: true,
- },
- ram_limit: {
- type: 'integer',
- label: gettext('RAM limit, MB'),
- required: true,
- resource_default_value: true,
- },
- },
},
},
}); |
906c2fbdbfeb2148db0649ed10d54e1e0ff9e83d | test-files/ts-pass.ts | test-files/ts-pass.ts | function getMaNumberFunction(value: number, ...rest: Array<number>) {
return value + rest.reduce((acc: number, curr: number) => acc + curr);
}
getMaNumberFunction(3, 4, 2, 1);
| function getMaNumberFunction(value: number, ...rest: Array<number>) {
return value + rest.reduce((acc: number, curr: number) => acc + curr);
}
const bazz = {
baz: 'baz',
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const anObject = {
...bazz,
foo: 'fo',
bar: 'bat',
};
getMaNumberFunction(3, 4, 2, 1);
| Test for object rest operator | Test for object rest operator
| TypeScript | bsd-3-clause | dabapps/eslint-config-dabapps,dabapps/eslint-config-dabapps,dabapps/eslint-config-dabapps | ---
+++
@@ -2,4 +2,15 @@
return value + rest.reduce((acc: number, curr: number) => acc + curr);
}
+const bazz = {
+ baz: 'baz',
+};
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+const anObject = {
+ ...bazz,
+ foo: 'fo',
+ bar: 'bat',
+};
+
getMaNumberFunction(3, 4, 2, 1); |
e02d900bb2f87ec2d89695fc9498220b3de3f18b | src/client/src/ui/analytics/epics.ts | src/client/src/ui/analytics/epics.ts | import { ofType } from 'redux-observable'
import { map, mergeMapTo, takeUntil, tap } from 'rxjs/operators'
import { ApplicationEpic } from '../../ApplicationEpic'
import { ACTION_TYPES as REF_ACTION_TYPES } from '../../referenceDataOperations'
import { PositionUpdates } from '../../types'
import { DISCONNECT_SERVICES } from './../../connectionActions'
import { AnalyticsActions } from './actions'
const CURRENCY: string = 'USD'
export const analyticsServiceEpic: ApplicationEpic = (action$, store, { analyticsService, openFin }) => {
return action$.pipe(
ofType(REF_ACTION_TYPES.REFERENCE_SERVICE),
mergeMapTo(
analyticsService.getAnalyticsStream(CURRENCY).pipe(
tap((action: PositionUpdates) => openFin.publishCurrentPositions(action.currentPositions)),
map(AnalyticsActions.fetchAnalytics),
takeUntil(action$.pipe(ofType(DISCONNECT_SERVICES)))
)
)
)
}
export default analyticsServiceEpic
| import { ofType } from 'redux-observable'
import { map, mergeMapTo, takeUntil, tap } from 'rxjs/operators'
import { ApplicationEpic } from '../../ApplicationEpic'
import { ACTION_TYPES as REF_ACTION_TYPES } from '../../referenceDataOperations'
import { PositionUpdates } from '../../types'
import { DISCONNECT_SERVICES } from './../../connectionActions'
import { AnalyticsActions } from './actions'
const CURRENCY: string = 'USD'
export const analyticsServiceEpic: ApplicationEpic = (action$, state$, { analyticsService, openFin }) => {
return action$.pipe(
ofType(REF_ACTION_TYPES.REFERENCE_SERVICE),
mergeMapTo(
analyticsService.getAnalyticsStream(CURRENCY).pipe(
tap((action: PositionUpdates) => openFin.publishCurrentPositions(action.currentPositions)),
map(AnalyticsActions.fetchAnalytics),
takeUntil(action$.pipe(ofType(DISCONNECT_SERVICES)))
)
)
)
}
export default analyticsServiceEpic
| Store renamed to state$ to show that it is a stream | Store renamed to state$ to show that it is a stream
| TypeScript | apache-2.0 | AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud | ---
+++
@@ -8,7 +8,7 @@
const CURRENCY: string = 'USD'
-export const analyticsServiceEpic: ApplicationEpic = (action$, store, { analyticsService, openFin }) => {
+export const analyticsServiceEpic: ApplicationEpic = (action$, state$, { analyticsService, openFin }) => {
return action$.pipe(
ofType(REF_ACTION_TYPES.REFERENCE_SERVICE),
mergeMapTo(
@@ -20,4 +20,5 @@
)
)
}
+
export default analyticsServiceEpic |
6b1c627e23dec5622163ee29bf560d094978fdcf | node_modules/dimensions/datatypes/bitsbyte.ts | node_modules/dimensions/datatypes/bitsbyte.ts | class BitsByte extends Array {
protected _value: number;
constructor(value: number) {
super(8);
this._value = value;
// Assign each flag to an index
this[0] = (value & 1) == 1;
this[1] = (value & 2) == 2;
this[2] = (value & 4) == 4;
this[3] = (value & 8) == 8;
this[4] = (value & 16) == 16;
this[5] = (value & 32) == 32;
this[6] = (value & 64) == 64;
this[7] = (value & 128) == 128;
}
public get value(): number {
return this._value;
}
}
export default BitsByte; | class BitsByte extends Array {
protected _value: number;
constructor(value: number) {
super(8);
this._value = value;
// Assign each flag to an index
this[0] = (value & 1) == 1;
this[1] = (value & 2) == 2;
this[2] = (value & 4) == 4;
this[3] = (value & 8) == 8;
this[4] = (value & 16) == 16;
this[5] = (value & 32) == 32;
this[6] = (value & 64) == 64;
this[7] = (value & 128) == 128;
}
public get value(): number {
this._value = this[0] ? this._value | 1 : this._value;
this._value = this[1] ? this._value | 2 : this._value;
this._value = this[2] ? this._value | 4 : this._value;
this._value = this[3] ? this._value | 8 : this._value;
this._value = this[4] ? this._value | 16 : this._value;
this._value = this[5] ? this._value | 32 : this._value;
this._value = this[6] ? this._value | 64 : this._value;
this._value = this[7] ? this._value | 128 : this._value;
return this._value;
}
}
export default BitsByte; | Fix value not getting updated | Fix value not getting updated
| TypeScript | mit | popstarfreas/Dimensions,popstarfreas/Dimensions,popstarfreas/Dimensions | ---
+++
@@ -17,6 +17,14 @@
}
public get value(): number {
+ this._value = this[0] ? this._value | 1 : this._value;
+ this._value = this[1] ? this._value | 2 : this._value;
+ this._value = this[2] ? this._value | 4 : this._value;
+ this._value = this[3] ? this._value | 8 : this._value;
+ this._value = this[4] ? this._value | 16 : this._value;
+ this._value = this[5] ? this._value | 32 : this._value;
+ this._value = this[6] ? this._value | 64 : this._value;
+ this._value = this[7] ? this._value | 128 : this._value;
return this._value;
}
} |
ce64cb57f937b27a02a10b17c2a8e68a51f4ddab | src/app/pages/badges/badges.component.ts | src/app/pages/badges/badges.component.ts | import { Component, OnInit } from '@angular/core';
import { SeoService } from '../../seo.service';
@Component({
selector: 'store-badges',
templateUrl: './badges.component.html',
styleUrls: ['./badges.component.scss']
})
export class BadgesComponent implements OnInit {
badgeExampleCode: string = "<a href='https://flathub.org/apps/details/org.gimp.GIMP'><img width='240' alt='Download on Flathub' src='https://flathub.org/assets/badges/flathub-badge-en.png'/></a>";
constructor(
private seoService: SeoService) {
this.setPageMetadata();
}
ngOnInit() {
}
setPageMetadata() {
const imageUrl: string = window.location.protocol + '//' + window.location.hostname + ':' +
window.location.port + '/assets/badges/flathub-badge-en.png'
this.seoService.setPageMetadata(
'Flathub Official Badges - Flathub',
'Official badges to promote your application on Flathub',
imageUrl);
}
}
| import { Component, OnInit } from '@angular/core';
import { SeoService } from '../../seo.service';
@Component({
selector: 'store-badges',
templateUrl: './badges.component.html',
styleUrls: ['./badges.component.scss']
})
export class BadgesComponent implements OnInit {
badgeExampleCode: string = "<a href='https://flathub.org/apps/details/org.gimp.GIMP'><img width='240' alt='Download on Flathub' src='https://flathub.org/assets/badges/flathub-badge-en.png'/></a>";
constructor(
private seoService: SeoService) {
this.setPageMetadata();
}
ngOnInit() {
}
setPageMetadata() {
const imageUrl: string = window.location.protocol + '//' + window.location.hostname + ':' +
window.location.port + '/assets/badges/flathub-badge-en.png'
this.seoService.setPageMetadata(
'Flathub Official Badges—Flathub',
'Official badges to promote your application on Flathub',
imageUrl);
}
}
| Use em dash in badges page | Use em dash in badges page
| TypeScript | apache-2.0 | jgarciao/linux-store-frontend,jgarciao/linux-store-frontend,jgarciao/linux-store-frontend | ---
+++
@@ -24,7 +24,7 @@
window.location.port + '/assets/badges/flathub-badge-en.png'
this.seoService.setPageMetadata(
- 'Flathub Official Badges - Flathub',
+ 'Flathub Official Badges—Flathub',
'Official badges to promote your application on Flathub',
imageUrl);
|
d214211f0b43222f3f91f789d323c8de16facc50 | src/commonPasswords.ts | src/commonPasswords.ts | export let commonPasswords = [
"123456", "password", "pikachu", "pokemon", "12345678", "qwerty", "123456789",
"12345", "123456789", "letmein", "1234567", "iloveyou", "admin", "welcome",
"monkey", "login", "abc123", "123123", "dragon", "passw0rd", "master",
"hello", "freedom", "whatever", "qazwsx"
];
| export let commonPasswords = [
"123456", "password", "pikachu", "pokemon"
];
| Remove passwords to quell the login god | Remove passwords to quell the login god
| TypeScript | agpl-3.0 | shoedrip-unbound/dogars,shoedrip-unbound/dogars,shoedrip-unbound/dogars | ---
+++
@@ -1,6 +1,3 @@
export let commonPasswords = [
- "123456", "password", "pikachu", "pokemon", "12345678", "qwerty", "123456789",
- "12345", "123456789", "letmein", "1234567", "iloveyou", "admin", "welcome",
- "monkey", "login", "abc123", "123123", "dragon", "passw0rd", "master",
- "hello", "freedom", "whatever", "qazwsx"
+ "123456", "password", "pikachu", "pokemon"
]; |
e79cd56fd3b41233e28f064e4c60ed1c650b8563 | src/generate/mathjax.ts | src/generate/mathjax.ts | /**
* A script to generate `../shared/styles/mathjax.css`.
*
* Run using `npm run build:mathjax`.
*/
import fs from 'fs'
import MathJax from 'mathjax-node'
import path from 'path'
const dest = path.join(__dirname, '..', 'shared', 'styles', 'mathjax.css')
MathJax.typeset(
{
css: true
},
result => {
const { errors, css } = result
if (errors !== undefined) errors.map(err => console.error(err))
fs.writeFileSync(
dest,
`/* Generated by ${path.basename(__filename)}. Do not edit. */\n\n${css}`
)
}
)
| /**
* A script to generate `../shared/styles/mathjax.css`.
*
* Run using `npm run generate:mathjax`.
*/
import fs from 'fs'
import MathJax from 'mathjax-node'
import path from 'path'
const dest = path.join(__dirname, '..', 'shared', 'styles', 'mathjax.css')
MathJax.typeset(
{
css: true
},
result => {
const { errors, css } = result
if (errors !== undefined) errors.map(err => console.error(err))
fs.writeFileSync(
dest,
`/* Generated by ${path.basename(__filename)}. Do not edit. */\n\n${css}`
)
}
)
| Update script reference to new name | docs(Comment): Update script reference to new name
| TypeScript | apache-2.0 | stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila | ---
+++
@@ -1,7 +1,7 @@
/**
* A script to generate `../shared/styles/mathjax.css`.
*
- * Run using `npm run build:mathjax`.
+ * Run using `npm run generate:mathjax`.
*/
import fs from 'fs' |
0c93fe50c7d234b54d8ce2db4ba25b06bc143f45 | templates/app/src/_name.ts | templates/app/src/_name.ts | import { <%= pAppName %>Config } from "./<%= hAppName %>.config";
import { <%= pAppName %>Run } from "./<%= hAppName %>.run";
angular.module("<%= appName %>", [
// Uncomment to use your app templates.
// "<%= appName %>.tpls",
"ui.router"
])
.config(<%= pAppName %>Config)
.run(<%= pAppName %>Run); | import * as angular from "angular";
import { <%= pAppName %>Config } from "./<%= hAppName %>.config";
import { <%= pAppName %>Run } from "./<%= hAppName %>.run";
import { services } from "./services/services";
angular.module("<%= appName %>", [
// Uncomment to use your app templates.
// "<%= appName %>.tpls",
"ui.router",
services
])
.config(<%= pAppName %>Config)
.run(<%= pAppName %>Run); | Add services and angular reference | Add services and angular reference
| TypeScript | mit | Kurtz1993/ngts-cli,Kurtz1993/ngts-cli,Kurtz1993/ngts-cli | ---
+++
@@ -1,10 +1,13 @@
+import * as angular from "angular";
import { <%= pAppName %>Config } from "./<%= hAppName %>.config";
import { <%= pAppName %>Run } from "./<%= hAppName %>.run";
+import { services } from "./services/services";
angular.module("<%= appName %>", [
// Uncomment to use your app templates.
// "<%= appName %>.tpls",
- "ui.router"
+ "ui.router",
+ services
])
.config(<%= pAppName %>Config)
.run(<%= pAppName %>Run); |
ef386b84e23d04d3aa25c352184168f5aee08436 | src/components/QueueCard/QueueTimer.tsx | src/components/QueueCard/QueueTimer.tsx | import * as React from 'react';
import { Caption } from '@shopify/polaris';
import { formatSecondsAsHhMmSs } from '../../utils/dates';
interface Props {
readonly timeLeftInSeconds: number;
}
interface State {
readonly secondsLeft: number;
}
class QueueTimer extends React.PureComponent<Props, State> {
private static readonly tickRate = 500;
private static readonly secondsPerTick = QueueTimer.tickRate / 1000;
private timerId: number;
constructor(props: Props) {
super(props);
this.state = { secondsLeft: props.timeLeftInSeconds };
}
static getDerivedStateFromProps(props: Props): Partial<State> {
return {
secondsLeft: props.timeLeftInSeconds
};
}
componentDidMount() {
this.startTimer();
}
componentWillUnmount() {
clearInterval(this.timerId);
}
private startTimer = () => {
clearInterval(this.timerId);
this.timerId = window.setInterval(this.tick, QueueTimer.tickRate);
};
private tick = () =>
this.setState((prevState: State) => ({
secondsLeft: prevState.secondsLeft - 1 * QueueTimer.secondsPerTick
}));
public render() {
return <Caption>{formatSecondsAsHhMmSs(this.state.secondsLeft)}</Caption>;
}
}
export default QueueTimer;
| import * as React from 'react';
import { Caption } from '@shopify/polaris';
import { formatSecondsAsHhMmSs } from '../../utils/dates';
interface Props {
readonly timeLeftInSeconds: number;
}
interface State {
readonly secondsLeft: number;
}
class QueueTimer extends React.PureComponent<Props, State> {
private static readonly tickRate = 500;
private static readonly secondsPerTick = QueueTimer.tickRate / 1000;
private timerId: number;
constructor(props: Props) {
super(props);
this.state = { secondsLeft: props.timeLeftInSeconds };
}
componentDidMount() {
this.startTimer();
}
componentWillUnmount() {
clearInterval(this.timerId);
}
private startTimer = () => {
clearInterval(this.timerId);
this.timerId = window.setInterval(this.tick, QueueTimer.tickRate);
};
private tick = () => {
this.setState((prevState: State) => ({
secondsLeft: prevState.secondsLeft - 10 * QueueTimer.secondsPerTick
}));
};
public render() {
return <Caption>{formatSecondsAsHhMmSs(this.state.secondsLeft)}</Caption>;
}
}
export default QueueTimer;
| Fix time left countdown for items in Queue not updating properly. | Fix time left countdown for items in Queue not updating properly.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -20,12 +20,6 @@
this.state = { secondsLeft: props.timeLeftInSeconds };
}
- static getDerivedStateFromProps(props: Props): Partial<State> {
- return {
- secondsLeft: props.timeLeftInSeconds
- };
- }
-
componentDidMount() {
this.startTimer();
}
@@ -39,10 +33,11 @@
this.timerId = window.setInterval(this.tick, QueueTimer.tickRate);
};
- private tick = () =>
+ private tick = () => {
this.setState((prevState: State) => ({
- secondsLeft: prevState.secondsLeft - 1 * QueueTimer.secondsPerTick
+ secondsLeft: prevState.secondsLeft - 10 * QueueTimer.secondsPerTick
}));
+ };
public render() {
return <Caption>{formatSecondsAsHhMmSs(this.state.secondsLeft)}</Caption>; |
cc9ea4af724c895606f99857416c1649720f9b70 | TameGame/Input/GameInputBehavior.ts | TameGame/Input/GameInputBehavior.ts | /// <reference path="Interface.ts" />
/// <reference path="../Core/Interface.ts" />
/// <reference path="DefaultControlRouter.ts" />
/// <reference path="DefaultControlEvents.ts" />
module TameGame {
// Extensions to the game interface to support input
export interface Game {
/** The main control router for the game */
controlRouter?: ControlRouter;
/** Registers event handlers for controls that apply across the entire game */
controlEvents?: ControlEvents;
}
/**
* The default input behavior
*
* Input is dispatched through the default control router to the default control events object
*/
export function defaultInputBehavior(game: Game) {
game.controlRouter = new DefaultControlRouter();
game.controlEvents = new DefaultControlEvents(game.controlRouter.actionForInput);
}
}
| /// <reference path="Interface.ts" />
/// <reference path="../Core/Interface.ts" />
/// <reference path="DefaultControlRouter.ts" />
/// <reference path="DefaultControlEvents.ts" />
module TameGame {
// Extensions to the game interface to support input
export interface Game {
/** The main control router for the game */
controlRouter?: ControlRouter;
/** Registers event handlers for controls that apply across the entire game */
controlEvents?: ControlEvents;
}
/**
* The default input behavior
*
* Input is dispatched through the default control router to the default control events object
*/
export function defaultInputBehavior(game: Game, dispatcher: WorkerMessageDispatcher) {
// Controls that have active pressure on them
var activeControls: ControlMap<ControlInput> = {};
// Give the game the default control router and events objects
game.controlRouter = new DefaultControlRouter();
game.controlEvents = new DefaultControlEvents(game.controlRouter.actionForInput);
// When the worker sends control events, update the list of controls
dispatcher.onMessage(workerMessages.inputControl, (msg) => {
var input: ControlInput = msg.data.input;
if (input.pressure > 0) {
setControlMap(activeControls, input, input);
} else {
deleteControlMap(activeControls, input);
}
});
// Every game tick, dispatch the player input
game.events.onPassStart(UpdatePass.PlayerInput, (pass, time) => {
// Collect all the control inputs into a single array
var allInput: ControlInput[] = [];
forEachControlMap(activeControls, (control, input) => allInput.push(input));
// Dispatch the input
game.controlEvents.tickInputs(allInput, time);
});
}
}
| Use the message dispatcher to dispatch input events to the game | Use the message dispatcher to dispatch input events to the game
| TypeScript | apache-2.0 | TameGame/Engine,TameGame/Engine,TameGame/Engine | ---
+++
@@ -18,8 +18,33 @@
*
* Input is dispatched through the default control router to the default control events object
*/
- export function defaultInputBehavior(game: Game) {
+ export function defaultInputBehavior(game: Game, dispatcher: WorkerMessageDispatcher) {
+ // Controls that have active pressure on them
+ var activeControls: ControlMap<ControlInput> = {};
+
+ // Give the game the default control router and events objects
game.controlRouter = new DefaultControlRouter();
game.controlEvents = new DefaultControlEvents(game.controlRouter.actionForInput);
+
+ // When the worker sends control events, update the list of controls
+ dispatcher.onMessage(workerMessages.inputControl, (msg) => {
+ var input: ControlInput = msg.data.input;
+
+ if (input.pressure > 0) {
+ setControlMap(activeControls, input, input);
+ } else {
+ deleteControlMap(activeControls, input);
+ }
+ });
+
+ // Every game tick, dispatch the player input
+ game.events.onPassStart(UpdatePass.PlayerInput, (pass, time) => {
+ // Collect all the control inputs into a single array
+ var allInput: ControlInput[] = [];
+ forEachControlMap(activeControls, (control, input) => allInput.push(input));
+
+ // Dispatch the input
+ game.controlEvents.tickInputs(allInput, time);
+ });
}
} |
7c43976bf5ea280b1060770f8ddd8f1ba9c9b47d | 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, (e, failures) => {
bootstrap.callback();
callback(e);
if (failures > 0) {
process.exitCode = 1;
}
});
}
};
| 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();
if (failures > 0) {
callback(new Error(failures + ' test(s) failed'));
process.exitCode = 1;
}
});
}
};
| Send error back to runner | Send error back to runner
| TypeScript | mit | neild3r/vscode-php-docblocker | ---
+++
@@ -25,8 +25,8 @@
run: function(testsRoot:string, callback: (error:Error) => void) {
testRunner.run(testsRoot, (e, failures) => {
bootstrap.callback();
- callback(e);
if (failures > 0) {
+ callback(new Error(failures + ' test(s) failed'));
process.exitCode = 1;
}
}); |
31a069a5261f4e56c654c1d54efea811141fee1c | src/definitions/SkillContext.ts | src/definitions/SkillContext.ts | import {Callback, Context as LambdaContext} from "aws-lambda";
import {AlexaRequestBody} from "./AlexaService";
export class RequestContext {
constructor(request: AlexaRequestBody, event: LambdaContext, callback: Callback) {
this.request = request;
this.event = event;
this.callback = callback;
}
request: AlexaRequestBody;
event: LambdaContext;
callback: Callback;
get(prop): any {
console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
return this[prop];
}
set(prop, value): boolean {
console.log(`Adding prop ${prop}...`);
return this[prop] = value;
}
delete(prop): boolean {
console.log(`Deleting prop ${prop}...`);
return delete this[prop];
}
}
export class Attributes {
constructor(props?: any) {
if (props) {
Object.assign(this, props);
}
}
get(prop): any {
console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
return this[prop];
}
set(prop, value): boolean {
console.log(`Adding prop ${prop}...`);
return this[prop] = value;
}
delete(prop): boolean {
console.log(`Deleting prop ${prop}...`);
return delete this[prop];
}
} | import {Callback, Context as LambdaContext} from "aws-lambda";
import {AlexaRequestBody} from "./AlexaService";
export class RequestContext {
constructor(request: AlexaRequestBody, event: LambdaContext, callback: Callback) {
this.request = request;
this.event = event;
this.callback = callback;
}
request: AlexaRequestBody;
event: LambdaContext;
callback: Callback;
get(prop): any {
console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
return this[prop];
}
set(prop, value): boolean {
console.log(`Adding prop ${prop}...`);
return this[prop] = value;
}
delete(prop): boolean {
console.log(`Deleting prop ${prop}...`);
return delete this[prop];
}
}
export class Attributes {
constructor(props?: any) {
this.FrameStack = [];
this.CookieCounter = "0";
if (props) {
Object.assign(this, props);
}
if (!this.CurrentFrame) {
this.CurrentFrame = "Start";
}
}
FrameStack: Array<string>;
CurrentFrame: string;
CookieCounter: string;
get(prop: string): any {
console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
return this[prop];
}
set(prop: string, value: any): boolean {
console.log(`Adding prop ${prop}...`);
return this[prop] = value;
}
delete(prop): boolean {
console.log(`Deleting prop ${prop}...`);
return delete this[prop];
}
} | Add model attributes for frame management. | Add model attributes for frame management.
| TypeScript | agpl-3.0 | deegles/cookietime,deegles/cookietime | ---
+++
@@ -34,17 +34,31 @@
export class Attributes {
constructor(props?: any) {
+ this.FrameStack = [];
+ this.CookieCounter = "0";
+
if (props) {
Object.assign(this, props);
}
+
+ if (!this.CurrentFrame) {
+ this.CurrentFrame = "Start";
+ }
}
- get(prop): any {
+ FrameStack: Array<string>;
+
+ CurrentFrame: string;
+
+ CookieCounter: string;
+
+ get(prop: string): any {
console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
+
return this[prop];
}
- set(prop, value): boolean {
+ set(prop: string, value: any): boolean {
console.log(`Adding prop ${prop}...`);
return this[prop] = value; |
d7caf50a76ab9e5a6d42aeff661ab8d716bce95c | src/Test/Ast/EdgeCases/LinkifiedConvention.ts | src/Test/Ast/EdgeCases/LinkifiedConvention.ts | import { expect } from 'chai'
import Up from '../../../index'
import { insideDocumentAndParagraph } from '../Helpers'
import { LinkNode } from '../../../SyntaxNodes/LinkNode'
import { InlineSpoilerNode } from '../../../SyntaxNodes/InlineSpoilerNode'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
import { ParenthesizedNode } from '../../../SyntaxNodes/ParenthesizedNode'
describe("An almost-linkified spoiler (with whitespace between its content and URL) terminated early due to a space in its URL", () => {
it('can contain an unclosed square bracket without affecting a linkified spoiler with a square bracketed URL that follows it', () => {
expect(Up.toAst('(SPOILER: Ash dies) (https://example.com/ending:[ has all the info) ... [anyway, go here instead] [https://example.com/happy]')).to.be.eql(
insideDocumentAndParagraph([
new InlineSpoilerNode([
new PlainTextNode('Ash dies')
]),
new PlainTextNode(' '),
new ParenthesizedNode([
new PlainTextNode('('),
new LinkNode([
new PlainTextNode('example.com/ending:[')
], 'https://example.com/ending:['),
new PlainTextNode(' has all the info)')
]),
new PlainTextNode(' ... '),
new LinkNode([
new PlainTextNode('anyway, go here instead'),
], 'https://example.com/happy')
]))
})
})
| import { expect } from 'chai'
import Up from '../../../index'
import { insideDocumentAndParagraph } from '../Helpers'
import { LinkNode } from '../../../SyntaxNodes/LinkNode'
import { InlineSpoilerNode } from '../../../SyntaxNodes/InlineSpoilerNode'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
import { ParenthesizedNode } from '../../../SyntaxNodes/ParenthesizedNode'
describe("An almost-linkified spoiler (with whitespace between its content and URL) terminated early due to a space in its URL", () => {
it('can contain an unclosed square bracket without affecting a linkified spoiler with a square bracketed URL that follows it', () => {
expect(Up.toAst('(SPOILER: Ash dies) (https://example.com/ending:[ has all the info) ... [SPOILER: anyway, go here instead] [https://example.com/happy]')).to.be.eql(
insideDocumentAndParagraph([
new InlineSpoilerNode([
new PlainTextNode('Ash dies')
]),
new PlainTextNode(' '),
new ParenthesizedNode([
new PlainTextNode('('),
new LinkNode([
new PlainTextNode('example.com/ending:[')
], 'https://example.com/ending:['),
new PlainTextNode(' has all the info)')
]),
new PlainTextNode(' ... '),
new InlineSpoilerNode([
new LinkNode([
new PlainTextNode('anyway, go here instead')
], 'https://example.com/happy')
])
]))
})
})
| Fix test to match description | Fix test to match description
| TypeScript | mit | start/up,start/up | ---
+++
@@ -9,7 +9,7 @@
describe("An almost-linkified spoiler (with whitespace between its content and URL) terminated early due to a space in its URL", () => {
it('can contain an unclosed square bracket without affecting a linkified spoiler with a square bracketed URL that follows it', () => {
- expect(Up.toAst('(SPOILER: Ash dies) (https://example.com/ending:[ has all the info) ... [anyway, go here instead] [https://example.com/happy]')).to.be.eql(
+ expect(Up.toAst('(SPOILER: Ash dies) (https://example.com/ending:[ has all the info) ... [SPOILER: anyway, go here instead] [https://example.com/happy]')).to.be.eql(
insideDocumentAndParagraph([
new InlineSpoilerNode([
new PlainTextNode('Ash dies')
@@ -23,9 +23,11 @@
new PlainTextNode(' has all the info)')
]),
new PlainTextNode(' ... '),
- new LinkNode([
- new PlainTextNode('anyway, go here instead'),
- ], 'https://example.com/happy')
+ new InlineSpoilerNode([
+ new LinkNode([
+ new PlainTextNode('anyway, go here instead')
+ ], 'https://example.com/happy')
+ ])
]))
})
}) |
db42d0afd549251215587c8867940f2b65c86818 | src/Test/Ast/OutlineSeparation.ts | src/Test/Ast/OutlineSeparation.ts | import { expect } from 'chai'
import Up from '../../index'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
describe('1 blank line between paragraphs', () => {
it('simply provides separation, producing no syntax node itself', () => {
const text = `Pokemon Moon has a Mew under a truck.
Pokemon Sun is a truck.`
expect(Up.toAst(text)).to.be.eql(
new DocumentNode([
new ParagraphNode([new PlainTextNode('Pokemon Moon has a Mew under a truck.')]),
new ParagraphNode([new PlainTextNode('Pokemon Sun is a truck.')]),
]))
})
})
describe('2 blank lines between paragraphs', () => {
it('simply provides separation, producing no syntax node itself', () => {
const text = `Pokemon Moon has a Mew under a truck.
\t
Pokemon Sun is a truck.`
expect(Up.toAst(text)).to.be.eql(
new DocumentNode([
new ParagraphNode([new PlainTextNode('Pokemon Moon has a Mew under a truck.')]),
new ParagraphNode([new PlainTextNode('Pokemon Sun is a truck.')]),
]))
})
})
| import { expect } from 'chai'
import Up from '../../index'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
describe('1 blank line between paragraphs', () => {
it('simply provides separation, producing no syntax node itself', () => {
const text = `
Pokemon Moon has a Mew under a truck.
\t
Pokemon Sun is a truck.`
expect(Up.toAst(text)).to.be.eql(
new DocumentNode([
new ParagraphNode([new PlainTextNode('Pokemon Moon has a Mew under a truck.')]),
new ParagraphNode([new PlainTextNode('Pokemon Sun is a truck.')]),
]))
})
})
describe('2 blank lines between paragraphs', () => {
it('simply provides separation, producing no syntax node itself', () => {
const text = `
Pokemon Moon has a Mew under a truck.
\t
\t
Pokemon Sun is a truck.`
expect(Up.toAst(text)).to.be.eql(
new DocumentNode([
new ParagraphNode([new PlainTextNode('Pokemon Moon has a Mew under a truck.')]),
new ParagraphNode([new PlainTextNode('Pokemon Sun is a truck.')]),
]))
})
})
| Improve 2 section separation tests | Improve 2 section separation tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -7,8 +7,9 @@
describe('1 blank line between paragraphs', () => {
it('simply provides separation, producing no syntax node itself', () => {
- const text = `Pokemon Moon has a Mew under a truck.
-
+ const text = `
+Pokemon Moon has a Mew under a truck.
+ \t
Pokemon Sun is a truck.`
expect(Up.toAst(text)).to.be.eql(
new DocumentNode([
@@ -20,8 +21,9 @@
describe('2 blank lines between paragraphs', () => {
it('simply provides separation, producing no syntax node itself', () => {
- const text = `Pokemon Moon has a Mew under a truck.
-
+ const text = `
+Pokemon Moon has a Mew under a truck.
+ \t
\t
Pokemon Sun is a truck.`
expect(Up.toAst(text)).to.be.eql( |
7f4bb8b30b7413cad4e5044fb3d07f305297aa89 | src/checker.ts | src/checker.ts | import { deepEqual } from 'assert';
export default (_module: NodeModule, tester: (check: <T>(name: string, a: T, b: T) => void ) => void) => {
const checkedCounts: { [key: string]: number } = {};
const stackRegex = new RegExp(`${_module.filename}:([0-9]+):[0-9]+`);
let failedCount = 0;
let passedCount = 0;
tester(<T>(name: string, a: T, b: T): void => {
const checkedCount = (name in checkedCounts)
? checkedCounts[name] += 1
: checkedCounts[name] = 1;
const caseIndex = checkedCount;
try {
deepEqual(a, b);
passedCount++;
} catch (error) {
failedCount++;
const stack = (error as Error).stack as string;
const linenum = (stack.match(stackRegex) as string[])[1];
console.log(`ERROR: at L${linenum} => Test(${name}): Case(${caseIndex})`);
}
});
console.log(`Passed: ${passedCount}, Failed: ${failedCount}`);
process.exit(failedCount > 0 ? 1 : 0);
};
| import { deepEqual } from 'assert';
export default (_module: NodeModule, tester: (check: <T>(name: string, a: T, b: T) => void ) => void) => {
const checkedCounts: { [key: string]: number } = {};
const stackRegex = new RegExp(`${_module.filename}:([0-9]+):[0-9]+`);
let failedCount = 0;
let passedCount = 0;
tester(<T>(name: string, a: T, b: T): void => {
const checkedCount = (name in checkedCounts)
? checkedCounts[name] += 1
: checkedCounts[name] = 1;
const caseIndex = checkedCount;
try {
deepEqual(a, b);
passedCount++;
} catch (_error) {
failedCount++;
const error = _error as Error;
const stack = error.stack as string;
const linenum = (stack.match(stackRegex) as string[])[1];
console.log(`ERROR: at L${linenum} => Test(${name}): Case(${caseIndex})`);
console.log(`> ${error.message}`);
}
});
console.log(`Passed: ${passedCount}, Failed: ${failedCount}`);
process.exit(failedCount > 0 ? 1 : 0);
};
| Update scripts log assertion message | Update scripts
log assertion message
| TypeScript | mit | ikatyang/types-ramda,ikatyang/types-ramda | ---
+++
@@ -15,11 +15,13 @@
try {
deepEqual(a, b);
passedCount++;
- } catch (error) {
+ } catch (_error) {
failedCount++;
- const stack = (error as Error).stack as string;
+ const error = _error as Error;
+ const stack = error.stack as string;
const linenum = (stack.match(stackRegex) as string[])[1];
console.log(`ERROR: at L${linenum} => Test(${name}): Case(${caseIndex})`);
+ console.log(`> ${error.message}`);
}
});
|
b34117ec84770d93c1ec2ec5a5e3f58eec502ed9 | src/command.ts | src/command.ts | import * as shelljs from 'shelljs';
import * as path from 'path';
import * as fs from 'fs';
var packageDir = path.join(path.dirname(fs.realpathSync(__filename)), '../');
shelljs.cd(packageDir);
shelljs.exec(path.join(packageDir, 'node_modules', '.bin', 'electron') + ' .');
| import * as shelljs from 'shelljs';
import * as path from 'path';
import * as fs from 'fs';
let packageDir = path.join(path.dirname(fs.realpathSync(__filename)), '../');
shelljs.cd(packageDir);
shelljs.exec(path.join(packageDir, 'node_modules', '.bin', 'electron') + ' .');
| Use let instead of var | Use let instead of var
| TypeScript | mit | AyaMorisawa/Disskey,AyaMorisawa/Disskey,AyaMorisawa/Disskey | ---
+++
@@ -2,6 +2,6 @@
import * as path from 'path';
import * as fs from 'fs';
-var packageDir = path.join(path.dirname(fs.realpathSync(__filename)), '../');
+let packageDir = path.join(path.dirname(fs.realpathSync(__filename)), '../');
shelljs.cd(packageDir);
shelljs.exec(path.join(packageDir, 'node_modules', '.bin', 'electron') + ' .'); |
7869eee8579a37a72a79a60af9046f7a125b1df0 | client/app/components/survey-login.ts | client/app/components/survey-login.ts | import {Component} from '@angular/core';
import {MD_CARD_DIRECTIVES} from '@angular2-material/card';
import {MdButton} from '@angular2-material/button';
import {MD_LIST_DIRECTIVES} from '@angular2-material/list';
import {MD_INPUT_DIRECTIVES} from '@angular2-material/input';
import {MdIcon} from '@angular2-material/icon';
@Component({
selector: 'survey-login',
templateUrl: '/app/components/templates/survey-login.html',
directives: [
MD_CARD_DIRECTIVES,
MdButton,
MD_LIST_DIRECTIVES,
MD_INPUT_DIRECTIVES,
MdIcon
]
})
export class SurveyLogin {
login: Object;
selectedIndex: number = -1;
submit(): void {
console.log('submitted');
}
constructor() {
this.login = {
user: '',
pass: ''
};
}
}
| import {Component} from '@angular/core';
import {Router} from '@angular/router-deprecated';
import {MD_CARD_DIRECTIVES} from '@angular2-material/card';
import {MdButton} from '@angular2-material/button';
import {MD_LIST_DIRECTIVES} from '@angular2-material/list';
import {MD_INPUT_DIRECTIVES} from '@angular2-material/input';
import {MdIcon} from '@angular2-material/icon';
import {SurveyLoginService} from '../services/survey-login.svc';
interface IUser {
isLoggedIn: boolean;
type: string;
}
@Component({
selector: 'survey-login',
templateUrl: '/app/components/templates/survey-login.html',
directives: [
MD_CARD_DIRECTIVES,
MdButton,
MD_LIST_DIRECTIVES,
MD_INPUT_DIRECTIVES,
MdIcon
]
})
export class SurveyLogin {
router: Router;
login: Object;
loginSvc: SurveyLoginService;
selectedIndex: number = -1;
submit(): void {
this.loginSvc.login(this.login);
}
constructor(router: Router, loginSvc: SurveyLoginService) {
this.router = router;
this.loginSvc = loginSvc;
this.loginSvc.login$.subscribe((res: IUser) => {
if (res.isLoggedIn) {
this.router.navigate(['List']);
}
});
this.login = {
user: '',
pass: ''
};
}
}
| Add login service to login component | Add login service to login component
| TypeScript | mit | JSMike/Material2-Survey,JSMike/Material2-Survey,JSMike/Material2-Survey | ---
+++
@@ -1,9 +1,16 @@
import {Component} from '@angular/core';
+import {Router} from '@angular/router-deprecated';
import {MD_CARD_DIRECTIVES} from '@angular2-material/card';
import {MdButton} from '@angular2-material/button';
import {MD_LIST_DIRECTIVES} from '@angular2-material/list';
import {MD_INPUT_DIRECTIVES} from '@angular2-material/input';
import {MdIcon} from '@angular2-material/icon';
+import {SurveyLoginService} from '../services/survey-login.svc';
+
+interface IUser {
+ isLoggedIn: boolean;
+ type: string;
+}
@Component({
selector: 'survey-login',
@@ -17,14 +24,23 @@
]
})
export class SurveyLogin {
+ router: Router;
login: Object;
+ loginSvc: SurveyLoginService;
selectedIndex: number = -1;
submit(): void {
- console.log('submitted');
+ this.loginSvc.login(this.login);
}
- constructor() {
+ constructor(router: Router, loginSvc: SurveyLoginService) {
+ this.router = router;
+ this.loginSvc = loginSvc;
+ this.loginSvc.login$.subscribe((res: IUser) => {
+ if (res.isLoggedIn) {
+ this.router.navigate(['List']);
+ }
+ });
this.login = {
user: '',
pass: '' |
5af1bd8343bd7b1a0c6906e0dbb990f3b0e2999b | src/dscanner.ts | src/dscanner.ts | 'use strict';
import * as cp from 'child_process';
import * as vsc from 'vscode';
export default class Dscanner {
public static path: string;
public static collection: vsc.DiagnosticCollection;
public constructor(document: vsc.TextDocument) {
let output = '';
let dscanner = cp.spawn(Dscanner.path + 'dscanner', ['--report']);
console.log(Dscanner.path + 'dscanner');
dscanner.stdout.on('data', (data) => {
console.log('data', data.toString());
output += data;
});
dscanner.on('exit', () => {
console.log('exit');
console.log(output);
});
dscanner.stdin.write(document.getText());
dscanner.stdin.end();
console.log('cons');
}
} | 'use strict';
import * as cp from 'child_process';
import * as vsc from 'vscode';
export default class Dscanner {
public static path: string;
public static collection: vsc.DiagnosticCollection;
public constructor(document: vsc.TextDocument) {
let output = '';
let dscanner = cp.spawn(Dscanner.path + 'dscanner', ['--report']);
dscanner.stdout.on('data', (data) => {
output += data;
});
dscanner.on('exit', () => {
// TODO : create diagnostics when dscanner accepts code from stdin
});
dscanner.stdin.write(document.getText());
dscanner.stdin.end();
}
} | Remove logs that were not supposed to be here | Remove logs that were not supposed to be here
| TypeScript | mit | mattiascibien/dlang-vscode,dlang-vscode/dlang-vscode | ---
+++
@@ -11,21 +11,15 @@
let output = '';
let dscanner = cp.spawn(Dscanner.path + 'dscanner', ['--report']);
- console.log(Dscanner.path + 'dscanner');
-
dscanner.stdout.on('data', (data) => {
- console.log('data', data.toString());
output += data;
});
dscanner.on('exit', () => {
- console.log('exit');
- console.log(output);
+ // TODO : create diagnostics when dscanner accepts code from stdin
});
dscanner.stdin.write(document.getText());
dscanner.stdin.end();
-
- console.log('cons');
}
} |
25ecfa0dc8f32a120b094b12dd8649193baf00d4 | src/Artsy/Relay/MockRelayRenderer.tsx | src/Artsy/Relay/MockRelayRenderer.tsx | import { createMockNetworkLayer } from "Artsy/Relay/createMockNetworkLayer"
import React from "react"
import { QueryRenderer } from "react-relay"
import { Environment, RecordSource, Store } from "relay-runtime"
export const MockRelayRenderer = ({
Component,
query,
mockResolvers,
}: {
Component: React.ComponentClass | React.SFC
query: any
mockResolvers: { [typeName: string]: () => any }
}) => {
const network = createMockNetworkLayer({
Query: () => ({}),
...mockResolvers,
})
const source = new RecordSource()
const store = new Store(source)
const environment = new Environment({
network,
store,
})
return (
<QueryRenderer
// tslint:disable-next-line
query={query}
environment={environment}
variables={{}}
render={({ error, props, retry }) => {
return error || !props ? <div>{error}</div> : <Component {...props} />
}}
/>
)
}
| import { createMockNetworkLayer } from "Artsy/Relay/createMockNetworkLayer"
import React from "react"
import { QueryRenderer } from "react-relay"
import { Environment, RecordSource, Store } from "relay-runtime"
export const MockRelayRenderer = ({
Component,
query,
mockResolvers,
}: {
Component: React.ComponentClass | React.SFC
query: any
mockResolvers: { [typeName: string]: () => any }
}) => {
const network = createMockNetworkLayer({
Query: () => ({}),
...mockResolvers,
})
const source = new RecordSource()
const store = new Store(source)
const environment = new Environment({
network,
store,
})
return (
<QueryRenderer
// tslint:disable-next-line relay-operation-generics
query={query}
environment={environment}
variables={{}}
render={({ error, props, retry }) => {
return error || !props ? <div>{error}</div> : <Component {...props} />
}}
/>
)
}
| Increase specificity of lint exception | Increase specificity of lint exception
| TypeScript | mit | artsy/reaction,artsy/reaction,artsy/reaction-force,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction | ---
+++
@@ -25,7 +25,7 @@
return (
<QueryRenderer
- // tslint:disable-next-line
+ // tslint:disable-next-line relay-operation-generics
query={query}
environment={environment}
variables={{}} |
ce2c0f5a70a7eaa022efc981f0e348f902dd924b | hooks/useUser/index.tsx | hooks/useUser/index.tsx | import { useLocalStorage } from 'react-use';
export const USERNAME_LOCAL_STORAGE_KEY = 'USERNAME';
interface User {
username: string;
}
const useUser = () => {
return useLocalStorage<User | undefined>(USERNAME_LOCAL_STORAGE_KEY);
};
export default useUser;
| import { useLocalStorage } from 'react-use';
export const USER_LOCAL_STORAGE_KEY = 'USER';
interface User {
username: string;
}
const useUser = () => {
return useLocalStorage<User | undefined>(USER_LOCAL_STORAGE_KEY);
};
export default useUser;
| Change user local storage key | Change user local storage key
| TypeScript | mit | sheldarr/Votenger,sheldarr/Votenger | ---
+++
@@ -1,13 +1,13 @@
import { useLocalStorage } from 'react-use';
-export const USERNAME_LOCAL_STORAGE_KEY = 'USERNAME';
+export const USER_LOCAL_STORAGE_KEY = 'USER';
interface User {
username: string;
}
const useUser = () => {
- return useLocalStorage<User | undefined>(USERNAME_LOCAL_STORAGE_KEY);
+ return useLocalStorage<User | undefined>(USER_LOCAL_STORAGE_KEY);
};
export default useUser; |
1e136657ea137e0f63b5bf70ae38ec1e6da994be | ts/ports/context.ts | ts/ports/context.ts | import * as fs from 'fs';
import * as fileGatherer from '../util/file-gatherer';
import { ElmApp, Context } from '../domain';
function setup(app: ElmApp, directory: string) {
app.ports.loadContext.subscribe(() => {
const input = fileGatherer.gather(directory);
var configuration;
try {
configuration = fs.readFileSync('./elm-analyse.json').toString();
} catch (e) {
configuration = '';
}
const data: Context = {
sourceFiles: input.sourceFiles,
interfaceFiles: input.interfaceFiles,
configuration: configuration
};
setTimeout(function() {
app.ports.onLoadedContext.send(data);
}, 5);
});
}
export { setup };
| import * as fs from 'fs';
import * as fileGatherer from '../util/file-gatherer';
import { ElmApp, Context } from '../domain';
import * as path from 'path';
function setup(app: ElmApp, directory: string) {
app.ports.loadContext.subscribe(() => {
const input = fileGatherer.gather(directory);
var configuration;
try {
configuration = fs.readFileSync(path.join(directory, 'elm-analyse.json')).toString();
} catch (e) {
configuration = '';
}
const data: Context = {
sourceFiles: input.sourceFiles,
interfaceFiles: input.interfaceFiles,
configuration: configuration
};
setTimeout(function() {
app.ports.onLoadedContext.send(data);
}, 5);
});
}
export { setup };
| Read elm-analyse configuration from the directory where the elm.json is rather than the current working directory of the process. This helps with running in a multi-project structure where you may open "/project/" in an editor and have an elm project under "/project/web/". | Read elm-analyse configuration from the directory where the elm.json is rather than the current working directory of the process. This helps with running in a multi-project structure where you may open "/project/" in an editor and have an elm project under "/project/web/".
| TypeScript | mit | stil4m/elm-analyse,stil4m/elm-analyse,stil4m/elm-analyse,stil4m/elm-analyse | ---
+++
@@ -1,13 +1,14 @@
import * as fs from 'fs';
import * as fileGatherer from '../util/file-gatherer';
import { ElmApp, Context } from '../domain';
+import * as path from 'path';
function setup(app: ElmApp, directory: string) {
app.ports.loadContext.subscribe(() => {
const input = fileGatherer.gather(directory);
var configuration;
try {
- configuration = fs.readFileSync('./elm-analyse.json').toString();
+ configuration = fs.readFileSync(path.join(directory, 'elm-analyse.json')).toString();
} catch (e) {
configuration = '';
} |
38ff21bbc0f64e805b75aa954fe2a748ad32e76f | src/log/index.ts | src/log/index.ts | // Copyright 2016 Joe Duffy. All rights reserved.
"use strict";
import * as contract from '../contract';
export interface ILogger {
infof(msg: string, ...args: any[]): void;
errorf(msg: string, ...args: any[]): void;
fatalf(msg: string, ...args: any[]): void;
}
let consoleLogger: ILogger = {
infof: (msg: string, ...args: any[]) => {
console.log(msg, ...args);
},
errorf: (msg: string, ...args: any[]) => {
console.error(msg, ...args);
},
fatalf: (msg: string, ...args: any[]) => {
contract.failf(msg, ...args);
},
};
let ignoreLogger: ILogger = {
infof: (msg: string, ...args: any[]) => {},
errorf: (msg: string, ...args: any[]) => {},
fatalf: (msg: string, ...args: any[]) => {},
};
export function Get(t?: number): ILogger {
if (!!t || t >= v) {
return consoleLogger;
}
return ignoreLogger;
}
let v: number = 0;
export function Set(t: number): void {
v = t;
}
export function V(t: number): boolean {
return (v >= t);
}
| // Copyright 2016 Joe Duffy. All rights reserved.
"use strict";
import * as contract from '../contract';
export interface ILogger {
infof(msg: string, ...args: any[]): void;
errorf(msg: string, ...args: any[]): void;
fatalf(msg: string, ...args: any[]): void;
}
let consoleLogger: ILogger = {
infof: (msg: string, ...args: any[]) => {
console.log(msg, ...args);
},
errorf: (msg: string, ...args: any[]) => {
console.error(msg, ...args);
},
fatalf: (msg: string, ...args: any[]) => {
contract.failf(msg, ...args);
},
};
let ignoreLogger: ILogger = {
infof: (msg: string, ...args: any[]) => {},
errorf: (msg: string, ...args: any[]) => {},
fatalf: (msg: string, ...args: any[]) => {},
};
let loglevel: number = 0;
export function configure(threshold: number): void {
loglevel = threshold;
}
export function out(target?: number): ILogger {
if (target === undefined || v(target)) {
return consoleLogger;
}
return ignoreLogger;
}
export function v(target: number): boolean {
return (target <= loglevel);
}
| Rename functions to be less obscure (and cased properly) | Rename functions to be less obscure (and cased properly)
| TypeScript | mit | joeduffy/nodets | ---
+++
@@ -27,21 +27,20 @@
fatalf: (msg: string, ...args: any[]) => {},
};
-export function Get(t?: number): ILogger {
- if (!!t || t >= v) {
+let loglevel: number = 0;
+
+export function configure(threshold: number): void {
+ loglevel = threshold;
+}
+
+export function out(target?: number): ILogger {
+ if (target === undefined || v(target)) {
return consoleLogger;
}
return ignoreLogger;
}
-let v: number = 0;
-
-export function Set(t: number): void {
- v = t;
+export function v(target: number): boolean {
+ return (target <= loglevel);
}
-export function V(t: number): boolean {
- return (v >= t);
-}
-
- |
d40540a3cefa62121b9c9e9240e780d08ecb8f0b | ui/src/shared/components/LineGraphColorSelector.tsx | ui/src/shared/components/LineGraphColorSelector.tsx | import React, {Component} from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import ColorScaleDropdown from 'src/shared/components/ColorScaleDropdown'
import {updateLineColors} from 'src/dashboards/actions/cellEditorOverlay'
import {ColorNumber} from 'src/types/colors'
import {ErrorHandling} from 'src/shared/decorators/errors'
interface Props {
lineColors: ColorNumber[]
handleUpdateLineColors: (colors: ColorNumber[]) => void
}
@ErrorHandling
class LineGraphColorSelector extends Component<Props> {
public render() {
const {lineColors} = this.props
return (
<div className="form-group col-xs-12">
<label>Line Colors</label>
<ColorScaleDropdown
onChoose={this.handleSelectColors}
stretchToFit={true}
selected={lineColors}
/>
</div>
)
}
public handleSelectColors = colorScale => {
const {handleUpdateLineColors} = this.props
const {colors} = colorScale
handleUpdateLineColors(colors)
}
}
const mapStateToProps = ({cellEditorOverlay: {lineColors}}) => ({
lineColors,
})
const mapDispatchToProps = dispatch => ({
handleUpdateLineColors: bindActionCreators(updateLineColors, dispatch),
})
export default connect(mapStateToProps, mapDispatchToProps)(
LineGraphColorSelector
)
| import React, {Component} from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import ColorScaleDropdown from 'src/shared/components/ColorScaleDropdown'
import {updateLineColors} from 'src/dashboards/actions/cellEditorOverlay'
import {ColorNumber} from 'src/types/colors'
import {ErrorHandling} from 'src/shared/decorators/errors'
interface Props {
lineColors: ColorNumber[]
handleUpdateLineColors: (colors: ColorNumber[]) => void
}
@ErrorHandling
class LineGraphColorSelector extends Component<Props> {
public render() {
const {lineColors} = this.props
return (
<div className="form-group col-xs-12">
<label>Line Colors</label>
<ColorScaleDropdown
onChoose={this.handleSelectColors}
stretchToFit={true}
selected={lineColors}
/>
</div>
)
}
public handleSelectColors = (colorScale): void => {
const {handleUpdateLineColors} = this.props
const {colors} = colorScale
handleUpdateLineColors(colors)
}
}
const mapStateToProps = ({cellEditorOverlay: {lineColors}}) => ({
lineColors,
})
const mapDispatchToProps = dispatch => ({
handleUpdateLineColors: bindActionCreators(updateLineColors, dispatch),
})
export default connect(mapStateToProps, mapDispatchToProps)(
LineGraphColorSelector
)
| Add return type to function | Add return type to function
| TypeScript | mit | influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,li-ang/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb | ---
+++
@@ -30,7 +30,7 @@
)
}
- public handleSelectColors = colorScale => {
+ public handleSelectColors = (colorScale): void => {
const {handleUpdateLineColors} = this.props
const {colors} = colorScale
|
5de7af22754a1fcce14cd411d6f1cee40198afca | front_end/src/app/shared/models/new-parent.ts | front_end/src/app/shared/models/new-parent.ts | export class NewParent {
private static GENDER = {
MALE: 1,
FEMALE: 2
};
FirstName: string;
LastName: string;
PhoneNumber: string;
EmailAddress: string;
GenderId: number = NewParent.GENDER.FEMALE;
CongregationId: number;
DuplicateEmail: string;
HouseholdId: string;
public static genderIdMale(): number {
return NewParent.GENDER.MALE;
}
public static genderIdFemale(): number {
return NewParent.GENDER.FEMALE;
}
static fromJson(json: any): NewParent {
let c = new NewParent();
if (json) {
Object.assign(c, json);
}
return c;
}
constructor(firstName = '', lastName = '', phone = '', email = '') {
this.FirstName = firstName;
this.LastName = lastName;
this.PhoneNumber = phone;
this.EmailAddress = email;
}
public isMale(): boolean {
return this.GenderId === NewParent.GENDER.MALE;
}
public isFemale(): boolean {
return this.GenderId === NewParent.GENDER.FEMALE;
}
}
| export class NewParent {
private static GENDER = {
MALE: 1,
FEMALE: 2
};
FirstName: string;
LastName: string;
PhoneNumber: string;
EmailAddress: string;
GenderId: number;
CongregationId: number;
DuplicateEmail: string;
HouseholdId: string;
public static genderIdMale(): number {
return NewParent.GENDER.MALE;
}
public static genderIdFemale(): number {
return NewParent.GENDER.FEMALE;
}
static fromJson(json: any): NewParent {
let c = new NewParent();
if (json) {
Object.assign(c, json);
}
return c;
}
constructor(firstName = '', lastName = '', phone = '', email = '') {
this.FirstName = firstName;
this.LastName = lastName;
this.PhoneNumber = phone;
this.EmailAddress = email;
}
public isMale(): boolean {
return this.GenderId === NewParent.GENDER.MALE;
}
public isFemale(): boolean {
return this.GenderId === NewParent.GENDER.FEMALE;
}
}
| Remove the requirment of gender. | Remove the requirment of gender.
| TypeScript | bsd-2-clause | crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin | ---
+++
@@ -9,7 +9,7 @@
LastName: string;
PhoneNumber: string;
EmailAddress: string;
- GenderId: number = NewParent.GENDER.FEMALE;
+ GenderId: number;
CongregationId: number;
DuplicateEmail: string;
HouseholdId: string; |
324b533c9970942c442ed84f1e556cdd31e7bbb3 | packages/json-mapper/src/index.ts | packages/json-mapper/src/index.ts | export * from "./components";
export * from "./decorators/jsonMapper";
export * from "./decorators/onDeserialize";
export * from "./decorators/onSerialize";
export * from "./domain/JsonMapperContext";
export * from "./domain/JsonMapperTypesContainer";
export * from "./interfaces/JsonMapperMethods";
export * from "./utils/deserialize";
export * from "./utils/serialize";
| export * from "./components";
export * from "./decorators/jsonMapper";
export * from "./decorators/onDeserialize";
export * from "./decorators/onSerialize";
export * from "./decorators/afterDeserialize";
export * from "./decorators/beforeDeserialize";
export * from "./domain/JsonMapperContext";
export * from "./domain/JsonMapperTypesContainer";
export * from "./interfaces/JsonMapperMethods";
export * from "./utils/deserialize";
export * from "./utils/serialize";
| Add missing exports for AfterDeserialize/BeforeDeserialize decorators | fix(json-mapper): Add missing exports for AfterDeserialize/BeforeDeserialize decorators
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -2,6 +2,8 @@
export * from "./decorators/jsonMapper";
export * from "./decorators/onDeserialize";
export * from "./decorators/onSerialize";
+export * from "./decorators/afterDeserialize";
+export * from "./decorators/beforeDeserialize";
export * from "./domain/JsonMapperContext";
export * from "./domain/JsonMapperTypesContainer";
export * from "./interfaces/JsonMapperMethods"; |
c5b6839c7bc14efe989e12351ce1816b97e1e70d | packages/react-day-picker/src/hooks/useModifiers/useModifiers.ts | packages/react-day-picker/src/hooks/useModifiers/useModifiers.ts | import { ModifierStatus } from '../../types';
import { useDayPicker } from '../useDayPicker';
import { useSelection } from '../useSelection';
import { getModifierStatus } from './utils/getModifierStatus';
/** Return the status for the modifiers given the specified date */
export function useModifiers(date: Date): ModifierStatus {
const context = useDayPicker();
const selection = useSelection();
const modifiers = Object.assign({}, context.modifiers);
if (context.mode !== 'uncontrolled') {
const { single, multiple, range } = selection ?? {};
switch (context.mode) {
case 'range':
if (!range.selected) break;
modifiers.selected = range.selected;
modifiers['range-middle'] = {
after: range.selected.from,
before: range.selected.to
};
modifiers['range-start'] = range.selected.from;
if (range.selected.to) modifiers['range-end'] = range.selected.to;
break;
case 'multiple':
if (!multiple.selected) break;
modifiers.selected = multiple.selected;
break;
default:
case 'single':
if (!single.selected) break;
modifiers.selected = single.selected;
break;
}
}
const status = getModifierStatus(date, modifiers);
return status;
}
| import { ModifierStatus } from '../../types';
import { useDayPicker } from '../useDayPicker';
import { useSelection } from '../useSelection';
import { getModifierStatus } from './utils/getModifierStatus';
/** Return the status for the modifiers given the specified date */
export function useModifiers(date: Date): ModifierStatus {
const context = useDayPicker();
const selection = useSelection();
const modifiers = Object.assign({}, context.modifiers);
modifiers.today = context.today;
if (context.mode !== 'uncontrolled') {
const { single, multiple, range } = selection ?? {};
switch (context.mode) {
case 'range':
if (!range.selected) break;
modifiers.selected = range.selected;
modifiers['range-middle'] = {
after: range.selected.from,
before: range.selected.to
};
modifiers['range-start'] = range.selected.from;
if (range.selected.to) modifiers['range-end'] = range.selected.to;
break;
case 'multiple':
if (!multiple.selected) break;
modifiers.selected = multiple.selected;
break;
default:
case 'single':
if (!single.selected) break;
modifiers.selected = single.selected;
break;
}
}
const status = getModifierStatus(date, modifiers);
return status;
}
| Fix for today modifier not being added | Fix for today modifier not being added
| TypeScript | mit | gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker | ---
+++
@@ -8,6 +8,8 @@
const context = useDayPicker();
const selection = useSelection();
const modifiers = Object.assign({}, context.modifiers);
+
+ modifiers.today = context.today;
if (context.mode !== 'uncontrolled') {
const { single, multiple, range } = selection ?? {}; |
97411075f5eeb19eee057671bf69ae4d037ab720 | src/subscribers/redis-subscriber.ts | src/subscribers/redis-subscriber.ts | var Redis = require('ioredis');
import { Log } from './../log';
import { Subscriber } from './subscriber';
export class RedisSubscriber implements Subscriber {
/**
* Redis pub/sub client.
*
* @type {object}
*/
private _redis: any;
/**
*
* KeyPrefix for used in the redis Connection
*
* @type {String}
*/
private keyPrefix: string;
/**
* Create a new instance of subscriber.
*
* @param {any} options
*/
constructor(private options) {
this._keyPrefix = options.databaseConfig.redis.keyPrefix || '';
this._redis = new Redis(options.databaseConfig.redis);
}
/**
* Subscribe to events to broadcast.
*
* @return {Promise<any>}
*/
subscribe(callback): Promise<any> {
return new Promise((resolve, reject) => {
this._redis.on('pmessage', (subscribed, channel, message) => {
try {
message = JSON.parse(message);
if (this.options.devMode) {
Log.info("Channel: " + channel);
Log.info("Event: " + message.event);
}
callback(channel, message);
} catch (e) {
if (this.options.devMode) {
Log.info("No JSON message");
}
}
});
this._redis.psubscribe(`${this.keyPrefix}*`, (err, count) => {
if (err) {
reject('Redis could not subscribe.')
}
Log.success('Listening for redis events...');
resolve();
});
});
}
}
| var Redis = require('ioredis');
import { Log } from './../log';
import { Subscriber } from './subscriber';
export class RedisSubscriber implements Subscriber {
/**
* Redis pub/sub client.
*
* @type {object}
*/
private _redis: any;
/**
*
* KeyPrefix for used in the redis Connection
*
* @type {String}
*/
private keyPrefix: string;
/**
* Create a new instance of subscriber.
*
* @param {any} options
*/
constructor(private options) {
this._keyPrefix = options.databaseConfig.redis.keyPrefix || '';
this._redis = new Redis(options.databaseConfig.redis);
}
/**
* Subscribe to events to broadcast.
*
* @return {Promise<any>}
*/
subscribe(callback): Promise<any> {
return new Promise((resolve, reject) => {
this._redis.on('pmessage', (subscribed, channel, message) => {
try {
message = JSON.parse(message);
if (this.options.devMode) {
Log.info("Channel: " + channel);
Log.info("Event: " + message.event);
}
callback(channel.substring(0, this.keyPrefix.length), message);
} catch (e) {
if (this.options.devMode) {
Log.info("No JSON message");
}
}
});
this._redis.psubscribe(`${this.keyPrefix}*`, (err, count) => {
if (err) {
reject('Redis could not subscribe.')
}
Log.success('Listening for redis events...');
resolve();
});
});
}
}
| Remove keyPrefix from the channel passed into the callback | Remove keyPrefix from the channel passed into the callback
| TypeScript | mit | tlaverdure/laravel-echo-server,tlaverdure/laravel-echo-server | ---
+++
@@ -45,7 +45,7 @@
Log.info("Event: " + message.event);
}
- callback(channel, message);
+ callback(channel.substring(0, this.keyPrefix.length), message);
} catch (e) {
if (this.options.devMode) {
Log.info("No JSON message"); |
293a15b13bc581e8fc6c3807294f3d7af198fbca | loaders/LoaderEntriesCache.ts | loaders/LoaderEntriesCache.ts | import { Cache, CacheClass } from "memory-cache"
export type EntriesReloader<Entry> = () => Promise<Entry[]>
export class LoaderEntriesCache<Entry> {
get entries(): Promise<Entry[]> {
return this.getEntries()
}
readonly timeout: number
private get cachedEntries(): Entry[] | null {
return this.#cache.get(this.#cacheKey)
}
private set cachedEntries(entries: Entry[] | null) {
if (entries === null) {
this.#cache.del(this.#cacheKey)
} else {
this.#cache.put(this.#cacheKey, entries, this.timeout)
}
}
private entriesReloader: EntriesReloader<Entry>
#cache: CacheClass<string, Entry[]>
#cacheKey: string
/**
*
* @param timeout The time in ms for cached values to be valid for. Defaults to 6 hours.
*/
constructor(
entriesReloader: EntriesReloader<Entry>,
key: string,
timeout: number = 6 * 60 * 1000,
) {
this.entriesReloader = entriesReloader
this.#cache = new Cache()
this.#cacheKey = key
this.timeout = timeout
}
private async getEntries(): Promise<Entry[]> {
if (this.cachedEntries !== null) {
return this.cachedEntries
}
const entries = await this.entriesReloader()
this.cachedEntries = entries
return entries
}
}
| import { Cache, CacheClass } from "memory-cache"
export type EntriesReloader<Entry> = () => Promise<Entry[]>
export class LoaderEntriesCache<Entry> {
get entries(): Promise<Entry[]> {
return this.getEntries()
}
readonly timeout: number
private get cachedEntries(): Entry[] | null {
return this.#cache.get(this.#cacheKey)
}
private set cachedEntries(entries: Entry[] | null) {
if (entries === null) {
this.#cache.del(this.#cacheKey)
} else {
this.#cache.put(this.#cacheKey, entries, this.timeout)
}
}
private entriesReloader: EntriesReloader<Entry>
#cache: CacheClass<string, Entry[]>
#cacheKey: string
/**
*
* @param timeout The time in ms for cached values to be valid for. Defaults to 6 hours.
*/
constructor(
entriesReloader: EntriesReloader<Entry>,
key: string,
timeout: number = 6 * 60 * 1000,
) {
this.entriesReloader = entriesReloader
this.#cache = new Cache()
this.#cacheKey = key
this.timeout = timeout
}
private async getEntries(): Promise<Entry[]> {
if (this.cachedEntries !== null) {
console.debug(`Cache hit for key ${this.#cacheKey}`)
return this.cachedEntries
}
console.debug(`Cache miss for key ${this.#cacheKey}`)
const entries = await this.entriesReloader()
this.cachedEntries = entries
return entries
}
}
| Add debug logging for cache hit and miss | Add debug logging for cache hit and miss
| TypeScript | mit | JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk | ---
+++
@@ -44,8 +44,11 @@
private async getEntries(): Promise<Entry[]> {
if (this.cachedEntries !== null) {
+ console.debug(`Cache hit for key ${this.#cacheKey}`)
return this.cachedEntries
}
+
+ console.debug(`Cache miss for key ${this.#cacheKey}`)
const entries = await this.entriesReloader()
this.cachedEntries = entries |
f5c228dd7b5779dddd1ac2dea7dea813545e072e | angular/app/pages/about/about.component.ts | angular/app/pages/about/about.component.ts | import { Component } from '@angular/core';
@Component({
selector: 'avl-about',
template: require('html!./about.component.html'),
styles: [require('!raw!sass!./about.component.scss')]
})
export class AboutComponent {
constructor() {
console.log('testdfsdfsdfsdfs');
}
ngOnInit() {
}
}
| import { Component } from '@angular/core';
@Component({
selector: 'avl-about',
template: require('html!./about.component.html'),
styles: [require('!raw!sass!./about.component.scss')]
})
export class AboutComponent {
constructor() {
}
}
| Remove console.log and unused method | Remove console.log and unused method
| TypeScript | mit | jaesung2061/anvel,jaesung2061/anvel,jaesung2061/anvel | ---
+++
@@ -7,9 +7,5 @@
})
export class AboutComponent {
constructor() {
- console.log('testdfsdfsdfsdfs');
- }
-
- ngOnInit() {
}
} |
38c2fc47bf987b41ad8afd3fdc0fca494d6cc9fe | packages/compile-common/src/types.ts | packages/compile-common/src/types.ts | import { Abi, ImmutableReferences } from "@truffle/contract-schema/spec";
export type Compilation = {
sourceIndexes: string[];
contracts: CompiledContract[];
compiler: {
name: string | undefined;
version: string | undefined;
};
};
export interface CompilerResult {
compilations: Compilation[];
}
export interface Bytecode {
bytes: string;
linkReferences: LinkReference[];
}
export interface LinkReference {
offsets: number[];
name: string | null; // this will be the contractName of the library or some other identifier
length: number;
}
export type CompiledContract = {
contractName: string;
sourcePath: string;
source: string;
sourceMap: string;
deployedSourceMap: string;
legacyAST: object;
ast: object;
abi: Abi;
metadata: string;
bytecode: Bytecode;
deployedBytecode: Bytecode;
compiler: {
name: string;
version: string;
};
devdoc: object;
userdoc: object;
immutableReferences: ImmutableReferences;
generatedSources: any;
deployedGeneratedSources: any;
};
export interface WorkflowCompileResult {
compilations: Compilation[];
contracts: CompiledContract[];
}
export interface Compiler {
all: (options: object) => Promise<CompilerResult>;
necessary: (options: object) => Promise<CompilerResult>;
sources: ({
sources,
options
}: {
sources: object;
options: object;
}) => Promise<CompilerResult>;
}
| import { Abi, ImmutableReferences } from "@truffle/contract-schema/spec";
export type Compilation = {
sourceIndexes: string[]; //note: doesnot include internal sources
contracts: CompiledContract[];
compiler: {
name: string | undefined;
version: string | undefined;
};
};
export interface CompilerResult {
compilations: Compilation[];
}
export interface Bytecode {
bytes: string;
linkReferences: LinkReference[];
}
export interface LinkReference {
offsets: number[];
name: string | null; // this will be the contractName of the library or some other identifier
length: number;
}
export type CompiledContract = {
contractName: string;
sourcePath: string;
source: string;
sourceMap: string;
deployedSourceMap: string;
legacyAST: object;
ast: object;
abi: Abi;
metadata: string;
bytecode: Bytecode;
deployedBytecode: Bytecode;
compiler: {
name: string;
version: string;
};
devdoc: object;
userdoc: object;
immutableReferences: ImmutableReferences;
generatedSources: any;
deployedGeneratedSources: any;
};
export interface WorkflowCompileResult {
compilations: Compilation[];
contracts: CompiledContract[];
}
export interface Compiler {
all: (options: object) => Promise<CompilerResult>;
necessary: (options: object) => Promise<CompilerResult>;
sources: ({
sources,
options
}: {
sources: object;
options: object;
}) => Promise<CompilerResult>;
}
| Add comment stating that sourceIndexes does not contain internal sources | Add comment stating that sourceIndexes does not contain internal sources
| TypeScript | mit | ConsenSys/truffle | ---
+++
@@ -1,7 +1,7 @@
import { Abi, ImmutableReferences } from "@truffle/contract-schema/spec";
export type Compilation = {
- sourceIndexes: string[];
+ sourceIndexes: string[]; //note: doesnot include internal sources
contracts: CompiledContract[];
compiler: {
name: string | undefined; |
e5f0b48547e0984afcebcd04ca3f961367bdb9a0 | dashboard/src/components/attribute/scroll/che-automatic-scroll.directive.ts | dashboard/src/components/attribute/scroll/che-automatic-scroll.directive.ts | /*
* Copyright (c) 2015-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*/
'use strict';
/**
* @ngdoc directive
* @name components.directive:cheAutoScroll
* @restrict A
* @function
* @element
*
* @description
* `che-auto-scroll` defines an attribute for auto scrolling to the bottom of the element applied.
*
* @usage
* <text-area che-auto-scroll></text-area>
*
* @author Florent Benoit
*/
export class CheAutoScroll {
/**
* Default constructor that is using resource
* @ngInject for Dependency injection
*/
constructor($timeout) {
this.$timeout = $timeout;
this.restrict = 'A';
}
/**
* Keep reference to the model controller
*/
link($scope, element, attr) {
$scope.$watch(attr.ngModel, () => {
this.$timeout(() => {
element[0].scrollTop = element[0].scrollHeight;
});
});
}
}
| /*
* Copyright (c) 2015-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*/
'use strict';
/**
* @ngdoc directive
* @name components.directive:cheAutoScroll
* @restrict A
* @function
* @element
*
* @description
* `che-auto-scroll` defines an attribute for auto scrolling to the bottom of the element applied.
*
* @usage
* <text-area che-auto-scroll></text-area>
*
* @author Florent Benoit
*/
export class CheAutoScroll {
/**
* Default constructor that is using resource
* @ngInject for Dependency injection
*/
constructor($timeout) {
this.$timeout = $timeout;
this.restrict = 'A';
}
/**
* Keep reference to the model controller
*/
link($scope, element, attr) {
$scope.$watch(attr.ngModel, () => {
this.$timeout(() => {
element[0].scrollTop = element[0].scrollHeight;
});
}, true);
}
}
| Allow auto-scroll to be used on array elements by watching internal changes | Allow auto-scroll to be used on array elements by watching internal changes
Change-Id: I931d6c980794480c4a7453a46ffd3cf21f695910
Signed-off-by: Florent BENOIT <[email protected]>
| TypeScript | epl-1.0 | sudaraka94/che,davidfestal/che,Patricol/che,lehmanju/che,akervern/che,akervern/che,Patricol/che,snjeza/che,sleshchenko/che,sleshchenko/che,codenvy/che,jonahkichwacoders/che,sleshchenko/che,snjeza/che,cemalkilic/che,TypeFox/che,bartlomiej-laczkowski/che,bartlomiej-laczkowski/che,Patricol/che,Patricol/che,sunix/che,bartlomiej-laczkowski/che,codenvy/che,lehmanju/che,snjeza/che,sudaraka94/che,snjeza/che,sudaraka94/che,lehmanju/che,cemalkilic/che,sudaraka94/che,akervern/che,sleshchenko/che,sleshchenko/che,sleshchenko/che,cemalkilic/che,Patricol/che,sudaraka94/che,davidfestal/che,cemalkilic/che,akervern/che,jonahkichwacoders/che,sudaraka94/che,sleshchenko/che,sunix/che,sunix/che,davidfestal/che,jonahkichwacoders/che,davidfestal/che,snjeza/che,bartlomiej-laczkowski/che,sunix/che,cemalkilic/che,sleshchenko/che,jonahkichwacoders/che,sudaraka94/che,snjeza/che,akervern/che,davidfestal/che,jonahkichwacoders/che,jonahkichwacoders/che,TypeFox/che,TypeFox/che,bartlomiej-laczkowski/che,TypeFox/che,lehmanju/che,TypeFox/che,lehmanju/che,bartlomiej-laczkowski/che,davidfestal/che,lehmanju/che,snjeza/che,sudaraka94/che,bartlomiej-laczkowski/che,davidfestal/che,jonahkichwacoders/che,TypeFox/che,lehmanju/che,akervern/che,sunix/che,TypeFox/che,davidfestal/che,cemalkilic/che,codenvy/che,Patricol/che,cemalkilic/che,davidfestal/che,sunix/che,akervern/che,TypeFox/che,sunix/che,codenvy/che,snjeza/che,jonahkichwacoders/che,jonahkichwacoders/che,TypeFox/che,sleshchenko/che,bartlomiej-laczkowski/che,Patricol/che,snjeza/che,lehmanju/che,davidfestal/che,cemalkilic/che,sleshchenko/che,lehmanju/che,jonahkichwacoders/che,bartlomiej-laczkowski/che,sudaraka94/che,sudaraka94/che,Patricol/che,sunix/che,sunix/che,akervern/che,akervern/che,cemalkilic/che,Patricol/che,Patricol/che,TypeFox/che | ---
+++
@@ -44,7 +44,7 @@
this.$timeout(() => {
element[0].scrollTop = element[0].scrollHeight;
});
- });
+ }, true);
}
} |
a4d1698e2e428801e86e7543f427aa917225e538 | src/node/worker/node-worker-thread-factory.ts | src/node/worker/node-worker-thread-factory.ts | import {fork} from "child_process";
import {IWorkerThreadFactory} from "../../common/worker/worker-thread-factory";
import {DefaultWorkerThread} from "../../common/worker/default-worker-thread";
import {IWorkerThread} from "../../common/worker/worker-thread";
import {DynamicFunctionRegistry} from "../../common/function/dynamic-function-registry";
import {ChildProcessWorkerThreadSlaveCommunicationChannel} from "./child-process-worker-thread-slave-communication-channel";
export class NodeWorkerThreadFactory implements IWorkerThreadFactory {
constructor(private functionLookupTable: DynamicFunctionRegistry) {}
public spawn(): IWorkerThread {
const child = fork(this.getSlaveFileName());
const workerThread = new DefaultWorkerThread(this.functionLookupTable, new ChildProcessWorkerThreadSlaveCommunicationChannel(child));
workerThread.initialize();
return workerThread;
}
/**
* Hackedy Hack... Issue is, webpack handles calls to require resolve and replaces the call with the module id
* but that's not what we want. We actually want the require resolve call to be left until execution.
* NoParse is neither an option because then no requires / imports are resolved
* @returns {string} the file name of the slave
*/
private getSlaveFileName(): string {
/* tslint:disable:no-eval */
const requireResolve = eval("require.resolve") as (moduleName: string) => string;
/* tslint:enable:no-eval */
// TODO get es5 or es6 version
return requireResolve("parallel-es/dist/node-slave.parallel.js");
}
}
| import {fork} from "child_process";
import {IWorkerThreadFactory} from "../../common/worker/worker-thread-factory";
import {DefaultWorkerThread} from "../../common/worker/default-worker-thread";
import {IWorkerThread} from "../../common/worker/worker-thread";
import {DynamicFunctionRegistry} from "../../common/function/dynamic-function-registry";
import {ChildProcessWorkerThreadSlaveCommunicationChannel} from "./child-process-worker-thread-slave-communication-channel";
export class NodeWorkerThreadFactory implements IWorkerThreadFactory {
constructor(private functionLookupTable: DynamicFunctionRegistry) {}
public spawn(): IWorkerThread {
const child = fork(this.getSlaveFileName());
const workerThread = new DefaultWorkerThread(this.functionLookupTable, new ChildProcessWorkerThreadSlaveCommunicationChannel(child));
workerThread.initialize();
return workerThread;
}
/**
* Hackedy Hack... Issue is, webpack handles calls to require resolve and replaces the call with the module id
* but that's not what we want. We actually want the require resolve call to be left until execution.
* NoParse is neither an option because then no requires / imports are resolved
* @returns {string} the file name of the slave
*/
private getSlaveFileName(): string {
return eval("require").resolve("./node-slave.parallel");
}
}
| Fix module resolution for node slave | Fix module resolution for node slave
| TypeScript | mit | DatenMetzgerX/parallel.es,DatenMetzgerX/parallel.es,MichaReiser/parallel.es,MichaReiser/parallel.es,DatenMetzgerX/parallel.es,MichaReiser/parallel.es | ---
+++
@@ -23,10 +23,6 @@
* @returns {string} the file name of the slave
*/
private getSlaveFileName(): string {
- /* tslint:disable:no-eval */
- const requireResolve = eval("require.resolve") as (moduleName: string) => string;
- /* tslint:enable:no-eval */
- // TODO get es5 or es6 version
- return requireResolve("parallel-es/dist/node-slave.parallel.js");
+ return eval("require").resolve("./node-slave.parallel");
}
} |
c9719c0e99347cf07389228b89f60c8808cd2ac2 | app/src/lib/__tests__/tasks_xfail.ts | app/src/lib/__tests__/tasks_xfail.ts | import { ITask, tasksRepository } from "../tasks";
jest.mock("axios", () => ({
default: {
get: (): Promise<any> => Promise.reject(new Error()),
},
}));
it("gets no task on error", async () => {
expect.assertions(1);
expect((await tasksRepository(false).get()).length).toBe(0);
});
| import { ITask, tasksRepository } from "../tasks";
jest.mock("axios", () => ({
default: {
get: (): Promise<any> => Promise.reject({ code: "storage/object-not-found" }),
},
}));
it("gets no task on error", async () => {
expect.assertions(1);
expect((await tasksRepository(false).get()).length).toBe(0);
});
| Fix xfail test of tasks repository | Fix xfail test of tasks repository
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -2,7 +2,7 @@
jest.mock("axios", () => ({
default: {
- get: (): Promise<any> => Promise.reject(new Error()),
+ get: (): Promise<any> => Promise.reject({ code: "storage/object-not-found" }),
},
}));
|
ba83cbf441c20bf1630b38ecbfaa3d1289b0c147 | src/Components/ArtworkGrid/ArtworkGridEmptyState.tsx | src/Components/ArtworkGrid/ArtworkGridEmptyState.tsx | import { Message } from "@artsy/palette"
import React from "react"
import styled from "styled-components"
interface ArtworkGridEmptyStateProps {
onClearFilters?: () => void
}
export const ArtworkGridEmptyState: React.SFC<ArtworkGridEmptyStateProps> = props => (
<EmptyMessage>
<span>
There aren't any works available that meet the following criteria at this
time.
</span>
{props.onClearFilters && (
<span>
{" "}
Change your filter criteria to view more works.{" "}
<a onClick={props.onClearFilters}>Clear all filters</a>.
</span>
)}
</EmptyMessage>
)
// TODO: add link styling to palette Message
const EmptyMessage = styled(Message)`
a {
text-decoration: underline;
cursor: pointer;
}
`
EmptyMessage.displayName = "EmptyMessage"
| import { Message } from "@artsy/palette"
import React from "react"
import styled from "styled-components"
interface ArtworkGridEmptyStateProps {
onClearFilters?: () => void
}
export const ArtworkGridEmptyState: React.SFC<ArtworkGridEmptyStateProps> = props => (
<Message>
<span>
There aren't any works available that meet the following criteria at this
time.
</span>
{props.onClearFilters && (
<span>
{" "}
Change your filter criteria to view more works.{" "}
<ResetFilterLink onClick={props.onClearFilters}>
Clear all filters
</ResetFilterLink>
.
</span>
)}
</Message>
)
const ResetFilterLink = styled.span`
text-decoration: underline;
cursor: pointer;
`
| Change reset link to be text instead of an anchor tag | [Filter] Change reset link to be text instead of an anchor tag
| TypeScript | mit | artsy/reaction,artsy/reaction,artsy/reaction-force,artsy/reaction-force,artsy/reaction | ---
+++
@@ -7,7 +7,7 @@
}
export const ArtworkGridEmptyState: React.SFC<ArtworkGridEmptyStateProps> = props => (
- <EmptyMessage>
+ <Message>
<span>
There aren't any works available that meet the following criteria at this
time.
@@ -16,18 +16,16 @@
<span>
{" "}
Change your filter criteria to view more works.{" "}
- <a onClick={props.onClearFilters}>Clear all filters</a>.
+ <ResetFilterLink onClick={props.onClearFilters}>
+ Clear all filters
+ </ResetFilterLink>
+ .
</span>
)}
- </EmptyMessage>
+ </Message>
)
-// TODO: add link styling to palette Message
-const EmptyMessage = styled(Message)`
- a {
- text-decoration: underline;
- cursor: pointer;
- }
+const ResetFilterLink = styled.span`
+ text-decoration: underline;
+ cursor: pointer;
`
-
-EmptyMessage.displayName = "EmptyMessage" |
8c591994a09eee5f4f89ca92a6a043e384c59b2c | src/security/Cookies.ts | src/security/Cookies.ts | import Test from '../Test';
class Cookies extends Test {
protected request: RequestInterface;
protected logger: LoggerInterface;
constructor(request: RequestInterface, logger: LoggerInterface) {
super();
this.request = request;
this.logger = logger;
}
public async run(url: string): Promise<ResultInterface> {
this.logger.info('Starting Cookies test...');
const result = await this.request.get(url);
let subChecks = null;
if (result.response.headers.hasOwnProperty('set-cookie')) {
const cookies = result.response.headers['set-cookie'];
subChecks = this.checkCookies(cookies);
}
return this.getResult('Cookies', this.getStatus(subChecks), subChecks);
}
private checkCookies(cookies: string[]): ResultInterface[] {
const regx = new RegExp('.*(secure; HttpOnly)$', 'i');
return cookies.map((cookie) => {
if (!regx.test(cookie)) {
return this.getResult(cookie.substr(0, cookie.indexOf('=')), 'UNSUCCESSFUL');
}
return this.getResult(cookie.substr(0, cookie.indexOf('=')), 'SUCCESSFUL');
});
}
}
export default Cookies;
| import Test from '../Test';
class Cookies extends Test {
protected request: RequestInterface;
protected logger: LoggerInterface;
constructor(request: RequestInterface, logger: LoggerInterface) {
super();
this.request = request;
this.logger = logger;
}
public async run(url: string): Promise<ResultInterface> {
this.logger.info('Starting Cookies test...');
const result = await this.request.get(url);
let subChecks = [];
if (result.response.headers.hasOwnProperty('set-cookie')) {
const cookies = result.response.headers['set-cookie'];
subChecks = this.checkCookies(cookies);
}
return this.getResult('Cookies', this.getStatus(subChecks), subChecks);
}
private checkCookies(cookies: string[]): ResultInterface[] {
const regx = new RegExp('.*(secure; HttpOnly)$', 'i');
return cookies.map((cookie) => {
if (!regx.test(cookie)) {
return this.getResult(cookie.substr(0, cookie.indexOf('=')), 'UNSUCCESSFUL');
}
return this.getResult(cookie.substr(0, cookie.indexOf('=')), 'SUCCESSFUL');
});
}
}
export default Cookies;
| Fix issue when page doesn't have any cookies | Fix issue when page doesn't have any cookies
| TypeScript | mit | juffalow/pentest-tool-lite,juffalow/pentest-tool-lite | ---
+++
@@ -14,7 +14,7 @@
public async run(url: string): Promise<ResultInterface> {
this.logger.info('Starting Cookies test...');
const result = await this.request.get(url);
- let subChecks = null;
+ let subChecks = [];
if (result.response.headers.hasOwnProperty('set-cookie')) {
const cookies = result.response.headers['set-cookie']; |
9dc850c2a4f9e9a0034bcd8e9ba5f9dd1a7c7ee1 | examples/simple/index.ts | examples/simple/index.ts | import {Observable, map} from '../../src/Observable';
import {h} from '../../src/DOMBuilder';
import run from '../../src/run';
const app = (input$: Observable<string>) => {
let inputOn;
const DOM = h('div', [
h('label', ['Name: ']),
h('br'),
h('span', ['Hello ']), h('span', [input$]),
h('h1', [
{on: inputOn} = h('input'),
input$
])
]);
const inputEvent$ = inputOn('input');
input$.def = map(ev => ev.target.value, inputEvent$);
return DOM;
};
run('body', app);
| import {Observable, map} from '../../src/Observable';
import {h} from '../../src/DOMBuilder';
import run from '../../src/run';
const app = (input$: Observable<string>) => {
let inputOn;
const DOM = h('div', [
h('span', ['Hello ']), h('span', [input$]),
h('br'),
h('label', ['Name: ']),
{on: inputOn} = h('input')
]);
const inputEvent$ = inputOn('input');
input$.def = map(ev => ev.target.value, inputEvent$);
return DOM;
};
run('body', app);
| Tweak DOM so input isn't inside h1 | Tweak DOM so input isn't inside h1
| TypeScript | mit | Funkia/hareactive,Funkia/hareactive,paldepind/hareactive,Funkia/hareactive,paldepind/hareactive,paldepind/hareactive | ---
+++
@@ -7,13 +7,10 @@
let inputOn;
const DOM = h('div', [
+ h('span', ['Hello ']), h('span', [input$]),
+ h('br'),
h('label', ['Name: ']),
- h('br'),
- h('span', ['Hello ']), h('span', [input$]),
- h('h1', [
- {on: inputOn} = h('input'),
- input$
- ])
+ {on: inputOn} = h('input')
]);
const inputEvent$ = inputOn('input'); |
7107d2eecf7c96704a0f5361f7a3df23ef3acd29 | src/transports/index.ts | src/transports/index.ts | import {EventEmitter} from 'nomatic-events';
import {LoggerEntry} from '../logger';
export interface TransportOptions {
level?: string;
[key: string]: any;
}
export abstract class Transport extends EventEmitter {
public level: string;
constructor(options: TransportOptions = {}) {
super();
this.level = options.level || null;
}
public abstract execute(entry: LoggerEntry);
}
| import {EventEmitter} from 'nomatic-events';
import {LoggerEntry} from '../../src';
export interface TransportOptions {
level?: string;
[key: string]: any;
}
export abstract class Transport extends EventEmitter {
public level: string;
constructor(options: TransportOptions = {}) {
super();
this.level = options.level || null;
}
public abstract execute(entry: LoggerEntry);
}
| Fix import of LoggerEntry interface | fix(Transport): Fix import of LoggerEntry interface
| TypeScript | mit | bdfoster/nomatic-logging | ---
+++
@@ -1,5 +1,5 @@
import {EventEmitter} from 'nomatic-events';
-import {LoggerEntry} from '../logger';
+import {LoggerEntry} from '../../src';
export interface TransportOptions {
level?: string; |
3ee8a3a64607749c03406fdfab678f941caf05f9 | src/app/documents/fields-view.component.ts | src/app/documents/fields-view.component.ts | import {Component, OnInit, OnChanges, Input} from "@angular/core";
import {ConfigLoader} from "../configuration/config-loader";
import {Resource} from "../model/resource";
@Component({
selector: 'fields-view',
moduleId: module.id,
templateUrl: './fields-view.html'
})
/**
* Shows fields of a document.
*
* @author Thomas Kleinke
* @author Sebastian Cuy
*/
export class FieldsViewComponent implements OnInit, OnChanges {
protected fields: Array<any>;
@Input() doc;
constructor(
private configLoader: ConfigLoader
) {
}
private init() {
this.fields = [];
if (!this.doc) return;
this.initializeFields(this.doc.resource);
}
ngOnInit() {
this.init();
}
ngOnChanges() {
this.init();
}
private initializeFields(resource: Resource) {
this.configLoader.getProjectConfiguration().then(
projectConfiguration => {
const ignoredFields: Array<string> = [ "relations" ];
for (var fieldName in resource) {
if (projectConfiguration.isVisible(resource.type,fieldName)==false) continue;
if (resource.hasOwnProperty(fieldName) && ignoredFields.indexOf(fieldName) == -1) {
this.fields.push({
name: projectConfiguration.getFieldDefinitionLabel(resource.type, fieldName),
value: resource[fieldName],
isArray: Array.isArray(resource[fieldName])
});
}
}
})
}
} | import {Component, OnChanges, Input} from "@angular/core";
import {ConfigLoader} from "../configuration/config-loader";
import {Resource} from "../model/resource";
@Component({
selector: 'fields-view',
moduleId: module.id,
templateUrl: './fields-view.html'
})
/**
* Shows fields of a document.
*
* @author Thomas Kleinke
* @author Sebastian Cuy
*/
export class FieldsViewComponent implements OnChanges {
protected fields: Array<any>;
@Input() doc;
constructor(
private configLoader: ConfigLoader
) { }
ngOnChanges() {
this.fields = [];
if (!this.doc) return;
this.processFields(this.doc.resource);
}
private processFields(resource: Resource) {
this.configLoader.getProjectConfiguration().then(
projectConfiguration => {
const ignoredFields: Array<string> = [ "relations" ];
for (let fieldName in resource) {
if (projectConfiguration.isVisible(resource.type,fieldName)==false) continue;
if (resource.hasOwnProperty(fieldName) && ignoredFields.indexOf(fieldName) == -1) {
this.fields.push({
name: projectConfiguration.getFieldDefinitionLabel(resource.type, fieldName),
value: resource[fieldName],
isArray: Array.isArray(resource[fieldName])
});
}
}
})
}
} | Fix where fields can appear twice. | Fix where fields can appear twice.
| TypeScript | apache-2.0 | dainst/idai-components-2,dainst/idai-components-2,dainst/idai-components-2 | ---
+++
@@ -1,4 +1,4 @@
-import {Component, OnInit, OnChanges, Input} from "@angular/core";
+import {Component, OnChanges, Input} from "@angular/core";
import {ConfigLoader} from "../configuration/config-loader";
import {Resource} from "../model/resource";
@@ -14,7 +14,7 @@
* @author Thomas Kleinke
* @author Sebastian Cuy
*/
-export class FieldsViewComponent implements OnInit, OnChanges {
+export class FieldsViewComponent implements OnChanges {
protected fields: Array<any>;
@@ -22,31 +22,22 @@
constructor(
private configLoader: ConfigLoader
- ) {
+ ) { }
+
+ ngOnChanges() {
+ this.fields = [];
+ if (!this.doc) return;
+ this.processFields(this.doc.resource);
}
- private init() {
- this.fields = [];
- if (!this.doc) return;
- this.initializeFields(this.doc.resource);
- }
-
- ngOnInit() {
- this.init();
- }
-
- ngOnChanges() {
- this.init();
- }
-
- private initializeFields(resource: Resource) {
+ private processFields(resource: Resource) {
this.configLoader.getProjectConfiguration().then(
projectConfiguration => {
const ignoredFields: Array<string> = [ "relations" ];
- for (var fieldName in resource) {
+ for (let fieldName in resource) {
if (projectConfiguration.isVisible(resource.type,fieldName)==false) continue;
|
93e79bc88e9d21b29d4c988f80640c808ba633f3 | src/util/useBrowserEffect.tsx | src/util/useBrowserEffect.tsx | import { DependencyList, EffectCallback, useLayoutEffect } from "react";
/**
* Source: https://medium.com/@alexandereardon/uselayouteffect-and-ssr-192986cdcf7a
*/
function noOpEffect(effect: EffectCallback, deps?: DependencyList) {
console.debug("No effect called", effect, deps);
}
const useBrowserEffect =
typeof window !== "undefined" ? useLayoutEffect : noOpEffect;
export default useBrowserEffect;
| import { DependencyList, EffectCallback, useLayoutEffect } from "react";
/**
* Source: https://medium.com/@alexandereardon/uselayouteffect-and-ssr-192986cdcf7a
*/
function noOpEffect(effect: EffectCallback, deps?: DependencyList) {
// console.debug("No effect called", effect, deps);
}
const useBrowserEffect =
typeof window !== "undefined" ? useLayoutEffect : noOpEffect;
export default useBrowserEffect;
| Stop with all the debug output | Stop with all the debug output
| TypeScript | apache-2.0 | saasquatch/saasquatch-docs,saasquatch/saasquatch-docs,saasquatch/saasquatch-docs | ---
+++
@@ -4,9 +4,8 @@
* Source: https://medium.com/@alexandereardon/uselayouteffect-and-ssr-192986cdcf7a
*/
-
function noOpEffect(effect: EffectCallback, deps?: DependencyList) {
- console.debug("No effect called", effect, deps);
+ // console.debug("No effect called", effect, deps);
}
const useBrowserEffect = |
b3b3b9d470fecb7461657daa3dc45f2d746af190 | src/app/settings/initial-settings.ts | src/app/settings/initial-settings.ts | import { defaultSettings, Settings as DimApiSettings } from '@destinyitemmanager/dim-api-types';
import { defaultLanguage } from 'app/i18n';
export const enum LoadoutSort {
ByEditTime,
ByName,
}
/**
* We extend the settings interface so we can try out new settings before committing them to dim-api-types
*/
export interface Settings extends DimApiSettings {
/** How many spaces to clear when using Farming Mode(make space). */
inventoryClearSpaces: number;
/** Display perks as a list instead of a grid. */
perkList: boolean;
loadoutSort: LoadoutSort;
itemFeedHideTagged: boolean;
itemFeedExpanded: boolean;
}
export const initialSettingsState: Settings = {
...defaultSettings,
language: defaultLanguage(),
inventoryClearSpaces: 1,
perkList: true,
loadoutSort: LoadoutSort.ByEditTime,
itemFeedHideTagged: false,
itemFeedExpanded: false,
};
| import { defaultSettings, Settings as DimApiSettings } from '@destinyitemmanager/dim-api-types';
import { defaultLanguage } from 'app/i18n';
export const enum LoadoutSort {
ByEditTime,
ByName,
}
/**
* We extend the settings interface so we can try out new settings before committing them to dim-api-types
*/
export interface Settings extends DimApiSettings {
/** How many spaces to clear when using Farming Mode(make space). */
inventoryClearSpaces: number;
/** Display perks as a list instead of a grid. */
perkList: boolean;
loadoutSort: LoadoutSort;
itemFeedHideTagged: boolean;
itemFeedExpanded: boolean;
}
export const initialSettingsState: Settings = {
...defaultSettings,
language: defaultLanguage(),
inventoryClearSpaces: 1,
perkList: true,
loadoutSort: LoadoutSort.ByEditTime,
itemFeedHideTagged: true,
itemFeedExpanded: false,
};
| Change hide tagged to default true | Change hide tagged to default true
| TypeScript | mit | delphiactual/DIM,delphiactual/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,delphiactual/DIM,DestinyItemManager/DIM,delphiactual/DIM | ---
+++
@@ -25,6 +25,6 @@
inventoryClearSpaces: 1,
perkList: true,
loadoutSort: LoadoutSort.ByEditTime,
- itemFeedHideTagged: false,
+ itemFeedHideTagged: true,
itemFeedExpanded: false,
}; |
7d0b51e497b130385527d3de80f2c2dd15335c50 | src/client/app/soundcloud/soundcloud.service.ts | src/client/app/soundcloud/soundcloud.service.ts | import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
@Injectable()
export class SoundcloudService {
public basePath: string = 'https://api.soundcloud.com/tracks';
private _clientId: string = '8159b4b99151c48d6aaf6770853bfd7a';
constructor(private _http: Http) {
}
public getTrack(trackId: number) {
let params = new URLSearchParams();
params.set('client_id', this._clientId);
let url = this.basePath + `/${trackId}`;
return this._http.get(url, {search: params});
}
public search(searchTerm: string) {
let params = new URLSearchParams();
params.set('client_id', this._clientId);
params.set('q', searchTerm);
return this._http.get(this.basePath, {search: params});
}
}
| import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
@Injectable()
export class SoundcloudService {
public basePath: string = 'https://api.soundcloud.com/tracks';
private _clientId: string = '8159b4b99151c48d6aaf6770853bfd7a';
constructor(private _http: Http) {
}
public getTrack(trackId: number) {
let params = new URLSearchParams();
params.set('client_id', this._clientId);
let url = this.basePath + `/${trackId}`;
return this._http.get(url, {search: params});
}
public search(searchTerm: string) {
const LIMIT: number = 200;
let params = new URLSearchParams();
params.set('client_id', this._clientId);
params.set('q', searchTerm);
params.set('limit', LIMIT);
return this._http.get(this.basePath, {search: params});
}
}
| Set search limit to 200 | Set search limit to 200
| TypeScript | mit | JavierPDev/SounderProject,JavierPDev/SounderRadio,JavierPDev/SounderRadio,JavierPDev/SounderRadio,JavierPDev/SounderProject,JavierPDev/SounderProject | ---
+++
@@ -17,9 +17,11 @@
}
public search(searchTerm: string) {
+ const LIMIT: number = 200;
let params = new URLSearchParams();
params.set('client_id', this._clientId);
params.set('q', searchTerm);
+ params.set('limit', LIMIT);
return this._http.get(this.basePath, {search: params});
}
} |
3e6b7cf1a1832e97efa3289653d1db31f92ce743 | server/src/actions/proxy.ts | server/src/actions/proxy.ts | import axios from 'axios';
import { Request, Response } from 'express';
interface ProxyRequest {
body: string;
headers: { [name: string]: string };
method: string;
url: string;
}
export function proxy(req: Request, res: Response) {
const content = req.body as ProxyRequest;
const request = {
method: content.method,
data: content.body,
headers: content.headers,
url: content.url
};
axios.request(request)
.then(r => res.send(r.data))
.catch(e => {
if (e.response && e.response.status) {
res.status(e.response.status).send(e.response);
} else if (e.request) {
res.status(400).send({
reason: 'PassThrough',
error: 'request error'
});
} else {
res.status(400).send({
reason: 'PassThrough',
error: e.code
});
}
});
}
| import axios from 'axios';
import { Request, Response } from 'express';
interface ProxyRequest {
body: string;
headers: { [name: string]: string };
method: string;
url: string;
}
export function proxy(req: Request, res: Response) {
const content = req.body as ProxyRequest;
const request = {
method: content.method,
data: content.body,
headers: content.headers,
url: content.url
};
axios.request(request)
.then(r => res.send(r.data))
.catch(e => {
if (e.response && e.response.status) {
res.status(e.response.status).send(e.response.data);
} else if (e.request) {
res.status(400).send({
reason: 'PassThrough',
error: 'request error'
});
} else {
res.status(400).send({
reason: 'PassThrough',
error: e.code
});
}
});
}
| Return data on error from the server | Return data on error from the server
| TypeScript | apache-2.0 | projectkudu/WebJobsPortal,projectkudu/AzureFunctions,projectkudu/AzureFunctions,projectkudu/AzureFunctions,projectkudu/AzureFunctions,projectkudu/WebJobsPortal,projectkudu/WebJobsPortal,projectkudu/WebJobsPortal | ---
+++
@@ -20,7 +20,7 @@
.then(r => res.send(r.data))
.catch(e => {
if (e.response && e.response.status) {
- res.status(e.response.status).send(e.response);
+ res.status(e.response.status).send(e.response.data);
} else if (e.request) {
res.status(400).send({
reason: 'PassThrough', |
69fe3050927856d6741e2f25e01660c051e074b6 | src/Components/Artwork/Metadata.tsx | src/Components/Artwork/Metadata.tsx | import { Metadata_artwork } from "__generated__/Metadata_artwork.graphql"
import { ContextConsumer } from "Artsy"
import colors from "Assets/Colors"
import { garamond } from "Assets/Fonts"
import StyledTextLink from "Components/TextLink"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import styled from "styled-components"
import { DetailsFragmentContainer as Details } from "./Details"
export interface MetadataProps extends React.HTMLProps<MetadataContainer> {
artwork: Metadata_artwork
extended?: boolean
}
export class MetadataContainer extends React.Component<MetadataProps> {
static defaultProps = {
extended: true,
}
render() {
const { artwork, className, extended } = this.props
return (
<ContextConsumer>
{({ user }) => {
const detailsContent = (
<div className={className}>
<Details
includeLinks={false}
showSaleLine={extended}
artwork={artwork}
/>
</div>
)
return (
<StyledTextLink href={artwork.href}>
{detailsContent}
</StyledTextLink>
)
}}
</ContextConsumer>
)
}
}
export const Metadata = styled(MetadataContainer)`
${garamond("s15")};
color: ${colors.graySemibold};
margin-top: 12px;
text-align: left;
`
export default createFragmentContainer(
Metadata,
graphql`
fragment Metadata_artwork on Artwork {
...Details_artwork
...Contact_artwork
href
}
`
)
| import { Metadata_artwork } from "__generated__/Metadata_artwork.graphql"
import colors from "Assets/Colors"
import { garamond } from "Assets/Fonts"
import StyledTextLink from "Components/TextLink"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import styled from "styled-components"
import { DetailsFragmentContainer as Details } from "./Details"
export interface MetadataProps extends React.HTMLProps<MetadataContainer> {
artwork: Metadata_artwork
extended?: boolean
}
export class MetadataContainer extends React.Component<MetadataProps> {
static defaultProps = {
extended: true,
}
render() {
const { artwork, className, extended } = this.props
return (
<StyledTextLink href={artwork.href}>
<div className={className}>
<Details
includeLinks={false}
showSaleLine={extended}
artwork={artwork}
/>
</div>
</StyledTextLink>
)
}
}
export const Metadata = styled(MetadataContainer)`
${garamond("s15")};
color: ${colors.graySemibold};
margin-top: 12px;
text-align: left;
`
export default createFragmentContainer(
Metadata,
graphql`
fragment Metadata_artwork on Artwork {
...Details_artwork
...Contact_artwork
href
}
`
)
| Remove the SystemContext around an Artwork metadata because it wasn't being used | Remove the SystemContext around an Artwork metadata because it wasn't being used
| TypeScript | mit | artsy/reaction,artsy/reaction-force,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,xtina-starr/reaction | ---
+++
@@ -1,5 +1,4 @@
import { Metadata_artwork } from "__generated__/Metadata_artwork.graphql"
-import { ContextConsumer } from "Artsy"
import colors from "Assets/Colors"
import { garamond } from "Assets/Fonts"
import StyledTextLink from "Components/TextLink"
@@ -22,24 +21,15 @@
const { artwork, className, extended } = this.props
return (
- <ContextConsumer>
- {({ user }) => {
- const detailsContent = (
- <div className={className}>
- <Details
- includeLinks={false}
- showSaleLine={extended}
- artwork={artwork}
- />
- </div>
- )
- return (
- <StyledTextLink href={artwork.href}>
- {detailsContent}
- </StyledTextLink>
- )
- }}
- </ContextConsumer>
+ <StyledTextLink href={artwork.href}>
+ <div className={className}>
+ <Details
+ includeLinks={false}
+ showSaleLine={extended}
+ artwork={artwork}
+ />
+ </div>
+ </StyledTextLink>
)
}
} |
8490eadf0cf82226eaafb1c31c0eda818fb5b905 | src/UserProvidedSettings.ts | src/UserProvidedSettings.ts | export interface UserProvidedSettings {
createSourceMap?: boolean
renderUnsafeContent?: boolean
idPrefix?: string
ellipsis?: string
defaultUrlScheme?: string
baseForUrlsStartingWithSlash?: string
baseForUrlsStartingWithHashMark?: string
terms?: UserProvidedSettings.Terms
}
export namespace UserProvidedSettings {
export interface Terms {
markup?: Terms.Markup
rendered?: Terms.Rendered
}
export namespace Terms {
export interface Markup {
audio?: Terms.FoundInMarkup
chart?: Terms.FoundInMarkup
highlight?: Terms.FoundInMarkup
image?: Terms.FoundInMarkup
nsfl?: Terms.FoundInMarkup
nsfw?: Terms.FoundInMarkup
sectionLink?: Terms.FoundInMarkup
spoiler?: Terms.FoundInMarkup
table?: Terms.FoundInMarkup
video?: Terms.FoundInMarkup
}
export type FoundInMarkup = string[] | string
export interface Rendered {
footnote?: Terms.RenderedToOutput
footnoteReference?: Terms.RenderedToOutput
sectionReferencedByTableOfContents?: Terms.RenderedToOutput
tableOfContents?: Terms.RenderedToOutput
toggleNsfl?: Terms.RenderedToOutput
toggleNsfw?: Terms.RenderedToOutput
toggleSpoiler?: Terms.RenderedToOutput
}
export type RenderedToOutput = string
}
}
| export interface UserProvidedSettings {
parsing: UserProvidedSettings.Parsing
rendering: UserProvidedSettings.Rendering
}
export namespace UserProvidedSettings {
export interface Parsing {
createSourceMap?: boolean
defaultUrlScheme?: string
baseForUrlsStartingWithSlash?: string
baseForUrlsStartingWithHashMark?: string
ellipsis?: string
terms?: Parsing.Terms
}
export namespace Parsing {
export interface Terms {
audio?: Term
chart?: Term
highlight?: Term
image?: Term
nsfl?: Term
nsfw?: Term
sectionLink?: Term
spoiler?: Term
table?: Term
video?: Term
}
export type Term = string[] | string
}
export interface Rendering {
renderUnsafeContent?: boolean
terms?: Rendering.Terms
}
export namespace Rendering {
export interface Terms {
footnote?: Term
footnoteReference?: Term
sectionReferencedByTableOfContents?: Term
tableOfContents?: Term
toggleNsfl?: Term
toggleNsfw?: Term
toggleSpoiler?: Term
}
export type Term = string
}
}
| Change shape of user-provided settings | [Broken] Change shape of user-provided settings
| TypeScript | mit | start/up,start/up | ---
+++
@@ -1,47 +1,53 @@
export interface UserProvidedSettings {
- createSourceMap?: boolean
- renderUnsafeContent?: boolean
- idPrefix?: string
- ellipsis?: string
- defaultUrlScheme?: string
- baseForUrlsStartingWithSlash?: string
- baseForUrlsStartingWithHashMark?: string
- terms?: UserProvidedSettings.Terms
+ parsing: UserProvidedSettings.Parsing
+ rendering: UserProvidedSettings.Rendering
}
export namespace UserProvidedSettings {
- export interface Terms {
- markup?: Terms.Markup
- rendered?: Terms.Rendered
+ export interface Parsing {
+ createSourceMap?: boolean
+ defaultUrlScheme?: string
+ baseForUrlsStartingWithSlash?: string
+ baseForUrlsStartingWithHashMark?: string
+ ellipsis?: string
+ terms?: Parsing.Terms
}
- export namespace Terms {
- export interface Markup {
- audio?: Terms.FoundInMarkup
- chart?: Terms.FoundInMarkup
- highlight?: Terms.FoundInMarkup
- image?: Terms.FoundInMarkup
- nsfl?: Terms.FoundInMarkup
- nsfw?: Terms.FoundInMarkup
- sectionLink?: Terms.FoundInMarkup
- spoiler?: Terms.FoundInMarkup
- table?: Terms.FoundInMarkup
- video?: Terms.FoundInMarkup
+ export namespace Parsing {
+ export interface Terms {
+ audio?: Term
+ chart?: Term
+ highlight?: Term
+ image?: Term
+ nsfl?: Term
+ nsfw?: Term
+ sectionLink?: Term
+ spoiler?: Term
+ table?: Term
+ video?: Term
}
- export type FoundInMarkup = string[] | string
+ export type Term = string[] | string
+ }
- export interface Rendered {
- footnote?: Terms.RenderedToOutput
- footnoteReference?: Terms.RenderedToOutput
- sectionReferencedByTableOfContents?: Terms.RenderedToOutput
- tableOfContents?: Terms.RenderedToOutput
- toggleNsfl?: Terms.RenderedToOutput
- toggleNsfw?: Terms.RenderedToOutput
- toggleSpoiler?: Terms.RenderedToOutput
+
+ export interface Rendering {
+ renderUnsafeContent?: boolean
+ terms?: Rendering.Terms
+ }
+
+ export namespace Rendering {
+ export interface Terms {
+ footnote?: Term
+ footnoteReference?: Term
+ sectionReferencedByTableOfContents?: Term
+ tableOfContents?: Term
+ toggleNsfl?: Term
+ toggleNsfw?: Term
+ toggleSpoiler?: Term
}
- export type RenderedToOutput = string
+ export type Term = string
}
} |
36581a6dc0d8e8acfbbf0d34be7b94bf2bd7e7c1 | src/console/DatabaseResetCommand.ts | src/console/DatabaseResetCommand.ts | import { Logger } from '../core/Logger';
import * as Knex from 'knex';
import { AbstractCommand } from './lib/AbstractCommand';
import * as options from './../../knexfile';
const log = new Logger(__filename);
/**
* DatabaseResetCommand rollback all current migrations and
* then migrate to the latest one.
*
* @export
* @class DatabaseResetCommand
*/
export class DatabaseResetCommand extends AbstractCommand {
public static command = 'db:reset';
public static description = 'Reverse all current migrations and migrate to latest.';
public async run(): Promise<void> {
const knex = Knex(options);
const migrate: any = knex.migrate;
// Force unlock in case of bad state
await migrate.forceFreeMigrationsLock();
// Get completed migrations
log.info('Get completed migrations');
const completedMigrations = await migrate._listCompleted();
// Rollback migrations
log.info('Rollback migrations');
await migrate._waterfallBatch(0, completedMigrations.reverse(), 'down');
// Migrate to latest
log.info('Migrate to latest');
await migrate.latest();
// Close connection to the database
await knex.destroy();
log.info('Done');
}
}
| import { Logger } from '../core/Logger';
import * as Knex from 'knex';
import { AbstractCommand } from './lib/AbstractCommand';
import * as options from './../../knexfile';
const log = new Logger(__filename);
/**
* DatabaseResetCommand rollback all current migrations and
* then migrate to the latest one.
*
* @export
* @class DatabaseResetCommand
*/
export class DatabaseResetCommand extends AbstractCommand {
public static command = 'db:reset';
public static description = 'Reverse all current migrations and migrate to latest.';
public async run(): Promise<void> {
const knex = Knex(options as Knex.Config);
const migrate: any = knex.migrate;
// Force unlock in case of bad state
await migrate.forceFreeMigrationsLock();
// Get completed migrations
log.info('Get completed migrations');
const completedMigrations = await migrate._listCompleted();
// Rollback migrations
log.info('Rollback migrations');
await migrate._waterfallBatch(0, completedMigrations.reverse(), 'down');
// Migrate to latest
log.info('Migrate to latest');
await migrate.latest();
// Close connection to the database
await knex.destroy();
log.info('Done');
}
}
| Add type to reset database command | Add type to reset database command
| TypeScript | mit | w3tecch/express-typescript-boilerplate,w3tecch/express-typescript-boilerplate,w3tecch/express-typescript-boilerplate | ---
+++
@@ -20,7 +20,7 @@
public static description = 'Reverse all current migrations and migrate to latest.';
public async run(): Promise<void> {
- const knex = Knex(options);
+ const knex = Knex(options as Knex.Config);
const migrate: any = knex.migrate;
|
c033d0abc2ef2d03b68575339edd40802fd50875 | client/src/app/data-services/base.service.ts | client/src/app/data-services/base.service.ts | import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class BaseService {
constructor(public http: HttpClient) { }
public catchHandler = (parameter: HttpErrorResponse): HttpErrorResponse => parameter;
}
| import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class BaseService {
constructor(protected http: HttpClient) { }
protected catchHandler = (parameter: HttpErrorResponse): HttpErrorResponse => parameter;
}
| Set BaseService's functions to 'protected' | Set BaseService's functions to 'protected'
| TypeScript | mit | Ionaru/EVE-Track,Ionaru/EVE-Track,Ionaru/EVE-Track | ---
+++
@@ -4,7 +4,7 @@
@Injectable()
export class BaseService {
- constructor(public http: HttpClient) { }
+ constructor(protected http: HttpClient) { }
- public catchHandler = (parameter: HttpErrorResponse): HttpErrorResponse => parameter;
+ protected catchHandler = (parameter: HttpErrorResponse): HttpErrorResponse => parameter;
} |
ef25f68aa5e9345950a30a3f2933af0f207e8e4a | src/app/toggle-scroll.service.ts | src/app/toggle-scroll.service.ts | import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Injectable()
export class ToggleScrollService {
/**
* Setting position fixed on body will prevent scroll, and setting overflow
* to scroll ensures the scrollbar is always visible.
* IE 11 requires an empty string rather than null to unset styles.
*/
set allowScroll(val: boolean) {
this.document.body.style.position = val ? '' : 'fixed';
this.document.body.style.overflowY = val ? '' : 'scroll';
}
constructor(@Inject(DOCUMENT) private document: any) { }
}
| import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Injectable()
export class ToggleScrollService {
/**
* Setting position fixed on body will prevent scroll, and setting overflow
* to scroll ensures the scrollbar is always visible.
* IE 11 requires an empty string rather than null to unset styles.
*/
set allowScroll(val: boolean) {
const changeScroll = !val && this.document.documentElement.scrollTop === 0;
this.document.body.style.position = changeScroll ? 'fixed' : '';
this.document.body.style.overflowY = changeScroll ? 'scroll' : '';
}
constructor(@Inject(DOCUMENT) private document: any) { }
}
| Check scrollTop in toggle scroll | Check scrollTop in toggle scroll
| TypeScript | mit | EvictionLab/eviction-maps,EvictionLab/eviction-maps,EvictionLab/eviction-maps,EvictionLab/eviction-maps | ---
+++
@@ -9,8 +9,9 @@
* IE 11 requires an empty string rather than null to unset styles.
*/
set allowScroll(val: boolean) {
- this.document.body.style.position = val ? '' : 'fixed';
- this.document.body.style.overflowY = val ? '' : 'scroll';
+ const changeScroll = !val && this.document.documentElement.scrollTop === 0;
+ this.document.body.style.position = changeScroll ? 'fixed' : '';
+ this.document.body.style.overflowY = changeScroll ? 'scroll' : '';
}
constructor(@Inject(DOCUMENT) private document: any) { } |
bbd620d2a58bf66d089b53b171b39db37ccec8be | src/customer/types.ts | src/customer/types.ts | export type PhoneNumber =
| string
| {
national_number: string;
country_code: string;
};
// Customer has only two mandatory fields: name and email, rest are optional.
export interface Customer {
url?: string;
uuid?: string;
email: string;
name: string;
display_name?: string;
abbreviation?: string;
access_subnets?: string;
accounting_start_date?: string;
address?: string;
agreement_number?: string;
bank_account?: string;
bank_name?: string;
contact_details?: string;
country_name?: string;
country?: string;
default_tax_percent?: string;
native_name?: string;
phone_number?: PhoneNumber;
postal?: string;
registration_code?: string;
domain?: string;
homepage?: string;
type?: string;
vat_code?: string;
image?: string;
is_service_provider?: boolean;
created?: string;
}
| export type PhoneNumber =
| string
| {
national_number: string;
country_code: string;
};
// Customer has only two mandatory fields: name and email, rest are optional.
export interface Customer {
url?: string;
uuid?: string;
email: string;
name: string;
display_name?: string;
abbreviation?: string;
access_subnets?: string;
accounting_start_date?: string;
address?: string;
agreement_number?: string;
bank_account?: string;
bank_name?: string;
contact_details?: string;
country_name?: string;
country?: string;
default_tax_percent?: string;
native_name?: string;
phone_number?: PhoneNumber;
postal?: string;
registration_code?: string;
domain?: string;
homepage?: string;
vat_code?: string;
image?: string;
is_service_provider?: boolean;
created?: string;
}
| Remove leftover type field from customer interface. | Remove leftover type field from customer interface.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -29,7 +29,6 @@
registration_code?: string;
domain?: string;
homepage?: string;
- type?: string;
vat_code?: string;
image?: string;
is_service_provider?: boolean; |
90610b09eff6efa7bf18b84c9ec5ccc219293990 | frontend/javascript/snippets/search.ts | frontend/javascript/snippets/search.ts | function applyToForm(searchForm: HTMLFormElement) {
function submitForm() {
searchForm.submit();
}
const inputs = searchForm.querySelectorAll('select, input[type="date"]');
let i;
for (i = 0; i < inputs.length; i += 1) {
const selectInput = inputs[i];
selectInput.addEventListener("change", submitForm);
}
function dropdownSubmit(input: HTMLInputElement) {
return function(this: HTMLElement, e: Event) {
e.preventDefault();
input.value = this.dataset.value || "";
searchForm.submit();
};
}
const dropdowns = searchForm.querySelectorAll(".dropdown");
for (i = 0; i < dropdowns.length; i += 1) {
const dropdown = dropdowns[i];
const input = dropdown.querySelector("input") as HTMLInputElement;
const dropdownLinks = dropdown.querySelectorAll(".dropdown-menu a");
Array.from(dropdownLinks).forEach((dropdownLink) => {
dropdownLink.addEventListener("click", dropdownSubmit(input));
});
}
}
let form = document.querySelector(".search-form") as HTMLFormElement;
if (form !== null) {
applyToForm(form);
}
| function applyToForm(searchForm: HTMLFormElement) {
function submitForm() {
searchForm.submit();
}
const inputs = searchForm.querySelectorAll('select, input[type="date"]');
let i;
for (i = 0; i < inputs.length; i += 1) {
const selectInput = inputs[i];
selectInput.addEventListener("change", submitForm);
}
function dropdownSubmit(input: HTMLInputElement) {
return function(this: HTMLElement, e: Event) {
e.preventDefault();
input.value = this.dataset.value || "";
searchForm.submit();
};
}
const dropdowns = searchForm.querySelectorAll(".dropdown");
for (i = 0; i < dropdowns.length; i += 1) {
const dropdown = dropdowns[i];
const input = dropdown.querySelector("input") as HTMLInputElement;
const dropdownLinks = dropdown.querySelectorAll(".dropdown-menu a");
Array.from(dropdownLinks).forEach((dropdownLink) => {
dropdownLink.addEventListener("click", dropdownSubmit(input));
});
}
}
let domSearchForm = document.querySelector(".search-form") as HTMLFormElement;
if (domSearchForm !== null) {
applyToForm(domSearchForm);
}
| Fix global form typescript error | Fix global form typescript error | TypeScript | mit | fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide | ---
+++
@@ -28,7 +28,7 @@
}
}
-let form = document.querySelector(".search-form") as HTMLFormElement;
-if (form !== null) {
- applyToForm(form);
+let domSearchForm = document.querySelector(".search-form") as HTMLFormElement;
+if (domSearchForm !== null) {
+ applyToForm(domSearchForm);
} |
a824cf00a62b4a8f68667270ec0635abf987eda3 | src/utils/comments/index.ts | src/utils/comments/index.ts | import patternFromPresets from './patternFromPresets';
/**
* Resolves difference in length from a string pattern.
* The string pattern is how the string looks after being commented, where
* `%s` replaces the string
* @param {string} commentPattern pattern for the comment (i.e. `// %s`)
* @return {number} difference in length
*/
const lengthDiffFromCommentPattern: (string) => number = (
commentPattern: string
) => commentPattern.length - 2;
function commentPatternFromLanguage(languageId: string) : Promise<string> {
// TODO: handle non-existant
const tryPatternFromPresets = patternFromPresets(languageId);
if (tryPatternFromPresets) {
return Promise.resolve(tryPatternFromPresets);
}
// TODO: handle user prompt to add comment pattern
return Promise.resolve("// %s");
}
export { lengthDiffFromCommentPattern, commentPatternFromLanguage };
| import { window } from "vscode";
import patternFromPresets from "./patternFromPresets";
/**
* Resolves difference in length from a string pattern.
* The string pattern is how the string looks after being commented, where
* `%s` replaces the string
* @param {string} commentPattern pattern for the comment (i.e. `// %s`)
* @return {number} difference in length
*/
const lengthDiffFromCommentPattern: (string) => number = (
commentPattern: string
) => commentPattern.length - 2;
/**
* Resolves a comment pattern from the languageId in the active editor.
* In case the languageId is not inside the presets (defined by the extension),
* the user will input their own style of comment.
*
* > The setting will be saved in the configuration for future uses.
* @param languageId language id in the editor
* @return {Promise<string>} the comment pattern for the languageId
*/
async function commentPatternFromLanguage(languageId: string): Promise<string> {
// const tryPatternFromPresets = patternFromPresets(languageId);
// if (tryPatternFromPresets) {
// return Promise.resolve(tryPatternFromPresets);
// }
let input = "";
while (!input.includes("%s")) {
input = await window.showInputBox({
prompt:
"This language is not recognized. Enter a comment pattern for this language in the style `// %s` where %s is the comment text",
value: "// %s"
});
}
return Promise.resolve(input);
}
export { lengthDiffFromCommentPattern, commentPatternFromLanguage };
| Add user prompt for defining comment pattern | Add user prompt for defining comment pattern
| TypeScript | mit | guywald1/vscode-prismo | ---
+++
@@ -1,4 +1,5 @@
-import patternFromPresets from './patternFromPresets';
+import { window } from "vscode";
+import patternFromPresets from "./patternFromPresets";
/**
* Resolves difference in length from a string pattern.
@@ -11,15 +12,29 @@
commentPattern: string
) => commentPattern.length - 2;
-function commentPatternFromLanguage(languageId: string) : Promise<string> {
- // TODO: handle non-existant
- const tryPatternFromPresets = patternFromPresets(languageId);
- if (tryPatternFromPresets) {
- return Promise.resolve(tryPatternFromPresets);
+/**
+ * Resolves a comment pattern from the languageId in the active editor.
+ * In case the languageId is not inside the presets (defined by the extension),
+ * the user will input their own style of comment.
+ *
+ * > The setting will be saved in the configuration for future uses.
+ * @param languageId language id in the editor
+ * @return {Promise<string>} the comment pattern for the languageId
+ */
+async function commentPatternFromLanguage(languageId: string): Promise<string> {
+ // const tryPatternFromPresets = patternFromPresets(languageId);
+ // if (tryPatternFromPresets) {
+ // return Promise.resolve(tryPatternFromPresets);
+ // }
+ let input = "";
+ while (!input.includes("%s")) {
+ input = await window.showInputBox({
+ prompt:
+ "This language is not recognized. Enter a comment pattern for this language in the style `// %s` where %s is the comment text",
+ value: "// %s"
+ });
}
- // TODO: handle user prompt to add comment pattern
- return Promise.resolve("// %s");
+ return Promise.resolve(input);
}
-
-export { lengthDiffFromCommentPattern, commentPatternFromLanguage };
+export { lengthDiffFromCommentPattern, commentPatternFromLanguage }; |
be560ac73ca772b8a6184f0364c788311237ce37 | src/default-errors.ts | src/default-errors.ts | import {ErrorMessage} from "./Models/ErrorMessage";
export const DEFAULT_ERRORS: ErrorMessage[] = [
{
error: 'required',
format: label => `${label} is required`
},
{
error: 'pattern',
format: label => `${label} is invalid`
},
{
error: 'minlength',
format: (label, error) => `${label} must be at least ${error.requiredLength} characters`
},
{
error: 'maxlength',
format: (label, error) => `${label} must be no longer than ${error.requiredLength} characters`
},
{
error: 'requiredTrue',
format: (label, error) => `${label} is required`
},
{
error: 'email',
format: (label, error) => `Invalid email address`
}
];
| import {ErrorMessage} from "./Models/ErrorMessage";
export const DEFAULT_ERRORS: ErrorMessage[] = [
{
error: 'required',
format: label => `${label} is required`
},
{
error: 'pattern',
format: label => `${label} is invalid`
},
{
error: 'minlength',
format: (label, error) => `${label} must be at least ${error.requiredLength} characters`
},
{
error: 'maxlength',
format: (label, error) => `${label} must be no longer than ${error.requiredLength} characters`
},
{
error: 'requiredTrue',
format: (label, error) => `${label} is required`
},
{
error: 'email',
format: (label, error) => `Invalid email address`
},
{
error: 'max',
format: (label, error) => `${label} must be no greater than ${error.max}`
},
{
error: 'min',
format: (label, error) => `${label} must be no less than ${error.min}`
}
];
| Add default errors for min and max | Add default errors for min and max
| TypeScript | mit | third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation | ---
+++
@@ -24,5 +24,13 @@
{
error: 'email',
format: (label, error) => `Invalid email address`
+ },
+ {
+ error: 'max',
+ format: (label, error) => `${label} must be no greater than ${error.max}`
+ },
+ {
+ error: 'min',
+ format: (label, error) => `${label} must be no less than ${error.min}`
}
]; |
b4ae6d7bb2ea21e037875b42fbb04932b0120ddf | source/tasks/startTaskScheduler.ts | source/tasks/startTaskScheduler.ts | import { MONGODB_URI, PERIL_WEBHOOK_SECRET, PUBLIC_FACING_API } from "../globals"
import * as Agenda from "agenda"
import db from "../db/getDB"
import logger from "../logger"
import { runTask } from "./runTask"
export interface DangerFileTaskConfig {
installationID: number
taskName: string
data: any
}
export let agenda: Agenda
export const runDangerfileTaskName = "runDangerfile"
export const startTaskScheduler = async () => {
agenda = new Agenda({ db: { address: MONGODB_URI } })
agenda.define(runDangerfileTaskName, async (job, done) => {
const data = job.attrs.data as DangerFileTaskConfig
const installation = await db.getInstallation(data.installationID)
if (!installation) {
logger.error(`Could not find installation for task: ${data.taskName}`)
return
}
const taskString = installation.tasks[data.taskName]
if (!taskString) {
logger.error(`Could not find the task: ${data.taskName} on installation ${data.installationID}`)
return
}
runTask(installation, taskString, data.data)
})
}
| import { MONGODB_URI, PERIL_WEBHOOK_SECRET, PUBLIC_FACING_API } from "../globals"
import * as Agenda from "agenda"
import db from "../db/getDB"
import logger from "../logger"
import { runTask } from "./runTask"
export interface DangerFileTaskConfig {
installationID: number
taskName: string
data: any
}
export let agenda: Agenda
export const runDangerfileTaskName = "runDangerfile"
export const startTaskScheduler = async () => {
agenda = new Agenda({ db: { address: MONGODB_URI } })
agenda.on("ready", () => {
logger.info("Task runner ready")
agenda.start()
})
agenda.define(runDangerfileTaskName, async (job, done) => {
const data = job.attrs.data as DangerFileTaskConfig
logger.info(`Recieved a new task, ${data.taskName}`)
const installation = await db.getInstallation(data.installationID)
if (!installation) {
logger.error(`Could not find installation for task: ${data.taskName}`)
return
}
const taskString = installation.tasks[data.taskName]
if (!taskString) {
logger.error(`Could not find the task: ${data.taskName} on installation ${data.installationID}`)
return
}
runTask(installation, taskString, data.data)
})
}
| Add some notes to the scheduler, and make it start | Add some notes to the scheduler, and make it start
| TypeScript | mit | danger/peril,danger/peril,danger/peril,danger/peril,danger/peril | ---
+++
@@ -16,9 +16,14 @@
export const startTaskScheduler = async () => {
agenda = new Agenda({ db: { address: MONGODB_URI } })
+ agenda.on("ready", () => {
+ logger.info("Task runner ready")
+ agenda.start()
+ })
agenda.define(runDangerfileTaskName, async (job, done) => {
const data = job.attrs.data as DangerFileTaskConfig
+ logger.info(`Recieved a new task, ${data.taskName}`)
const installation = await db.getInstallation(data.installationID)
if (!installation) { |
c74e5fb759a7f7bd01bfd4e10af0ea44d87ec131 | services/api/src/resources/environment/sql.ts | services/api/src/resources/environment/sql.ts | const { knex } = require('../../util/db');
export const Sql = {
updateEnvironment: ({ id, patch }: { id: number, patch: { [key: string]: any } }) =>
knex('environment')
.where('id', '=', id)
.update(patch)
.toString(),
selectEnvironmentById: (id: number) =>
knex('environment')
.where('id', '=', id)
.toString(),
selectEnvironmentByNameAndProject: (name: string, projectId: number) =>
knex('environment')
.where('name', '=', name)
.andWhere('project', '=', projectId)
.toString(),
truncateEnvironment: () =>
knex('environment')
.truncate()
.toString(),
insertService: (
environment: number,
name: string,
) =>
knex('environment_service')
.insert({
environment,
name,
})
.toString(),
selectServicesByEnvironmentId: (id: number) =>
knex('environment_service')
.where('environment', '=', id)
.toString(),
deleteServices: (id: number) =>
knex('environment_service')
.where('environment', '=', id)
.delete()
.toString(),
};
| const { knex } = require('../../util/db');
export const Sql = {
updateEnvironment: ({ id, patch }: { id: number, patch: { [key: string]: any } }) => {
const updatePatch = {
...patch,
updated: knex.fn.now(),
};
return knex('environment')
.where('id', '=', id)
.update(updatePatch)
.toString();
},
selectEnvironmentById: (id: number) =>
knex('environment')
.where('id', '=', id)
.toString(),
selectEnvironmentByNameAndProject: (name: string, projectId: number) =>
knex('environment')
.where('name', '=', name)
.andWhere('project', '=', projectId)
.toString(),
truncateEnvironment: () =>
knex('environment')
.truncate()
.toString(),
insertService: (
environment: number,
name: string,
) =>
knex('environment_service')
.insert({
environment,
name,
})
.toString(),
selectServicesByEnvironmentId: (id: number) =>
knex('environment_service')
.where('environment', '=', id)
.toString(),
deleteServices: (id: number) =>
knex('environment_service')
.where('environment', '=', id)
.delete()
.toString(),
};
| Fix updateEnvironment mutation not setting "updated" date | Fix updateEnvironment mutation not setting "updated" date
| TypeScript | apache-2.0 | amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon | ---
+++
@@ -1,11 +1,17 @@
const { knex } = require('../../util/db');
export const Sql = {
- updateEnvironment: ({ id, patch }: { id: number, patch: { [key: string]: any } }) =>
- knex('environment')
- .where('id', '=', id)
- .update(patch)
- .toString(),
+ updateEnvironment: ({ id, patch }: { id: number, patch: { [key: string]: any } }) => {
+ const updatePatch = {
+ ...patch,
+ updated: knex.fn.now(),
+ };
+
+ return knex('environment')
+ .where('id', '=', id)
+ .update(updatePatch)
+ .toString();
+ },
selectEnvironmentById: (id: number) =>
knex('environment')
.where('id', '=', id) |
b4b7dc9826c0981cedd0182d8b1fcb7f0bad964a | packages/lesswrong/server/intercomSetup.ts | packages/lesswrong/server/intercomSetup.ts | import Intercom from 'intercom-client';
import { DatabaseServerSetting } from './databaseSettings';
// Initiate Intercom on the server
const intercomTokenSetting = new DatabaseServerSetting<string | null>("intercomToken", null)
let intercomClient: any = null;
export const getIntercomClient = () => {
if (!intercomClient && intercomTokenSetting.get()) {
intercomClient = new Intercom.Client({ token: intercomTokenSetting.get() })
}
return intercomClient;
}
| import { Client } from 'intercom-client';
import { DatabaseServerSetting } from './databaseSettings';
// Initiate Intercom on the server
const intercomTokenSetting = new DatabaseServerSetting<string | null>("intercomToken", null)
let intercomClient: any = null;
export const getIntercomClient = () => {
if (!intercomClient && intercomTokenSetting.get()) {
intercomClient = new Client({ token: intercomTokenSetting.get() })
}
return intercomClient;
}
| Fix crash due to importing Intercom in the wrong way | Fix crash due to importing Intercom in the wrong way
| TypeScript | mit | Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2 | ---
+++
@@ -1,4 +1,4 @@
-import Intercom from 'intercom-client';
+import { Client } from 'intercom-client';
import { DatabaseServerSetting } from './databaseSettings';
// Initiate Intercom on the server
@@ -7,7 +7,7 @@
let intercomClient: any = null;
export const getIntercomClient = () => {
if (!intercomClient && intercomTokenSetting.get()) {
- intercomClient = new Intercom.Client({ token: intercomTokenSetting.get() })
+ intercomClient = new Client({ token: intercomTokenSetting.get() })
}
return intercomClient;
} |
15f0662e77a580c66676f3c73ce2fdd77f856d3b | src/components/progress-bar/progress-bar.tsx | src/components/progress-bar/progress-bar.tsx | import { Component, Prop, h } from '@stencil/core';
/**
* @since 2.0
* @status stable
*
* @slot - A label to show inside the indicator.
*
* @part base - The component's base wrapper.
* @part indicator - The progress bar indicator.
* @part label - The progress bar label.
*/
@Component({
tag: 'sl-progress-bar',
styleUrl: 'progress-bar.scss',
shadow: true
})
export class ProgressBar {
/** The progress bar's percentage, 0 to 100. */
@Prop() percentage = 0;
render() {
return (
<div
part="base"
class="progress-bar"
role="progressbar"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow={this.percentage}
>
<div
part="base"
class="progress-bar__indicator"
style={{
width: `${this.percentage}%`
}}
>
<span part="label" class="progress-bar__label">
<slot />
</span>
</div>
</div>
);
}
}
| import { Component, Prop, h } from '@stencil/core';
/**
* @since 2.0
* @status stable
*
* @slot - A label to show inside the indicator.
*
* @part base - The component's base wrapper.
* @part indicator - The progress bar indicator.
* @part label - The progress bar label.
*/
@Component({
tag: 'sl-progress-bar',
styleUrl: 'progress-bar.scss',
shadow: true
})
export class ProgressBar {
/** The progress bar's percentage, 0 to 100. */
@Prop() percentage = 0;
render() {
return (
<div
part="base"
class="progress-bar"
role="progressbar"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow={this.percentage}
>
<div
part="indicator"
class="progress-bar__indicator"
style={{
width: `${this.percentage}%`
}}
>
<span part="label" class="progress-bar__label">
<slot />
</span>
</div>
</div>
);
}
}
| Fix bug where progress bar had the wrong part name | Fix bug where progress bar had the wrong part name
| TypeScript | mit | claviska/shoelace-css,shoelace-style/shoelace,claviska/shoelace-css,shoelace-style/shoelace,shoelace-style/shoelace | ---
+++
@@ -31,7 +31,7 @@
aria-valuenow={this.percentage}
>
<div
- part="base"
+ part="indicator"
class="progress-bar__indicator"
style={{
width: `${this.percentage}%` |
d7a8fa91bf96d8ada70053179ac2100f7101fcf2 | app/src/ui/updates/update-available.tsx | app/src/ui/updates/update-available.tsx | import * as React from 'react'
import { LinkButton } from '../lib/link-button'
import { Dispatcher } from '../../lib/dispatcher'
import { updateStore } from '../lib/update-store'
import { Octicon, OcticonSymbol } from '../octicons'
interface IUpdateAvailableProps {
readonly dispatcher: Dispatcher
}
/**
* A component which tells the user an update is available and gives them the
* option of moving into the future or being a luddite.
*/
export class UpdateAvailable extends React.Component<IUpdateAvailableProps, void> {
public render() {
return (
<div
id='update-available'
onSubmit={this.updateNow}
>
<span>
<Octicon symbol={OcticonSymbol.desktopDownload} />
An updated version of GitHub Desktop is avalble and will be installed at the next launch. See what's new or <LinkButton onClick={this.updateNow}>restart now </LinkButton>.
<a onClick={this.dismiss}>
<Octicon symbol={OcticonSymbol.x} />
</a>
</span>
</div>
)
}
private updateNow = () => {
updateStore.quitAndInstallUpdate()
}
private dismiss = () => {
this.props.dispatcher.closePopup()
}
}
| import * as React from 'react'
import { LinkButton } from '../lib/link-button'
import { Dispatcher } from '../../lib/dispatcher'
import { updateStore } from '../lib/update-store'
import { Octicon, OcticonSymbol } from '../octicons'
interface IUpdateAvailableProps {
readonly dispatcher: Dispatcher
}
/**
* A component which tells the user an update is available and gives them the
* option of moving into the future or being a luddite.
*/
export class UpdateAvailable extends React.Component<IUpdateAvailableProps, void> {
public render() {
return (
<div
id='update-available'
onSubmit={this.updateNow}
>
<Octicon symbol={OcticonSymbol.desktopDownload} />
<span>
An updated version of GitHub Desktop is avalble and will be installed at the next launch. See what's new or <LinkButton onClick={this.updateNow}>restart now </LinkButton>.
</span>
<a
className='close'
onClick={this.dismiss}>
<Octicon symbol={OcticonSymbol.x} />
</a>
</div>
)
}
private updateNow = () => {
updateStore.quitAndInstallUpdate()
}
private dismiss = () => {
this.props.dispatcher.closePopup()
}
}
| Move icons outside of text element | Move icons outside of text element
| TypeScript | mit | hjobrien/desktop,hjobrien/desktop,desktop/desktop,say25/desktop,desktop/desktop,BugTesterTest/desktops,hjobrien/desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,BugTesterTest/desktops,BugTesterTest/desktops,artivilla/desktop,say25/desktop,desktop/desktop,gengjiawen/desktop,j-f1/forked-desktop,shiftkey/desktop,gengjiawen/desktop,shiftkey/desktop,say25/desktop,gengjiawen/desktop,artivilla/desktop,kactus-io/kactus,desktop/desktop,kactus-io/kactus,hjobrien/desktop,gengjiawen/desktop,artivilla/desktop,j-f1/forked-desktop,BugTesterTest/desktops,kactus-io/kactus,shiftkey/desktop | ---
+++
@@ -19,14 +19,17 @@
id='update-available'
onSubmit={this.updateNow}
>
+ <Octicon symbol={OcticonSymbol.desktopDownload} />
+
<span>
- <Octicon symbol={OcticonSymbol.desktopDownload} />
An updated version of GitHub Desktop is avalble and will be installed at the next launch. See what's new or <LinkButton onClick={this.updateNow}>restart now </LinkButton>.
+ </span>
- <a onClick={this.dismiss}>
- <Octicon symbol={OcticonSymbol.x} />
- </a>
- </span>
+ <a
+ className='close'
+ onClick={this.dismiss}>
+ <Octicon symbol={OcticonSymbol.x} />
+ </a>
</div>
)
} |
1573be8e2f68cf480e2fa55a3fd91a51992ffdb2 | src/Assets/Icons/ChevronIcon.tsx | src/Assets/Icons/ChevronIcon.tsx | import { color } from "@artsy/palette"
import React from "react"
export enum Direction {
LEFT,
RIGHT,
}
interface IconProps {
/** default is RIGHT */
direction?: Direction
/** default is black10 */
fill?: string
}
export const ChevronIcon = ({ direction, fill }: IconProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 12 12"
width="8px"
height="8px"
transform={direction === Direction.LEFT ? "" : "scale(-1, 1)"}
>
<path
fill={fill ? fill : color("black10")}
fillRule="evenodd"
d="M9.091 10.758l-.788.771-5.832-5.708L8.303.113l.788.771-5.044 4.937 5.044 4.937"
/>
</svg>
)
| import { color } from "@artsy/palette"
import React from "react"
export enum Direction {
LEFT = "rotate(0deg)",
RIGHT = "rotate(180deg)",
UP = "rotate(90deg)",
DOWN = "rotate(270deg)",
}
interface IconProps {
/** default is RIGHT */
direction?: Direction
/** default is black10 */
fill?: string
}
export const ChevronIcon = ({ direction, fill }: IconProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 12 12"
width="8px"
height="8px"
transform={direction || Direction.RIGHT}
>
<path
fill={fill ? fill : color("black10")}
fillRule="evenodd"
d="M9.091 10.758l-.788.771-5.832-5.708L8.303.113l.788.771-5.044 4.937 5.044 4.937"
/>
</svg>
)
| Add the other two directions | Add the other two directions
Use rotate instead of scale too.
h/t @sepans
| TypeScript | mit | xtina-starr/reaction,artsy/reaction,artsy/reaction-force,artsy/reaction,artsy/reaction,artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction | ---
+++
@@ -2,8 +2,10 @@
import React from "react"
export enum Direction {
- LEFT,
- RIGHT,
+ LEFT = "rotate(0deg)",
+ RIGHT = "rotate(180deg)",
+ UP = "rotate(90deg)",
+ DOWN = "rotate(270deg)",
}
interface IconProps {
@@ -20,7 +22,7 @@
viewBox="0 0 12 12"
width="8px"
height="8px"
- transform={direction === Direction.LEFT ? "" : "scale(-1, 1)"}
+ transform={direction || Direction.RIGHT}
>
<path
fill={fill ? fill : color("black10")} |
2d8cc9d0d173a99f4435696ea805b2925b53fc32 | src/app/app.component.ts | src/app/app.component.ts | import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
}
| import { Component, HostListener, ViewChild } from '@angular/core';
import { MdSidenav } from '@angular/material';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild(MdSidenav) sidenav: MdSidenav;
@HostListener('window:resize', ['$event'])
onResize(evt: Event) {
console.log(evt);
if ((evt.target as any).innerWidth < 500) {
this.sidenav.close();
} else {
this.sidenav.open();
}
}
}
| Hide sidebar when viewport is too small | Hide sidebar when viewport is too small
| TypeScript | mit | exequiel09/angular-lecture,exequiel09/angular-lecture,exequiel09/angular-lecture | ---
+++
@@ -1,4 +1,5 @@
-import { Component } from '@angular/core';
+import { Component, HostListener, ViewChild } from '@angular/core';
+import { MdSidenav } from '@angular/material';
@Component({
selector: 'app-root',
@@ -6,5 +7,16 @@
styleUrls: ['./app.component.css']
})
export class AppComponent {
- title = 'app works!';
+ @ViewChild(MdSidenav) sidenav: MdSidenav;
+
+ @HostListener('window:resize', ['$event'])
+ onResize(evt: Event) {
+ console.log(evt);
+ if ((evt.target as any).innerWidth < 500) {
+ this.sidenav.close();
+ } else {
+ this.sidenav.open();
+ }
+ }
+
} |
d81c02dab4357c4efe4ee99fa90f7d344538b3de | peril/compareReactionSchema.ts | peril/compareReactionSchema.ts | import { buildSchema } from "graphql"
const { diff: schemaDiff } = require("@graphql-inspector/core")
import fetch from "node-fetch"
import { warn, danger } from "danger"
// If there is a breaking change between the local schema,
// and the current Reaction one, warn.
export default async () => {
const forcePackageJSON = await (await fetch(
"https://raw.githubusercontent.com/artsy/force/release/package.json"
)).json()
const reactionVersion = forcePackageJSON["dependencies"]["@artsy/reaction"]
const reactionSchemaUrl = `https://github.com/artsy/reaction/raw/v${reactionVersion}/data/schema.graphql`
const reactionSchema = await (await fetch(reactionSchemaUrl)).text()
const repo = danger.github.pr.head.repo.full_name
const sha = danger.github.pr.head.sha
const localSchema = await (await fetch(
`https://raw.githubusercontent.com/${repo}/${sha}/_schemaV2.graphql`
)).text()
const allChanges = schemaDiff(
buildSchema(reactionSchema),
buildSchema(localSchema)
)
const breakings = allChanges.filter(c => c.criticality.level === "BREAKING")
const messages = breakings.map(c => c.message)
if (messages.length) {
warn(
`The V2 schema in this PR has breaking changes with production Force. Remember to update Reaction if necessary:\n\n${messages}`
)
}
}
| import { buildSchema } from "graphql"
const { diff: schemaDiff } = require("@graphql-inspector/core")
import fetch from "node-fetch"
import { warn, danger } from "danger"
// If there is a breaking change between the local schema,
// and the current Reaction one, warn.
export default async () => {
const forcePackageJSON = await (await fetch(
"https://raw.githubusercontent.com/artsy/force/master/package.json"
)).json()
const reactionVersion = forcePackageJSON["dependencies"]["@artsy/reaction"]
const reactionSchemaUrl = `https://github.com/artsy/reaction/raw/v${reactionVersion}/data/schema.graphql`
const reactionSchema = await (await fetch(reactionSchemaUrl)).text()
const repo = danger.github.pr.head.repo.full_name
const sha = danger.github.pr.head.sha
const localSchema = await (await fetch(
`https://raw.githubusercontent.com/${repo}/${sha}/_schemaV2.graphql`
)).text()
const allChanges = schemaDiff(
buildSchema(reactionSchema),
buildSchema(localSchema)
)
const breakings = allChanges.filter(c => c.criticality.level === "BREAKING")
const messages = breakings.map(c => c.message)
if (messages.length) {
warn(
`The V2 schema in this PR has breaking changes with Force. Remember to update Reaction if necessary.
${messages.join("\n")}`
)
}
}
| Tweak output of schema warning | [Peril] Tweak output of schema warning
| TypeScript | mit | artsy/metaphysics,artsy/metaphysics,artsy/metaphysics | ---
+++
@@ -7,7 +7,7 @@
// and the current Reaction one, warn.
export default async () => {
const forcePackageJSON = await (await fetch(
- "https://raw.githubusercontent.com/artsy/force/release/package.json"
+ "https://raw.githubusercontent.com/artsy/force/master/package.json"
)).json()
const reactionVersion = forcePackageJSON["dependencies"]["@artsy/reaction"]
const reactionSchemaUrl = `https://github.com/artsy/reaction/raw/v${reactionVersion}/data/schema.graphql`
@@ -27,7 +27,9 @@
const messages = breakings.map(c => c.message)
if (messages.length) {
warn(
- `The V2 schema in this PR has breaking changes with production Force. Remember to update Reaction if necessary:\n\n${messages}`
+ `The V2 schema in this PR has breaking changes with Force. Remember to update Reaction if necessary.
+
+${messages.join("\n")}`
)
}
} |
89df763147d2a9e2de711ef807cc2a03a4a62e64 | src/index.ts | src/index.ts | import Shuffler from "./shuffler";
new Shuffler().run();
| #! /usr/bin/env node
import Shuffler from "./shuffler";
new Shuffler().run();
| Fix CLI usage to be executable | Fix CLI usage to be executable
| TypeScript | mit | nickp10/shuffler,nickp10/shuffler | ---
+++
@@ -1,3 +1,5 @@
+#! /usr/bin/env node
+
import Shuffler from "./shuffler";
new Shuffler().run(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.