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
|
---|---|---|---|---|---|---|---|---|---|---|
59631f5e2545dd4f6f94901aff4f1c25c15316aa | ui/src/app/jobs/components/definition-status.component.ts | ui/src/app/jobs/components/definition-status.component.ts | import {
AfterContentInit, Component, DoCheck, Input
} from '@angular/core';
import { JobExecution } from '../model/job-execution.model';
/**
* Component used to format the deployment status of Job Executions.
*
* @author Gunnar Hillert
*/
@Component({
selector: 'app-definition-status',
template: `
<span class="label label-{{labelClass}}">{{label}}</span>
`
})
export class DefinitionStatusComponent implements AfterContentInit, DoCheck {
/**
* The Job Execution from which the status will be retrieved.
*/
@Input()
jobExecution: JobExecution;
label: string;
labelClass: string;
ngAfterContentInit() {
this.setStyle();
}
ngDoCheck() {
this.setStyle();
}
private setStyle() {
if (this.jobExecution) {
if (!this.jobExecution.defined) {
this.labelClass = 'danger';
this.label = 'Deleted';
}
}
}
}
| import {
AfterContentInit, Component, DoCheck, Input
} from '@angular/core';
import { JobExecution } from '../model/job-execution.model';
/**
* Component used to format the deployment status of Job Executions.
*
* @author Gunnar Hillert
*/
@Component({
selector: 'app-definition-status',
template: `
<span class="label label-{{labelClass}}">{{label}}</span>
`
})
export class DefinitionStatusComponent implements AfterContentInit, DoCheck {
/**
* The Job Execution from which the status will be retrieved.
*/
@Input()
jobExecution: JobExecution;
label: string;
labelClass: string;
ngAfterContentInit() {
this.setStyle();
}
ngDoCheck() {
this.setStyle();
}
private setStyle() {
if (this.jobExecution) {
if (!this.jobExecution.defined) {
this.labelClass = 'info';
this.label = 'No Task Definition';
}
}
}
}
| Change the no task definition message on jobs | Change the no task definition message on jobs
Change class from Danger to Info
Updated message from `Deleted` to `No Task Definition`.
resolves #579
| TypeScript | apache-2.0 | cppwfs/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,ghillert/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,ghillert/spring-cloud-dataflow-ui,ghillert/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,ghillert/spring-cloud-dataflow-ui | ---
+++
@@ -38,8 +38,8 @@
if (this.jobExecution) {
if (!this.jobExecution.defined) {
- this.labelClass = 'danger';
- this.label = 'Deleted';
+ this.labelClass = 'info';
+ this.label = 'No Task Definition';
}
}
} |
a8f5804c2c92deffec21aae740554772f02c81af | src/classes/OnceImporter.ts | src/classes/OnceImporter.ts | import resolveUrl from '../functions/resolve-url';
import { IImporter } from '../interfaces/IImporter';
type ResolveUrl = typeof resolveUrl;
export interface IDependencies {
resolveUrl: ResolveUrl;
}
export class OnceImporter implements IImporter {
private resolveUrl: ResolveUrl;
private store: Set<string>;
constructor({ resolveUrl }: IDependencies) {
this.resolveUrl = resolveUrl;
this.store = new Set();
}
public import(url: string, includePaths: string[] = []) {
const resolvedUrl = this.resolveUrl(
url,
includePaths,
);
if (this.store.has(resolvedUrl)) {
return {
file: ``,
contents: ``,
};
}
this.store.add(resolvedUrl);
return { file: url };
}
}
export function onceImporterFactory(): IImporter {
return new OnceImporter({ resolveUrl });
}
| import resolveUrl from '../functions/resolve-url';
import { IImporter } from '../interfaces/IImporter';
type resolveUrl = typeof resolveUrl;
export interface IDependencies {
resolveUrl: resolveUrl;
}
export class OnceImporter implements IImporter {
private resolveUrl: resolveUrl;
private store: Set<string>;
constructor({ resolveUrl }: IDependencies) {
this.resolveUrl = resolveUrl;
this.store = new Set();
}
public import(url: string, includePaths: string[] = []) {
const resolvedUrl = this.resolveUrl(
url,
includePaths,
);
if (this.store.has(resolvedUrl)) {
return {
file: ``,
contents: ``,
};
}
this.store.add(resolvedUrl);
return { file: url };
}
}
export function onceImporterFactory(): IImporter {
return new OnceImporter({ resolveUrl });
}
| Use lowercase first letter for types | Use lowercase first letter for types
| TypeScript | mit | maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer | ---
+++
@@ -2,14 +2,14 @@
import { IImporter } from '../interfaces/IImporter';
-type ResolveUrl = typeof resolveUrl;
+type resolveUrl = typeof resolveUrl;
export interface IDependencies {
- resolveUrl: ResolveUrl;
+ resolveUrl: resolveUrl;
}
export class OnceImporter implements IImporter {
- private resolveUrl: ResolveUrl;
+ private resolveUrl: resolveUrl;
private store: Set<string>;
constructor({ resolveUrl }: IDependencies) { |
584196b793ed8b1381b012582eaf7d436e4fa746 | app/src/models/pull-request.ts | app/src/models/pull-request.ts | import { IAPIRefStatus } from '../lib/api'
import { GitHubRepository } from './github-repository'
export class PullRequestRef {
public readonly ref: string
public readonly sha: string
public readonly gitHubRepository: GitHubRepository
public constructor(
ref: string,
sha: string,
gitHubRepository: GitHubRepository
) {
this.ref = ref
this.sha = sha
this.gitHubRepository = gitHubRepository
}
}
export class PullRequest {
public readonly created: Date
public readonly status: IAPIRefStatus
public readonly title: string
public readonly number: number
public readonly head: PullRequestRef
public readonly base: PullRequestRef
public readonly author: string
public constructor(
created: Date,
status: IAPIRefStatus,
title: string,
number_: number,
head: PullRequestRef,
base: PullRequestRef,
author: string
) {
this.created = created
this.status = status
this.title = title
this.number = number_
this.head = head
this.base = base
this.author = author
}
}
| import { IAPIRefStatus } from '../lib/api'
import { GitHubRepository } from './github-repository'
export class PullRequestRef {
public readonly ref: string
public readonly sha: string
public readonly gitHubRepository: GitHubRepository
public constructor(
ref: string,
sha: string,
gitHubRepository: GitHubRepository
) {
this.ref = ref
this.sha = sha
this.gitHubRepository = gitHubRepository
}
}
export class PullRequest {
public readonly id: number
public readonly created: Date
public readonly status: IAPIRefStatus
public readonly title: string
public readonly number: number
public readonly head: PullRequestRef
public readonly base: PullRequestRef
public readonly author: string
public constructor(
id: number,
created: Date,
status: IAPIRefStatus,
title: string,
number_: number,
head: PullRequestRef,
base: PullRequestRef,
author: string
) {
this.id = id
this.created = created
this.status = status
this.title = title
this.number = number_
this.head = head
this.base = base
this.author = author
}
}
| Add id to pr model | Add id to pr model
| TypeScript | mit | artivilla/desktop,artivilla/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,desktop/desktop,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus,say25/desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,shiftkey/desktop | ---
+++
@@ -18,6 +18,7 @@
}
export class PullRequest {
+ public readonly id: number
public readonly created: Date
public readonly status: IAPIRefStatus
public readonly title: string
@@ -27,6 +28,7 @@
public readonly author: string
public constructor(
+ id: number,
created: Date,
status: IAPIRefStatus,
title: string,
@@ -35,6 +37,7 @@
base: PullRequestRef,
author: string
) {
+ this.id = id
this.created = created
this.status = status
this.title = title |
ce49d905833f9620746a93b24ac1ea0ebc10ed67 | app/src/experiment/console-visualizer.ts | app/src/experiment/console-visualizer.ts | import ConsoleRunner from "./console-runner"
import * as Rx from "rxjs"
import { h } from "snabbdom/h"
import { VNode } from "snabbdom/vnode"
export default class ConsoleVisualizer {
public dom: Rx.Observable<VNode>
constructor(dataSource: ConsoleRunner) {
this.dom = dataSource.dataObs
.repeat()
.map(message => {
if (message === "reset") {
return h("div.reset", "Restarted at " + new Date())
}
if (typeof message === "object" && "level" in message && "arguments" in message) {
return h(`div.level-${message.level}`, message.arguments)
}
return h("div", JSON.stringify(message))
})
.scan((list, next) => list.concat([next]), [])
.startWith([])
.map(list => h("div.console-messages", {
hook: {
postpatch: (old, next) => { scrollToBottom(next.elm as HTMLElement) },
},
}, list))
}
}
function scrollToBottom(elm: HTMLElement) {
elm.scrollTop = elm.scrollHeight
}
| import ConsoleRunner from "./console-runner"
import * as Rx from "rxjs"
import { h } from "snabbdom/h"
import { VNode } from "snabbdom/vnode"
export default class ConsoleVisualizer {
public dom: Rx.Observable<VNode>
constructor(dataSource: ConsoleRunner) {
this.dom = dataSource.dataObs
.repeat()
.scan((state, message) => {
let kept = state.keep < 0 ? state.list.slice(0) : state.list.slice(-state.keep)
let keep = message === "reset" ? 1 : -1
return { list: kept.concat([{ date: new Date(), message, json: JSON.stringify(message) }]), keep }
}, { keep: -1, list: [] })
.map(_ => _.list)
.startWith([])
.map(list => h("div.console-messages", {
hook: {
postpatch: (old, next) => { scrollToBottom(next.elm as HTMLElement) },
},
}, list.map(format)))
}
}
function format({ message, date, json }: { message: any, date: Date, json: string }, i: number) {
if (message === "reset") {
return h("div.reset", i === 0 ? "Restarted at " + date : "Stopped at " + date)
}
if (typeof message === "object" && "level" in message && "arguments" in message) {
return h(`div.level-${message.level}`, message.arguments)
}
return h("div", json)
}
function scrollToBottom(elm: HTMLElement) {
elm.scrollTop = elm.scrollHeight
}
| Clear the console upon restart | Clear the console upon restart
| TypeScript | mit | hermanbanken/RxFiddle,hermanbanken/RxFiddle,hermanbanken/RxFiddle,hermanbanken/RxFiddle,hermanbanken/RxFiddle | ---
+++
@@ -8,23 +8,29 @@
constructor(dataSource: ConsoleRunner) {
this.dom = dataSource.dataObs
.repeat()
- .map(message => {
- if (message === "reset") {
- return h("div.reset", "Restarted at " + new Date())
- }
- if (typeof message === "object" && "level" in message && "arguments" in message) {
- return h(`div.level-${message.level}`, message.arguments)
- }
- return h("div", JSON.stringify(message))
- })
- .scan((list, next) => list.concat([next]), [])
+ .scan((state, message) => {
+ let kept = state.keep < 0 ? state.list.slice(0) : state.list.slice(-state.keep)
+ let keep = message === "reset" ? 1 : -1
+ return { list: kept.concat([{ date: new Date(), message, json: JSON.stringify(message) }]), keep }
+ }, { keep: -1, list: [] })
+ .map(_ => _.list)
.startWith([])
.map(list => h("div.console-messages", {
hook: {
postpatch: (old, next) => { scrollToBottom(next.elm as HTMLElement) },
},
- }, list))
+ }, list.map(format)))
}
+}
+
+function format({ message, date, json }: { message: any, date: Date, json: string }, i: number) {
+ if (message === "reset") {
+ return h("div.reset", i === 0 ? "Restarted at " + date : "Stopped at " + date)
+ }
+ if (typeof message === "object" && "level" in message && "arguments" in message) {
+ return h(`div.level-${message.level}`, message.arguments)
+ }
+ return h("div", json)
}
function scrollToBottom(elm: HTMLElement) { |
c057a793838a8e140588955821adcb75a745afd8 | src/chrome/app/scripts/chrome_ui_connector.spec.ts | src/chrome/app/scripts/chrome_ui_connector.spec.ts | /// <reference path='chrome_ui_connector.ts' />
describe('chrome-ui-connector', () => {
it('test stub', () => {
});
});
| /// <reference path='chrome_ui_connector.ts' />
describe('chrome-ui-connector', () => {
it('test placeholder', () => {
// TODO: Write tests for ChromeUIConnector.
});
});
| Add todo for ChromeUIConnector tests. | Add todo for ChromeUIConnector tests.
| TypeScript | apache-2.0 | roceys/uproxy,dhkong88/uproxy,jpevarnek/uproxy,chinarustin/uproxy,jpevarnek/uproxy,itplanes/uproxy,roceys/uproxy,IveWong/uproxy,itplanes/uproxy,itplanes/uproxy,uProxy/uproxy,chinarustin/uproxy,uProxy/uproxy,roceys/uproxy,MinFu/uproxy,qida/uproxy,dhkong88/uproxy,roceys/uproxy,jpevarnek/uproxy,roceys/uproxy,MinFu/uproxy,uProxy/uproxy,qida/uproxy,jpevarnek/uproxy,MinFu/uproxy,MinFu/uproxy,jpevarnek/uproxy,dhkong88/uproxy,dhkong88/uproxy,qida/uproxy,qida/uproxy,dhkong88/uproxy,MinFu/uproxy,IveWong/uproxy,uProxy/uproxy,chinarustin/uproxy,qida/uproxy,IveWong/uproxy,uProxy/uproxy,chinarustin/uproxy,itplanes/uproxy,chinarustin/uproxy,itplanes/uproxy,IveWong/uproxy | ---
+++
@@ -1,6 +1,7 @@
/// <reference path='chrome_ui_connector.ts' />
describe('chrome-ui-connector', () => {
- it('test stub', () => {
+ it('test placeholder', () => {
+ // TODO: Write tests for ChromeUIConnector.
});
}); |
efd012491f0457d364fe50d273d360e47639cf25 | helpers/object.ts | helpers/object.ts | export default class HelperObject {
public static clone<T extends any>(obj: T): T {
if (obj === undefined || typeof (obj) !== "object") {
return obj; // any non-objects are passed by value, not reference
}
if (obj instanceof Date) {
return <any>new Date(obj.getTime());
}
const temp: any = new obj.constructor();
Object.keys(obj).forEach(key => {
temp[key] = HelperObject.clone(obj[key]);
});
return temp;
}
public static merge(from: any, to: any, reverseArrays = false): any {
for (const i in from) {
if (from[i] instanceof Array && to[i] instanceof Array) {
to[i] = reverseArrays ? from[i].concat(to[i]) : to[i].concat(from[i]);
} else {
to[i] = from[i];
}
}
return to;
}
}
| export default class HelperObject {
public static clone<T extends any>(obj: T): T {
if (obj === undefined || typeof (obj) !== "object") {
return obj; // any non-objects are passed by value, not reference
}
if (obj instanceof Date) {
return <any>new Date(obj.getTime());
}
const temp: any = new obj.constructor();
Object.keys(obj).forEach(key => {
temp[key] = HelperObject.clone(obj[key]);
});
return temp;
}
public static merge<T>(from: T, to: T, reverseArrays = false): T {
for (const i in from) {
if (from[i] instanceof Array && to[i] instanceof Array) {
to[i] = reverseArrays ? (<any>from[i]).concat(to[i]) : (<any>to[i]).concat(from[i]);
} else {
to[i] = from[i];
}
}
return to;
}
}
| Rewrite HelperObject.merge() header as a generic | Rewrite HelperObject.merge() header as a generic
| TypeScript | mit | crossroads-education/eta,crossroads-education/eta | ---
+++
@@ -13,10 +13,10 @@
return temp;
}
- public static merge(from: any, to: any, reverseArrays = false): any {
+ public static merge<T>(from: T, to: T, reverseArrays = false): T {
for (const i in from) {
if (from[i] instanceof Array && to[i] instanceof Array) {
- to[i] = reverseArrays ? from[i].concat(to[i]) : to[i].concat(from[i]);
+ to[i] = reverseArrays ? (<any>from[i]).concat(to[i]) : (<any>to[i]).concat(from[i]);
} else {
to[i] = from[i];
} |
39240848d0bd3112aa248ba14ecbc9405922dede | src/app/progress/ActivityModifier.tsx | src/app/progress/ActivityModifier.tsx | import { useD2Definitions } from 'app/manifest/selectors';
import React from 'react';
import BungieImage from '../dim-ui/BungieImage';
import PressTip from '../dim-ui/PressTip';
import './ActivityModifier.scss';
export function ActivityModifier({ modifierHash }: { modifierHash: number }) {
const defs = useD2Definitions()!;
const modifier = defs.ActivityModifier.get(modifierHash);
const modifierName = modifier.displayProperties.name;
const modifierIcon = modifier.displayProperties.icon;
if (!modifier || (!modifierName && !modifierIcon)) {
return null;
}
return (
<div className="milestone-modifier">
{Boolean(modifierIcon) && <BungieImage src={modifierIcon} />}
{Boolean(modifierName) && (
<div className="milestone-modifier-info">
<PressTip tooltip={modifier.displayProperties.description}>
<div className="milestone-modifier-name">{modifierName}</div>
</PressTip>
</div>
)}
</div>
);
}
| import RichDestinyText from 'app/dim-ui/RichDestinyText';
import { useD2Definitions } from 'app/manifest/selectors';
import BungieImage from '../dim-ui/BungieImage';
import PressTip from '../dim-ui/PressTip';
import './ActivityModifier.scss';
export function ActivityModifier({ modifierHash }: { modifierHash: number }) {
const defs = useD2Definitions()!;
const modifier = defs.ActivityModifier.get(modifierHash);
const modifierName = modifier.displayProperties.name;
const modifierIcon = modifier.displayProperties.icon;
if (!modifier || (!modifierName && !modifierIcon)) {
return null;
}
return (
<div className="milestone-modifier">
{Boolean(modifierIcon) && <BungieImage src={modifierIcon} />}
{Boolean(modifierName) && (
<div className="milestone-modifier-info">
<PressTip tooltip={<RichDestinyText text={modifier.displayProperties.description} />}>
<div className="milestone-modifier-name">{modifierName}</div>
</PressTip>
</div>
)}
</div>
);
}
| Use RichDestinyText for activity modifier tooltips. | Use RichDestinyText for activity modifier tooltips.
| TypeScript | mit | DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM | ---
+++
@@ -1,5 +1,5 @@
+import RichDestinyText from 'app/dim-ui/RichDestinyText';
import { useD2Definitions } from 'app/manifest/selectors';
-import React from 'react';
import BungieImage from '../dim-ui/BungieImage';
import PressTip from '../dim-ui/PressTip';
import './ActivityModifier.scss';
@@ -20,7 +20,7 @@
{Boolean(modifierIcon) && <BungieImage src={modifierIcon} />}
{Boolean(modifierName) && (
<div className="milestone-modifier-info">
- <PressTip tooltip={modifier.displayProperties.description}>
+ <PressTip tooltip={<RichDestinyText text={modifier.displayProperties.description} />}>
<div className="milestone-modifier-name">{modifierName}</div>
</PressTip>
</div> |
dbdc7a9edce47411899557498af954607bfc6b6b | applications/web/pages/_app.tsx | applications/web/pages/_app.tsx | import withRedux from "next-redux-wrapper";
import App from "next/app";
import React from "react";
import { Provider } from "react-redux";
import { Store } from "redux";
import configureStore from "../redux/store";
/**
* Next.JS requires all global CSS to be imported here.
*/
import "@nteract/styles/app.css";
import "@nteract/styles/global-variables.css";
import "@nteract/styles/themes/base.css";
import "@nteract/styles/themes/default.css";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/lib/codemirror.css";
import "@nteract/styles/editor-overrides.css";
import "@nteract/styles/markdown/github.css";
interface StoreProps {
store: Store;
}
class WebApp extends App<StoreProps> {
static async getInitialProps({ Component, ctx }) {
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
return { pageProps };
}
render() {
const { Component, pageProps, store } = this.props;
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
}
export default withRedux(configureStore as any)(WebApp);
| import { createWrapper } from "next-redux-wrapper";
import App from "next/app";
import React from "react";
import { Provider } from "react-redux";
import { Store } from "redux";
import configureStore from "../redux/store";
/**
* Next.JS requires all global CSS to be imported here.
*/
import "@nteract/styles/app.css";
import "@nteract/styles/global-variables.css";
import "@nteract/styles/themes/base.css";
import "@nteract/styles/themes/default.css";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/lib/codemirror.css";
import "@nteract/styles/editor-overrides.css";
import "@nteract/styles/markdown/github.css";
interface StoreProps {
store: Store;
}
class WebApp extends App<StoreProps> {
static async getInitialProps({ Component, ctx }) {
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
return { pageProps };
}
render() {
const { Component, pageProps, store } = this.props;
return (<Component {...pageProps} />);
}
}
const wrapper = createWrapper(configureStore, { debug: true });
export default wrapper.withRedux(WebApp);
| Fix instantiation of Redux wrapper | Fix instantiation of Redux wrapper
| TypeScript | bsd-3-clause | nteract/nteract,nteract/composition,nteract/nteract,nteract/composition,nteract/nteract,nteract/composition,nteract/nteract,nteract/nteract | ---
+++
@@ -1,4 +1,4 @@
-import withRedux from "next-redux-wrapper";
+import { createWrapper } from "next-redux-wrapper";
import App from "next/app";
import React from "react";
import { Provider } from "react-redux";
@@ -37,12 +37,10 @@
render() {
const { Component, pageProps, store } = this.props;
- return (
- <Provider store={store}>
- <Component {...pageProps} />
- </Provider>
- );
+ return (<Component {...pageProps} />);
}
}
-export default withRedux(configureStore as any)(WebApp);
+const wrapper = createWrapper(configureStore, { debug: true });
+
+export default wrapper.withRedux(WebApp); |
2947cd596480ab8063ce6d77bd85a467caa352cb | src/renderer/contentSecurityPolicy.ts | src/renderer/contentSecurityPolicy.ts | import { session, OnResponseStartedDetails } from "electron"
export const setContentSecurityPolicy: () => void = () => {
session.defaultSession.webRequest.onHeadersReceived(
(details: OnResponseStartedDetails, callback: Function) => {
callback({ responseHeaders: `default-src 'none'` })
},
)
}
| import { session, OnResponseStartedDetails } from "electron"
export const setContentSecurityPolicy = (): void => {
session.defaultSession.webRequest.onHeadersReceived(
(details: OnResponseStartedDetails, callback: Function): void => {
callback({ responseHeaders: `default-src 'none'` })
},
)
}
| Fix linting errors in ContentSecurityPolicy | Fix linting errors in ContentSecurityPolicy
| TypeScript | agpl-3.0 | briandk/transcriptase,briandk/transcriptase | ---
+++
@@ -1,8 +1,8 @@
import { session, OnResponseStartedDetails } from "electron"
-export const setContentSecurityPolicy: () => void = () => {
+export const setContentSecurityPolicy = (): void => {
session.defaultSession.webRequest.onHeadersReceived(
- (details: OnResponseStartedDetails, callback: Function) => {
+ (details: OnResponseStartedDetails, callback: Function): void => {
callback({ responseHeaders: `default-src 'none'` })
},
) |
506fae85dacba7e2a7b187f51961edb02baa483b | src/app/services/app.service.ts | src/app/services/app.service.ts | import { Injectable } from '@angular/core';
export type InternalStateType = {
[key: string]: any
};
@Injectable()
export class AppState {
_state: InternalStateType = {};
constructor() {
}
// already return a clone of the current state
get state() {
return this._state = this._clone(this._state);
}
// never allow mutation
set state(value) {
throw new Error('do not mutate the `.state` directly');
}
get(prop?: string) {
// use our state getter for the clone
const state = this.state;
return state[prop];
}
set(prop: string, value: any) {
// internally mutate our state
return this._state[prop] = value;
}
private _clone(object: InternalStateType) {
// simple object clone
return JSON.parse(JSON.stringify(object));
}
}
| import { Injectable } from '@angular/core';
export type InternalStateType = {
[key: string]: any
};
@Injectable()
export class AppState {
_state: InternalStateType = {};
constructor() {
}
// already return a clone of the current state
get state() {
return this._state = this._clone(this._state);
}
// never allow mutation
set state(value) {
throw new Error('do not mutate the `.state` directly');
}
get(prop?: string) {
// use our state getter for the clone
const state = this.state;
return state[prop];
}
set(prop: string, value: any) {
// internally mutate our state
// return this._state[prop] = value;
this._state[prop] = value;
console.log(this._state);
return this._state[prop];
}
private _clone(object: InternalStateType) {
// simple object clone
return JSON.parse(JSON.stringify(object));
}
}
| Add just a log for every state change temporally | Add just a log for every state change temporally
| TypeScript | mit | johndi9/ng2-web,johndi9/ng2-web,johndi9/ng2-web | ---
+++
@@ -29,7 +29,10 @@
set(prop: string, value: any) {
// internally mutate our state
- return this._state[prop] = value;
+ // return this._state[prop] = value;
+ this._state[prop] = value;
+ console.log(this._state);
+ return this._state[prop];
}
private _clone(object: InternalStateType) { |
a409aa972e4f7c50b2928856360069fbd4146770 | src/middlewear/resultsReporter.ts | src/middlewear/resultsReporter.ts | import Setup from "../types/Setup";
import { EventEmitter } from "events";
import Results from "../types/Results";
import groupBy from "../utils/groupBy";
import Result from "../types/Result";
export default function printResults(setup: Setup, events?: EventEmitter) {
events.on("results", (results: Results) => {
console.log("Results:\n");
Object.entries(groupBy<Result[]>(results, "testFilePath")).forEach(
entry => {
const [testFilePath, results] = entry;
const testFileTime =
results[results.length - 1].end.getTime() -
results[0].start.getTime();
console.log(`[${testFilePath} (${testFileTime} ms)]:`);
console.log();
results.forEach(({ state, description, error, time }) => {
console.log(`- ${state}: ${description} (${time} ms)`);
if (state === "failed") {
console.log();
console.log(`${error.message}`);
}
if (state === "errored") {
console.log();
console.log(`Error: ${error.message}\n`);
console.log(`Stack: ${error.stack}`);
}
console.log();
});
console.log("\n");
}
);
});
}
| import Setup from "../types/Setup";
import { EventEmitter } from "events";
import Results from "../types/Results";
import groupBy from "../utils/groupBy";
import Result from "../types/Result";
export default function printResults(setup: Setup, events?: EventEmitter) {
events.on("results", (results: Results) => {
console.log("Results:\n");
Object.entries(groupBy<Result[]>(results, "testFilePath")).forEach(
entry => {
const [testFilePath, results] = entry;
const testFileTime = results.reduce(
(time, result) => time + result.time,
0
);
console.log(`[${testFilePath} (${testFileTime} ms)]:`);
console.log();
results.forEach(({ state, description, error, time }) => {
console.log(`- ${state}: ${description} (${time} ms)`);
if (state === "failed") {
console.log();
console.log(`${error.message}`);
}
if (state === "errored") {
console.log();
console.log(`Error: ${error.message}\n`);
console.log(`Stack: ${error.stack}`);
}
console.log();
});
console.log("\n");
}
);
});
}
| Refactor time file time calculation | Refactor time file time calculation
| TypeScript | mit | testingrequired/tf,testingrequired/tf | ---
+++
@@ -12,9 +12,10 @@
entry => {
const [testFilePath, results] = entry;
- const testFileTime =
- results[results.length - 1].end.getTime() -
- results[0].start.getTime();
+ const testFileTime = results.reduce(
+ (time, result) => time + result.time,
+ 0
+ );
console.log(`[${testFilePath} (${testFileTime} ms)]:`);
console.log(); |
031f8643a2733823c352b8087dab29aed6c35818 | test/unittests/front_end/core/common/Throttler_test.ts | test/unittests/front_end/core/common/Throttler_test.ts | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const {assert} = chai;
import * as Common from '../../../../../front_end/core/common/common.js';
const Throttler = Common.Throttler.Throttler;
describe('Throttler class', () => {
it('is able to schedule a process as soon as possible', () => {
let result = 'original value';
async function assignVar1() {
result = 'new value';
}
const throttler = new Throttler(10);
const promiseTest = throttler.schedule(assignVar1, true);
void promiseTest.then(() => {
assert.strictEqual(result, 'new value', 'process was not scheduled correctly');
});
assert.strictEqual(result, 'original value', 'process was not scheduled correctly');
});
it('is able to schedule two processes as soon as possible', () => {
let result = 'original value';
async function assignVar1() {
result = 'new value 1';
}
async function assignVar2() {
result = 'new value 2';
}
const throttler = new Throttler(10);
const promiseTest = throttler.schedule(assignVar1, true);
void throttler.schedule(assignVar2, true);
void promiseTest.then(() => {
assert.strictEqual(result, 'new value 2', 'process was not scheduled correctly');
});
assert.strictEqual(result, 'original value', 'process was not scheduled correctly');
});
});
| // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const {assert} = chai;
import * as Common from '../../../../../front_end/core/common/common.js';
const Throttler = Common.Throttler.Throttler;
describe('Throttler class', () => {
it('is able to schedule a process as soon as possible', async () => {
let result = 'original value';
async function assignVar1() {
result = 'new value';
}
const throttler = new Throttler(10);
const promiseTest = throttler.schedule(assignVar1, true);
assert.strictEqual(result, 'original value', 'process was not scheduled correctly');
await promiseTest;
assert.strictEqual(result, 'new value', 'process was not scheduled correctly');
});
it('is able to schedule two processes as soon as possible', async () => {
let result = 'original value';
async function assignVar1() {
result = 'new value 1';
}
async function assignVar2() {
result = 'new value 2';
}
const throttler = new Throttler(10);
const promiseTest = throttler.schedule(assignVar1, true);
void throttler.schedule(assignVar2, true);
assert.strictEqual(result, 'original value', 'process was not scheduled correctly');
await promiseTest;
assert.strictEqual(result, 'new value 2', 'process was not scheduled correctly');
});
});
| Make throttler tests to properly wait for the promise before assertions. | Make throttler tests to properly wait for the promise before assertions.
Bug: 1376495
Change-Id: Ic914b03a4eaf3a3af1e64b18346fd5da77582ff1
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3966439
Auto-Submit: Danil Somsikov <[email protected]>
Reviewed-by: Kateryna Prokopenko <[email protected]>
Commit-Queue: Danil Somsikov <[email protected]>
| TypeScript | bsd-3-clause | ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend | ---
+++
@@ -9,7 +9,7 @@
const Throttler = Common.Throttler.Throttler;
describe('Throttler class', () => {
- it('is able to schedule a process as soon as possible', () => {
+ it('is able to schedule a process as soon as possible', async () => {
let result = 'original value';
async function assignVar1() {
@@ -18,14 +18,13 @@
const throttler = new Throttler(10);
const promiseTest = throttler.schedule(assignVar1, true);
- void promiseTest.then(() => {
- assert.strictEqual(result, 'new value', 'process was not scheduled correctly');
- });
assert.strictEqual(result, 'original value', 'process was not scheduled correctly');
+ await promiseTest;
+ assert.strictEqual(result, 'new value', 'process was not scheduled correctly');
});
- it('is able to schedule two processes as soon as possible', () => {
+ it('is able to schedule two processes as soon as possible', async () => {
let result = 'original value';
async function assignVar1() {
@@ -39,10 +38,9 @@
const throttler = new Throttler(10);
const promiseTest = throttler.schedule(assignVar1, true);
void throttler.schedule(assignVar2, true);
- void promiseTest.then(() => {
- assert.strictEqual(result, 'new value 2', 'process was not scheduled correctly');
- });
assert.strictEqual(result, 'original value', 'process was not scheduled correctly');
+ await promiseTest;
+ assert.strictEqual(result, 'new value 2', 'process was not scheduled correctly');
});
}); |
d2f63f459dbae8b0d4ea5d14bc4dd36bdda5bda0 | src/Inventory.ts | src/Inventory.ts | import { observable } from 'mobx';
import Story from "./Story";
import Item from "./Item";
import * as _ from "lodash";
export default class Inventory {
@observable items: Item[];
constructor(private story: Story, public readonly length: number) {
this.items = _.times<Item>(this.length, i => null);
}
addItem(itemTag: string): boolean {
let item = this.story.getItem(itemTag);
return this.add(item);
}
add(item: Item): boolean {
// We find the first index that contains `null`
let i = this.items.reduceRight((p, c, i) => c == null ? i : p, -1);
if (i == -1) {
return false;
}
this.items[i] = item;
return true;
}
remove(i: number): boolean {
if (i >= this.length) {
return false;
}
this.items[i] = null;
return true;
}
removeItem(item: Item): boolean {
let i = this.items.indexOf(item);
if (i == -1) {
return false;
}
return this.remove(i);
}
} | import { observable } from 'mobx';
import Story from "./Story";
import Item from "./Item";
import * as _ from "lodash";
export default class Inventory {
@observable items: Item[];
constructor(private story: Story, public readonly length: number) {
this.items = observable.shallowArray(_.times<Item>(this.length, i => null));
}
addItem(itemTag: string): boolean {
let item = this.story.getItem(itemTag);
return this.add(item);
}
add(item: Item): boolean {
// We find the first index that contains `null`
let i = this.items.reduceRight((p, c, i) => c == null ? i : p, -1);
if (i == -1) {
return false;
}
this.items[i] = item;
return true;
}
hasItem(itemTag: string): boolean {
let item = this.story.getItem(itemTag);
return this.has(item);
}
has(item: Item): boolean {
let i = this.items.indexOf(item);
return i > -1;
}
remove(i: number): boolean {
if (i >= this.length) {
return false;
}
this.items[i] = null;
return true;
}
removeItem(item: Item): boolean {
let i = this.items.indexOf(item);
if (i == -1) {
return false;
}
return this.remove(i);
}
} | Fix a bug with Mobx's object conservation | Fix a bug with Mobx's object conservation
| TypeScript | mit | Longwelwind/adventures,Longwelwind/adventures,Longwelwind/adventures | ---
+++
@@ -7,7 +7,7 @@
@observable items: Item[];
constructor(private story: Story, public readonly length: number) {
- this.items = _.times<Item>(this.length, i => null);
+ this.items = observable.shallowArray(_.times<Item>(this.length, i => null));
}
addItem(itemTag: string): boolean {
@@ -26,6 +26,17 @@
this.items[i] = item;
return true;
+ }
+
+ hasItem(itemTag: string): boolean {
+ let item = this.story.getItem(itemTag);
+
+ return this.has(item);
+ }
+
+ has(item: Item): boolean {
+ let i = this.items.indexOf(item);
+ return i > -1;
}
remove(i: number): boolean { |
c715d6f469a0dd711cdd8cb133ef49e1d974debc | src/logging.ts | src/logging.ts | "use strict";
import gLong = require('./gLong');
// default module: logging
function debug_var(e: any): string {
if (e === null) {
return '!';
}
if (e === void 0) {
return 'undef';
}
if (e.ref != null) {
return "*" + e.ref;
}
if (e instanceof gLong) {
return "" + e + "L";
}
return e;
}
// used for debugging the stack and local variables
export function debug_vars(arr: Array): string[] {
return arr.map(debug_var);
}
// log levels
// TODO: turn this into an enum, if possible
export var VTRACE = 10;
export var TRACE = 9;
export var DEBUG = 5;
export var ERROR = 1;
export var log_level = ERROR;
function log(level: number, msgs: any[]): void {
if (level <= log_level) {
var msg = msgs.join(' ');
if (level == 1) {
console.error(msg);
} else {
console.log(msg);
}
}
};
export function vtrace(...msgs: any[]): void {
log(VTRACE, msgs);
}
export function trace(...msgs: any[]): void {
log(TRACE, msgs);
}
export function debug(...msgs: any[]): void {
log(DEBUG, msgs);
}
export function error(...msgs: any[]): void {
log(ERROR, msgs);
}
| "use strict";
import gLong = require('./gLong');
// default module: logging
function debug_var(e: any): string {
if (e === null) {
return '!';
} else if (e === void 0) {
return 'undef';
} else if (e.ref != null) {
return "*" + e.ref;
} else if (e instanceof gLong) {
return e + "L";
}
return e;
}
// used for debugging the stack and local variables
export function debug_vars(arr: Array): string[] {
return arr.map(debug_var);
}
// log levels
// TODO: turn this into an enum, if possible
export var VTRACE = 10;
export var TRACE = 9;
export var DEBUG = 5;
export var ERROR = 1;
export var log_level = ERROR;
function log(level: number, msgs: any[]): void {
if (level <= log_level) {
var msg = msgs.join(' ');
if (level == 1) {
console.error(msg);
} else {
console.log(msg);
}
}
}
export function vtrace(...msgs: any[]): void {
log(VTRACE, msgs);
}
export function trace(...msgs: any[]): void {
log(TRACE, msgs);
}
export function debug(...msgs: any[]): void {
log(DEBUG, msgs);
}
export function error(...msgs: any[]): void {
log(ERROR, msgs);
}
| Make code somewhat more idiomatic. | Make code somewhat more idiomatic.
| TypeScript | mit | jmptrader/doppio,bpowers/doppio,netopyr/doppio,netopyr/doppio,jmptrader/doppio,plasma-umass/doppio,bpowers/doppio,plasma-umass/doppio,bpowers/doppio,Wanderfalke/doppio,plasma-umass/doppio,Wanderfalke/doppio,netopyr/doppio,jmptrader/doppio,Wanderfalke/doppio | ---
+++
@@ -6,15 +6,12 @@
function debug_var(e: any): string {
if (e === null) {
return '!';
- }
- if (e === void 0) {
+ } else if (e === void 0) {
return 'undef';
- }
- if (e.ref != null) {
+ } else if (e.ref != null) {
return "*" + e.ref;
- }
- if (e instanceof gLong) {
- return "" + e + "L";
+ } else if (e instanceof gLong) {
+ return e + "L";
}
return e;
}
@@ -41,7 +38,7 @@
console.log(msg);
}
}
-};
+}
export function vtrace(...msgs: any[]): void {
log(VTRACE, msgs); |
8cbfd8d80da1f58be85c82df802c59e749085c17 | src/main/ts/ephox/sugar/selection/alien/Geometry.ts | src/main/ts/ephox/sugar/selection/alien/Geometry.ts | import { ClientRect, DOMRect } from "@ephox/dom-globals";
var searchForPoint = function (rectForOffset: (number) => (ClientRect | DOMRect), x: number, y: number, maxX: number, length: number) {
// easy cases
if (length === 0) return 0;
else if (x === maxX) return length - 1;
var xDelta = maxX;
// start at 1, zero is the fallback
for (var i = 1; i < length; i++) {
var rect = rectForOffset(i);
var curDeltaX = Math.abs(x - rect.left);
if (y > rect.bottom) {
// range is too high, above drop point, do nothing
} else if (y < rect.top || curDeltaX > xDelta) {
// if the search winds up on the line below the drop point,
// or we pass the best X offset,
// wind back to the previous (best) delta
return i - 1;
} else {
// update current search delta
xDelta = curDeltaX;
}
}
return 0; // always return something, even if it's not the exact offset it'll be better than nothing
};
var inRect = function (rect: ClientRect | DOMRect, x: number, y: number) {
return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
};
export default {
inRect,
searchForPoint,
}; | import { ClientRect, DOMRect } from "@ephox/dom-globals";
var searchForPoint = function (rectForOffset: (number) => (ClientRect | DOMRect), x: number, y: number, maxX: number, length: number) {
// easy cases
if (length === 0) return 0;
else if (x === maxX) return length - 1;
var xDelta = maxX;
// start at 1, zero is the fallback
for (var i = 1; i < length; i++) {
var rect = rectForOffset(i);
var curDeltaX = Math.abs(x - rect.left);
// If Y is below drop point, do nothing
if (y <= rect.bottom) {
if (y < rect.top || curDeltaX > xDelta) {
// if the search winds up on the line below the drop point,
// or we pass the best X offset,
// wind back to the previous (best) delta
return i - 1;
} else {
// update current search delta
xDelta = curDeltaX;
}
}
}
return 0; // always return something, even if it's not the exact offset it'll be better than nothing
};
var inRect = function (rect: ClientRect | DOMRect, x: number, y: number) {
return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
};
export default {
inRect,
searchForPoint,
}; | Update logic to not include an empty if block | Update logic to not include an empty if block
| TypeScript | lgpl-2.1 | TeamupCom/tinymce,FernCreek/tinymce,tinymce/tinymce,FernCreek/tinymce,tinymce/tinymce,tinymce/tinymce,TeamupCom/tinymce,FernCreek/tinymce | ---
+++
@@ -12,16 +12,17 @@
var rect = rectForOffset(i);
var curDeltaX = Math.abs(x - rect.left);
- if (y > rect.bottom) {
- // range is too high, above drop point, do nothing
- } else if (y < rect.top || curDeltaX > xDelta) {
- // if the search winds up on the line below the drop point,
- // or we pass the best X offset,
- // wind back to the previous (best) delta
- return i - 1;
- } else {
- // update current search delta
- xDelta = curDeltaX;
+ // If Y is below drop point, do nothing
+ if (y <= rect.bottom) {
+ if (y < rect.top || curDeltaX > xDelta) {
+ // if the search winds up on the line below the drop point,
+ // or we pass the best X offset,
+ // wind back to the previous (best) delta
+ return i - 1;
+ } else {
+ // update current search delta
+ xDelta = curDeltaX;
+ }
}
}
return 0; // always return something, even if it's not the exact offset it'll be better than nothing |
5b96c5c248d6dd2b7b4168c0f8e9990ba316f9f1 | src/server/migrations/1580263521268-CreateUserTable.ts | src/server/migrations/1580263521268-CreateUserTable.ts | import {MigrationInterface, QueryRunner} from "typeorm";
export class CreateUserTable1580263521268 implements MigrationInterface {
readonly name = 'CreateUserTable1580263521268'
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`CREATE TABLE "user" ("id" SERIAL NOT NULL, "email" character varying NOT NULL, CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE ("email"), CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id"))`, undefined);
}
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`DROP TABLE "user"`, undefined);
}
}
| import {MigrationInterface, QueryRunner} from "typeorm";
export class CreateUserTable1580263521268 implements MigrationInterface {
readonly name = 'CreateUserTable1580263521268'
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`CREATE TABLE "user" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "email" character varying NOT NULL, CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE ("email"), CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id"))`, undefined);
}
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`DROP TABLE "user"`, undefined);
}
}
| Switch migration to use uuid for id column | Switch migration to use uuid for id column
| TypeScript | apache-2.0 | PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder | ---
+++
@@ -4,7 +4,7 @@
readonly name = 'CreateUserTable1580263521268'
public async up(queryRunner: QueryRunner): Promise<any> {
- await queryRunner.query(`CREATE TABLE "user" ("id" SERIAL NOT NULL, "email" character varying NOT NULL, CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE ("email"), CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id"))`, undefined);
+ await queryRunner.query(`CREATE TABLE "user" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "email" character varying NOT NULL, CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE ("email"), CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id"))`, undefined);
}
public async down(queryRunner: QueryRunner): Promise<any> { |
eb9d053f308b6dec0a7a8e45b912a8669b79f28e | src/app/client/game/components/join.component.ts | src/app/client/game/components/join.component.ts | import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
template: `
<h1 class="cover-heading">Join Game</h1>
<p class="lead">To join a game, ask the host for the game key.</p>
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="gameKey">Email address</label>
<input class="form-control upper" [(ngModel)]="gameKey" type="text" name="gameKey" />
</div>
<a class="btn btn-success" (click)="join()" [disabled]="gameKey">Join Game</a>
</form>
`
})
export class JoinPageComponent {
public gameKey: string;
constructor(private router: Router){}
public join(){
const key = this.gameKey.toUpperCase();
this.router.navigate(['/player', key]);
}
} | import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
template: `
<h1 class="cover-heading">Join Game</h1>
<p class="lead">To join a game, ask the host for the game key.</p>
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="gameKey">Email address</label>
<input class="form-control upper" [(ngModel)]="gameKey" type="text" name="gameKey" />
</div>
<button type="button" class="btn btn-success" (click)="join()" [disabled]="gameKey">Join Game</button>
</form>
`
})
export class JoinPageComponent {
public gameKey: string;
constructor(private router: Router){}
public join(){
const key = this.gameKey.toUpperCase();
this.router.navigate(['/player', key]);
}
} | Use a button so it can support | Use a button so it can support [disabled]
| TypeScript | mit | carbonrobot/parakeet,carbonrobot/parakeet,carbonrobot/parakeet | ---
+++
@@ -11,7 +11,7 @@
<label class="sr-only" for="gameKey">Email address</label>
<input class="form-control upper" [(ngModel)]="gameKey" type="text" name="gameKey" />
</div>
- <a class="btn btn-success" (click)="join()" [disabled]="gameKey">Join Game</a>
+ <button type="button" class="btn btn-success" (click)="join()" [disabled]="gameKey">Join Game</button>
</form>
`
}) |
ea3361812433ddbbb2b35fa15e46f2c3b19c0e46 | examples/simple-jsbeautifyrc/tsx/expected/test.tsx | examples/simple-jsbeautifyrc/tsx/expected/test.tsx | class Test extends React.Component<Foo> {
render() {
return (
<div className= "class" >
<h2 className="anotherClass" >
{ this.foo.bar }
< /h2>
{ this.foo.bar.children }
</div>
);
}
}
| class Test extends React.Component<Foo> {
render() {
return (
<div className="class">
<h2 className="anotherClass">
{this.foo.bar}
</h2>
{this.foo.bar.children}
</div>
);
}
} | Fix expected output for TSX | Fix expected output for TSX
| TypeScript | mit | Glavin001/atom-beautify,Glavin001/atom-beautify,Glavin001/atom-beautify,Glavin001/atom-beautify,Glavin001/atom-beautify | ---
+++
@@ -1,12 +1,12 @@
class Test extends React.Component<Foo> {
render() {
return (
- <div className= "class" >
- <h2 className="anotherClass" >
- { this.foo.bar }
- < /h2>
- { this.foo.bar.children }
- </div>
+ <div className="class">
+ <h2 className="anotherClass">
+ {this.foo.bar}
+ </h2>
+ {this.foo.bar.children}
+ </div>
);
}
} |
9cf758f455b0cafd6f0b1a129fe36b3ff5ff6056 | src/browser/app/app-configs.ts | src/browser/app/app-configs.ts | import { Provider } from '@angular/core';
import { NoteCollectionActionTypes } from '../note/note-collection';
import { NoteEditorActionTypes } from '../note/note-editor';
import { VCS_DETECT_CHANGES_EFFECT_ACTIONS } from '../vcs';
import { BaseVcsItemFactory, VCS_ITEM_MAKING_FACTORIES, VcsItemFactory } from '../vcs/vcs-view';
export const AppVcsItemFactoriesProvider: Provider = {
provide: VCS_ITEM_MAKING_FACTORIES,
useFactory(baseVcsItemFactory: BaseVcsItemFactory): VcsItemFactory<any>[] {
return [baseVcsItemFactory];
},
deps: [BaseVcsItemFactory],
};
export const AppVcsDetectChangesEffectActionsProvider: Provider = {
provide: VCS_DETECT_CHANGES_EFFECT_ACTIONS,
useValue: [
NoteCollectionActionTypes.LOAD_COLLECTION,
NoteCollectionActionTypes.ADD_NOTE,
NoteEditorActionTypes.SAVE_NOTE_CONTENT_COMPLETE,
],
};
| import { Provider } from '@angular/core';
import { NoteCollectionActionTypes } from '../note/note-collection';
import { NoteEditorActionTypes } from '../note/note-editor';
import { NoteVcsItemFactory } from '../note/note-shared';
import { VCS_DETECT_CHANGES_EFFECT_ACTIONS } from '../vcs';
import { BaseVcsItemFactory, VCS_ITEM_MAKING_FACTORIES, VcsItemFactory } from '../vcs/vcs-view';
export const AppVcsItemFactoriesProvider: Provider = {
provide: VCS_ITEM_MAKING_FACTORIES,
useFactory(
noteVcsItemFactory: NoteVcsItemFactory,
baseVcsItemFactory: BaseVcsItemFactory,
): VcsItemFactory<any>[] {
// 1. Note related files
// 2. Others... (asset etc.)
return [noteVcsItemFactory, baseVcsItemFactory];
},
deps: [NoteVcsItemFactory, BaseVcsItemFactory],
};
export const AppVcsDetectChangesEffectActionsProvider: Provider = {
provide: VCS_DETECT_CHANGES_EFFECT_ACTIONS,
useValue: [
NoteCollectionActionTypes.LOAD_COLLECTION_COMPLETE,
NoteCollectionActionTypes.ADD_NOTE,
NoteEditorActionTypes.SAVE_NOTE_CONTENT_COMPLETE,
],
};
| Update app config: add note vcs item factory | Update app config: add note vcs item factory
| TypeScript | mit | seokju-na/geeks-diary,seokju-na/geeks-diary,seokju-na/geeks-diary | ---
+++
@@ -1,23 +1,29 @@
import { Provider } from '@angular/core';
import { NoteCollectionActionTypes } from '../note/note-collection';
import { NoteEditorActionTypes } from '../note/note-editor';
+import { NoteVcsItemFactory } from '../note/note-shared';
import { VCS_DETECT_CHANGES_EFFECT_ACTIONS } from '../vcs';
import { BaseVcsItemFactory, VCS_ITEM_MAKING_FACTORIES, VcsItemFactory } from '../vcs/vcs-view';
export const AppVcsItemFactoriesProvider: Provider = {
provide: VCS_ITEM_MAKING_FACTORIES,
- useFactory(baseVcsItemFactory: BaseVcsItemFactory): VcsItemFactory<any>[] {
- return [baseVcsItemFactory];
+ useFactory(
+ noteVcsItemFactory: NoteVcsItemFactory,
+ baseVcsItemFactory: BaseVcsItemFactory,
+ ): VcsItemFactory<any>[] {
+ // 1. Note related files
+ // 2. Others... (asset etc.)
+ return [noteVcsItemFactory, baseVcsItemFactory];
},
- deps: [BaseVcsItemFactory],
+ deps: [NoteVcsItemFactory, BaseVcsItemFactory],
};
export const AppVcsDetectChangesEffectActionsProvider: Provider = {
provide: VCS_DETECT_CHANGES_EFFECT_ACTIONS,
useValue: [
- NoteCollectionActionTypes.LOAD_COLLECTION,
+ NoteCollectionActionTypes.LOAD_COLLECTION_COMPLETE,
NoteCollectionActionTypes.ADD_NOTE,
NoteEditorActionTypes.SAVE_NOTE_CONTENT_COMPLETE,
], |
174c016f0f2cc4a6f00ea0d3a547d0d8745235bf | packages/puppeteer/src/index.ts | packages/puppeteer/src/index.ts | import {
Webdriver,
ElementNotFoundError,
ElementNotVisibleError,
} from 'mugshot';
import { Page } from 'puppeteer';
/**
* Webdriver adapter over [Puppeteer](https://github.com/puppeteer/puppeteer)
* to be used with [[WebdriverScreenshotter].
*
* @see https://github.com/puppeteer/puppeteer/blob/v2.0.0/docs/api.md
*/
export default class PuppeteerAdapter implements Webdriver {
constructor(private readonly page: Page) {}
getElementRect = async (selector: string) => {
const elements = await this.page.$$(selector);
if (!elements.length) {
throw new ElementNotFoundError(selector);
}
const rects = await Promise.all(
elements.map(async (element) => {
const rect = await element.boundingBox();
if (!rect) {
throw new ElementNotVisibleError(selector);
}
return rect;
})
);
return rects.length === 1 ? rects[0] : rects;
};
setViewportSize = (width: number, height: number) =>
this.page.setViewport({
width,
height,
});
takeScreenshot = () => this.page.screenshot();
execute = <R>(func: (...args: any[]) => R, ...args: any[]) =>
this.page.evaluate(func, ...args);
}
| import {
Webdriver,
ElementNotFoundError,
ElementNotVisibleError,
} from 'mugshot';
import { Page } from 'puppeteer';
/**
* Webdriver adapter over [Puppeteer](https://github.com/puppeteer/puppeteer)
* to be used with [[WebdriverScreenshotter]].
*
* @see https://github.com/puppeteer/puppeteer/blob/v2.0.0/docs/api.md
*/
export default class PuppeteerAdapter implements Webdriver {
constructor(private readonly page: Page) {}
getElementRect = async (selector: string) => {
const elements = await this.page.$$(selector);
if (!elements.length) {
throw new ElementNotFoundError(selector);
}
const rects = await Promise.all(
elements.map(async (element) => {
const rect = await element.boundingBox();
if (!rect) {
throw new ElementNotVisibleError(selector);
}
return rect;
})
);
return rects.length === 1 ? rects[0] : rects;
};
setViewportSize = (width: number, height: number) =>
this.page.setViewport({
width,
height,
});
takeScreenshot = () => this.page.screenshot();
execute = <R>(func: (...args: any[]) => R, ...args: any[]) =>
this.page.evaluate(func, ...args);
}
| Fix typedoc link in docstring | docs(puppeteer): Fix typedoc link in docstring
| TypeScript | mit | uberVU/mugshot,uberVU/mugshot | ---
+++
@@ -7,7 +7,7 @@
/**
* Webdriver adapter over [Puppeteer](https://github.com/puppeteer/puppeteer)
- * to be used with [[WebdriverScreenshotter].
+ * to be used with [[WebdriverScreenshotter]].
*
* @see https://github.com/puppeteer/puppeteer/blob/v2.0.0/docs/api.md
*/ |
fe4b14d32b3dd4c5972a6dba70438d7021d64af1 | packages/react-day-picker/src/components/Day/Day.tsx | packages/react-day-picker/src/components/Day/Day.tsx | import * as React from 'react';
import { DayProps } from 'types';
import { defaultProps } from '../DayPicker/defaultProps';
import { getDayComponent } from './getDayComponent';
export function Day(props: DayProps): JSX.Element {
const { day, dayPickerProps, currentMonth } = props;
const locale = dayPickerProps.locale ?? defaultProps.locale;
const formatDay = dayPickerProps.formatDay ?? defaultProps.formatDay;
const { containerProps, wrapperProps } = getDayComponent(
day,
currentMonth,
dayPickerProps
);
return (
<span {...containerProps}>
<time {...wrapperProps}>{formatDay(day, { locale })}</time>
</span>
);
}
| import * as React from 'react';
import { DayProps } from 'types';
import { defaultProps } from '../DayPicker/defaultProps';
import { getDayComponent } from './getDayComponent';
export function Day(props: DayProps): JSX.Element {
const { day, dayPickerProps, currentMonth } = props;
const locale = dayPickerProps.locale ?? defaultProps.locale;
const formatDay = dayPickerProps.formatDay ?? defaultProps.formatDay;
const { containerProps, wrapperProps, modifiers } = getDayComponent(
day,
currentMonth,
dayPickerProps
);
if (modifiers.hidden) {
return <span />;
}
return (
<span {...containerProps}>
<time {...wrapperProps}>{formatDay(day, { locale })}</time>
</span>
);
}
| Fix outside day not hidden when required | Fix outside day not hidden when required
| TypeScript | mit | gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker | ---
+++
@@ -9,11 +9,15 @@
const locale = dayPickerProps.locale ?? defaultProps.locale;
const formatDay = dayPickerProps.formatDay ?? defaultProps.formatDay;
- const { containerProps, wrapperProps } = getDayComponent(
+ const { containerProps, wrapperProps, modifiers } = getDayComponent(
day,
currentMonth,
dayPickerProps
);
+
+ if (modifiers.hidden) {
+ return <span />;
+ }
return (
<span {...containerProps}> |
931eca33f0db1e97f4d0d87398c46e2d6cd21a1e | tools/env/dev.ts | tools/env/dev.ts | import { EnvConfig } from './env-config.interface';
const DevConfig: EnvConfig = {
API: 'http://knora.nie-ine.ch/v1/search/',
ENV: 'DEV'
};
export = DevConfig;
| import { EnvConfig } from './env-config.interface';
const DevConfig: EnvConfig = {
API: 'http://130.60.24.65:3333/v1/',
ENV: 'DEV'
};
export = DevConfig;
| Change API url to 130.60.23.65:3333/v1 | Change API url to 130.60.23.65:3333/v1
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -1,7 +1,7 @@
import { EnvConfig } from './env-config.interface';
const DevConfig: EnvConfig = {
- API: 'http://knora.nie-ine.ch/v1/search/',
+ API: 'http://130.60.24.65:3333/v1/',
ENV: 'DEV'
};
|
a634c7fcbbddd3ef4ed85b2a13626db1730d592d | src/FeathersVuexInputWrapper.ts | src/FeathersVuexInputWrapper.ts | export default {
name: 'FeathersVuexInputWrapper',
props: {
item: {
type: Object,
required: true
},
prop: {
type: String,
required: true
}
},
data: () => ({
clone: null
}),
computed: {
current() {
return this.clone || this.item
}
},
methods: {
createClone(e) {
this.clone = this.item.clone()
},
cleanup() {
this.$nextTick(() => {
this.clone = null
})
},
handler(e, callback) {
if (!this.clone) {
this.createClone()
}
const maybePromise = callback({
event: e,
clone: this.clone,
prop: this.prop,
data: { [this.prop]: this.clone[this.prop] }
})
if (maybePromise && maybePromise.then) {
maybePromise.then(this.cleanup)
} else {
this.cleanup()
}
}
},
render() {
const { current, prop, createClone, handler } = this
return this.$scopedSlots.default({ current, prop, createClone, handler })
}
}
| import _debounce from 'lodash/debounce'
export default {
name: 'FeathersVuexInputWrapper',
props: {
item: {
type: Object,
required: true
},
prop: {
type: String,
required: true
},
debounce: {
type: Number,
default: 0
}
},
data: () => ({
clone: null
}),
computed: {
current() {
return this.clone || this.item
}
},
watch: {
debounce: {
handler(wait) {
this.debouncedHandler = _debounce(this.handler, wait)
},
immediate: true
}
},
methods: {
createClone(e) {
this.clone = this.item.clone()
},
cleanup() {
this.$nextTick(() => {
this.clone = null
})
},
handler(e, callback) {
debugger
if (!this.clone) {
this.createClone()
}
const maybePromise = callback({
event: e,
clone: this.clone,
prop: this.prop,
data: { [this.prop]: this.clone[this.prop] }
})
if (maybePromise && maybePromise.then) {
maybePromise.then(this.cleanup)
} else {
this.cleanup()
}
}
},
render() {
const { current, prop, createClone } = this
const handler = this.debounce ? this.debouncedHandler : this.handler
return this.$scopedSlots.default({ current, prop, createClone, handler })
}
}
| Add internal debounce to the input wrapper | Add internal debounce to the input wrapper
This adds a new `debounce` prop to the input-wrapper which allows proper internal debouncing.
| TypeScript | mit | feathers-plus/feathers-vuex,feathers-plus/feathers-vuex | ---
+++
@@ -1,3 +1,5 @@
+import _debounce from 'lodash/debounce'
+
export default {
name: 'FeathersVuexInputWrapper',
props: {
@@ -8,6 +10,10 @@
prop: {
type: String,
required: true
+ },
+ debounce: {
+ type: Number,
+ default: 0
}
},
data: () => ({
@@ -16,6 +22,14 @@
computed: {
current() {
return this.clone || this.item
+ }
+ },
+ watch: {
+ debounce: {
+ handler(wait) {
+ this.debouncedHandler = _debounce(this.handler, wait)
+ },
+ immediate: true
}
},
methods: {
@@ -28,6 +42,7 @@
})
},
handler(e, callback) {
+ debugger
if (!this.clone) {
this.createClone()
}
@@ -45,7 +60,9 @@
}
},
render() {
- const { current, prop, createClone, handler } = this
+ const { current, prop, createClone } = this
+ const handler = this.debounce ? this.debouncedHandler : this.handler
+
return this.$scopedSlots.default({ current, prop, createClone, handler })
}
} |
b73fd9d1e9069e815cdcf8d98fadea63cc7fd50b | applications/drive/src/app/components/uploads/UploadButton.tsx | applications/drive/src/app/components/uploads/UploadButton.tsx | import React from 'react';
import { c } from 'ttag';
import { FloatingButton, SidebarPrimaryButton } from 'react-components';
import { useDriveActiveFolder } from '../Drive/DriveFolderProvider';
import useFileUploadInput from '../../hooks/drive/useFileUploadInput';
interface Props {
floating?: boolean;
}
const UploadButton = ({ floating }: Props) => {
const { folder } = useDriveActiveFolder();
const { inputRef: fileInput, handleClick, handleChange: handleFileChange } = useFileUploadInput();
return (
<>
<input multiple type="file" ref={fileInput} className="hidden" onChange={handleFileChange} />
{floating ? (
<FloatingButton
disabled={!folder?.shareId}
onClick={handleClick}
title={c('Action').t`New upload`}
icon="plus"
/>
) : (
<SidebarPrimaryButton disabled={!folder?.shareId} onClick={handleClick}>{c('Action')
.t`New upload`}</SidebarPrimaryButton>
)}
</>
);
};
export default UploadButton;
| import React from 'react';
import { c } from 'ttag';
import { classnames, FloatingButton, SidebarPrimaryButton } from 'react-components';
import { useDriveActiveFolder } from '../Drive/DriveFolderProvider';
import useFileUploadInput from '../../hooks/drive/useFileUploadInput';
import { useDownloadProvider } from '../downloads/DownloadProvider';
import { useUploadProvider } from './UploadProvider';
interface Props {
floating?: boolean;
}
const UploadButton = ({ floating }: Props) => {
const { folder } = useDriveActiveFolder();
const { inputRef: fileInput, handleClick, handleChange: handleFileChange } = useFileUploadInput();
const { downloads } = useDownloadProvider();
const { uploads } = useUploadProvider();
const isTransfering = uploads.length > 0 || downloads.length > 0;
return (
<>
<input multiple type="file" ref={fileInput} className="hidden" onChange={handleFileChange} />
{floating ? (
<FloatingButton
className={classnames([isTransfering && 'compose-fab--is-higher'])}
disabled={!folder?.shareId}
onClick={handleClick}
title={c('Action').t`New upload`}
icon="plus"
/>
) : (
<SidebarPrimaryButton disabled={!folder?.shareId} onClick={handleClick}>{c('Action')
.t`New upload`}</SidebarPrimaryButton>
)}
</>
);
};
export default UploadButton;
| Move fab button when transfer manager is open | Move fab button when transfer manager is open
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,10 +1,12 @@
import React from 'react';
import { c } from 'ttag';
-import { FloatingButton, SidebarPrimaryButton } from 'react-components';
+import { classnames, FloatingButton, SidebarPrimaryButton } from 'react-components';
import { useDriveActiveFolder } from '../Drive/DriveFolderProvider';
import useFileUploadInput from '../../hooks/drive/useFileUploadInput';
+import { useDownloadProvider } from '../downloads/DownloadProvider';
+import { useUploadProvider } from './UploadProvider';
interface Props {
floating?: boolean;
@@ -14,11 +16,16 @@
const { folder } = useDriveActiveFolder();
const { inputRef: fileInput, handleClick, handleChange: handleFileChange } = useFileUploadInput();
+ const { downloads } = useDownloadProvider();
+ const { uploads } = useUploadProvider();
+ const isTransfering = uploads.length > 0 || downloads.length > 0;
+
return (
<>
<input multiple type="file" ref={fileInput} className="hidden" onChange={handleFileChange} />
{floating ? (
<FloatingButton
+ className={classnames([isTransfering && 'compose-fab--is-higher'])}
disabled={!folder?.shareId}
onClick={handleClick}
title={c('Action').t`New upload`} |
34c90d09b80edf974a3e64c76497d275aa1f3ffd | tests/gui/specs/simple.spec.ts | tests/gui/specs/simple.spec.ts | import path from 'path';
import fs from 'fs-extra';
import { describe, expect, it, loadFixture } from '../suite';
import Mugshot from '../../../src/mugshot';
import jimpEditor from '../../../src/lib/jimp-editor';
describe('Mugshot', () => {
const resultsPath = path.join(__dirname, `../screenshots/${process.env.BROWSER}`);
it('should pass when identical', async browser => {
await loadFixture('simple');
const mugshot = new Mugshot(browser, resultsPath, {
fs,
pngEditor: jimpEditor
});
const result = await mugshot.check('simple');
expect(result.matches).to.be.true;
});
it('should fail when different', async browser => {
await loadFixture('simple2');
const mugshot = new Mugshot(browser, resultsPath, {
fs,
pngEditor: jimpEditor
});
const result = await mugshot.check('simple');
expect(result.matches).to.be.false;
});
});
| import path from 'path';
import fs from 'fs-extra';
import { describe, expect, it, loadFixture } from '../suite';
import Mugshot from '../../../src/mugshot';
import jimpEditor from '../../../src/lib/jimp-editor';
describe('Mugshot', () => {
const resultsPath = path.join(__dirname, `../screenshots/${process.env.BROWSER}`);
it('should pass when identical', async browser => {
await loadFixture('simple');
const mugshot = new Mugshot(browser, resultsPath, {
fs,
pngEditor: jimpEditor
});
const result = await mugshot.check('simple');
expect(result.matches).to.be.true;
});
it('should fail when different', async browser => {
await loadFixture('simple2');
const mugshot = new Mugshot(browser, resultsPath, {
fs,
pngEditor: jimpEditor
});
const result = await mugshot.check('simple');
expect(result.matches).to.be.false;
});
it('should write first baseline', async browser => {
await loadFixture('simple2');
const baselinePath = path.join(resultsPath, 'new.png');
await fs.remove(baselinePath);
const mugshot = new Mugshot(browser, resultsPath, {
fs,
pngEditor: jimpEditor
});
const resultWhenMissingBaseline = await mugshot.check('new');
expect(resultWhenMissingBaseline.matches).to.be.false;
expect(
await fs.pathExists(baselinePath),
'Baseline wasn\'t written'
).to.be.true;
const resultWhenExistingBaseline = await mugshot.check('new');
expect(resultWhenExistingBaseline.matches).to.be.true;
});
});
| Add failing e2e tests for writing new baselines | Add failing e2e tests for writing new baselines
| TypeScript | mit | uberVU/mugshot,uberVU/mugshot | ---
+++
@@ -32,4 +32,26 @@
expect(result.matches).to.be.false;
});
+
+ it('should write first baseline', async browser => {
+ await loadFixture('simple2');
+
+ const baselinePath = path.join(resultsPath, 'new.png');
+ await fs.remove(baselinePath);
+
+ const mugshot = new Mugshot(browser, resultsPath, {
+ fs,
+ pngEditor: jimpEditor
+ });
+
+ const resultWhenMissingBaseline = await mugshot.check('new');
+ expect(resultWhenMissingBaseline.matches).to.be.false;
+ expect(
+ await fs.pathExists(baselinePath),
+ 'Baseline wasn\'t written'
+ ).to.be.true;
+
+ const resultWhenExistingBaseline = await mugshot.check('new');
+ expect(resultWhenExistingBaseline.matches).to.be.true;
+ });
}); |
389e1271d7a072442b756f62072c9e447d81dc47 | app/javascript/retrospring/features/moderation/blockAnon.ts | app/javascript/retrospring/features/moderation/blockAnon.ts | import Rails from '@rails/ujs';
import swal from 'sweetalert';
import { showErrorNotification, showNotification } from "utilities/notifications";
import I18n from "retrospring/i18n";
export function blockAnonEventHandler(event: Event): void {
event.preventDefault();
swal({
title: I18n.translate('frontend.mod_mute.confirm.title'),
text: I18n.translate('frontend.mod_mute.confirm.text'),
type: 'warning',
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: I18n.translate('voc.y'),
cancelButtonText: I18n.translate('voc.n'),
closeOnConfirm: true,
}, (dialogResult) => {
if (!dialogResult) {
return;
}
const sender: HTMLAnchorElement = event.target as HTMLAnchorElement;
const data = {
question: sender.getAttribute('data-q-id'),
global: 'true'
};
Rails.ajax({
url: '/ajax/block_anon',
type: 'POST',
data: new URLSearchParams(data).toString(),
success: (data) => {
if (!data.success) return false;
showNotification(data.message);
},
error: (data, status, xhr) => {
console.log(data, status, xhr);
showErrorNotification(I18n.translate('frontend.error.message'));
}
});
});
} | import { post } from '@rails/request.js';
import swal from 'sweetalert';
import { showErrorNotification, showNotification } from "utilities/notifications";
import I18n from "retrospring/i18n";
export function blockAnonEventHandler(event: Event): void {
event.preventDefault();
swal({
title: I18n.translate('frontend.mod_mute.confirm.title'),
text: I18n.translate('frontend.mod_mute.confirm.text'),
type: 'warning',
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: I18n.translate('voc.y'),
cancelButtonText: I18n.translate('voc.n'),
closeOnConfirm: true,
}, (dialogResult) => {
if (!dialogResult) {
return;
}
const sender: HTMLAnchorElement = event.target as HTMLAnchorElement;
const data = {
question: sender.getAttribute('data-q-id'),
global: 'true'
};
post('/ajax/block_anon', {
body: data,
contentType: 'application/json'
})
.then(async response => {
const data = await response.json;
if (!data.success) return false;
showNotification(data.message);
})
.catch(err => {
console.log(err);
showErrorNotification(I18n.translate('frontend.error.message'));
});
});
} | Refactor global anon blocks to use request.js | Refactor global anon blocks to use request.js
| TypeScript | agpl-3.0 | Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring | ---
+++
@@ -1,46 +1,47 @@
-import Rails from '@rails/ujs';
+import { post } from '@rails/request.js';
import swal from 'sweetalert';
import { showErrorNotification, showNotification } from "utilities/notifications";
import I18n from "retrospring/i18n";
export function blockAnonEventHandler(event: Event): void {
- event.preventDefault();
-
- swal({
- title: I18n.translate('frontend.mod_mute.confirm.title'),
- text: I18n.translate('frontend.mod_mute.confirm.text'),
- type: 'warning',
- showCancelButton: true,
- confirmButtonColor: "#DD6B55",
- confirmButtonText: I18n.translate('voc.y'),
- cancelButtonText: I18n.translate('voc.n'),
- closeOnConfirm: true,
- }, (dialogResult) => {
- if (!dialogResult) {
- return;
- }
+ event.preventDefault();
+
+ swal({
+ title: I18n.translate('frontend.mod_mute.confirm.title'),
+ text: I18n.translate('frontend.mod_mute.confirm.text'),
+ type: 'warning',
+ showCancelButton: true,
+ confirmButtonColor: "#DD6B55",
+ confirmButtonText: I18n.translate('voc.y'),
+ cancelButtonText: I18n.translate('voc.n'),
+ closeOnConfirm: true,
+ }, (dialogResult) => {
+ if (!dialogResult) {
+ return;
+ }
- const sender: HTMLAnchorElement = event.target as HTMLAnchorElement;
+ const sender: HTMLAnchorElement = event.target as HTMLAnchorElement;
- const data = {
- question: sender.getAttribute('data-q-id'),
- global: 'true'
- };
+ const data = {
+ question: sender.getAttribute('data-q-id'),
+ global: 'true'
+ };
- Rails.ajax({
- url: '/ajax/block_anon',
- type: 'POST',
- data: new URLSearchParams(data).toString(),
- success: (data) => {
- if (!data.success) return false;
+ post('/ajax/block_anon', {
+ body: data,
+ contentType: 'application/json'
+ })
+ .then(async response => {
+ const data = await response.json;
- showNotification(data.message);
- },
- error: (data, status, xhr) => {
- console.log(data, status, xhr);
- showErrorNotification(I18n.translate('frontend.error.message'));
- }
- });
- });
+ if (!data.success) return false;
+
+ showNotification(data.message);
+ })
+ .catch(err => {
+ console.log(err);
+ showErrorNotification(I18n.translate('frontend.error.message'));
+ });
+ });
} |
7944fe7822b273041c15174152f1a37ce10a698a | src/history/daily/container.tsx | src/history/daily/container.tsx | import * as React from 'react';
import DatePicker from 'material-ui/DatePicker';
import { retrieveHistoricalReadings } from '../../api';
import { formatDateFull, isFutureDate } from '../../dates';
import { Reading } from '../../model';
import Promised from '../../promised';
import View from './view';
const PromisedRecentReadingsView = Promised<Reading>('data', View);
interface State {
promise?: Promise<Reading>;
selectedDate?: Date;
}
class HistoryContainer extends React.Component<{}, State> {
constructor(props: {}) {
super(props);
this.state = {};
}
render() {
const { promise } = this.state;
return (
<React.Fragment>
<h1>Retrieve history</h1>
<DatePicker
hintText='Select a date...'
container='inline'
autoOk={ true }
formatDate={ formatDateFull }
shouldDisableDate={ isFutureDate }
onChange={ this.selectDate }
/>
<br />
{ promise && <PromisedRecentReadingsView promise={ promise } /> }
</React.Fragment>
);
}
private selectDate = (event: any, selectedDate: Date) => {
// First remove the old promise (forcing React to re-render container)...
this.setState({ promise: undefined }, () => {
// ... only then to create the new promise (forcing another re-render).
this.setState({ promise: retrieveHistoricalReadings(selectedDate) });
});
}
}
export default HistoryContainer;
| import * as React from 'react';
import DatePicker from 'material-ui/DatePicker';
import { retrieveHistoricalReadings } from '../../api';
import { formatDateFull, isFutureDate } from '../../dates';
import { Reading } from '../../model';
import Promised from '../../promised';
import View from './view';
const PromisedRecentReadingsView = Promised<Reading>('data', View);
interface State {
promise?: Promise<Reading>;
selectedDate?: Date;
}
class HistoryContainer extends React.Component<{}, State> {
constructor(props: {}) {
super(props);
this.state = {};
}
render() {
const { promise } = this.state;
return (
<React.Fragment>
<h1>Retrieve history by date</h1>
<DatePicker
hintText='Select a date...'
container='inline'
autoOk={ true }
firstDayOfWeek={ 0 }
formatDate={ formatDateFull }
shouldDisableDate={ isFutureDate }
onChange={ this.selectDate }
/>
<br />
{ promise && <PromisedRecentReadingsView promise={ promise } /> }
</React.Fragment>
);
}
private selectDate = (event: any, selectedDate: Date) => {
// First remove the old promise (forcing React to re-render container)...
this.setState({ promise: undefined }, () => {
// ... only then to create the new promise (forcing another re-render).
this.setState({ promise: retrieveHistoricalReadings(selectedDate) });
});
}
}
export default HistoryContainer;
| Put Sunday as first day of the week | Put Sunday as first day of the week
| TypeScript | mit | mthmulders/hyperion-web,mthmulders/hyperion-web,mthmulders/hyperion-web | ---
+++
@@ -26,11 +26,12 @@
return (
<React.Fragment>
- <h1>Retrieve history</h1>
+ <h1>Retrieve history by date</h1>
<DatePicker
hintText='Select a date...'
container='inline'
autoOk={ true }
+ firstDayOfWeek={ 0 }
formatDate={ formatDateFull }
shouldDisableDate={ isFutureDate }
onChange={ this.selectDate } |
73bd965ee5f99eda157b24a45b245248a70a1e78 | types/esm.d.ts | types/esm.d.ts | import { SleepOptions } from './shared';
declare function sleep<T = any>(
timeout: number,
options: SleepOptions = {},
): Promise<T> & ((value: T) => T);
export default sleep;
| import { SleepOptions } from './shared';
declare function sleep<T = any>(
timeout: number,
options?: SleepOptions,
): Promise<T> & ((value: T) => T);
export default sleep;
| Fix typings in esm file | Fix typings in esm file
| TypeScript | mit | brummelte/sleep-promise | ---
+++
@@ -2,7 +2,7 @@
declare function sleep<T = any>(
timeout: number,
- options: SleepOptions = {},
+ options?: SleepOptions,
): Promise<T> & ((value: T) => T);
export default sleep; |
99bd2bce5edbbc9dddabb16c21a7c1ca73c822c5 | packages/commutable/__tests__/primitive.spec.ts | packages/commutable/__tests__/primitive.spec.ts | import { remultiline } from "../src/primitives";
describe("remultiline", () => {
it("correctly splits strings by newline", () => {
const testString = "this\nis\na\ntest\n";
const multilined = remultiline(testString);
expect(multilined).toBe(["this", "is", "a", "test"]);
})
}) | import { remultiline } from "../src/primitives";
describe("remultiline", () => {
it("correctly splits strings by newline", () => {
const testString = "this\nis\na\ntest\n";
const multilined = remultiline(testString);
expect(multilined).toEqual(["this\n", "is\n", "a\n", "test\n"]);
})
}) | Fix equality check for tests | Fix equality check for tests
| TypeScript | bsd-3-clause | nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract,nteract/composition,nteract/composition,nteract/nteract,nteract/nteract | ---
+++
@@ -4,6 +4,6 @@
it("correctly splits strings by newline", () => {
const testString = "this\nis\na\ntest\n";
const multilined = remultiline(testString);
- expect(multilined).toBe(["this", "is", "a", "test"]);
+ expect(multilined).toEqual(["this\n", "is\n", "a\n", "test\n"]);
})
}) |
708723036dbd0aba0de3faa9a1c317e761f9359a | src/polyfills.ts | src/polyfills.ts | // This file includes polyfills needed by Angular 2 and is loaded before
// the app. You can add your own extra polyfills to this file.
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/set';
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
import 'proxy-polyfill';
| // This file includes polyfills needed by Angular 2 and is loaded before
// the app. You can add your own extra polyfills to this file.
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/set';
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
// Proxy stub
if (!('Proxy' in window)) {
window['Proxy'] = {};
}
| Remove proxy-polyfill from dev deps and try to stub it for tests | Remove proxy-polyfill from dev deps and try to stub it for tests
| TypeScript | mit | gund/ng-http-interceptor,gund/ng-http-interceptor,gund/ng-http-interceptor,gund/ng2-http-interceptor,gund/ng2-http-interceptor,gund/ng2-http-interceptor | ---
+++
@@ -18,4 +18,7 @@
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
-import 'proxy-polyfill';
+// Proxy stub
+if (!('Proxy' in window)) {
+ window['Proxy'] = {};
+} |
95776d175e6fba24c19954b85f7919293adf1405 | experimental/msal-react/src/utilities.ts | experimental/msal-react/src/utilities.ts | import { IMsalContext } from './MsalContext';
import {
IPublicClientApplication,
AuthenticationResult,
} from '@azure/msal-browser';
type FaaCFunction = (props: IMsalContext) => React.ReactNode;
export function getChildrenOrFunction(
children: React.ReactNode | FaaCFunction,
context: IMsalContext
): React.ReactNode {
if (typeof children === 'function') {
return children(context);
}
return children;
}
export function isAuthenticated(
instance: IPublicClientApplication,
username?: string
): boolean {
// TODO: Remove the `|| []` hack when the @azure/msal-browser is updated
return username
? !!instance.getAccountByUsername(username)
: (instance.getAllAccounts() || []).length > 0;
}
export function defaultLoginHandler(
context: IMsalContext
): Promise<AuthenticationResult> {
const { instance } = context;
return instance.loginPopup({
scopes: ['user.read'],
prompt: 'select_account',
});
}
| import { IMsalContext } from './MsalContext';
import {
IPublicClientApplication,
AuthenticationResult,
} from '@azure/msal-browser';
type FaaCFunction = <T>(args: T) => React.ReactNode;
export function getChildrenOrFunction<T>(
children: React.ReactNode | FaaCFunction,
args: T
): React.ReactNode {
if (typeof children === 'function') {
return children(args);
}
return children;
}
export function isAuthenticated(
instance: IPublicClientApplication,
username?: string
): boolean {
// TODO: Remove the `|| []` hack when the @azure/msal-browser is updated
return username
? !!instance.getAccountByUsername(username)
: (instance.getAllAccounts() || []).length > 0;
}
export function defaultLoginHandler(
context: IMsalContext
): Promise<AuthenticationResult> {
const { instance } = context;
return instance.loginPopup({
scopes: ['user.read'],
prompt: 'select_account',
});
}
| Update the FaaC helper utility to use generic props | Update the FaaC helper utility to use generic props
| TypeScript | mit | AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js | ---
+++
@@ -4,14 +4,14 @@
AuthenticationResult,
} from '@azure/msal-browser';
-type FaaCFunction = (props: IMsalContext) => React.ReactNode;
+type FaaCFunction = <T>(args: T) => React.ReactNode;
-export function getChildrenOrFunction(
+export function getChildrenOrFunction<T>(
children: React.ReactNode | FaaCFunction,
- context: IMsalContext
+ args: T
): React.ReactNode {
if (typeof children === 'function') {
- return children(context);
+ return children(args);
}
return children;
} |
f7360f32b45bc290952a03140d349dcf0239ac43 | src/components/Condition/Condition.Operator.tsx | src/components/Condition/Condition.Operator.tsx | import * as React from 'react'
import propConnect from '../PropProvider/propConnect'
import Text from '../Text'
import { classNames } from '../../utilities/classNames'
import { COMPONENT_KEY } from './Condition.utils'
import { ConditionOperatorProps } from './Condition.types'
import { OperatorUI } from './styles/Condition.css'
export const Operator = (props: ConditionOperatorProps) => {
const { className, isBorderless, type, ...rest } = props
const label = type.toLowerCase() === 'and' ? 'and' : 'or'
const componentClassName = classNames(
Operator.className,
isBorderless && 'is-borderless',
`is-${label}`,
className
)
return (
<OperatorUI {...rest} className={componentClassName}>
<Text block lineHeightReset size="11">
{label}
</Text>
</OperatorUI>
)
}
Operator.className = 'c-ConditionOperator'
Operator.defaultProps = {
isBorderless: true,
type: 'or',
}
const PropConnectedComponent = propConnect(COMPONENT_KEY.Operator)(Operator)
export default PropConnectedComponent
| import * as React from 'react'
import propConnect from '../PropProvider/propConnect'
import Text from '../Text'
import { classNames } from '../../utilities/classNames'
import { COMPONENT_KEY } from './Condition.utils'
import { ConditionOperatorProps } from './Condition.types'
import { OperatorUI } from './styles/Condition.css'
export const Operator = (props: ConditionOperatorProps) => {
const { className, isBorderless, type, ...rest } = props
const label = type.toLowerCase() === 'and' ? 'and' : 'or'
const componentClassName = classNames(
Operator.className,
isBorderless && 'is-borderless',
`is-${label}`,
className
)
return (
<OperatorUI {...rest} className={componentClassName}>
<Text block lineHeightReset size="11" weight={500}>
{label}
</Text>
</OperatorUI>
)
}
Operator.className = 'c-ConditionOperator'
Operator.defaultProps = {
isBorderless: true,
type: 'or',
}
const PropConnectedComponent = propConnect(COMPONENT_KEY.Operator)(Operator)
export default PropConnectedComponent
| Update Condtional Operation font weight | Update Condtional Operation font weight
| TypeScript | mit | helpscout/blue,helpscout/blue,helpscout/blue | ---
+++
@@ -19,7 +19,7 @@
return (
<OperatorUI {...rest} className={componentClassName}>
- <Text block lineHeightReset size="11">
+ <Text block lineHeightReset size="11" weight={500}>
{label}
</Text>
</OperatorUI> |
e78f7a278f486e5dc0f5409abe417de7cd7152a4 | packages/@sanity/components/src/menuButton/menuButton.tsx | packages/@sanity/components/src/menuButton/menuButton.tsx | import Button from 'part:@sanity/components/buttons/default'
import {ClickOutside} from 'part:@sanity/components/click-outside'
import {Popover} from 'part:@sanity/components/popover'
import React, {useCallback} from 'react'
import {ButtonProps} from '../buttons'
import {Placement} from '../types'
interface MenuButtonProps {
boundaryElement?: HTMLElement | null
buttonProps?: ButtonProps
menu?: React.ReactNode
placement?: Placement
open?: boolean
setOpen: (val: boolean) => void
}
export function MenuButton(props: MenuButtonProps & React.HTMLProps<HTMLDivElement>) {
const {
boundaryElement,
buttonProps,
children,
menu,
open,
placement,
setOpen,
...restProps
} = props
const handleClose = useCallback(() => setOpen(false), [setOpen])
const handleButtonClick = useCallback(() => setOpen(!open), [open, setOpen])
return (
<ClickOutside onClickOutside={handleClose}>
{ref => (
<div {...restProps} ref={ref}>
<Popover
boundaryElement={boundaryElement}
content={menu}
open={open}
placement={placement}
>
<div>
<Button {...buttonProps} onClick={handleButtonClick}>
{children}
</Button>
</div>
</Popover>
</div>
)}
</ClickOutside>
)
}
| import Button from 'part:@sanity/components/buttons/default'
import {ClickOutside} from 'part:@sanity/components/click-outside'
import {Popover} from 'part:@sanity/components/popover'
import Escapable from 'part:@sanity/components/utilities/escapable'
import React, {useCallback} from 'react'
import {ButtonProps} from '../buttons'
import {Placement} from '../types'
interface MenuButtonProps {
boundaryElement?: HTMLElement | null
buttonProps?: ButtonProps
menu?: React.ReactNode
placement?: Placement
open?: boolean
setOpen: (val: boolean) => void
}
export function MenuButton(props: MenuButtonProps & React.HTMLProps<HTMLDivElement>) {
const {
boundaryElement,
buttonProps,
children,
menu,
open,
placement,
setOpen,
...restProps
} = props
const handleClose = useCallback(() => setOpen(false), [setOpen])
const handleButtonClick = useCallback(() => setOpen(!open), [open, setOpen])
return (
<ClickOutside onClickOutside={handleClose}>
{ref => (
<div {...restProps} ref={ref}>
<Popover
boundaryElement={boundaryElement}
content={menu}
open={open}
placement={placement}
>
<div>
<Button {...buttonProps} onClick={handleButtonClick}>
{children}
</Button>
</div>
</Popover>
{open && <Escapable onEscape={handleClose} />}
</div>
)}
</ClickOutside>
)
}
| Add escape handler to menu button | [components] Add escape handler to menu button
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -1,6 +1,7 @@
import Button from 'part:@sanity/components/buttons/default'
import {ClickOutside} from 'part:@sanity/components/click-outside'
import {Popover} from 'part:@sanity/components/popover'
+import Escapable from 'part:@sanity/components/utilities/escapable'
import React, {useCallback} from 'react'
import {ButtonProps} from '../buttons'
import {Placement} from '../types'
@@ -45,6 +46,8 @@
</Button>
</div>
</Popover>
+
+ {open && <Escapable onEscape={handleClose} />}
</div>
)}
</ClickOutside> |
d6543898df0b1d7f2cbacbada561ea5014da947d | src/app/leaflet-wms-layer/leaflet-wms-layer.component.ts | src/app/leaflet-wms-layer/leaflet-wms-layer.component.ts | /*!
* Leaflet WMS Layer Component
*
* Copyright(c) Exequiel Ceasar Navarrete <[email protected]>
* Licensed under MIT
*/
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { LeafletMapService } from '../leaflet-map.service';
import { WMS } from 'leaflet';
@Component({
selector: 'app-leaflet-wms-layer',
templateUrl: './leaflet-wms-layer.component.html',
styleUrls: ['./leaflet-wms-layer.component.sass']
})
export class LeafletWmsLayerComponent implements OnInit, AfterViewInit {
public layer: WMS;
constructor(private _mapService: LeafletMapService) { }
ngOnInit() {
let workspace = 'sarai-latest';
let url = `http://202.92.144.40:8080/geoserver/${workspace}/wms?tiled=true`;
let leafletApi = (L as any);
// create the WMS tile layer
this.layer = leafletApi.tileLayer.wms(url, {
layers: workspace + ':rice_merged',
format: 'image/png',
transparent: true,
maxZoom: 10,
crs: leafletApi.CRS.EPSG900913,
zIndex: 1000,
attribution: `Crop data © 2016
<a href="http://www.pcaarrd.dost.gov.ph/" target="_blank">PCAARRD</a> and
<a href="http://uplb.edu.ph/" target="_blank">University of the Philippines Los Banos</a>`
});
}
ngAfterViewInit() {
this._mapService.addSingleWMSLayer(this.layer);
}
}
| /*!
* Leaflet WMS Layer Component
*
* Copyright(c) Exequiel Ceasar Navarrete <[email protected]>
* Licensed under MIT
*/
import { Component, OnInit, Input } from '@angular/core';
import { LeafletMapService } from '../leaflet-map.service';
import { WMS, WMSOptions } from 'leaflet';
@Component({
selector: 'app-leaflet-wms-layer',
templateUrl: './leaflet-wms-layer.component.html',
styleUrls: ['./leaflet-wms-layer.component.sass']
})
export class LeafletWmsLayerComponent implements OnInit {
public layer: WMS;
@Input() url: string;
@Input() layerOptions: WMSOptions;
constructor(private _mapService: LeafletMapService) {}
ngOnInit() {
if (typeof this.url === 'undefined') {
throw new Error('WMS Tile URL should be provided.');
}
if (typeof this.layerOptions === 'undefined') {
throw new Error('WMS Option should be provided.');
}
this._mapService
.addWMSLayer(this.url, this.layerOptions)
.then((layer: WMS) => {
this.layer = layer;
console.log(layer);
})
;
}
}
| Implement the new interface for adding WMS layer | Implement the new interface for adding WMS layer
| TypeScript | mit | ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2 | ---
+++
@@ -5,42 +5,40 @@
* Licensed under MIT
*/
-import { Component, OnInit, AfterViewInit } from '@angular/core';
+import { Component, OnInit, Input } from '@angular/core';
import { LeafletMapService } from '../leaflet-map.service';
-import { WMS } from 'leaflet';
+import { WMS, WMSOptions } from 'leaflet';
@Component({
selector: 'app-leaflet-wms-layer',
templateUrl: './leaflet-wms-layer.component.html',
styleUrls: ['./leaflet-wms-layer.component.sass']
})
-export class LeafletWmsLayerComponent implements OnInit, AfterViewInit {
+export class LeafletWmsLayerComponent implements OnInit {
public layer: WMS;
- constructor(private _mapService: LeafletMapService) { }
+ @Input() url: string;
+ @Input() layerOptions: WMSOptions;
+
+ constructor(private _mapService: LeafletMapService) {}
ngOnInit() {
- let workspace = 'sarai-latest';
- let url = `http://202.92.144.40:8080/geoserver/${workspace}/wms?tiled=true`;
+ if (typeof this.url === 'undefined') {
+ throw new Error('WMS Tile URL should be provided.');
+ }
- let leafletApi = (L as any);
+ if (typeof this.layerOptions === 'undefined') {
+ throw new Error('WMS Option should be provided.');
+ }
- // create the WMS tile layer
- this.layer = leafletApi.tileLayer.wms(url, {
- layers: workspace + ':rice_merged',
- format: 'image/png',
- transparent: true,
- maxZoom: 10,
- crs: leafletApi.CRS.EPSG900913,
- zIndex: 1000,
- attribution: `Crop data © 2016
- <a href="http://www.pcaarrd.dost.gov.ph/" target="_blank">PCAARRD</a> and
- <a href="http://uplb.edu.ph/" target="_blank">University of the Philippines Los Banos</a>`
- });
- }
+ this._mapService
+ .addWMSLayer(this.url, this.layerOptions)
+ .then((layer: WMS) => {
+ this.layer = layer;
- ngAfterViewInit() {
- this._mapService.addSingleWMSLayer(this.layer);
+ console.log(layer);
+ })
+ ;
}
} |
6a6203261cb45ac3f8f1c63ea0a1d6078ebe96b8 | packages/components/components/version/ChangelogModal.tsx | packages/components/components/version/ChangelogModal.tsx | import React, { useState } from 'react';
import { c } from 'ttag';
import markdownit from 'markdown-it';
import { FormModal } from '../modal';
import './ChangeLogModal.scss';
import { getAppVersion } from '../../helpers';
const md = markdownit('default', {
breaks: true,
linkify: true,
});
interface Props {
changelog?: string;
}
const ChangelogModal = ({ changelog = '', ...rest }: Props) => {
const [html] = useState(() => {
const modifiedChangelog = changelog.replace(/\[(\d+\.\d+\.\d+[^\]]*)]/g, (match, capture) => {
return `[${getAppVersion(capture)}]`;
});
return {
__html: md.render(modifiedChangelog),
};
});
return (
<FormModal title={c('Title').t`Release notes`} close={c('Action').t`Close`} submit={null} {...rest}>
<div className="modal-content-inner-changelog" dangerouslySetInnerHTML={html} lang="en" />
</FormModal>
);
};
export default ChangelogModal;
| import React, { useState } from 'react';
import { c } from 'ttag';
import markdownit from 'markdown-it';
import { FormModal } from '../modal';
import './ChangeLogModal.scss';
import { getAppVersion } from '../../helpers';
const md = markdownit('default', {
breaks: true,
linkify: true,
});
const defaultRender =
md.renderer.rules.link_open ||
function render(tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options);
};
md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
tokens[idx].attrPush(['target', '_blank']);
return defaultRender(tokens, idx, options, env, self);
};
interface Props {
changelog?: string;
}
const ChangelogModal = ({ changelog = '', ...rest }: Props) => {
const [html] = useState(() => {
const modifiedChangelog = changelog.replace(/\[(\d+\.\d+\.\d+[^\]]*)]/g, (match, capture) => {
return `[${getAppVersion(capture)}]`;
});
return {
__html: md.render(modifiedChangelog),
};
});
return (
<FormModal title={c('Title').t`Release notes`} close={c('Action').t`Close`} submit={null} {...rest}>
<div className="modal-content-inner-changelog" dangerouslySetInnerHTML={html} lang="en" />
</FormModal>
);
};
export default ChangelogModal;
| Add blank target to changelog links | Add blank target to changelog links
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -10,6 +10,17 @@
breaks: true,
linkify: true,
});
+
+const defaultRender =
+ md.renderer.rules.link_open ||
+ function render(tokens, idx, options, env, self) {
+ return self.renderToken(tokens, idx, options);
+ };
+
+md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
+ tokens[idx].attrPush(['target', '_blank']);
+ return defaultRender(tokens, idx, options, env, self);
+};
interface Props {
changelog?: string; |
19bb8b425ba4285a6fa663e716ae7bd0f651d999 | src/Components/Display/SvgIcon/index.tsx | src/Components/Display/SvgIcon/index.tsx | import * as React from 'react';
import { SvgProps } from './types';
import styled from '../../../Common/theming/themedComponents';
import Icons from './icons';
const SvgIconWrapper = styled.div`
float: left;
display: inline;
width: ${ props => props.width}px ;
height:${ props => props.height}px ;
margin: 4px;
svg {
fill:${ props => props.color} ;
}
`
export type Props = SvgProps & React.HTMLProps<typeof SvgIcon>;
export default function SvgIcon({
children,
viewBox,
iconName,
color,
...others,
}: Props): JSX.Element {
const height = others.height || 24 ;
const width = others.height || 24 ;
if(iconName) {
return (
<SvgIconWrapper color={color} height={height} width={width}
//{...others}
dangerouslySetInnerHTML={{__html: Icons[iconName]}}
></SvgIconWrapper>
);
} else {
const defaultViewBox = `0 0 ${width} ${height}` ;
const viewBoxProps = viewBox || defaultViewBox;
return (
<svg
//{...others}
fill={color}
viewBox={viewBoxProps}>
{children}
</svg>);
}
}
| import * as React from 'react';
import { SvgProps } from './types';
import styled from '../../../Common/theming/themedComponents';
import Icons from './icons';
const SvgIconWrapper = styled.div`
float: left;
display: inline;
width: ${ props => props.width}px ;
height:${ props => props.height}px ;
margin: 4px;
svg {
fill:${ props => props.color} ;
}
`
export type Props = SvgProps & React.HTMLProps<typeof SvgIcon>;
export default function SvgIcon({
children,
viewBox,
iconName,
className,
color,
...others,
}: Props): JSX.Element {
const height = others.height || 24 ;
const width = others.height || 24 ;
if(iconName) {
return (
<SvgIconWrapper className={className} color={color} height={height} width={width}
//{...others}
dangerouslySetInnerHTML={{__html: Icons[iconName]}}
></SvgIconWrapper>
);
} else {
const defaultViewBox = `0 0 ${width} ${height}` ;
const viewBoxProps = viewBox || defaultViewBox;
return (
<svg
//{...others}
fill={color}
viewBox={viewBoxProps}>
{children}
</svg>);
}
}
| Allow to set a classname to a SVG icon | Allow to set a classname to a SVG icon
| TypeScript | mit | Up-Group/react-controls,Up-Group/react-controls,Up-Group/react-controls | ---
+++
@@ -19,6 +19,7 @@
children,
viewBox,
iconName,
+ className,
color,
...others,
}: Props): JSX.Element {
@@ -28,7 +29,7 @@
if(iconName) {
return (
- <SvgIconWrapper color={color} height={height} width={width}
+ <SvgIconWrapper className={className} color={color} height={height} width={width}
//{...others}
dangerouslySetInnerHTML={{__html: Icons[iconName]}}
></SvgIconWrapper> |
f5af6a92935bd77e13b099d14c584912dcd1b4de | src/frontend/components/Layout/index.tsx | src/frontend/components/Layout/index.tsx | import * as React from 'react'
import {urls} from '~/frontend/routes'
interface ILayout {
children?: Element
displayName: string
username: string
}
const NavBtn = ({url, title, name}: {url: string; title: string; name: string}) =>
<a href={url} id={`nav--${name}`}>
<button className={`pt-button pt-minimal pt-icon-${name}`}>
{title}
</button>
</a>
const Brand = () =>
<div className="pt-navbar-group pt-align-left">
<div className="pt-navbar-heading">
Clarity
</div>
</div>
const LayoutComponent = ({displayName, username, children}: ILayout) =>
<div>
<nav style={{display: 'flow-root', height: '48px', marginBottom: '25px'}}>
<Brand />
<div className="pt-navbar-group pt-align-right">
{displayName &&
<div>
<NavBtn title="New post" url={urls.newPost} name="plus" />
<NavBtn title={displayName} url={urls.user(username)} name="user" />
<span className="pt-navbar-divider" />
</div>}
{displayName
? <NavBtn title="Sign out" url={urls.signout} name="log-out" />
: <NavBtn title="Sign in" url={urls.fbSignin} name="log-in" />}
</div>
</nav>
<main>
{children}
</main>
</div>
export default LayoutComponent
| import * as React from 'react'
import {urls} from '~/frontend/routes'
interface ILayout {
children?: Element
displayName: string
username: string
}
const NavBtn = ({url, title, name}: {url: string; title: string; name: string}) =>
<a href={url} id={`nav--${name}`}>
<button className={`pt-button pt-minimal pt-icon-${name}`}>
{title}
</button>
</a>
const LayoutComponent = ({displayName, username, children}: ILayout) =>
<div>
<nav style={{display: 'flow-root', height: '48px', marginBottom: '25px'}}>
{displayName &&
<div className="pt-navbar-group pt-align-right">
<div>
<NavBtn title="New post" url={urls.newPost} name="plus" />
<NavBtn title={displayName} url={urls.user(username)} name="user" />
<span className="pt-navbar-divider" />
</div>
<NavBtn title="Sign out" url={urls.signout} name="log-out" />
</div>}
</nav>
<main style={{paddingBottom: '150px'}}>
{children}
</main>
</div>
export default LayoutComponent
| Remove the app-oriented nav bar when not signed in | Remove the app-oriented nav bar when not signed in
| TypeScript | mit | devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity | ---
+++
@@ -15,31 +15,21 @@
</button>
</a>
-const Brand = () =>
- <div className="pt-navbar-group pt-align-left">
- <div className="pt-navbar-heading">
- Clarity
- </div>
- </div>
-
const LayoutComponent = ({displayName, username, children}: ILayout) =>
<div>
<nav style={{display: 'flow-root', height: '48px', marginBottom: '25px'}}>
- <Brand />
- <div className="pt-navbar-group pt-align-right">
- {displayName &&
+ {displayName &&
+ <div className="pt-navbar-group pt-align-right">
<div>
<NavBtn title="New post" url={urls.newPost} name="plus" />
<NavBtn title={displayName} url={urls.user(username)} name="user" />
<span className="pt-navbar-divider" />
- </div>}
- {displayName
- ? <NavBtn title="Sign out" url={urls.signout} name="log-out" />
- : <NavBtn title="Sign in" url={urls.fbSignin} name="log-in" />}
- </div>
+ </div>
+ <NavBtn title="Sign out" url={urls.signout} name="log-out" />
+ </div>}
</nav>
- <main>
+ <main style={{paddingBottom: '150px'}}>
{children}
</main>
</div> |
61f48b658e852f1027dd3f8f9bff17ce408fab27 | config/libs/ruter-js/src/Controllers/PlaceAPI.ts | config/libs/ruter-js/src/Controllers/PlaceAPI.ts | import * as Api from '../Utils/ApiConnector';
export function findPlace(name: string): Promise<PlaceInterface> {
return new Promise<PlaceInterface>((resolve, reject) => {
// Perform some basic validation
if (name.length === 0) {
reject(new Error('The name of the place must not be empty'));
}
//TODO Query the Ruter API to search the place
let place = {
ID: 123,
Name: "Jernbanetorget",
District: "Oslo",
Zone: "1",
PlaceType: "Stop"
};
resolve(place);
});
}
| import * as Api from '../Utils/ApiConnector';
/**
* Queries the rest API for places matching the provided name.
*
* @param name Name of the place to search for.
* @param placeType (Optional) If provided, only places of this type will be returned.
* @returns {Promise<PlaceInterface[]>} Promise that resolves once the list of places has been retrieved from the API.
*/
export function findPlace(name: string, placeType: string): Promise<PlaceInterface[]> {
return new Promise<PlaceInterface[]>((resolve, reject) => {
// Perform some basic validation
if (name.length === 0) {
reject(new Error('The name of the place must not be empty'));
}
// Query the Ruter API to search the place and get a list of results
Api.get('/Place/GetPlaces/' + name)
.then((response: Object) => {
let places = parseGetPlacesResponse(response);
if (placeType) {
places = places.filter((item:PlaceInterface) => item.PlaceType === placeType);
}
resolve(places)
})
.catch((error: string) => reject(error));
});
}
/**
* Helper function to convert the objects coming from the response into objects that implement PlaceInterface.
*
* @param response The response obtained from the API (/Place/GetPlaces).
* @returns {PlaceInterface[]} Array of places contained in the response.
*/
function parseGetPlacesResponse(response: Object): PlaceInterface[] {
let places: PlaceInterface[] = [];
Object.keys(response).forEach((key: string, index: number) => {
let newPlace: PlaceInterface = (<any> response)[key];
places.push(newPlace);
});
return places;
}
| Make the actual API call to find places by name | Make the actual API call to find places by name
| TypeScript | mit | hector-gomez/ruter-pebble,hector-gomez/ruter-pebble,hector-gomez/ruter-pebble,hector-gomez/ruter-pebble,hector-gomez/ruter-pebble,hector-gomez/ruter-pebble | ---
+++
@@ -1,20 +1,45 @@
import * as Api from '../Utils/ApiConnector';
-export function findPlace(name: string): Promise<PlaceInterface> {
- return new Promise<PlaceInterface>((resolve, reject) => {
+/**
+ * Queries the rest API for places matching the provided name.
+ *
+ * @param name Name of the place to search for.
+ * @param placeType (Optional) If provided, only places of this type will be returned.
+ * @returns {Promise<PlaceInterface[]>} Promise that resolves once the list of places has been retrieved from the API.
+ */
+export function findPlace(name: string, placeType: string): Promise<PlaceInterface[]> {
+ return new Promise<PlaceInterface[]>((resolve, reject) => {
// Perform some basic validation
if (name.length === 0) {
reject(new Error('The name of the place must not be empty'));
}
- //TODO Query the Ruter API to search the place
- let place = {
- ID: 123,
- Name: "Jernbanetorget",
- District: "Oslo",
- Zone: "1",
- PlaceType: "Stop"
- };
- resolve(place);
+ // Query the Ruter API to search the place and get a list of results
+ Api.get('/Place/GetPlaces/' + name)
+ .then((response: Object) => {
+ let places = parseGetPlacesResponse(response);
+ if (placeType) {
+ places = places.filter((item:PlaceInterface) => item.PlaceType === placeType);
+ }
+ resolve(places)
+ })
+ .catch((error: string) => reject(error));
});
}
+
+/**
+ * Helper function to convert the objects coming from the response into objects that implement PlaceInterface.
+ *
+ * @param response The response obtained from the API (/Place/GetPlaces).
+ * @returns {PlaceInterface[]} Array of places contained in the response.
+ */
+function parseGetPlacesResponse(response: Object): PlaceInterface[] {
+ let places: PlaceInterface[] = [];
+
+ Object.keys(response).forEach((key: string, index: number) => {
+ let newPlace: PlaceInterface = (<any> response)[key];
+ places.push(newPlace);
+ });
+
+ return places;
+} |
7bff4dace1bdd2ff91a6e5db060ae4cda8a8ae84 | grid-packages/ag-grid-docs/src/example-runner/lib/viewport.ts | grid-packages/ag-grid-docs/src/example-runner/lib/viewport.ts | import * as jQuery from 'jquery';
const win = jQuery(window);
const contentEl = document.getElementsByClassName('page-content')[0];
function getCurrentViewPort() {
const viewport = {
top : win.scrollTop(),
left : win.scrollLeft(),
right: NaN,
bottom: NaN
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
return viewport;
}
function getRect(element) {
const bounds = element.offset();
bounds.right = bounds.left + element.outerWidth();
bounds.bottom = bounds.top + element.outerHeight();
return bounds;
}
export function whenInViewPort(element, callback) {
function comparePosition() {
const viewPort = getCurrentViewPort();
const box = getRect(element);
if (viewPort.bottom >= box.top) {
contentEl.removeEventListener('scroll', comparePosition);
callback();
// window.setTimeout(callback, 2000);
}
}
comparePosition();
contentEl.addEventListener('scroll', comparePosition);
}
export function trackIfInViewPort(element, callback) {
function comparePosition() {
const viewPort = getCurrentViewPort();
const box = getRect(element);
var inViewPort = viewPort.bottom >= box.top && viewPort.top <= box.bottom;
callback(inViewPort);
}
comparePosition();
contentEl.addEventListener('scroll', comparePosition);
}
| import * as jQuery from 'jquery';
const win = jQuery(window);
const contentEl = document.getElementsByClassName('page-content')[0];
function getCurrentViewPort() {
const viewport = {
top : win.scrollTop(),
left : win.scrollLeft(),
right: NaN,
bottom: NaN
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
return viewport;
}
function getRect(element) {
const bounds = element.offset();
bounds.right = bounds.left + element.outerWidth();
bounds.bottom = bounds.top + element.outerHeight();
return bounds;
}
export function whenInViewPort(element, callback) {
function comparePosition() {
const viewPort = getCurrentViewPort();
const box = getRect(element);
if (viewPort.bottom >= box.top) {
contentEl.removeEventListener('scroll', comparePosition);
callback();
// window.setTimeout(callback, 2000);
}
}
comparePosition();
contentEl.addEventListener('scroll', comparePosition);
}
export function trackIfInViewPort(element, callback) {
function comparePosition() {
const viewPort = getCurrentViewPort();
const box = getRect(element);
var inViewPort = viewPort.bottom >= box.top && viewPort.top <= box.bottom;
callback(inViewPort);
}
comparePosition();
contentEl.addEventListener('scroll', comparePosition);
}
document.addEventListener('DOMContentLoaded', function () {
const link = document.querySelector('a[href="' + location.hash + '"]');
if (link && link.scrollIntoView) {
link.scrollIntoView();
}
});
| Return to the previous scroll position on page reload. | Return to the previous scroll position on page reload.
| TypeScript | mit | ceolter/angular-grid,ceolter/ag-grid,ceolter/ag-grid,ceolter/angular-grid | ---
+++
@@ -51,3 +51,10 @@
comparePosition();
contentEl.addEventListener('scroll', comparePosition);
}
+
+document.addEventListener('DOMContentLoaded', function () {
+ const link = document.querySelector('a[href="' + location.hash + '"]');
+ if (link && link.scrollIntoView) {
+ link.scrollIntoView();
+ }
+}); |
cf27fcdc938b7054aecf21061f6ac11ef7df2a00 | e2e/app.e2e-spec.ts | e2e/app.e2e-spec.ts | import { Ng2CiAppPage } from './app.po';
describe('ng2-ci-app App', function () {
let page: Ng2CiAppPage;
beforeEach(() => {
page = new Ng2CiAppPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('NG Friends!');
});
it('should display some ng friends', () => {
page.navigateTo();
expect(page.getFriends()).toEqual(6);
});
});
| import { Ng2CiAppPage } from './app.po';
describe('ng2-ci-app App', function () {
let page: Ng2CiAppPage;
beforeEach(() => {
page = new Ng2CiAppPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('NG Friends!');
});
it('should display some ng friends', () => {
page.navigateTo();
expect(page.getFriends()).toEqual(7);
});
});
| Fix e2e tests for Uri | test(e2e): Fix e2e tests for Uri
Fix e2e tests for Uri
| TypeScript | mit | Elecash/ng2-ci-app,Elecash/ng2-ci-app,Elecash/ng2-ci-app,Elecash/ng2-ci-app | ---
+++
@@ -14,6 +14,6 @@
it('should display some ng friends', () => {
page.navigateTo();
- expect(page.getFriends()).toEqual(6);
+ expect(page.getFriends()).toEqual(7);
});
}); |
35216fde00419bfabae2421c3cadd943945ea86c | source/workerlib.ts | source/workerlib.ts | export { SurfaceWorker } from "./workers/target/surfaceworker";
export { WorkerEvent } from "./workers/workerevent";
export { Config } from "./app/config"; | export { SurfaceWorker } from "./workers/target/surfaceworker";
export { ParticlesWorker } from "./workers/target/particlesworker";
export { WorkerEvent } from "./workers/workerevent";
export { Config } from "./app/config"; | Add particles worker code to worker lib | Add particles worker code to worker lib
| TypeScript | apache-2.0 | Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d | ---
+++
@@ -1,3 +1,4 @@
export { SurfaceWorker } from "./workers/target/surfaceworker";
+export { ParticlesWorker } from "./workers/target/particlesworker";
export { WorkerEvent } from "./workers/workerevent";
export { Config } from "./app/config"; |
c5b004166d75672ea86e1d0731b511716fc10caf | src/file/xml-components/xml-component.ts | src/file/xml-components/xml-component.ts | import { BaseXmlComponent } from "./base";
import { IXmlableObject } from "./xmlable-object";
export { BaseXmlComponent };
export abstract class XmlComponent extends BaseXmlComponent {
protected root: Array<BaseXmlComponent | string>;
constructor(rootKey: string, initContent?: XmlComponent) {
super(rootKey);
this.root = initContent ? initContent.root : new Array<BaseXmlComponent>();
}
public prepForXml(): IXmlableObject {
const children = this.root
.filter((c) => {
if (c instanceof BaseXmlComponent) {
return !c.IsDeleted;
}
return true;
})
.map((comp) => {
if (comp instanceof BaseXmlComponent) {
return comp.prepForXml();
}
return comp;
})
.filter((comp) => comp); // Exclude null, undefined, and empty strings
return {
[this.rootKey]: children,
};
}
// TODO: Unused method
public addChildElement(child: XmlComponent | string): XmlComponent {
this.root.push(child);
return this;
}
public delete(): void {
this.deleted = true;
}
}
| import { BaseXmlComponent } from "./base";
import { IXmlableObject } from "./xmlable-object";
export { BaseXmlComponent };
export abstract class XmlComponent extends BaseXmlComponent {
protected root: Array<BaseXmlComponent | string>;
constructor(rootKey: string, initContent?: XmlComponent) {
super(rootKey);
this.root = initContent ? initContent.root : new Array<BaseXmlComponent>();
}
public prepForXml(): IXmlableObject {
const children = this.root
.filter((c) => {
if (c instanceof BaseXmlComponent) {
return !c.IsDeleted;
}
return true;
})
.map((comp) => {
if (comp instanceof BaseXmlComponent) {
return comp.prepForXml();
}
return comp;
})
.filter((comp) => comp !== null); // Exclude null, undefined, and empty strings
return {
[this.rootKey]: children,
};
}
// TODO: Unused method
public addChildElement(child: XmlComponent | string): XmlComponent {
this.root.push(child);
return this;
}
public delete(): void {
this.deleted = true;
}
}
| Add back comp null check | Add back comp null check
| TypeScript | mit | dolanmiu/docx,dolanmiu/docx,dolanmiu/docx | ---
+++
@@ -24,7 +24,7 @@
}
return comp;
})
- .filter((comp) => comp); // Exclude null, undefined, and empty strings
+ .filter((comp) => comp !== null); // Exclude null, undefined, and empty strings
return {
[this.rootKey]: children,
}; |
86a7405ebf6300f9f0538abfedf1bb249e150796 | src/utils/loadAndBundleSpec.ts | src/utils/loadAndBundleSpec.ts | import * as JsonSchemaRefParser from 'json-schema-ref-parser';
import { convertObj } from 'swagger2openapi';
import { OpenAPISpec } from '../types';
export async function loadAndBundleSpec(specUrlOrObject: object | string): Promise<OpenAPISpec> {
const _parser = new JsonSchemaRefParser();
const spec = await _parser.bundle(specUrlOrObject, {
resolve: { http: { withCredentials: false } },
} as object);
if (spec.swagger !== undefined) {
return convertSwagger2OpenAPI(spec);
} else {
return spec;
}
}
export function convertSwagger2OpenAPI(spec: any): Promise<OpenAPISpec> {
console.warn('[ReDoc Compatibility mode]: Converting OpenAPI 2.0 to OpenAPI 3.0');
return new Promise<OpenAPISpec>((resolve, reject) =>
convertObj(spec, {}, (err, res) => {
// TODO: log any warnings
if (err) {
return reject(err);
}
resolve(res && (res.openapi as any));
}),
);
}
| import * as JsonSchemaRefParser from 'json-schema-ref-parser';
import { convertObj } from 'swagger2openapi';
import { OpenAPISpec } from '../types';
export async function loadAndBundleSpec(specUrlOrObject: object | string): Promise<OpenAPISpec> {
const _parser = new JsonSchemaRefParser();
const spec = await _parser.bundle(specUrlOrObject, {
resolve: { http: { withCredentials: false } },
} as object);
if (spec.swagger !== undefined) {
return convertSwagger2OpenAPI(spec);
} else {
return spec;
}
}
export function convertSwagger2OpenAPI(spec: any): Promise<OpenAPISpec> {
console.warn('[ReDoc Compatibility mode]: Converting OpenAPI 2.0 to OpenAPI 3.0');
return new Promise<OpenAPISpec>((resolve, reject) =>
convertObj(spec, { patch: true, warnOnly: true }, (err, res) => {
// TODO: log any warnings
if (err) {
return reject(err);
}
resolve(res && (res.openapi as any));
}),
);
}
| Make conversion process more robust | Make conversion process more robust
| TypeScript | mit | Rebilly/ReDoc,Rebilly/ReDoc,Rebilly/ReDoc,Rebilly/ReDoc | ---
+++
@@ -18,7 +18,7 @@
export function convertSwagger2OpenAPI(spec: any): Promise<OpenAPISpec> {
console.warn('[ReDoc Compatibility mode]: Converting OpenAPI 2.0 to OpenAPI 3.0');
return new Promise<OpenAPISpec>((resolve, reject) =>
- convertObj(spec, {}, (err, res) => {
+ convertObj(spec, { patch: true, warnOnly: true }, (err, res) => {
// TODO: log any warnings
if (err) {
return reject(err); |
2501af9c282bc63eb244ae41c2195fbde3bacbff | packages/sk-marked/src/index.ts | packages/sk-marked/src/index.ts | import Element from '@skatejs/element';
import marked from 'marked';
function format(src) {
src = src || '';
// Remove leading newlines.
src = src.split('\n');
// Get the initial indent so we can remove it from subsequent lines.
const indent = src[0] ? src[0].match(/^\s*/)[0].length : 0;
// Format indentation.
src = src.map(s => s.substring(indent) || '');
// Re-instate newline formatting.
return src.join('\n');
}
export default class extends Element {
static props = {
css: String,
renderers: Object,
src: String
};
css: string = '';
renderers: {} = {};
src: string = '';
render() {
const { css, renderers, src } = this;
const renderer = new marked.Renderer();
Object.assign(renderer, renderers);
return `
<style>${css}></style>
${marked(format(src), { renderer })}
`;
}
}
| import Element from '@skatejs/element';
import marked from 'marked';
function format(src) {
src = src || '';
// Sanitise quotes.
src = src.replace(/'/g, ''');
src = src.replace(/"/g, '"');
// Ensure windows doesn't screw anything up.
src = src.replace(/\r/g, '');
// Remove leading newlines.
src = src.split('\n');
// Get the initial indent so we can remove it from subsequent lines.
const indent = src[0] ? src[0].match(/^\s*/)[0].length : 0;
// Format indentation.
src = src.map(s => s.substring(indent) || '');
// Re-instate newline formatting.
return src.join('\n');
}
export default class extends Element {
static props = {
css: String,
renderers: Object,
src: String
};
css: string = '';
renderers: {} = {};
src: string = '';
render() {
const { css, renderers, src } = this;
const renderer = new marked.Renderer();
Object.assign(renderer, renderers);
return `
<style>${css}></style>
${marked(format(src), { renderer })}
`;
}
}
| Fix quotes and ensure carriage returns don't screw up the formatting. | Fix quotes and ensure carriage returns don't screw up the formatting.
| TypeScript | mit | skatejs/skatejs,skatejs/skatejs,skatejs/skatejs | ---
+++
@@ -3,6 +3,13 @@
function format(src) {
src = src || '';
+
+ // Sanitise quotes.
+ src = src.replace(/'/g, ''');
+ src = src.replace(/"/g, '"');
+
+ // Ensure windows doesn't screw anything up.
+ src = src.replace(/\r/g, '');
// Remove leading newlines.
src = src.split('\n'); |
26d5ba14c0000443ac6237037f270ee597296b88 | src/components/cli/migrate-init.ts | src/components/cli/migrate-init.ts | import { addProcess, storeProcessTable, processTable } from "../kernel/kernel";
import Process = require("../processes/process");
import InitProcess = require("../processes/init");
export = function (___: any) {
let p = new InitProcess(0, 0);
let pidZero = processTable[0];
if (!pidZero) {
addProcess(p);
p.pid = 0;
storeProcessTable();
} else {
addProcess(pidZero);
let newPid = pidZero.pid;
let processList: Process[] = _.values(processTable) as Process[];
for (let process of processList) {
if (process.parentPID === 0) {
process.parentPID = newPid;
}
}
delete (processTable[0]);
addProcess(p);
storeProcessTable();
}
};
| import { addProcess, storeProcessTable, processTable } from "../kernel/kernel";
import Process = require("../processes/process");
import InitProcess = require("../processes/init");
export = function (___: any) {
let p = new InitProcess(0, 0);
let pidZero = processTable[0];
if (!pidZero) {
addProcess(p);
p.pid = 0;
storeProcessTable();
} else {
addProcess(pidZero);
let newPid = pidZero.pid;
let processList: Process[] = _.values(processTable) as Process[];
for (let process of processList) {
if (process.parentPID === 0) {
process.parentPID = newPid;
}
}
pidZero.parentPID = 0;
Memory.processMemory[newPid] = _.cloneDeep(Memory.processMemory[0]);
delete (processTable[0]);
addProcess(p);
p.pid = 0;
storeProcessTable();
}
};
| Fix bug in init process migration | Fix bug in init process migration
| TypeScript | mit | NhanHo/ScreepsOS,NhanHo/ScreepsOS | ---
+++
@@ -17,8 +17,11 @@
process.parentPID = newPid;
}
}
+ pidZero.parentPID = 0;
+ Memory.processMemory[newPid] = _.cloneDeep(Memory.processMemory[0]);
delete (processTable[0]);
addProcess(p);
+ p.pid = 0;
storeProcessTable();
}
}; |
3858e0698c0e428c8318e8dfb412ca47e6b6081c | src/ts/user-config/default-features.ts | src/ts/user-config/default-features.ts | import { FeatureOptions } from "./feature-options";
export const defaultFeatures: FeatureOptions = {
calculator: true,
commandLine: true,
customCommands: true,
email: true,
environmentVariables: false,
fileBrowser: false,
fileSearch: true,
operatingSystemCommands: false,
operatingSystemSettings: false,
programs: true,
shortcuts: true,
ueliCommands: true,
webSearch: true,
webUrl: true,
};
| import { FeatureOptions } from "./feature-options";
export const defaultFeatures: FeatureOptions = {
calculator: true,
commandLine: true,
customCommands: true,
email: true,
environmentVariables: false,
fileBrowser: true,
fileSearch: true,
operatingSystemCommands: true,
operatingSystemSettings: false,
programs: true,
shortcuts: true,
ueliCommands: true,
webSearch: true,
webUrl: true,
};
| Enable file browser and operating system command features by default | Enable file browser and operating system command features by default
| TypeScript | mit | oliverschwendener/electronizr,oliverschwendener/electronizr | ---
+++
@@ -6,9 +6,9 @@
customCommands: true,
email: true,
environmentVariables: false,
- fileBrowser: false,
+ fileBrowser: true,
fileSearch: true,
- operatingSystemCommands: false,
+ operatingSystemCommands: true,
operatingSystemSettings: false,
programs: true,
shortcuts: true, |
394f8d4f057db1b82a9926f603d3bee62a41f07a | index.ts | index.ts | import { NG2_BOOLEAN_PIPES } from './boolean';
import { NG2_MATH_PIPES } from './math';
import { NG2_ARRAY_PIPES } from './array';
import { NG2_STRING_PIPES } from './string';
export * from './boolean';
export * from './math';
export * from './array';
export * from './string';
export const NG2_PIPES = [
...NG2_BOOLEAN_PIPES,
...NG2_MATH_PIPES,
...NG2_ARRAY_PIPES,
...NG2_STRING_PIPES
]; | /// <reference path="node_modules/angular2/typings/browser.d.ts" />
import { NG2_BOOLEAN_PIPES } from './boolean';
import { NG2_MATH_PIPES } from './math';
import { NG2_ARRAY_PIPES } from './array';
import { NG2_STRING_PIPES } from './string';
export * from './boolean';
export * from './math';
export * from './array';
export * from './string';
export const NG2_PIPES = [
...NG2_BOOLEAN_PIPES,
...NG2_MATH_PIPES,
...NG2_ARRAY_PIPES,
...NG2_STRING_PIPES
]; | Add reference to angular type definition | Add reference to angular type definition
| TypeScript | mit | fknop/angular-pipes,fknop/angular-pipes | ---
+++
@@ -1,3 +1,5 @@
+/// <reference path="node_modules/angular2/typings/browser.d.ts" />
+
import { NG2_BOOLEAN_PIPES } from './boolean';
import { NG2_MATH_PIPES } from './math';
import { NG2_ARRAY_PIPES } from './array'; |
0b5721bdf4ebb9e1199173adccf9457421854e3c | applications/mail/src/app/components/list/ItemCheckbox.tsx | applications/mail/src/app/components/list/ItemCheckbox.tsx | import React, { ReactElement, ChangeEvent } from 'react';
import { Icon, classnames } from 'react-components';
interface Props {
children: ReactElement | string;
className: string;
checked: boolean;
onChange: (event: ChangeEvent) => void;
}
const ItemCheckbox = ({ children, className, ...rest }: Props) => {
return (
<label className={classnames(['relative stop-propagation', className])}>
<input type="checkbox" className="item-checkbox inner-ratio-container cursor-pointer m0" {...rest} />
<span className="item-icon flex-item-noshrink rounded50 bg-white inline-flex">
<span className="mauto item-abbr">{children}</span>
<span className="item-icon-fakecheck color-white mauto">
<Icon name="on" />
</span>
</span>
</label>
);
};
export default ItemCheckbox;
| import React, { ReactElement, ChangeEvent } from 'react';
import { Icon, classnames } from 'react-components';
interface Props {
children: ReactElement | string;
className: string;
checked: boolean;
onChange: (event: ChangeEvent) => void;
}
const ItemCheckbox = ({ children, className, ...rest }: Props) => {
return (
<label className={classnames(['relative stop-propagation', className])}>
<input type="checkbox" className="item-checkbox inner-ratio-container cursor-pointer m0" {...rest} />
<span className="item-icon flex-item-noshrink relative rounded50 inline-flex">
<span className="mauto item-abbr">{children}</span>
<span className="item-icon-fakecheck mauto">
<Icon name="on" className="item-icon-fakecheck-icon" />
</span>
</span>
</label>
);
};
export default ItemCheckbox;
| Fix [MAILWEB-757] hover state on list item | Fix [MAILWEB-757] hover state on list item
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -12,10 +12,10 @@
return (
<label className={classnames(['relative stop-propagation', className])}>
<input type="checkbox" className="item-checkbox inner-ratio-container cursor-pointer m0" {...rest} />
- <span className="item-icon flex-item-noshrink rounded50 bg-white inline-flex">
+ <span className="item-icon flex-item-noshrink relative rounded50 inline-flex">
<span className="mauto item-abbr">{children}</span>
- <span className="item-icon-fakecheck color-white mauto">
- <Icon name="on" />
+ <span className="item-icon-fakecheck mauto">
+ <Icon name="on" className="item-icon-fakecheck-icon" />
</span>
</span>
</label> |
221733e887b85b9335d393a58b0167735de3e5ce | src/presentation/theme/text.ts | src/presentation/theme/text.ts | export const text = {
fontFamily: "Source Serif Pro",
fontFallback: "serif"
};
| export const text = {
fontFamily: "Source Serif Pro",
fontFallback: "serif",
size: {
paragraph: "1.2rem"
}
};
| Add default size to theme | Add default size to theme
| TypeScript | mit | osdiab/osdiab.github.io,osdiab/osdiab.github.io,osdiab/osdiab.github.io,osdiab/osdiab.github.io | ---
+++
@@ -1,4 +1,7 @@
export const text = {
fontFamily: "Source Serif Pro",
- fontFallback: "serif"
+ fontFallback: "serif",
+ size: {
+ paragraph: "1.2rem"
+ }
}; |
f2a75dd4441094d1217cedacf1571a4cf934591d | app/services/MessageBroker.ts | app/services/MessageBroker.ts | import {EventEmitter, Injectable} from 'angular2/angular2';
import {IWeatherUpdate} from '../common/interfaces/WeatherInterfaces';
@Injectable()
export class MessageBroker {
io: SocketIOClientStatic;
socket: SocketIOClient.Socket;
weatherUpdates: EventEmitter<IWeatherUpdate>;
constructor() {
// Connect to the server
this.io = io;
this.socket = io.connect();
// Create publications
this.weatherUpdates = new EventEmitter<IWeatherUpdate>();
// Set up publication updating
this.socket.on('weatherUpdate', (update:IWeatherUpdate) => {
this.weatherUpdates.next(update);
});
}
getWeatherUpdates() : EventEmitter<IWeatherUpdate> {
return this.weatherUpdates;
}
}
| import {EventEmitter, Injectable} from 'angular2/angular2';
import {IWeatherUpdate} from '../common/interfaces/WeatherInterfaces';
import {IAccident} from '../common/interfaces/TrafficInterfaces';
@Injectable()
export class MessageBroker {
io: SocketIOClientStatic;
socket: SocketIOClient.Socket;
weatherUpdates: EventEmitter<IWeatherUpdate>;
accidentUpdates: EventEmitter<IAccident>;
constructor() {
// Connect to the server
this.io = io;
this.socket = io.connect();
// Create publications
this.weatherUpdates = new EventEmitter<IWeatherUpdate>();
this.accidentUpdates = new EventEmitter<IAccident>();
// Set up publication updating
this.socket.on('weatherUpdate', (update:IWeatherUpdate) => {
this.weatherUpdates.next(update);
});
this.socket.on('accident', (accident:IAccident) => {
console.log(`Accident involving ${accident.vehiclesInvolved} vehicles in ${accident.state} at ${accident.time}.`);
this.accidentUpdates.next(accident);
});
}
getWeatherUpdates() : EventEmitter<IWeatherUpdate> {
return this.weatherUpdates;
}
}
| Update the message broker to publish accidents | Update the message broker to publish accidents
| TypeScript | mit | hpinsley/angular-mashup,hpinsley/angular-mashup,AngularShowcase/angular2-seed-example-mashup,hpinsley/angular-mashup,AngularShowcase/angular2-seed-example-mashup,AngularShowcase/angular2-seed-example-mashup | ---
+++
@@ -1,5 +1,6 @@
import {EventEmitter, Injectable} from 'angular2/angular2';
import {IWeatherUpdate} from '../common/interfaces/WeatherInterfaces';
+import {IAccident} from '../common/interfaces/TrafficInterfaces';
@Injectable()
export class MessageBroker {
@@ -7,6 +8,7 @@
io: SocketIOClientStatic;
socket: SocketIOClient.Socket;
weatherUpdates: EventEmitter<IWeatherUpdate>;
+ accidentUpdates: EventEmitter<IAccident>;
constructor() {
// Connect to the server
@@ -15,10 +17,16 @@
// Create publications
this.weatherUpdates = new EventEmitter<IWeatherUpdate>();
+ this.accidentUpdates = new EventEmitter<IAccident>();
// Set up publication updating
this.socket.on('weatherUpdate', (update:IWeatherUpdate) => {
this.weatherUpdates.next(update);
+ });
+
+ this.socket.on('accident', (accident:IAccident) => {
+ console.log(`Accident involving ${accident.vehiclesInvolved} vehicles in ${accident.state} at ${accident.time}.`);
+ this.accidentUpdates.next(accident);
});
}
|
568826be9d9ec8f6e9fc30725cd0516a42d3f6f1 | src/misc.ts | src/misc.ts | 'use strict';
import * as vsc from 'vscode';
export const D_MODE = { language: 'd', scheme: 'file' };
export function getRootPath() {
return vsc.workspace.workspaceFolders
? vsc.window.activeTextEditor
? vsc.workspace.getWorkspaceFolder(vsc.window.activeTextEditor.document.uri).uri.fsPath
: vsc.workspace.workspaceFolders[0].uri.fsPath
: null;
};
export function chooseRootPath() {
if (!vsc.workspace.workspaceFolders) {
return Promise.resolve<string>(null);
}
const stdRootPath = Promise.resolve(vsc.workspace.workspaceFolders[0].uri.fsPath);
let rootPath: Thenable<string> = stdRootPath;
if (vsc.workspace.workspaceFolders.length > 1) {
rootPath = vsc.window.showQuickPick(vsc.workspace.workspaceFolders.map((f) => f.uri.fsPath))
.then((rp) => rp || stdRootPath);
}
return rootPath;
} | 'use strict';
import * as vsc from 'vscode';
export const D_MODE = { language: 'd', scheme: 'file' };
export function getRootPath() {
return vsc.workspace.workspaceFolders
? vsc.window.activeTextEditor
? (vsc.workspace.getWorkspaceFolder(vsc.window.activeTextEditor.document.uri) || vsc.workspace.workspaceFolders[0]).uri.fsPath
: vsc.workspace.workspaceFolders[0].uri.fsPath
: null;
};
export function chooseRootPath() {
if (!vsc.workspace.workspaceFolders) {
return Promise.resolve<string>(null);
}
const stdRootPath = Promise.resolve(vsc.workspace.workspaceFolders[0].uri.fsPath);
let rootPath: Thenable<string> = stdRootPath;
if (vsc.workspace.workspaceFolders.length > 1) {
rootPath = vsc.window.showQuickPick(vsc.workspace.workspaceFolders.map((f) => f.uri.fsPath))
.then((rp) => rp || stdRootPath);
}
return rootPath;
} | Fix crash when first document isn't in workspace | Fix crash when first document isn't in workspace
| TypeScript | mit | dlang-vscode/dlang-vscode,mattiascibien/dlang-vscode | ---
+++
@@ -7,7 +7,7 @@
export function getRootPath() {
return vsc.workspace.workspaceFolders
? vsc.window.activeTextEditor
- ? vsc.workspace.getWorkspaceFolder(vsc.window.activeTextEditor.document.uri).uri.fsPath
+ ? (vsc.workspace.getWorkspaceFolder(vsc.window.activeTextEditor.document.uri) || vsc.workspace.workspaceFolders[0]).uri.fsPath
: vsc.workspace.workspaceFolders[0].uri.fsPath
: null;
}; |
a4dfa18e930d26ad09a0137839be04eef349d3fb | crawler/src/util.spec.ts | crawler/src/util.spec.ts | import 'mocha'
import { expect } from 'chai'
import { parsePrice } from '../src/util'
describe('util functions', () => {
it('should parse price', () => {
const testInput = ['5', '25', '1.2', '1,2', '-12,25€', '-12,25 €', '$5.5', '1.256.000', '1,213.12', '.25', ',0025']
const result = testInput.map(val => parsePrice(val))
const spected = [5, 25, 1.2, 1.2, -12.25, -12.25, 5.5, 1256000, 1213.12, 0.25, 0.0025]
expect(result).to.eql(spected)
})
})
| import 'mocha'
import { expect } from 'chai'
import { parsePrice } from '../src/util'
describe('util functions', () => {
it('should parse price', () => {
const testInput = ['5', '25', '1.2', '1,2', '-12,25€', '-12,25 €', '144,50 € ', '$5.5', '1.256.000', '1,213.12', '.25', ',0025']
const result = testInput.map(val => parsePrice(val))
const spected = [5, 25, 1.2, 1.2, -12.25, -12.25, 144.50, 5.5, 1256000, 1213.12, 0.25, 0.0025]
expect(result).to.eql(spected)
})
})
| Add price case to util.ts test | Add price case to util.ts test
| TypeScript | mit | davidglezz/tfg,davidglezz/tfg,davidglezz/tfg,davidglezz/tfg | ---
+++
@@ -5,9 +5,9 @@
describe('util functions', () => {
it('should parse price', () => {
- const testInput = ['5', '25', '1.2', '1,2', '-12,25€', '-12,25 €', '$5.5', '1.256.000', '1,213.12', '.25', ',0025']
+ const testInput = ['5', '25', '1.2', '1,2', '-12,25€', '-12,25 €', '144,50 € ', '$5.5', '1.256.000', '1,213.12', '.25', ',0025']
const result = testInput.map(val => parsePrice(val))
- const spected = [5, 25, 1.2, 1.2, -12.25, -12.25, 5.5, 1256000, 1213.12, 0.25, 0.0025]
+ const spected = [5, 25, 1.2, 1.2, -12.25, -12.25, 144.50, 5.5, 1256000, 1213.12, 0.25, 0.0025]
expect(result).to.eql(spected)
}) |
48fa297f58ba7c44eb2d3d5c3cfc353cd6e4c045 | addon/-private/utils/model-aware-types.ts | addon/-private/utils/model-aware-types.ts | import { QueryOrExpressions, TransformOrOperations } from '@orbit/data';
import {
RecordIdentity,
RecordKeyValue,
RecordOperation,
RecordQueryBuilder,
RecordQueryExpression,
RecordTransformBuilder,
UninitializedRecord
} from '@orbit/records';
import { Model } from 'ember-orbit';
import { ModelFields } from './model-fields';
export type RecordIdentityOrModel = RecordIdentity | RecordKeyValue | Model;
export type RecordFieldsOrModel = UninitializedRecord | Model | ModelFields;
export class ModelAwareTransformBuilder extends RecordTransformBuilder<
string,
RecordIdentityOrModel,
RecordFieldsOrModel
> {}
export class ModelAwareQueryBuilder extends RecordQueryBuilder<
string,
RecordIdentityOrModel
> {}
export type ModelAwareQueryOrExpressions = QueryOrExpressions<
RecordQueryExpression,
ModelAwareQueryBuilder
>;
export type ModelAwareTransformOrOperations = TransformOrOperations<
RecordOperation,
RecordTransformBuilder
>;
| import { QueryOrExpressions, TransformOrOperations } from '@orbit/data';
import {
RecordIdentity,
RecordKeyValue,
RecordOperation,
RecordQueryBuilder,
RecordQueryExpression,
RecordTransformBuilder,
UninitializedRecord
} from '@orbit/records';
import { Model } from 'ember-orbit';
import { ModelFields } from './model-fields';
export type RecordIdentityOrModel = RecordIdentity | RecordKeyValue | Model;
export type RecordFieldsOrModel = UninitializedRecord | Model | ModelFields;
export class ModelAwareTransformBuilder extends RecordTransformBuilder<
string,
RecordIdentityOrModel,
RecordFieldsOrModel
> {}
export class ModelAwareQueryBuilder extends RecordQueryBuilder<
string,
RecordIdentityOrModel
> {}
export type ModelAwareQueryOrExpressions = QueryOrExpressions<
RecordQueryExpression,
ModelAwareQueryBuilder
>;
export type ModelAwareTransformOrOperations = TransformOrOperations<
RecordOperation,
ModelAwareTransformBuilder
>;
| Fix type ModelAwareTransformOrOperations to reference ModelAwareTransformBuilder | Fix type ModelAwareTransformOrOperations to reference ModelAwareTransformBuilder
| TypeScript | mit | orbitjs/ember-orbit,orbitjs/ember-orbit,orbitjs/ember-orbit | ---
+++
@@ -33,5 +33,5 @@
export type ModelAwareTransformOrOperations = TransformOrOperations<
RecordOperation,
- RecordTransformBuilder
+ ModelAwareTransformBuilder
>; |
20f7dce6a7ab0c88adebcae22b786b23b53e077e | src/slurm/details/utils.spec.ts | src/slurm/details/utils.spec.ts | import { getEChartOptions } from './utils';
import { palette } from '@waldur/slurm/details/constants';
const usages = require('./fixtures/usages.json');
const userUsages = require('./fixtures/user-usages.json');
const chartSpec = require('./fixtures/chart-spec.json');
const eChartOption = require('./fixtures/echart-option.json');
describe('SLURM allocation usage chart formatter', () => {
it('parses data and returns eChart option correctly', () => {
expect(getEChartOptions(chartSpec, usages, userUsages)).toEqual({
...eChartOption,
color: palette,
});
});
});
| import { palette } from '@waldur/slurm/details/constants';
import { getEChartOptions } from './utils';
const usages = require('./fixtures/usages.json');
const userUsages = require('./fixtures/user-usages.json');
const chartSpec = require('./fixtures/chart-spec.json');
const eChartOption = require('./fixtures/echart-option.json');
jest.mock('moment-timezone', () => {
return () => jest.requireActual('moment')('2020-07-01T00:00:00.000Z');
});
describe('SLURM allocation usage chart formatter', () => {
it('parses data and returns eChart option correctly', () => {
expect(getEChartOptions(chartSpec, usages, userUsages)).toEqual({
...eChartOption,
color: palette,
});
});
});
| Fix unit tests by mocking momentjs. | Fix unit tests by mocking momentjs.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -1,10 +1,15 @@
+import { palette } from '@waldur/slurm/details/constants';
+
import { getEChartOptions } from './utils';
-import { palette } from '@waldur/slurm/details/constants';
const usages = require('./fixtures/usages.json');
const userUsages = require('./fixtures/user-usages.json');
const chartSpec = require('./fixtures/chart-spec.json');
const eChartOption = require('./fixtures/echart-option.json');
+
+jest.mock('moment-timezone', () => {
+ return () => jest.requireActual('moment')('2020-07-01T00:00:00.000Z');
+});
describe('SLURM allocation usage chart formatter', () => {
it('parses data and returns eChart option correctly', () => { |
dfba899334ba42875c35863525fecd19d2fae5f3 | tests/de/gurkenlabs/litiengine/environment/tilemap/xml/external-tileset.tsx | tests/de/gurkenlabs/litiengine/environment/tilemap/xml/external-tileset.tsx | <?xml version="1.0" encoding="UTF-8"?>
<tileset name="tiles-test" tilewidth="16" tileheight="16" tilecount="2" columns="2">
<image source="tiles-test.png" trans="ff00ff" width="32" height="16"/>
<tile id="0">
<properties>
<property name="baz" value="bap"/>
</properties>
</tile>
</tileset>
| <?xml version="1.0" encoding="UTF-8"?>
<tileset name="external-tileset" tilewidth="16" tileheight="16" tilecount="2" columns="2">
<image source="tiles-test.png" trans="ff00ff" width="32" height="16"/>
<tile id="0">
<properties>
<property name="baz" value="bap"/>
</properties>
</tile>
</tileset>
| Adjust naming of external tileset. | Adjust naming of external tileset.
| TypeScript | mit | gurkenlabs/litiengine,gurkenlabs/litiengine | ---
+++
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
-<tileset name="tiles-test" tilewidth="16" tileheight="16" tilecount="2" columns="2">
+<tileset name="external-tileset" tilewidth="16" tileheight="16" tilecount="2" columns="2">
<image source="tiles-test.png" trans="ff00ff" width="32" height="16"/>
<tile id="0">
<properties> |
8605b8ee312783766ddabb1c49237e517b5559db | resources/app/auth/components/register/register.component.ts | resources/app/auth/components/register/register.component.ts | export class RegisterComponent implements ng.IComponentOptions {
static NAME:string = 'appRegister';
template: any;
controllerAs:string;
controller;
constructor() {
this.template = require('./register.component.html');
this.controllerAs = '$ctrl';
this.controller = RegisterController;
}
}
class RegisterController implements ng.IComponentController {
static $inject = ['$http', '$state'];
title: string;
user;
emailUsed = false;
constructor(private http: ng.IHttpService, private $state: ng.ui.IStateService) {
this.title = "Register Page";
this.user = {};
}
register() {
this.http.post('http://localhost:8080/api/register', this.user, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(response => {
console.log(response.data);
if (response.data === 'email already used') {
this.emailUsed = true;
return;
}
this.$state.go('app.dashboard.student');
})
}
} | export class RegisterComponent implements ng.IComponentOptions {
static NAME:string = 'appRegister';
template: any;
controllerAs:string;
controller;
constructor() {
this.template = require('./register.component.html');
this.controllerAs = '$ctrl';
this.controller = RegisterController;
}
}
class RegisterController implements ng.IComponentController {
static $inject = ['$http', '$state', '$httpParamSerializerJQLike'];
title: string;
user;
emailUsed = false;
constructor(
private http: ng.IHttpService,
private $state: ng.ui.IStateService,
private httpParamSerializerJQLike: ng.IHttpParamSerializer
) {
this.title = "Register Page";
this.user = {};
}
register() {
this.http.post(
'http://localhost:8080/api/register',
this.httpParamSerializerJQLike(this.user),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then(response => {
console.log(response.data);
if (response.data === 'email already used') {
this.emailUsed = true;
return;
}
this.$state.go('app.dashboard.student');
})
}
} | Send data using jqaram in registration controller | Send data using jqaram in registration controller
| TypeScript | mit | ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io | ---
+++
@@ -12,22 +12,30 @@
}
class RegisterController implements ng.IComponentController {
- static $inject = ['$http', '$state'];
+ static $inject = ['$http', '$state', '$httpParamSerializerJQLike'];
title: string;
user;
emailUsed = false;
- constructor(private http: ng.IHttpService, private $state: ng.ui.IStateService) {
+ constructor(
+ private http: ng.IHttpService,
+ private $state: ng.ui.IStateService,
+ private httpParamSerializerJQLike: ng.IHttpParamSerializer
+ ) {
this.title = "Register Page";
this.user = {};
}
register() {
- this.http.post('http://localhost:8080/api/register', this.user, {
+ this.http.post(
+ 'http://localhost:8080/api/register',
+ this.httpParamSerializerJQLike(this.user),
+ {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
- }).then(response => {
+ }
+ ).then(response => {
console.log(response.data);
if (response.data === 'email already used') { |
73f4ce4aafa90d40d4824c8338533341418fab14 | src/app/journal/journal.component.spec.ts | src/app/journal/journal.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { JournalComponent } from './journal.component';
import {SearchComponent} from './nubaSearch.component';
import {JournalListComponent} from './journalList.component';
import {FormsModule} from '@angular/forms';
import {FIREBASE_PROVIDERS, defaultFirebase} from 'angularfire2';
describe('JournalComponent', () => {
let component: JournalComponent;
let fixture: ComponentFixture<JournalComponent>;
const firebaseConfig = {
apiKey: 'AIzaSyBf7RiiafbN6IKzYoDdsZtOaQqFK-54oB0',
authDomain: 'nuba-c3e84.firebaseapp.com',
databaseURL: 'https://nuba-c3e84.firebaseio.com/',
storageBucket: 'nuba-c3e84.appspot.com',
messagingSenderId: '126418702718'
};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
JournalComponent,
SearchComponent,
JournalListComponent
],
imports: [
FormsModule
],
providers: [
FIREBASE_PROVIDERS, defaultFirebase(firebaseConfig)
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JournalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { JournalComponent } from './journal.component';
import {SearchComponent} from './nubaSearch.component';
import {JournalListComponent} from './journalList.component';
import {FormsModule} from '@angular/forms';
import {FirebaseService} from '../food-database/firebase.service';
import {AngularFire} from 'angularfire2';
import {JournalEntriesService} from './journalEntries.service';
import {EventEmitter} from '@angular/core';
import {Output} from '@angular/core/src/metadata/directives';
class FirebaseServiceStub {}
class AngularFireStub {}
class JournalEntriesServiceStub implements JournalEntriesService {
@Output() data = new EventEmitter();
public getMutableData () {
return {
'entriesOfActiveDate': new Date(),
'activeDate': new Date()
};
}
}
describe('JournalComponent', () => {
let component: JournalComponent;
let fixture: ComponentFixture<JournalComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
JournalComponent,
SearchComponent,
JournalListComponent
],
imports: [
FormsModule
],
providers: [
{ provide: AngularFire, useClass: AngularFireStub }
]
}).overrideComponent(JournalComponent, {
set: {
providers: [
{ provide: FirebaseService, useClass: FirebaseServiceStub },
{ provide: JournalEntriesService, useClass: JournalEntriesServiceStub }
]
}
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JournalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| Create stub for FirebaseService and AngularFire in test | Create stub for FirebaseService and AngularFire in test
| TypeScript | mit | stefanamport/nuba,stefanamport/nuba,stefanamport/nuba | ---
+++
@@ -4,19 +4,30 @@
import {SearchComponent} from './nubaSearch.component';
import {JournalListComponent} from './journalList.component';
import {FormsModule} from '@angular/forms';
-import {FIREBASE_PROVIDERS, defaultFirebase} from 'angularfire2';
+import {FirebaseService} from '../food-database/firebase.service';
+import {AngularFire} from 'angularfire2';
+import {JournalEntriesService} from './journalEntries.service';
+import {EventEmitter} from '@angular/core';
+import {Output} from '@angular/core/src/metadata/directives';
+
+class FirebaseServiceStub {}
+
+class AngularFireStub {}
+
+class JournalEntriesServiceStub implements JournalEntriesService {
+ @Output() data = new EventEmitter();
+
+ public getMutableData () {
+ return {
+ 'entriesOfActiveDate': new Date(),
+ 'activeDate': new Date()
+ };
+ }
+}
describe('JournalComponent', () => {
let component: JournalComponent;
let fixture: ComponentFixture<JournalComponent>;
-
- const firebaseConfig = {
- apiKey: 'AIzaSyBf7RiiafbN6IKzYoDdsZtOaQqFK-54oB0',
- authDomain: 'nuba-c3e84.firebaseapp.com',
- databaseURL: 'https://nuba-c3e84.firebaseio.com/',
- storageBucket: 'nuba-c3e84.appspot.com',
- messagingSenderId: '126418702718'
- };
beforeEach(async(() => {
TestBed.configureTestingModule({
@@ -29,8 +40,15 @@
FormsModule
],
providers: [
- FIREBASE_PROVIDERS, defaultFirebase(firebaseConfig)
+ { provide: AngularFire, useClass: AngularFireStub }
]
+ }).overrideComponent(JournalComponent, {
+ set: {
+ providers: [
+ { provide: FirebaseService, useClass: FirebaseServiceStub },
+ { provide: JournalEntriesService, useClass: JournalEntriesServiceStub }
+ ]
+ }
})
.compileComponents();
})); |
8bea19631ed5c22dcb6e6dd7a4acd0a446a5779f | workers/dummyeventworker/eventgenerator.ts | workers/dummyeventworker/eventgenerator.ts | var amqp = require('amqp');
var sleep = require('sleep');
import epcis = require('./node_modules/epcis-js/lib/epcisevents');
var connection = amqp.createConnection({
host: '192.168.59.103',
login: 'admin',
password: 'admin'
});
connection.on('error', function (err) {
console.log("Error: Could not connect to AMQP broker:");
console.log(err);
});
connection.on('ready', function() {
var exchange = this.exchange('amq.topic');
exchange.on('error', function (err) {
console.log(err);
});
exchange.on('open', function () {
while (true) {
sleep.sleep(3);
var event = new epcis.EPCIS.AggregationEvent();
var dt = new Date().toISOString();
event.eventTime = dt;
// TODO: add more meaningful properties
// send the event
var msg = JSON.stringify(event, null, 4);
console.log('Sending msg...');
this.publish('input.json', msg);
}
});
});
| var amqp = require('amqp');
var sleep = require('sleep');
import epcis = require('./node_modules/epcis-js/lib/epcisevents');
var connection = amqp.createConnection({
host: '192.168.59.103',
login: 'admin',
password: 'admin'
});
connection.on('error', function (err) {
console.log("Error: Could not connect to AMQP broker:");
console.log(err);
});
connection.on('ready', function() {
var exchange = this.exchange('amq.topic');
exchange.on('error', function (err) {
console.log(err);
});
exchange.on('open', function () {
while (true) {
sleep.sleep(3);
var event = new epcis.EPCIS.AggregationEvent();
var dt = new Date();
event.eventTime = dt;
// TODO: add more meaningful properties
// send the event
//var msg = JSON.stringify(event, null, 4);
console.log('Sending msg...');
this.publish('input.json', event);
}
});
});
| Use date instead of string | generator: Use date instead of string
| TypeScript | mit | matgnt/ls-epcis | ---
+++
@@ -25,14 +25,14 @@
while (true) {
sleep.sleep(3);
var event = new epcis.EPCIS.AggregationEvent();
- var dt = new Date().toISOString();
+ var dt = new Date();
event.eventTime = dt;
// TODO: add more meaningful properties
// send the event
- var msg = JSON.stringify(event, null, 4);
+ //var msg = JSON.stringify(event, null, 4);
console.log('Sending msg...');
- this.publish('input.json', msg);
+ this.publish('input.json', event);
}
}); |
d57c4b99707fdd72caaed38cbe13f87222bf5ad2 | packages/components/components/miniCalendar/LocalizedMiniCalendar.tsx | packages/components/components/miniCalendar/LocalizedMiniCalendar.tsx | import React, { useMemo, useCallback } from 'react';
import { c } from 'ttag';
import { getFormattedMonths, getFormattedWeekdays, getWeekStartsOn } from 'proton-shared/lib/date/date';
import { dateLocale } from 'proton-shared/lib/i18n';
import { format } from 'date-fns';
import MiniCalendar, { Props as MiniCalProps } from './MiniCalendar';
export type Props = MiniCalProps;
const LocalizedMiniCalendar = ({ weekStartsOn, ...rest }: Props) => {
const weekdaysLong = useMemo(() => {
return getFormattedWeekdays('cccc', { locale: dateLocale });
}, [dateLocale]);
const weekdaysShort = useMemo(() => {
return getFormattedWeekdays('ccccc', { locale: dateLocale });
}, [dateLocale]);
const months = useMemo(() => {
return getFormattedMonths('MMMM', { locale: dateLocale });
}, [dateLocale]);
const formatDay = useCallback(
(date) => {
return format(date, 'PPPP', { locale: dateLocale });
},
[dateLocale]
);
return (
<MiniCalendar
nextMonth={c('Action').t`Next month`}
prevMonth={c('Action').t`Prev month`}
weekdaysLong={weekdaysLong}
weekdaysShort={weekdaysShort}
months={months}
weekStartsOn={weekStartsOn || getWeekStartsOn(dateLocale)}
formatDay={formatDay}
{...rest}
/>
);
};
export default LocalizedMiniCalendar;
| import React, { useMemo, useCallback } from 'react';
import { c } from 'ttag';
import { getFormattedMonths, getFormattedWeekdays, getWeekStartsOn } from 'proton-shared/lib/date/date';
import { dateLocale } from 'proton-shared/lib/i18n';
import { format } from 'date-fns';
import MiniCalendar, { Props as MiniCalProps } from './MiniCalendar';
export type Props = MiniCalProps;
const LocalizedMiniCalendar = ({ weekStartsOn, ...rest }: Props) => {
const weekdaysLong = useMemo(() => {
return getFormattedWeekdays('cccc', { locale: dateLocale });
}, [dateLocale]);
const weekdaysShort = useMemo(() => {
return getFormattedWeekdays('ccccc', { locale: dateLocale });
}, [dateLocale]);
const months = useMemo(() => {
return getFormattedMonths('MMMM', { locale: dateLocale });
}, [dateLocale]);
const formatDay = useCallback(
(date) => {
return format(date, 'PPPP', { locale: dateLocale });
},
[dateLocale]
);
return (
<MiniCalendar
nextMonth={c('Action').t`Next month`}
prevMonth={c('Action').t`Prev month`}
weekdaysLong={weekdaysLong}
weekdaysShort={weekdaysShort}
months={months}
weekStartsOn={weekStartsOn !== undefined ? weekStartsOn : getWeekStartsOn(dateLocale)}
formatDay={formatDay}
{...rest}
/>
);
};
export default LocalizedMiniCalendar;
| Use weekStart in the mini-calendar properly | Use weekStart in the mini-calendar properly
CALWEB-2112
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -35,7 +35,7 @@
weekdaysLong={weekdaysLong}
weekdaysShort={weekdaysShort}
months={months}
- weekStartsOn={weekStartsOn || getWeekStartsOn(dateLocale)}
+ weekStartsOn={weekStartsOn !== undefined ? weekStartsOn : getWeekStartsOn(dateLocale)}
formatDay={formatDay}
{...rest}
/> |
c0d2e388d0ae5cf7362bb84282be2697d5195cb3 | src/tasks/MeteorEnvSetupTask.ts | src/tasks/MeteorEnvSetupTask.ts | import {SCRIPT_DIR, TEMPLATES_DIR} from "./Task";
import {SetupTask} from "./SetupTask";
const fs = require('fs');
const path = require('path');
const util = require('util');
export class MeteorEnvSetupTask extends SetupTask {
public describe() : string {
return 'Setting up environment for meteor application';
}
public build(taskList) {
taskList.copy("Setting up shared bash functions", {
src: path.resolve(SCRIPT_DIR, 'functions.sh'),
dest: '/opt/functions.sh',
vars: this.extendArgs({ }),
});
taskList.executeScript(this.describe(), {
script: path.resolve(SCRIPT_DIR, 'setup-env.sh'),
vars: {
appName: this.config.app.name,
deployPrefix: this.deployPrefix
}
});
}
}
| import {SCRIPT_DIR, TEMPLATES_DIR} from "./Task";
import {SetupTask} from "./SetupTask";
const fs = require('fs');
const path = require('path');
const util = require('util');
export class MeteorEnvSetupTask extends SetupTask {
public describe() : string {
return 'Setting up environment for meteor application';
}
public build(taskList) {
taskList.executeScript(this.describe(), {
script: path.resolve(SCRIPT_DIR, 'setup-env.sh'),
vars: {
appName: this.config.app.name,
deployPrefix: this.deployPrefix
}
});
taskList.copy("Setting up shared bash functions", {
src: path.resolve(SCRIPT_DIR, 'functions.sh'),
dest: '/opt/functions.sh',
vars: this.extendArgs({ }),
});
}
}
| Fix shared function setup permission error | Fix shared function setup permission error
Issue #39
| TypeScript | mit | c9s/typeloy,c9s/typeloy | ---
+++
@@ -11,11 +11,6 @@
}
public build(taskList) {
- taskList.copy("Setting up shared bash functions", {
- src: path.resolve(SCRIPT_DIR, 'functions.sh'),
- dest: '/opt/functions.sh',
- vars: this.extendArgs({ }),
- });
taskList.executeScript(this.describe(), {
script: path.resolve(SCRIPT_DIR, 'setup-env.sh'),
vars: {
@@ -23,5 +18,10 @@
deployPrefix: this.deployPrefix
}
});
+ taskList.copy("Setting up shared bash functions", {
+ src: path.resolve(SCRIPT_DIR, 'functions.sh'),
+ dest: '/opt/functions.sh',
+ vars: this.extendArgs({ }),
+ });
}
} |
a637b1bfcd8b9584ae3884e9bc4dae6b7ae86480 | appsrc/reducers/game-updates.ts | appsrc/reducers/game-updates.ts |
import {handleActions} from "redux-actions";
import {IGameUpdatesState} from "../types";
import {
IAction,
IGameUpdateAvailablePayload,
} from "../constants/action-types";
const initialState = {
updates: {},
} as IGameUpdatesState;
export default handleActions<IGameUpdatesState, any>({
GAME_UPDATE_AVAILABLE: (state: IGameUpdatesState, action: IAction<IGameUpdateAvailablePayload>) => {
const updates = Object.assign({}, state.updates, {
[action.payload.caveId]: action.payload.update,
});
return Object.assign({}, state, {updates});
},
}, initialState);
|
import {handleActions} from "redux-actions";
import {IGameUpdatesState} from "../types";
import {omit} from "underscore";
import {
IAction,
IGameUpdateAvailablePayload,
IQueueGameUpdatePayload,
} from "../constants/action-types";
const initialState = {
updates: {},
} as IGameUpdatesState;
export default handleActions<IGameUpdatesState, any>({
GAME_UPDATE_AVAILABLE: (state: IGameUpdatesState, action: IAction<IGameUpdateAvailablePayload>) => {
const updates = Object.assign({}, state.updates, {
[action.payload.caveId]: action.payload.update,
});
return Object.assign({}, state, {updates});
},
QUEUE_GAME_UPDATE: (state: IGameUpdatesState, action: IAction<IQueueGameUpdatePayload>) => {
const updates = omit(state.updates, action.payload.caveId);
return Object.assign({}, state, {updates});
},
}, initialState);
| Remove game update from state when queued | Remove game update from state when queued
| TypeScript | mit | leafo/itchio-app,itchio/itchio-app,itchio/itch,itchio/itchio-app,leafo/itchio-app,itchio/itch,itchio/itch,itchio/itch,itchio/itch,leafo/itchio-app,itchio/itch,itchio/itchio-app | ---
+++
@@ -2,10 +2,12 @@
import {handleActions} from "redux-actions";
import {IGameUpdatesState} from "../types";
+import {omit} from "underscore";
import {
IAction,
IGameUpdateAvailablePayload,
+ IQueueGameUpdatePayload,
} from "../constants/action-types";
const initialState = {
@@ -20,4 +22,10 @@
return Object.assign({}, state, {updates});
},
+
+ QUEUE_GAME_UPDATE: (state: IGameUpdatesState, action: IAction<IQueueGameUpdatePayload>) => {
+ const updates = omit(state.updates, action.payload.caveId);
+
+ return Object.assign({}, state, {updates});
+ },
}, initialState); |
70a4acde8a1975cfbfca62aea886543922f2a55d | src/client/app/suche/basic-search/basic-search.component.ts | src/client/app/suche/basic-search/basic-search.component.ts | import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
moduleId: module.id,
selector: 'rae-basic-search',
templateUrl: './basic-search.component.html',
styleUrls: ['./basic-search.component.css']
})
export class BasicSearchComponent {
hideSearchfield: boolean = true;
placeholder = 'Suche...';
constructor(private router: Router) {
}
sendRequest(values: any) {
this.router.navigateByUrl('/suche/' + encodeURIComponent(values),);
}
}
| import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
moduleId: module.id,
selector: 'rae-basic-search',
templateUrl: './basic-search.component.html',
styleUrls: ['./basic-search.component.css']
})
export class BasicSearchComponent {
hideSearchfield: boolean = true;
placeholder = 'Suche...';
constructor(private router: Router) {
router.events.subscribe(changes => {
this.hideSearchfield = true;
this.placeholder = 'Suche...';
});
}
sendRequest(values: any) {
this.router.navigateByUrl('/suche/' + encodeURIComponent(values),);
}
}
| Delete search string and hide input field if route is changed (i.e. a new "page" is loaded) | Delete search string and hide input field if route is changed (i.e. a new "page" is loaded)
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -13,6 +13,10 @@
placeholder = 'Suche...';
constructor(private router: Router) {
+ router.events.subscribe(changes => {
+ this.hideSearchfield = true;
+ this.placeholder = 'Suche...';
+ });
}
sendRequest(values: any) { |
5c5d52fda6c0da7cf68381bf6036b1254a1e1e3d | src/material/material.module.ts | src/material/material.module.ts | import {NgModule} from '@angular/core';
import {MatButtonModule, MatCardModule, MatFormFieldModule, MatIconModule, MatInputModule, MatListModule, MatToolbarModule} from '@angular/material';
const matModules = [
MatButtonModule, MatCardModule, MatFormFieldModule, MatIconModule, MatInputModule, MatListModule,
MatToolbarModule
];
@NgModule({
imports: matModules,
exports: matModules,
})
export class MaterialModule {
} | import {NgModule} from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import {MatCardModule} from '@angular/material/card';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatIconModule} from '@angular/material/icon';
import {MatInputModule} from '@angular/material/input';
import {MatListModule} from '@angular/material/list';
import {MatToolbarModule} from '@angular/material/toolbar';
const matModules = [
MatButtonModule, MatCardModule, MatFormFieldModule, MatIconModule, MatInputModule, MatListModule,
MatToolbarModule
];
@NgModule({
imports: matModules,
exports: matModules,
})
export class MaterialModule {
} | Switch to deep imports of ANgular Material | Switch to deep imports of ANgular Material
| TypeScript | mit | angular/angular-bazel-example,angular/angular-bazel-example,angular/angular-bazel-example,angular/angular-bazel-example | ---
+++
@@ -1,5 +1,11 @@
import {NgModule} from '@angular/core';
-import {MatButtonModule, MatCardModule, MatFormFieldModule, MatIconModule, MatInputModule, MatListModule, MatToolbarModule} from '@angular/material';
+import {MatButtonModule} from '@angular/material/button';
+import {MatCardModule} from '@angular/material/card';
+import {MatFormFieldModule} from '@angular/material/form-field';
+import {MatIconModule} from '@angular/material/icon';
+import {MatInputModule} from '@angular/material/input';
+import {MatListModule} from '@angular/material/list';
+import {MatToolbarModule} from '@angular/material/toolbar';
const matModules = [
MatButtonModule, MatCardModule, MatFormFieldModule, MatIconModule, MatInputModule, MatListModule, |
fe9b7538fc212961da40f45783c4eefe9ddf3f55 | src/components/SectionHeader.tsx | src/components/SectionHeader.tsx | import React from 'react';
import styled from '@emotion/styled';
import { fontSecondary, colorTertiary, colorPrimary } from 'style/theme';
import { letterSpacing } from 'style/helpers';
type Props = {
name: string;
};
const Container = styled.h1`
margin-top: 80px;
width: 100%;
text-align: center;
text-transform: uppercase;
font-family: ${fontSecondary};
font-size: 24px;
font-weight: 400;
color: ${colorPrimary};
${letterSpacing(16)};
border-top: 1px solid ${colorTertiary};
padding-top: 16px;
margin-bottom: 40px;
`;
const SectionHeader = ({ name }: Props) => <Container>{name}</Container>;
export default SectionHeader;
| import React from 'react';
import styled from '@emotion/styled';
import { fontSecondary, colorTertiary, colorPrimary } from 'style/theme';
import { letterSpacing } from 'style/helpers';
type Props = {
name: string;
};
const Container = styled.h1`
margin-top: 80px;
width: 100%;
text-align: center;
text-transform: uppercase;
font-family: ${fontSecondary};
font-size: 24px;
font-weight: 400;
color: ${colorPrimary};
border-top: 1px solid ${colorTertiary};
padding-top: 16px;
margin-bottom: 40px;
span {
${letterSpacing(16)};
}
`;
const SectionHeader = ({ name }: Props) => <Container><span>{name}</span></Container>;
export default SectionHeader;
| Fix out of bound element | Fix out of bound element
| TypeScript | mit | lucaslos/lucaslos.github.io,lucaslos/lucaslos.github.io,lucaslos/lucaslos.github.io | ---
+++
@@ -16,13 +16,16 @@
font-size: 24px;
font-weight: 400;
color: ${colorPrimary};
- ${letterSpacing(16)};
border-top: 1px solid ${colorTertiary};
padding-top: 16px;
margin-bottom: 40px;
+
+ span {
+ ${letterSpacing(16)};
+ }
`;
-const SectionHeader = ({ name }: Props) => <Container>{name}</Container>;
+const SectionHeader = ({ name }: Props) => <Container><span>{name}</span></Container>;
export default SectionHeader; |
5ea6d2fd3a6524e6235b3e52f67cc9c48e96aad9 | packages/react-day-picker/src/components/Day/utils/createTabIndex.ts | packages/react-day-picker/src/components/Day/utils/createTabIndex.ts | import { isSameDay, isSameMonth } from 'date-fns';
import { DayPickerProps, ModifiersStatus } from '../../../types';
export function createTabIndex(
day: Date,
modifiers: ModifiersStatus,
props: DayPickerProps
): number | undefined {
if (!modifiers.interactive) return;
let tabIndex: number;
if (props.focusedDay && isSameDay(day, props.focusedDay)) {
tabIndex = 0;
} else if (isSameDay(day, new Date())) {
tabIndex = 0;
} else if (
!isSameDay(day, new Date()) &&
!isSameMonth(day, new Date()) &&
day.getDate() === 1
) {
tabIndex = 0;
} else {
tabIndex = -1;
}
return tabIndex;
}
| import { isSameDay, isSameMonth } from 'date-fns';
import { DayPickerProps, ModifiersStatus } from '../../../types';
export function createTabIndex(
day: Date,
modifiers: ModifiersStatus,
props: DayPickerProps
): number | undefined {
let tabIndex: number;
if (props.focusedDay && isSameDay(day, props.focusedDay)) {
tabIndex = 0;
} else if (isSameMonth(day, props.month) && day.getDate() === 1) {
tabIndex = 0;
} else {
tabIndex = -1;
}
return tabIndex;
}
| Fix tabIndex not being set correctly | Fix tabIndex not being set correctly
| TypeScript | mit | gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker | ---
+++
@@ -6,22 +6,13 @@
modifiers: ModifiersStatus,
props: DayPickerProps
): number | undefined {
- if (!modifiers.interactive) return;
-
let tabIndex: number;
if (props.focusedDay && isSameDay(day, props.focusedDay)) {
tabIndex = 0;
- } else if (isSameDay(day, new Date())) {
- tabIndex = 0;
- } else if (
- !isSameDay(day, new Date()) &&
- !isSameMonth(day, new Date()) &&
- day.getDate() === 1
- ) {
+ } else if (isSameMonth(day, props.month) && day.getDate() === 1) {
tabIndex = 0;
} else {
tabIndex = -1;
}
-
return tabIndex;
} |
b0e355367c227b508e448f1acc60ad834d9c2485 | Presentation.Web/app/components/it-project/it-project-overview.spec.ts | Presentation.Web/app/components/it-project/it-project-overview.spec.ts | module Kitos.ItProject.Overview.Tests {
"use strict";
describe("project.OverviewCtrl", () => {
// mock object references
var scopeMock: ng.IScope,
httpBackendMock: ng.IHttpBackendService,
httpMock: ng.IHttpService,
notifyMock: any,
projectRolesMock: any,
userMock: any,
$qMock: any,
controller: OverviewController;
// setup module
beforeEach(() => angular.module("app"));
// setup mocks
beforeEach(inject(($injector: angular.auto.IInjectorService) => {
scopeMock = $injector.get<ng.IScope>("$rootScope").$new();
httpBackendMock = $injector.get<ng.IHttpBackendService>("$httpBackend");
// setup HTTP path responses here
// http://dotnetspeak.com/2014/03/testing-controllers-in-angular-with-jasmine
userMock = {
currentOrganizationId: 1
};
}));
// TODO
});
}
| module Kitos.ItProject.Overview.Tests {
"use strict";
describe("project.OverviewCtrl", () => {
// mock object references
var scopeMock: ng.IScope,
httpBackendMock: ng.IHttpBackendService,
httpMock: ng.IHttpService,
notifyMock: any,
projectRolesMock: any,
userMock: any,
$qMock: any,
controller: OverviewController;
// setup module
beforeEach(() => angular.module("app"));
// setup mocks
beforeEach(inject(($injector: angular.auto.IInjectorService) => {
scopeMock = $injector.get<ng.IScope>("$rootScope").$new();
httpBackendMock = $injector.get<ng.IHttpBackendService>("$httpBackend");
// setup HTTP path responses here
// http://dotnetspeak.com/2014/03/testing-controllers-in-angular-with-jasmine
userMock = {
currentOrganizationId: 1
};
}));
// TODO
it("should do stuff", () => {
expect(true).toBeTruthy();
});
});
}
| Add true is true unit test. | Add true is true unit test.
| TypeScript | mpl-2.0 | os2kitos/kitos,miracle-as/kitos,os2kitos/kitos,miracle-as/kitos,os2kitos/kitos,os2kitos/kitos,miracle-as/kitos,miracle-as/kitos | ---
+++
@@ -29,5 +29,8 @@
}));
// TODO
+ it("should do stuff", () => {
+ expect(true).toBeTruthy();
+ });
});
} |
f076ac020bfd325cdff28e5f361d886c8440b29f | integration/injector/e2e/core-injectables.spec.ts | integration/injector/e2e/core-injectables.spec.ts | import { Test, TestingModule } from '@nestjs/testing';
import { expect } from 'chai';
import { CoreInjectablesModule } from '../src/core-injectables/core-injectables.module';
import { ApplicationConfig } from '@nestjs/core';
describe('Core Injectables', () => {
let testingModule: TestingModule;
beforeEach(async () => {
const builder = Test.createTestingModule({
imports: [CoreInjectablesModule],
});
testingModule = await builder.compile();
});
it('should provide ApplicationConfig as core injectable', () => {
const applicationConfig = testingModule.get<ApplicationConfig>(
ApplicationConfig,
);
applicationConfig.setGlobalPrefix('/api');
expect(applicationConfig).to.not.be.undefined;
expect(applicationConfig.getGlobalPrefix()).to.be.eq('/api');
});
});
| import { Test, TestingModule } from '@nestjs/testing';
import { expect } from 'chai';
import { CoreInjectablesModule } from '../src/core-injectables/core-injectables.module';
import { ApplicationConfig, ModuleRef } from '@nestjs/core';
describe('Core Injectables', () => {
let testingModule: TestingModule;
beforeEach(async () => {
const builder = Test.createTestingModule({
imports: [CoreInjectablesModule],
});
testingModule = await builder.compile();
});
it('should provide ApplicationConfig as core injectable', () => {
const applicationConfig = testingModule.get<ApplicationConfig>(
ApplicationConfig,
);
applicationConfig.setGlobalPrefix('/api');
expect(applicationConfig).to.not.be.undefined;
expect(applicationConfig.getGlobalPrefix()).to.be.eq('/api');
});
it('should provide ModuleRef as core injectable', () => {
const moduleRef = testingModule.get<ModuleRef>(ModuleRef);
expect(moduleRef).to.not.be.undefined;
});
it('should provide the current Module as provider', () => {
const module = testingModule.get<CoreInjectablesModule>(CoreInjectablesModule);
expect(module).to.not.be.undefined;
expect(module.constructor.name).to.be.eq('CoreInjectablesModule');
});
});
| Add integration test for core injectables | test(): Add integration test for core injectables
| TypeScript | mit | kamilmysliwiec/nest,kamilmysliwiec/nest | ---
+++
@@ -1,7 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing';
import { expect } from 'chai';
import { CoreInjectablesModule } from '../src/core-injectables/core-injectables.module';
-import { ApplicationConfig } from '@nestjs/core';
+import { ApplicationConfig, ModuleRef } from '@nestjs/core';
describe('Core Injectables', () => {
let testingModule: TestingModule;
@@ -23,4 +23,15 @@
expect(applicationConfig).to.not.be.undefined;
expect(applicationConfig.getGlobalPrefix()).to.be.eq('/api');
});
+
+ it('should provide ModuleRef as core injectable', () => {
+ const moduleRef = testingModule.get<ModuleRef>(ModuleRef);
+ expect(moduleRef).to.not.be.undefined;
+ });
+
+ it('should provide the current Module as provider', () => {
+ const module = testingModule.get<CoreInjectablesModule>(CoreInjectablesModule);
+ expect(module).to.not.be.undefined;
+ expect(module.constructor.name).to.be.eq('CoreInjectablesModule');
+ });
}); |
f213a0ea9506ffa73a0e5485677def7f1e571eba | src/app/gallery/image-container/image-container.component.spec.ts | src/app/gallery/image-container/image-container.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ImageContainerComponent } from './image-container.component';
describe('ImageContainerComponent', () => {
let component: ImageContainerComponent;
let fixture: ComponentFixture<ImageContainerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ImageContainerComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ImageContainerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| import { SimpleChange, SimpleChanges } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpModule } from '@angular/http';
import { RouterTestingModule } from '@angular/router/testing';
import { GalleryFormatPipe } from '../gallery-format.pipe';
import { ThumbnailComponent } from '../thumbnail/thumbnail.component';
import { ImageService } from '../image.service';
import { MockImageService } from '../mocks/mock-image.service';
import { ImageContainerComponent } from './image-container.component';
describe('ImageContainerComponent', () => {
const mockImageService = new MockImageService();
let component: ImageContainerComponent;
let fixture: ComponentFixture<ImageContainerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpModule,
RouterTestingModule
],
declarations: [
ImageContainerComponent,
GalleryFormatPipe,
ThumbnailComponent
],
providers: [
{provide: ImageService, useValue: mockImageService}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ImageContainerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should update images when page changed', async(() => {
spyOn(mockImageService, 'getImagesFromAlbum').and.callThrough();
expect(mockImageService.getImagesFromAlbum).not.toHaveBeenCalled();
component.page = 2;
component.ngOnChanges({page: new SimpleChange(1, 2, true)});
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(mockImageService.getImagesFromAlbum).toHaveBeenCalled();
});
}));
it('should update images when album changed', async(() => {
spyOn(mockImageService, 'getImagesFromAlbum').and.callThrough();
expect(mockImageService.getImagesFromAlbum).not.toHaveBeenCalled();
component.albumName = 'another';
component.ngOnChanges({albumName: new SimpleChange('_default', 'albumName', true)});
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(mockImageService.getImagesFromAlbum).toHaveBeenCalled();
});
}));
});
| Add tests for image container component | Add tests for image container component
| TypeScript | apache-2.0 | jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog | ---
+++
@@ -1,14 +1,34 @@
+import { SimpleChange, SimpleChanges } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
+import { HttpModule } from '@angular/http';
+import { RouterTestingModule } from '@angular/router/testing';
+
+import { GalleryFormatPipe } from '../gallery-format.pipe';
+import { ThumbnailComponent } from '../thumbnail/thumbnail.component';
+import { ImageService } from '../image.service';
+import { MockImageService } from '../mocks/mock-image.service';
import { ImageContainerComponent } from './image-container.component';
describe('ImageContainerComponent', () => {
+ const mockImageService = new MockImageService();
let component: ImageContainerComponent;
let fixture: ComponentFixture<ImageContainerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
- declarations: [ ImageContainerComponent ]
+ imports: [
+ HttpModule,
+ RouterTestingModule
+ ],
+ declarations: [
+ ImageContainerComponent,
+ GalleryFormatPipe,
+ ThumbnailComponent
+ ],
+ providers: [
+ {provide: ImageService, useValue: mockImageService}
+ ]
})
.compileComponents();
}));
@@ -19,7 +39,32 @@
fixture.detectChanges();
});
- it('should create', () => {
- expect(component).toBeTruthy();
- });
+ it('should update images when page changed', async(() => {
+ spyOn(mockImageService, 'getImagesFromAlbum').and.callThrough();
+ expect(mockImageService.getImagesFromAlbum).not.toHaveBeenCalled();
+
+ component.page = 2;
+ component.ngOnChanges({page: new SimpleChange(1, 2, true)});
+
+ fixture.detectChanges();
+ fixture.whenStable().then(() => {
+ fixture.detectChanges();
+ expect(mockImageService.getImagesFromAlbum).toHaveBeenCalled();
+ });
+ }));
+
+ it('should update images when album changed', async(() => {
+ spyOn(mockImageService, 'getImagesFromAlbum').and.callThrough();
+ expect(mockImageService.getImagesFromAlbum).not.toHaveBeenCalled();
+
+ component.albumName = 'another';
+ component.ngOnChanges({albumName: new SimpleChange('_default', 'albumName', true)});
+
+ fixture.detectChanges();
+ fixture.whenStable().then(() => {
+ fixture.detectChanges();
+ expect(mockImageService.getImagesFromAlbum).toHaveBeenCalled();
+ });
+ }));
+
}); |
ce614cda3ba7eba26abb5f6afe5a9432a40a4e21 | src/schema/v1/fields/initials.ts | src/schema/v1/fields/initials.ts | import { get, take } from "lodash"
import { GraphQLString, GraphQLInt, GraphQLFieldConfig } from "graphql"
import { ResolverContext } from "types/graphql"
export function initials(string = "", length = 3) {
if (!string) return null
// FIXME: Expected 1 arguments, but got 2.
// @ts-ignore
const letters = take(string.match(/\b[A-Z]/g, ""), length)
if (letters.length >= 1) return letters.join("").toUpperCase()
// FIXME: Expected 1 arguments, but got 2.
// @ts-ignore
return take(string.match(/\b\w/g, ""), length).join("").toUpperCase()
}
export default (attr): GraphQLFieldConfig<void, ResolverContext> => ({
type: GraphQLString,
args: {
length: {
type: GraphQLInt,
defaultValue: 3,
},
},
resolve: (obj, { length }) => initials(get(obj, attr), length),
})
| import { get, take } from "lodash"
import { GraphQLString, GraphQLInt, GraphQLFieldConfig } from "graphql"
import { ResolverContext } from "types/graphql"
export function initials(string = "", length = 3) {
if (!string) return null
const letters = take(string.match(/\b[A-Z]/g), length)
if (letters.length >= 1) return letters.join("").toUpperCase()
return take(string.match(/\b\w/g), length).join("").toUpperCase()
}
export default (attr): GraphQLFieldConfig<void, ResolverContext> => ({
type: GraphQLString,
args: {
length: {
type: GraphQLInt,
defaultValue: 3,
},
},
resolve: (obj, { length }) => initials(get(obj, attr), length),
})
| Remove ts-ignores around improper usage of string.match | Remove ts-ignores around improper usage of string.match
| TypeScript | mit | artsy/metaphysics,artsy/metaphysics,artsy/metaphysics | ---
+++
@@ -5,14 +5,10 @@
export function initials(string = "", length = 3) {
if (!string) return null
- // FIXME: Expected 1 arguments, but got 2.
- // @ts-ignore
- const letters = take(string.match(/\b[A-Z]/g, ""), length)
+ const letters = take(string.match(/\b[A-Z]/g), length)
if (letters.length >= 1) return letters.join("").toUpperCase()
- // FIXME: Expected 1 arguments, but got 2.
- // @ts-ignore
- return take(string.match(/\b\w/g, ""), length).join("").toUpperCase()
+ return take(string.match(/\b\w/g), length).join("").toUpperCase()
}
export default (attr): GraphQLFieldConfig<void, ResolverContext> => ({ |
73db5fafde9dafef98041daf135590e65ef4fc3e | lib/msal-node/src/network/HttpClient.ts | lib/msal-node/src/network/HttpClient.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import {
INetworkModule,
NetworkRequestOptions,
NetworkResponse,
} from "@azure/msal-common";
import { HttpMethod } from "../utils/Constants";
import axios, { AxiosRequestConfig } from "axios";
/**
* This class implements the API for network requests.
*/
export class HttpClient implements INetworkModule {
constructor() {
axios.defaults.validateStatus = () => true;
}
/**
* Http Get request
* @param url
* @param options
*/
async sendGetRequestAsync<T>(
url: string,
options?: NetworkRequestOptions
): Promise<NetworkResponse<T>> {
const request: AxiosRequestConfig = {
method: HttpMethod.GET,
url: url,
headers: options && options.headers,
};
const response = await axios(request);
return {
headers: response.headers,
body: response.data as T,
status: response.status,
};
}
/**
* Http Post request
* @param url
* @param options
*/
async sendPostRequestAsync<T>(
url: string,
options?: NetworkRequestOptions
): Promise<NetworkResponse<T>> {
const request: AxiosRequestConfig = {
method: HttpMethod.POST,
url: url,
data: (options && options.body) || "",
headers: options && options.headers,
};
const response = await axios(request);
return {
headers: response.headers,
body: response.data as T,
status: response.status,
};
}
}
| /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import {
INetworkModule,
NetworkRequestOptions,
NetworkResponse,
} from "@azure/msal-common";
import { HttpMethod } from "../utils/Constants";
import axios, { AxiosRequestConfig } from "axios";
/**
* This class implements the API for network requests.
*/
export class HttpClient implements INetworkModule {
/**
* Http Get request
* @param url
* @param options
*/
async sendGetRequestAsync<T>(
url: string,
options?: NetworkRequestOptions
): Promise<NetworkResponse<T>> {
const request: AxiosRequestConfig = {
method: HttpMethod.GET,
url: url,
headers: options && options.headers,
validateStatus: () => true
};
const response = await axios(request);
return {
headers: response.headers,
body: response.data as T,
status: response.status,
};
}
/**
* Http Post request
* @param url
* @param options
*/
async sendPostRequestAsync<T>(
url: string,
options?: NetworkRequestOptions
): Promise<NetworkResponse<T>> {
const request: AxiosRequestConfig = {
method: HttpMethod.POST,
url: url,
data: (options && options.body) || "",
headers: options && options.headers,
validateStatus: () => true
};
const response = await axios(request);
return {
headers: response.headers,
body: response.data as T,
status: response.status,
};
}
}
| Set the validateStatus locally than globally for `axios` | Set the validateStatus locally than globally for `axios`
| TypeScript | mit | AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js | ---
+++
@@ -15,9 +15,6 @@
* This class implements the API for network requests.
*/
export class HttpClient implements INetworkModule {
- constructor() {
- axios.defaults.validateStatus = () => true;
- }
/**
* Http Get request
@@ -32,6 +29,7 @@
method: HttpMethod.GET,
url: url,
headers: options && options.headers,
+ validateStatus: () => true
};
const response = await axios(request);
@@ -56,6 +54,7 @@
url: url,
data: (options && options.body) || "",
headers: options && options.headers,
+ validateStatus: () => true
};
const response = await axios(request); |
2aa52f51dadd98c6cd7a750bd739e25cc7e63e1d | src/graphql/GraphQLCV.ts | src/graphql/GraphQLCV.ts | import {
GraphQLInputObjectType,
GraphQLList,
GraphQLObjectType,
GraphQLString,
} from 'graphql'
const MutableItemFields = {
title: { type: GraphQLString },
description: { type: GraphQLString },
when: { type: GraphQLString },
organization: { type: GraphQLString },
city: { type: GraphQLString },
}
export const GraphQLCVItem = new GraphQLObjectType({
name: 'CVItem',
fields: {
...MutableItemFields,
},
})
export const GraphQLCVItemInput = new GraphQLInputObjectType ({
name: 'CVItemInput',
fields: {
...MutableItemFields,
},
})
const MutableCVSectionFields = {
title: { type: GraphQLString },
}
export const GraphQLCVSection = new GraphQLObjectType({
name: 'CVSection',
fields: {
...MutableCVSectionFields,
items: { type: new GraphQLList(GraphQLCVItem) },
},
})
export const GraphQLCVSectionInput = new GraphQLInputObjectType({
name: 'CVSectionInput',
fields: {
...MutableCVSectionFields,
items: { type: new GraphQLList(GraphQLCVItemInput) },
},
})
export const GraphQLCV = new GraphQLObjectType({
name: 'CV',
fields: {
userId: { type: GraphQLString },
text: { type: GraphQLString },
sections: { type: new GraphQLList(GraphQLCVSection) },
},
})
export const GraphQLCVInput = new GraphQLInputObjectType({
name: 'CVInput',
fields: {
sections: { type: new GraphQLList(GraphQLCVSectionInput) },
},
})
| import {
GraphQLInputObjectType,
GraphQLList,
GraphQLObjectType,
GraphQLString,
} from 'graphql'
const MutableItemFields = {
title: { type: GraphQLString },
description: { type: GraphQLString },
when: { type: GraphQLString },
organization: { type: GraphQLString },
city: { type: GraphQLString },
}
export const GraphQLCVItem = new GraphQLObjectType({
name: 'CVItem',
fields: {
...MutableItemFields,
},
})
export const GraphQLCVItemInput = new GraphQLInputObjectType ({
name: 'CVItemInput',
fields: {
...MutableItemFields,
},
})
const MutableCVSectionFields = {
title: { type: GraphQLString },
}
export const GraphQLCVSection = new GraphQLObjectType({
name: 'CVSection',
fields: {
...MutableCVSectionFields,
items: { type: new GraphQLList(GraphQLCVItem) },
},
})
export const GraphQLCVSectionInput = new GraphQLInputObjectType({
name: 'CVSectionInput',
fields: {
...MutableCVSectionFields,
items: { type: new GraphQLList(GraphQLCVItemInput) },
},
})
export const GraphQLCV = new GraphQLObjectType({
name: 'CV',
fields: {
userId: { type: GraphQLString },
sections: { type: new GraphQLList(GraphQLCVSection) },
},
})
export const GraphQLCVInput = new GraphQLInputObjectType({
name: 'CVInput',
fields: {
sections: { type: new GraphQLList(GraphQLCVSectionInput) },
},
})
| Remove text field from CV | Remove text field from CV
| TypeScript | mit | studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord | ---
+++
@@ -51,7 +51,6 @@
name: 'CV',
fields: {
userId: { type: GraphQLString },
- text: { type: GraphQLString },
sections: { type: new GraphQLList(GraphQLCVSection) },
},
}) |
7697cd9e118f64580fc57b4742a99a4edc4ce297 | app/client/src/components/common/Input.tsx | app/client/src/components/common/Input.tsx | import { InputHTMLAttributes, memo, FC } from 'react'
import { FieldPath, UseFormReturn } from 'react-hook-form'
import styled from 'styled-components'
import { colors } from '../../theme'
import { FormValues } from '../../types/form'
const StyledInput = styled.input`
border: none;
background: ${colors.input};
padding: 1rem;
color: ${colors.white};
transition: all 0.2s ease;
border-radius: 10px;
font-size: 0.85rem;
&:focus {
outline: 0;
border-color: ${colors.primary};
box-shadow: 0 0 4px 1px ${colors.primary};
}
&::placeholder {
color: white;
opacity: 0;
}
`
export interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
formContext: UseFormReturn<FormValues>
name: FieldPath<FormValues>
}
export const Input: FC<InputProps> = memo(
({ formContext, name, ...inputProps }) => (
<StyledInput {...inputProps} {...formContext.register(name)} />
),
(prevProps, nextProps) =>
prevProps.formContext.formState.isDirty ===
nextProps.formContext.formState.isDirty
)
| import { InputHTMLAttributes, memo, FC } from 'react'
import { FieldPath, UseFormReturn } from 'react-hook-form'
import styled from 'styled-components'
import { colors } from '../../theme'
import { FormValues } from '../../types/form'
const StyledInput = styled.input`
border: none;
background: ${colors.input};
padding: 1rem;
color: ${colors.white};
transition: all 0.2s ease;
border-radius: 10px;
font-size: 0.85rem;
&:focus {
outline: 0;
border-color: ${colors.primary};
box-shadow: 0 0 4px 1px ${colors.primary};
&::placeholder {
color: #c0c5ce;
opacity: 0.3;
}
}
&::placeholder {
color: white;
opacity: 0;
}
`
export interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
formContext: UseFormReturn<FormValues>
name: FieldPath<FormValues>
}
export const Input: FC<InputProps> = memo(
({ formContext, name, ...inputProps }) => (
<StyledInput {...inputProps} {...formContext.register(name)} />
),
(prevProps, nextProps) =>
prevProps.formContext.formState.isDirty ===
nextProps.formContext.formState.isDirty
)
| Change placeholder styling on focus | Change placeholder styling on focus
| TypeScript | mit | saadq/latexresu.me,saadq/latexresu.me | ---
+++
@@ -17,6 +17,10 @@
outline: 0;
border-color: ${colors.primary};
box-shadow: 0 0 4px 1px ${colors.primary};
+ &::placeholder {
+ color: #c0c5ce;
+ opacity: 0.3;
+ }
}
&::placeholder { |
31c39f5f8650899449e3c480bc03c05616cb472e | backend/src/index.ts | backend/src/index.ts | import { GraphQLServer } from 'graphql-yoga';
import { prisma } from './generated/prisma-client';
import resolvers from './resolvers';
const server = new GraphQLServer({
typeDefs: 'src/schema.graphql',
resolvers,
context: req => ({
...req,
db: prisma,
}),
});
server.start(() => console.log('Server is running on http://localhost:4000'));
| import { GraphQLServer } from 'graphql-yoga';
import { prisma } from './generated/prisma-client';
import resolvers from './resolvers';
const express = require('express');
const server = new GraphQLServer({
typeDefs: 'src/schema.graphql',
resolvers,
context: req => ({
...req,
db: prisma,
}),
});
// The 'files' directory should be a docker volume, maybe in a dedicated container
server.express.use('/files', express.static('files'));
server.start(() => console.log('Server is running on http://localhost:4000'));
| Add express.static route to serve image files | Add express.static route to serve image files
| TypeScript | agpl-3.0 | iquabius/olimat,iquabius/olimat,iquabius/olimat | ---
+++
@@ -1,6 +1,7 @@
import { GraphQLServer } from 'graphql-yoga';
import { prisma } from './generated/prisma-client';
import resolvers from './resolvers';
+const express = require('express');
const server = new GraphQLServer({
typeDefs: 'src/schema.graphql',
@@ -11,4 +12,7 @@
}),
});
+// The 'files' directory should be a docker volume, maybe in a dedicated container
+server.express.use('/files', express.static('files'));
+
server.start(() => console.log('Server is running on http://localhost:4000')); |
26752f62c0e3ff9f802d542fb11e9127814556c1 | coffee-chats/src/main/webapp/src/components/LinkComponents.tsx | coffee-chats/src/main/webapp/src/components/LinkComponents.tsx | import React from "react";
import {Link, useRouteMatch} from "react-router-dom";
import {ListItem, ListItemText} from "@material-ui/core";
export function useRenderLink(to: string) {
return React.useMemo(
() => React.forwardRef(itemProps => <Link to={to} {...itemProps} />),
[to],
);
}
interface ListItemLinkProps {
to: string
primary: string
}
export function ListItemLink({to, primary}: ListItemLinkProps) {
const match = useRouteMatch(to)?.isExact;
const renderLink = useRenderLink(to);
return (
<ListItem button component={renderLink} selected={match}>
<ListItemText primary={primary} />
</ListItem>
);
}
| import React from "react";
import {Link, useRouteMatch} from "react-router-dom";
import {ListItem, ListItemText} from "@material-ui/core";
export function useRenderLink(to: string) {
return React.useMemo(
() => React.forwardRef<HTMLAnchorElement, React.ComponentPropsWithoutRef<"a">>((props, ref) => (
<Link to={to} ref={ref} {...props} />)
), [to]
);
}
interface ListItemLinkProps {
to: string
primary: string
}
export function ListItemLink({to, primary}: ListItemLinkProps) {
const match = useRouteMatch(to)?.isExact;
const renderLink = useRenderLink(to);
return (
<ListItem button component={renderLink} selected={match}>
<ListItemText primary={primary} />
</ListItem>
);
}
| Fix ref forwarding in useRenderLink | Fix ref forwarding in useRenderLink
| TypeScript | apache-2.0 | googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020 | ---
+++
@@ -4,8 +4,9 @@
export function useRenderLink(to: string) {
return React.useMemo(
- () => React.forwardRef(itemProps => <Link to={to} {...itemProps} />),
- [to],
+ () => React.forwardRef<HTMLAnchorElement, React.ComponentPropsWithoutRef<"a">>((props, ref) => (
+ <Link to={to} ref={ref} {...props} />)
+ ), [to]
);
}
|
229bd1056ac20fa5834cba569977a347395a709f | lib/model/GraphEntity.ts | lib/model/GraphEntity.ts | import {isPresent} from "../utils/core";
export type Persisted<T> = T & { id:string };
export type Peristable = { id?:string };
export function isPersisted<T extends Peristable>(entity:T | Persisted<T>):entity is Persisted<T> {
return isPresent(<any>entity.id);
}
export function assertPersisted<T extends Peristable>(entity:T | Persisted<T>) {
if (!isPersisted(entity)) {
throw new Error(`Expected entity to be persisted: ${entity}`);
}
} | import {isPresent} from "../utils/core";
export type Persisted<T> = T & { id:string };
export type PersistedAggregate<T> = {
[P in keyof T]: Persisted<T[P]>;
};
export type Peristable = { id?:string };
export function isPersisted<T extends Peristable>(entity:T | Persisted<T>):entity is Persisted<T> {
return isPresent(<any>entity.id);
}
export function assertPersisted<T extends Peristable>(entity:T | Persisted<T>) {
if (!isPersisted(entity)) {
throw new Error(`Expected entity to be persisted: ${entity}`);
}
} | Add mapped type for aggregate objects | Add mapped type for aggregate objects
| TypeScript | mit | robak86/neography | ---
+++
@@ -1,6 +1,11 @@
import {isPresent} from "../utils/core";
export type Persisted<T> = T & { id:string };
+export type PersistedAggregate<T> = {
+ [P in keyof T]: Persisted<T[P]>;
+};
+
+
export type Peristable = { id?:string };
export function isPersisted<T extends Peristable>(entity:T | Persisted<T>):entity is Persisted<T> { |
48d0f6b6c8cc41abec78fecb0c65f8787c63c6e6 | packages/components/components/contacts/ContactGroupLabels.tsx | packages/components/components/contacts/ContactGroupLabels.tsx | import React from 'react';
import { ContactGroup } from 'proton-shared/lib/interfaces/contacts/Contact';
import LabelStack, { LabelDescription } from '../labelStack/LabelStack';
interface Props {
contactGroups: ContactGroup[];
}
const ContactGroupLabels = ({ contactGroups }: Props) => {
const labels = contactGroups.reduce((acc: LabelDescription[], contactGroup: ContactGroup) => {
return contactGroup
? [
...acc,
{
name: contactGroup.Name,
color: contactGroup.Color,
title: contactGroup.Name,
},
]
: acc;
}, []);
return <LabelStack labels={labels} isStacked />;
};
export default ContactGroupLabels;
| import React, { MouseEvent } from 'react';
import { APPS } from 'proton-shared/lib/constants';
import { ContactGroup } from 'proton-shared/lib/interfaces/contacts/Contact';
import LabelStack, { LabelDescription } from '../labelStack/LabelStack';
import { useAppLink } from '../link';
interface Props {
contactGroups: ContactGroup[];
}
const ContactGroupLabels = ({ contactGroups }: Props) => {
const appLink = useAppLink();
const labels = contactGroups.reduce((acc: LabelDescription[], contactGroup: ContactGroup) => {
return contactGroup
? [
...acc,
{
name: contactGroup.Name,
color: contactGroup.Color,
title: contactGroup.Name,
onClick: (event: MouseEvent) => {
appLink(`/?contactGroupID=${contactGroup.ID}`, APPS.PROTONCONTACTS);
event.stopPropagation();
},
},
]
: acc;
}, []);
return <LabelStack labels={labels} isStacked />;
};
export default ContactGroupLabels;
| Add a link on the contact group label | [MAILWEB-1569] Add a link on the contact group label
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,12 +1,16 @@
-import React from 'react';
+import React, { MouseEvent } from 'react';
+import { APPS } from 'proton-shared/lib/constants';
import { ContactGroup } from 'proton-shared/lib/interfaces/contacts/Contact';
import LabelStack, { LabelDescription } from '../labelStack/LabelStack';
+import { useAppLink } from '../link';
interface Props {
contactGroups: ContactGroup[];
}
const ContactGroupLabels = ({ contactGroups }: Props) => {
+ const appLink = useAppLink();
+
const labels = contactGroups.reduce((acc: LabelDescription[], contactGroup: ContactGroup) => {
return contactGroup
? [
@@ -15,6 +19,10 @@
name: contactGroup.Name,
color: contactGroup.Color,
title: contactGroup.Name,
+ onClick: (event: MouseEvent) => {
+ appLink(`/?contactGroupID=${contactGroup.ID}`, APPS.PROTONCONTACTS);
+ event.stopPropagation();
+ },
},
]
: acc; |
969421fd0e73a46a1ce7fadfbfe5a91632f968f9 | types/multi-progress/index.d.ts | types/multi-progress/index.d.ts | // Type definitions for multi-progress 2.0
// Project: https://github.com/pitaj/multi-progress
// Definitions by: David Brett <https://github.com/DHBrett>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node"/>
import ProgressBar, { ProgressBarOptions } from '../progress';
import { Stream } from 'stream';
export default class MultiProgress {
/**
* Create a new @see MultiProgress with the given stream, or stderr by default
* @param stream A stream to write the progress bars to
*/
constructor(stream?: Stream)
/**
* Add a new bar
*/
newBar: (format: string, options: ProgressBarOptions) => ProgressBar;
/**
* Close all bars
*/
terminate: () => void;
/**
* Render the given progress bar
*/
move: (index: number) => void;
/**
* Move the bar indicated by index forward the number of steps indicated by value
*/
tick: (index: number, value: number, options?: any) => void;
/**
* Update the bar indicated by index to the value given
*/
update: (index: number, value: number, options?: any) => void;
}
| // Type definitions for multi-progress 2.0
// Project: https://github.com/pitaj/multi-progress
// Definitions by: David Brett <https://github.com/DHBrett>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node"/>
import ProgressBar, { ProgressBarOptions } from 'progress';
import { Stream } from 'stream';
export default class MultiProgress {
/**
* Create a new @see MultiProgress with the given stream, or stderr by default
* @param stream A stream to write the progress bars to
*/
constructor(stream?: Stream)
/**
* Add a new bar
*/
newBar: (format: string, options: ProgressBarOptions) => ProgressBar;
/**
* Close all bars
*/
terminate: () => void;
/**
* Render the given progress bar
*/
move: (index: number) => void;
/**
* Move the bar indicated by index forward the number of steps indicated by value
*/
tick: (index: number, value: number, options?: any) => void;
/**
* Update the bar indicated by index to the value given
*/
update: (index: number, value: number, options?: any) => void;
}
| Fix multi-progress reference to progress | Fix multi-progress reference to progress
| TypeScript | mit | markogresak/DefinitelyTyped,mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped | ---
+++
@@ -5,7 +5,7 @@
/// <reference types="node"/>
-import ProgressBar, { ProgressBarOptions } from '../progress';
+import ProgressBar, { ProgressBarOptions } from 'progress';
import { Stream } from 'stream';
export default class MultiProgress { |
e5357a99643c7600aa89a5d912fabfb7c7876ad6 | server/src/main/webapp/WEB-INF/rails/webpack/config/loaders/static-assets-loader.ts | server/src/main/webapp/WEB-INF/rails/webpack/config/loaders/static-assets-loader.ts | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {ConfigOptions} from "config/variables";
import webpack from "webpack";
export function getStaticAssetsLoader(configOptions: ConfigOptions): webpack.RuleSetRule {
return {
test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]",
outputPath: configOptions.production ? "media/" : "fonts/"
}
}
]
};
}
| /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {ConfigOptions} from "config/variables";
import webpack from "webpack";
export function getStaticAssetsLoader(configOptions: ConfigOptions): webpack.RuleSetRule {
return {
test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]",
outputPath: configOptions.production ? "media/" : "fonts/",
esModule: false
}
}
]
};
}
| Fix build that broke because of `file-loader` upgrade. | Fix build that broke because of `file-loader` upgrade.
| TypeScript | apache-2.0 | bdpiparva/gocd,bdpiparva/gocd,bdpiparva/gocd,bdpiparva/gocd,bdpiparva/gocd,bdpiparva/gocd | ---
+++
@@ -25,7 +25,8 @@
loader: "file-loader",
options: {
name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]",
- outputPath: configOptions.production ? "media/" : "fonts/"
+ outputPath: configOptions.production ? "media/" : "fonts/",
+ esModule: false
}
}
] |
92d8a8a1c5c726722c970bb94739d81e4664c6e7 | types/graphql-api-koa/index.d.ts | types/graphql-api-koa/index.d.ts | // Type definitions for graphql-api-koa 2.0
// Project: https://github.com/jaydenseric/graphql-api-koa#readme
// Definitions by: Mike Marcacci <https://github.com/mike-marcacci>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
import { GraphQLSchema } from "graphql";
import { Middleware, ParameterizedContext } from "koa";
interface ExecuteOptions {
schema?: GraphQLSchema;
rootValue?: any;
contextValue?: any;
fieldResolver?: any;
}
export const errorHandler: <StateT = any, CustomT = {}>() => Middleware<
StateT,
CustomT
>;
export const execute: <StateT = any, CustomT = {}>(
options: ExecuteOptions & {
override?: (ctx: ParameterizedContext<StateT, CustomT>) => ExecuteOptions;
}
) => Middleware<StateT, CustomT>;
| // Type definitions for graphql-api-koa 2.0
// Project: https://github.com/jaydenseric/graphql-api-koa#readme
// Definitions by: Mike Marcacci <https://github.com/mike-marcacci>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.4
import { GraphQLSchema } from "graphql";
import { Middleware, ParameterizedContext } from "koa";
interface ExecuteOptions {
schema?: GraphQLSchema;
rootValue?: any;
contextValue?: any;
fieldResolver?: any;
}
export const errorHandler: <StateT = any, CustomT = {}>() => Middleware<
StateT,
CustomT
>;
export const execute: <StateT = any, CustomT = {}>(
options: ExecuteOptions & {
override?: (ctx: ParameterizedContext<StateT, CustomT>) => ExecuteOptions;
}
) => Middleware<StateT, CustomT>;
| Use the latest TS version | Use the latest TS version
| TypeScript | mit | mcliment/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped | ---
+++
@@ -2,7 +2,7 @@
// Project: https://github.com/jaydenseric/graphql-api-koa#readme
// Definitions by: Mike Marcacci <https://github.com/mike-marcacci>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
-// TypeScript Version: 2.6
+// TypeScript Version: 3.4
import { GraphQLSchema } from "graphql";
import { Middleware, ParameterizedContext } from "koa"; |
024db7757c5a6ead015b6346293770a6d9cbe25b | tests/Renderer/Renderer.spec.ts | tests/Renderer/Renderer.spec.ts | import { Light } from '../../src/renderer/interfaces/Light';
import { Renderer } from '../../src/renderer/Renderer';
describe('Renderer', () => {
const maxLights: number = 3;
const light: Light = {
lightPosition: [1, 1, 1],
lightColor: [0, 0, 0],
lightIntensity: 256
}
describe('addLight', () => {
it('can append a new light to the `lights` array', () => {
const renderer: Renderer = new Renderer(800, 600, maxLights);
expect(renderer.getLights().length).toEqual(0);
renderer.addLight(light);
expect(renderer.getLights().length).toEqual(1);
});
});
describe('removeLight', () => {
it('can remove an existing light from the `lights` array', () => {
const renderer: Renderer = new Renderer(800, 600, maxLights);
renderer.addLight(light);
expect(renderer.getLights().length).toEqual(1);
renderer.removeLight(light);
expect(renderer.getLights().length).toEqual(0);
});
});
});
| import { Light } from '../../src/renderer/interfaces/Light';
import { Renderer } from '../../src/renderer/Renderer';
describe('Renderer', () => {
const maxLights: number = 3;
const light: Light = {
lightPosition: [1, 1, 1],
lightColor: [0, 0, 0],
lightIntensity: 256
}
xdescribe('addLight', () => {
it('can append a new light to the `lights` array', () => {
const renderer: Renderer = new Renderer(800, 600, maxLights);
expect(renderer.getLights().length).toEqual(0);
renderer.addLight(light);
expect(renderer.getLights().length).toEqual(1);
});
});
xdescribe('removeLight', () => {
it('can remove an existing light from the `lights` array', () => {
const renderer: Renderer = new Renderer(800, 600, maxLights);
renderer.addLight(light);
expect(renderer.getLights().length).toEqual(1);
renderer.removeLight(light);
expect(renderer.getLights().length).toEqual(0);
});
});
});
| Mark failing tests as pending. | Mark failing tests as pending.
| TypeScript | mit | calder-gl/calder,calder-gl/calder,calder-gl/calder,calder-gl/calder | ---
+++
@@ -9,7 +9,7 @@
lightIntensity: 256
}
- describe('addLight', () => {
+ xdescribe('addLight', () => {
it('can append a new light to the `lights` array', () => {
const renderer: Renderer = new Renderer(800, 600, maxLights);
expect(renderer.getLights().length).toEqual(0);
@@ -19,7 +19,7 @@
});
});
- describe('removeLight', () => {
+ xdescribe('removeLight', () => {
it('can remove an existing light from the `lights` array', () => {
const renderer: Renderer = new Renderer(800, 600, maxLights);
renderer.addLight(light); |
24cc79112d779f5327a2668efbc5f54bd253aec1 | src/utils/misc.ts | src/utils/misc.ts | import cheerio from 'cheerio';
import { ChapterInfo } from './types';
export function getChapterInfoFromAnchor(
el: Cheerio | CheerioElement,
domain: string = '',
): ChapterInfo {
const $el = cheerio(el);
return {
name: $el.text().trim(),
url: `${domain}${$el.attr('href')}`,
};
}
| import cheerio from 'cheerio';
import { ChapterInfo } from './types';
/**
* Extract chapter info from `<a href="CHAPTER_URL">CHAPTER_NAME</a>`
* @param el DOM element
* @param domain current domain
* @returns chapter info
*/
export function getChapterInfoFromAnchor(
el: Cheerio | CheerioElement,
domain: string = '',
): ChapterInfo {
const $el = cheerio(el);
return {
name: $el.text().trim(),
url: `${domain}${$el.attr('href')}`,
};
}
/**
* Eval
* @param func stringified function
*/
export function exec(func: string): any {
// eslint-disable-next-line no-new-func
return new Function(func)();
}
| Add `exec` method with tsdoc | Add `exec` method with tsdoc
| TypeScript | mit | HakurouKen/manga-downloader,HakurouKen/manga-downloader,HakurouKen/manga-downloader | ---
+++
@@ -1,6 +1,12 @@
import cheerio from 'cheerio';
import { ChapterInfo } from './types';
+/**
+ * Extract chapter info from `<a href="CHAPTER_URL">CHAPTER_NAME</a>`
+ * @param el DOM element
+ * @param domain current domain
+ * @returns chapter info
+ */
export function getChapterInfoFromAnchor(
el: Cheerio | CheerioElement,
domain: string = '',
@@ -11,3 +17,12 @@
url: `${domain}${$el.attr('href')}`,
};
}
+
+/**
+ * Eval
+ * @param func stringified function
+ */
+export function exec(func: string): any {
+ // eslint-disable-next-line no-new-func
+ return new Function(func)();
+} |
c1e8345eb1675866997baa3ef895fc1ad023a1b5 | src/provider/CircleCi.ts | src/provider/CircleCi.ts | import { Embed } from '../model/DiscordApi'
import { DirectParseProvider } from '../provider/BaseProvider'
/**
* https://circleci.com/docs/1.0/configuration/#notify
*/
export class CircleCi extends DirectParseProvider {
public getName(): string {
return 'CircleCi'
}
public async parseData(): Promise<void> {
this.setEmbedColor(0x343433)
const sha = this.body.payload.vcs_revision.slice(0, 7)
const compare = this.body.payload.compare
const subject = this.body.payload.subject
const committer = this.body.payload.committer_name
const outcome = this.body.payload.outcome
const buildNumber = this.body.payload.build_num
const buildUrl = this.body.payload.build_url
let description = `[${sha}]`
if (compare != null) {
description += `(${compare})`
}
if (subject != null) {
description += ' : ' + (subject.length > 48 ? `${subject.substring(0, 48)}\u2026` : subject)
}
if (outcome != null) {
description += '\n\n' + `**Outcome**: ${outcome}`
}
const embed: Embed = {
title: `Build #${buildNumber}`,
url: buildUrl,
description: description,
author: {
name: committer
}
}
this.addEmbed(embed)
}
}
| import { Embed } from '../model/DiscordApi'
import { DirectParseProvider } from '../provider/BaseProvider'
/**
* https://circleci.com/docs/1.0/configuration/#notify
*/
export class CircleCi extends DirectParseProvider {
public getName(): string {
return 'CircleCi'
}
public async parseData(): Promise<void> {
this.setEmbedColor(0x343433)
const sha = this.body.payload.vcs_revision
const compare = this.body.payload.compare
const subject = this.body.payload.subject
const committer = this.body.payload.committer_name
const outcome = this.body.payload.outcome
const buildNumber = this.body.payload.build_num
const buildUrl = this.body.payload.build_url
let description = ""
if (sha != null) {
description += `[${sha.slice(0, 7)}]`
}
if (compare != null) {
description += `(${compare})`
}
if (subject != null) {
description += ' : ' + (subject.length > 48 ? `${subject.substring(0, 48)}\u2026` : subject)
}
if (outcome != null) {
description += '\n\n' + `**Outcome**: ${outcome}`
}
const embed: Embed = {
title: `Build #${buildNumber}`,
url: buildUrl,
description: description,
author: {
name: committer
}
}
this.addEmbed(embed)
}
}
| Fix for vcs_revision sometimes being null | Fix for vcs_revision sometimes being null
| TypeScript | mit | Commit451/skyhook | ---
+++
@@ -13,7 +13,7 @@
public async parseData(): Promise<void> {
this.setEmbedColor(0x343433)
- const sha = this.body.payload.vcs_revision.slice(0, 7)
+ const sha = this.body.payload.vcs_revision
const compare = this.body.payload.compare
const subject = this.body.payload.subject
const committer = this.body.payload.committer_name
@@ -21,7 +21,10 @@
const buildNumber = this.body.payload.build_num
const buildUrl = this.body.payload.build_url
- let description = `[${sha}]`
+ let description = ""
+ if (sha != null) {
+ description += `[${sha.slice(0, 7)}]`
+ }
if (compare != null) {
description += `(${compare})`
} |
77b38d3f8f32964fc28a7b7268abd6d52fc28575 | front_end/core/common/Runnable.ts | front_end/core/common/Runnable.ts | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @interface
*/
/* eslint-disable rulesdir/no_underscored_properties */
export interface Runnable {
run(): Promise<void>;
}
type LateInitializationLoader = () => Promise<Runnable>;
export interface LateInitializableRunnableSetting {
id: string;
loadRunnable: LateInitializationLoader;
}
const registeredLateInitializationRunnables = new Map<string, LateInitializationLoader>();
export function registerLateInitializationRunnable(setting: LateInitializableRunnableSetting): void {
const {id, loadRunnable} = setting;
if (registeredLateInitializationRunnables.has(id)) {
throw new Error(`Duplicate late Initializable runnable id '${id}'`);
}
registeredLateInitializationRunnables.set(id, loadRunnable);
}
export function lateInitializationRunnables(): Array<LateInitializationLoader> {
return [...registeredLateInitializationRunnables.values()];
}
const registeredEarlyInitializationRunnables: (() => Runnable)[] = [];
export function registerEarlyInitializationRunnable(runnable: () => Runnable): void {
registeredEarlyInitializationRunnables.push(runnable);
}
export function earlyInitializationRunnables(): (() => Runnable)[] {
return registeredEarlyInitializationRunnables;
}
| // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @interface
*/
/* eslint-disable rulesdir/no_underscored_properties */
export interface Runnable {
run(): Promise<void>;
}
type LateInitializationLoader = () => Promise<Runnable>;
export interface LateInitializableRunnableSetting {
id: string;
loadRunnable: LateInitializationLoader;
}
const registeredLateInitializationRunnables = new Map<string, LateInitializationLoader>();
export function registerLateInitializationRunnable(setting: LateInitializableRunnableSetting): void {
const {id, loadRunnable} = setting;
if (registeredLateInitializationRunnables.has(id)) {
throw new Error(`Duplicate late Initializable runnable id '${id}'`);
}
registeredLateInitializationRunnables.set(id, loadRunnable);
}
export function maybeRemoveLateInitializationRunnable(runnableId: string): boolean {
return registeredLateInitializationRunnables.delete(runnableId);
}
export function lateInitializationRunnables(): Array<LateInitializationLoader> {
return [...registeredLateInitializationRunnables.values()];
}
const registeredEarlyInitializationRunnables: (() => Runnable)[] = [];
export function registerEarlyInitializationRunnable(runnable: () => Runnable): void {
registeredEarlyInitializationRunnables.push(runnable);
}
export function earlyInitializationRunnables(): (() => Runnable)[] {
return registeredEarlyInitializationRunnables;
}
| Add functionality to remove registered late initialization runnables | Add functionality to remove registered late initialization runnables
Bug: none
Change-Id: Ie44ba44c8845e050c402ebed5642908bb09eb5e8
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3020890
Reviewed-by: Tim van der Lippe <[email protected]>
Commit-Queue: Andres Olivares <[email protected]>
| TypeScript | bsd-3-clause | ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend | ---
+++
@@ -27,6 +27,10 @@
registeredLateInitializationRunnables.set(id, loadRunnable);
}
+export function maybeRemoveLateInitializationRunnable(runnableId: string): boolean {
+ return registeredLateInitializationRunnables.delete(runnableId);
+}
+
export function lateInitializationRunnables(): Array<LateInitializationLoader> {
return [...registeredLateInitializationRunnables.values()];
} |
01fd93e6794d0e238ab64a381de925a28b1ca900 | examples/official-storybook/stories/addon-controls.stories.tsx | examples/official-storybook/stories/addon-controls.stories.tsx | import React from 'react';
import Button from '../components/TsButton';
export default {
title: 'Addons/Controls',
component: Button,
argTypes: {
children: { control: 'text', name: 'Children' },
type: { control: 'text', name: 'Type' },
somethingElse: { control: 'object', name: 'Something Else' },
},
};
const Template = (args) => <Button {...args} />;
export const Basic = Template.bind({});
Basic.args = {
children: 'basic',
somethingElse: { a: 2 },
};
export const Action = Template.bind({});
Action.args = {
children: 'hmmm',
type: 'action',
somethingElse: { a: 4 },
};
export const CustomControls = Template.bind({});
CustomControls.argTypes = {
children: { table: { disable: true } },
type: { control: { disable: true } },
};
export const NoArgs = () => <Button>no args</Button>;
const hasCycle: any = {};
hasCycle.cycle = hasCycle;
export const CyclicArgs = Template.bind({});
CyclicArgs.args = {
hasCycle,
};
| import React from 'react';
import Button from '../components/TsButton';
export default {
title: 'Addons/Controls',
component: Button,
argTypes: {
children: { control: 'text', name: 'Children' },
type: { control: 'text', name: 'Type' },
somethingElse: { control: 'object', name: 'Something Else' },
},
};
const Template = (args) => <Button {...args} />;
export const Basic = Template.bind({});
Basic.args = {
children: 'basic',
somethingElse: { a: 2 },
};
export const Action = Template.bind({});
Action.args = {
children: 'hmmm',
type: 'action',
somethingElse: { a: 4 },
};
export const CustomControls = Template.bind({});
CustomControls.argTypes = {
children: { table: { disable: true } },
type: { control: { disable: true } },
};
export const NoArgs = () => <Button>no args</Button>;
const hasCycle: any = {};
hasCycle.cycle = hasCycle;
export const CyclicArgs = Template.bind({});
CyclicArgs.args = {
hasCycle,
};
CyclicArgs.parameters = {
chromatic: { disable: true },
};
| Disable chromatic for broken story | Disable chromatic for broken story
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook | ---
+++
@@ -41,3 +41,6 @@
CyclicArgs.args = {
hasCycle,
};
+CyclicArgs.parameters = {
+ chromatic: { disable: true },
+}; |
3cabfb63adbca7ca3fc591a26f5aeb7b278cc3b7 | src/lib/Components/ArtworkFilterOptions/MediumOptions.tsx | src/lib/Components/ArtworkFilterOptions/MediumOptions.tsx | import { MediumOption, OrderedMediumFilters } from "lib/Scenes/Collection/Helpers/FilterArtworksHelpers"
import { ArtworkFilterContext, useSelectedOptionsDisplay } from "lib/utils/ArtworkFiltersStore"
import React, { useContext } from "react"
import { NavigatorIOS } from "react-native"
import { SingleSelectOptionScreen } from "./SingleSelectOption"
interface MediumOptionsScreenProps {
navigator: NavigatorIOS
}
export const MediumOptionsScreen: React.SFC<MediumOptionsScreenProps> = ({ navigator }) => {
const { dispatch } = useContext(ArtworkFilterContext)
const filterType = "medium"
const selectedOptions = useSelectedOptionsDisplay()
const selectedOption = selectedOptions.find(option => option.filterType === filterType)?.value! as MediumOption
const selectOption = (option: MediumOption) => {
dispatch({ type: "selectFilters", payload: { value: option, filterType } })
}
return (
<SingleSelectOptionScreen
onSelect={selectOption}
filterHeaderText="Medium"
filterOptions={OrderedMediumFilters}
selectedOption={selectedOption}
navigator={navigator}
/>
)
}
| import { AggregateOption, FilterParamName, FilterType } from "lib/Scenes/Collection/Helpers/FilterArtworksHelpers"
import { ArtworkFilterContext, useSelectedOptionsDisplay } from "lib/utils/ArtworkFiltersStore"
import React, { useContext } from "react"
import { NavigatorIOS } from "react-native"
import { aggregationFromFilterType } from "../FilterModal"
import { SingleSelectOptionScreen } from "./SingleSelectOption"
interface MediumOptionsScreenProps {
navigator: NavigatorIOS
}
export const MediumOptionsScreen: React.SFC<MediumOptionsScreenProps> = ({ navigator }) => {
const { dispatch, aggregations } = useContext(ArtworkFilterContext)
const filterType = FilterType.medium
const aggregationName = aggregationFromFilterType(filterType)
const aggregation = aggregations!.filter(value => value.slice === aggregationName)[0]
const options = aggregation.counts.map(aggCount => {
return {
displayText: aggCount.name,
paramName: FilterParamName.medium,
paramValue: aggCount.value,
filterType,
}
})
const selectedOptions = useSelectedOptionsDisplay()
const selectedOption = selectedOptions.find(option => option.filterType === filterType)!
const selectOption = (option: AggregateOption) => {
dispatch({
type: "selectFilters",
payload: {
displayText: option.displayText,
paramValue: option.paramValue,
paramName: FilterParamName.medium,
filterType,
},
})
}
return (
<SingleSelectOptionScreen
onSelect={selectOption}
filterHeaderText="Medium"
filterOptions={options}
selectedOption={selectedOption}
navigator={navigator}
/>
)
}
| Convert mediums to aggregate filters | Convert mediums to aggregate filters
| TypeScript | mit | artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen | ---
+++
@@ -1,7 +1,8 @@
-import { MediumOption, OrderedMediumFilters } from "lib/Scenes/Collection/Helpers/FilterArtworksHelpers"
+import { AggregateOption, FilterParamName, FilterType } from "lib/Scenes/Collection/Helpers/FilterArtworksHelpers"
import { ArtworkFilterContext, useSelectedOptionsDisplay } from "lib/utils/ArtworkFiltersStore"
import React, { useContext } from "react"
import { NavigatorIOS } from "react-native"
+import { aggregationFromFilterType } from "../FilterModal"
import { SingleSelectOptionScreen } from "./SingleSelectOption"
interface MediumOptionsScreenProps {
@@ -9,22 +10,40 @@
}
export const MediumOptionsScreen: React.SFC<MediumOptionsScreenProps> = ({ navigator }) => {
- const { dispatch } = useContext(ArtworkFilterContext)
+ const { dispatch, aggregations } = useContext(ArtworkFilterContext)
- const filterType = "medium"
+ const filterType = FilterType.medium
+ const aggregationName = aggregationFromFilterType(filterType)
+ const aggregation = aggregations!.filter(value => value.slice === aggregationName)[0]
+ const options = aggregation.counts.map(aggCount => {
+ return {
+ displayText: aggCount.name,
+ paramName: FilterParamName.medium,
+ paramValue: aggCount.value,
+ filterType,
+ }
+ })
const selectedOptions = useSelectedOptionsDisplay()
- const selectedOption = selectedOptions.find(option => option.filterType === filterType)?.value! as MediumOption
+ const selectedOption = selectedOptions.find(option => option.filterType === filterType)!
- const selectOption = (option: MediumOption) => {
- dispatch({ type: "selectFilters", payload: { value: option, filterType } })
+ const selectOption = (option: AggregateOption) => {
+ dispatch({
+ type: "selectFilters",
+ payload: {
+ displayText: option.displayText,
+ paramValue: option.paramValue,
+ paramName: FilterParamName.medium,
+ filterType,
+ },
+ })
}
return (
<SingleSelectOptionScreen
onSelect={selectOption}
filterHeaderText="Medium"
- filterOptions={OrderedMediumFilters}
+ filterOptions={options}
selectedOption={selectedOption}
navigator={navigator}
/> |
d709cc4a3d8f1eeb3d8e76c0d2945e905c14f546 | test/testdeck/src/commands/cluster_commands/ProvisionCommand.ts | test/testdeck/src/commands/cluster_commands/ProvisionCommand.ts | import {Argv} from 'yargs'
import { ClusterFactory } from '../../ClusterManager'
import {Config} from '../../Config'
interface Opts {
config: string
}
class ProvisionCommand {
command = "provision"
describe = "Provision a cluster"
builder(yargs: Argv) {
return yargs
.option('config', {
describe: 'Cluster configuration location',
type: 'string'
})
}
async handler(opts: Opts) {
const config = await Config.Load('./config.yml')
const cluster = await ClusterFactory.CreateCluster(opts.config || config.clusterConfig, {
image: config.baseImage,
licenseFile: config.licenseFile
})
await cluster.startCluster()
}
}
module.exports = new ProvisionCommand()
| import {Argv} from 'yargs'
import { ClusterFactory } from '../../ClusterManager'
import {Config} from '../../Config'
interface Opts {
config: string
image: string
}
class ProvisionCommand {
command = "provision"
describe = "Provision a cluster"
builder(yargs: Argv) {
return yargs
.option('config', {
describe: 'Cluster configuration location',
type: 'string'
})
.option('image', {
describe: 'The Rundeck Docker image to use instead of the default',
type: 'string'
})
}
async handler(opts: Opts) {
const config = await Config.Load('./config.yml')
const cluster = await ClusterFactory.CreateCluster(opts.config || config.clusterConfig, {
image: opts.image || config.baseImage,
licenseFile: config.licenseFile
})
await cluster.startCluster()
}
}
module.exports = new ProvisionCommand()
| Add image option to provision | Add image option to provision
| TypeScript | apache-2.0 | rundeck/rundeck,variacode/rundeck,rundeck/rundeck,rundeck/rundeck,rundeck/rundeck,variacode/rundeck,variacode/rundeck,variacode/rundeck,variacode/rundeck,rundeck/rundeck | ---
+++
@@ -6,6 +6,7 @@
interface Opts {
config: string
+ image: string
}
class ProvisionCommand {
@@ -18,12 +19,16 @@
describe: 'Cluster configuration location',
type: 'string'
})
+ .option('image', {
+ describe: 'The Rundeck Docker image to use instead of the default',
+ type: 'string'
+ })
}
async handler(opts: Opts) {
const config = await Config.Load('./config.yml')
const cluster = await ClusterFactory.CreateCluster(opts.config || config.clusterConfig, {
- image: config.baseImage,
+ image: opts.image || config.baseImage,
licenseFile: config.licenseFile
})
|
9722c6fce0115a476bc3cbbf600d5cb5e2634eb5 | directives/vaadin-date-picker.ts | directives/vaadin-date-picker.ts | import {Directive, ElementRef, Output, HostListener, EventEmitter} from 'angular2/core';
@Directive({selector: 'vaadin-date-picker'})
export class VaadinDatePicker {
@Output() _selectedDateChange: EventEmitter<any> = new EventEmitter(false);
@HostListener('selected-date-changed', ['$event.detail.value'])
_selectedDatechanged(value) {
this._selectedDateChange.emit(value);
}
@Output() valueChange: EventEmitter<any> = new EventEmitter(false);
@HostListener('value-changed', ['$event.detail.value'])
valuechanged(value) {
this.valueChange.emit(value);
}
@Output() invalidChange: EventEmitter<any> = new EventEmitter(false);
@HostListener('invalid-changed', ['$event.detail.value'])
invalidchanged(value) {
this.invalidChange.emit(value);
}
constructor(el: ElementRef) {
if (!Polymer.isInstance(el.nativeElement)) {
Polymer.Base.importHref('bower_components/vaadin-date-picker/vaadin-date-picker.html')
}
}
}
| import {Directive, ElementRef, Output, HostListener, EventEmitter} from 'angular2/core';
declare var Polymer;
@Directive({selector: 'vaadin-date-picker'})
export class VaadinDatePicker {
private element;
@Output() valueChange: EventEmitter<any> = new EventEmitter(false);
@HostListener('value-changed', ['$event.detail.value'])
valuechanged(value) {
if (value) {
this.valueChange.emit(value);
this.element.fire('input');
}
}
@Output() invalidChange: EventEmitter<any> = new EventEmitter(false);
@HostListener('invalid-changed', ['$event.detail.value'])
invalidchanged(value) {
this.invalidChange.emit(value);
}
onImport(e) {
this.element.$$('paper-input-container').addEventListener('blur', () => {
if (!this.element.opened && !this.element._opened) {
this.element.fire('blur');
}
});
}
constructor(el: ElementRef) {
this.element = el.nativeElement;
if (!Polymer.isInstance(el.nativeElement)) {
Polymer.Base.importHref('bower_components/vaadin-date-picker/vaadin-date-picker.html', this.onImport.bind(this));
}
}
}
| Update Angular2 directive with ngControl support | Update Angular2 directive with ngControl support
| TypeScript | apache-2.0 | vaadin/vaadin-date-picker,vaadin/vaadin-date-picker | ---
+++
@@ -1,30 +1,38 @@
import {Directive, ElementRef, Output, HostListener, EventEmitter} from 'angular2/core';
+declare var Polymer;
@Directive({selector: 'vaadin-date-picker'})
+export class VaadinDatePicker {
-export class VaadinDatePicker {
-
- @Output() _selectedDateChange: EventEmitter<any> = new EventEmitter(false);
- @HostListener('selected-date-changed', ['$event.detail.value'])
- _selectedDatechanged(value) {
- this._selectedDateChange.emit(value);
- }
-
+ private element;
+
@Output() valueChange: EventEmitter<any> = new EventEmitter(false);
@HostListener('value-changed', ['$event.detail.value'])
valuechanged(value) {
- this.valueChange.emit(value);
+ if (value) {
+ this.valueChange.emit(value);
+ this.element.fire('input');
+ }
}
-
+
@Output() invalidChange: EventEmitter<any> = new EventEmitter(false);
@HostListener('invalid-changed', ['$event.detail.value'])
invalidchanged(value) {
this.invalidChange.emit(value);
}
-
+
+ onImport(e) {
+ this.element.$$('paper-input-container').addEventListener('blur', () => {
+ if (!this.element.opened && !this.element._opened) {
+ this.element.fire('blur');
+ }
+ });
+ }
+
constructor(el: ElementRef) {
+ this.element = el.nativeElement;
if (!Polymer.isInstance(el.nativeElement)) {
- Polymer.Base.importHref('bower_components/vaadin-date-picker/vaadin-date-picker.html')
+ Polymer.Base.importHref('bower_components/vaadin-date-picker/vaadin-date-picker.html', this.onImport.bind(this));
}
}
} |
cabaffbc473f9a8c133f5d3d7f749a3cc3e5a7e4 | src/model/Grid.ts | src/model/Grid.ts | import { Cell } from './Cell'
import { Settings } from './Settings'
export class Grid {
private constructor() {
for (let rowIndex = 0; rowIndex < Settings.instance.rows; rowIndex++) {
for (let columnIndex = 0; columnIndex < Settings.instance.columns; columnIndex++) {
let cellToTheLeft: Cell | undefined
if (columnIndex === 0) {
cellToTheLeft = undefined
}
else {
cellToTheLeft = this.cells[this.cells.length - 1]
}
const cell = new Cell(rowIndex, columnIndex, cellToTheLeft)
this.cells.push(cell)
}
}
}
private static _instance: Grid
public static get instance(): Grid {
if (this._instance === undefined) {
this._instance = new Grid()
}
return this._instance
}
public readonly cells: Array<Cell> = []
} | import { computed } from 'mobx'
import { Cell } from './Cell'
import { Settings } from './Settings'
export class Grid {
private constructor() {
}
private static _instance: Grid
public static get instance(): Grid {
if (this._instance === undefined) {
this._instance = new Grid()
}
return this._instance
}
@computed
public get cells(): ReadonlyArray<Cell> {
const cells: Array<Cell> = []
for (let rowIndex = 0; rowIndex < Settings.instance.rows; rowIndex++) {
for (let columnIndex = 0; columnIndex < Settings.instance.columns; columnIndex++) {
let cellToTheLeft: Cell | undefined
if (columnIndex === 0) {
cellToTheLeft = undefined
}
else {
cellToTheLeft = cells[cells.length - 1]
}
const cell = new Cell(rowIndex, columnIndex, cellToTheLeft)
cells.push(cell)
}
}
return cells
}
} | Make cells a computed value | Make cells a computed value
| TypeScript | mit | janaagaard75/desert-walk,janaagaard75/desert-walk | ---
+++
@@ -1,22 +1,10 @@
+import { computed } from 'mobx'
+
import { Cell } from './Cell'
import { Settings } from './Settings'
export class Grid {
private constructor() {
- for (let rowIndex = 0; rowIndex < Settings.instance.rows; rowIndex++) {
- for (let columnIndex = 0; columnIndex < Settings.instance.columns; columnIndex++) {
- let cellToTheLeft: Cell | undefined
- if (columnIndex === 0) {
- cellToTheLeft = undefined
- }
- else {
- cellToTheLeft = this.cells[this.cells.length - 1]
- }
-
- const cell = new Cell(rowIndex, columnIndex, cellToTheLeft)
- this.cells.push(cell)
- }
- }
}
private static _instance: Grid
@@ -29,5 +17,24 @@
return this._instance
}
- public readonly cells: Array<Cell> = []
+ @computed
+ public get cells(): ReadonlyArray<Cell> {
+ const cells: Array<Cell> = []
+ for (let rowIndex = 0; rowIndex < Settings.instance.rows; rowIndex++) {
+ for (let columnIndex = 0; columnIndex < Settings.instance.columns; columnIndex++) {
+ let cellToTheLeft: Cell | undefined
+ if (columnIndex === 0) {
+ cellToTheLeft = undefined
+ }
+ else {
+ cellToTheLeft = cells[cells.length - 1]
+ }
+
+ const cell = new Cell(rowIndex, columnIndex, cellToTheLeft)
+ cells.push(cell)
+ }
+ }
+
+ return cells
+ }
} |
d2f42e8cd237e339223e785f9ef9aaa46e260750 | demo/src/app/components/radiobutton/radiobuttondemo-dataproperties.json.ts | demo/src/app/components/radiobutton/radiobuttondemo-dataproperties.json.ts | /**
* Created by William on 23/06/2017.
*/
export const dataProperties = [
{
name: "iconBefore",
type: "string",
default: "null",
description: "Create an icon Before the Input.",
options: "ion-printer | fa fa-home | any"
},
{
name: "iconAfter",
type: "string",
default: "null",
description: "Create an icon After the Input.",
options: "ion-printer | fa fa-home | any"
},
{
name: "label",
type: "string",
default: "null",
description: "Create a label together with Input Element",
options: "Any Text"
},
{
name: "labelPlacement",
type: "string",
default: "left",
description: "Label Position",
options: "top | left"
},
{
name: "clearButton",
type: "boolean",
default: "false",
description: "Display an icon to clear any Input Value",
options: "Any Text"
},
{
name: "disabled",
type: "boolean",
default: "false",
description: "Display an input with not selectable text (disabled)",
options: "Any Text"
},
{
name: "readonly",
type: "boolean",
default: "false",
description: "Display an input with selectable text (only read)",
options: "Any Text"
},
{
name: "placeholder",
type: "string",
default: "null",
description: "Display a help text on Input",
options: "Any Text"
},
{
name: "textBefore",
type: "string",
default: "null",
description: "Display a text Before the Input",
options: "Any Text"
}
,
{
name: "textAfter",
type: "string",
default: "null",
description: "Display a text After the Input",
options: "Any Text"
}
];
| /**
* Created by William on 23/06/2017.
*/
export const dataProperties = [
{
name: "label",
type: "string",
default: "null",
description: "Label of Radio Button",
options: "any text"
},
{
name: "value",
type: "string | number",
default: "null",
description: "Value of Radio Button that going be returned to model",
options: "any text"
},
{
name: "nameGroup",
type: "string",
default: "null",
description: "Name of group of Radio Button",
options: "Any Text"
},
{
name: "orientation",
type: "string",
default: "horizontal",
description: "Orientation of the Radios",
options: "vertical | horizontal"
}
];
| Change docs of radio button | docs(showcase): Change docs of radio button
| TypeScript | mit | TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui | ---
+++
@@ -3,74 +3,31 @@
*/
export const dataProperties = [
{
- name: "iconBefore",
- type: "string",
- default: "null",
- description: "Create an icon Before the Input.",
- options: "ion-printer | fa fa-home | any"
- },
- {
- name: "iconAfter",
- type: "string",
- default: "null",
- description: "Create an icon After the Input.",
- options: "ion-printer | fa fa-home | any"
- },
- {
name: "label",
type: "string",
default: "null",
- description: "Create a label together with Input Element",
+ description: "Label of Radio Button",
+ options: "any text"
+ },
+ {
+ name: "value",
+ type: "string | number",
+ default: "null",
+ description: "Value of Radio Button that going be returned to model",
+ options: "any text"
+ },
+ {
+ name: "nameGroup",
+ type: "string",
+ default: "null",
+ description: "Name of group of Radio Button",
options: "Any Text"
},
{
- name: "labelPlacement",
+ name: "orientation",
type: "string",
- default: "left",
- description: "Label Position",
- options: "top | left"
- },
- {
- name: "clearButton",
- type: "boolean",
- default: "false",
- description: "Display an icon to clear any Input Value",
- options: "Any Text"
- },
- {
- name: "disabled",
- type: "boolean",
- default: "false",
- description: "Display an input with not selectable text (disabled)",
- options: "Any Text"
- },
- {
- name: "readonly",
- type: "boolean",
- default: "false",
- description: "Display an input with selectable text (only read)",
- options: "Any Text"
- },
- {
- name: "placeholder",
- type: "string",
- default: "null",
- description: "Display a help text on Input",
- options: "Any Text"
- },
- {
- name: "textBefore",
- type: "string",
- default: "null",
- description: "Display a text Before the Input",
- options: "Any Text"
- }
- ,
- {
- name: "textAfter",
- type: "string",
- default: "null",
- description: "Display a text After the Input",
- options: "Any Text"
+ default: "horizontal",
+ description: "Orientation of the Radios",
+ options: "vertical | horizontal"
}
]; |
cfc03b7e6e0d87665ad95d70cc151d75d2fcb4fc | src/app/app.component.spec.ts | src/app/app.component.spec.ts | import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { HspApiService } from './hsp-api.service';
import { ResourceService } from './national_rail/resource.service';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common'
describe('AppComponent', function () {
let de: DebugElement;
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
// Configure the test bed
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ],
imports: [ AppModule ],
providers: [
{provide: APP_BASE_HREF, useValue: '/'}
]
})
.compileComponents();
}));
// Create the component under test
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('h1'));
});
// Test component created
it('should create component', () => expect(comp).toBeDefined() );
// Test title
it('should have expected <h1> text', () => {
fixture.detectChanges();
const h1 = de.nativeElement;
expect(h1.innerText).toMatch(/Late Mate/i,
'<h1> should say something about "Late Mate"');
});
});
| import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { HspApiService } from './hsp-api.service';
import { ResourceService } from './national_rail/resource.service';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common'
describe('AppComponent', function () {
let de: DebugElement;
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
// Configure the test bed
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ],
imports: [ AppModule ],
providers: [
{provide: APP_BASE_HREF, useValue: '/'}
]
})
.compileComponents();
}));
// Create the component under test
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('.title'));
});
// Test component created
it('should create component', () => expect(comp).toBeDefined() );
// Test title
it('should have expected <h1> text', () => {
fixture.detectChanges();
const h1 = de.nativeElement;
expect(h1.innerText).toMatch(/Late Mate/i,
'<h1> should say something about "Late Mate"');
});
});
| Fix test by updating css selector | Fix test by updating css selector
| TypeScript | mit | briggySmalls/late-train-mate,briggySmalls/late-train-mate,briggySmalls/late-train-mate | ---
+++
@@ -29,7 +29,7 @@
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
- de = fixture.debugElement.query(By.css('h1'));
+ de = fixture.debugElement.query(By.css('.title'));
});
// Test component created |
34d70ad8958bd74204c032ff85b1f10b8cf89e46 | frontend/src/component/feedback/FeedbackCES/sendFeedbackInput.ts | frontend/src/component/feedback/FeedbackCES/sendFeedbackInput.ts | import { IFeedbackCESForm } from 'component/feedback/FeedbackCES/FeedbackCESForm';
interface IFeedbackEndpointRequestBody {
source: 'app' | 'app:segments';
data: {
score: number;
comment?: string;
customerType?: 'open source' | 'paying';
openedManually?: boolean;
currentPage?: string;
};
}
export const sendFeedbackInput = async (
form: Partial<IFeedbackCESForm>
): Promise<void> => {
if (!form.score) {
return;
}
const body: IFeedbackEndpointRequestBody = {
source: 'app:segments',
data: {
score: form.score,
comment: form.comment,
currentPage: form.path,
openedManually: false,
customerType: 'paying',
},
};
await fetch(
'https://europe-west3-docs-feedback-v1.cloudfunctions.net/function-1',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}
);
};
| import { IFeedbackCESForm } from 'component/feedback/FeedbackCES/FeedbackCESForm';
interface IFeedbackEndpointRequestBody {
source: 'app' | 'app:segments';
data: {
score: number;
comment?: string;
customerType?: 'open source' | 'paying';
openedManually?: boolean;
currentPage?: string;
};
}
export const sendFeedbackInput = async (
form: Partial<IFeedbackCESForm>
): Promise<void> => {
if (!form.score) {
return;
}
const body: IFeedbackEndpointRequestBody = {
source: 'app:segments',
data: {
score: form.score,
comment: form.comment,
currentPage: form.path,
openedManually: false,
customerType: 'paying',
},
};
await fetch(
'https://europe-west3-metrics-304612.cloudfunctions.net/docs-app-feedback',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}
);
};
| Update target URL for sending feedback input | chore: Update target URL for sending feedback input
| TypeScript | apache-2.0 | Unleash/unleash,Unleash/unleash,Unleash/unleash,Unleash/unleash | ---
+++
@@ -30,7 +30,7 @@
};
await fetch(
- 'https://europe-west3-docs-feedback-v1.cloudfunctions.net/function-1',
+ 'https://europe-west3-metrics-304612.cloudfunctions.net/docs-app-feedback',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' }, |
402133ad4944da0f11d69595f159bb7a3d52b05d | projects/hslayers/src/components/add-data/common/add-data-url.component.ts | projects/hslayers/src/components/add-data/common/add-data-url.component.ts | import {Component, EventEmitter, Input, Output} from '@angular/core';
import {HsHistoryListService} from '../../../common/history-list/history-list.service';
@Component({
selector: 'hs-add-data-common-url',
templateUrl: './add-data-url.directive.html',
})
export class HsAddDataUrlComponent {
items;
what;
@Input() type: any; // @type'; TODO: comes from another scope
@Input() url: any;
@Output() urlChange = new EventEmitter<any>();
@Input() connect: any; //'=connect'; TODO: comes from another scope
//field: '=field'; TODO: some AngularJS stuff?
constructor(private historyListService: HsHistoryListService) {
this.items = this.historyListService.readSourceHistory(this.what);
}
change(): void {
this.urlChange.emit(this.url);
}
historySelected(url): void {
this.url = url;
this.change();
}
}
| import {Component, EventEmitter, Input, Output} from '@angular/core';
import {HsHistoryListService} from '../../../common/history-list/history-list.service';
@Component({
selector: 'hs-add-data-common-url',
templateUrl: './add-data-url.directive.html',
})
export class HsAddDataUrlComponent {
items;
what;
@Input() type: any; // @type'; TODO: comes from another scope
@Input() url: any;
@Output() urlChange = new EventEmitter<any>();
@Input() connect: any; //'=connect'; TODO: comes from another scope
//field: '=field'; TODO: some AngularJS stuff?
constructor(private historyListService: HsHistoryListService) {
this.items = this.historyListService.readSourceHistory(this.what);
}
change(): void {
this.urlChange.emit(this.url.trim());
}
historySelected(url): void {
this.url = url;
this.change();
}
}
| Trim external source url before data request | fix: Trim external source url before data request
| TypeScript | mit | hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng | ---
+++
@@ -21,7 +21,7 @@
}
change(): void {
- this.urlChange.emit(this.url);
+ this.urlChange.emit(this.url.trim());
}
historySelected(url): void { |
8572664c6c7674c31750d94754c6e1309251fe10 | extensions/typescript-language-features/src/utils/fileSchemes.ts | extensions/typescript-language-features/src/utils/fileSchemes.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export const file = 'file';
export const untitled = 'untitled';
export const git = 'git';
/** Live share scheme */
export const vsls = 'vsls';
export const walkThroughSnippet = 'walkThroughSnippet';
export const semanticSupportedSchemes = [
file,
untitled,
walkThroughSnippet,
];
/**
* File scheme for which JS/TS language feature should be disabled
*/
export const disabledSchemes = new Set([
git,
vsls
]);
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export const file = 'file';
export const untitled = 'untitled';
export const git = 'git';
/** Live share scheme */
export const vsls = 'vsls';
export const walkThroughSnippet = 'walkThroughSnippet';
export const vscodeNotebookCell = 'vscode-notebook-cell';
export const semanticSupportedSchemes = [
file,
untitled,
walkThroughSnippet,
vscodeNotebookCell,
];
/**
* File scheme for which JS/TS language feature should be disabled
*/
export const disabledSchemes = new Set([
git,
vsls
]);
| Enable semantic features (such as error reporting) in JS/TS notebook cells | Enable semantic features (such as error reporting) in JS/TS notebook cells
| TypeScript | mit | eamodio/vscode,Microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,Microsoft/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Microsoft/vscode | ---
+++
@@ -9,11 +9,13 @@
/** Live share scheme */
export const vsls = 'vsls';
export const walkThroughSnippet = 'walkThroughSnippet';
+export const vscodeNotebookCell = 'vscode-notebook-cell';
export const semanticSupportedSchemes = [
file,
untitled,
walkThroughSnippet,
+ vscodeNotebookCell,
];
/** |
7e4efa6aa078c651afc07a381632c5999dde8d45 | src/vs/workbench/contrib/terminal/common/terminalExtensionPoints.contribution.ts | src/vs/workbench/contrib/terminal/common/terminalExtensionPoints.contribution.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITerminalContributionService, TerminalContributionService } from './terminalExtensionPoints';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
registerSingleton(ITerminalContributionService, TerminalContributionService, true);
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { ITerminalContributionService, TerminalContributionService } from 'vs/workbench/contrib/terminal/common/terminalExtensionPoints';
registerSingleton(ITerminalContributionService, TerminalContributionService, true);
| Fix a relative import warning | Fix a relative import warning
| TypeScript | mit | eamodio/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode | ---
+++
@@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
-import { ITerminalContributionService, TerminalContributionService } from './terminalExtensionPoints';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
+import { ITerminalContributionService, TerminalContributionService } from 'vs/workbench/contrib/terminal/common/terminalExtensionPoints';
registerSingleton(ITerminalContributionService, TerminalContributionService, true); |
e0e08b61a2b7544147621e5b58d0f11ec8d2862e | app/src/lib/open-shell.ts | app/src/lib/open-shell.ts | import { spawn } from 'child_process'
import { platform } from 'os'
class Command {
public name: string
public args: string[]
}
/** Opens a shell setting the working directory to fullpath. If a shell is not specified, OS defaults are used. */
export function openShell(fullPath: string, shell?: string) {
const currentPlatform = platform()
const command = new Command
switch (currentPlatform) {
case 'darwin': {
command.name = 'open'
command.args = [ '-a', shell || 'Terminal', fullPath ]
break
}
case 'win32': {
command.name = 'START'
command.args = [ shell || 'cmd', '/D', `"${fullPath}"` , 'title', 'GitHub Desktop' ]
break
}
}
spawn(command.name, command.args, { 'shell' : true })
}
| import { spawn } from 'child_process'
/** Opens a shell setting the working directory to fullpath. If a shell is not specified, OS defaults are used. */
export function openShell(fullPath: string, shell?: string) {
let commandName: string = ''
let commandArgs: string[] = []
if ( __DARWIN__) {
commandName = 'open'
commandArgs = [ '-a', shell || 'Terminal', fullPath ]
}
else if (__WIN32__) {
commandName = 'START'
commandArgs = [ shell || 'cmd', '/D', `"${fullPath}"` , 'title', 'GitHub Desktop' ]
}
spawn(commandName, commandArgs, { 'shell' : true })
}
| Use global defaults and remove Command class in favor of local variables | Use global defaults and remove Command class in favor of local variables
| TypeScript | mit | artivilla/desktop,gengjiawen/desktop,artivilla/desktop,kactus-io/kactus,shiftkey/desktop,say25/desktop,desktop/desktop,BugTesterTest/desktops,desktop/desktop,BugTesterTest/desktops,BugTesterTest/desktops,hjobrien/desktop,kactus-io/kactus,BugTesterTest/desktops,shiftkey/desktop,j-f1/forked-desktop,gengjiawen/desktop,j-f1/forked-desktop,j-f1/forked-desktop,gengjiawen/desktop,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,hjobrien/desktop,kactus-io/kactus,hjobrien/desktop,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,desktop/desktop,say25/desktop,gengjiawen/desktop,artivilla/desktop,hjobrien/desktop,say25/desktop | ---
+++
@@ -1,28 +1,18 @@
import { spawn } from 'child_process'
-import { platform } from 'os'
-
-class Command {
- public name: string
- public args: string[]
-}
/** Opens a shell setting the working directory to fullpath. If a shell is not specified, OS defaults are used. */
export function openShell(fullPath: string, shell?: string) {
- const currentPlatform = platform()
- const command = new Command
+ let commandName: string = ''
+ let commandArgs: string[] = []
- switch (currentPlatform) {
- case 'darwin': {
- command.name = 'open'
- command.args = [ '-a', shell || 'Terminal', fullPath ]
- break
- }
- case 'win32': {
- command.name = 'START'
- command.args = [ shell || 'cmd', '/D', `"${fullPath}"` , 'title', 'GitHub Desktop' ]
- break
- }
+ if ( __DARWIN__) {
+ commandName = 'open'
+ commandArgs = [ '-a', shell || 'Terminal', fullPath ]
+ }
+ else if (__WIN32__) {
+ commandName = 'START'
+ commandArgs = [ shell || 'cmd', '/D', `"${fullPath}"` , 'title', 'GitHub Desktop' ]
}
- spawn(command.name, command.args, { 'shell' : true })
+ spawn(commandName, commandArgs, { 'shell' : true })
} |
94dc3a736e7868c53e0348c8c916564e74c32683 | app/core/map.ts | app/core/map.ts | // Enum for the kind of map
export type MapType = City | Square;
interface City { kind: "city"; }
interface Square { kind: "square"; }
// Map class
export class Map {
constructor(
private id: number,
private height: number,
private width: number,
private mapType: MapType,
private title?: string,
private owner?: number,
private graphics?: string,
private hash?: string,
private dateCreation?: string,
) {}
} | // Enum for the kind of map
export type MapType = City | Square;
interface City { kind: "city"; }
interface Square { kind: "square"; }
// Map class
export class Map {
constructor(
private id: number,
private height: number,
private width: number,
private mapType: MapType,
private extent: string,
private title?: string,
private owner?: number,
private graphics?: string,
private hash?: string,
private dateCreation?: string,
) {}
} | Add extent field to the Map class | Add extent field to the Map class
| TypeScript | mit | ABAPlan/abaplan-core,ABAPlan/abaplan-core,ABAPlan/abaplan-core | ---
+++
@@ -10,6 +10,7 @@
private height: number,
private width: number,
private mapType: MapType,
+ private extent: string,
private title?: string,
private owner?: number,
private graphics?: string, |
c310e402216b17450add3111c0fa986a4b421819 | src/vs/workbench/contrib/webview/electron-browser/webviewCommands.ts | src/vs/workbench/contrib/webview/electron-browser/webviewCommands.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { WebviewTag } from 'electron';
import { Action2 } from 'vs/platform/actions/common/actions';
import * as nls from 'vs/nls';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { CATEGORIES } from 'vs/workbench/common/actions';
export class OpenWebviewDeveloperToolsAction extends Action2 {
constructor() {
super({
id: 'workbench.action.webview.openDeveloperTools',
title: { value: nls.localize('openToolsLabel', "Open Webview Developer Tools"), original: 'Open Webview Developer Tools' },
category: CATEGORIES.Developer,
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const elements = document.querySelectorAll('webview.ready');
for (let i = 0; i < elements.length; i++) {
try {
(elements.item(i) as WebviewTag).openDevTools();
} catch (e) {
console.error(e);
}
}
}
}
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { WebviewTag } from 'electron';
import * as nls from 'vs/nls';
import { Action2 } from 'vs/platform/actions/common/actions';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { CATEGORIES } from 'vs/workbench/common/actions';
export class OpenWebviewDeveloperToolsAction extends Action2 {
constructor() {
super({
id: 'workbench.action.webview.openDeveloperTools',
title: { value: nls.localize('openToolsLabel', "Open Webview Developer Tools"), original: 'Open Webview Developer Tools' },
category: CATEGORIES.Developer,
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const nativeHostService = accessor.get(INativeHostService);
const webviewElements = document.querySelectorAll('webview.ready');
for (const element of webviewElements) {
try {
(element as WebviewTag).openDevTools();
} catch (e) {
console.error(e);
}
}
const iframeWebviewElements = document.querySelectorAll('iframe.webview.ready');
if (iframeWebviewElements.length) {
console.info(nls.localize('iframeWebviewAlert', "Using standard dev tools to debug iframe based webview"));
nativeHostService.openDevTools();
}
}
}
| Enable webview developer tools command for iframe based webviews | Enable webview developer tools command for iframe based webviews
Iframe based webviews are debuggable/inspectable using the standard dev tools. They do not have their own dev tools window
| TypeScript | mit | microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,Microsoft/vscode,Microsoft/vscode | ---
+++
@@ -4,9 +4,10 @@
*--------------------------------------------------------------------------------------------*/
import { WebviewTag } from 'electron';
+import * as nls from 'vs/nls';
import { Action2 } from 'vs/platform/actions/common/actions';
-import * as nls from 'vs/nls';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
+import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { CATEGORIES } from 'vs/workbench/common/actions';
export class OpenWebviewDeveloperToolsAction extends Action2 {
@@ -21,13 +22,21 @@
}
async run(accessor: ServicesAccessor): Promise<void> {
- const elements = document.querySelectorAll('webview.ready');
- for (let i = 0; i < elements.length; i++) {
+ const nativeHostService = accessor.get(INativeHostService);
+
+ const webviewElements = document.querySelectorAll('webview.ready');
+ for (const element of webviewElements) {
try {
- (elements.item(i) as WebviewTag).openDevTools();
+ (element as WebviewTag).openDevTools();
} catch (e) {
console.error(e);
}
}
+
+ const iframeWebviewElements = document.querySelectorAll('iframe.webview.ready');
+ if (iframeWebviewElements.length) {
+ console.info(nls.localize('iframeWebviewAlert', "Using standard dev tools to debug iframe based webview"));
+ nativeHostService.openDevTools();
+ }
}
} |
a8e37a4b43398363fbe832bc47e5314853be96a9 | src/vs/platform/extensions/electron-main/directMainProcessExtensionHostStarter.ts | src/vs/platform/extensions/electron-main/directMainProcessExtensionHostStarter.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ExtensionHostStarter, IPartialLogService } from 'vs/platform/extensions/node/extensionHostStarter';
import { ILifecycleMainService } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
import { ILogService } from 'vs/platform/log/common/log';
export class DirectMainProcessExtensionHostStarter extends ExtensionHostStarter {
constructor(
@ILogService logService: IPartialLogService,
@ILifecycleMainService lifecycleMainService: ILifecycleMainService
) {
super(logService);
lifecycleMainService.onWillShutdown((e) => {
const exitPromises: Promise<void>[] = [];
for (const [, extHost] of this._extHosts) {
exitPromises.push(extHost.waitForExit(6000));
}
e.join(Promise.all(exitPromises).then(() => { }));
});
}
}
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService';
import { ExtensionHostStarter, IPartialLogService } from 'vs/platform/extensions/node/extensionHostStarter';
import { ILifecycleMainService } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
import { ILogService } from 'vs/platform/log/common/log';
export class DirectMainProcessExtensionHostStarter extends ExtensionHostStarter {
constructor(
@ILogService logService: IPartialLogService,
@ILifecycleMainService lifecycleMainService: ILifecycleMainService,
@IEnvironmentMainService environmentService: IEnvironmentMainService,
) {
super(logService);
lifecycleMainService.onWillShutdown((e) => {
if (environmentService.extensionTestsLocationURI) {
// extension testing => don't wait for graceful shutdown
for (const [, extHost] of this._extHosts) {
extHost.kill();
}
} else {
const exitPromises: Promise<void>[] = [];
for (const [, extHost] of this._extHosts) {
exitPromises.push(extHost.waitForExit(6000));
}
e.join(Promise.all(exitPromises).then(() => { }));
}
});
}
}
| Kill extension host processes immediately when doing extension test | Kill extension host processes immediately when doing extension test
| TypeScript | mit | eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode | ---
+++
@@ -3,6 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
+import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService';
import { ExtensionHostStarter, IPartialLogService } from 'vs/platform/extensions/node/extensionHostStarter';
import { ILifecycleMainService } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
import { ILogService } from 'vs/platform/log/common/log';
@@ -11,16 +12,24 @@
constructor(
@ILogService logService: IPartialLogService,
- @ILifecycleMainService lifecycleMainService: ILifecycleMainService
+ @ILifecycleMainService lifecycleMainService: ILifecycleMainService,
+ @IEnvironmentMainService environmentService: IEnvironmentMainService,
) {
super(logService);
lifecycleMainService.onWillShutdown((e) => {
- const exitPromises: Promise<void>[] = [];
- for (const [, extHost] of this._extHosts) {
- exitPromises.push(extHost.waitForExit(6000));
+ if (environmentService.extensionTestsLocationURI) {
+ // extension testing => don't wait for graceful shutdown
+ for (const [, extHost] of this._extHosts) {
+ extHost.kill();
+ }
+ } else {
+ const exitPromises: Promise<void>[] = [];
+ for (const [, extHost] of this._extHosts) {
+ exitPromises.push(extHost.waitForExit(6000));
+ }
+ e.join(Promise.all(exitPromises).then(() => { }));
}
- e.join(Promise.all(exitPromises).then(() => { }));
});
}
|
55e324044ba20b8292e1365003aefad034325501 | src/ngx-tree-select/src/module.ts | src/ngx-tree-select/src/module.ts | import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ItemPipe } from './pipes/item.pipe';
import { ModuleWithProviders, NgModule } from '@angular/core';
import { OffClickDirective } from './directives/off-click.directive';
import { TreeSelectComponent } from './components/tree-select.component';
import { TreeSelectDefaultOptions } from './models/tree-select-default-options';
import { TreeSelectItemComponent } from './components/tree-select-item.component';
@NgModule({
imports: [
CommonModule,
FormsModule
],
declarations: [
TreeSelectComponent,
TreeSelectItemComponent,
OffClickDirective,
ItemPipe
],
exports: [
TreeSelectComponent
]
})
export class NgxTreeSelectModule {
public static forRoot(options: TreeSelectDefaultOptions): ModuleWithProviders {
return {
ngModule: NgxTreeSelectModule,
providers: [
{ provide: TreeSelectDefaultOptions, useValue: options }
]
};
}
}
| import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ItemPipe } from './pipes/item.pipe';
import { ModuleWithProviders, NgModule } from '@angular/core';
import { OffClickDirective } from './directives/off-click.directive';
import { TreeSelectComponent } from './components/tree-select.component';
import { TreeSelectDefaultOptions } from './models/tree-select-default-options';
import { TreeSelectItemComponent } from './components/tree-select-item.component';
@NgModule({
imports: [
CommonModule,
FormsModule
],
declarations: [
TreeSelectComponent,
TreeSelectItemComponent,
OffClickDirective,
ItemPipe
],
exports: [
TreeSelectComponent
]
})
export class NgxTreeSelectModule {
public static forRoot(options: TreeSelectDefaultOptions): ModuleWithProviders<NgxTreeSelectModule> {
return {
ngModule: NgxTreeSelectModule,
providers: [
{ provide: TreeSelectDefaultOptions, useValue: options }
]
};
}
}
| Set ModuleWithProviders type (Angular 10+ support) | Set ModuleWithProviders type (Angular 10+ support)
From Angular 10 onward, to set a type to the ModuleWithProviders is now mandatory. With this simple alteration, the library becomes Angular 10+ supported. | TypeScript | mit | Crazyht/crazy-select,Crazyht/ngx-tree-select,Crazyht/ngx-tree-select,Crazyht/crazy-select,Crazyht/ngx-tree-select,Crazyht/crazy-select | ---
+++
@@ -24,7 +24,7 @@
})
export class NgxTreeSelectModule {
- public static forRoot(options: TreeSelectDefaultOptions): ModuleWithProviders {
+ public static forRoot(options: TreeSelectDefaultOptions): ModuleWithProviders<NgxTreeSelectModule> {
return {
ngModule: NgxTreeSelectModule,
providers: [ |
2f886fff844ccf9b1ff3358f89555bb1e28fd5e8 | src/token/abstract-token-storage.ts | src/token/abstract-token-storage.ts | import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { Observable } from "rxjs/Observable";
import { Token } from "./token";
import { TokenStorage } from "./token-storage";
export abstract class AbstractTokenStorage implements TokenStorage {
private _hasValidTokenPublisher: BehaviorSubject<boolean> = new BehaviorSubject(false);
public abstract getToken(): Token;
public hasValidToken(): boolean {
const token: Token = this.getToken();
return !!token && token.isValid();
}
public observeTokenAvailable(): Observable<boolean> {
return this._hasValidTokenPublisher;
}
public removeToken(): void {
this._hasValidTokenPublisher.next(this.hasValidToken());
}
public storeToken(token: Token): void {
this._hasValidTokenPublisher.next(this.hasValidToken());
}
}
| import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { Observable } from "rxjs/Observable";
import { Token } from "./token";
import { TokenStorage } from "./token-storage";
export abstract class AbstractTokenStorage implements TokenStorage {
private _hasValidTokenPublisher: BehaviorSubject<boolean> = new BehaviorSubject(false);
public abstract getToken(): Token;
public hasValidToken(): boolean {
const token: Token = this.getToken();
if (token) {
if (token.isValid()) {
return true;
}
// stored token is invalid (expired) - remove it
this.removeToken();
}
return false;
}
public observeTokenAvailable(): Observable<boolean> {
return this._hasValidTokenPublisher;
}
public removeToken(): void {
this._hasValidTokenPublisher.next(this.hasValidToken());
}
public storeToken(token: Token): void {
this._hasValidTokenPublisher.next(this.hasValidToken());
}
}
| Remove invalid token in token storage | Remove invalid token in token storage
| TypeScript | mit | cookingfox/stibble-api-client-angular,cookingfox/stibble-api-client-angular,cookingfox/stibble-api-client-angular | ---
+++
@@ -13,7 +13,16 @@
public hasValidToken(): boolean {
const token: Token = this.getToken();
- return !!token && token.isValid();
+ if (token) {
+ if (token.isValid()) {
+ return true;
+ }
+
+ // stored token is invalid (expired) - remove it
+ this.removeToken();
+ }
+
+ return false;
}
public observeTokenAvailable(): Observable<boolean> { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.