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 |
|---|---|---|---|---|---|---|---|---|---|---|
252563fe7d899216b5f85cedb9e987ce4d8dfdf9 | projects/angular-auth-oidc-client/src/lib/extractors/jwk.extractor.ts | projects/angular-auth-oidc-client/src/lib/extractors/jwk.extractor.ts | import { Injectable } from '@angular/core';
@Injectable()
export class JwkExtractor {
extractJwk(keys: JsonWebKey[], keyId?: string, use?: string): JsonWebKey {
const isNil = (c: any): boolean => {
return null === c || undefined === c;
};
if (0 === keys.length) {
throw new Error('Array of JsonWebKey was empty. Unable to extract');
}
let foundKeys = [...keys];
if (!isNil(keyId)) {
foundKeys = foundKeys.filter((k) => k['kid'] === keyId);
}
if (!isNil(use)) {
foundKeys = foundKeys.filter((k) => k['use'] === use);
}
if (foundKeys.length === 0) {
throw new Error(`No JsonWebKey found`);
}
if (foundKeys.length > 1 && isNil(keyId) && isNil(use)) {
throw new Error(`More than one JsonWebKey found`);
}
return foundKeys[0];
}
}
| import { Injectable } from '@angular/core';
@Injectable()
export class JwkExtractor {
static InvalidArgumentError = {
name: JwkExtractor.buildErrorName('InvalidArgumentError'),
message: 'Array of keys was empty. Unable to extract'
};
static NoMatchingKeysError = {
name: JwkExtractor.buildErrorName('NoMatchingKeysError'),
message: 'No key found matching the spec'
};
static SeveralMatchingKeysError = {
name: JwkExtractor.buildErrorName('SeveralMatchingKeysError'),
message: 'More than one key found. Please use spec to filter'
};
private static buildErrorName(name: string): string {
return JwkExtractor.name + ': ' + name;
}
extractJwk(keys: JsonWebKey[], spec?: {kid?: string, use?: string, kty?: string}): JsonWebKey {
if (0 === keys.length) {
throw JwkExtractor.InvalidArgumentError;
}
let foundKeys = keys
.filter((k) => spec?.kid ? k['kid'] === spec.kid : true)
.filter((k) => spec?.use ? k['use'] === spec.use : true)
.filter((k) => spec?.kty ? k['kty'] === spec.kty : true);
if (foundKeys.length === 0) {
throw JwkExtractor.NoMatchingKeysError;
}
if (foundKeys.length > 1 && (null === spec || undefined === spec)) {
throw JwkExtractor.SeveralMatchingKeysError;
}
return foundKeys[0];
}
}
| Support for kty in the spec. Also simplified the code a bit | ADD: Support for kty in the spec. Also simplified the code a bit
| TypeScript | mit | damienbod/angular-auth-oidc-client,damienbod/angular-auth-oidc-client,damienbod/angular-auth-oidc-client | ---
+++
@@ -2,31 +2,41 @@
@Injectable()
export class JwkExtractor {
- extractJwk(keys: JsonWebKey[], keyId?: string, use?: string): JsonWebKey {
- const isNil = (c: any): boolean => {
- return null === c || undefined === c;
- };
+ static InvalidArgumentError = {
+ name: JwkExtractor.buildErrorName('InvalidArgumentError'),
+ message: 'Array of keys was empty. Unable to extract'
+ };
+ static NoMatchingKeysError = {
+ name: JwkExtractor.buildErrorName('NoMatchingKeysError'),
+ message: 'No key found matching the spec'
+ };
+
+ static SeveralMatchingKeysError = {
+ name: JwkExtractor.buildErrorName('SeveralMatchingKeysError'),
+ message: 'More than one key found. Please use spec to filter'
+ };
+
+ private static buildErrorName(name: string): string {
+ return JwkExtractor.name + ': ' + name;
+ }
+
+ extractJwk(keys: JsonWebKey[], spec?: {kid?: string, use?: string, kty?: string}): JsonWebKey {
if (0 === keys.length) {
- throw new Error('Array of JsonWebKey was empty. Unable to extract');
+ throw JwkExtractor.InvalidArgumentError;
}
- let foundKeys = [...keys];
+ let foundKeys = keys
+ .filter((k) => spec?.kid ? k['kid'] === spec.kid : true)
+ .filter((k) => spec?.use ? k['use'] === spec.use : true)
+ .filter((k) => spec?.kty ? k['kty'] === spec.kty : true);
- if (!isNil(keyId)) {
- foundKeys = foundKeys.filter((k) => k['kid'] === keyId);
+ if (foundKeys.length === 0) {
+ throw JwkExtractor.NoMatchingKeysError;
}
- if (!isNil(use)) {
- foundKeys = foundKeys.filter((k) => k['use'] === use);
- }
-
- if (foundKeys.length === 0) {
- throw new Error(`No JsonWebKey found`);
- }
-
- if (foundKeys.length > 1 && isNil(keyId) && isNil(use)) {
- throw new Error(`More than one JsonWebKey found`);
+ if (foundKeys.length > 1 && (null === spec || undefined === spec)) {
+ throw JwkExtractor.SeveralMatchingKeysError;
}
return foundKeys[0]; |
3a66ab31b816000cbb251fbf7b89470dacf7b314 | packages/components/components/sidebar/SimpleSidebarListItemHeader.tsx | packages/components/components/sidebar/SimpleSidebarListItemHeader.tsx | import React from 'react';
import { classnames, Icon } from '../../index';
import SidebarListItem from './SidebarListItem';
interface Props {
toggle: boolean;
onToggle: () => void;
hasCaret?: boolean;
right?: React.ReactNode;
text: string;
title?: string;
}
const SimpleSidebarListItemHeader = ({ toggle, onToggle, hasCaret = true, right, text, title }: Props) => {
return (
<SidebarListItem className="navigation__link--groupHeader">
<div className="flex flex-nowrap">
<button
className="uppercase flex-item-fluid alignleft navigation__link--groupHeader-link"
type="button"
onClick={onToggle}
title={title}
>
<span className="mr0-5 small">{text}</span>
{hasCaret && (
<Icon
name="caret"
className={classnames(['navigation__icon--expand', toggle && 'rotateX-180'])}
/>
)}
</button>
{right}
</div>
</SidebarListItem>
);
};
export default SimpleSidebarListItemHeader;
| import React from 'react';
import { classnames, Icon } from '../../index';
import SidebarListItem from './SidebarListItem';
interface Props {
toggle: boolean;
onToggle: () => void;
hasCaret?: boolean;
right?: React.ReactNode;
text: string;
title?: string;
}
const SimpleSidebarListItemHeader = ({ toggle, onToggle, hasCaret = true, right, text, title }: Props) => {
return (
<SidebarListItem className="navigation__link--groupHeader">
<div className="flex flex-nowrap">
<button
className="uppercase flex-item-fluid alignleft navigation__link--groupHeader-link"
type="button"
onClick={onToggle}
title={title}
aria-expanded={toggle}
>
<span className="mr0-5 small">{text}</span>
{hasCaret && (
<Icon
name="caret"
className={classnames(['navigation__icon--expand', toggle && 'rotateX-180'])}
/>
)}
</button>
{right}
</div>
</SidebarListItem>
);
};
export default SimpleSidebarListItemHeader;
| Fix [COREWEB-211] add aria-expanded to group label/folder button | Fix [COREWEB-211] add aria-expanded to group label/folder button
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -19,6 +19,7 @@
type="button"
onClick={onToggle}
title={title}
+ aria-expanded={toggle}
>
<span className="mr0-5 small">{text}</span>
{hasCaret && ( |
4b368ceb8fe3a3f71c9312f727f1cf730343d094 | typings/vega-util.d.ts | typings/vega-util.d.ts | declare module 'vega-util' {
export interface LoggerInterface {
level: (_: number) => number | LoggerInterface;
warn(...args: any[]): LoggerInterface;
info(...args: any[]): LoggerInterface;
debug(...args: any[]): LoggerInterface;
}
export const None: number;
export const Warn: number;
export const Info: number;
export const Debug: number;
export function log(...args: any[]): void;
export function logger(_: number): LoggerInterface;
export function extend<T, U, V, W>(a: T, b: U, c: V, d: W): T & U & V & W;
export function extend<T, U, V>(a: T, b: U, c: V): T & U & V;
export function extend<T, U>(a: T, b: U): T & U;
export function extend(...all: any[]): any;
export function truncate(a: string, length: number): string;
export function isArray(a: any | any[]): a is any[];
export function isObject(a: any): a is any;
export function isString(a: any): a is string;
export function isNumber(a: any): a is number;
export function toSet<T>(array: T[]): {T: 1}
}
| declare module 'vega-util' {
export interface LoggerInterface {
level: (_: number) => number | LoggerInterface;
warn(...args: any[]): LoggerInterface;
info(...args: any[]): LoggerInterface;
debug(...args: any[]): LoggerInterface;
}
export const None: number;
export const Warn: number;
export const Info: number;
export const Debug: number;
export function log(...args: any[]): void;
export function logger(_: number): LoggerInterface;
export function extend<T, U, V, W>(a: T, b: U, c: V, d: W): T & U & V & W;
export function extend<T, U, V>(a: T, b: U, c: V): T & U & V;
export function extend<T, U>(a: T, b: U): T & U;
export function extend(...all: any[]): any;
export function truncate(a: string, length: number): string;
export function isArray(a: any | any[]): a is any[];
export function isObject(a: any): a is any;
export function isString(a: any): a is string;
export function isNumber(a: any): a is number;
export function toSet<T>(array: T[]): {[T: string]: 1}
}
| Fix incorrect type for `toSet` | Fix incorrect type for `toSet`
| TypeScript | bsd-3-clause | uwdata/vega-lite,vega/vega-lite,vega/vega-lite,uwdata/vega-lite,uwdata/vega-lite,uwdata/vega-lite,vega/vega-lite,uwdata/vega-lite,vega/vega-lite,vega/vega-lite | ---
+++
@@ -26,5 +26,5 @@
export function isString(a: any): a is string;
export function isNumber(a: any): a is number;
- export function toSet<T>(array: T[]): {T: 1}
+ export function toSet<T>(array: T[]): {[T: string]: 1}
} |
1183f9834ec34c43ffc3ec1a6ebcec8e4a32df97 | src/app/app.routes.ts | src/app/app.routes.ts | // tslint:disable-next-line:max-line-length
import { AudiologistNavigationComponent } from './audiologist-navigation/audiologist-navigation.component';
import { CheckInComponent } from './check-in/check-in.component';
import { Routes } from '@angular/router';
import { HomeComponent } from './home';
import { NoContentComponent } from './no-content';
import { DataResolver } from './app.resolver';
export const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{ path: 'home', component: HomeComponent },
{ path: 'login', component: CheckInComponent},
{ path: 'audio-nav', component: AudiologistNavigationComponent},
{ path: '**', component: NoContentComponent },
];
| // tslint:disable-next-line:max-line-length
import { AudiologistNavigationComponent } from './audiologist-navigation/audiologist-navigation.component';
import { CheckInComponent } from './check-in/check-in.component';
import { Routes } from '@angular/router';
import { HomeComponent } from './home';
import { NoContentComponent } from './no-content';
import { ThankYouComponent } from './thank-you/thank-you.component';
import { DataResolver } from './app.resolver';
export const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{ path: 'home', component: HomeComponent },
{ path: 'login', component: CheckInComponent},
{ path: 'audio-nav', component: AudiologistNavigationComponent},
{ path: 'thank-you', component: ThankYouComponent},
{ path: '**', component: NoContentComponent },
];
| Add thank-you component to routing | Add thank-you component to routing
| TypeScript | mit | marissa-hagglund/VA-Audiology-Website,marissa-hagglund/VA-Audiology-Website,marissa-hagglund/VA-Audiology-Website | ---
+++
@@ -4,6 +4,7 @@
import { Routes } from '@angular/router';
import { HomeComponent } from './home';
import { NoContentComponent } from './no-content';
+import { ThankYouComponent } from './thank-you/thank-you.component';
import { DataResolver } from './app.resolver';
@@ -12,5 +13,6 @@
{ path: 'home', component: HomeComponent },
{ path: 'login', component: CheckInComponent},
{ path: 'audio-nav', component: AudiologistNavigationComponent},
+ { path: 'thank-you', component: ThankYouComponent},
{ path: '**', component: NoContentComponent },
]; |
e357c60509039c5ac572f50a869597b0132f02de | applications/calendar/src/app/containers/setup/CalendarResetSection.tsx | applications/calendar/src/app/containers/setup/CalendarResetSection.tsx | import { Alert } from '@proton/components';
import { c } from 'ttag';
import { Calendar } from '@proton/shared/lib/interfaces/calendar';
import CalendarTableRows from './CalendarTableRows';
interface Props {
calendarsToReset: Calendar[];
}
const CalendarResetSection = ({ calendarsToReset = [] }: Props) => {
return (
<>
<Alert type="warning">{c('Info')
.t`You have reset your password and events linked to the following calendars couldn't be decrypted. Any shared calendar links you created previously will no longer work.`}</Alert>
<CalendarTableRows calendars={calendarsToReset} />
</>
);
};
export default CalendarResetSection;
| import { Alert } from '@proton/components';
import { c } from 'ttag';
import { Calendar } from '@proton/shared/lib/interfaces/calendar';
import CalendarTableRows from './CalendarTableRows';
interface Props {
calendarsToReset: Calendar[];
}
const CalendarResetSection = ({ calendarsToReset = [] }: Props) => {
return (
<>
<Alert type="warning">
<div className="text-pre-wrap">
{c('Info')
.t`You have reset your password and events linked to the following calendars couldn't be decrypted.
Any shared calendar links you created previously will no longer work.
Any active subscribed calendars will synchronize again after a few minutes.`}
</div>
</Alert>
<CalendarTableRows calendars={calendarsToReset} />
</>
);
};
export default CalendarResetSection;
| Improve calendar reset modal copy | Improve calendar reset modal copy
Made the translation multi-line and added info about subscribed calendars
CALWEB-2640
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -9,8 +9,14 @@
const CalendarResetSection = ({ calendarsToReset = [] }: Props) => {
return (
<>
- <Alert type="warning">{c('Info')
- .t`You have reset your password and events linked to the following calendars couldn't be decrypted. Any shared calendar links you created previously will no longer work.`}</Alert>
+ <Alert type="warning">
+ <div className="text-pre-wrap">
+ {c('Info')
+ .t`You have reset your password and events linked to the following calendars couldn't be decrypted.
+ Any shared calendar links you created previously will no longer work.
+ Any active subscribed calendars will synchronize again after a few minutes.`}
+ </div>
+ </Alert>
<CalendarTableRows calendars={calendarsToReset} />
</>
); |
b10fec4b2e41bd9af0eadac687462b8c5fd343cb | src/contexts/index.ts | src/contexts/index.ts | import { context as unoContext } from './arduino-uno';
export interface Context {
[x: string]: string;
run_wrapper: string;
run: string;
}
interface IndexedContexts {
[x: string]: Context;
}
const contexts = {
'arduino-uno': unoContext
};
export const getContext = (key: string) => contexts[key];
| import { context as unoContext } from './arduino-uno';
import { context as rivuletContext } from './rivulet';
export interface Context {
[x: string]: string;
include_headers: string;
}
interface IndexedContexts {
[x: string]: Context;
}
const contexts = {
'arduino-uno': unoContext,
rivulet: rivuletContext
};
export const getContext = (key: string) => contexts[key];
| Add include headers to contexts | Add include headers to contexts
| TypeScript | mit | AmnisIO/typewriter,AmnisIO/typewriter,AmnisIO/typewriter | ---
+++
@@ -1,9 +1,9 @@
import { context as unoContext } from './arduino-uno';
+import { context as rivuletContext } from './rivulet';
export interface Context {
[x: string]: string;
- run_wrapper: string;
- run: string;
+ include_headers: string;
}
interface IndexedContexts {
@@ -11,7 +11,8 @@
}
const contexts = {
- 'arduino-uno': unoContext
+ 'arduino-uno': unoContext,
+ rivulet: rivuletContext
};
export const getContext = (key: string) => contexts[key]; |
f4b474fc203bb46a6874d026f76e3b42d53aadeb | app/src/component/Video.tsx | app/src/component/Video.tsx | import * as React from "react";
import { connect } from "react-redux";
import { IVideo } from "../lib/videos";
import { actionCreators } from "../redux/videos";
import Item from "./Item";
import "./style/Video.css";
interface IProps extends IVideo {
currentItem: IVideo | null;
detailed: boolean;
done: boolean;
toggleItemState: (video: IVideo) => void;
removeItem: (video: IVideo) => void;
setCurrentItem: (video: IVideo | null) => void;
}
class Video extends React.Component<IProps> {
public render() {
const { description, embedUri, name, publishedAt, uri } = this.video;
return (
<Item
{...this.props}
details={[
<div key="video" className="Video-wrapper">
<iframe
id="ytplayer"
src={embedUri}
frameBorder="0"
/>
</div>,
description && <div>{description}</div>,
publishedAt &&
<div className="Video-date">
Published on: {(new Date(publishedAt)).toLocaleDateString()}
</div>]}
href={uri}
item={this.video}
/>
);
}
private get video(): IVideo {
const { id, description, embedUri, name, publishedAt, uri } = this.props;
return { id, description, embedUri, name, publishedAt, uri };
}
}
export default connect(({ videos }) => videos, actionCreators)(Video);
| import * as React from "react";
import { connect } from "react-redux";
import { IVideo } from "../lib/videos";
import { actionCreators } from "../redux/videos";
import Item from "./Item";
import "./style/Video.css";
interface IProps extends IVideo {
currentItem: IVideo | null;
detailed: boolean;
done: boolean;
toggleItemState: (video: IVideo) => void;
removeItem: (video: IVideo) => void;
setCurrentItem: (video: IVideo | null) => void;
}
class Video extends React.Component<IProps> {
public render() {
const { description, embedUri, name, publishedAt, uri } = this.video;
return (
<Item
{...this.props}
details={[
<div key="video" className="Video-wrapper">
<iframe
id="ytplayer"
src={embedUri}
frameBorder="0"
/>
</div>,
description && <div key="description">{description}</div>,
publishedAt &&
<div key="publishedOn" className="Video-date">
Published on: {(new Date(publishedAt)).toLocaleDateString()}
</div>]}
href={uri}
item={this.video}
/>
);
}
private get video(): IVideo {
const { id, description, embedUri, name, publishedAt, uri } = this.props;
return { id, description, embedUri, name, publishedAt, uri };
}
}
export default connect(({ videos }) => videos, actionCreators)(Video);
| Add keys to video details | Add keys to video details
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -30,9 +30,9 @@
frameBorder="0"
/>
</div>,
- description && <div>{description}</div>,
+ description && <div key="description">{description}</div>,
publishedAt &&
- <div className="Video-date">
+ <div key="publishedOn" className="Video-date">
Published on: {(new Date(publishedAt)).toLocaleDateString()}
</div>]}
href={uri} |
f2ab2b681f3b1d7fd530ad12f4ecaa2293e91da3 | app/templates/ts/src/app.ts | app/templates/ts/src/app.ts | import {ui, Button, TextView} from 'tabris';
let button = new Button({
centerX: 0, top: 100,
text: 'Show Message'
}).appendTo(ui.contentView);
let textView = new TextView({
centerX: 0, top: [button, 50],
font: '24px'
}).appendTo(ui.contentView);
button.on('select', () => textView.text = 'Tabris.js rocks!');
| import {ui, Button, TextView} from 'tabris';
let button = new Button({
centerX: 0, top: 100,
text: 'Show Message'
}).appendTo(ui.contentView);
let textView = new TextView({
centerX: 0, top: [button, 50],
font: '24px'
}).appendTo(ui.contentView);
button.on({select: () => textView.text = 'Tabris.js rocks!'});
| Use object to attach event listener in TypeScript template | Use object to attach event listener in TypeScript template
Change-Id: Ica58ecd12a4952e27db7a8fe8fea75e305c64f03
| TypeScript | bsd-3-clause | eclipsesource/generator-tabris-js,eclipsesource/generator-tabris-js | ---
+++
@@ -10,4 +10,4 @@
font: '24px'
}).appendTo(ui.contentView);
-button.on('select', () => textView.text = 'Tabris.js rocks!');
+button.on({select: () => textView.text = 'Tabris.js rocks!'}); |
71ec02578631f1ac478f778d860a259b435c60a3 | figma-plugin/src/ui.ts | figma-plugin/src/ui.ts | import {
ID_REQUEST,
SEND_OVERLAY_REQUEST,
CLOSE_PLUGIN_REQUEST,
SELECT_OVERLAY_ERR,
MULTI_OVERLAY_ERR,
INVALID_ID_ERR,
setError
} from './helper'
import * as Server from './server_requests'
document.getElementById('send').onclick = () => {
parent.postMessage({ pluginMessage: { type: SEND_OVERLAY_REQUEST } }, '*')
}
document.getElementById('cancel').onclick = () => {
Server.cancelOverlay();
parent.postMessage({ pluginMessage: { type: CLOSE_PLUGIN_REQUEST } }, '*')
}
window.onmessage = async (event) => {
switch (event.data.pluginMessage.type) {
case ID_REQUEST:
Server.requestOverlayId();
break;
case SEND_OVERLAY_REQUEST:
await Server.sendOverlay(event.data.pluginMessage);
break;
case CLOSE_PLUGIN_REQUEST:
Server.cancelOverlay();
break;
case INVALID_ID_ERR:
setError("This overlay does not exist anymore.");
Server.cancelOverlay();
break;
case SELECT_OVERLAY_ERR:
setError("Please select an overlay before trying to send to Android Studio.")
break;
case MULTI_OVERLAY_ERR:
setError("Please select only one overlay.");
break;
}
} | import {
ID_REQUEST,
SEND_OVERLAY_REQUEST,
CLOSE_PLUGIN_REQUEST,
SELECT_OVERLAY_ERR,
MULTI_OVERLAY_ERR,
INVALID_ID_ERR,
setError
} from './helper'
import * as Server from './server_requests'
document.getElementById('send').onclick = () => {
parent.postMessage({ pluginMessage: { type: SEND_OVERLAY_REQUEST } }, '*')
}
document.getElementById('cancel').onclick = () => {
Server.manualCancelOverlay();
parent.postMessage({ pluginMessage: { type: CLOSE_PLUGIN_REQUEST } }, '*')
}
window.onmessage = async (event) => {
switch (event.data.pluginMessage.type) {
case ID_REQUEST:
Server.requestOverlayId();
break;
case SEND_OVERLAY_REQUEST:
await Server.sendOverlay(event.data.pluginMessage);
break;
case INVALID_ID_ERR:
setError("This overlay does not exist anymore.");
Server.cancelOverlay();
break;
case SELECT_OVERLAY_ERR:
setError("Please select an overlay before trying to send to Android Studio.")
break;
case MULTI_OVERLAY_ERR:
setError("Please select only one overlay.");
break;
}
} | Change cancel button onClick method to use new manual cancel method. | Change cancel button onClick method to use new manual cancel method.
bug: 106757419
Change-Id: Ibd035e86c8e263bd70cc5f52881565de5b9649e1
| TypeScript | apache-2.0 | googleinterns/android-studio-figma-overlay,googleinterns/android-studio-figma-overlay,googleinterns/android-studio-figma-overlay,googleinterns/android-studio-figma-overlay | ---
+++
@@ -15,7 +15,7 @@
}
document.getElementById('cancel').onclick = () => {
- Server.cancelOverlay();
+ Server.manualCancelOverlay();
parent.postMessage({ pluginMessage: { type: CLOSE_PLUGIN_REQUEST } }, '*')
}
@@ -26,9 +26,6 @@
break;
case SEND_OVERLAY_REQUEST:
await Server.sendOverlay(event.data.pluginMessage);
- break;
- case CLOSE_PLUGIN_REQUEST:
- Server.cancelOverlay();
break;
case INVALID_ID_ERR:
setError("This overlay does not exist anymore."); |
a417d5abdb4dd5911eff5ac7cc6f25b582ab9cea | src/screens/App/index.tsx | src/screens/App/index.tsx | import React, { ReactElement } from 'react'
import { useMatchMedia, useI18n } from 'hooks'
import { Header, Title } from 'components/Layout'
import Menu, { Item } from 'components/Layout/Menu'
import AnimatedPatterns from 'components/AnimatedPatterns'
import LanguageSwitcher from 'components/LanguageSwitcher'
import styles from './styles.module.sass'
export default function App(): ReactElement {
const matches = useMatchMedia('max-width: 500px')
const { getAllMessages } = useI18n()
const {
supporters,
literature,
software,
design,
about,
contact,
} = getAllMessages()
return (
<div className="App">
<Header classNames={[styles.header]}>
<LanguageSwitcher />
<Title>DALTON MENEZES</Title>
<Menu
horizontal={!matches}
withBullets={!matches}
classNames={[styles.menu]}
>
<Item to="/supporters">{supporters}</Item>
<Item to="/literature">{literature}</Item>
<Item to="/software">{software}</Item>
<Item to="/design">{design}</Item>
<Item to="/about">{about}</Item>
<Item to="/contact">{contact}</Item>
</Menu>
</Header>
<AnimatedPatterns />
</div>
)
}
| import React, { ReactElement } from 'react'
import { useMatchMedia, useI18n } from 'hooks'
import { Header, Title } from 'components/Layout'
import Menu, { Item } from 'components/Layout/Menu'
import AnimatedPatterns from 'components/AnimatedPatterns'
import LanguageSwitcher from 'components/LanguageSwitcher'
import styles from './styles.module.sass'
export default function App(): ReactElement {
const { getAllMessages } = useI18n()
const matcheWidth = useMatchMedia('max-width: 500px')
const matcheHeight = useMatchMedia('max-height: 320px')
const matchMedia = matcheWidth && !matcheHeight
const {
supporters,
literature,
software,
design,
about,
contact,
} = getAllMessages()
return (
<div className="App">
<Header classNames={[styles.header]}>
<LanguageSwitcher />
<Title>DALTON MENEZES</Title>
<Menu
horizontal={!matchMedia}
withBullets={!matchMedia}
classNames={[styles.menu]}
>
<Item to="/supporters">{supporters}</Item>
<Item to="/literature">{literature}</Item>
<Item to="/software">{software}</Item>
<Item to="/design">{design}</Item>
<Item to="/about">{about}</Item>
<Item to="/contact">{contact}</Item>
</Menu>
</Header>
<AnimatedPatterns />
</div>
)
}
| Fix maches matchMedia to render horizontal or vertical menu by adding max-height check also | Fix maches matchMedia to render horizontal or vertical menu by adding max-height check also
| TypeScript | mit | daltonmenezes/daltonmenezes.github.io,daltonmenezes/daltonmenezes.github.io,daltonmenezes/daltonmenezes.github.io | ---
+++
@@ -8,8 +8,10 @@
import styles from './styles.module.sass'
export default function App(): ReactElement {
- const matches = useMatchMedia('max-width: 500px')
const { getAllMessages } = useI18n()
+ const matcheWidth = useMatchMedia('max-width: 500px')
+ const matcheHeight = useMatchMedia('max-height: 320px')
+ const matchMedia = matcheWidth && !matcheHeight
const {
supporters,
@@ -28,8 +30,8 @@
<Title>DALTON MENEZES</Title>
<Menu
- horizontal={!matches}
- withBullets={!matches}
+ horizontal={!matchMedia}
+ withBullets={!matchMedia}
classNames={[styles.menu]}
>
<Item to="/supporters">{supporters}</Item> |
33efe4c60a4920e5790377f59b7b57c47840ded5 | src/vmware/VMwareVirtualMachineSummary.tsx | src/vmware/VMwareVirtualMachineSummary.tsx | import * as React from 'react';
import { ENV } from '@waldur/core/services';
import { withTranslation } from '@waldur/i18n';
import { Field, PureResourceSummaryBase } from '@waldur/resource/summary';
import { formatSummary } from '@waldur/resource/utils';
const PureVMwareVirtualMachineSummary = props => {
const { translate, resource } = props;
const advancedMode = !ENV.plugins.WALDUR_VMWARE.BASIC_MODE;
return (
<>
<PureResourceSummaryBase {...props}/>
<Field
label={translate('Summary')}
value={formatSummary(resource)}
/>
<Field
label={translate('Guest OS')}
value={resource.guest_os_name}
/>
{advancedMode && (
<>
<Field
label={translate('Template')}
value={resource.template_name}
/>
<Field
label={translate('Cluster')}
value={resource.cluster_name}
/>
<Field
label={translate('Datastore')}
value={resource.datastore_name}
/>
<Field
label={translate('Networks')}
value={resource.networks.map(network => network.name).join(', ')}
/>
</>
)}
</>
);
};
export const VMwareVirtualMachineSummary = withTranslation(PureVMwareVirtualMachineSummary);
| import * as React from 'react';
import { ENV } from '@waldur/core/services';
import { withTranslation } from '@waldur/i18n';
import { Field, PureResourceSummaryBase } from '@waldur/resource/summary';
import { formatSummary } from '@waldur/resource/utils';
const PureVMwareVirtualMachineSummary = props => {
const { translate, resource } = props;
const advancedMode = !ENV.plugins.WALDUR_VMWARE.BASIC_MODE;
return (
<>
<PureResourceSummaryBase {...props}/>
<Field
label={translate('Summary')}
value={formatSummary(resource)}
/>
<Field
label={translate('Guest OS')}
value={resource.guest_os_name}
/>
{advancedMode && (
<>
<Field
label={translate('Template')}
value={resource.template_name}
/>
<Field
label={translate('Cluster')}
value={resource.cluster_name}
/>
<Field
label={translate('Datastore')}
value={resource.datastore_name}
/>
</>
)}
</>
);
};
export const VMwareVirtualMachineSummary = withTranslation(PureVMwareVirtualMachineSummary);
| Remove networks list in VMware VM details as it is gonna be moved to separate tab | Remove networks list in VMware VM details as it is gonna be moved to separate tab [WAL-2505]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -33,10 +33,6 @@
label={translate('Datastore')}
value={resource.datastore_name}
/>
- <Field
- label={translate('Networks')}
- value={resource.networks.map(network => network.name).join(', ')}
- />
</>
)}
</> |
e9b5da3e1d24613f4a7a99e8be756582b80517c8 | src/vendor.browser.ts | src/vendor.browser.ts | // Vendors
import "reflect-metadata";
import "zone.js/dist/long-stack-trace-zone.js";
import "@angular/platform-browser-dynamic";
import "@angular/platform-browser";
import "@angular/core";
import "@angular/http";
import "@angular/router";
// NOTE: reference path is temporary workaround (see https://github.com/angular/zone.js/issues/297)
///<reference path="../node_modules/zone.js/dist/zone.js.d.ts"/>
require('zone.js');
// Angular 2
// RxJS 5
// import 'rxjs/Rx';
// For vendors for example jQuery, Lodash, angular2-jwt import them here
// Also see src/typings.d.ts as you also need to run `typings install x` where `x` is your module
| // Vendors
import 'reflect-metadata';
// NOTE: reference path is temporary workaround (see https://github.com/angular/zone.js/issues/297)
///<reference path="../node_modules/zone.js/dist/zone.js.d.ts"/>
require('zone.js');
import "zone.js/dist/long-stack-trace-zone.js";
// Angular 2
import '@angular/platform-browser-dynamic';
import '@angular/platform-browser';
import '@angular/core';
import '@angular/http';
import '@angular/router';
// RxJS 5
// import 'rxjs/Rx';
// For vendors for example jQuery, Lodash, angular2-jwt import them here
// Also see src/typings.d.ts as you also need to run `typings install x` where `x` is your module
| Fix vendor imports (remove automatic code optimization on commit.) | Fix vendor imports (remove automatic code optimization on commit.)
| TypeScript | mit | bryangreen/poker-evaluator,bryangreen/poker-evaluator,bryangreen/poker-evaluator | ---
+++
@@ -1,18 +1,18 @@
// Vendors
-import "reflect-metadata";
-import "zone.js/dist/long-stack-trace-zone.js";
-import "@angular/platform-browser-dynamic";
-import "@angular/platform-browser";
-import "@angular/core";
-import "@angular/http";
-import "@angular/router";
+import 'reflect-metadata';
// NOTE: reference path is temporary workaround (see https://github.com/angular/zone.js/issues/297)
///<reference path="../node_modules/zone.js/dist/zone.js.d.ts"/>
require('zone.js');
+import "zone.js/dist/long-stack-trace-zone.js";
// Angular 2
+import '@angular/platform-browser-dynamic';
+import '@angular/platform-browser';
+import '@angular/core';
+import '@angular/http';
+import '@angular/router';
// RxJS 5
// import 'rxjs/Rx'; |
7ef0d08d1eaf515a8b48a4d963b1f841e8b84355 | lib/src/index.ts | lib/src/index.ts | // Packages
import webpack = require('webpack')
// Ours
import { CompilerOptions } from './types/options'
import { merge } from './config'
const core = (options: CompilerOptions): webpack.Compiler => {
return webpack(merge(options))
}
export { core }
| // Packages
import webpack = require('webpack')
// Ours
import { CompilerOptions } from './types/options'
import { merge } from './config'
const prepare = (options: CompilerOptions): webpack.Compiler => {
return webpack(merge(options))
}
export { prepare }
| Rename exported function 'core' to 'prepare' | refactor(lib): Rename exported function 'core' to 'prepare'
BREAKING CHANGE: Rename exported function `core` to `prepare`
| TypeScript | mit | glitchapp/glitch,glitchapp/glitch,glitchapp/glitch | ---
+++
@@ -5,8 +5,8 @@
import { CompilerOptions } from './types/options'
import { merge } from './config'
-const core = (options: CompilerOptions): webpack.Compiler => {
+const prepare = (options: CompilerOptions): webpack.Compiler => {
return webpack(merge(options))
}
-export { core }
+export { prepare } |
4622021a4713b489a9a57961c3dae0b32cdd0322 | packages/vanilla/example/index.ts | packages/vanilla/example/index.ts | import { createExampleSelection } from '../../examples/src/register';
import { createThemeSelection } from './theme.switcher';
import { vanillaStyles } from '../src/helpers';
window.onload = () => {
createExampleSelection({styles: vanillaStyles});
createThemeSelection();
};
| import { createExampleSelection } from '../../examples/src/register';
import { createThemeSelection } from './theme.switcher';
import { vanillaStyles } from '../src/util';
window.onload = () => {
createExampleSelection({styles: vanillaStyles});
createThemeSelection();
};
| Fix import of vanillaStyles in vanilla examples | Fix import of vanillaStyles in vanilla examples
| TypeScript | mit | qb-project/jsonforms,qb-project/jsonforms,qb-project/jsonforms | ---
+++
@@ -1,6 +1,6 @@
import { createExampleSelection } from '../../examples/src/register';
import { createThemeSelection } from './theme.switcher';
-import { vanillaStyles } from '../src/helpers';
+import { vanillaStyles } from '../src/util';
window.onload = () => {
createExampleSelection({styles: vanillaStyles}); |
167c422e4b100496d1e5fdb76fa87edad9810ec3 | extensions/github-authentication/src/common/clientRegistrar.ts | extensions/github-authentication/src/common/clientRegistrar.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface ClientDetails {
id?: string;
secret?: string;
}
export interface ClientConfig {
OSS: ClientDetails;
INSIDERS: ClientDetails;
}
export class Registrar {
private _config: ClientConfig;
constructor() {
this._config = require('./config.json') as ClientConfig;
}
getClientDetails(product: string): ClientDetails {
let details: ClientDetails | undefined;
switch (product) {
case 'code-oss':
details = this._config.OSS;
break;
case 'vscode-insiders':
details = this._config.INSIDERS;
break;
default:
throw new Error(`Unrecognized product ${product}`);
}
if (!details.id || !details.secret) {
throw new Error(`No client configuration available for ${product}`);
}
return details;
}
}
const ClientRegistrar = new Registrar();
export default ClientRegistrar;
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface ClientDetails {
id?: string;
secret?: string;
}
export interface ClientConfig {
OSS: ClientDetails;
INSIDERS: ClientDetails;
}
export class Registrar {
private _config: ClientConfig;
constructor() {
try {
this._config = require('./config.json') as ClientConfig;
} catch (e) {
this._config = {
OSS: {},
INSIDERS: {}
};
}
}
getClientDetails(product: string): ClientDetails {
let details: ClientDetails | undefined;
switch (product) {
case 'code-oss':
details = this._config.OSS;
break;
case 'vscode-insiders':
details = this._config.INSIDERS;
break;
default:
throw new Error(`Unrecognized product ${product}`);
}
if (!details.id || !details.secret) {
throw new Error(`No client configuration available for ${product}`);
}
return details;
}
}
const ClientRegistrar = new Registrar();
export default ClientRegistrar;
| Handle no github auth config | Handle no github auth config
| TypeScript | mit | microsoft/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,eamodio/vscode,hoovercj/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,hoovercj/vscode,joaomoreno/vscode,eamodio/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,the-ress/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,joaomoreno/vscode,Microsoft/vscode,joaomoreno/vscode,Microsoft/vscode,eamodio/vscode,hoovercj/vscode,microsoft/vscode,hoovercj/vscode,Microsoft/vscode,the-ress/vscode,hoovercj/vscode,eamodio/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,the-ress/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,the-ress/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,the-ress/vscode,joaomoreno/vscode,Microsoft/vscode,the-ress/vscode,the-ress/vscode,hoovercj/vscode,Microsoft/vscode,microsoft/vscode,hoovercj/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,the-ress/vscode,hoovercj/vscode,the-ress/vscode,microsoft/vscode,joaomoreno/vscode,Microsoft/vscode,hoovercj/vscode,the-ress/vscode,joaomoreno/vscode,joaomoreno/vscode,hoovercj/vscode,the-ress/vscode,joaomoreno/vscode,joaomoreno/vscode,eamodio/vscode,hoovercj/vscode,microsoft/vscode,hoovercj/vscode,joaomoreno/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,joaomoreno/vscode,eamodio/vscode,the-ress/vscode,hoovercj/vscode,joaomoreno/vscode,joaomoreno/vscode,eamodio/vscode,microsoft/vscode,hoovercj/vscode,Microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,the-ress/vscode,hoovercj/vscode,the-ress/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,joaomoreno/vscode | ---
+++
@@ -17,7 +17,14 @@
private _config: ClientConfig;
constructor() {
- this._config = require('./config.json') as ClientConfig;
+ try {
+ this._config = require('./config.json') as ClientConfig;
+ } catch (e) {
+ this._config = {
+ OSS: {},
+ INSIDERS: {}
+ };
+ }
}
getClientDetails(product: string): ClientDetails {
let details: ClientDetails | undefined; |
3f1a624567af40c509ac34ff92cd24e7f54efaa4 | app/src/ui/welcome/sign-in-enterprise.tsx | app/src/ui/welcome/sign-in-enterprise.tsx | import * as React from 'react'
import { WelcomeStep } from './welcome'
import { Button } from '../lib/button'
import { SignIn } from '../lib/sign-in'
import { Dispatcher, SignInState } from '../../lib/dispatcher'
interface ISignInEnterpriseProps {
readonly dispatcher: Dispatcher
readonly advance: (step: WelcomeStep) => void
readonly signInState: SignInState | null
}
/** The Welcome flow step to login to an Enterprise instance. */
export class SignInEnterprise extends React.Component<ISignInEnterpriseProps, void> {
public render() {
const state = this.props.signInState
if (!state) {
return null
}
return (
<div id='sign-in-enterprise'>
<h1 className='welcome-title'>Sign in to your GitHub Enterprise server</h1>
<p className='welcome-text'>Get started by signing into GitHub Enterprise</p>
<SignIn
signInState={state}
dispatcher={this.props.dispatcher}
>
<Button onClick={this.cancel}>Cancel</Button>
</SignIn>
</div>
)
}
private cancel = () => {
this.props.advance(WelcomeStep.Start)
}
}
| import * as React from 'react'
import { WelcomeStep } from './welcome'
import { Button } from '../lib/button'
import { SignIn } from '../lib/sign-in'
import { Dispatcher, SignInState } from '../../lib/dispatcher'
interface ISignInEnterpriseProps {
readonly dispatcher: Dispatcher
readonly advance: (step: WelcomeStep) => void
readonly signInState: SignInState | null
}
/** The Welcome flow step to login to an Enterprise instance. */
export class SignInEnterprise extends React.Component<ISignInEnterpriseProps, void> {
public render() {
const state = this.props.signInState
if (!state) {
return null
}
return (
<div id='sign-in-enterprise'>
<h1 className='welcome-title'>Sign in to your GitHub Enterprise server</h1>
<SignIn
signInState={state}
dispatcher={this.props.dispatcher}
>
<Button onClick={this.cancel}>Cancel</Button>
</SignIn>
</div>
)
}
private cancel = () => {
this.props.advance(WelcomeStep.Start)
}
}
| Remove redundant text from Enterprise sign in | Remove redundant text from Enterprise sign in
| TypeScript | mit | kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop,j-f1/forked-desktop,gengjiawen/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,BugTesterTest/desktops,BugTesterTest/desktops,hjobrien/desktop,j-f1/forked-desktop,kactus-io/kactus,gengjiawen/desktop,desktop/desktop,kactus-io/kactus,hjobrien/desktop,say25/desktop,hjobrien/desktop,artivilla/desktop,artivilla/desktop,hjobrien/desktop,gengjiawen/desktop,j-f1/forked-desktop,shiftkey/desktop,BugTesterTest/desktops,desktop/desktop,gengjiawen/desktop,BugTesterTest/desktops,shiftkey/desktop,say25/desktop,desktop/desktop | ---
+++
@@ -24,7 +24,6 @@
return (
<div id='sign-in-enterprise'>
<h1 className='welcome-title'>Sign in to your GitHub Enterprise server</h1>
- <p className='welcome-text'>Get started by signing into GitHub Enterprise</p>
<SignIn
signInState={state} |
b5ba0545c17e39429e485f8609094ba5e2fafb1c | server/webapp/WEB-INF/rails/webpack/single_page_apps/config_repos.tsx | server/webapp/WEB-INF/rails/webpack/single_page_apps/config_repos.tsx | /*
* 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 {RoutedPage} from "helpers/spa_base";
import {ConfigReposPage} from "views/pages/config_repos";
export class ConfigReposSPA extends RoutedPage {
constructor() {
super({
"": ConfigReposPage,
"/:id": ConfigReposPage
});
}
}
// tslint:disable-next-line
new ConfigReposSPA();
| /*
* 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 {RoutedPage} from "helpers/spa_base";
import {ConfigReposPage} from "views/pages/config_repos";
export class ConfigReposSPA extends RoutedPage {
constructor() {
super({
"/": ConfigReposPage,
"/:id": ConfigReposPage
});
}
}
// tslint:disable-next-line
new ConfigReposSPA();
| Fix config repo SPA routes after mithril 2.x upgrade | Fix config repo SPA routes after mithril 2.x upgrade
| TypeScript | apache-2.0 | Skarlso/gocd,marques-work/gocd,kierarad/gocd,gocd/gocd,gocd/gocd,arvindsv/gocd,ketan/gocd,ketan/gocd,gocd/gocd,ibnc/gocd,ibnc/gocd,gocd/gocd,arvindsv/gocd,bdpiparva/gocd,marques-work/gocd,Skarlso/gocd,ketan/gocd,bdpiparva/gocd,kierarad/gocd,kierarad/gocd,marques-work/gocd,marques-work/gocd,bdpiparva/gocd,arvindsv/gocd,ibnc/gocd,ibnc/gocd,arvindsv/gocd,GaneshSPatil/gocd,ketan/gocd,marques-work/gocd,gocd/gocd,Skarlso/gocd,ibnc/gocd,marques-work/gocd,Skarlso/gocd,GaneshSPatil/gocd,arvindsv/gocd,GaneshSPatil/gocd,kierarad/gocd,GaneshSPatil/gocd,Skarlso/gocd,kierarad/gocd,Skarlso/gocd,bdpiparva/gocd,GaneshSPatil/gocd,ketan/gocd,gocd/gocd,ketan/gocd,GaneshSPatil/gocd,bdpiparva/gocd,bdpiparva/gocd,arvindsv/gocd,kierarad/gocd,ibnc/gocd | ---
+++
@@ -20,7 +20,7 @@
export class ConfigReposSPA extends RoutedPage {
constructor() {
super({
- "": ConfigReposPage,
+ "/": ConfigReposPage,
"/:id": ConfigReposPage
});
} |
73c40eee1b090660f651fcbe67b0300ce53c3b35 | src/app/map/download-image-form/download-image-form.component.spec.ts | src/app/map/download-image-form/download-image-form.component.spec.ts | /* tslint:disable:no-unused-variable */
/*!
* Download Image Form Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { TestBed, async, inject } from '@angular/core/testing';
import { FormBuilder } from '@angular/forms';
import { Http, BaseRequestOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { LocationsService } from '../locations.service';
import { SuitabilityMapService } from '../suitability-map.service';
import { MapConfig, MAP_CONFIG } from '../map.config';
import { DownloadImageFormComponent } from './download-image-form.component';
describe('Component: DownloadImageForm', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
MockBackend,
BaseRequestOptions,
FormBuilder,
LocationsService,
SuitabilityMapService,
DownloadImageFormComponent,
{ provide: MAP_CONFIG, useValue: MapConfig },
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backendInstance, defaultOptions);
}
},
]
});
});
it('should create an instance', inject([DownloadImageFormComponent], (component: DownloadImageFormComponent) => {
expect(component).toBeTruthy();
}));
});
| /* tslint:disable:no-unused-variable */
/*!
* Download Image Form Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { TestBed, async, inject } from '@angular/core/testing';
import { FormBuilder } from '@angular/forms';
import { Http, BaseRequestOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { AppLoggerService } from '../../app-logger.service';
import { LocationsService } from '../locations.service';
import { SuitabilityMapService } from '../suitability-map.service';
import { MapConfig, MAP_CONFIG } from '../map.config';
import { DownloadImageFormComponent } from './download-image-form.component';
describe('Component: DownloadImageForm', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
MockBackend,
BaseRequestOptions,
FormBuilder,
AppLoggerService,
LocationsService,
SuitabilityMapService,
DownloadImageFormComponent,
{ provide: MAP_CONFIG, useValue: MapConfig },
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backendInstance, defaultOptions);
}
},
]
});
});
it('should create an instance', inject([DownloadImageFormComponent], (component: DownloadImageFormComponent) => {
expect(component).toBeTruthy();
}));
});
| Fix test to reflect the injected AppLoggerService | Fix test to reflect the injected AppLoggerService
| TypeScript | mit | ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2 | ---
+++
@@ -11,6 +11,7 @@
import { FormBuilder } from '@angular/forms';
import { Http, BaseRequestOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
+import { AppLoggerService } from '../../app-logger.service';
import { LocationsService } from '../locations.service';
import { SuitabilityMapService } from '../suitability-map.service';
import { MapConfig, MAP_CONFIG } from '../map.config';
@@ -24,6 +25,7 @@
MockBackend,
BaseRequestOptions,
FormBuilder,
+ AppLoggerService,
LocationsService,
SuitabilityMapService,
DownloadImageFormComponent, |
66e757569e92517e7c1ae77445a3e2348c96d24f | src/functions/getImages.ts | src/functions/getImages.ts | import { URL } from 'url';
import getObject from './getObject';
const getImages = (result: any): string[] => {
const origin = (new URL(result.url)).origin;
return getObject(result.html, 'name', 'img')
.filter((image: any) => {
return Object.prototype.hasOwnProperty.call(image, 'attribs') && Object.prototype.hasOwnProperty.call(image.attribs, 'src');
})
.map((image: any) => {
if (image.attribs.src.startsWith('./')) {
if (result.url.endsWith('/')) {
return result.url + image.attribs.src.substring(2);
}
return result.url + image.attribs.src.substring(1);
}
if (image.attribs.src.startsWith('/')) {
return origin + image.attribs.src;
}
if (!image.attribs.src.startsWith('http')) {
return origin + '/' + image.attribs.src;
}
return image.attribs.src;
});
};
export default getImages;
| import { URL } from 'url';
import getObject from './getObject';
const getImages = (result: any): string[] => {
const origin = (new URL(result.url)).origin;
return getObject(result.html, 'name', 'img')
.filter((image: any) => {
return Object.prototype.hasOwnProperty.call(image, 'attribs') && Object.prototype.hasOwnProperty.call(image.attribs, 'src');
})
.filter((image: any) => {
return !image.attribs.src.startsWith('data:image')
})
.map((image: any) => {
if (image.attribs.src.startsWith('./')) {
if (result.url.endsWith('/')) {
return result.url + image.attribs.src.substring(2);
}
return result.url + image.attribs.src.substring(1);
}
if (image.attribs.src.startsWith('/')) {
return origin + image.attribs.src;
}
if (!image.attribs.src.startsWith('http')) {
return origin + '/' + image.attribs.src;
}
return image.attribs.src;
});
};
export default getImages;
| Fix image check if base64 | Fix image check if base64
| TypeScript | mit | juffalow/pentest-tool-lite,juffalow/pentest-tool-lite | ---
+++
@@ -7,6 +7,9 @@
return getObject(result.html, 'name', 'img')
.filter((image: any) => {
return Object.prototype.hasOwnProperty.call(image, 'attribs') && Object.prototype.hasOwnProperty.call(image.attribs, 'src');
+ })
+ .filter((image: any) => {
+ return !image.attribs.src.startsWith('data:image')
})
.map((image: any) => {
if (image.attribs.src.startsWith('./')) { |
ff644b3066e18f232ce0b9de9129f34d42d3f35d | client/src/app/header/header.component.ts | client/src/app/header/header.component.ts | import { filter, map } from 'rxjs/operators'
import { Component, OnInit } from '@angular/core'
import { NavigationEnd, Router } from '@angular/router'
import { getParameterByName } from '../shared/misc/utils'
@Component({
selector: 'my-header',
templateUrl: './header.component.html',
styleUrls: [ './header.component.scss' ]
})
export class HeaderComponent implements OnInit {
searchValue = ''
constructor (private router: Router) {}
ngOnInit () {
this.router.events
.pipe(
filter(e => e instanceof NavigationEnd),
map(() => getParameterByName('search', window.location.href)),
filter(searchQuery => !!searchQuery)
)
.subscribe(searchQuery => this.searchValue = searchQuery)
}
doSearch () {
this.router.navigate([ '/videos', 'search' ], {
queryParams: { search: this.searchValue }
})
}
}
| import { filter, map } from 'rxjs/operators'
import { Component, OnInit } from '@angular/core'
import { NavigationEnd, Router } from '@angular/router'
import { getParameterByName } from '../shared/misc/utils'
@Component({
selector: 'my-header',
templateUrl: './header.component.html',
styleUrls: [ './header.component.scss' ]
})
export class HeaderComponent implements OnInit {
searchValue = ''
constructor (private router: Router) {}
ngOnInit () {
this.router.events
.pipe(
filter(e => e instanceof NavigationEnd),
map(() => getParameterByName('search', window.location.href))
)
.subscribe(searchQuery => this.searchValue = searchQuery || '')
}
doSearch () {
this.router.navigate([ '/videos', 'search' ], {
queryParams: { search: this.searchValue }
})
}
}
| Reset search on page change | Reset search on page change
| TypeScript | agpl-3.0 | Green-Star/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube | ---
+++
@@ -18,10 +18,9 @@
this.router.events
.pipe(
filter(e => e instanceof NavigationEnd),
- map(() => getParameterByName('search', window.location.href)),
- filter(searchQuery => !!searchQuery)
+ map(() => getParameterByName('search', window.location.href))
)
- .subscribe(searchQuery => this.searchValue = searchQuery)
+ .subscribe(searchQuery => this.searchValue = searchQuery || '')
}
doSearch () { |
99502f4819a9bfb1e7bfe5c2978b53b3f0862b93 | types/event-emitter/pipe.d.ts | types/event-emitter/pipe.d.ts | import { Emitter } from "event-emitter";
declare namespace pipe {
interface EmitterPipe {
close(): void;
}
}
declare function pipe(source: Emitter, target: Emitter, emitMethodName?: string | Symbol): pipe.EmitterPipe;
export = pipe;
| import { Emitter } from "event-emitter";
declare namespace pipe {
interface EmitterPipe {
close(): void;
}
}
declare function pipe(source: Emitter, target: Emitter, emitMethodName?: string | symbol): pipe.EmitterPipe;
export = pipe;
| Change symbol type to lowercase | Change symbol type to lowercase
| TypeScript | mit | laurentiustamate94/DefinitelyTyped,abbasmhd/DefinitelyTyped,mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,one-pieces/DefinitelyTyped,jimthedev/DefinitelyTyped,benishouga/DefinitelyTyped,jimthedev/DefinitelyTyped,chrootsu/DefinitelyTyped,arusakov/DefinitelyTyped,arusakov/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,benishouga/DefinitelyTyped,benishouga/DefinitelyTyped,zuzusik/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,aciccarello/DefinitelyTyped,rolandzwaga/DefinitelyTyped,georgemarshall/DefinitelyTyped,chrootsu/DefinitelyTyped,AgentME/DefinitelyTyped,aciccarello/DefinitelyTyped,jimthedev/DefinitelyTyped,nycdotnet/DefinitelyTyped,zuzusik/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,nycdotnet/DefinitelyTyped,zuzusik/DefinitelyTyped,benliddicott/DefinitelyTyped,borisyankov/DefinitelyTyped,alexdresko/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,rolandzwaga/DefinitelyTyped,ashwinr/DefinitelyTyped,aciccarello/DefinitelyTyped,AgentME/DefinitelyTyped,alexdresko/DefinitelyTyped,ashwinr/DefinitelyTyped,abbasmhd/DefinitelyTyped,markogresak/DefinitelyTyped,arusakov/DefinitelyTyped | ---
+++
@@ -6,5 +6,5 @@
}
}
-declare function pipe(source: Emitter, target: Emitter, emitMethodName?: string | Symbol): pipe.EmitterPipe;
+declare function pipe(source: Emitter, target: Emitter, emitMethodName?: string | symbol): pipe.EmitterPipe;
export = pipe; |
d7a32cf8a4b5f653be1fe8855f23411774183df8 | src/platforms/bitbucket.ts | src/platforms/bitbucket.ts | import Renderer from '../renderer'
class BitBucketRenderer extends Renderer {
getCodeDOM() {
return document.querySelector('.file-source .code')
}
getCode() {
return this.$code.innerText
}
getFontDOM() {
return this.$code.querySelector('span[class]')
}
getLineWidthAndHeight() {
return {
width: (<HTMLElement>document.querySelector('.file-source')).offsetWidth - 43,
height: 16
}
}
getPadding() {
return {
left: 10,
top: 8,
}
}
getTabSize() {
return 8
}
}
const renderer = new BitBucketRenderer()
// Dynamic injection
// https://github.com/OctoLinker/injection/blob/master/index.js
const $DOM = document.querySelector('#source-container')
const spy = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'childList' && mutation.addedNodes.length) {
new BitBucketRenderer()
}
})
})
spy.observe($DOM, {
attributes: true,
childList: true,
characterData: true
})
| import Renderer from '../renderer'
class BitBucketRenderer extends Renderer {
getCodeDOM() {
return document.querySelector('.file-source .code')
}
getCode() {
return this.$code.innerText
}
getFontDOM() {
return this.$code.querySelector('span[class]')
}
getLineWidthAndHeight() {
return {
width: (<HTMLElement>document.querySelector('.file-source')).offsetWidth - 43,
height: 16
}
}
getPadding() {
return {
left: 10,
top: 8,
}
}
getTabSize() {
return 8
}
}
const renderer = new BitBucketRenderer()
// Dynamic injection
// https://github.com/OctoLinker/injection/blob/master/index.js
const spy = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'childList' && mutation.addedNodes.length) {
new BitBucketRenderer()
}
})
})
const $DOM = document.querySelector('#source-container')
if ($DOM) {
spy.observe($DOM, {
attributes: true,
childList: true,
characterData: true
})
}
| Fix Bitbucket DOM not found error | Fix Bitbucket DOM not found error
| TypeScript | mit | pd4d10/intelli-octo,pd4d10/intelli-octo,pd4d10/intelli-octo | ---
+++
@@ -36,8 +36,6 @@
// Dynamic injection
// https://github.com/OctoLinker/injection/blob/master/index.js
-const $DOM = document.querySelector('#source-container')
-
const spy = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'childList' && mutation.addedNodes.length) {
@@ -46,8 +44,11 @@
})
})
-spy.observe($DOM, {
- attributes: true,
- childList: true,
- characterData: true
-})
+const $DOM = document.querySelector('#source-container')
+if ($DOM) {
+ spy.observe($DOM, {
+ attributes: true,
+ childList: true,
+ characterData: true
+ })
+} |
16036d4243de2ee0eae458e3db3f788d3a442a82 | backend/src/resolvers/Mutation/questions.ts | backend/src/resolvers/Mutation/questions.ts | import { Context } from '../../utils';
import { Question, QuestionCreateInput, QuestionUpdateInput } from '../../generated/prisma';
export interface QuestionPayload {
question: Question;
}
export const questions = {
async createQuestion(
parent,
{ input }: { input: QuestionCreateInput },
ctx: Context,
info,
): Promise<QuestionPayload> {
const newQuestion = await ctx.db.createQuestion({
...input,
});
return {
question: newQuestion,
};
},
async deleteQuestion(parent, { id }, ctx: Context, info): Promise<QuestionPayload> {
const questionExists = await ctx.db.$exists.question({
id,
});
if (!questionExists) {
throw new Error(`Question not found or you're not authorized`);
}
return {
question: await ctx.db.deleteQuestion({ id }),
};
},
async updateQuestion(
parent,
{ input: { id, patch } },
ctx: Context,
info,
): Promise<QuestionPayload> {
return {
question: await ctx.db.updateQuestion({
data: {
...patch,
},
where: {
id,
},
}),
};
},
};
| import { Context } from '../../utils';
// import { Question, QuestionCreateInput, QuestionUpdateInput } from '../../generated/prisma-client';
export const questions = {
async createQuestion(parent, { input }, ctx: Context, info) {
console.log('INPUT');
console.log(input);
const newQuestion = await ctx.db.createQuestion({
...input,
});
const newQuestionWithChoices = {
...newQuestion,
choices: await ctx.db.question({ id: newQuestion.id }).choices(),
};
return {
question: newQuestionWithChoices,
};
},
async deleteQuestion(parent, { id }, ctx: Context, info) {
const questionExists = await ctx.db.$exists.question({
id,
});
if (!questionExists) {
throw new Error(`Question not found or you're not authorized`);
}
return {
question: await ctx.db.deleteQuestion({ id }),
};
},
async updateQuestion(parent, { input: { id, patch } }, ctx: Context, info) {
return {
question: await ctx.db.updateQuestion({
data: {
...patch,
},
where: {
id,
},
}),
};
},
};
| Remove TS types from question mutation resolvers | Remove TS types from question mutation resolvers
There was a problem making the types work for the
'choices' field in the Question type.
| TypeScript | agpl-3.0 | iquabius/olimat,iquabius/olimat,iquabius/olimat | ---
+++
@@ -1,26 +1,23 @@
import { Context } from '../../utils';
-import { Question, QuestionCreateInput, QuestionUpdateInput } from '../../generated/prisma';
-
-export interface QuestionPayload {
- question: Question;
-}
+// import { Question, QuestionCreateInput, QuestionUpdateInput } from '../../generated/prisma-client';
export const questions = {
- async createQuestion(
- parent,
- { input }: { input: QuestionCreateInput },
- ctx: Context,
- info,
- ): Promise<QuestionPayload> {
+ async createQuestion(parent, { input }, ctx: Context, info) {
+ console.log('INPUT');
+ console.log(input);
const newQuestion = await ctx.db.createQuestion({
...input,
});
+ const newQuestionWithChoices = {
+ ...newQuestion,
+ choices: await ctx.db.question({ id: newQuestion.id }).choices(),
+ };
return {
- question: newQuestion,
+ question: newQuestionWithChoices,
};
},
- async deleteQuestion(parent, { id }, ctx: Context, info): Promise<QuestionPayload> {
+ async deleteQuestion(parent, { id }, ctx: Context, info) {
const questionExists = await ctx.db.$exists.question({
id,
});
@@ -33,12 +30,7 @@
};
},
- async updateQuestion(
- parent,
- { input: { id, patch } },
- ctx: Context,
- info,
- ): Promise<QuestionPayload> {
+ async updateQuestion(parent, { input: { id, patch } }, ctx: Context, info) {
return {
question: await ctx.db.updateQuestion({
data: { |
59ecc6fb13751304ba178758e98cdb1b29d7ccfb | src/app/components/ProgressCard.tsx | src/app/components/ProgressCard.tsx | import * as React from 'react';
import MUI from 'material-ui';
import Theme from './MurphyTheme';
interface Props {
progress: number;
message: string;
error: boolean;
}
export default class ProgressCard extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
static childContextTypes: any = {
muiTheme: React.PropTypes.object
}
private get styles() {
const padding: number = Theme.spacing.desktopGutter;
return {
progressMessage: {
fontSize: 14,
marginTop: padding / 2
},
error: {
color: 'red'
}
};
}
render() {
return (
<div>
<MUI.LinearProgress mode="determinate" value={this.props.progress * 100} color={this.props.error ? '#F44336' : undefined} />
<div style={this.styles.progressMessage}>{this.props.message}</div>
</div>
);
}
}
| import * as React from 'react';
import MUI from 'material-ui';
import Theme from './MurphyTheme';
interface Props {
progress: number;
message: string;
error: boolean;
}
export default class ProgressCard extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
static childContextTypes: any = {
muiTheme: React.PropTypes.object
}
private get styles() {
const padding: number = Theme.spacing.desktopGutter;
return {
progressMessage: {
fontSize: 14,
marginTop: padding / 2,
wordWrap: 'break-word'
},
error: {
color: 'red'
}
};
}
render() {
return (
<div>
<MUI.LinearProgress mode="determinate" value={this.props.progress * 100} color={this.props.error ? '#F44336' : undefined} />
<div style={this.styles.progressMessage}>{this.props.message}</div>
</div>
);
}
}
| Fix long filenames overflowing progress card. | Fix long filenames overflowing progress card.
| TypeScript | mit | bmats/murphy,bmats/murphy,bmats/murphy | ---
+++
@@ -22,7 +22,8 @@
return {
progressMessage: {
fontSize: 14,
- marginTop: padding / 2
+ marginTop: padding / 2,
+ wordWrap: 'break-word'
},
error: {
color: 'red' |
6ecd27e2c96e75b4dbb63f9089f2dfaded648140 | src/components/Table/TableUtils.tsx | src/components/Table/TableUtils.tsx | import {
PredefinedTableColumnState,
TagTableColumnState,
} from './TableColumnSelector';
export const ALL_TAGS_COLUMN_KEY = 'All Tags';
export type TaggedResource = { id: number };
export interface ResourceTagBase {
id: number;
tag_key: string;
value: string;
}
export const TableColumnStateStoredProps: Array<
keyof PredefinedTableColumnState | keyof TagTableColumnState
> = ['key', 'selected', 'type', 'tagKey'];
export const getResourceTags = <T extends TaggedResource, P extends keyof T>(
item: T,
tagField: P,
) => item?.[tagField] as ResourceTagBase[] | undefined;
export const getFromLocalStorage = <T extends any>(
key: string,
): T | undefined => {
try {
const val = localStorage.getItem(key);
if (val != null) {
return JSON.parse(val);
}
return undefined;
} catch (err) {
console.error(err);
return undefined;
}
};
export const setToLocalStorage = (key: string, value: any) => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (err) {
console.error(err);
}
};
export const removeFromLocalStorage = (key: string) => {
try {
localStorage.removeItem(key);
} catch (err) {
console.error(err);
}
};
| import {
PredefinedTableColumnState,
TagTableColumnState,
} from './TableColumnSelector';
export const ALL_TAGS_COLUMN_KEY = 'All Tags';
export type TaggedResource = {};
export interface ResourceTagBase extends TaggedResource {
tag_key: string;
value: string;
}
export const TableColumnStateStoredProps: Array<
keyof PredefinedTableColumnState | keyof TagTableColumnState
> = ['key', 'selected', 'type', 'tagKey'];
export const getResourceTags = <T extends TaggedResource, P extends keyof T>(
item: T,
tagField: P,
) => item?.[tagField] as ResourceTagBase[] | undefined;
export const getFromLocalStorage = <T extends any>(
key: string,
): T | undefined => {
try {
const val = localStorage.getItem(key);
if (val != null) {
return JSON.parse(val);
}
return undefined;
} catch (err) {
console.error(err);
return undefined;
}
};
export const setToLocalStorage = (key: string, value: any) => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (err) {
console.error(err);
}
};
export const removeFromLocalStorage = (key: string) => {
try {
localStorage.removeItem(key);
} catch (err) {
console.error(err);
}
};
| Remove the unnecessary id field requirement from the generic arg | Table: Remove the unnecessary id field requirement from the generic arg
Change-type: patch
Signed-off-by: Thodoris Greasidis <5791bdc4541e79bd43d586e3c3eff1e39c16665f@balena.io> | TypeScript | mit | resin-io-modules/resin-components,resin-io-modules/resin-components,resin-io-modules/resin-components | ---
+++
@@ -4,9 +4,8 @@
} from './TableColumnSelector';
export const ALL_TAGS_COLUMN_KEY = 'All Tags';
-export type TaggedResource = { id: number };
-export interface ResourceTagBase {
- id: number;
+export type TaggedResource = {};
+export interface ResourceTagBase extends TaggedResource {
tag_key: string;
value: string;
} |
94572c97a7132fdbac40570026ca186b1307cd20 | index.d.ts | index.d.ts | declare module 'connected-react-router' {
import * as React from 'react'
import { Action, Middleware, Reducer } from 'redux'
import { History, Path, LocationState, LocationDescriptorObject } from 'history'
interface ConnectedRouterProps {
history: History
}
export interface RouterState {
location: {
pathname: string,
search: string,
hash: string,
key: string,
},
action: 'POP' | 'PUSH'
}
export const LOCATION_CHANGE: string
export const CALL_HISTORY_METHOD: string
export function push(path: Path, state?: LocationState): Action
export function push(location: LocationDescriptorObject): Action
export function replace(path: Path, state?: LocationState): Action
export function replace(location: LocationDescriptorObject): Action
export function go(n: number): Action
export function goBack(): Action
export function goForward(): Action
export const routerActions: {
push: typeof push,
replace: typeof replace,
go: typeof go,
goBack: typeof goBack,
goForward: typeof goForward,
}
export class ConnectedRouter extends React.Component<ConnectedRouterProps, {}> {
}
export function connectRouter(history: History)
: <S>(reducer: Reducer<S>) => Reducer<S>
export function routerMiddleware(history: History): Middleware
}
| declare module 'connected-react-router' {
import * as React from 'react'
import { Action, Middleware, Reducer } from 'redux'
import { History, Path, LocationState, LocationDescriptorObject } from 'history'
interface ConnectedRouterProps {
history: History
}
export interface RouterState {
location: {
pathname: string,
search: string,
hash: string,
key: string,
},
action: 'POP' | 'PUSH'
}
export const LOCATION_CHANGE: '@@router/LOCATION_CHANGE'
export const CALL_HISTORY_METHOD: string
export function push(path: Path, state?: LocationState): Action
export function push(location: LocationDescriptorObject): Action
export function replace(path: Path, state?: LocationState): Action
export function replace(location: LocationDescriptorObject): Action
export function go(n: number): Action
export function goBack(): Action
export function goForward(): Action
export const routerActions: {
push: typeof push,
replace: typeof replace,
go: typeof go,
goBack: typeof goBack,
goForward: typeof goForward,
}
export class ConnectedRouter extends React.Component<ConnectedRouterProps, {}> {
}
export function connectRouter(history: History)
: <S>(reducer: Reducer<S>) => Reducer<S>
export function routerMiddleware(history: History): Middleware
}
| Use string literal type for action type | Use string literal type for action type | TypeScript | mit | supasate/connected-react-router | ---
+++
@@ -17,7 +17,7 @@
action: 'POP' | 'PUSH'
}
- export const LOCATION_CHANGE: string
+ export const LOCATION_CHANGE: '@@router/LOCATION_CHANGE'
export const CALL_HISTORY_METHOD: string
export function push(path: Path, state?: LocationState): Action |
b47db5dfd92c275e43c66e5f8dffb52c06d03aff | src/lib/util/AbstractVueTransitionController.ts | src/lib/util/AbstractVueTransitionController.ts | import AbstractTransitionController, { TransitionDirection } from 'transition-controller';
import { TimelineLite, TimelineMax } from 'gsap';
import isString from 'lodash/isString';
import isElement from 'lodash/isElement';
import IAbstractTransitionComponent from '../interface/IAbstractTransitionComponent';
export default abstract class AbstractVueTransitionController extends AbstractTransitionController<
IAbstractTransitionComponent
> {
/**
* @protected
* @abstract getSubTimelineByComponent
* @param {string | HTMLElement | T} component
* @param {TransitionDirection} direction
* @returns {gsap.TimelineLite | gsap.TimelineMax}
*/
protected getSubTimelineByComponent(
component: string | HTMLElement | IAbstractTransitionComponent,
direction: TransitionDirection,
): TimelineLite | TimelineMax {
let instance: IAbstractTransitionComponent;
if (isElement(component)) {
instance = <IAbstractTransitionComponent>this.parentController.$children.find(
child => child.$el === component,
);
} else if (isString(component)) {
instance = <IAbstractTransitionComponent>this.parentController.$children.find(
(child: IAbstractTransitionComponent) => child.$_componentId === component,
);
} else {
instance = <IAbstractTransitionComponent>component;
}
if (instance === undefined) {
throw new Error('Unable to find the requested component timeline');
}
if (direction === TransitionDirection.IN) {
return instance.transitionController.transitionInTimeline;
}
return instance.transitionController.transitionOutTimeline;
}
}
| import AbstractTransitionController, { TransitionDirection } from 'transition-controller';
import { TimelineLite, TimelineMax } from 'gsap';
import isString from 'lodash/isString';
import isElement from 'lodash/isElement';
import IAbstractTransitionComponent from '../interface/IAbstractTransitionComponent';
export default abstract class AbstractVueTransitionController extends AbstractTransitionController<
IAbstractTransitionComponent
> {
/**
* @protected
* @abstract getSubTimelineByComponent
* @param {string | HTMLElement | T} component
* @param {TransitionDirection} direction
* @returns {gsap.TimelineLite | gsap.TimelineMax}
*/
protected getSubTimelineByComponent(
component: string | HTMLElement | IAbstractTransitionComponent,
direction: TransitionDirection,
): TimelineLite | TimelineMax {
let instance: IAbstractTransitionComponent;
if (isElement(component)) {
instance = <IAbstractTransitionComponent>this.parentController.$children.find(
child => child.$el === component,
);
} else if (isString(component)) {
const instances = this.parentController.$children
.map((child: IAbstractTransitionComponent) => {
return child.$_componentId === component ? child : null;
})
.filter(value => value !== null);
if (instances.length > 1) {
throw new Error(
`Found multiple components matching [${component}], use a unique ref when requesting a component with an id`,
);
}
instance = instances.pop();
} else {
instance = <IAbstractTransitionComponent>component;
}
if (instance === undefined) {
throw new Error(`The requested component [${component}] does not exist`);
}
if (direction === TransitionDirection.IN) {
return instance.transitionController.transitionInTimeline;
}
return instance.transitionController.transitionOutTimeline;
}
}
| Throw an error when multiple components with the same ref are found | Throw an error when multiple components with the same ref are found
| TypeScript | mit | larsvanbraam/vue-transition-component,larsvanbraam/vue-transition-component,larsvanbraam/vue-transition-component | ---
+++
@@ -25,15 +25,25 @@
child => child.$el === component,
);
} else if (isString(component)) {
- instance = <IAbstractTransitionComponent>this.parentController.$children.find(
- (child: IAbstractTransitionComponent) => child.$_componentId === component,
- );
+ const instances = this.parentController.$children
+ .map((child: IAbstractTransitionComponent) => {
+ return child.$_componentId === component ? child : null;
+ })
+ .filter(value => value !== null);
+
+ if (instances.length > 1) {
+ throw new Error(
+ `Found multiple components matching [${component}], use a unique ref when requesting a component with an id`,
+ );
+ }
+
+ instance = instances.pop();
} else {
instance = <IAbstractTransitionComponent>component;
}
if (instance === undefined) {
- throw new Error('Unable to find the requested component timeline');
+ throw new Error(`The requested component [${component}] does not exist`);
}
if (direction === TransitionDirection.IN) { |
0a19c64b79d4ab32f1b53da3c0a02f86f4cb79b2 | src/rules/pr.ts | src/rules/pr.ts | // Provides dev-time type structures for `danger` - doesn't affect runtime.
import {DangerDSLType} from '../../node_modules/danger/distribution/dsl/DangerDSL';
declare var danger: DangerDSLType;
export declare function message(message: string): void;
export declare function warn(message: string): void;
export declare function fail(message: string): void;
export declare function markdown(message: string): void;
/**
* Taqtile Danger-js Plugin
*/
export default {
body() {
const body = danger.github.pr.body;
if (!body) {
fail('Please add a description to your PR.');
} else if (body.length < 10) {
warn('Your PR description is too short, please elaborate more.');
}
},
};
| // Provides dev-time type structures for `danger` - doesn't affect runtime.
import {DangerDSLType} from '../../node_modules/danger/distribution/dsl/DangerDSL';
declare const danger: DangerDSLType;
export declare function message(message: string): void;
export declare function warn(message: string): void;
export declare function fail(message: string): void;
export declare function markdown(message: string): void;
/**
* Taqtile Danger-js Plugin
*/
export default {
body() {
const body = danger.github.pr.body;
if (!body) {
fail('Please add a description to your PR.');
} else if (body.length < 10) {
warn('Your PR description is too short, please elaborate more.');
}
},
};
| Use const instead of var | Use const instead of var
| TypeScript | mit | indigotech/dangerjs-plugin | ---
+++
@@ -1,6 +1,6 @@
// Provides dev-time type structures for `danger` - doesn't affect runtime.
import {DangerDSLType} from '../../node_modules/danger/distribution/dsl/DangerDSL';
-declare var danger: DangerDSLType;
+declare const danger: DangerDSLType;
export declare function message(message: string): void;
export declare function warn(message: string): void;
export declare function fail(message: string): void; |
0c8788e96fa58dea69b4fcb93adafefd54a29f16 | src/ts/index.ts | src/ts/index.ts | export function insertHTMLBeforeBegin(element: HTMLElement, text: string) {
element.insertAdjacentHTML("beforebegin", text);
};
export function insertHTMLAfterBegin(element: HTMLElement, text: string) {
element.insertAdjacentHTML("afterbegin", text);
};
export function insertHTMLBeforeEnd(element: HTMLElement, text: string) {
element.insertAdjacentHTML("beforeend", text);
};
export function insertHTMLAfterEnd(element: HTMLElement, text: string) {
element.insertAdjacentHTML("afterend", text);
};
export function insertElementBeforeBegin(targetElement: HTMLElement, element: HTMLElement) {
targetElement.insertAdjacentElement("beforebegin", element);
};
export function insertElementAfterBegin(targetElement: HTMLElement, element: HTMLElement) {
targetElement.insertAdjacentElement("afterbegin", element);
};
export function insertElementBeforeEnd(targetElement: HTMLElement, element: HTMLElement) {
targetElement.insertAdjacentElement("beforeend", element);
};
export function insertElementAfterEnd(targetElement: HTMLElement, element: HTMLElement) {
targetElement.insertAdjacentElement("afterend", element);
};
| export function insertHTMLBeforeBegin(element: HTMLElement, text: string): void {
element.insertAdjacentHTML("beforebegin", text);
};
export function insertHTMLAfterBegin(element: HTMLElement, text: string): void {
element.insertAdjacentHTML("afterbegin", text);
};
export function insertHTMLBeforeEnd(element: HTMLElement, text: string): void {
element.insertAdjacentHTML("beforeend", text);
};
export function insertHTMLAfterEnd(element: HTMLElement, text: string): void {
element.insertAdjacentHTML("afterend", text);
};
export function insertElementBeforeBegin(targetElement: HTMLElement, element: HTMLElement): HTMLElement | null {
return targetElement.insertAdjacentElement("beforebegin", element);
};
export function insertElementAfterBegin(targetElement: HTMLElement, element: HTMLElement): HTMLElement | null {
return targetElement.insertAdjacentElement("afterbegin", element);
};
export function insertElementBeforeEnd(targetElement: HTMLElement, element: HTMLElement): HTMLElement | null {
return targetElement.insertAdjacentElement("beforeend", element);
};
export function insertElementAfterEnd(targetElement: HTMLElement, element: HTMLElement): HTMLElement | null {
return targetElement.insertAdjacentElement("afterend", element);
};
| Fix return value and type | Fix return value and type
| TypeScript | mit | tee-talog/insert-adjacent-simple,tee-talog/insert-adjacent-simple,tee-talog/insert-adjacent-simple | ---
+++
@@ -1,26 +1,26 @@
-export function insertHTMLBeforeBegin(element: HTMLElement, text: string) {
+export function insertHTMLBeforeBegin(element: HTMLElement, text: string): void {
element.insertAdjacentHTML("beforebegin", text);
};
-export function insertHTMLAfterBegin(element: HTMLElement, text: string) {
+export function insertHTMLAfterBegin(element: HTMLElement, text: string): void {
element.insertAdjacentHTML("afterbegin", text);
};
-export function insertHTMLBeforeEnd(element: HTMLElement, text: string) {
+export function insertHTMLBeforeEnd(element: HTMLElement, text: string): void {
element.insertAdjacentHTML("beforeend", text);
};
-export function insertHTMLAfterEnd(element: HTMLElement, text: string) {
+export function insertHTMLAfterEnd(element: HTMLElement, text: string): void {
element.insertAdjacentHTML("afterend", text);
};
-export function insertElementBeforeBegin(targetElement: HTMLElement, element: HTMLElement) {
- targetElement.insertAdjacentElement("beforebegin", element);
+export function insertElementBeforeBegin(targetElement: HTMLElement, element: HTMLElement): HTMLElement | null {
+ return targetElement.insertAdjacentElement("beforebegin", element);
};
-export function insertElementAfterBegin(targetElement: HTMLElement, element: HTMLElement) {
- targetElement.insertAdjacentElement("afterbegin", element);
+export function insertElementAfterBegin(targetElement: HTMLElement, element: HTMLElement): HTMLElement | null {
+ return targetElement.insertAdjacentElement("afterbegin", element);
};
-export function insertElementBeforeEnd(targetElement: HTMLElement, element: HTMLElement) {
- targetElement.insertAdjacentElement("beforeend", element);
+export function insertElementBeforeEnd(targetElement: HTMLElement, element: HTMLElement): HTMLElement | null {
+ return targetElement.insertAdjacentElement("beforeend", element);
};
-export function insertElementAfterEnd(targetElement: HTMLElement, element: HTMLElement) {
- targetElement.insertAdjacentElement("afterend", element);
+export function insertElementAfterEnd(targetElement: HTMLElement, element: HTMLElement): HTMLElement | null {
+ return targetElement.insertAdjacentElement("afterend", element);
};
|
19c884fa70b0998570ab7b3982893097560bd082 | src/app/space/create/apps/apps.component.ts | src/app/space/create/apps/apps.component.ts | import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import {
AppsService,
Environment,
} from './services/apps.service';
import { ISubscription } from 'rxjs/Subscription';
@Component({
encapsulation: ViewEncapsulation.None,
selector: 'alm-apps',
templateUrl: 'apps.component.html'
})
export class AppsComponent implements OnDestroy, OnInit {
spaceId: string;
environments: Environment[];
applications: string[];
private envSubscription: ISubscription = null;
private appSubscription: ISubscription = null;
constructor(
private router: Router,
private appsService: AppsService
) {
this.spaceId = 'placeholder-space';
}
ngOnDestroy(): void {
if (this.envSubscription) {
this.envSubscription.unsubscribe();
}
if (this.appSubscription) {
this.appSubscription.unsubscribe();
}
}
ngOnInit(): void {
this.updateResources();
}
private updateResources(): void {
this.envSubscription = this.appsService.getEnvironments(this.spaceId).subscribe(val => this.environments = val);
this.appSubscription = this.appsService.getApplications(this.spaceId).subscribe(val => this.applications = val);
}
}
| import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { ISubscription } from 'rxjs/Subscription';
import {
AppsService,
Environment,
} from './services/apps.service';
@Component({
encapsulation: ViewEncapsulation.None,
selector: 'alm-apps',
templateUrl: 'apps.component.html'
})
export class AppsComponent implements OnDestroy, OnInit {
spaceId: string;
environments: Environment[];
applications: string[];
private readonly unsubscribe: Subject<void> = new Subject<void>();
constructor(
private router: Router,
private appsService: AppsService
) {
this.spaceId = 'placeholder-space';
}
ngOnDestroy(): void {
this.unsubscribe.next();
this.unsubscribe.complete();
}
ngOnInit(): void {
this.updateResources();
}
private updateResources(): void {
this.appsService
.getEnvironments(this.spaceId)
.takeUntil(this.unsubscribe)
.subscribe(val => this.environments = val);
this.appsService
.getApplications(this.spaceId)
.takeUntil(this.unsubscribe)
.subscribe(val => this.applications = val);
}
}
| Use Subject to unsubscribe on destroy | Use Subject to unsubscribe on destroy
| TypeScript | apache-2.0 | fabric8io/fabric8-ui,fabric8-ui/fabric8-ui,fabric8io/fabric8-ui,fabric8-ui/fabric8-ui,fabric8-ui/fabric8-ui,fabric8-ui/fabric8-ui,fabric8io/fabric8-ui,fabric8io/fabric8-ui,fabric8-ui/fabric8-ui,fabric8io/fabric8-ui | ---
+++
@@ -1,11 +1,13 @@
import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
+
+import { Subject } from 'rxjs';
+import { ISubscription } from 'rxjs/Subscription';
import {
AppsService,
Environment,
} from './services/apps.service';
-import { ISubscription } from 'rxjs/Subscription';
@Component({
encapsulation: ViewEncapsulation.None,
@@ -17,8 +19,7 @@
environments: Environment[];
applications: string[];
- private envSubscription: ISubscription = null;
- private appSubscription: ISubscription = null;
+ private readonly unsubscribe: Subject<void> = new Subject<void>();
constructor(
private router: Router,
@@ -28,12 +29,8 @@
}
ngOnDestroy(): void {
- if (this.envSubscription) {
- this.envSubscription.unsubscribe();
- }
- if (this.appSubscription) {
- this.appSubscription.unsubscribe();
- }
+ this.unsubscribe.next();
+ this.unsubscribe.complete();
}
ngOnInit(): void {
@@ -41,8 +38,15 @@
}
private updateResources(): void {
- this.envSubscription = this.appsService.getEnvironments(this.spaceId).subscribe(val => this.environments = val);
- this.appSubscription = this.appsService.getApplications(this.spaceId).subscribe(val => this.applications = val);
+ this.appsService
+ .getEnvironments(this.spaceId)
+ .takeUntil(this.unsubscribe)
+ .subscribe(val => this.environments = val);
+
+ this.appsService
+ .getApplications(this.spaceId)
+ .takeUntil(this.unsubscribe)
+ .subscribe(val => this.applications = val);
}
} |
c4a15bcec22b6e339f1eac1bca4899f02d0c668a | src/adapter.ts | src/adapter.ts | export class Adapter {
private static FILE_TEMPLATE: string = "# Dependencies\n## For users\n{{dependencies}}\n\n## For developers\n{{devDependencies}}";
private static DEPENCENCY_TEMPLATE: string = "* [{{package_name}}]({{package_url}}) ({{package_version}})\n";
public static getFileOutput(dependencies: string[][]) {
}
private static getDependenciesOutput(dependencies: string[]): string {
let output = "";
Object.keys(dependencies).forEach(function (key) {
let name = key;
let version = dependencies[key];
let url = "https://www.npmjs.com/package/" + name;
let line = Adapter.DEPENCENCY_TEMPLATE
.replace("{{package_name}}", name)
.replace("{{package_url}}", url)
.replace("{{package_version}}", version);
output += line;
});
return output;
}
}
| export class Adapter {
private static FILE_TEMPLATE: string = "# Dependencies\n## For users\n{{dependencies}}\n\n## For developers\n{{devDependencies}}";
private static DEPENCENCY_TEMPLATE: string = "* [{{package_name}}]({{package_url}}) ({{package_version}})\n";
public static getFileOutput(dependencies: string[][]) {
}
private static getDependenciesOutput(dependencies: string[]): string {
if (!dependencies) {
return undefined;
}
let output = "";
Object.keys(dependencies).forEach(function (key) {
let name = key;
let version = dependencies[key];
let url = "https://www.npmjs.com/package/" + name;
let line = Adapter.DEPENCENCY_TEMPLATE
.replace("{{package_name}}", name)
.replace("{{package_url}}", url)
.replace("{{package_version}}", version);
output += line;
});
return output;
}
}
| Return undefined if deps not specified | Return undefined if deps not specified
| TypeScript | unlicense | Jameskmonger/dependument,dependument/dependument,dependument/dependument,Jameskmonger/dependument | ---
+++
@@ -3,10 +3,14 @@
private static DEPENCENCY_TEMPLATE: string = "* [{{package_name}}]({{package_url}}) ({{package_version}})\n";
public static getFileOutput(dependencies: string[][]) {
-
+
}
private static getDependenciesOutput(dependencies: string[]): string {
+ if (!dependencies) {
+ return undefined;
+ }
+
let output = "";
Object.keys(dependencies).forEach(function (key) { |
b0b3b5d7349701a1cfb8d4c583a345ef42ee30d9 | src/desktop.ts | src/desktop.ts | import { resolveContainer, registerContainer, ContainerRegistration, container } from "./registry";
import { Container } from "./container";
import { ContainerWindow } from "./window";
import * as Default from "./Default/default";
import * as Electron from "./Electron/electron";
import * as OpenFin from "./OpenFin/openfin";
const exportDesktopJS = {
Container,
ContainerWindow,
container,
registerContainer,
resolveContainer,
Default,
Electron,
OpenFin
};
export default exportDesktopJS; // tslint:disable-line
| import { resolveContainer, registerContainer, ContainerRegistration } from "./registry";
import { Container } from "./container";
import { ContainerWindow } from "./window";
import * as Default from "./Default/default";
import * as Electron from "./Electron/electron";
import * as OpenFin from "./OpenFin/openfin";
const exportDesktopJS = {
Container,
ContainerWindow,
registerContainer,
resolveContainer,
Default,
Electron,
OpenFin
};
export default exportDesktopJS; // tslint:disable-line
| Remove confusing "container" global export. The singleton can always be retrieved via resolveContainer(). | Remove confusing "container" global export. The singleton can always be retrieved via resolveContainer().
Fixes #59
| TypeScript | apache-2.0 | Morgan-Stanley/desktopJS,Morgan-Stanley/desktopJS,bingenito/desktopJS,Morgan-Stanley/desktopJS,bingenito/desktopJS,bingenito/desktopJS | ---
+++
@@ -1,4 +1,4 @@
-import { resolveContainer, registerContainer, ContainerRegistration, container } from "./registry";
+import { resolveContainer, registerContainer, ContainerRegistration } from "./registry";
import { Container } from "./container";
import { ContainerWindow } from "./window";
import * as Default from "./Default/default";
@@ -8,7 +8,6 @@
const exportDesktopJS = {
Container,
ContainerWindow,
- container,
registerContainer,
resolveContainer,
Default, |
30ddb43cf4cef772b3ca761ab7ac3d355b927196 | src/PhotoGallery/wwwroot/app/core/services/notificationService.ts | src/PhotoGallery/wwwroot/app/core/services/notificationService.ts | import { Injectable } from 'angular2/core';
@Injectable()
export class NotificationService {
private _notifier: any = alertify;
constructor() {
}
printSuccessMessage(message: string) {
this._notifier.success(message);
}
printErrorMessage(message: string) {
this._notifier.error(message);
}
printConfirmationDialog(message: string, okCallback: () => any) {
this._notifier.confirm(message, function (e) {
if (e) {
okCallback();
} else {
}
});
}
} | import { Injectable } from 'angular2/core';
declare var alertify: any;
@Injectable()
export class NotificationService {
private _notifier: any = alertify;
constructor() {
}
printSuccessMessage(message: string) {
this._notifier.success(message);
}
printErrorMessage(message: string) {
this._notifier.error(message);
}
printConfirmationDialog(message: string, okCallback: () => any) {
this._notifier.confirm(message, function (e) {
if (e) {
okCallback();
} else {
}
});
}
} | Use external JavaScript library (alertify.js) properly | Use external JavaScript library (alertify.js) properly
| TypeScript | mit | myomyinthan/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,jensoleg/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,chsakell/aspnet5-angular2-typescript,myomyinthan/aspnet5-angular2-typescript,jensoleg/aspnet5-angular2-typescript,jensoleg/aspnet5-angular2-typescript,myomyinthan/aspnet5-angular2-typescript,chsakell/aspnet5-angular2-typescript,chsakell/aspnet5-angular2-typescript,chsakell/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,xizhe-zhang/aspnet5-angular2-typescript,jensoleg/aspnet5-angular2-typescript,myomyinthan/aspnet5-angular2-typescript | ---
+++
@@ -1,4 +1,6 @@
import { Injectable } from 'angular2/core';
+
+declare var alertify: any;
@Injectable()
export class NotificationService { |
84ad557a802cd4f66f3c021802e7631dd433dcba | src/providers/oneNoteApiDataProvider.ts | src/providers/oneNoteApiDataProvider.ts | import {OneNoteDataProvider} from './oneNoteDataProvider';
import {Notebook} from '../oneNoteDataStructures/notebook';
import {OneNoteApiResponseTransformer} from '../oneNoteDataStructures/oneNoteApiResponseTransformer';
import {Section} from '../oneNoteDataStructures/section';
import {Page} from '../oneNoteDataStructures/page';
/**
* Implements OneNoteDataProvider with external calls to OneNote's API.
*/
export class OneNoteApiDataProvider implements OneNoteDataProvider {
private api: OneNoteApi.IOneNoteApi;
private responseTransformer: OneNoteApiResponseTransformer;
constructor(authToken: string) {
this.api = new OneNoteApi.OneNoteApi(authToken);
this.responseTransformer = new OneNoteApiResponseTransformer();
}
getNotebooks(expands?: number, excludeReadOnlyNotebooks?: boolean): Promise<Notebook[]> {
return this.api.getNotebooksWithExpandedSections(expands, excludeReadOnlyNotebooks).then((responsePackage) => {
return Promise.resolve(this.responseTransformer.transformNotebooks(responsePackage.parsedResponse.value));
});
}
getPages(section: Section): Promise<Page[]> {
return this.api.getPages({sectionId: section.id}).then((responsePackage) => {
return Promise.resolve(this.responseTransformer.transformPages(responsePackage.parsedResponse.value, section));
});
}
}
| import {OneNoteDataProvider} from './oneNoteDataProvider';
import {Notebook} from '../oneNoteDataStructures/notebook';
import {OneNoteApiResponseTransformer} from '../oneNoteDataStructures/oneNoteApiResponseTransformer';
import {Section} from '../oneNoteDataStructures/section';
import {Page} from '../oneNoteDataStructures/page';
/**
* Implements OneNoteDataProvider with external calls to OneNote's API.
*/
export class OneNoteApiDataProvider implements OneNoteDataProvider {
private api: OneNoteApi.IOneNoteApi;
private responseTransformer: OneNoteApiResponseTransformer;
constructor(authToken: string, timeout?: number, headers?: { [key: string]: string }) {
this.api = new OneNoteApi.OneNoteApi(authToken, timeout, headers);
this.responseTransformer = new OneNoteApiResponseTransformer();
}
getNotebooks(expands?: number, excludeReadOnlyNotebooks?: boolean): Promise<Notebook[]> {
return this.api.getNotebooksWithExpandedSections(expands, excludeReadOnlyNotebooks).then((responsePackage) => {
return Promise.resolve(this.responseTransformer.transformNotebooks(responsePackage.parsedResponse.value));
});
}
getPages(section: Section): Promise<Page[]> {
return this.api.getPages({sectionId: section.id}).then((responsePackage) => {
return Promise.resolve(this.responseTransformer.transformPages(responsePackage.parsedResponse.value, section));
});
}
}
| Allow dev to add timeout and header overrides to OneNoteApiDataProvider | Allow dev to add timeout and header overrides to OneNoteApiDataProvider
| TypeScript | mit | OneNoteDev/OneNotePicker-JS,OneNoteDev/OneNotePicker-JS,OneNoteDev/OneNotePicker-JS | ---
+++
@@ -11,8 +11,8 @@
private api: OneNoteApi.IOneNoteApi;
private responseTransformer: OneNoteApiResponseTransformer;
- constructor(authToken: string) {
- this.api = new OneNoteApi.OneNoteApi(authToken);
+ constructor(authToken: string, timeout?: number, headers?: { [key: string]: string }) {
+ this.api = new OneNoteApi.OneNoteApi(authToken, timeout, headers);
this.responseTransformer = new OneNoteApiResponseTransformer();
}
|
2597ca4ca7e2d1c39d52b3f5d28225ebf2b9ed57 | packages/schematics/src/scam/index.ts | packages/schematics/src/scam/index.ts | import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export function scam(options: ScamOptions): Rule {
return chain([
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
}),
]);
}
| import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export function scam(options: ScamOptions): Rule {
if (!options.separateModule) {
throw new Error('😱 Not implemented yet!');
}
return chain([
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
}),
]);
}
| Merge module and component as default behavior. | @wishtack/schematics:scam: Merge module and component as default behavior.
| TypeScript | mit | wishtack/wishtack-steroids,wishtack/ng-steroids,wishtack/ng-steroids,wishtack/wishtack-steroids,wishtack/wishtack-steroids | ---
+++
@@ -6,6 +6,10 @@
}
export function scam(options: ScamOptions): Rule {
+
+ if (!options.separateModule) {
+ throw new Error('😱 Not implemented yet!');
+ }
return chain([
externalSchematic('@schematics/angular', 'module', options), |
eeb11836edcd34f805c30d71c14e923ba80e6930 | src/components/shared/ImageSpacer.tsx | src/components/shared/ImageSpacer.tsx | import React from "react"
import styled from "styled-components"
const Container = styled.div`
width: 100vw;
left: 0;
overflow: hidden;
`
const ImagesContainer = styled.div`
width: 130%;
left: -15%;
position: relative;
display: flex;
justify-content: space-between;
`
const ImageContainer = styled.div`
width: 25%;
height: 300px;
overflow: hidden;
margin: 10px;
@media (max-width: 768px) {
height: 100px;
}
`
const Image = styled.img`
object-fit: cover;
height: 100%;
width: 100%;
overflow: hidden;
`
const images = [
"images/imagespacer/1.png",
"images/imagespacer/2.png",
"images/imagespacer/3.png",
"images/imagespacer/4.png",
]
export const ImageSpacer: React.FC = () => {
return (
<Container>
<ImagesContainer>
{images.map(image => (
<ImageContainer key={image}>
<Image src={image} />
</ImageContainer>
))}
</ImagesContainer>
</Container>
)
}
| import React from "react"
import styled from "styled-components"
import { StaticImage } from 'gatsby-plugin-image'
const Container = styled.div`
width: 100vw;
left: 0;
overflow: hidden;
`
const ImagesContainer = styled.div`
width: 130%;
left: -15%;
position: relative;
display: flex;
justify-content: space-between;
`
const ImageContainer = styled.div`
width: 25%;
height: 300px;
overflow: hidden;
margin: 10px;
@media (max-width: 768px) {
height: 100px;
}
`
const Image = styled.img`
object-fit: cover;
height: 100%;
width: 100%;
overflow: hidden;
`
const images = [
<StaticImage src="../../../static/images/imagespacer/1.png" alt={'image spacer 1'} />,
<StaticImage src="../../../static/images/imagespacer/2.png" alt={'image spacer 2'} />,
<StaticImage src="../../../static/images/imagespacer/3.png" alt={'image spacer 3'} />,
<StaticImage src="../../../static/images/imagespacer/4.png" alt={'image spacer 4'} />,
]
export const ImageSpacer: React.FC = () => {
return (
<Container>
<ImagesContainer>
{images.map(image => (
<ImageContainer key={image.key}>
{image}
</ImageContainer>
))}
</ImagesContainer>
</Container>
)
}
| Replace image spacer images with StaticImage | Replace image spacer images with StaticImage
| TypeScript | mit | bright/new-www,bright/new-www | ---
+++
@@ -1,5 +1,6 @@
import React from "react"
import styled from "styled-components"
+import { StaticImage } from 'gatsby-plugin-image'
const Container = styled.div`
width: 100vw;
@@ -33,10 +34,10 @@
`
const images = [
- "images/imagespacer/1.png",
- "images/imagespacer/2.png",
- "images/imagespacer/3.png",
- "images/imagespacer/4.png",
+ <StaticImage src="../../../static/images/imagespacer/1.png" alt={'image spacer 1'} />,
+ <StaticImage src="../../../static/images/imagespacer/2.png" alt={'image spacer 2'} />,
+ <StaticImage src="../../../static/images/imagespacer/3.png" alt={'image spacer 3'} />,
+ <StaticImage src="../../../static/images/imagespacer/4.png" alt={'image spacer 4'} />,
]
export const ImageSpacer: React.FC = () => {
@@ -44,8 +45,8 @@
<Container>
<ImagesContainer>
{images.map(image => (
- <ImageContainer key={image}>
- <Image src={image} />
+ <ImageContainer key={image.key}>
+ {image}
</ImageContainer>
))}
</ImagesContainer> |
a006f71d8e7b73d0173ac761d47ed2b803bd40b4 | gapi.auth2/gapi.auth2-tests.ts | gapi.auth2/gapi.auth2-tests.ts | /// <reference path="gapi.auth2.d.ts" />
function test_init(){
var auth = gapi.auth2.init();
}
function test_getAuthInstance(){
gapi.auth2.init();
var auth = gapi.auth2.getAuthInstance();
}
function test_render(){
var success = (googleUser: gapi.auth2.GoogleUser): void => {
console.log(googleUser);
};
var failure = (): void => {
console.log('Failure callback');
};
gapi.signin2.render('testId', {
scope: 'some scope',
width: 250,
height: 50,
longtitle: true,
theme: 'dark',
onsuccess: success,
onfailure: failure
});
}
| /// <reference path="gapi.auth2.d.ts" />
function test_init(){
var auth = gapi.auth2.init({
client_id: 'my-id',
cookie_policy: 'single_host_origin',
scope: 'https://www.googleapis.com/auth/plus.login',
fetch_basic_profile: true
});
}
function test_getAuthInstance(){
gapi.auth2.init({
client_id: 'my-id',
cookie_policy: 'single_host_origin',
scope: 'https://www.googleapis.com/auth/plus.login',
fetch_basic_profile: true
});
var auth = gapi.auth2.getAuthInstance();
}
function test_render(){
var success = (googleUser: gapi.auth2.GoogleUser): void => {
console.log(googleUser);
};
var failure = (): void => {
console.log('Failure callback');
};
gapi.signin2.render('testId', {
scope: 'https://www.googleapis.com/auth/plus.login',
width: 250,
height: 50,
longtitle: true,
theme: 'dark',
onsuccess: success,
onfailure: failure
});
}
| Add some missing required params to tests | Add some missing required params to tests
| TypeScript | mit | nakakura/DefinitelyTyped,mhegazy/DefinitelyTyped,donnut/DefinitelyTyped,trystanclarke/DefinitelyTyped,progre/DefinitelyTyped,rcchen/DefinitelyTyped,esperco/DefinitelyTyped,aciccarello/DefinitelyTyped,zuzusik/DefinitelyTyped,ashwinr/DefinitelyTyped,abner/DefinitelyTyped,Litee/DefinitelyTyped,rcchen/DefinitelyTyped,gcastre/DefinitelyTyped,johan-gorter/DefinitelyTyped,EnableSoftware/DefinitelyTyped,emanuelhp/DefinitelyTyped,progre/DefinitelyTyped,abbasmhd/DefinitelyTyped,MugeSo/DefinitelyTyped,scriby/DefinitelyTyped,stacktracejs/DefinitelyTyped,one-pieces/DefinitelyTyped,pocesar/DefinitelyTyped,Ptival/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,philippstucki/DefinitelyTyped,behzad888/DefinitelyTyped,pwelter34/DefinitelyTyped,chbrown/DefinitelyTyped,dsebastien/DefinitelyTyped,mattblang/DefinitelyTyped,paulmorphy/DefinitelyTyped,georgemarshall/DefinitelyTyped,danfma/DefinitelyTyped,damianog/DefinitelyTyped,abner/DefinitelyTyped,xStrom/DefinitelyTyped,alvarorahul/DefinitelyTyped,OpenMaths/DefinitelyTyped,applesaucers/lodash-invokeMap,optical/DefinitelyTyped,chrootsu/DefinitelyTyped,magny/DefinitelyTyped,pwelter34/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,psnider/DefinitelyTyped,Pro/DefinitelyTyped,micurs/DefinitelyTyped,Zzzen/DefinitelyTyped,shlomiassaf/DefinitelyTyped,EnableSoftware/DefinitelyTyped,dsebastien/DefinitelyTyped,yuit/DefinitelyTyped,georgemarshall/DefinitelyTyped,newclear/DefinitelyTyped,rolandzwaga/DefinitelyTyped,borisyankov/DefinitelyTyped,isman-usoh/DefinitelyTyped,psnider/DefinitelyTyped,Penryn/DefinitelyTyped,martinduparc/DefinitelyTyped,amanmahajan7/DefinitelyTyped,ashwinr/DefinitelyTyped,greglo/DefinitelyTyped,nycdotnet/DefinitelyTyped,Dashlane/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,jimthedev/DefinitelyTyped,schmuli/DefinitelyTyped,wilfrem/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,QuatroCode/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,arma-gast/DefinitelyTyped,xStrom/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,daptiv/DefinitelyTyped,paulmorphy/DefinitelyTyped,applesaucers/lodash-invokeMap,arusakov/DefinitelyTyped,chrootsu/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,damianog/DefinitelyTyped,scriby/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,Zorgatone/DefinitelyTyped,arusakov/DefinitelyTyped,chrismbarr/DefinitelyTyped,AgentME/DefinitelyTyped,optical/DefinitelyTyped,chrismbarr/DefinitelyTyped,nainslie/DefinitelyTyped,syuilo/DefinitelyTyped,tan9/DefinitelyTyped,YousefED/DefinitelyTyped,alvarorahul/DefinitelyTyped,johan-gorter/DefinitelyTyped,alextkachman/DefinitelyTyped,RX14/DefinitelyTyped,nitintutlani/DefinitelyTyped,tan9/DefinitelyTyped,AgentME/DefinitelyTyped,eugenpodaru/DefinitelyTyped,amir-arad/DefinitelyTyped,mhegazy/DefinitelyTyped,benishouga/DefinitelyTyped,raijinsetsu/DefinitelyTyped,Penryn/DefinitelyTyped,nfriend/DefinitelyTyped,borisyankov/DefinitelyTyped,behzad888/DefinitelyTyped,raijinsetsu/DefinitelyTyped,sledorze/DefinitelyTyped,martinduparc/DefinitelyTyped,syuilo/DefinitelyTyped,jimthedev/DefinitelyTyped,OpenMaths/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,isman-usoh/DefinitelyTyped,smrq/DefinitelyTyped,amanmahajan7/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,pocesar/DefinitelyTyped,gandjustas/DefinitelyTyped,UzEE/DefinitelyTyped,zuzusik/DefinitelyTyped,stephenjelfs/DefinitelyTyped,mcrawshaw/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,trystanclarke/DefinitelyTyped,RX14/DefinitelyTyped,hellopao/DefinitelyTyped,alexdresko/DefinitelyTyped,musicist288/DefinitelyTyped,sledorze/DefinitelyTyped,smrq/DefinitelyTyped,frogcjn/DefinitelyTyped,shlomiassaf/DefinitelyTyped,hellopao/DefinitelyTyped,MugeSo/DefinitelyTyped,arusakov/DefinitelyTyped,UzEE/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,rolandzwaga/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,reppners/DefinitelyTyped,use-strict/DefinitelyTyped,abbasmhd/DefinitelyTyped,mcrawshaw/DefinitelyTyped,stephenjelfs/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,AgentME/DefinitelyTyped,Zorgatone/DefinitelyTyped,mareek/DefinitelyTyped,subash-a/DefinitelyTyped,benishouga/DefinitelyTyped,yuit/DefinitelyTyped,minodisk/DefinitelyTyped,axelcostaspena/DefinitelyTyped,sclausen/DefinitelyTyped,nainslie/DefinitelyTyped,use-strict/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,florentpoujol/DefinitelyTyped,Pro/DefinitelyTyped,Zzzen/DefinitelyTyped,mareek/DefinitelyTyped,mattblang/DefinitelyTyped,philippstucki/DefinitelyTyped,newclear/DefinitelyTyped,Litee/DefinitelyTyped,frogcjn/DefinitelyTyped,nitintutlani/DefinitelyTyped,subash-a/DefinitelyTyped,arma-gast/DefinitelyTyped,vagarenko/DefinitelyTyped,Dashlane/DefinitelyTyped,jraymakers/DefinitelyTyped,florentpoujol/DefinitelyTyped,aciccarello/DefinitelyTyped,stacktracejs/DefinitelyTyped,esperco/DefinitelyTyped,zuzusik/DefinitelyTyped,alexdresko/DefinitelyTyped,schmuli/DefinitelyTyped,benliddicott/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,HPFOD/DefinitelyTyped,mcliment/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,reppners/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,nobuoka/DefinitelyTyped,minodisk/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,HPFOD/DefinitelyTyped,schmuli/DefinitelyTyped,nycdotnet/DefinitelyTyped,vagarenko/DefinitelyTyped,martinduparc/DefinitelyTyped,emanuelhp/DefinitelyTyped,jraymakers/DefinitelyTyped,nobuoka/DefinitelyTyped,sclausen/DefinitelyTyped,AgentME/DefinitelyTyped,alextkachman/DefinitelyTyped,danfma/DefinitelyTyped,ryan10132/DefinitelyTyped,georgemarshall/DefinitelyTyped,gcastre/DefinitelyTyped,benishouga/DefinitelyTyped,flyfishMT/DefinitelyTyped,greglo/DefinitelyTyped,hellopao/DefinitelyTyped,pocesar/DefinitelyTyped,flyfishMT/DefinitelyTyped,donnut/DefinitelyTyped,magny/DefinitelyTyped,QuatroCode/DefinitelyTyped,jimthedev/DefinitelyTyped,Ptival/DefinitelyTyped,YousefED/DefinitelyTyped,gandjustas/DefinitelyTyped,aciccarello/DefinitelyTyped,nakakura/DefinitelyTyped,psnider/DefinitelyTyped,wilfrem/DefinitelyTyped | ---
+++
@@ -1,11 +1,21 @@
/// <reference path="gapi.auth2.d.ts" />
function test_init(){
- var auth = gapi.auth2.init();
+ var auth = gapi.auth2.init({
+ client_id: 'my-id',
+ cookie_policy: 'single_host_origin',
+ scope: 'https://www.googleapis.com/auth/plus.login',
+ fetch_basic_profile: true
+ });
}
function test_getAuthInstance(){
- gapi.auth2.init();
+ gapi.auth2.init({
+ client_id: 'my-id',
+ cookie_policy: 'single_host_origin',
+ scope: 'https://www.googleapis.com/auth/plus.login',
+ fetch_basic_profile: true
+ });
var auth = gapi.auth2.getAuthInstance();
}
@@ -18,7 +28,7 @@
};
gapi.signin2.render('testId', {
- scope: 'some scope',
+ scope: 'https://www.googleapis.com/auth/plus.login',
width: 250,
height: 50,
longtitle: true, |
b601a025b58200ac04bedf738fdd9898c462a251 | src/utils/WellKnownUtils.ts | src/utils/WellKnownUtils.ts | /*
Copyright 2020 The Matrix.org Foundation C.I.C.
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 {MatrixClientPeg} from '../MatrixClientPeg';
const E2EE_WK_KEY = "im.vector.e2ee";
const E2EE_WK_KEY_DEPRECATED = "im.vector.riot.e2ee";
export interface IE2EEWellKnown {
default?: boolean;
}
export function getE2EEWellKnown(): IE2EEWellKnown {
const clientWellKnown = MatrixClientPeg.get().getClientWellKnown();
if (clientWellKnown && clientWellKnown[E2EE_WK_KEY]) {
return clientWellKnown[E2EE_WK_KEY];
}
if (clientWellKnown && clientWellKnown[E2EE_WK_KEY_DEPRECATED]) {
return clientWellKnown[E2EE_WK_KEY_DEPRECATED]
}
return null;
}
export function isSecureBackupRequired(): boolean {
const wellKnown = getE2EEWellKnown();
return wellKnown && wellKnown["secure_backup_required"] === true;
}
| /*
Copyright 2020 The Matrix.org Foundation C.I.C.
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 {MatrixClientPeg} from '../MatrixClientPeg';
const E2EE_WK_KEY = "io.element.e2ee";
const E2EE_WK_KEY_DEPRECATED = "im.vector.riot.e2ee";
export interface IE2EEWellKnown {
default?: boolean;
}
export function getE2EEWellKnown(): IE2EEWellKnown {
const clientWellKnown = MatrixClientPeg.get().getClientWellKnown();
if (clientWellKnown && clientWellKnown[E2EE_WK_KEY]) {
return clientWellKnown[E2EE_WK_KEY];
}
if (clientWellKnown && clientWellKnown[E2EE_WK_KEY_DEPRECATED]) {
return clientWellKnown[E2EE_WK_KEY_DEPRECATED]
}
return null;
}
export function isSecureBackupRequired(): boolean {
const wellKnown = getE2EEWellKnown();
return wellKnown && wellKnown["secure_backup_required"] === true;
}
| Use `io.element` instead of `im.vector` | Use `io.element` instead of `im.vector`
| TypeScript | apache-2.0 | matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk | ---
+++
@@ -16,7 +16,7 @@
import {MatrixClientPeg} from '../MatrixClientPeg';
-const E2EE_WK_KEY = "im.vector.e2ee";
+const E2EE_WK_KEY = "io.element.e2ee";
const E2EE_WK_KEY_DEPRECATED = "im.vector.riot.e2ee";
export interface IE2EEWellKnown { |
20fbbad5855dad478cd5b3f5e20b7c2b05e121f7 | src/plugins/StylusPlugin.ts | src/plugins/StylusPlugin.ts | import { PluginChain } from '../PluginChain';
import { File } from '../File';
import { WorkFlowContext } from '../WorkflowContext';
import { Plugin } from '../WorkflowContext';
let stylus;
export class StylusPluginClass implements Plugin {
public test: RegExp = /\.styl$/;
public options: any;
constructor (options: any) {
this.options = options || {};
}
public init (context: WorkFlowContext) {
context.allowExtension('.styl');
}
public transform (file: File): Promise<File> {
file.loadContents();
if (!stylus) stylus = require('stylus');
return new Promise((res, rej) => {
return stylus.render(file.contents, this.options, (err, css) => {
if (err) return rej(err);
file.contents = css;
return res(file);
});
});
}
}
export const StylusPlugin = (options: any) => {
return new StylusPluginClass(options);
} | import { PluginChain } from '../PluginChain';
import { File } from '../File';
import { WorkFlowContext } from '../WorkflowContext';
import { Plugin } from '../WorkflowContext';
let stylus;
export class StylusPluginClass implements Plugin {
public test: RegExp = /\.styl$/;
public options: any;
constructor (options: any) {
this.options = options || {};
}
public init (context: WorkFlowContext) {
context.allowExtension('.styl');
}
public transform (file: File): Promise<any> {
file.loadContents();
if (!stylus) stylus = require('stylus');
return new Promise((res, rej) => {
return stylus.render(file.contents, this.options, (err, css) => {
if (err) return rej(err);
file.contents = css;
return res(file);
});
});
}
}
export const StylusPlugin = (options: any) => {
return new StylusPluginClass(options);
} | Change ret type for transform method | Change ret type for transform method
| TypeScript | mit | fuse-box/fuse-box,pnml/fuse-box,fuse-box/fuse-box,rs3d/fuse-box,pnml/fuse-box,fuse-box/fuse-box,rs3d/fuse-box,rs3d/fuse-box,fuse-box/fuse-box,pnml/fuse-box | ---
+++
@@ -17,7 +17,7 @@
context.allowExtension('.styl');
}
- public transform (file: File): Promise<File> {
+ public transform (file: File): Promise<any> {
file.loadContents();
if (!stylus) stylus = require('stylus'); |
2e810a718919218c6dd9020d508be3d295cd93bb | src/__mocks__/next_model.ts | src/__mocks__/next_model.ts | import faker from 'faker';
export class Faker {
private static get positiveInteger(): number {
return faker.random.number({
min: 0,
max: Number.MAX_SAFE_INTEGER,
precision: 1,
});
}
private static get className(): string {
return faker.lorem.word();
}
static get modelName(): string {
return this.className;
}
static get limit(): number {
return this.positiveInteger;
}
static get skip(): number {
return this.positiveInteger;
}
};
| import faker from 'faker';
import {
Filter,
Schema,
ModelConstructor,
} from '../types';
function positiveInteger(): number {
return faker.random.number(Number.MAX_SAFE_INTEGER);
}
function className(): string {
return faker.lorem.word();
}
function propertyName(): string {
return faker.lorem.word().toLowerCase();
}
function type(): string {
return faker.lorem.word().toLowerCase();
}
const seed = positiveInteger();
console.log(`Running with seed ${seed}`)
faker.seed(seed);
export class Faker {
static get modelName(): string {
return className();
}
static get schema() {
return {}
}
static schemaByPropertyCount(count: number): Schema<any> {
let schema = {};
for (let i = 0; i < count; i++) {
const name = propertyName();
schema[name] = { type: type() };
if (faker.random.boolean) schema[name].defaultValue = faker.lorem.text;
}
return schema;
}
static get limit(): number {
return positiveInteger();
}
static get skip(): number {
return positiveInteger();
}
};
| Refactor mocks - add seed | Refactor mocks - add seed
| TypeScript | mit | tamino-martinius/node-next-model | ---
+++
@@ -1,27 +1,55 @@
import faker from 'faker';
+import {
+ Filter,
+ Schema,
+ ModelConstructor,
+} from '../types';
+
+function positiveInteger(): number {
+ return faker.random.number(Number.MAX_SAFE_INTEGER);
+}
+
+function className(): string {
+ return faker.lorem.word();
+}
+
+function propertyName(): string {
+ return faker.lorem.word().toLowerCase();
+}
+
+function type(): string {
+ return faker.lorem.word().toLowerCase();
+}
+
+const seed = positiveInteger();
+console.log(`Running with seed ${seed}`)
+faker.seed(seed);
+
export class Faker {
- private static get positiveInteger(): number {
- return faker.random.number({
- min: 0,
- max: Number.MAX_SAFE_INTEGER,
- precision: 1,
- });
+ static get modelName(): string {
+ return className();
}
- private static get className(): string {
- return faker.lorem.word();
+ static get schema() {
+ return {}
}
- static get modelName(): string {
- return this.className;
+ static schemaByPropertyCount(count: number): Schema<any> {
+ let schema = {};
+ for (let i = 0; i < count; i++) {
+ const name = propertyName();
+ schema[name] = { type: type() };
+ if (faker.random.boolean) schema[name].defaultValue = faker.lorem.text;
+ }
+ return schema;
}
static get limit(): number {
- return this.positiveInteger;
+ return positiveInteger();
}
static get skip(): number {
- return this.positiveInteger;
+ return positiveInteger();
}
}; |
780d3263ffdaf5e981e34a63f19a1bac7606ddf9 | src/components/todo-list.ts | src/components/todo-list.ts | import { VNode } from 'inferno'
import Component from 'inferno-component'
import h from 'inferno-hyperscript'
import Todo from './todo'
interface Props {
todoItems: {
title: string,
completed: boolean,
toggleItem: (number) => () => void,
removeItem: (number) => () => void
}[]
}
interface State {}
export default class TodoList extends Component<Props, State> {
render(): VNode {
const todoList = this.props.todoItems.map((item, i) => {
return h(Todo, {
...item,
toggle: this.props.toggleItem(i),
remove: this.props.removeItem(i)
})
})
return h('div', todoList)
}
}
| import { VNode } from 'inferno'
import Component from 'inferno-component'
import h from 'inferno-hyperscript'
import Todo from './todo'
interface Props {
todoItems: {
title: string,
completed: boolean
}[]
toggleItem: (number) => () => void
removeItem: (number) => () => void
}
interface State {}
export default class TodoList extends Component<Props, State> {
render(): VNode {
const todoList = this.props.todoItems.map((item, i) => {
return h(Todo, {
...item,
toggle: this.props.toggleItem(i),
remove: this.props.removeItem(i)
})
})
return h('div', todoList)
}
}
| Fix TodoList component Props interface | Fix TodoList component Props interface
| TypeScript | mit | y0za/typescript-inferno-todo,y0za/typescript-inferno-todo,y0za/typescript-inferno-todo | ---
+++
@@ -6,10 +6,10 @@
interface Props {
todoItems: {
title: string,
- completed: boolean,
- toggleItem: (number) => () => void,
- removeItem: (number) => () => void
+ completed: boolean
}[]
+ toggleItem: (number) => () => void
+ removeItem: (number) => () => void
}
interface State {} |
ffc74b51310f958a37b20d355292b24b7c7072bf | src/menu/bookmarks/components/Bookmarks/index.tsx | src/menu/bookmarks/components/Bookmarks/index.tsx | import { observer } from 'mobx-react';
import { hot } from 'react-hot-loader';
import React from 'react';
import AppStore from '../../../../app/store';
import Store from '../../store';
import db from '../../../../shared/models/app-database';
import Item from '../Item';
import TreeBar from '../TreeBar';
import { Content, Items } from './styles';
@observer
class Bookmarks extends React.Component {
public componentDidMount() {
this.loadBookmarks();
}
public loadBookmarks = async () => {
const bookmarks = await db.bookmarks.toArray();
db.favicons.each(favicon => {
if (AppStore.favicons[favicon.url] == null && favicon.favicon.byteLength !== 0) {
AppStore.favicons[favicon.url] = window.URL.createObjectURL(new Blob([favicon.favicon]));
}
});
Store.bookmarks = bookmarks;
Store.goTo(-1);
};
public render() {
return (
<React.Fragment>
<TreeBar />
<Content>
{Store.bookmarks.length > 0 && (
<Items>
{Store.bookmarks.map(data => {
if (data.parent === Store.currentTree) {
return <Item data={data} key={data.id} />;
}
return null;
})}
</Items>
)}
</Content>
</React.Fragment>
);
}
}
export default hot(module)(Bookmarks);
| import { observer } from 'mobx-react';
import { hot } from 'react-hot-loader';
import React from 'react';
import AppStore from '../../../../app/store';
import Store from '../../store';
import db from '../../../../shared/models/app-database';
import Item from '../Item';
import TreeBar from '../TreeBar';
import { Content, Items } from './styles';
@observer
class Bookmarks extends React.Component {
public componentDidMount() {
this.loadBookmarks();
}
public loadBookmarks = async () => {
const bookmarks = await db.bookmarks.toArray();
db.favicons.each(favicon => {
if (AppStore.favicons[favicon.url] == null && favicon.favicon.byteLength !== 0) {
AppStore.favicons[favicon.url] = window.URL.createObjectURL(new Blob([favicon.favicon]));
}
});
Store.bookmarks = bookmarks;
Store.goTo(-1);
};
public render() {
const items = Store.bookmarks.filter(r => r.parent === Store.currentTree);
return (
<React.Fragment>
<TreeBar />
<Content>
{items.length > 0 && (
<Items>
{items.map(data => <Item data={data} key={data.id} />)}
</Items>
)}
</Content>
</React.Fragment>
);
}
}
export default hot(module)(Bookmarks);
| Fix empty container in bookmarks | Fix empty container in bookmarks
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -28,18 +28,15 @@
};
public render() {
+ const items = Store.bookmarks.filter(r => r.parent === Store.currentTree);
+
return (
<React.Fragment>
<TreeBar />
<Content>
- {Store.bookmarks.length > 0 && (
+ {items.length > 0 && (
<Items>
- {Store.bookmarks.map(data => {
- if (data.parent === Store.currentTree) {
- return <Item data={data} key={data.id} />;
- }
- return null;
- })}
+ {items.map(data => <Item data={data} key={data.id} />)}
</Items>
)}
</Content> |
d40eab44fbe0be77545758e7251be8b71fd38317 | packages/coreutils/src/time.ts | packages/coreutils/src/time.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import moment from 'moment';
/**
* The namespace for date functions.
*/
export namespace Time {
/**
* Convert a timestring to a human readable string (e.g. 'two minutes ago').
*
* @param value - The date timestring or date object.
*
* @returns A formatted date.
*/
export function formatHuman(value: string | Date): string {
let time = moment(value).fromNow();
time = time === 'a few seconds ago' ? 'seconds ago' : time;
return time;
}
/**
* Convert a timestring to a date format.
*
* @param value - The date timestring or date object.
*
* @param format - The format string.
*
* @returns A formatted date.
*/
export function format(
value: string | Date,
format = 'YYYY-MM-DD HH:mm'
): string {
return moment(value).format(format);
}
}
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import moment from 'moment';
/**
* The namespace for date functions.
*/
export namespace Time {
/**
* Convert a timestring to a human readable string (e.g. 'two minutes ago').
*
* @param value - The date timestring or date object.
*
* @returns A formatted date.
*/
export function formatHuman(value: string | Date): string {
let time = moment(value).fromNow();
time = time === 'a few seconds ago' ? 'seconds ago' : time;
return time;
}
/**
* Convert a timestring to a date format.
*
* @param value - The date timestring or date object.
*
* @param format - The format string.
*
* @returns A formatted date.
*/
export function format(
value: string | Date,
timeFormat = 'YYYY-MM-DD HH:mm'
): string {
return moment(value).format(timeFormat);
}
}
| Fix duplicate parameter in function with default parameter values | Fix duplicate parameter in function with default parameter values
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -31,8 +31,8 @@
*/
export function format(
value: string | Date,
- format = 'YYYY-MM-DD HH:mm'
+ timeFormat = 'YYYY-MM-DD HH:mm'
): string {
- return moment(value).format(format);
+ return moment(value).format(timeFormat);
}
} |
148b71ca66df74a03178b12f5b04fe5e0db7134e | src/mobile/lib/model/MstGoal.ts | src/mobile/lib/model/MstGoal.ts | import {MstSvt} from "../../../model/master/Master";
import {MstSkillContainer, MstSvtSkillContainer, MstCombineSkillContainer} from "../../../model/impl/MstContainer";
export interface MstGoal {
appVer: string;
svtRawData: Array<MstSvt>;
svtSkillData: MstSvtSkillContainer;
skillCombineData: MstCombineSkillContainer;
skillData: MstSkillContainer;
current: Goal;
goals: Array<Goal>;
}
export interface Goal {
id: string; // UUID
name: string;
servants: Array<GoalSvt>;
}
export interface GoalSvt {
svtId: number;
skills: Array<GoalSvtSkill>;
}
export interface GoalSvtSkill {
skillId: number;
level: number;
}
export const defaultCurrentGoal = {
id: "current",
name: "current",
servants: [],
} as Goal;
export const defaultMstGoal = {
appVer: undefined,
current: undefined,
goals: [],
} as MstGoal; | import {MstSvt} from "../../../model/master/Master";
import {MstSkillContainer, MstSvtSkillContainer, MstCombineSkillContainer} from "../../../model/impl/MstContainer";
export interface MstGoal {
appVer: string;
svtRawData: Array<MstSvt>;
svtSkillData: MstSvtSkillContainer;
skillCombineData: MstCombineSkillContainer;
skillData: MstSkillContainer;
current: Goal;
goals: Array<Goal>;
compareSourceId: string; // UUID of one Goal
compareTargetId: string; // UUID of one Goal
}
export interface Goal {
id: string; // UUID
name: string;
servants: Array<GoalSvt>;
}
export interface GoalSvt {
svtId: number;
skills: Array<GoalSvtSkill>;
}
export interface GoalSvtSkill {
skillId: number;
level: number;
}
export const defaultCurrentGoal = {
id: "current",
name: "current",
servants: [],
} as Goal;
export const defaultMstGoal = {
appVer: undefined,
current: undefined,
goals: [],
compareSourceId: "current",
compareTargetId: "current",
} as MstGoal; | Add compare ids into state. | Add compare ids into state.
| TypeScript | mit | agreatfool/fgo-handbook,agreatfool/fgo-handbook,agreatfool/fgo-handbook,agreatfool/fgo-handbook,agreatfool/fgo-handbook,agreatfool/fgo-handbook | ---
+++
@@ -9,6 +9,8 @@
skillData: MstSkillContainer;
current: Goal;
goals: Array<Goal>;
+ compareSourceId: string; // UUID of one Goal
+ compareTargetId: string; // UUID of one Goal
}
export interface Goal {
@@ -37,4 +39,6 @@
appVer: undefined,
current: undefined,
goals: [],
+ compareSourceId: "current",
+ compareTargetId: "current",
} as MstGoal; |
a9b358d46fd2779fb83997a6439d23357f4a7724 | packages/components/components/input/FileInput.tsx | packages/components/components/input/FileInput.tsx | import { ChangeEvent, DetailedHTMLProps, forwardRef, InputHTMLAttributes, ReactNode, Ref, useRef } from 'react';
import { ButtonLike, Color, Shape } from '../button';
import { useCombinedRefs } from '../../hooks';
export interface Props extends DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> {
children: ReactNode;
id?: string;
className?: string;
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
disabled?: boolean;
shape?: Shape;
color?: Color;
}
const FileInput = (
{ children, id = 'fileInput', className, onChange, disabled, shape, color, ...rest }: Props,
ref: Ref<HTMLInputElement>
) => {
const inputRef = useRef<HTMLInputElement>(null);
const combinedRef = useCombinedRefs(inputRef, ref);
return (
<ButtonLike as="label" htmlFor={id} className={className} disabled={disabled} shape={shape} color={color}>
<input
id={id}
type="file"
className="hidden"
onChange={(e) => {
onChange(e);
if (inputRef.current) {
// Reset it to allow to select the same file again.
inputRef.current.value = '';
}
}}
{...rest}
ref={combinedRef}
/>
{children}
</ButtonLike>
);
};
export default forwardRef<HTMLInputElement, Props>(FileInput);
| import { ChangeEvent, DetailedHTMLProps, forwardRef, InputHTMLAttributes, ReactNode, Ref, useRef } from 'react';
import { ButtonLike, Color, Shape } from '../button';
import { useCombinedRefs } from '../../hooks';
export interface Props extends DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> {
children: ReactNode;
id?: string;
className?: string;
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
disabled?: boolean;
shape?: Shape;
color?: Color;
}
const FileInput = (
{ children, id = 'fileInput', className, onChange, disabled, shape, color, ...rest }: Props,
ref: Ref<HTMLInputElement>
) => {
const inputRef = useRef<HTMLInputElement>(null);
const combinedRef = useCombinedRefs(inputRef, ref);
return (
<ButtonLike as="label" htmlFor={id} className={className} disabled={disabled} shape={shape} color={color}>
<input
id={id}
type="file"
className="sr-only"
onChange={(e) => {
onChange(e);
if (inputRef.current) {
// Reset it to allow to select the same file again.
inputRef.current.value = '';
}
}}
{...rest}
ref={combinedRef}
/>
{children}
</ButtonLike>
);
};
export default forwardRef<HTMLInputElement, Props>(FileInput);
| Make the file input accessible by keyboard | Make the file input accessible by keyboard
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -24,7 +24,7 @@
<input
id={id}
type="file"
- className="hidden"
+ className="sr-only"
onChange={(e) => {
onChange(e);
if (inputRef.current) { |
a5484665cb6ee75c58d9625abc561c5da5874e81 | packages/sonarwhal/tests/helpers/rule-test-type.ts | packages/sonarwhal/tests/helpers/rule-test-type.ts | import { ProblemLocation } from '../../src/lib/types';
export type Report = {
/** The message to validate */
message: string;
position?: ProblemLocation;
};
export type RuleTest = {
/** The code to execute before `closing` the connector. */
after?(): void | Promise<void>;
/** The code to execute before creating the connector. */
before?(): void | Promise<void>;
/** The name of the test. */
name: string;
/** The expected results of the execution. */
reports?: Array<Report>;
/** The configuration `test-server` should use. */
serverConfig?: any;
/** The url to `executeOn` if different than `localhost`. */
serverUrl?: string;
};
export type RuleLocalTest = {
/** The code to execute before `closing` the connector. */
after?(context?): void | Promise<void>;
/** The code to execute before creating the connector. */
before?(context?): void | Promise<void>;
/** Path to send to the local connector. */
path: string;
/** The name of the test. */
name: string;
/** The expected results of the execution. */
reports?: Array<Report>;
};
| import { AnyContext } from 'ava';
import { ProblemLocation } from '../../src/lib/types';
export type Report = {
/** The message to validate */
message: string;
position?: ProblemLocation;
};
export type RuleTest = {
/** The code to execute before `closing` the connector. */
after?(): void | Promise<void>;
/** The code to execute before creating the connector. */
before?(): void | Promise<void>;
/** The name of the test. */
name: string;
/** The expected results of the execution. */
reports?: Array<Report>;
/** The configuration `test-server` should use. */
serverConfig?: any;
/** The url to `executeOn` if different than `localhost`. */
serverUrl?: string;
};
export type RuleLocalTest = {
/** The code to execute before `closing` the connector. */
after?(context?: AnyContext): void | Promise<void>;
/** The code to execute before creating the connector. */
before?(context?: AnyContext): void | Promise<void>;
/** Path to send to the local connector. */
path: string;
/** The name of the test. */
name: string;
/** The expected results of the execution. */
reports?: Array<Report>;
};
| Add explicit type to `context` | Chore: Add explicit type to `context`
| TypeScript | apache-2.0 | sonarwhal/sonar,sonarwhal/sonar,sonarwhal/sonar | ---
+++
@@ -1,3 +1,5 @@
+import { AnyContext } from 'ava';
+
import { ProblemLocation } from '../../src/lib/types';
export type Report = {
@@ -23,9 +25,9 @@
export type RuleLocalTest = {
/** The code to execute before `closing` the connector. */
- after?(context?): void | Promise<void>;
+ after?(context?: AnyContext): void | Promise<void>;
/** The code to execute before creating the connector. */
- before?(context?): void | Promise<void>;
+ before?(context?: AnyContext): void | Promise<void>;
/** Path to send to the local connector. */
path: string;
/** The name of the test. */ |
0ae7108bbee406d23fcb9f7a429aad893d5871e8 | vscode-extensions/vscode-bosh/lib/Main.ts | vscode-extensions/vscode-bosh/lib/Main.ts | 'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as VSCode from 'vscode';
import * as commons from 'commons-vscode';
import * as Path from 'path';
import * as FS from 'fs';
import * as Net from 'net';
import * as ChildProcess from 'child_process';
import {LanguageClient, LanguageClientOptions, SettingMonitor, ServerOptions, StreamInfo} from 'vscode-languageclient';
import {TextDocument, OutputChannel} from 'vscode';
var log_output : OutputChannel = null;
function log(msg : string) {
if (log_output) {
log_output.append(msg +"\n");
}
}
function error(msg : string) {
if (log_output) {
log_output.append("ERR: "+msg+"\n");
}
}
/** Called when extension is activated */
export function activate(context: VSCode.ExtensionContext) {
let options : commons.ActivatorOptions = {
DEBUG : false,
CONNECT_TO_LS: false,
extensionId: 'vscode-bosh',
launcher: (context: VSCode.ExtensionContext) => Path.resolve(context.extensionPath, 'jars/language-server.jar'),
jvmHeap: "48m",
clientOptions: {
documentSelector: [
"bosh-deployment-manifest",
"bosh-cloud-config"
],
synchronize: {
configurationSection: "bosh"
}
}
};
let clientPromise = commons.activate(options, context);
}
| 'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as VSCode from 'vscode';
import * as commons from 'commons-vscode';
import * as Path from 'path';
import * as FS from 'fs';
import * as Net from 'net';
import * as ChildProcess from 'child_process';
import {LanguageClient, LanguageClientOptions, SettingMonitor, ServerOptions, StreamInfo} from 'vscode-languageclient';
import {TextDocument, OutputChannel} from 'vscode';
var log_output : OutputChannel = null;
function log(msg : string) {
if (log_output) {
log_output.append(msg +"\n");
}
}
function error(msg : string) {
if (log_output) {
log_output.append("ERR: "+msg+"\n");
}
}
/** Called when extension is activated */
export function activate(context: VSCode.ExtensionContext) {
let options : commons.ActivatorOptions = {
DEBUG : false,
CONNECT_TO_LS: false,
extensionId: 'vscode-bosh',
jvmHeap: "48m",
clientOptions: {
documentSelector: [
"bosh-deployment-manifest",
"bosh-cloud-config"
],
synchronize: {
configurationSection: "bosh"
}
}
};
let clientPromise = commons.activate(options, context);
}
| Fix compile error in vscode-bosh | Fix compile error in vscode-bosh
| TypeScript | epl-1.0 | spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4 | ---
+++
@@ -31,7 +31,6 @@
DEBUG : false,
CONNECT_TO_LS: false,
extensionId: 'vscode-bosh',
- launcher: (context: VSCode.ExtensionContext) => Path.resolve(context.extensionPath, 'jars/language-server.jar'),
jvmHeap: "48m",
clientOptions: {
documentSelector: [ |
fe51e127feec8bd90d001a00c00503f7b4317645 | server/methods/quiz.methods.ts | server/methods/quiz.methods.ts | import {Meteor} from 'meteor/meteor';
import {Quiz} from "../../both/models/quiz.model";
import {QuizCollection} from "../../both/collections/quiz.collection";
Meteor.methods({
saveQuiz: function(quizModel: Quiz) {
return QuizCollection.insert(quizModel);
}
}); | import {Meteor} from 'meteor/meteor';
import {Quiz} from "../../both/models/quiz.model";
import {QuizCollection} from "../../both/collections/quiz.collection";
Meteor.methods({
saveQuiz: function(quizModel: Quiz) {
return QuizCollection.collection.insert(quizModel);
}
}); | Use collection to get the id of the inserted quiz | Use collection to get the id of the inserted quiz
| TypeScript | mit | prikril/ro-inf-sa,prikril/ro-inf-sa | ---
+++
@@ -5,6 +5,6 @@
Meteor.methods({
saveQuiz: function(quizModel: Quiz) {
- return QuizCollection.insert(quizModel);
+ return QuizCollection.collection.insert(quizModel);
}
}); |
424436579ba6a4d55e501e5cdc191c95a43ccaa7 | src/file/index.ts | src/file/index.ts | export * from "./paragraph";
export * from "./table";
export * from "./file";
export * from "./numbering";
export * from "./media";
export * from "./drawing";
export * from "./styles";
export * from "./xml-components"; | export * from "./paragraph";
export * from "./table";
export * from "./file";
export * from "./numbering";
export * from "./media";
export * from "./drawing";
export * from "./styles";
| Remove xml component from main export | Remove xml component from main export
| TypeScript | mit | dolanmiu/docx,dolanmiu/docx,dolanmiu/docx | ---
+++
@@ -5,4 +5,3 @@
export * from "./media";
export * from "./drawing";
export * from "./styles";
-export * from "./xml-components"; |
135df63af498bd12b7bb12fd8797e55f71128d13 | src/models/context.ts | src/models/context.ts | import * as Discord from 'discord.js';
import * as mongoose from 'mongoose';
import { logInteraction } from '../helpers/logger';
export default class Context {
id: string;
bot: Discord.Client;
channel: Discord.TextChannel | Discord.DMChannel | Discord.NewsChannel;
guild: Discord.Guild;
msg: string;
preferences: mongoose.Document;
db: mongoose.Connection;
shard: number;
logInteraction;
constructor(id: string, bot: Discord.Client, channel: Discord.TextChannel | Discord.DMChannel | Discord.NewsChannel, guild: Discord.Guild,
msg: string, preferences: mongoose.Document, db: mongoose.Connection) {
this.id = id;
this.bot = bot;
this.msg = msg;
this.channel = channel;
this.guild = guild;
this.preferences = preferences;
this.db = db;
this.shard = guild.shardID;
this.logInteraction = logInteraction;
}
} | import * as Discord from 'discord.js';
import * as mongoose from 'mongoose';
import { logInteraction } from '../helpers/logger';
export default class Context {
id: string;
bot: Discord.Client;
channel: Discord.TextChannel | Discord.DMChannel;
guild: Discord.Guild;
msg: string;
preferences: mongoose.Document;
db: mongoose.Connection;
shard: number;
logInteraction;
constructor(id: string, bot: Discord.Client, channel: Discord.TextChannel | Discord.DMChannel, guild: Discord.Guild,
msg: string, preferences: mongoose.Document, db: mongoose.Connection) {
this.id = id;
this.bot = bot;
this.msg = msg;
this.channel = channel;
this.guild = guild;
this.preferences = preferences;
this.db = db;
this.shard = guild.shardID;
this.logInteraction = logInteraction;
}
} | Remove extraneous channel type in Context model. | Remove extraneous channel type in Context model.
| TypeScript | mpl-2.0 | BibleBot/BibleBot,BibleBot/BibleBot,BibleBot/BibleBot | ---
+++
@@ -5,7 +5,7 @@
export default class Context {
id: string;
bot: Discord.Client;
- channel: Discord.TextChannel | Discord.DMChannel | Discord.NewsChannel;
+ channel: Discord.TextChannel | Discord.DMChannel;
guild: Discord.Guild;
msg: string;
preferences: mongoose.Document;
@@ -13,7 +13,7 @@
shard: number;
logInteraction;
- constructor(id: string, bot: Discord.Client, channel: Discord.TextChannel | Discord.DMChannel | Discord.NewsChannel, guild: Discord.Guild,
+ constructor(id: string, bot: Discord.Client, channel: Discord.TextChannel | Discord.DMChannel, guild: Discord.Guild,
msg: string, preferences: mongoose.Document, db: mongoose.Connection) {
this.id = id;
this.bot = bot; |
84c9b0a29e64ab99ce689c239da54aa538b24db4 | modules/interfaces/src/functional-group.ts | modules/interfaces/src/functional-group.ts | import { CustomCommandDefinition } from "./custom-command-definition";
import { CustomQueryDefinition } from "./custom-query-definition";
import { EntityDefinition } from "./entity-definition";
import { UserDefinition } from "./user-definition";
export type EntityDefinitions = {
[EntityName: string]: EntityDefinition;
};
export type CustomQueryDefinitions = {
[QueryName: string]: CustomQueryDefinition;
};
export type CustomCommandDefinitions = {
[CommandName: string]: CustomCommandDefinition;
};
export type UserDefinitions = {
[EntityName: string]: UserDefinition;
};
export type NormalizedFunctionalGroup = {
users: UserDefinitions;
nonUsers: EntityDefinitions;
customQueries: CustomQueryDefinitions;
customCommands: CustomCommandDefinitions;
};
export type FunctionalGroup = Partial<NormalizedFunctionalGroup>;
| import { CustomCommandDefinition } from "./custom-command-definition";
import { CustomQueryDefinition } from "./custom-query-definition";
import { EntityDefinition } from "./entity-definition";
import { UserDefinition } from "./user-definition";
import {
GeneralTypeMap,
UserEntityNameOf,
NonUserEntityNameOf,
CustomQueryNameOf,
CustomCommandNameOf
} from "./type-map";
export type EntityDefinitions = {
[EntityName: string]: EntityDefinition;
};
export type CustomQueryDefinitions = {
[QueryName: string]: CustomQueryDefinition;
};
export type CustomCommandDefinitions = {
[CommandName: string]: CustomCommandDefinition;
};
export type UserDefinitions = {
[EntityName: string]: UserDefinition;
};
export type GeneralNormalizedFunctionalGroup = {
users: UserDefinitions;
nonUsers: EntityDefinitions;
customQueries: CustomQueryDefinitions;
customCommands: CustomCommandDefinitions;
};
export interface NormalizedFunctionalGroup<TM extends GeneralTypeMap>
extends GeneralNormalizedFunctionalGroup {
users: { [AN in UserEntityNameOf<TM>]: UserDefinition };
nonUsers: { [EN in NonUserEntityNameOf<TM>]: EntityDefinition };
customQueries: { [QN in CustomQueryNameOf<TM>]: CustomQueryDefinition };
customCommands: { [CN in CustomCommandNameOf<TM>]: CustomCommandDefinition };
}
export type FunctionalGroup<TM extends GeneralTypeMap> = Partial<
NormalizedFunctionalGroup<TM>
>;
export type GeneralFunctionalGroup = Partial<GeneralNormalizedFunctionalGroup>;
| Make FunctionalGroup contain TypeMap type parameter | feat(interfaces): Make FunctionalGroup contain TypeMap type parameter
| TypeScript | apache-2.0 | phenyl-js/phenyl,phenyl-js/phenyl,phenyl-js/phenyl,phenyl-js/phenyl | ---
+++
@@ -2,6 +2,13 @@
import { CustomQueryDefinition } from "./custom-query-definition";
import { EntityDefinition } from "./entity-definition";
import { UserDefinition } from "./user-definition";
+import {
+ GeneralTypeMap,
+ UserEntityNameOf,
+ NonUserEntityNameOf,
+ CustomQueryNameOf,
+ CustomCommandNameOf
+} from "./type-map";
export type EntityDefinitions = {
[EntityName: string]: EntityDefinition;
@@ -19,11 +26,23 @@
[EntityName: string]: UserDefinition;
};
-export type NormalizedFunctionalGroup = {
+export type GeneralNormalizedFunctionalGroup = {
users: UserDefinitions;
nonUsers: EntityDefinitions;
customQueries: CustomQueryDefinitions;
customCommands: CustomCommandDefinitions;
};
-export type FunctionalGroup = Partial<NormalizedFunctionalGroup>;
+export interface NormalizedFunctionalGroup<TM extends GeneralTypeMap>
+ extends GeneralNormalizedFunctionalGroup {
+ users: { [AN in UserEntityNameOf<TM>]: UserDefinition };
+ nonUsers: { [EN in NonUserEntityNameOf<TM>]: EntityDefinition };
+ customQueries: { [QN in CustomQueryNameOf<TM>]: CustomQueryDefinition };
+ customCommands: { [CN in CustomCommandNameOf<TM>]: CustomCommandDefinition };
+}
+
+export type FunctionalGroup<TM extends GeneralTypeMap> = Partial<
+ NormalizedFunctionalGroup<TM>
+>;
+
+export type GeneralFunctionalGroup = Partial<GeneralNormalizedFunctionalGroup>; |
6a993204daae7dd224d991f30c852e9c49764bf1 | src/method-decorators/cacheable.ts | src/method-decorators/cacheable.ts | export interface CacheableAnnotation {
}
export function Cacheable(options?: CacheableAnnotation) {
return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
// save a reference to the original method this way we keep the values currently in the
// descriptor and don't overwrite what another decorator might have done to the descriptor.
if(descriptor === undefined) {
descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
}
// Editing the descriptor/value parameter
/*var originalMethod = descriptor.value;
descriptor.value = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
var a = args.map(function (a) { return JSON.stringify(a); }).join();
// note usage of originalMethod here
var result = originalMethod.apply(this, args);
var r = JSON.stringify(result);
console.log(`${prefix}${printTimeStamp(new Date())}Call: ${propertyKey}(${a}) => ${r}`);
return result;
};*/
console.log('dv: ', descriptor);
// return edited descriptor as opposed to overwriting the descriptor
return descriptor;
}
} | export interface CacheableAnnotation {
stats?: boolean;
platform?: 'browser' | 'nodejs';
storage?: 'memory' | 'localStorage' | 'sessionStorage';
}
export function Cacheable(options?: CacheableAnnotation) {
var memory = {};
return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
// save a reference to the original method this way we keep the values currently in the
// descriptor and don't overwrite what another decorator might have done to the descriptor.
if(descriptor === undefined) {
descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
}
let originalMethod = descriptor.value;
descriptor.value = function() {
let args = [];
for (let _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
if(memory[args.toString()]) {
console.log('Cache entry found!');
return memory[args.toString()];
} else {
console.log('Cache entry not found!');
let result = originalMethod.apply(this, args);
memory[args.toString()] = result;
return result;
}
};
// return edited descriptor as opposed to overwriting the descriptor
return descriptor;
}
} | Add minimal storage engine: in memory | Add minimal storage engine: in memory
| TypeScript | mit | semagarcia/typescript-decorators,semagarcia/typescript-decorators | ---
+++
@@ -1,8 +1,11 @@
export interface CacheableAnnotation {
-
+ stats?: boolean;
+ platform?: 'browser' | 'nodejs';
+ storage?: 'memory' | 'localStorage' | 'sessionStorage';
}
export function Cacheable(options?: CacheableAnnotation) {
+ var memory = {};
return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
// save a reference to the original method this way we keep the values currently in the
// descriptor and don't overwrite what another decorator might have done to the descriptor.
@@ -10,23 +13,23 @@
descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
}
- // Editing the descriptor/value parameter
- /*var originalMethod = descriptor.value;
- descriptor.value = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
+ let originalMethod = descriptor.value;
+ descriptor.value = function() {
+ let args = [];
+ for (let _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
- var a = args.map(function (a) { return JSON.stringify(a); }).join();
-
- // note usage of originalMethod here
- var result = originalMethod.apply(this, args);
- var r = JSON.stringify(result);
- console.log(`${prefix}${printTimeStamp(new Date())}Call: ${propertyKey}(${a}) => ${r}`);
- return result;
- };*/
- console.log('dv: ', descriptor);
+ if(memory[args.toString()]) {
+ console.log('Cache entry found!');
+ return memory[args.toString()];
+ } else {
+ console.log('Cache entry not found!');
+ let result = originalMethod.apply(this, args);
+ memory[args.toString()] = result;
+ return result;
+ }
+ };
// return edited descriptor as opposed to overwriting the descriptor
return descriptor; |
2844d057fb870fc3bf5e8f996af51031dfd4b20d | src/styles/globals/page-heading.ts | src/styles/globals/page-heading.ts | import {
em,
rem
} from 'polished';
export const headerFontWeight = 'bold';
export const headerLineHeight = em(18 / 14);
export const h1 = rem(28 / 14);
export const h2 = rem(24 / 14);
export const h3 = rem(18 / 14);
export const h4 = rem(15 / 14);
export const h5 = rem(14 / 14);
| import {
pixelsToEm,
pixelsToRem
} from './exact-pixel-values';
export const headerFontWeight = 'bold';
export const headerLineHeight = pixelsToEm(18);
export const h1 = pixelsToRem(28);
export const h2 = pixelsToRem(24);
export const h3 = pixelsToRem(18);
export const h4 = pixelsToRem(15);
export const h5 = pixelsToRem(14);
| Use exact pixel value functions to calculate page headings | Use exact pixel value functions to calculate page headings
| TypeScript | mit | maxdeviant/semantic-ui-css-in-js,maxdeviant/semantic-ui-css-in-js | ---
+++
@@ -1,13 +1,13 @@
import {
- em,
- rem
-} from 'polished';
+ pixelsToEm,
+ pixelsToRem
+} from './exact-pixel-values';
export const headerFontWeight = 'bold';
-export const headerLineHeight = em(18 / 14);
+export const headerLineHeight = pixelsToEm(18);
-export const h1 = rem(28 / 14);
-export const h2 = rem(24 / 14);
-export const h3 = rem(18 / 14);
-export const h4 = rem(15 / 14);
-export const h5 = rem(14 / 14);
+export const h1 = pixelsToRem(28);
+export const h2 = pixelsToRem(24);
+export const h3 = pixelsToRem(18);
+export const h4 = pixelsToRem(15);
+export const h5 = pixelsToRem(14); |
f55fdd6a507e273acfaff19a809da417b583d241 | src/model/optional-range.ts | src/model/optional-range.ts | import { isObject } from 'tsfun';
export interface OptionalRange {
value: string;
endValue?: string;
}
export module OptionalRange {
export const VALUE = 'value';
export const ENDVALUE = 'endValue';
export type Translations = 'from'|'to';
export function isOptionalRange(optionalRange: any): optionalRange is OptionalRange {
return isObject(optionalRange) && isValid(optionalRange);
}
export function isValid(optionalRange: OptionalRange): boolean {
const keys = Object.keys(optionalRange);
if (keys.length < 1 || keys.length > 2) return false;
if (keys.length === 1 && keys[0] !== VALUE) return false;
if (keys.length === 2 && (!keys.includes(VALUE) || !keys.includes(ENDVALUE))) return false;
return true;
}
export function generateLabel(optionalRange: OptionalRange,
getTranslation: (term: OptionalRange.Translations) => string,
getLabel: (object: any) => string): string {
return optionalRange.endValue
? getTranslation('from') + getLabel(optionalRange.value) + getTranslation('to')
+ getLabel(optionalRange.endValue)
: getLabel(optionalRange.value);
}
}
| import { isObject, isString } from 'tsfun';
export interface OptionalRange {
value: string;
endValue?: string;
}
export module OptionalRange {
export const VALUE = 'value';
export const ENDVALUE = 'endValue';
export type Translations = 'from'|'to';
export function isOptionalRange(optionalRange: any): optionalRange is OptionalRange {
if (!isObject(optionalRange)) return false;
if (optionalRange.value && !isString(optionalRange.value)) return false;
if (optionalRange.endValue && !isString(optionalRange.endValue)) return false;
return isValid(optionalRange);
}
export function isValid(optionalRange: OptionalRange): boolean {
const keys = Object.keys(optionalRange);
if (keys.length < 1 || keys.length > 2) return false;
if (keys.length === 1 && keys[0] !== VALUE) return false;
if (keys.length === 2 && (!keys.includes(VALUE) || !keys.includes(ENDVALUE))) return false;
return true;
}
export function generateLabel(optionalRange: OptionalRange,
getTranslation: (term: OptionalRange.Translations) => string,
getLabel: (object: any) => string): string {
return optionalRange.endValue
? getTranslation('from') + getLabel(optionalRange.value) + getTranslation('to')
+ getLabel(optionalRange.endValue)
: getLabel(optionalRange.value);
}
}
| Validate value types in typeguard | Validate value types in typeguard
| TypeScript | apache-2.0 | dainst/idai-components-2,dainst/idai-components-2,dainst/idai-components-2 | ---
+++
@@ -1,4 +1,4 @@
-import { isObject } from 'tsfun';
+import { isObject, isString } from 'tsfun';
export interface OptionalRange {
@@ -18,7 +18,10 @@
export function isOptionalRange(optionalRange: any): optionalRange is OptionalRange {
- return isObject(optionalRange) && isValid(optionalRange);
+ if (!isObject(optionalRange)) return false;
+ if (optionalRange.value && !isString(optionalRange.value)) return false;
+ if (optionalRange.endValue && !isString(optionalRange.endValue)) return false;
+ return isValid(optionalRange);
}
@@ -28,7 +31,6 @@
if (keys.length < 1 || keys.length > 2) return false;
if (keys.length === 1 && keys[0] !== VALUE) return false;
if (keys.length === 2 && (!keys.includes(VALUE) || !keys.includes(ENDVALUE))) return false;
-
return true;
}
|
9975a166869998b7d183e547b857f3dbee99c901 | types/sqlstring/sqlstring-tests.ts | types/sqlstring/sqlstring-tests.ts | import * as SqlString from "sqlstring";
// Code samples taken from:
// https://github.com/mysqljs/sqlstring/blob/master/README.md
const userId = "some user provided value";
const sql1 = "SELECT * FROM users WHERE id = " + SqlString.escape(userId);
const userId2 = 1;
const sql2 = SqlString.format("SELECT * FROM users WHERE id = ?", [userId2]);
const userId3 = 1;
const sql3 = SqlString.format(
"UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?",
["a", "b", "c", userId3],
);
const post = { id: 1, title: "Hello MySQL" };
const sql4 = SqlString.format("INSERT INTO posts SET ?", post);
const sorter = "date";
const sql5 =
"SELECT * FROM posts ORDER BY " + SqlString.escapeId("posts." + sorter);
const sorter2 = "date.2";
const sql6 =
"SELECT * FROM posts ORDER BY " + SqlString.escapeId(sorter2, true);
const userId4 = 1;
const inserts = ["users", "id", userId4];
const sql7 = SqlString.format("SELECT * FROM ?? WHERE ?? = ?", inserts);
const userId4 = 1;
const inserts = ["users", "id", userId4];
const sql7 = SqlString.format("SELECT * FROM ?? WHERE ?? = ?", inserts);
var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()');
const sql8 = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]);
| import * as SqlString from "sqlstring";
// Code samples taken from:
// https://github.com/mysqljs/sqlstring/blob/master/README.md
const userId = "some user provided value";
const sql1 = "SELECT * FROM users WHERE id = " + SqlString.escape(userId);
const userId2 = 1;
const sql2 = SqlString.format("SELECT * FROM users WHERE id = ?", [userId2]);
const userId3 = 1;
const sql3 = SqlString.format(
"UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?",
["a", "b", "c", userId3],
);
const post = { id: 1, title: "Hello MySQL" };
const sql4 = SqlString.format("INSERT INTO posts SET ?", post);
const sorter = "date";
const sql5 =
"SELECT * FROM posts ORDER BY " + SqlString.escapeId("posts." + sorter);
const sorter2 = "date.2";
const sql6 =
"SELECT * FROM posts ORDER BY " + SqlString.escapeId(sorter2, true);
const userId4 = 1;
const inserts = ["users", "id", userId4];
const sql7 = SqlString.format("SELECT * FROM ?? WHERE ?? = ?", inserts);
const CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()');
const sql8 = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]);
| Add sqlstring.raw to sqlstring type definitions. | Add sqlstring.raw to sqlstring type definitions.
| TypeScript | mit | georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,borisyankov/DefinitelyTyped | ---
+++
@@ -30,9 +30,5 @@
const inserts = ["users", "id", userId4];
const sql7 = SqlString.format("SELECT * FROM ?? WHERE ?? = ?", inserts);
-const userId4 = 1;
-const inserts = ["users", "id", userId4];
-const sql7 = SqlString.format("SELECT * FROM ?? WHERE ?? = ?", inserts);
-
-var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()');
+const CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()');
const sql8 = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); |
9b4389ba612916c5e03c1586e7d6db847de4451a | src/main/components/GlobalStyle.tsx | src/main/components/GlobalStyle.tsx | import { createGlobalStyle } from 'styled-components'
import { textColor, backgroundColor } from '../styles/colors'
const GlobalStyle = createGlobalStyle`
body {
color: ${textColor};
background-color: ${backgroundColor};
}
a {
color: inherit;
}
`
export default GlobalStyle
| import { createGlobalStyle } from 'styled-components'
import { textColor, backgroundColor } from '../styles/colors'
const GlobalStyle = createGlobalStyle`
body {
color: ${textColor};
background-color: ${backgroundColor};
margin: 0;
}
a {
color: inherit;
}
`
export default GlobalStyle
| Discard margin of body element | Discard margin of body element
| TypeScript | mit | Sarah-Seo/Inpad,Sarah-Seo/Inpad | ---
+++
@@ -5,6 +5,7 @@
body {
color: ${textColor};
background-color: ${backgroundColor};
+ margin: 0;
}
a {
color: inherit; |
09d8ada3a04e06ad8e879e6f4b3c5a94f61f9ae7 | Error/Message.ts | Error/Message.ts | // The MIT License (MIT)
//
// Copyright (c) 2016 Simon Mika
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/// <reference path="Type" />
/// <reference path="Level" />
module U10sil.Error {
export class Message {
constructor(private description: string, private level: Level, private type: Type, private region: Region) {
}
toString(): string {
return this.level + ": " + this.type + " Error. " + this.description + " @ " + this.region.toString();
}
}
}
| // The MIT License (MIT)
//
// Copyright (c) 2016 Simon Mika
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/// <reference path="Type" />
/// <reference path="Level" />
module U10sil.Error {
export class Message {
constructor(private description: string, private level: Level, private type: Type, private region: Region) {
}
toString(): string {
return Level[this.level] + ": " + Type[this.type] + " error. " + this.description + " @ " + this.region.toString();
}
}
}
| Print textual value instead of numerical | Print textual value instead of numerical
| TypeScript | mit | cogneco/u10sil,cogneco/mend | ---
+++
@@ -28,7 +28,7 @@
constructor(private description: string, private level: Level, private type: Type, private region: Region) {
}
toString(): string {
- return this.level + ": " + this.type + " Error. " + this.description + " @ " + this.region.toString();
+ return Level[this.level] + ": " + Type[this.type] + " error. " + this.description + " @ " + this.region.toString();
}
}
} |
50a988e8e9efd0c9159855752354699a544729b0 | src/test.ts | src/test.ts | // import { expect } from 'chai';
import * as fs from './index';
describe('fs', function() {
describe('unlink', function() {
it('should do maybe unlink stuff', function(done) {
fs.writeFileAsync('/tmp/foo', 'something').then(function() {
return fs.unlinkAsync('/tmp/foo');
}).then(function() {
done();
}).catch(done);
});
});
});
| let fs = require(./index');
describe('fs', function() {
describe('unlink', function() {
it('should do maybe unlink stuff', function(done) {
fs.writeFileAsync('/tmp/foo', 'something').then(function() {
return fs.unlinkAsync('/tmp/foo');
}).then(function() {
done();
}).catch(done);
});
});
});
| Fix "use of const" error in strict mode for Node 0.12. | Fix "use of const" error in strict mode for Node 0.12.
| TypeScript | mit | bls/node-sane-fs | ---
+++
@@ -1,5 +1,4 @@
-// import { expect } from 'chai';
-import * as fs from './index';
+let fs = require(./index');
describe('fs', function() {
describe('unlink', function() { |
e98546fdb908d025ae33ccd1c959f064ff524877 | front/client/router/index.ts | front/client/router/index.ts | import Router from 'vue-router'
function createRouter (store) {
return new Router({
mode: 'history',
fallback: false,
// TODO update vue-router when scroll issue will be fixed
// https://github.com/vuejs/vue-router/issues/2095
// Router doesnt support navigation to same anchor yet
// https://github.com/vuejs/vue-router/issues/1668
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else if (to.hash) {
return { selector: to.hash }
} else {
return { x: 0, y: 0 }
}
},
routes: [
{
path: '/',
name: 'Index',
component: () => import('../page/Index.vue')
},
{
path: '/haskell/:category',
name: 'Category',
component: () => import('../page/CategoryPage.vue'),
props: (route) => ({ categoryId: route.params.category.split('#').shift().split('-').pop() })
},
{
path: '/haskell/search/results/',
name: 'SearchResults',
component: () => import('../page/SearchResults.vue'),
props: (route) => ({ query: route.query.query })
},
{
path: '*',
name: 'Page404',
component: () => import('../page/Page404.vue')
}
]
})
}
export {
createRouter
}
| import Router from 'vue-router'
function createRouter (store) {
return new Router({
mode: 'history',
fallback: false,
// TODO update vue-router when scroll issue will be fixed
// https://github.com/vuejs/vue-router/issues/2095
// Router doesnt support navigation to same anchor yet
// https://github.com/vuejs/vue-router/issues/1668
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else if (to.hash) {
return { selector: to.hash }
} else {
return { x: 0, y: 0 }
}
},
routes: [
{
path: '/',
redirect: '/haskell'
},
{
path: '/haskell',
name: 'Index',
component: () => import('../page/Index.vue')
},
{
path: '/haskell/:category',
name: 'Category',
component: () => import('../page/CategoryPage.vue'),
props: (route) => ({ categoryId: route.params.category.split('#').shift().split('-').pop() })
},
{
path: '/haskell/search/results/',
name: 'SearchResults',
component: () => import('../page/SearchResults.vue'),
props: (route) => ({ query: route.query.query })
},
{
path: '*',
name: 'Page404',
component: () => import('../page/Page404.vue')
}
]
})
}
export {
createRouter
}
| Index page path and redirect '/' to '/haskell' | Index page path and redirect '/' to '/haskell'
| TypeScript | bsd-3-clause | aelve/guide,aelve/guide,aelve/guide,aelve/guide | ---
+++
@@ -20,6 +20,10 @@
routes: [
{
path: '/',
+ redirect: '/haskell'
+ },
+ {
+ path: '/haskell',
name: 'Index',
component: () => import('../page/Index.vue')
}, |
bd3344c7bf5f4d517d3ee3160463b170f191b19f | src/cp-cli.ts | src/cp-cli.ts | #!/usr/bin/env node
import fse from 'fs-extra';
import yargs from 'yargs';
const argv = yargs
.usage('Usage: $0 [-L] source target')
.demand(2, 2)
.boolean('d')
.alias('d', 'dereference')
.describe('d', 'Dereference symlinks')
.help('h')
.alias('h', 'help').argv;
const source = argv._[0];
const target = argv._[1];
const options: fse.CopyOptions = {
dereference: argv.dereference,
overwrite: true,
};
fse.copy(source, target, options).catch((error: Error) => {
if (error) {
// tslint:disable-next-line
console.error(error);
}
});
| #!/usr/bin/env node
import fse from 'fs-extra';
import yargs from 'yargs';
const argv = yargs
.usage('Usage: $0 [-L] source target')
.demand(2, 2)
.boolean('d')
.alias('d', 'dereference')
.describe('d', 'Dereference symlinks')
.help('h')
.alias('h', 'help').argv;
const source = argv._[0];
const target = argv._[1];
const options: fse.CopyOptions = {
dereference: argv.dereference,
overwrite: true,
};
fse.copy(source, target, options).catch((error: Error) => {
if (error) {
// tslint:disable-next-line
console.error(error);
process.exit(1);
}
});
| Exit with code 1 on error | Exit with code 1 on error
If this is not present, it breaks cli chaining (like `cp-cli foo bar/ && cat bar/foo`) | TypeScript | mit | screendriver/cp-cli | ---
+++
@@ -23,5 +23,6 @@
if (error) {
// tslint:disable-next-line
console.error(error);
+ process.exit(1);
}
}); |
0ef2c395326d1749bda2a2804c522d6421ec8aaa | src/server.ts | src/server.ts | import { config } from 'dotenv';
config();
import Application from './application';
new Application().start();
| import { config } from 'dotenv';
config();
import 'reflect-metadata';
import Application from './application';
new Application().start();
| Add reflect-metadata on the project | Add reflect-metadata on the project
| TypeScript | mit | rafaell-lycan/sabesp-mananciais-api,rafaell-lycan/sabesp-mananciais-api | ---
+++
@@ -1,5 +1,7 @@
import { config } from 'dotenv';
config();
+
+import 'reflect-metadata';
import Application from './application';
|
db9b93ad02de8304cddb461557af01c070ae544c | addons/a11y/src/components/Report/index.tsx | addons/a11y/src/components/Report/index.tsx | import React, { Fragment, FunctionComponent } from 'react';
import { Placeholder } from '@storybook/components';
import { styled } from '@storybook/theming';
import { Result, NodeResult } from 'axe-core';
import { Item } from './Item';
import { RuleType } from '../A11YPanel';
import HighlightToggle from './HighlightToggle';
const GlobalToggleWrapper = styled.div({
fontWeight: 'bold',
paddingTop: '5px',
textAlign: 'right',
paddingRight: '5px',
});
export interface ReportProps {
items: Result[];
empty: string;
passes: boolean;
type: RuleType;
}
function retrieveAllNodeResults(items: Result[]): NodeResult[] {
let nodeArray: NodeResult[] = [];
for (const item of items) {
nodeArray = nodeArray.concat(item.nodes);
}
return nodeArray;
}
export const Report: FunctionComponent<ReportProps> = ({ items, empty, type, passes }) => (
<Fragment>
<GlobalToggleWrapper>
Highlight Results: <HighlightToggle type={type} elementsToHighlight={retrieveAllNodeResults(items)} />
</GlobalToggleWrapper>
{items.length ? (
items.map(item => <Item passes={passes} item={item} key={item.id} type={type} />)
) : (
<Placeholder key="placeholder">{empty}</Placeholder>
)}
</Fragment>
); | import React, { Fragment, FunctionComponent } from 'react';
import { Placeholder } from '@storybook/components';
import { styled } from '@storybook/theming';
import { Result, NodeResult } from 'axe-core';
import { Item } from './Item';
import { RuleType } from '../A11YPanel';
import HighlightToggle from './HighlightToggle';
const GlobalToggleWrapper = styled.div({
fontWeight: 'bold',
paddingTop: '5px',
textAlign: 'right',
paddingRight: '5px',
});
export interface ReportProps {
items: Result[];
empty: string;
passes: boolean;
type: RuleType;
}
function retrieveAllNodeResults(items: Result[]): NodeResult[] {
let nodeArray: NodeResult[] = [];
for (const item of items) {
nodeArray = nodeArray.concat(item.nodes);
}
return nodeArray;
}
export const Report: FunctionComponent<ReportProps> = ({ items, empty, type, passes }) => (
<Fragment>
<GlobalToggleWrapper>
Highlight Results: <HighlightToggle type={type} elementsToHighlight={retrieveAllNodeResults(items)} />
</GlobalToggleWrapper>
{items.length ? (
items.map(item => <Item passes={passes} item={item} key={`${type}:${item.id}`} type={type} />)
) : (
<Placeholder key="placeholder">{empty}</Placeholder>
)}
</Fragment>
); | Set key to type:item-id to fix the unique id issue with the already passed in type value | Set key to type:item-id to fix the unique id issue with the already passed in type value
| TypeScript | mit | storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook | ---
+++
@@ -34,7 +34,7 @@
Highlight Results: <HighlightToggle type={type} elementsToHighlight={retrieveAllNodeResults(items)} />
</GlobalToggleWrapper>
{items.length ? (
- items.map(item => <Item passes={passes} item={item} key={item.id} type={type} />)
+ items.map(item => <Item passes={passes} item={item} key={`${type}:${item.id}`} type={type} />)
) : (
<Placeholder key="placeholder">{empty}</Placeholder>
)} |
839be6477d4b5870a03c82791af5a156882eadcb | src/server/api/index.ts | src/server/api/index.ts | /**
* API Server
*/
import * as Koa from 'koa';
import * as Router from 'koa-router';
import * as multer from 'koa-multer';
import * as bodyParser from 'koa-bodyparser';
const cors = require('@koa/cors');
import endpoints from './endpoints';
const handler = require('./api-handler').default;
// Init app
const app = new Koa();
app.use(cors({
origin: '*'
}));
app.use(bodyParser({
// リクエストが multipart/form-data でない限りはJSONだと見なす
detectJSON: ctx => !ctx.is('multipart/form-data')
}));
// Init multer instance
const upload = multer({
storage: multer.diskStorage({})
});
// Init router
const router = new Router();
/**
* Register endpoint handlers
*/
endpoints.forEach(endpoint => endpoint.meta.requireFile
? router.post(`/${endpoint.name}`, upload.single('file'), handler.bind(null, endpoint))
: router.post(`/${endpoint.name}`, handler.bind(null, endpoint))
);
router.post('/signup', require('./private/signup').default);
router.post('/signin', require('./private/signin').default);
router.use(require('./service/github').routes());
router.use(require('./service/twitter').routes());
// Register router
app.use(router.routes());
module.exports = app;
| /**
* API Server
*/
import * as Koa from 'koa';
import * as Router from 'koa-router';
import * as multer from 'koa-multer';
import * as bodyParser from 'koa-bodyparser';
const cors = require('@koa/cors');
import endpoints from './endpoints';
const handler = require('./api-handler').default;
// Init app
const app = new Koa();
app.use(cors({
origin: '*'
}));
app.use(bodyParser({
// リクエストが multipart/form-data でない限りはJSONだと見なす
detectJSON: ctx => !ctx.is('multipart/form-data')
}));
// Init multer instance
const upload = multer({
storage: multer.diskStorage({})
});
// Init router
const router = new Router();
/**
* Register endpoint handlers
*/
endpoints.forEach(endpoint => endpoint.meta.requireFile
? router.post(`/${endpoint.name}`, upload.single('file'), handler.bind(null, endpoint))
: router.post(`/${endpoint.name}`, handler.bind(null, endpoint))
);
router.post('/signup', require('./private/signup').default);
router.post('/signin', require('./private/signin').default);
router.use(require('./service/github').routes());
router.use(require('./service/twitter').routes());
// Return 404 for unknown API
router.all('*', async ctx => {
ctx.status = 404;
});
// Register router
app.use(router.routes());
module.exports = app;
| Return 404 for unknown API | Return 404 for unknown API
| TypeScript | mit | syuilo/Misskey,syuilo/Misskey | ---
+++
@@ -46,6 +46,11 @@
router.use(require('./service/github').routes());
router.use(require('./service/twitter').routes());
+// Return 404 for unknown API
+router.all('*', async ctx => {
+ ctx.status = 404;
+});
+
// Register router
app.use(router.routes());
|
75adbf43f26b3e600af42022e0fd9df806f34dbe | packages/ajv/src/services/Ajv.ts | packages/ajv/src/services/Ajv.ts | import {Configuration, InjectorService, ProviderScope, registerProvider} from "@tsed/di";
import Ajv from "ajv";
import AjvFormats from "ajv-formats";
import {IAjvSettings} from "../interfaces/IAjvSettings";
registerProvider({
provide: Ajv,
deps: [Configuration, InjectorService],
scope: ProviderScope.SINGLETON,
useFactory(configuration: Configuration, injector: InjectorService) {
const {errorFormatter, keywords = {}, ...props} = configuration.get<IAjvSettings>("ajv") || {};
const ajv = new Ajv({
verbose: false,
coerceTypes: true,
async: true,
...props
} as any);
AjvFormats(ajv);
return ajv;
}
});
| import {Configuration, InjectorService, ProviderScope, registerProvider} from "@tsed/di";
import Ajv from "ajv";
import AjvFormats from "ajv-formats";
import {IAjvSettings} from "../interfaces/IAjvSettings";
registerProvider({
provide: Ajv,
deps: [Configuration, InjectorService],
scope: ProviderScope.SINGLETON,
useFactory(configuration: Configuration, injector: InjectorService) {
const {errorFormatter, keywords = {}, ...props} = configuration.get<IAjvSettings>("ajv") || {};
const ajv = new Ajv({
verbose: false,
coerceTypes: true,
async: true,
strict: false,
...props
} as any);
AjvFormats(ajv);
return ajv;
}
});
| Add `strict: false` to ajv options by default | fix(ajv): Add `strict: false` to ajv options by default
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -14,6 +14,7 @@
verbose: false,
coerceTypes: true,
async: true,
+ strict: false,
...props
} as any);
|
6babbc718ab0c30a1eae43d4e4b4360c01c07b50 | service/templates/service.ts | service/templates/service.ts | /// <reference path="../../app.d.ts" />
'use strict';
module <%= capName %>App.Services.<%= camelName %> {
class <%= camelName %>Service {
static $inject = [];
constructor() {
}
}
angular.module('<%= appname %>').service('<%= camelName %>', <%= camelName %>Service);
}
| /// <reference path="../../app.d.ts" />
'use strict';
module <%= capName %>App.Services.<%= camelName %> {
class <%= camelName %>Service {
static $inject = [];
constructor() {
}
}
angular.module('<%= appname %>').service('<%= camelName %>', <%= camelName %>Service);
}
| Remove trailing whitespace in Service Template | Remove trailing whitespace in Service Template
| TypeScript | bsd-3-clause | NovaeWorkshop/Nova,NovaeWorkshop/Nova,NovaeWorkshop/Nova | ---
+++
@@ -6,7 +6,7 @@
class <%= camelName %>Service {
static $inject = [];
-
+
constructor() {
} |
5d4bdb994756f080822d5b19c9a4b60433aa5b94 | CeraonUI/src/Components/MealCard.tsx | CeraonUI/src/Components/MealCard.tsx | import * as React from 'react';
import { Card, Label, Rating } from 'semantic-ui-react';
import Meal from '../State/Meal/Meal';
interface MealCardProps extends React.Props<MealCard> {
meal: Meal;
}
export default class MealCard extends React.Component<MealCardProps, any> {
constructor() {
super();
}
render() {
return (
<Card.Group>
<Card fluid>
<Card.Content>
<Card.Header>{this.props.meal.name} <Label tag>${this.props.meal.price}</Label></Card.Header>
<Card.Meta>{this.props.meal.location.name}</Card.Meta>
<Card.Description>{this.props.meal.description}</Card.Description>
</Card.Content>
<Card.Content extra>
<Rating icon='star' rating={this.props.meal.location.rating} disabled/>
</Card.Content>
</Card>
</Card.Group>
)
}
}
| import * as React from 'react';
import { Card, Label, Rating } from 'semantic-ui-react';
import Meal from '../State/Meal/Meal';
interface MealCardProps extends React.Props<MealCard> {
meal: Meal;
}
export default class MealCard extends React.Component<MealCardProps, any> {
constructor() {
super();
}
render() {
return (
<Card.Group>
<Card fluid>
<Card.Content>
<Card.Header>{this.props.meal.name} <Label tag>${this.props.meal.price}</Label></Card.Header>
<Card.Meta>{this.props.meal.location.name}</Card.Meta>
<Card.Description>{this.props.meal.description}</Card.Description>
</Card.Content>
<Card.Content extra>
<Rating icon='star' rating={this.props.meal.location.rating} maxRating={5} disabled/>
</Card.Content>
</Card>
</Card.Group>
)
}
}
| Fix bug with ratings in meal card | Fix bug with ratings in meal card
| TypeScript | bsd-3-clause | Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound | ---
+++
@@ -21,7 +21,7 @@
<Card.Description>{this.props.meal.description}</Card.Description>
</Card.Content>
<Card.Content extra>
- <Rating icon='star' rating={this.props.meal.location.rating} disabled/>
+ <Rating icon='star' rating={this.props.meal.location.rating} maxRating={5} disabled/>
</Card.Content>
</Card>
</Card.Group> |
a8ecc7a95006796aca3a913a7c5882bf1ba89d93 | transpiler/src/index.ts | transpiler/src/index.ts | import { getAST } from './ast';
import { emit } from './emitter';
declare function require(name: string);
declare var process: any;
(function () {
if (typeof process !== 'undefined' && process.nextTick && !process.browser && typeof require !== "undefined") {
var fs = require('fs');
if (process.argv.length < 2)
process.exit();
var fileNames = process.argv.slice(2);
const sourceFile = getAST(fileNames);
const result = emit(sourceFile, {});
console.log(result.emitted_string);
process.exit();
}
})();
| import { getAST } from './ast';
import { emit } from './emitter';
declare function require(name: string);
declare var process: any;
(function () {
if (typeof process !== 'undefined' && process.nextTick && !process.browser && typeof require !== "undefined") {
var fs = require('fs');
if (process.argv.length < 2)
process.exit();
var fileNames = process.argv.slice(2);
const sourceFile = getAST(fileNames);
const result = emit(sourceFile, { run: '', run_wrapper: '' });
console.log(result.emitted_string);
process.exit();
}
})();
| Add run ad run_wrapper dummy to initial context | Add run ad run_wrapper dummy to initial context
| TypeScript | mit | artfuldev/RIoT | ---
+++
@@ -11,7 +11,7 @@
process.exit();
var fileNames = process.argv.slice(2);
const sourceFile = getAST(fileNames);
- const result = emit(sourceFile, {});
+ const result = emit(sourceFile, { run: '', run_wrapper: '' });
console.log(result.emitted_string);
process.exit();
} |
76de62a27308faddbc0a01cfc51802a1957fb3f4 | src/app/series/directives/series-basic.component.ts | src/app/series/directives/series-basic.component.ts | import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { SeriesModel, TabService } from '../../shared';
@Component({
styleUrls: [],
template: `
<form *ngIf="series">
<publish-fancy-field textinput required [model]="series" name="title" label="Series Title">
<div class="fancy-hint">What's the name of your series?</div>
</publish-fancy-field>
<publish-fancy-field textinput required [model]="series" name="shortDescription" label="Teaser">
<div class="fancy-hint">A short description of your series.</div>
</publish-fancy-field>
<publish-fancy-field textarea [model]="series" name="description" label="Description">
<div class="fancy-hint">A full description of your series.</div>
</publish-fancy-field>
</form>
`
})
export class SeriesBasicComponent implements OnDestroy {
series: SeriesModel;
tabSub: Subscription;
constructor(tab: TabService) {
this.tabSub = tab.model.subscribe((s: SeriesModel) => this.series = s);
}
ngOnDestroy(): any {
this.tabSub.unsubscribe();
}
}
| import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { SeriesModel, TabService } from '../../shared';
@Component({
styleUrls: [],
template: `
<form *ngIf="series">
<publish-fancy-field textinput required [model]="series" name="title" label="Series Title" required>
<div class="fancy-hint">What's the name of your series?</div>
</publish-fancy-field>
<publish-fancy-field textinput required [model]="series" name="shortDescription" label="Teaser" required>
<div class="fancy-hint">A short description of your series.</div>
</publish-fancy-field>
<publish-fancy-field textarea [model]="series" name="description" label="Description">
<div class="fancy-hint">A full description of your series.</div>
</publish-fancy-field>
</form>
`
})
export class SeriesBasicComponent implements OnDestroy {
series: SeriesModel;
tabSub: Subscription;
constructor(tab: TabService) {
this.tabSub = tab.model.subscribe((s: SeriesModel) => this.series = s);
}
ngOnDestroy(): any {
this.tabSub.unsubscribe();
}
}
| Add required symbol to series title + teaser. | Add required symbol to series title + teaser.
| TypeScript | agpl-3.0 | PRX/publish.prx.org,PRX/publish.prx.org,PRX/publish.prx.org,PRX/publish.prx.org | ---
+++
@@ -6,11 +6,11 @@
styleUrls: [],
template: `
<form *ngIf="series">
- <publish-fancy-field textinput required [model]="series" name="title" label="Series Title">
+ <publish-fancy-field textinput required [model]="series" name="title" label="Series Title" required>
<div class="fancy-hint">What's the name of your series?</div>
</publish-fancy-field>
- <publish-fancy-field textinput required [model]="series" name="shortDescription" label="Teaser">
+ <publish-fancy-field textinput required [model]="series" name="shortDescription" label="Teaser" required>
<div class="fancy-hint">A short description of your series.</div>
</publish-fancy-field>
|
7229952555d95a4741119b21f82542d39b300ed1 | packages/schematics/src/scam/index.ts | packages/schematics/src/scam/index.ts | import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
import { findModuleFromOptions } from '@schematics/angular/utility/find-module';
import { buildDefaultPath, getProject } from '@schematics/angular/utility/project';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => {
const project = getProject(tree, options.project);
const modulePath = findModuleFromOptions(tree, {
...options,
path: options.path || buildDefaultPath(project)
});
tree.read(modulePath);
// @todo: read module content.
// @todo: merge module content in component.
// @todo: remove module file.
return tree;
};
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList,
_mergeModuleIntoComponentFile(options)
];
}
return chain(ruleList);
}
| import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
import { findModuleFromOptions } from '@schematics/angular/utility/find-module';
import { buildDefaultPath, getProject } from '@schematics/angular/utility/project';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => {
const project = getProject(tree, options.project);
const modulePath = findModuleFromOptions(tree, {
...options,
path: options.path || buildDefaultPath(project)
});
/* @hack: Well, that's a dirty way for guessing the component's path from the module. */
const componentPath = modulePath.replace(/module.ts$/, 'component.ts');
const moduleContent = tree.read(modulePath);
const componentContent = tree.read(componentPath);
// @todo: read module content.
// @todo: merge module content in component.
// @todo: remove module file.
return tree;
};
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList,
_mergeModuleIntoComponentFile(options)
];
}
return chain(ruleList);
}
| Merge module and component as default behavior. | @wishtack/schematics:scam: Merge module and component as default behavior.
| TypeScript | mit | wishtack/wishtack-steroids,wishtack/ng-steroids,wishtack/wishtack-steroids,wishtack/ng-steroids,wishtack/wishtack-steroids | ---
+++
@@ -16,7 +16,11 @@
path: options.path || buildDefaultPath(project)
});
- tree.read(modulePath);
+ /* @hack: Well, that's a dirty way for guessing the component's path from the module. */
+ const componentPath = modulePath.replace(/module.ts$/, 'component.ts');
+
+ const moduleContent = tree.read(modulePath);
+ const componentContent = tree.read(componentPath);
// @todo: read module content.
// @todo: merge module content in component. |
9e73ef967fa3b9ddc1347f242d623799c75a010e | src/converters/pluralise.ts | src/converters/pluralise.ts | import { valueConverter } from 'aurelia-framework';
@valueConverter('pluralise')
export class PluraliseValueConverter {
toView(value: number, text: string): string {
if (value > 1) {
return `${text}s`;
} else {
return text;
}
}
}
| import { valueConverter } from 'aurelia-framework';
@valueConverter('pluralise')
export class PluraliseValueConverter {
toView(value: number, text: string): string {
return value > 1 ? `${text}s` : text;
}
}
| Use ternary operator in PluraliseValueConverter | Use ternary operator in PluraliseValueConverter
| TypeScript | isc | michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news,michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news,michaelbull/aurelia-hacker-news | ---
+++
@@ -3,10 +3,6 @@
@valueConverter('pluralise')
export class PluraliseValueConverter {
toView(value: number, text: string): string {
- if (value > 1) {
- return `${text}s`;
- } else {
- return text;
- }
+ return value > 1 ? `${text}s` : text;
}
} |
b972d9580004a676c87f4d7da261805af9542de0 | src/redux/actions/mediaPlayer.ts | src/redux/actions/mediaPlayer.ts | import { actionTypes } from "~/redux/constants"
export const mediaPlayerLoadNowPlayingItem = payload => {
return {
type: actionTypes.MEDIA_PLAYER_LOAD_NOW_PLAYING_ITEM,
payload
}
}
export const mediaPlayerUpdatePlaying = payload => {
return {
type: actionTypes.MEDIA_PLAYER_UPDATE_PLAYING,
payload
}
}
export const mediaPlayerSetClipFinished = payload => {
return {
type: actionTypes.MEDIA_PLAYER_SET_CLIP_FINISHED,
payload
}
}
export const mediaPlayerSetPlayedAfterClipFinished = payload => {
return {
type: actionTypes.MEDIA_PLAYER_SET_PLAYED_AFTER_CLIP_FINISHED,
payload
}
}
| import { cleanNowPlayingItem } from "podverse-shared"
import { actionTypes } from "~/redux/constants"
export const mediaPlayerLoadNowPlayingItem = payload => {
const cleanedNowPlayingItem = cleanNowPlayingItem(payload)
return {
type: actionTypes.MEDIA_PLAYER_LOAD_NOW_PLAYING_ITEM,
payload: cleanedNowPlayingItem
}
}
export const mediaPlayerUpdatePlaying = payload => {
return {
type: actionTypes.MEDIA_PLAYER_UPDATE_PLAYING,
payload
}
}
export const mediaPlayerSetClipFinished = payload => {
return {
type: actionTypes.MEDIA_PLAYER_SET_CLIP_FINISHED,
payload
}
}
export const mediaPlayerSetPlayedAfterClipFinished = payload => {
return {
type: actionTypes.MEDIA_PLAYER_SET_PLAYED_AFTER_CLIP_FINISHED,
payload
}
}
| Use cleanNowPlayingItem before adding a NowPlayingItem to global state | Use cleanNowPlayingItem before adding a NowPlayingItem to global state
| TypeScript | agpl-3.0 | podverse/podverse-web,podverse/podverse-web,podverse/podverse-web,podverse/podverse-web | ---
+++
@@ -1,9 +1,12 @@
+import { cleanNowPlayingItem } from "podverse-shared"
import { actionTypes } from "~/redux/constants"
export const mediaPlayerLoadNowPlayingItem = payload => {
+ const cleanedNowPlayingItem = cleanNowPlayingItem(payload)
+
return {
type: actionTypes.MEDIA_PLAYER_LOAD_NOW_PLAYING_ITEM,
- payload
+ payload: cleanedNowPlayingItem
}
}
|
b36dbb545d58a692e5b2806bf6332a30fd13ae73 | app/core/map.service.ts | app/core/map.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { OptionMap } from './map';
import { LayerType } from './layer';
@Injectable()
export class MapService {
private mapsUrl = "app/maps";
private divId: Node | string = 'map-div';
constructor(private http: Http) {
}
add(
title: string = "",
height: number,
width: number,
mapType: LayerType,
creatorId: number,
graphics: string = ""
) {
// TODO: compute hash, id, date and return an Observable<OptionMap>
}
map(id: number): Observable<OptionMap> {
return this.http.get(
this.mapsUrl + `/${id}`).map(
(r: Response) => r.json().data as OptionMap
);
}
maps(): Observable<OptionMap[]> {
return this.http.get(this.mapsUrl).map( (r: Response) => r.json().data as OptionMap[] );
}
delete(id: number) {}
} | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { OptionMap } from './map';
import { LayerType } from './layer';
@Injectable()
export class MapService {
private mapsUrl = "app/maps";
private divId: Node | string = 'map-div';
constructor(private http: Http) {
}
add(
title: string = "",
height: number,
width: number,
layerType: LayerType,
creatorId: number,
graphics: string = ""
) {
// TODO: compute hash, id, date and return an Observable<OptionMap>
}
map(id: number): Observable<OptionMap> {
return this.http.get(
this.mapsUrl + `/${id}`).map(
(r: Response) => r.json().data as OptionMap
);
}
maps(): Observable<OptionMap[]> {
return this.http.get(this.mapsUrl).map( (r: Response) => r.json().data as OptionMap[] );
}
delete(id: number) {}
} | Change typo name for map field | Change typo name for map field
| TypeScript | mit | ABAPlan/abaplan-core,ABAPlan/abaplan-core,ABAPlan/abaplan-core | ---
+++
@@ -18,7 +18,7 @@
title: string = "",
height: number,
width: number,
- mapType: LayerType,
+ layerType: LayerType,
creatorId: number,
graphics: string = ""
) { |
c51ac6a639c8e2579d0b104c1cc48bf652947965 | src_ts/components/support-btn.ts | src_ts/components/support-btn.ts | import {PolymerElement, html} from '@polymer/polymer/polymer-element';
import '@polymer/iron-icons/communication-icons';
/* eslint-disable max-len */
/**
* @polymer
* @customElement
*/
export class SupportBtn extends PolymerElement {
public static get template(): HTMLTemplateElement {
return html`
<style>
:host(:hover) {
cursor: pointer;
}
a {
color: inherit;
text-decoration: none;
font-size: 16px;
}
iron-icon {
margin-right: 4px;
}
</style>
<a href="https://unicef.service-now.com/cc/?id=sc_cat_item&sys_id=35b00b1bdb255f00085184735b9619e6&sysparm_category=c6ab1444db5b5700085184735b961920"
target="_blank">
<iron-icon icon="communication:textsms"></iron-icon>
Support
</a>
`;
}
}
| import {PolymerElement, html} from '@polymer/polymer/polymer-element';
import '@polymer/iron-icons/communication-icons';
/* eslint-disable max-len */
/**
* @polymer
* @customElement
*/
export class SupportBtn extends PolymerElement {
public static get template(): HTMLTemplateElement {
return html`
<style>
:host(:hover) {
cursor: pointer;
}
a {
color: inherit;
text-decoration: none;
font-size: 16px;
}
iron-icon {
margin-right: 4px;
}
</style>
<a href="https://unicef.service-now.com/cc?id=sc_cat_item&sys_id=c8e43760db622450f65a2aea4b9619ad&sysparm_category=99c51053db0a6f40f65a2aea4b9619af"
target="_blank">
<iron-icon icon="communication:textsms"></iron-icon>
Support
</a>
`;
}
}
| Update support link in header | [ch26816] Update support link in header
| TypeScript | apache-2.0 | unicef/etools-dashboard,unicef/etools-dashboard,unicef/etools-dashboard,unicef/etools-dashboard | ---
+++
@@ -23,7 +23,7 @@
margin-right: 4px;
}
</style>
- <a href="https://unicef.service-now.com/cc/?id=sc_cat_item&sys_id=35b00b1bdb255f00085184735b9619e6&sysparm_category=c6ab1444db5b5700085184735b961920"
+ <a href="https://unicef.service-now.com/cc?id=sc_cat_item&sys_id=c8e43760db622450f65a2aea4b9619ad&sysparm_category=99c51053db0a6f40f65a2aea4b9619af"
target="_blank">
<iron-icon icon="communication:textsms"></iron-icon>
Support |
4ce7681cc82d278108d003bcfcea3dfa2c2ef03d | packages/angular/cli/commands/e2e-impl.ts | packages/angular/cli/commands/e2e-impl.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ArchitectCommand } from '../models/architect-command';
import { Arguments } from '../models/interface';
import { Schema as E2eCommandSchema } from './e2e';
export class E2eCommand extends ArchitectCommand<E2eCommandSchema> {
public readonly target = 'e2e';
public readonly multiTarget = true;
public readonly missingTargetError = `
Cannot find "e2e" target for the specified project.
You should add a package that implements end-to-end testing capabilities.
For example:
Cypress: ng add @cypress/schematic
WebdriverIO: ng add @wdio/schematics
More options will be added to the list as they become available.
`;
async initialize(options: E2eCommandSchema & Arguments) {
if (!options.help) {
return super.initialize(options);
}
}
}
| /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ArchitectCommand } from '../models/architect-command';
import { Arguments } from '../models/interface';
import { Schema as E2eCommandSchema } from './e2e';
export class E2eCommand extends ArchitectCommand<E2eCommandSchema> {
public readonly target = 'e2e';
public readonly multiTarget = true;
public readonly missingTargetError = `
Cannot find "e2e" target for the specified project.
You should add a package that implements end-to-end testing capabilities.
For example:
Cypress: ng add @cypress/schematic
Nightwatch: ng add @nightwatch/schematics
WebdriverIO: ng add @wdio/schematics
More options will be added to the list as they become available.
`;
async initialize(options: E2eCommandSchema & Arguments) {
if (!options.help) {
return super.initialize(options);
}
}
}
| Add Nightwatch schematics to e2e command | docs(@angular/cli): Add Nightwatch schematics to e2e command
| TypeScript | mit | catull/angular-cli,Brocco/angular-cli,clydin/angular-cli,Brocco/angular-cli,geofffilippi/angular-cli,Brocco/angular-cli,Brocco/angular-cli,geofffilippi/angular-cli,clydin/angular-cli,angular/angular-cli,catull/angular-cli,catull/angular-cli,Brocco/angular-cli,geofffilippi/angular-cli,clydin/angular-cli,angular/angular-cli,angular/angular-cli,clydin/angular-cli,geofffilippi/angular-cli,catull/angular-cli,angular/angular-cli | ---
+++
@@ -20,6 +20,7 @@
For example:
Cypress: ng add @cypress/schematic
+ Nightwatch: ng add @nightwatch/schematics
WebdriverIO: ng add @wdio/schematics
More options will be added to the list as they become available. |
64f8b28f0070563855be345356b467a179f4ab13 | app/scripts/components/__tests__/appSpec.tsx | app/scripts/components/__tests__/appSpec.tsx | import * as React from 'react';
import * as ReactTestUtils from 'react-addons-test-utils'
import { MuiThemeProvider } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import MenuItem from 'material-ui/MenuItem';
import { App } from '../app';
describe('<App />', () => {
const root = ReactTestUtils.renderIntoDocument(<MuiThemeProvider><App /></MuiThemeProvider>);
const app = ReactTestUtils.findRenderedComponentWithType(root, App);
describe('when clicking the hamburger', () => {
it('should show the drawer', () => {
// Arrange
const appbar = ReactTestUtils.findRenderedComponentWithType(root, AppBar);
// Act
appbar.props.onLeftIconButtonTouchTap();
// Assert
expect(app.state.drawerOpen).toBe(true);
});
});
describe('when clicking the menu', () => {
it('should hide the drawer', () => {
// Arrange
const appbar = ReactTestUtils.findRenderedComponentWithType(root, AppBar);
appbar.props.onLeftIconButtonTouchTap();
const menuItems = ReactTestUtils.scryRenderedComponentsWithType(root, MenuItem);
// Act
menuItems[0].props.onTouchTap();
// Assert
expect(app.state.drawerOpen).toBe(false);
});
});
}); | import * as React from 'react';
import * as ReactTestUtils from 'react-addons-test-utils'
import { MuiThemeProvider } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import MenuItem from 'material-ui/MenuItem';
import { App, AppState } from '../app';
describe('<App />', () => {
const root = ReactTestUtils.renderIntoDocument(<MuiThemeProvider><App /></MuiThemeProvider>);
const app = ReactTestUtils.findRenderedComponentWithType(root as React.Component<any, any>, App as any);
describe('when clicking the hamburger', () => {
it('should show the drawer', () => {
// Arrange
const appbar: React.Component<any, any> = ReactTestUtils.findRenderedComponentWithType(root as React.Component<any, any>, AppBar);
// Act
appbar.props.onLeftIconButtonTouchTap();
// Assert
expect((app.state as AppState).drawerOpen).toBe(true);
});
});
describe('when clicking the menu', () => {
it('should hide the drawer', () => {
// Arrange
const appbar: React.Component<any, any> = ReactTestUtils.findRenderedComponentWithType(root as React.Component<any, any>, AppBar);
appbar.props.onLeftIconButtonTouchTap();
const menuItems: React.Component<any, any>[] = ReactTestUtils.scryRenderedComponentsWithType(root as React.Component<any, any>, MenuItem);
// Act
menuItems[0].props.onTouchTap();
// Assert
expect((app.state as AppState).drawerOpen).toBe(false);
});
});
}); | Fix typing in unit tests | Fix typing in unit tests
| TypeScript | mit | mthmulders/hyperion-web,mthmulders/hyperion-web,mthmulders/hyperion-web | ---
+++
@@ -5,37 +5,37 @@
import AppBar from 'material-ui/AppBar';
import MenuItem from 'material-ui/MenuItem';
-import { App } from '../app';
+import { App, AppState } from '../app';
describe('<App />', () => {
const root = ReactTestUtils.renderIntoDocument(<MuiThemeProvider><App /></MuiThemeProvider>);
- const app = ReactTestUtils.findRenderedComponentWithType(root, App);
+ const app = ReactTestUtils.findRenderedComponentWithType(root as React.Component<any, any>, App as any);
describe('when clicking the hamburger', () => {
it('should show the drawer', () => {
// Arrange
- const appbar = ReactTestUtils.findRenderedComponentWithType(root, AppBar);
+ const appbar: React.Component<any, any> = ReactTestUtils.findRenderedComponentWithType(root as React.Component<any, any>, AppBar);
// Act
appbar.props.onLeftIconButtonTouchTap();
// Assert
- expect(app.state.drawerOpen).toBe(true);
+ expect((app.state as AppState).drawerOpen).toBe(true);
});
});
describe('when clicking the menu', () => {
it('should hide the drawer', () => {
// Arrange
- const appbar = ReactTestUtils.findRenderedComponentWithType(root, AppBar);
+ const appbar: React.Component<any, any> = ReactTestUtils.findRenderedComponentWithType(root as React.Component<any, any>, AppBar);
appbar.props.onLeftIconButtonTouchTap();
- const menuItems = ReactTestUtils.scryRenderedComponentsWithType(root, MenuItem);
+ const menuItems: React.Component<any, any>[] = ReactTestUtils.scryRenderedComponentsWithType(root as React.Component<any, any>, MenuItem);
// Act
menuItems[0].props.onTouchTap();
// Assert
- expect(app.state.drawerOpen).toBe(false);
+ expect((app.state as AppState).drawerOpen).toBe(false);
});
});
}); |
90c42dc28ff91180914d5d5a0fa12f94f480523e | src/examples/worker/index.ts | src/examples/worker/index.ts | import { runWorker } from '../../utils/worker'
import { viewHandler } from '../../interfaces/view'
import { logFns } from '../../utils/log'
// all communicatios are transfered via postMessage
runWorker({
worker: new (<any> require('worker-loader!./worker')),
interfaces: {
view: viewHandler('#app'),
},
/* NOTE: this would be defined in the module (worker.ts)
if your run the module over a webworker
is implemented this way for showing how you can communicate over any workerAPI
you can run worket.ts in the server via websockets or even remotely in a client via webRTC!!
*/
// DEV ONLY (you can handle it manually)
...logFns,
})
| import { runWorker } from '../../utils/worker'
import { viewHandler } from '../../interfaces/view'
import { logFns } from '../../utils/log'
// all communicatios are transfered via postMessage
runWorker({
worker: new (<any> require('worker-loader!./worker')),
interfaces: {
view: viewHandler('#app'),
},
// DEV ONLY (you can handle it manually)
...logFns,
})
| Remove note on worker implementation | Remove note on worker implementation
| TypeScript | mit | FractalBlocks/Fractal,FractalBlocks/Fractal,FractalBlocks/Fractal | ---
+++
@@ -8,11 +8,6 @@
interfaces: {
view: viewHandler('#app'),
},
- /* NOTE: this would be defined in the module (worker.ts)
- if your run the module over a webworker
- is implemented this way for showing how you can communicate over any workerAPI
- you can run worket.ts in the server via websockets or even remotely in a client via webRTC!!
- */
// DEV ONLY (you can handle it manually)
...logFns,
}) |
e428a97fd09f92491214742ba90a9bb3924717d1 | modules/tinymce/src/core/demo/ts/demo/TinyMceDemo.ts | modules/tinymce/src/core/demo/ts/demo/TinyMceDemo.ts | import { document } from '@ephox/dom-globals';
declare let tinymce: any;
export default function () {
const textarea = document.createElement('textarea');
textarea.innerHTML = '<p>Bolt</p>';
textarea.classList.add('tinymce');
document.querySelector('#ephox-ui').appendChild(textarea);
tinymce.init({
// imagetools_cors_hosts: ["moxiecode.cachefly.net"],
// imagetools_proxy: "proxy.php",
// imagetools_api_key: '123',
// images_upload_url: 'postAcceptor.php',
// images_upload_base_path: 'base/path',
// images_upload_credentials: true,
skin_url: '../../../../js/tinymce/skins/ui/oxide',
setup(ed) {
ed.addButton('demoButton', {
type: 'button',
text: 'Demo',
onclick() {
ed.insertContent('Hello world!');
}
});
},
selector: 'textarea.tinymce',
toolbar1: 'demoButton bold italic',
menubar: false
});
} | import { document } from '@ephox/dom-globals';
declare let tinymce: any;
export default function () {
const textarea = document.createElement('textarea');
textarea.innerHTML = '<p>Bolt</p>';
textarea.classList.add('tinymce');
document.querySelector('#ephox-ui').appendChild(textarea);
tinymce.init({
// imagetools_cors_hosts: ["moxiecode.cachefly.net"],
// imagetools_proxy: "proxy.php",
// imagetools_api_key: '123',
// images_upload_url: 'postAcceptor.php',
// images_upload_base_path: 'base/path',
// images_upload_credentials: true,
skin_url: '../../../../js/tinymce/skins/ui/oxide',
setup(ed) {
ed.ui.registry.addButton('demoButton', {
type: 'button',
text: 'Demo',
onAction() {
ed.insertContent('Hello world!');
}
});
},
selector: 'textarea.tinymce',
toolbar1: 'demoButton bold italic',
menubar: false
});
}
| Update demo page for TinyMCE 5. | Update demo page for TinyMCE 5.
| TypeScript | lgpl-2.1 | TeamupCom/tinymce,FernCreek/tinymce,tinymce/tinymce,tinymce/tinymce,TeamupCom/tinymce,tinymce/tinymce,FernCreek/tinymce,FernCreek/tinymce | ---
+++
@@ -19,10 +19,10 @@
// images_upload_credentials: true,
skin_url: '../../../../js/tinymce/skins/ui/oxide',
setup(ed) {
- ed.addButton('demoButton', {
+ ed.ui.registry.addButton('demoButton', {
type: 'button',
text: 'Demo',
- onclick() {
+ onAction() {
ed.insertContent('Hello world!');
}
}); |
b6f05b06d7357e7dd5582e9b0cabbce7a79d201f | react-redux-webpack2-todomvc/client/todos/components/TodoTextInput.tsx | react-redux-webpack2-todomvc/client/todos/components/TodoTextInput.tsx | import * as React from 'react'
import * as classNames from 'classnames'
interface TodoTextInputProps {
editing?: boolean
newTodo?: boolean
placeholder?: string
text?: string
onSave: (text: string) => void
}
interface TodoTextInputState {
text: string
}
export class TodoTextInput extends React.Component<TodoTextInputProps, TodoTextInputState> {
constructor(props, context) {
super(props, context)
this.state = {
text: this.props.text || ''
}
}
handleSubmit(e) {
const text = e.target.value.trim()
if (e.which === 13) {
this.props.onSave(text)
if (this.props.newTodo) {
this.setState({ text: '' })
}
}
}
handleChange(e) {
this.setState({ text: e.target.value })
}
handleBlur(e) {
if (!this.props.newTodo) {
this.props.onSave(e.target.value)
}
}
render() {
return (
<input
type="text"
className={
classNames({
edit: this.props.editing,
'new-todo': this.props.newTodo
})
}
placeholder={this.props.placeholder}
autoFocus={true}
value={this.state.text}
onBlur={this.handleBlur.bind(this)}
onChange={this.handleChange.bind(this)}
onKeyDown={this.handleSubmit.bind(this)}
/>
)
}
} | import * as React from 'react'
import * as classNames from 'classnames'
interface TodoTextInputProps {
editing?: boolean
newTodo?: boolean
placeholder?: string
text?: string
onSave: (text: string) => void
}
interface TodoTextInputState {
text: string
}
export class TodoTextInput extends React.Component<TodoTextInputProps, TodoTextInputState> {
constructor(props, context) {
super(props, context)
this.state = {
text: this.props.text || ''
}
}
handleSubmit(e: Event) {
const text = (e.target as HTMLInputElement).value.trim()
if ((e as KeyboardEvent).which === 13) {
this.props.onSave(text)
if (this.props.newTodo) {
this.setState({ text: '' })
}
}
}
handleChange(e: Event) {
this.setState({ text: (e.target as HTMLInputElement).value })
}
handleBlur(e: Event) {
if (!this.props.newTodo) {
this.props.onSave((e.target as HTMLInputElement).value)
}
}
render() {
return (
<input
type="text"
className={
classNames({
edit: this.props.editing,
'new-todo': this.props.newTodo
})
}
placeholder={this.props.placeholder}
autoFocus={true}
value={this.state.text}
onBlur={this.handleBlur.bind(this)}
onChange={this.handleChange.bind(this)}
onKeyDown={this.handleSubmit.bind(this)}
/>
)
}
} | Add types for the events | Add types for the events
| TypeScript | unlicense | janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations | ---
+++
@@ -21,9 +21,9 @@
}
}
- handleSubmit(e) {
- const text = e.target.value.trim()
- if (e.which === 13) {
+ handleSubmit(e: Event) {
+ const text = (e.target as HTMLInputElement).value.trim()
+ if ((e as KeyboardEvent).which === 13) {
this.props.onSave(text)
if (this.props.newTodo) {
this.setState({ text: '' })
@@ -31,13 +31,13 @@
}
}
- handleChange(e) {
- this.setState({ text: e.target.value })
+ handleChange(e: Event) {
+ this.setState({ text: (e.target as HTMLInputElement).value })
}
- handleBlur(e) {
+ handleBlur(e: Event) {
if (!this.props.newTodo) {
- this.props.onSave(e.target.value)
+ this.props.onSave((e.target as HTMLInputElement).value)
}
}
|
aaeea9bc44c962d59b1eacc9cea53c9671a946c7 | frontend/src/app/modules/aggregation/components/aggregation-chart/aggregation-chart.component.spec.ts | frontend/src/app/modules/aggregation/components/aggregation-chart/aggregation-chart.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AggregationChartComponent } from './aggregation-chart.component';
import {BarchartDataService} from "../../services/barchart-data.service";
import {AggregationChartDataService} from "../../services/aggregation-chart-data.service";
import {SharedMocksModule} from "../../../../testing/shared-mocks.module";
import {ResultSelectionStore} from "../../../result-selection/services/result-selection.store";
import {ResultSelectionService} from "../../../result-selection/services/result-selection.service";
describe('AggregationChartComponent', () => {
let component: AggregationChartComponent;
let fixture: ComponentFixture<AggregationChartComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AggregationChartComponent ],
providers: [
BarchartDataService,
AggregationChartDataService,
ResultSelectionStore,
ResultSelectionService
],
imports: [SharedMocksModule]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AggregationChartComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AggregationChartComponent } from './aggregation-chart.component';
import {BarchartDataService} from "../../services/barchart-data.service";
import {AggregationChartDataService} from "../../services/aggregation-chart-data.service";
import {SharedMocksModule} from "../../../../testing/shared-mocks.module";
import {ResultSelectionStore} from "../../../result-selection/services/result-selection.store";
import {ResultSelectionService} from "../../../result-selection/services/result-selection.service";
import {SpinnerComponent} from "../../../shared/components/spinner/spinner.component";
describe('AggregationChartComponent', () => {
let component: AggregationChartComponent;
let fixture: ComponentFixture<AggregationChartComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AggregationChartComponent, SpinnerComponent ],
providers: [
BarchartDataService,
AggregationChartDataService,
ResultSelectionStore,
ResultSelectionService
],
imports: [SharedMocksModule]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AggregationChartComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| Test SpinnerComponent in AggregationChart component | [IT-2784] Test SpinnerComponent in AggregationChart component
| TypeScript | apache-2.0 | iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor | ---
+++
@@ -6,6 +6,7 @@
import {SharedMocksModule} from "../../../../testing/shared-mocks.module";
import {ResultSelectionStore} from "../../../result-selection/services/result-selection.store";
import {ResultSelectionService} from "../../../result-selection/services/result-selection.service";
+import {SpinnerComponent} from "../../../shared/components/spinner/spinner.component";
describe('AggregationChartComponent', () => {
let component: AggregationChartComponent;
@@ -13,7 +14,7 @@
beforeEach(async(() => {
TestBed.configureTestingModule({
- declarations: [ AggregationChartComponent ],
+ declarations: [ AggregationChartComponent, SpinnerComponent ],
providers: [
BarchartDataService,
AggregationChartDataService, |
00ab9da9db3696cccfc493debe2c28c2a2cf4cd2 | src/nerdbank-streams/src/tests/Timeout.ts | src/nerdbank-streams/src/tests/Timeout.ts | import { Deferred } from "../Deferred";
export function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {
const deferred = new Deferred<T>();
const timer = setTimeout(
() => {
deferred.reject("timeout expired");
},
ms);
promise.then((result) => {
clearTimeout(timer);
deferred.resolve(result);
});
promise.catch((reason) => {
clearTimeout(timer);
deferred.reject(reason);
});
return deferred.promise;
}
| import { Deferred } from "../Deferred";
export function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {
const deferred = new Deferred<T>();
const timer = setTimeout(
() => {
deferred.reject("timeout expired");
},
ms);
promise.then((result) => {
clearTimeout(timer);
deferred.resolve(result);
});
promise.catch((reason) => {
clearTimeout(timer);
deferred.reject(reason);
});
return deferred.promise;
}
export function delay(ms: number): Promise<void> {
const deferred = new Deferred<void>();
const t = setTimeout(
() => {
deferred.resolve();
},
ms);
return deferred.promise;
} | Add delay promise method for testing | Add delay promise method for testing
| TypeScript | mit | AArnott/Nerdbank.FullDuplexStream | ---
+++
@@ -17,3 +17,13 @@
});
return deferred.promise;
}
+
+export function delay(ms: number): Promise<void> {
+ const deferred = new Deferred<void>();
+ const t = setTimeout(
+ () => {
+ deferred.resolve();
+ },
+ ms);
+ return deferred.promise;
+} |
bdd0ff06eea57b4ea0002860e246d7341f964184 | command-params.ts | command-params.ts | ///<reference path="../.d.ts"/>
"use strict";
export class StringCommandParameter implements ICommandParameter {
public mandatory = false;
public errorMessage: string;
public validate(validationValue: string): IFuture<boolean> {
return (() => {
if(!validationValue) {
if(this.errorMessage) {
$injector.resolve("errors").fail(this.errorMessage);
}
return false;
}
return true;
}).future<boolean>()();
}
}
$injector.register("stringParameter", StringCommandParameter);
export class StringParameterBuilder implements IStringParameterBuilder {
public createMandatoryParameter(errorMsg: string) {
var commandParameter = new StringCommandParameter();
commandParameter.mandatory = true;
commandParameter.errorMessage = errorMsg;
return commandParameter;
}
}
$injector.register("stringParameterBuilder", StringParameterBuilder);
| ///<reference path="../.d.ts"/>
"use strict";
export class StringCommandParameter implements ICommandParameter {
public mandatory = false;
public errorMessage: string;
public validate(validationValue: string): IFuture<boolean> {
return (() => {
if(!validationValue) {
if(this.errorMessage) {
$injector.resolve("errors").fail(this.errorMessage);
}
return false;
}
return true;
}).future<boolean>()();
}
}
$injector.register("stringParameter", StringCommandParameter);
export class StringParameterBuilder implements IStringParameterBuilder {
public createMandatoryParameter(errorMsg: string) : ICommandParameter {
var commandParameter = new StringCommandParameter();
commandParameter.mandatory = true;
commandParameter.errorMessage = errorMsg;
return commandParameter;
}
}
$injector.register("stringParameterBuilder", StringParameterBuilder);
| Fix return type of createMandatoryParameter | Fix return type of createMandatoryParameter
Add ICommandParameter as return type of createMandatoryParameter method.
| TypeScript | apache-2.0 | telerik/mobile-cli-lib,telerik/mobile-cli-lib | ---
+++
@@ -22,7 +22,7 @@
$injector.register("stringParameter", StringCommandParameter);
export class StringParameterBuilder implements IStringParameterBuilder {
- public createMandatoryParameter(errorMsg: string) {
+ public createMandatoryParameter(errorMsg: string) : ICommandParameter {
var commandParameter = new StringCommandParameter();
commandParameter.mandatory = true;
commandParameter.errorMessage = errorMsg; |
4a7f90248b546803cab07188521ac97e175b31e6 | server/controllers/live.ts | server/controllers/live.ts | import * as express from 'express'
import { mapToJSON } from '@server/helpers/core-utils'
import { LiveManager } from '@server/lib/live-manager'
const liveRouter = express.Router()
liveRouter.use('/segments-sha256/:videoUUID',
getSegmentsSha256
)
// ---------------------------------------------------------------------------
export {
liveRouter
}
// ---------------------------------------------------------------------------
function getSegmentsSha256 (req: express.Request, res: express.Response) {
const videoUUID = req.params.videoUUID
const result = LiveManager.Instance.getSegmentsSha256(videoUUID)
if (!result) {
return res.sendStatus(404)
}
return res.json(mapToJSON(result))
}
| import * as cors from 'cors'
import * as express from 'express'
import { mapToJSON } from '@server/helpers/core-utils'
import { LiveManager } from '@server/lib/live-manager'
const liveRouter = express.Router()
liveRouter.use('/segments-sha256/:videoUUID',
cors(),
getSegmentsSha256
)
// ---------------------------------------------------------------------------
export {
liveRouter
}
// ---------------------------------------------------------------------------
function getSegmentsSha256 (req: express.Request, res: express.Response) {
const videoUUID = req.params.videoUUID
const result = LiveManager.Instance.getSegmentsSha256(videoUUID)
if (!result) {
return res.sendStatus(404)
}
return res.json(mapToJSON(result))
}
| Fix cors on sha segment endpoint | Fix cors on sha segment endpoint
| TypeScript | agpl-3.0 | Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube | ---
+++
@@ -1,3 +1,4 @@
+import * as cors from 'cors'
import * as express from 'express'
import { mapToJSON } from '@server/helpers/core-utils'
import { LiveManager } from '@server/lib/live-manager'
@@ -5,6 +6,7 @@
const liveRouter = express.Router()
liveRouter.use('/segments-sha256/:videoUUID',
+ cors(),
getSegmentsSha256
)
|
73e6fe9df07b4abca3856ecc10eaff757553f7a0 | big-theta-app/src/app/home/home.component.ts | big-theta-app/src/app/home/home.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../services/user.service';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
appUser: any;
constructor(
private router:Router,
private _userService:UserService,
private _authService:AuthService
) {
this.appUser = this._userService.getUser();
}
ngOnInit() {}
logout() {
this._authService.logout();
this.router.navigateByUrl('login');
}
}
| import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../services/user.service';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
appUser: any;
constructor(
private router:Router,
private _userService:UserService,
private _authService:AuthService
) {
this.appUser = this._userService.getUser();
}
ngOnInit() {}
logout() {
this._authService.logout();
window.location.href = "/login";
}
}
| Change router to href link for logout | Change router to href link for logout
| TypeScript | mit | pghant/big-theta,pghant/big-theta,pghant/big-theta,pghant/big-theta | ---
+++
@@ -23,7 +23,7 @@
logout() {
this._authService.logout();
- this.router.navigateByUrl('login');
+ window.location.href = "/login";
}
} |
fad6e2f833f3f6a28c143cfac8db347a5b989121 | src/components/App.tsx | src/components/App.tsx | import * as React from "react";
import { hot } from "react-hot-loader";
const reactLogo = require("./../assets/img/react_logo.svg");
import "./../assets/scss/App.scss";
class App extends React.Component<{}, undefined> {
public render() {
return (
<div className="app">
<h1>Hello World!</h1>
<p>Foo to the barz</p>
<img src={reactLogo} height="480"/>
</div>
);
}
}
declare let module: object;
export default hot(module)(App);
| import * as React from "react";
import { hot } from "react-hot-loader";
const reactLogo = require("./../assets/img/react_logo.svg");
import "./../assets/scss/App.scss";
class App extends React.Component<{}, undefined> {
public render() {
return (
<div className="app">
<h1>Hello World!</h1>
<p>Foo to the barz</p>
<img src={reactLogo.default} height="480"/>
</div>
);
}
}
declare let module: object;
export default hot(module)(App);
| Update source to sample image. | Update source to sample image.
| TypeScript | mit | vikpe/react-webpack-typescript-starter,vikpe/react-webpack-typescript-starter | ---
+++
@@ -10,7 +10,7 @@
<div className="app">
<h1>Hello World!</h1>
<p>Foo to the barz</p>
- <img src={reactLogo} height="480"/>
+ <img src={reactLogo.default} height="480"/>
</div>
);
} |
0530152d2d5cb5f09f54849bad2bdd1f3b853597 | src/PhpParser/PhpParser.ts | src/PhpParser/PhpParser.ts | import * as fs from "fs";
import * as vscode from "vscode";
import MemberTypes from "./MemberTypes";
class ParsedPhpClass {
public name: string;
public properties: MemberTypes = new MemberTypes();
public methods: MemberTypes = new MemberTypes();
}
function parsePhpToObject(phpClass: string): ParsedPhpClass {
const parsed = new ParsedPhpClass();
const propertyRegex = /(public|protected|private) \$(.*) (?==)/g;
let propertyMatches = propertyRegex.exec(phpClass);
while (propertyMatches != null) {
parsed.properties[propertyMatches[1]].push(propertyMatches[2]);
propertyMatches = propertyRegex.exec(phpClass);
}
const methodRegex = /(public|protected|private) (.*function) (.*)(?=\()/g;
let methodMatches = methodRegex.exec(phpClass);
while (methodMatches != null) {
parsed.methods[methodMatches[1]].push(methodMatches[3]);
methodMatches = methodRegex.exec(phpClass);
}
return parsed;
}
export default async function parse(filePath: string) {
const phpClassAsString = await new Promise<string>((resolve, reject) => {
fs.readFile(filePath, null, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data.toString("utf8"));
}
});
});
const parsed = parsePhpToObject(phpClassAsString);
parsed.name = filePath.match(/.*[\/\\](\w*).php$/i)[1];
return parsed;
}
| import * as fs from "fs";
import * as path from "path";
import * as vscode from "vscode";
import MemberTypes from "./MemberTypes";
class ParsedPhpClass {
public name: string;
public properties: MemberTypes = new MemberTypes();
public methods: MemberTypes = new MemberTypes();
}
function parsePhpToObject(phpClass: string): ParsedPhpClass {
const parsed = new ParsedPhpClass();
const propertyRegex = /(public|protected|private) \$(.*) (?==)/g;
let propertyMatches = propertyRegex.exec(phpClass);
while (propertyMatches != null) {
parsed.properties[propertyMatches[1]].push(propertyMatches[2]);
propertyMatches = propertyRegex.exec(phpClass);
}
const methodRegex = /(public|protected|private) (.*function) (.*)(?=\()/g;
let methodMatches = methodRegex.exec(phpClass);
while (methodMatches != null) {
parsed.methods[methodMatches[1]].push(methodMatches[3]);
methodMatches = methodRegex.exec(phpClass);
}
return parsed;
}
export default async function parse(filePath: string) {
const phpClassAsString = await new Promise<string>((resolve, reject) => {
fs.readFile(filePath, null, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data.toString("utf8"));
}
});
});
const parsed = parsePhpToObject(phpClassAsString);
parsed.name = path.basename(filePath, '.php');
return parsed;
}
| Use basename to extract class name | Use basename to extract class name
| TypeScript | mit | elonmallin/vscode-phpunit | ---
+++
@@ -1,4 +1,5 @@
import * as fs from "fs";
+import * as path from "path";
import * as vscode from "vscode";
import MemberTypes from "./MemberTypes";
@@ -42,7 +43,7 @@
});
const parsed = parsePhpToObject(phpClassAsString);
- parsed.name = filePath.match(/.*[\/\\](\w*).php$/i)[1];
+ parsed.name = path.basename(filePath, '.php');
return parsed;
} |
5183e58c8047d0bc519fd5b762b7986e85bfa171 | src/components/class/class-list.tsx | src/components/class/class-list.tsx | import * as React from "react";
import { ClassSummary } from "./class-summary"
import {ClassXCourse} from "../../control/class"
interface ClassString extends ClassXCourse {
teacher_string: string,
department_string: string
}
export interface ClassListProps {
classes: ClassXCourse[],
}
export class ClassList extends React.Component<ClassListProps, {}> {
render() {
let classes = this.props.classes.map( (c, i) => {
return <ClassSummary key={c.title} class_={c} />
});
return <table className="class-list">
<thead>
<tr>
<th>Instructor</th>
<th>Section</th>
<th>Semester</th>
<th>CRN</th>
<th>Days</th>
<th>Time</th>
<th>Length</th>
</tr>
</thead>
<tbody>
{classes}
</tbody>
</table>
}
} | import * as React from "react";
import { ClassSummary } from "./class-summary"
import {ClassXCourse} from "../../control/class"
interface ClassString extends ClassXCourse {
teacher_string: string,
department_string: string
}
export interface ClassListProps {
classes: ClassXCourse[],
}
export class ClassList extends React.Component<ClassListProps, {}> {
render() {
let classes = this.props.classes.map( (c, i) => {
return <ClassSummary key={c.CRN} class_={c} />
});
return <table className="class-list">
<thead>
<tr>
<th>Instructor</th>
<th>Section</th>
<th>Semester</th>
<th>CRN</th>
<th>Days</th>
<th>Time</th>
<th>Length</th>
</tr>
</thead>
<tbody>
{classes}
</tbody>
</table>
}
} | Make the Key Actually Unique | Make the Key Actually Unique
| TypeScript | mit | goodbye-island/S-Store-Front-End,goodbye-island/S-Store-Front-End,goodbye-island/S-Store-Front-End | ---
+++
@@ -14,7 +14,7 @@
export class ClassList extends React.Component<ClassListProps, {}> {
render() {
let classes = this.props.classes.map( (c, i) => {
- return <ClassSummary key={c.title} class_={c} />
+ return <ClassSummary key={c.CRN} class_={c} />
});
return <table className="class-list">
<thead> |
b931aedd0a4a074aa074fd912157217101bdb321 | src/components/parser/syntax.ts | src/components/parser/syntax.ts | import type {latexParser, bibtexParser} from 'latex-utensils'
import * as path from 'path'
import * as workerpool from 'workerpool'
import type {Proxy} from 'workerpool'
import type {ISyntaxWorker} from './syntax_worker'
export class UtensilsParser {
private readonly pool: workerpool.WorkerPool
private readonly proxy: workerpool.Promise<Proxy<ISyntaxWorker>>
constructor() {
this.pool = workerpool.pool(
path.join(__dirname, 'syntax_worker.js'),
{ minWorkers: 1, maxWorkers: 1, workerType: 'process' }
)
this.proxy = this.pool.proxy<ISyntaxWorker>()
}
async dispose() {
await this.pool.terminate()
}
/**
* Parse a LaTeX file.
*
* @param s The content of a LaTeX file to be parsed.
* @param options
* @return undefined if parsing fails
*/
async parseLatex(s: string, options?: latexParser.ParserOptions): Promise<latexParser.LatexAst> {
return (await this.proxy).parseLatex(s, options).timeout(3000)
}
async parseLatexPreamble(s: string): Promise<latexParser.AstPreamble> {
return (await this.proxy).parseLatexPreamble(s).timeout(500)
}
async parseBibtex(s: string, options?: bibtexParser.ParserOptions): Promise<bibtexParser.BibtexAst> {
return (await this.proxy).parseBibtex(s, options).timeout(30000)
}
}
| import type {latexParser, bibtexParser} from 'latex-utensils'
import * as path from 'path'
import * as workerpool from 'workerpool'
import type {Proxy} from 'workerpool'
import type {ISyntaxWorker} from './syntax_worker'
export class UtensilsParser {
private readonly pool: workerpool.WorkerPool
private readonly proxy: workerpool.Promise<Proxy<ISyntaxWorker>>
constructor() {
this.pool = workerpool.pool(
path.join(__dirname, 'syntax_worker.js'),
{ minWorkers: 1, maxWorkers: 1, workerType: 'process' }
)
this.proxy = this.pool.proxy<ISyntaxWorker>()
}
async dispose() {
await this.pool.terminate()
}
/**
* Parse a LaTeX file.
*
* @param s The content of a LaTeX file to be parsed.
* @param options
* @return undefined if parsing fails
*/
async parseLatex(s: string, options?: latexParser.ParserOptions): Promise<latexParser.LatexAst | undefined> {
return (await this.proxy).parseLatex(s, options).timeout(3000).catch(() => undefined)
}
async parseLatexPreamble(s: string): Promise<latexParser.AstPreamble> {
return (await this.proxy).parseLatexPreamble(s).timeout(500)
}
async parseBibtex(s: string, options?: bibtexParser.ParserOptions): Promise<bibtexParser.BibtexAst> {
return (await this.proxy).parseBibtex(s, options).timeout(30000)
}
}
| Make parseLatex return undefined on errors. Reverting changes | Make parseLatex return undefined on errors. Reverting changes
| TypeScript | mit | James-Yu/LaTeX-Workshop,James-Yu/LaTeX-Workshop,James-Yu/LaTeX-Workshop,James-Yu/LaTeX-Workshop,James-Yu/LaTeX-Workshop | ---
+++
@@ -27,8 +27,8 @@
* @param options
* @return undefined if parsing fails
*/
- async parseLatex(s: string, options?: latexParser.ParserOptions): Promise<latexParser.LatexAst> {
- return (await this.proxy).parseLatex(s, options).timeout(3000)
+ async parseLatex(s: string, options?: latexParser.ParserOptions): Promise<latexParser.LatexAst | undefined> {
+ return (await this.proxy).parseLatex(s, options).timeout(3000).catch(() => undefined)
}
async parseLatexPreamble(s: string): Promise<latexParser.AstPreamble> { |
37874f313fa7b2c2934ab1c20ff43a88463840bb | client/components/Admin/User/UserSearchForm.tsx | client/components/Admin/User/UserSearchForm.tsx | import React, { FC } from 'react'
interface Props {
handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void
handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void
value: string
}
const UserSearchForm: FC<Props> = ({ handleSubmit, handleChange, value }) => {
return (
<form className="form-group input-group col-xs-6" onSubmit={handleSubmit}>
{/* q だと事故る (検索欄に入ってしまう) ので、uq にしてます */}
<input
autoComplete="off"
type="text"
className="form-control"
placeholder="Search ... User ID, Name and Email /"
name="uq"
value={value}
onChange={handleChange}
/>
<span className="input-group-append">
<button type="submit" className="btn btn-outline-secondary">
<i className="search-top-icon mdi mdi-magnify" />
</button>
</span>
</form>
)
}
export default UserSearchForm
| import React, { FC } from 'react'
import Icon from 'client/components/Common/Icon'
interface Props {
handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void
handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void
value: string
}
const UserSearchForm: FC<Props> = ({ handleSubmit, handleChange, value }) => {
return (
<form className="form-group input-group col-xs-6" onSubmit={handleSubmit}>
{/* q だと事故る (検索欄に入ってしまう) ので、uq にしてます */}
<input
autoComplete="off"
type="text"
className="form-control"
placeholder="Search ... User ID, Name and Email /"
name="uq"
value={value}
onChange={handleChange}
/>
<span className="input-group-append">
<button type="submit" className="btn btn-outline-secondary">
<Icon className="search-top-icon" name="magnify" />
</button>
</span>
</form>
)
}
export default UserSearchForm
| Fix user search form icon | Fix user search form icon | TypeScript | mit | crowi/crowi,crowi/crowi,crowi/crowi | ---
+++
@@ -1,4 +1,5 @@
import React, { FC } from 'react'
+import Icon from 'client/components/Common/Icon'
interface Props {
handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void
@@ -21,7 +22,7 @@
/>
<span className="input-group-append">
<button type="submit" className="btn btn-outline-secondary">
- <i className="search-top-icon mdi mdi-magnify" />
+ <Icon className="search-top-icon" name="magnify" />
</button>
</span>
</form> |
2b752a67964a6eed227ca98fe96e08c3fe97367c | src/AccordionItem/AccordionItem.wrapper.tsx | src/AccordionItem/AccordionItem.wrapper.tsx | import * as React from 'react';
import {
AccordionContext,
Consumer as AccordionConsumer,
} from '../AccordionContext/AccordionContext';
import { nextUuid } from '../helpers/uuid';
import { Provider as ItemProvider } from '../ItemContext/ItemContext';
import AccordionItem from './AccordionItem';
type AccordionItemWrapperProps = React.HTMLAttributes<HTMLDivElement> & {
expandedClassName?: string;
uuid?: string;
};
type AccordionItemWrapperState = {};
export default class AccordionItemWrapper extends React.Component<
AccordionItemWrapperProps,
AccordionItemWrapperState
> {
static defaultProps: AccordionItemWrapperProps = {
className: 'accordion__item',
expandedClassName: '',
uuid: undefined,
};
id: number = nextUuid();
renderChildren = (accordionContext: AccordionContext): JSX.Element => {
const { uuid = this.id, ...rest } = this.props;
const expanded = accordionContext.isItemExpanded(uuid);
return (
<ItemProvider uuid={uuid}>
<AccordionItem {...rest} expanded={expanded} />
</ItemProvider>
);
};
render(): JSX.Element {
return <AccordionConsumer>{this.renderChildren}</AccordionConsumer>;
}
}
| import * as React from 'react';
import {
AccordionContext,
Consumer as AccordionConsumer,
} from '../AccordionContext/AccordionContext';
import { nextUuid } from '../helpers/uuid';
import { Provider as ItemProvider } from '../ItemContext/ItemContext';
import AccordionItem from './AccordionItem';
type AccordionItemWrapperProps = React.HTMLAttributes<HTMLDivElement> & {
expandedClassName?: string;
uuid?: string;
};
type AccordionItemWrapperState = {};
export default class AccordionItemWrapper extends React.Component<
AccordionItemWrapperProps,
AccordionItemWrapperState
> {
static defaultProps: AccordionItemWrapperProps = {
className: 'accordion__item',
expandedClassName: 'accordion__item--expanded',
uuid: undefined,
};
id: number = nextUuid();
renderChildren = (accordionContext: AccordionContext): JSX.Element => {
const { uuid = this.id, ...rest } = this.props;
const expanded = accordionContext.isItemExpanded(uuid);
return (
<ItemProvider uuid={uuid}>
<AccordionItem {...rest} expanded={expanded} />
</ItemProvider>
);
};
render(): JSX.Element {
return <AccordionConsumer>{this.renderChildren}</AccordionConsumer>;
}
}
| Fix missing expandedClassName in AccordionItem | Fix missing expandedClassName in AccordionItem
| TypeScript | mit | springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion | ---
+++
@@ -21,7 +21,7 @@
> {
static defaultProps: AccordionItemWrapperProps = {
className: 'accordion__item',
- expandedClassName: '',
+ expandedClassName: 'accordion__item--expanded',
uuid: undefined,
};
|
450f54d71fb31653623dc86b40f09505cd5985e8 | src/selectors/watcherFolders.ts | src/selectors/watcherFolders.ts | import { createSelector } from 'reselect';
import { watcherFoldersSelector } from './index';
import { Watcher } from '../types';
import { normalizedWatchers } from './watchers';
import { Map } from 'immutable';
export const watchersToFolderWatcherMap = createSelector(
[normalizedWatchers, watcherFoldersSelector],
(watchers, folders) => {
return watchers.reduce(
(acc: Map<string, Watcher[]>, cur: Watcher) =>
acc.update(
cur.folderId,
(watcherArray: Watcher[]) =>
watcherArray && watcherArray.length > 0
? [...watcherArray, cur]
: [cur]
),
Map<string, Watcher[]>()
);
}
);
export const getWatcherIdsAssignedToFolder = (folderId: string) =>
createSelector([watchersToFolderWatcherMap], watcherFolderMap =>
watcherFolderMap.get(folderId).map((cur: Watcher) => cur.groupId)
);
| import { createSelector } from 'reselect';
import { watcherFoldersSelector } from './index';
import { Watcher } from '../types';
import { normalizedWatchers } from './watchers';
import { Map } from 'immutable';
export const watchersToFolderWatcherMap = createSelector(
[normalizedWatchers, watcherFoldersSelector],
(watchers, folders) => {
return watchers.reduce(
(acc: Map<string, Watcher[]>, cur: Watcher) =>
acc.update(
cur.folderId,
(watcherArray: Watcher[]) =>
watcherArray && watcherArray.length > 0
? [...watcherArray, cur]
: [cur]
),
Map<string, Watcher[]>()
);
}
);
export const getWatcherIdsAssignedToFolder = (folderId: string) =>
createSelector([watchersToFolderWatcherMap], watcherFolderMap =>
watcherFolderMap.get(folderId, []).map((cur: Watcher) => cur.groupId)
);
| Fix crash when selecting an empty watcher folder. | Fix crash when selecting an empty watcher folder.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -23,5 +23,5 @@
export const getWatcherIdsAssignedToFolder = (folderId: string) =>
createSelector([watchersToFolderWatcherMap], watcherFolderMap =>
- watcherFolderMap.get(folderId).map((cur: Watcher) => cur.groupId)
+ watcherFolderMap.get(folderId, []).map((cur: Watcher) => cur.groupId)
); |
bbee13dcd7851b4b0388e0c4d449456509570ac4 | app/scripts/modules/amazon/src/loadBalancer/configure/network/NLBAdvancedSettings.tsx | app/scripts/modules/amazon/src/loadBalancer/configure/network/NLBAdvancedSettings.tsx | import React from 'react';
import { CheckboxInput, FormikFormField, HelpField } from '@spinnaker/core';
export interface INLBAdvancedSettingsProps {
showDualstack: boolean;
}
export const NLBAdvancedSettings = React.forwardRef<HTMLDivElement, INLBAdvancedSettingsProps>((props, ref) => (
<div ref={ref}>
<FormikFormField
name="deletionProtection"
label="Protection"
help={<HelpField id="loadBalancer.advancedSettings.deletionProtection" />}
input={(inputProps) => <CheckboxInput {...inputProps} text="Enable deletion protection" />}
/>
<FormikFormField
name="loadBalancingCrossZone"
label="Cross-Zone Load Balancing"
help={<HelpField id="loadBalancer.advancedSettings.loadBalancingCrossZone" />}
input={(inputProps) => <CheckboxInput {...inputProps} text="Enable deletion protection" />}
/>
{props.showDualstack && (
<FormikFormField
name="dualstack"
label="Dualstack"
help={<HelpField id="loadBalancer.advancedSettings.nlbIpAddressType" />}
input={(inputProps) => <CheckboxInput {...inputProps} text="Assign Ipv4 and IPv6" />}
/>
)}
</div>
));
| import React from 'react';
import { CheckboxInput, FormikFormField, HelpField } from '@spinnaker/core';
export interface INLBAdvancedSettingsProps {
showDualstack: boolean;
}
export const NLBAdvancedSettings = React.forwardRef<HTMLDivElement, INLBAdvancedSettingsProps>((props, ref) => (
<div ref={ref}>
<FormikFormField
name="deletionProtection"
label="Protection"
help={<HelpField id="loadBalancer.advancedSettings.deletionProtection" />}
input={(inputProps) => <CheckboxInput {...inputProps} text="Enable deletion protection" />}
/>
<FormikFormField
name="loadBalancingCrossZone"
label="Cross-Zone Load Balancing"
help={<HelpField id="loadBalancer.advancedSettings.loadBalancingCrossZone" />}
input={(inputProps) => <CheckboxInput {...inputProps} text="Distribute traffic across zones" />}
/>
{props.showDualstack && (
<FormikFormField
name="dualstack"
label="Dualstack"
help={<HelpField id="loadBalancer.advancedSettings.nlbIpAddressType" />}
input={(inputProps) => <CheckboxInput {...inputProps} text="Assign Ipv4 and IPv6" />}
/>
)}
</div>
));
| Fix text for cross-zone load balancing | fix(amazon/loadBalancer): Fix text for cross-zone load balancing
| TypeScript | apache-2.0 | spinnaker/deck,spinnaker/deck,spinnaker/deck,spinnaker/deck | ---
+++
@@ -19,7 +19,7 @@
name="loadBalancingCrossZone"
label="Cross-Zone Load Balancing"
help={<HelpField id="loadBalancer.advancedSettings.loadBalancingCrossZone" />}
- input={(inputProps) => <CheckboxInput {...inputProps} text="Enable deletion protection" />}
+ input={(inputProps) => <CheckboxInput {...inputProps} text="Distribute traffic across zones" />}
/>
{props.showDualstack && ( |
0acec31c37a505e8ac5948e72fc3627b3a2d36b8 | LegatumClient/src/app/home/home.component.ts | LegatumClient/src/app/home/home.component.ts | import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
| import { Component, OnInit } from '@angular/core';
declare var swal: any;
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
handleLogin(): void {
console.log('clicked');
swal({
title: 'Login',
html:
'<input type="email" placeholder="email" id="swal-input1" class="swal2-input">' +
'<input type="password" placeholder="password" id="swal-input2" class="swal2-input">',
});
}
}
| Add handleLogin function that uses sweetalert2 | Add handleLogin function that uses sweetalert2
| TypeScript | apache-2.0 | tonymichaelhead/Legatum,tonymichaelhead/Legatum,tonymichaelhead/Legatum | ---
+++
@@ -1,4 +1,6 @@
import { Component, OnInit } from '@angular/core';
+
+declare var swal: any;
@Component({
selector: 'app-home',
@@ -12,4 +14,13 @@
ngOnInit() {
}
+ handleLogin(): void {
+ console.log('clicked');
+ swal({
+ title: 'Login',
+ html:
+ '<input type="email" placeholder="email" id="swal-input1" class="swal2-input">' +
+ '<input type="password" placeholder="password" id="swal-input2" class="swal2-input">',
+ });
+ }
} |
c4739c1ecbecec0a4ff5e0d0f16cb157405cd64f | app/services/zivi.service.ts | app/services/zivi.service.ts | /**
* Provides Zivi information from the backend's REST interface.
*/
import {Http} from '@angular/http';
import {Injectable} from '@angular/core';
import 'rxjs/Rx';
export class Zivi {
constructor(public name: string,
public name_mx: string,
public post_count: number,
public color: string,
public colorHex: string,
public picture: string,
public first: number) {
}
}
@Injectable()
export class ZiviService {
private url = 'http://localhost:4000/api/v1/zivis';
static createPictureUrl(url: string) {
return 'http://localhost:4000/images/' + url;
}
constructor(private http: Http) {
}
getZiviByName(name: string) {
return new Zivi(name, 'name', 0, 'teal', '#009688', 'picture', 0);
}
getAllZivis() {
return this.http.get(this.url)
.map(res => res.json())
.map(res => {
let zivis: Zivi[] = [];
res.zivis.forEach(function (zivi: any) {
zivis.push(new Zivi(zivi.name,
zivi.name_mx,
zivi.post_count,
zivi.color,
zivi.colorHex,
ZiviService.createPictureUrl(zivi.picture),
zivi.first));
});
return zivis;
});
}
}
| /**
* Provides Zivi information from the backend's REST interface.
*/
import {Http} from '@angular/http';
import {Injectable} from '@angular/core';
import 'rxjs/Rx';
export class Zivi {
constructor(public name: string,
public name_mx: string,
public post_count: number,
public color: string,
public colorHex: string,
public picture: string,
public first: number) {
}
}
@Injectable()
export class ZiviService {
private url = 'http://localhost:4000/api/v1/zivis';
static createPictureUrl(url: string) {
return 'http://localhost:4000/images/' + url;
}
constructor(private http: Http) {
}
getAllZivis() {
return this.http.get(this.url)
.map(res => res.json())
.map(res => {
return res.zivis.map((zivi: any) => ZiviService.createZiviFromJsonObject(zivi));
});
}
static createZiviFromJsonObject(data: any) {
return new Zivi(data.name,
data.name_mx,
data.post_count,
data.color,
data.colorHex,
ZiviService.createPictureUrl(data.picture),
data.first
);
}
}
| Add common Zivi JSON deserialisation method to ZiviService | Add common Zivi JSON deserialisation method to ZiviService
| TypeScript | mit | realzimon/ng-zimon,realzimon/ng-zimon,realzimon/ng-zimon | ---
+++
@@ -32,25 +32,22 @@
constructor(private http: Http) {
}
- getZiviByName(name: string) {
- return new Zivi(name, 'name', 0, 'teal', '#009688', 'picture', 0);
- }
-
getAllZivis() {
return this.http.get(this.url)
.map(res => res.json())
.map(res => {
- let zivis: Zivi[] = [];
- res.zivis.forEach(function (zivi: any) {
- zivis.push(new Zivi(zivi.name,
- zivi.name_mx,
- zivi.post_count,
- zivi.color,
- zivi.colorHex,
- ZiviService.createPictureUrl(zivi.picture),
- zivi.first));
- });
- return zivis;
+ return res.zivis.map((zivi: any) => ZiviService.createZiviFromJsonObject(zivi));
});
}
+
+ static createZiviFromJsonObject(data: any) {
+ return new Zivi(data.name,
+ data.name_mx,
+ data.post_count,
+ data.color,
+ data.colorHex,
+ ZiviService.createPictureUrl(data.picture),
+ data.first
+ );
+ }
} |
30202a013c9f40e2bb2e912718e38e1169e419e9 | client/test/Combatant.test.ts | client/test/Combatant.test.ts | import { StatBlock } from "../../common/StatBlock";
import { InitializeSettings } from "../Settings/Settings";
import { buildEncounter } from "./buildEncounter";
describe("Combatant", () => {
beforeEach(() => {
InitializeSettings();
});
test("Should have its Max HP set from the statblock", () => {
const encounter = buildEncounter();
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), HP: { Value: 10, Notes: "" } });
expect(combatant.MaxHP).toBe(10);
});
test("Should update its Max HP when its statblock is updated", () => {
const encounter = buildEncounter();
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), Player: "player" });
combatant.StatBlock({ ...StatBlock.Default(), HP: { Value: 15, Notes: "" } });
expect(combatant.MaxHP).toBe(15);
});
}); | import { StatBlock } from "../../common/StatBlock";
import { Encounter } from "../Encounter/Encounter";
import { InitializeSettings } from "../Settings/Settings";
import { buildEncounter } from "./buildEncounter";
describe("Combatant", () => {
let encounter: Encounter;
beforeEach(() => {
InitializeSettings();
encounter = buildEncounter();
});
test("Should have its Max HP set from the statblock", () => {
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), HP: { Value: 10, Notes: "" } });
expect(combatant.MaxHP).toBe(10);
});
test("Should update its Max HP when its statblock is updated", () => {
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), Player: "player" });
combatant.StatBlock({ ...StatBlock.Default(), HP: { Value: 15, Notes: "" } });
expect(combatant.MaxHP).toBe(15);
});
test("Should notify the encounter when its statblock is updated", () => {
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), Player: "player" });
const combatantsSpy = jest.fn();
encounter.Combatants.subscribe(combatantsSpy);
combatant.StatBlock({ ...StatBlock.Default(), HP: { Value: 15, Notes: "" } });
expect(combatantsSpy).toBeCalled();
});
}); | Test that combatants is rerendered when a statblock is changed | Test that combatants is rerendered when a statblock is changed
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -1,24 +1,35 @@
import { StatBlock } from "../../common/StatBlock";
+import { Encounter } from "../Encounter/Encounter";
import { InitializeSettings } from "../Settings/Settings";
import { buildEncounter } from "./buildEncounter";
describe("Combatant", () => {
+ let encounter: Encounter;
beforeEach(() => {
+
InitializeSettings();
+ encounter = buildEncounter();
});
test("Should have its Max HP set from the statblock", () => {
- const encounter = buildEncounter();
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), HP: { Value: 10, Notes: "" } });
expect(combatant.MaxHP).toBe(10);
});
test("Should update its Max HP when its statblock is updated", () => {
- const encounter = buildEncounter();
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), Player: "player" });
combatant.StatBlock({ ...StatBlock.Default(), HP: { Value: 15, Notes: "" } });
expect(combatant.MaxHP).toBe(15);
});
+
+ test("Should notify the encounter when its statblock is updated", () => {
+ const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), Player: "player" });
+ const combatantsSpy = jest.fn();
+ encounter.Combatants.subscribe(combatantsSpy);
+
+ combatant.StatBlock({ ...StatBlock.Default(), HP: { Value: 15, Notes: "" } });
+ expect(combatantsSpy).toBeCalled();
+ });
}); |
b74dfd969044fe948cb119ac2271fd421b8d027d | src/utils/fillDefaultFormatCodeSettings.ts | src/utils/fillDefaultFormatCodeSettings.ts | import {ManipulationSettingsContainer} from "../ManipulationSettings";
import {ts} from "../typescript";
import {FormatCodeSettings} from "../compiler";
import {setValueIfUndefined} from "./setValueIfUndefined";
import {fillDefaultEditorSettings} from "./fillDefaultEditorSettings";
export function fillDefaultFormatCodeSettings(settings: FormatCodeSettings, manipulationSettings: ManipulationSettingsContainer) {
fillDefaultEditorSettings(settings, manipulationSettings);
setValueIfUndefined(settings, "insertSpaceAfterCommaDelimiter", true);
setValueIfUndefined(settings, "insertSpaceAfterConstructor", false);
setValueIfUndefined(settings, "insertSpaceAfterSemicolonInForStatements", false);
setValueIfUndefined(settings, "insertSpaceAfterKeywordsInControlFlowStatements", true);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", false);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", false);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", false);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces", false);
setValueIfUndefined(settings, "insertSpaceBeforeFunctionParenthesis", false);
setValueIfUndefined(settings, "insertSpaceAfterSemicolonInForStatements", true);
setValueIfUndefined(settings, "insertSpaceBeforeAndAfterBinaryOperators", true);
setValueIfUndefined(settings, "placeOpenBraceOnNewLineForFunctions", false);
setValueIfUndefined(settings, "placeOpenBraceOnNewLineForControlBlocks", false);
setValueIfUndefined(settings, "ensureNewLineAtEndOfFile", true);
}
| import {ManipulationSettingsContainer} from "../ManipulationSettings";
import {ts} from "../typescript";
import {FormatCodeSettings} from "../compiler";
import {setValueIfUndefined} from "./setValueIfUndefined";
import {fillDefaultEditorSettings} from "./fillDefaultEditorSettings";
export function fillDefaultFormatCodeSettings(settings: FormatCodeSettings, manipulationSettings: ManipulationSettingsContainer) {
fillDefaultEditorSettings(settings, manipulationSettings);
setValueIfUndefined(settings, "insertSpaceAfterCommaDelimiter", true);
setValueIfUndefined(settings, "insertSpaceAfterConstructor", false);
setValueIfUndefined(settings, "insertSpaceAfterSemicolonInForStatements", true);
setValueIfUndefined(settings, "insertSpaceAfterKeywordsInControlFlowStatements", true);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", true);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", false);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", false);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces", false);
setValueIfUndefined(settings, "insertSpaceBeforeFunctionParenthesis", false);
setValueIfUndefined(settings, "insertSpaceBeforeAndAfterBinaryOperators", true);
setValueIfUndefined(settings, "placeOpenBraceOnNewLineForFunctions", false);
setValueIfUndefined(settings, "placeOpenBraceOnNewLineForControlBlocks", false);
setValueIfUndefined(settings, "ensureNewLineAtEndOfFile", true);
}
| Change formatting settings insertSpaceAfterSemicolonInForStatements to be true by default. | fix: Change formatting settings insertSpaceAfterSemicolonInForStatements to be true by default.
This was meant to be true, but was accidentally set as false above the statement that would set it to true by default.
| TypeScript | mit | dsherret/ts-simple-ast | ---
+++
@@ -8,14 +8,13 @@
fillDefaultEditorSettings(settings, manipulationSettings);
setValueIfUndefined(settings, "insertSpaceAfterCommaDelimiter", true);
setValueIfUndefined(settings, "insertSpaceAfterConstructor", false);
- setValueIfUndefined(settings, "insertSpaceAfterSemicolonInForStatements", false);
+ setValueIfUndefined(settings, "insertSpaceAfterSemicolonInForStatements", true);
setValueIfUndefined(settings, "insertSpaceAfterKeywordsInControlFlowStatements", true);
- setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", false);
+ setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", true);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", false);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", false);
setValueIfUndefined(settings, "insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces", false);
setValueIfUndefined(settings, "insertSpaceBeforeFunctionParenthesis", false);
- setValueIfUndefined(settings, "insertSpaceAfterSemicolonInForStatements", true);
setValueIfUndefined(settings, "insertSpaceBeforeAndAfterBinaryOperators", true);
setValueIfUndefined(settings, "placeOpenBraceOnNewLineForFunctions", false);
setValueIfUndefined(settings, "placeOpenBraceOnNewLineForControlBlocks", false); |
b08589b98088fe45ab2aff2e9341fccf9de0d566 | ui/src/main.ts | ui/src/main.ts | "use strict";
import {HttpClient} from "aurelia-fetch-client";
import {Aurelia} from "aurelia-framework";
import "bootstrap";
export function configure(aurelia: Aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging();
configureContainer(aurelia.container);
aurelia.start().then(() =>
aurelia.setRoot("app/config"));
}
function configureContainer(container) {
let http = new HttpClient();
http.configure(config => {
config
.useStandardConfiguration()
.withBaseUrl("/api/");
});
container.registerInstance(HttpClient, http);
}
| "use strict";
import {HttpClient} from "aurelia-fetch-client";
import {Aurelia} from "aurelia-framework";
export function configure(aurelia: Aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging();
configureContainer(aurelia.container);
aurelia.start().then(() =>
aurelia.setRoot("app/config"));
}
function configureContainer(container) {
let http = new HttpClient();
http.configure(config => {
config
.useStandardConfiguration()
.withBaseUrl("/api/");
});
container.registerInstance(HttpClient, http);
}
| Remove currently not needed import. | Remove currently not needed import.
| TypeScript | mit | jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr | ---
+++
@@ -2,7 +2,6 @@
import {HttpClient} from "aurelia-fetch-client";
import {Aurelia} from "aurelia-framework";
-import "bootstrap";
export function configure(aurelia: Aurelia) {
aurelia.use |
c237051c550cc92e5d6b0c13972f708d95ce123c | dev/contacts/contact.component.ts | dev/contacts/contact.component.ts | import {Component} from "angular2/core";
@Component({
selector: "contact",
template: `
<div>
<div>
<label for="first-name">First Name:</label>
<input [(ngModel)]="contact.firstName">
</div>
<div>
<label for="first-name">Last Name:</label>
<input [(ngModel)]="contact.lastName">
</div>
<div>
<label for="first-name">Phone Number:</label>
<input [(ngModel)]="contact.phone">
</div>
<div>
<label for="first-name">Email:</label>
<input [(ngModel)]="contact.email">
</div>
</div>
`,
inputs: ["contact"],
styles: [`
label {
display: inline-block;
width: 140px;
}
input {
width: 250px;
}
`]
})
export class ContactComponent {
public contact = {};
} | import {Component} from 'angular2/core';
import {Router} from 'angular2/router';
import {Contact} from './contact';
@Component({
selector: "contact",
template: `
<div>
<div>
<label for="first-name">First Name:</label>
<input [(ngModel)]="contact.firstName">
</div>
<div>
<label for="first-name">Last Name:</label>
<input [(ngModel)]="contact.lastName">
</div>
<div>
<label for="first-name">Phone Number:</label>
<input [(ngModel)]="contact.phone">
</div>
<div>
<label for="first-name">Email:</label>
<input [(ngModel)]="contact.email">
</div>
<button (click)="onCreateNew()">Create new contact from this contact</button>
</div>
`,
inputs: ["contact"],
styles: [`
label {
display: inline-block;
width: 140px;
}
input {
width: 250px;
}
`]
})
export class ContactComponent {
public contact: Contact = null;
constructor(private _privateRouter: Router){};
onCreateNew(){
this._privateRouter.navigate(['NewContactFromContact', {
lastName: this.contact.lastName
}])
}
} | Add a button to go the selected user form | Add a button to go the selected user form
| TypeScript | mit | tonirilix/angular2-playground,tonirilix/angular2-playground,tonirilix/angular2-playground | ---
+++
@@ -1,4 +1,6 @@
-import {Component} from "angular2/core";
+import {Component} from 'angular2/core';
+import {Router} from 'angular2/router';
+import {Contact} from './contact';
@Component({
selector: "contact",
@@ -20,6 +22,7 @@
<label for="first-name">Email:</label>
<input [(ngModel)]="contact.email">
</div>
+ <button (click)="onCreateNew()">Create new contact from this contact</button>
</div>
`,
inputs: ["contact"],
@@ -35,5 +38,13 @@
`]
})
export class ContactComponent {
- public contact = {};
+ public contact: Contact = null;
+
+ constructor(private _privateRouter: Router){};
+
+ onCreateNew(){
+ this._privateRouter.navigate(['NewContactFromContact', {
+ lastName: this.contact.lastName
+ }])
+ }
} |
f2758d83449d4bc070063e76487fb50c8adad6d2 | src/tests/compiler/namespace/namespaceChildableNode.ts | src/tests/compiler/namespace/namespaceChildableNode.ts | import {expect} from "chai";
import {NamespaceDeclaration, NamespaceChildableNode} from "./../../../compiler";
import {getInfoFromText} from "./../testHelpers";
describe(nameof(NamespaceChildableNode), () => {
describe(nameof<NamespaceChildableNode>(d => d.getParentNamespace), () => {
it("should get the parent namespace when not using dot notation", () => {
const {firstChild} = getInfoFromText<NamespaceDeclaration>("namespace MyNamespace { class MyClass {} }");
expect(firstChild.getClasses()[0].getParentNamespace()).to.equal(firstChild);
});
it("should get the parent namespace when using dot notation", () => {
const {firstChild} = getInfoFromText<NamespaceDeclaration>("namespace MyNamespace.MyOtherNamespace { class MyClass {} }");
expect(firstChild.getClasses()[0].getParentNamespace()).to.equal(firstChild);
});
it("should get the parent namespace when using dot notation with the module keyword", () => {
const {firstChild} = getInfoFromText<NamespaceDeclaration>("module MyNamespace.MyOtherNamespace { class MyClass {} }");
expect(firstChild.getClasses()[0].getParentNamespace()).to.equal(firstChild);
});
it("should get the parent namespace for variable statements", () => {
const {firstChild} = getInfoFromText<NamespaceDeclaration>("namespace MyNamespace.MyOtherNamespace { const v; }");
expect(firstChild.getVariableStatements()[0].getParentNamespace()).to.equal(firstChild);
});
});
});
| import {expect} from "chai";
import {NamespaceDeclaration, NamespaceChildableNode} from "./../../../compiler";
import {getInfoFromText} from "./../testHelpers";
describe(nameof(NamespaceChildableNode), () => {
describe(nameof<NamespaceChildableNode>(d => d.getParentNamespace), () => {
it("should get the parent namespace when not using dot notation", () => {
const {firstChild} = getInfoFromText<NamespaceDeclaration>("namespace MyNamespace { class MyClass {} }");
expect(firstChild.getClasses()[0].getParentNamespace()).to.equal(firstChild);
});
it("should get the parent namespace when using dot notation", () => {
const {firstChild} = getInfoFromText<NamespaceDeclaration>("namespace MyNamespace.MyOtherNamespace { class MyClass {} }");
expect(firstChild.getClasses()[0].getParentNamespace()).to.equal(firstChild);
});
it("should get the parent namespace when using dot notation with the module keyword", () => {
const {firstChild} = getInfoFromText<NamespaceDeclaration>("module MyNamespace.MyOtherNamespace { class MyClass {} }");
expect(firstChild.getClasses()[0].getParentNamespace()).to.equal(firstChild);
});
it("should get the parent namespace for variable statements", () => {
const {firstChild} = getInfoFromText<NamespaceDeclaration>("namespace MyNamespace.MyOtherNamespace { const v; }");
expect(firstChild.getVariableStatements()[0].getParentNamespace()).to.equal(firstChild);
});
it("should return undefined when not in a namespace", () => {
const {firstChild} = getInfoFromText<NamespaceDeclaration>("namespace MyNamespace.MyOtherNamespace { }");
expect(firstChild.getParentNamespace()).to.equal(undefined);
});
});
});
| Add missing undefined test for NamespaceChildableNode.getParentNamespace | Add missing undefined test for NamespaceChildableNode.getParentNamespace
| TypeScript | mit | dsherret/ts-simple-ast | ---
+++
@@ -23,5 +23,10 @@
const {firstChild} = getInfoFromText<NamespaceDeclaration>("namespace MyNamespace.MyOtherNamespace { const v; }");
expect(firstChild.getVariableStatements()[0].getParentNamespace()).to.equal(firstChild);
});
+
+ it("should return undefined when not in a namespace", () => {
+ const {firstChild} = getInfoFromText<NamespaceDeclaration>("namespace MyNamespace.MyOtherNamespace { }");
+ expect(firstChild.getParentNamespace()).to.equal(undefined);
+ });
});
}); |
e6dfbbff828d09f0644c9ccb8a0e7a32b728623d | packages/design-studio/schemas/author.ts | packages/design-studio/schemas/author.ts | import icon from 'part:@sanity/base/user-icon'
export default {
type: 'document',
name: 'author',
title: 'Author',
icon,
fields: [
{
type: 'string',
name: 'name',
title: 'Name',
validation: Rule =>
Rule.required()
.min(10)
.max(80)
},
{
type: 'string',
name: 'role',
title: 'Role',
options: {
layout: 'radio',
list: ['developer', 'designer', 'manager'],
direction: 'horizontal' // | 'vertical'
}
},
{
type: 'image',
name: 'avatar',
title: 'Avatar',
options: {
hotspot: true
}
},
{
type: 'array',
name: 'bio',
title: 'Bio',
of: [{type: 'block'}]
},
{
type: 'string',
name: 'phoneNumber',
title: 'Phone #'
}
]
}
| import icon from 'part:@sanity/base/user-icon'
export default {
type: 'document',
name: 'author',
title: 'Author',
icon,
fields: [
{
type: 'string',
name: 'name',
title: 'Name',
validation: Rule =>
Rule.required()
.min(10)
.max(80)
},
{
type: 'string',
name: 'role',
title: 'Role',
options: {
layout: 'radio',
list: ['developer', 'designer', 'manager'],
direction: 'horizontal' // | 'vertical'
}
},
{
type: 'image',
name: 'avatar',
title: 'Avatar',
options: {
hotspot: true
},
fields: [
{
name: 'caption',
type: 'string',
title: 'Caption',
options: {
isHighlighted: true // <-- make this field easily accessible
}
},
{
// Editing this field will be hidden behind an "Edit"-button
name: 'attribution',
type: 'string',
title: 'Attribution'
}
]
},
{
type: 'array',
name: 'bio',
title: 'Bio',
of: [{type: 'block'}]
},
{
type: 'string',
name: 'phoneNumber',
title: 'Phone #'
}
]
}
| Add example of image meta fields | [design-studio] Add example of image meta fields
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -31,7 +31,23 @@
title: 'Avatar',
options: {
hotspot: true
- }
+ },
+ fields: [
+ {
+ name: 'caption',
+ type: 'string',
+ title: 'Caption',
+ options: {
+ isHighlighted: true // <-- make this field easily accessible
+ }
+ },
+ {
+ // Editing this field will be hidden behind an "Edit"-button
+ name: 'attribution',
+ type: 'string',
+ title: 'Attribution'
+ }
+ ]
},
{
type: 'array', |
a43906111af617a497520feae3cc651bcef615c6 | src/moves.ts | src/moves.ts | export function getMoves(grid: boolean[]): number[] {
var moves = [];
for(let i=0; i< grid.length; i++) {
if(grid[i] == undefined)
moves.push(i);
}
return moves;
}
| export function getMoves(grid: boolean[]): number[] {
const moves = [];
for(let i=0; i< grid.length; i++) {
if(grid[i] == undefined)
moves.push(i);
}
return moves;
}
| Use const instead of var | Use const instead of var
| TypeScript | mit | artfuldev/tictactoe-ai,artfuldev/tictactoe-ai | ---
+++
@@ -1,5 +1,5 @@
export function getMoves(grid: boolean[]): number[] {
- var moves = [];
+ const moves = [];
for(let i=0; i< grid.length; i++) {
if(grid[i] == undefined)
moves.push(i); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.