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 |
|---|---|---|---|---|---|---|---|---|---|---|
dfdeffbc0979ef9edf85f3b98b1f8353c76b2776 | desktop/flipper-ui-core/src/utils/globalErrorHandling.tsx | desktop/flipper-ui-core/src/utils/globalErrorHandling.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
export const startGlobalErrorHandling = () => {
if (typeof window !== 'undefined') {
window.addEventListener('error', (event) => {
console.error('"error" event intercepted:', event.error);
});
window.addEventListener('unhandledrejection', (event) => {
console.error('"unhandledrejection" event intercepted:', event.reason);
});
}
};
| /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
export const startGlobalErrorHandling = () => {
if (typeof window !== 'undefined') {
window.onerror = (event) => {
console.error('"onerror" event intercepted:', event);
};
window.onunhandledrejection = (event) => {
console.error('"unhandledrejection" event intercepted:', event.reason);
};
}
};
| Use event handlers instead of listeners for error handing | Use event handlers instead of listeners for error handing
Summary:
^
Adding listeners was correctly intercepting events but the event object often lacked the information necessary to correctly triage and fix an issue.
I discovered that by subscribing to these events directly, the event object did have the required information.
Changelog: Use global window event handlers instead of listeners
Reviewed By: antonk52
Differential Revision: D39809292
fbshipit-source-id: 8a0fc7b7cd86ea16e40f2dc383bc30364f6fc16c
| TypeScript | mit | facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper | ---
+++
@@ -9,11 +9,11 @@
export const startGlobalErrorHandling = () => {
if (typeof window !== 'undefined') {
- window.addEventListener('error', (event) => {
- console.error('"error" event intercepted:', event.error);
- });
- window.addEventListener('unhandledrejection', (event) => {
+ window.onerror = (event) => {
+ console.error('"onerror" event intercepted:', event);
+ };
+ window.onunhandledrejection = (event) => {
console.error('"unhandledrejection" event intercepted:', event.reason);
- });
+ };
}
}; |
21e51a8f1ce738f0976f02a5f5527443e6630213 | src/plugins/reynir/lmgtfy/lmgtfy.ts | src/plugins/reynir/lmgtfy/lmgtfy.ts | export class Plugin {
bot: any;
commands: any;
constructor(bot : any) {
this.bot = bot;
this.commands = {
'lmgtfy': 'onCommandLmgtfy'
};
this.querystring = require('querystring');
}
onCommandLmgtfy(from: string, to: string, message: string, args: Array<string>) {
if (args.length < 2) {
return this.usage(from, to);
}
var query = this.querystring.stringify({ q : args.splice(1).join(' ') });
this.bot.reply(from, to, 'http://lmgtfy.com/?'+query);
}
usage(from: string, to:string) {
this.bot.reply(from, to, 'Usage: .lmgtfy How is babby formed');
}
}
| export class Plugin {
bot: any;
commands: any;
constructor(bot : any) {
this.bot = bot;
this.commands = {
'lmgtfy': 'onCommandLmgtfy'
};
this.querystring = require('querystring');
}
onCommandLmgtfy(from: string, to: string, message: string, args: Array<string>) {
if (args.length < 2) {
return this.usage(from, to);
}
var query = this.querystring.stringify({ q : args.splice(1).join(' ') });
this.bot.reply(from, to, 'http://lmgtfy.com/?'+query);
}
usage(from: string, to:string) {
this.bot.reply(from, to, 'Usage: .lmgtfy <query>', 'notice');
}
}
| Send usage as a notice | Send usage as a notice
| TypeScript | bsd-3-clause | modubot/modubot.js,modubot/modubot.js | ---
+++
@@ -19,6 +19,6 @@
}
usage(from: string, to:string) {
- this.bot.reply(from, to, 'Usage: .lmgtfy How is babby formed');
+ this.bot.reply(from, to, 'Usage: .lmgtfy <query>', 'notice');
}
} |
c630b42e4b52bb2012d10be381161fc82923f4c1 | src/com/mendix/widget/carousel/components/CarouselItem.ts | src/com/mendix/widget/carousel/components/CarouselItem.ts | import { DOM } from "react";
interface CarouselItemProps {
imageUrl: string;
active?: boolean;
}
export const CarouselItem = (props: CarouselItemProps) => {
return (
DOM.div({ className: props.active ? "item active" : "item" },
DOM.img({ alt: "item", height: 300, src: props.imageUrl, width: 900 })
)
);
};
| import { DOM } from "react";
export interface CarouselItemProps {
imageUrl: string;
active?: boolean;
}
export const CarouselItem = (props: CarouselItemProps) => {
return (
DOM.div({ className: props.active ? "item active" : "item" },
DOM.img({ alt: "item", src: props.imageUrl })
)
);
};
| Remove hardcoded carousel image dimensions | Remove hardcoded carousel image dimensions
| TypeScript | apache-2.0 | mendixlabs/carousel,FlockOfBirds/carousel,mendixlabs/carousel,FlockOfBirds/carousel | ---
+++
@@ -1,6 +1,6 @@
import { DOM } from "react";
-interface CarouselItemProps {
+export interface CarouselItemProps {
imageUrl: string;
active?: boolean;
}
@@ -8,7 +8,7 @@
export const CarouselItem = (props: CarouselItemProps) => {
return (
DOM.div({ className: props.active ? "item active" : "item" },
- DOM.img({ alt: "item", height: 300, src: props.imageUrl, width: 900 })
+ DOM.img({ alt: "item", src: props.imageUrl })
)
);
}; |
4de765e4895fecd2e8df919776c0dc061d001d87 | csComp/services/layer/sources/WmsSource.ts | csComp/services/layer/sources/WmsSource.ts | module csComp.Services {
'use strict';
export class WmsSource implements ILayerSource
{
title = "wms";
service : LayerService;
init(service : LayerService){
this.service = service;
}
public addLayer(layer : ProjectLayer, callback : Function)
{
var wms : any = L.tileLayer.wms(layer.url, {
layers : layer.wmsLayers,
opacity : layer.opacity/100,
format : 'image/png',
transparent: true,
attribution: layer.description
});
callback(layer);
//this.$rootScope.$apply();
}
removeLayer(layer : ProjectLayer)
{
}
}
}
| module csComp.Services {
'use strict';
export class WmsSource implements ILayerSource
{
title = "wms";
service : LayerService;
init(service : LayerService){
this.service = service;
}
public addLayer(layer : ProjectLayer, callback : Function)
{
var wms : any = L.tileLayer.wms(layer.url, {
layers : layer.wmsLayers,
opacity : layer.opacity/100,
format : 'image/png',
transparent: true,
attribution: layer.description
});
layer.layerRenderer = "wms";
callback(layer);
//this.$rootScope.$apply();
}
removeLayer(layer : ProjectLayer)
{
}
}
}
| Fix for showing wms layers | Fix for showing wms layers
| TypeScript | mit | mkuzak/csWeb,mkuzak/csWeb,Maartenvm/csWeb,Maartenvm/csWeb,mkuzak/csWeb,c-martinez/csWeb,TNOCS/csWeb,TNOCS/csWeb,Maartenvm/csWeb,indodutch/csWeb,c-martinez/csWeb,mkuzak/csWeb,Maartenvm/csWeb,TNOCS/csWeb,c-martinez/csWeb,indodutch/csWeb,indodutch/csWeb | ---
+++
@@ -18,8 +18,8 @@
format : 'image/png',
transparent: true,
attribution: layer.description
- });
-
+ });
+ layer.layerRenderer = "wms";
callback(layer);
//this.$rootScope.$apply();
} |
4beb6ad91235f7c5b1ece4a27b37632daba41fb6 | src/app/item-switch/item.switch.ts | src/app/item-switch/item.switch.ts | export abstract class ItemSwitch<T> {
protected loadMoreItems: Function;
public setLoadMoreItemsCallback(loadMoreItems?: () => Promise<T[]>) {
this.loadMoreItems = loadMoreItems;
}
public showPreviousItem(items: T[]) {
this.showItem(items, -1);
}
public showNextItem(items: T[]) {
this.showItem(items, 1);
}
protected showItem(items: T[], modifier: number): void {
let currentItemIndex = this.getCurrentItemIndex(items);
if (currentItemIndex !== null) {
let nextItemIndex = currentItemIndex + modifier;
if (this.loadMoreItems && this.moreItemsNeeded(items, currentItemIndex,
nextItemIndex)) {
this.loadMoreItems().then(updatedItems => {
this.switchToItem(updatedItems[nextItemIndex]);
});
}
if (nextItemIndex > -1 && nextItemIndex < items.length) {
this.switchToItem(items[nextItemIndex]);
}
}
}
protected abstract getCurrentItemIndex(items: T[]): number;
protected abstract moreItemsNeeded(items: T[], currentItemIndex: number,
nextItemIndex: number): boolean;
protected abstract switchToItem(item: T): void;
}
| export abstract class ItemSwitch<T> {
protected loadMoreItems: Function;
public setLoadMoreItemsCallback(loadMoreItems?: () => Promise<T[]>) {
this.loadMoreItems = loadMoreItems;
}
public showPreviousItem(items: T[]) {
this.showItem(items, -1);
}
public showNextItem(items: T[]) {
this.showItem(items, 1);
}
protected showItem(items: T[], modifier: number): void {
let currentItemIndex = this.getCurrentItemIndex(items);
if (currentItemIndex !== null) {
let nextItemIndex = currentItemIndex + modifier;
if (this.loadMoreItems && this.moreItemsNeeded(items, currentItemIndex,
nextItemIndex)) {
this.loadMoreItems().then(updatedItems => {
this.switchToItem(updatedItems[nextItemIndex]);
}).catch(() => {});
}
if (nextItemIndex > -1 && nextItemIndex < items.length) {
this.switchToItem(items[nextItemIndex]);
}
}
}
protected abstract getCurrentItemIndex(items: T[]): number;
protected abstract moreItemsNeeded(items: T[], currentItemIndex: number,
nextItemIndex: number): boolean;
protected abstract switchToItem(item: T): void;
}
| Handle promise rejection in ItemSwitch | Handle promise rejection in ItemSwitch
| TypeScript | mit | zoehneto/tumblr-reader,zoehneto/tumblr-reader,zoehneto/tumblr-reader | ---
+++
@@ -22,7 +22,7 @@
nextItemIndex)) {
this.loadMoreItems().then(updatedItems => {
this.switchToItem(updatedItems[nextItemIndex]);
- });
+ }).catch(() => {});
}
if (nextItemIndex > -1 && nextItemIndex < items.length) { |
eaaba7ca0b7b4750dfb336d701f3ec7be5960716 | packages/shared/lib/helpers/formValidators.ts | packages/shared/lib/helpers/formValidators.ts | import { c } from 'ttag';
import { validateEmailAddress } from './email';
import { isNumber } from './validators';
export const requiredValidator = (value: any) =>
value === undefined || value === null || value?.trim?.() === '' ? c('Error').t`This field is required` : '';
export const emailValidator = (value: string) => (!validateEmailAddress(value) ? c('Error').t`Email is not valid` : '');
export const numberValidator = (value: string) => (!isNumber(value) ? c('Error').t`Not a valid number` : '');
export const confirmPasswordValidator = (a: string, b: string) => (a !== b ? c('Error').t`Passwords do not match` : '');
| import { c } from 'ttag';
import { validateEmailAddress } from './email';
import { isNumber } from './validators';
export const requiredValidator = (value: any) =>
value === undefined || value === null || value?.trim?.() === '' ? c('Error').t`This field is required` : '';
export const minLengthValidator = (value: string, minimumLength: number) =>
value.length < minimumLength ? c('Error').t`This field requires a minimum of ${minimumLength} characters.` : '';
export const emailValidator = (value: string) => (!validateEmailAddress(value) ? c('Error').t`Email is not valid` : '');
export const numberValidator = (value: string) => (!isNumber(value) ? c('Error').t`Not a valid number` : '');
export const confirmPasswordValidator = (a: string, b: string) => (a !== b ? c('Error').t`Passwords do not match` : '');
export const passwordLengthValidator = (a: string, length = 8) =>
a.length < length ? c('Error').t`Password should have at least ${length} characters` : '';
| Add a minimum password length validator | Add a minimum password length validator
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -4,6 +4,10 @@
export const requiredValidator = (value: any) =>
value === undefined || value === null || value?.trim?.() === '' ? c('Error').t`This field is required` : '';
+export const minLengthValidator = (value: string, minimumLength: number) =>
+ value.length < minimumLength ? c('Error').t`This field requires a minimum of ${minimumLength} characters.` : '';
export const emailValidator = (value: string) => (!validateEmailAddress(value) ? c('Error').t`Email is not valid` : '');
export const numberValidator = (value: string) => (!isNumber(value) ? c('Error').t`Not a valid number` : '');
export const confirmPasswordValidator = (a: string, b: string) => (a !== b ? c('Error').t`Passwords do not match` : '');
+export const passwordLengthValidator = (a: string, length = 8) =>
+ a.length < length ? c('Error').t`Password should have at least ${length} characters` : ''; |
4bd49b0bf6011f2e0a3694acc2919bd044fa4224 | src/app/shared/components/page.tsx | src/app/shared/components/page.tsx | import { Page as ArgoPage, TopBarProps } from 'argo-ui';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { AppContext } from '../context';
import { services } from '../services';
export class Page extends React.Component<TopBarProps> {
public static contextTypes = {
router: PropTypes.object,
history: PropTypes.object,
};
public render() {
const toolbar = this.props.toolbar || {};
toolbar.tools = [
toolbar.tools,
<a style={{float: 'right', paddingLeft: '1em'}} key='logout' onClick={() => this.logout()}>Logout</a>,
];
return <ArgoPage {...this.props} toolbar={toolbar} />;
}
private async logout() {
await services.userService.logout();
this.appContext.history.push('/login');
}
private get appContext(): AppContext {
return this.context as AppContext;
}
}
| import { Page as ArgoPage, TopBarProps } from 'argo-ui';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { AppContext } from '../context';
import { services } from '../services';
export class Page extends React.Component<TopBarProps> {
public static contextTypes = {
router: PropTypes.object,
history: PropTypes.object,
};
public render() {
const toolbar = this.props.toolbar || {};
toolbar.tools = [
toolbar.tools,
<a style={{position: 'absolute', top: 0, right: '1em'}} key='logout' onClick={() => this.logout()}>Logout</a>,
];
return <ArgoPage {...this.props} toolbar={toolbar} />;
}
private async logout() {
await services.userService.logout();
this.appContext.history.push('/login');
}
private get appContext(): AppContext {
return this.context as AppContext;
}
}
| Move logout button to right top corner | Move logout button to right top corner
| TypeScript | apache-2.0 | argoproj/argo-cd,argoproj/argo-cd,argoproj/argo-cd,argoproj/argo-cd,argoproj/argo-cd | ---
+++
@@ -14,7 +14,7 @@
const toolbar = this.props.toolbar || {};
toolbar.tools = [
toolbar.tools,
- <a style={{float: 'right', paddingLeft: '1em'}} key='logout' onClick={() => this.logout()}>Logout</a>,
+ <a style={{position: 'absolute', top: 0, right: '1em'}} key='logout' onClick={() => this.logout()}>Logout</a>,
];
return <ArgoPage {...this.props} toolbar={toolbar} />;
} |
5d801a639e8f1ae5b89f07ef3c127cd3d0685cd5 | capstone-project/src/main/angular-webapp/src/app/authentication/authentication.component.ts | capstone-project/src/main/angular-webapp/src/app/authentication/authentication.component.ts | import { Component, OnInit } from '@angular/core';
import { SocialAuthService, GoogleLoginProvider, SocialUser } from "angularx-social-login";
import { UserService } from "../user.service";
@Component({
selector: 'app-authentication',
templateUrl: './authentication.component.html',
styleUrls: ['./authentication.component.css']
})
export class AuthenticationComponent implements OnInit {
constructor(private authService: SocialAuthService, private userService: UserService) { }
ngOnInit(): void {
// When user status changes update the user service
this.authService.authState.subscribe((user) => {
this.userService.setUser(user);
});
}
// Sign in user
signInWithGoogle(): void {
this.authService.signIn(GoogleLoginProvider.PROVIDER_ID);
window.location.reload();
}
// Sign out user and reload page
signOut(): void {
this.authService.signOut();
window.location.reload();
}
// Return the current user
get user(): SocialUser {
return this.userService.getUser();
}
}
| import { Component, OnInit } from '@angular/core';
import { SocialAuthService, GoogleLoginProvider, SocialUser } from "angularx-social-login";
import { UserService } from "../user.service";
@Component({
selector: 'app-authentication',
templateUrl: './authentication.component.html',
styleUrls: ['./authentication.component.css']
})
export class AuthenticationComponent implements OnInit {
constructor(private authService: SocialAuthService, private userService: UserService) { }
ngOnInit(): void {
// When user status changes update the user service
this.authService.authState.subscribe((user) => {
this.userService.setUser(user);
});
}
// Sign in user
signInWithGoogle(): void {
this.authService.signIn(GoogleLoginProvider.PROVIDER_ID);
}
// Sign out user and reload page
signOut(): void {
this.authService.signOut();
window.location.reload();
}
// Return the current user
get user(): SocialUser {
return this.userService.getUser();
}
}
| Remove reload after sign in | Remove reload after sign in
| TypeScript | apache-2.0 | googleinterns/step263-2020,googleinterns/step263-2020,googleinterns/step263-2020,googleinterns/step263-2020 | ---
+++
@@ -21,7 +21,6 @@
// Sign in user
signInWithGoogle(): void {
this.authService.signIn(GoogleLoginProvider.PROVIDER_ID);
- window.location.reload();
}
// Sign out user and reload page |
6ba508d38a4c16bac3450f942cbf55e030c0b471 | ui/simul/src/view/util.ts | ui/simul/src/view/util.ts | import { h } from 'snabbdom';
import { Player } from '../interfaces';
import SimulCtrl from '../ctrl';
export function player(p: Player, ctrl: SimulCtrl) {
return h(
'a.ulpt.user-link.' + p.online ? 'online' : 'offline',
{
attrs: { href: '/@/' + p.name },
hook: {
destroy(vnode) {
$.powerTip.destroy(vnode.elm as HTMLElement);
},
},
},
[
h(`i.line${p.patron ? '.patron' : ''}`),
h('span.name', userName(p)),
ctrl.opts.showRatings ? h('em', ` ${p.rating}${p.provisional ? '?' : ''}`) : null,
]
);
}
const userName = (u: LightUser) => (u.title ? [h('span.utitle', u.title), ' ' + u.name] : [u.name]);
export const title = (ctrl: SimulCtrl) =>
h('h1', [ctrl.data.fullName, h('br'), h('span.author', ctrl.trans.vdom('by', player(ctrl.data.host, ctrl)))]);
| import { h } from 'snabbdom';
import { Player } from '../interfaces';
import SimulCtrl from '../ctrl';
export function player(p: Player, ctrl: SimulCtrl) {
return h(
'a.ulpt.user-link.' + (p.online ? 'online' : 'offline'),
{
attrs: { href: '/@/' + p.name },
hook: {
destroy(vnode) {
$.powerTip.destroy(vnode.elm as HTMLElement);
},
},
},
[
h(`i.line${p.patron ? '.patron' : ''}`),
h('span.name', userName(p)),
ctrl.opts.showRatings ? h('em', ` ${p.rating}${p.provisional ? '?' : ''}`) : null,
]
);
}
const userName = (u: LightUser) => (u.title ? [h('span.utitle', u.title), ' ' + u.name] : [u.name]);
export const title = (ctrl: SimulCtrl) =>
h('h1', [ctrl.data.fullName, h('br'), h('span.author', ctrl.trans.vdom('by', player(ctrl.data.host, ctrl)))]);
| Fix bug concerning ternary operator and simul host status | Fix bug concerning ternary operator and simul host status
| TypeScript | agpl-3.0 | arex1337/lila,arex1337/lila,arex1337/lila,arex1337/lila,arex1337/lila,arex1337/lila,arex1337/lila | ---
+++
@@ -4,7 +4,7 @@
export function player(p: Player, ctrl: SimulCtrl) {
return h(
- 'a.ulpt.user-link.' + p.online ? 'online' : 'offline',
+ 'a.ulpt.user-link.' + (p.online ? 'online' : 'offline'),
{
attrs: { href: '/@/' + p.name },
hook: { |
203ff24f95c869050325f4404ad2c9b683bd034c | mehuge/mehuge-events.ts | mehuge/mehuge-events.ts | /// <reference path="../cu/cu.ts" />
module MehugeEvents {
var subscribers: any = {};
var listener;
export function sub(topic: string, handler: (...data: any[]) => void) {
var subs = subscribers[topic] = subscribers[topic] || { listeners: [] };
subs.listeners.push({ listener: handler });
// first handler for any topic? Register event handler
if (!listener) {
cuAPI.OnEvent(listener = function (topic: string, ...data: any[]) {
var listeners = subscribers[topic].listeners, parsedData;
for (var i = 0; i < listeners.length; i++) {
if (listeners[i].listener) {
listeners[i].listener(topic, data);
}
}
});
}
// first handler for this topic, ask client to send these events
if (subs.listeners.length === 1) {
cuAPI.Listen(topic);
}
}
export function unsub(topic: string) {
cuAPI.Ignore(topic);
}
export function pub(topic: string, ...data: any[]) {
cuAPI.Fire(topic, data);
}
} | /// <reference path="../cu/cu.ts" />
module MehugeEvents {
var subscribers: any = {};
var listener;
export function sub(topic: string, handler: (...data: any[]) => void) {
var subs = subscribers[topic] = subscribers[topic] || { listeners: [] };
subs.listeners.push({ listener: handler });
// first handler for any topic? Register event handler
if (!listener) {
cuAPI.OnEvent(listener = function (topic: string, ...data: any[]) {
var listeners = subscribers[topic].listeners, parsedData;
for (var i = 0; i < listeners.length; i++) {
if (listeners[i].listener) {
listeners[i].listener(topic, data);
}
}
});
}
// first handler for this topic, ask client to send these events
if (subs.listeners.length === 1) {
cuAPI.Listen(topic);
}
}
export function unsub(topic: string) {
cuAPI.Ignore(topic);
}
export function pub(topic: string, ...data: any[]) {
cuAPI.Fire(topic, data);
}
// fire/onevent/ignore aliases (work exactly like pub/sub/unsub)
export var fire = pub;
export var onevent = sub;
export var ignore = unsub;
} | Add fire/onevent/ignore aliases for pub/sub/unsub | Add fire/onevent/ignore aliases for pub/sub/unsub
| TypeScript | mpl-2.0 | Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy | ---
+++
@@ -32,4 +32,9 @@
export function pub(topic: string, ...data: any[]) {
cuAPI.Fire(topic, data);
}
+
+ // fire/onevent/ignore aliases (work exactly like pub/sub/unsub)
+ export var fire = pub;
+ export var onevent = sub;
+ export var ignore = unsub;
} |
cdf799a958ba572ddd14706a6753d161b8e95c04 | src/app/components/post-components/post-chat/post-chat.component.ts | src/app/components/post-components/post-chat/post-chat.component.ts | import { Component, Input } from '@angular/core';
import { Post } from '../../../data.types';
@Component({
selector: 'post-chat',
template: `
<p *ngFor="let message of post.dialogue">
<span class="label">{{message.label}}</span> {{message.phrase}}
</p>
`,
styleUrls: ['./post-chat.component.scss']
})
export class PostChatComponent {
@Input('post') post: Post;
}
| import { Component, Input } from '@angular/core';
import { Post } from '../../../data.types';
@Component({
selector: 'post-chat',
template: `
<p *ngFor="let message of post.dialogue">
<span class="label" [innerHTML]="message.label"></span>
<span [innerHTML]="message.phrase"></span>
</p>
`,
styleUrls: ['./post-chat.component.scss']
})
export class PostChatComponent {
@Input('post') post: Post;
}
| Support html for post type chat | Support html for post type chat
| TypeScript | mit | zoehneto/tumblr-reader,zoehneto/tumblr-reader,zoehneto/tumblr-reader | ---
+++
@@ -5,7 +5,8 @@
selector: 'post-chat',
template: `
<p *ngFor="let message of post.dialogue">
- <span class="label">{{message.label}}</span> {{message.phrase}}
+ <span class="label" [innerHTML]="message.label"></span>
+ <span [innerHTML]="message.phrase"></span>
</p>
`,
styleUrls: ['./post-chat.component.scss'] |
3a751b3f77d98672eaaec7eb90d1d346df308459 | test/tests/Import.ts | test/tests/Import.ts | import * as localBower from 'local-bower';
import * as Types from 'local-bower/lib/Types';
describe("module", function() {
describe("'local-bower'", function() {
it("should be a function", function() {
expect(typeof require('local-bower')).toBe('function');
});
});
describe("'local-bower/lib/Types'", function() {
it("should be an object", function() {
expect(typeof require('local-bower/lib/Types')).toBe('object');
});
});
});
| describe("module", function() {
describe("'local-bower'", function() {
it("should be a function", function() {
expect(typeof require('local-bower')).toBe('function');
});
});
describe("'local-bower/lib/Types'", function() {
it("should be an object", function() {
expect(typeof require('local-bower/lib/Types')).toBe('object');
});
});
});
| Remove imports from module tests | Remove imports from module tests
| TypeScript | mit | MortenHoustonLudvigsen/local-bower,MortenHoustonLudvigsen/local-bower | ---
+++
@@ -1,6 +1,3 @@
-import * as localBower from 'local-bower';
-import * as Types from 'local-bower/lib/Types';
-
describe("module", function() {
describe("'local-bower'", function() {
it("should be a function", function() { |
5dc943feb92fbae1e43750d3000717135898a0a5 | src/sdkVersion.ts | src/sdkVersion.ts | import semver from 'semver';
import packageVersionConst from './packageVersion.const';
export default function sdkVersion(toolchainVersion = packageVersionConst) {
const version = semver.parse(toolchainVersion);
if (version === null) {
throw new Error(`Invalid SDK package version: ${toolchainVersion}`);
}
// SDK versions do not have a patch or prerelease. Strip them out.
version.patch = 0;
version.prerelease = [];
version.format(); // Side effect: updates the version.version property.
return version;
}
export function apiVersions(
{ enableProposedAPI }: { enableProposedAPI?: boolean } = {},
toolchainVersion = packageVersionConst,
) {
if (enableProposedAPI) return { deviceApi: '*', companionApi: '*' };
const { major, minor } = sdkVersion(toolchainVersion);
if (major === 1 && minor === 0) {
return { deviceApi: '1.0.0', companionApi: '1.0.0' };
}
if (major === 2 && minor === 0) {
return { deviceApi: '3.0.0', companionApi: '2.0.0' };
}
if (major === 3 && minor === 0) {
return { deviceApi: '4.0.0', companionApi: '2.1.0' };
}
throw new Error(
`No known API versions for SDK package version ${major}.${minor}`,
);
}
| import semver from 'semver';
import packageVersionConst from './packageVersion.const';
export default function sdkVersion(toolchainVersion = packageVersionConst) {
const version = semver.parse(toolchainVersion);
if (version === null) {
throw new Error(`Invalid SDK package version: ${toolchainVersion}`);
}
// SDK versions do not have a patch or prerelease. Strip them out.
version.patch = 0;
version.prerelease = [];
version.format(); // Side effect: updates the version.version property.
return version;
}
export function apiVersions(
{ enableProposedAPI }: { enableProposedAPI?: boolean } = {},
toolchainVersion = packageVersionConst,
) {
if (enableProposedAPI) return { deviceApi: '*', companionApi: '*' };
const { major, minor } = sdkVersion(toolchainVersion);
if (major === 1 && minor === 0) {
return { deviceApi: '1.0.0', companionApi: '1.0.0' };
}
if (major === 2 && minor === 0) {
return { deviceApi: '3.0.0', companionApi: '2.0.0' };
}
if (major === 3 && minor === 0) {
return { deviceApi: '4.0.0', companionApi: '2.1.0' };
}
if (major === 3 && minor === 1) {
return { deviceApi: '4.0.0', companionApi: '2.1.0' };
}
throw new Error(
`No known API versions for SDK package version ${major}.${minor}`,
);
}
| Add SDK 3.1 version target | Add SDK 3.1 version target
Signed-off-by: Liam McLoughlin <a63c1d66dbd75d3cc434e11bdf376be6f9ff043b@fitbit.com>
| TypeScript | bsd-3-clause | Fitbit/fitbit-sdk-toolchain,Fitbit/fitbit-sdk-toolchain | ---
+++
@@ -30,6 +30,9 @@
if (major === 3 && minor === 0) {
return { deviceApi: '4.0.0', companionApi: '2.1.0' };
}
+ if (major === 3 && minor === 1) {
+ return { deviceApi: '4.0.0', companionApi: '2.1.0' };
+ }
throw new Error(
`No known API versions for SDK package version ${major}.${minor}`,
); |
e8ecd5d6436f8fae6f7d5cdba39b41c366659842 | resources/assets/lib/beatmap-discussions/markdown-embed-tokenizer.ts | resources/assets/lib/beatmap-discussions/markdown-embed-tokenizer.ts | import * as remarkParse from 'remark-parse';
function embedTokenizer() {
function locator(value: string, fromIndex: number) {
return value.indexOf('%[', fromIndex);
}
function inlineTokenizer(eat: remarkParse.Eat, value: string, silent: true): boolean | void {
// Custom Markdown to Embed a Discussion
// e.g. given a discussion_id of 123: %[](#123)
const regex = new RegExp(/%\[\]\(#(\d+)\)\n*/);
const result = regex.exec(value);
if (silent) {
return silent;
}
if (!result || result.index !== 0) {
return;
}
const [matched, embed, reference] = result;
return eat(matched)({
children: [
{type: 'text', value: embed},
],
data: {
discussion_id: embed,
},
reference,
type: 'embed',
});
}
const Parser = this.Parser;
const inlineTokenizers = Parser.prototype.inlineTokenizers;
const inlineMethods = Parser.prototype.inlineMethods;
// Inject inlineTokenizer
inlineTokenizer.locator = locator;
inlineTokenizers.embed = inlineTokenizer;
inlineMethods.splice(0, 0, 'embed');
}
module.exports = embedTokenizer;
| import { Eat } from 'remark-parse';
import { Node } from 'unist';
function embedTokenizer() {
function locator(value: string, fromIndex: number) {
return value.indexOf('%[', fromIndex);
}
function inlineTokenizer(eat: Eat, value: string, silent?: true): Node | boolean | void {
// Custom Markdown to Embed a Discussion
// e.g. given a discussion_id of 123: %[](#123)
const regex = new RegExp(/%\[\]\(#(\d+)\)\n*/);
const result = regex.exec(value);
if (silent) {
return true;
}
if (!result || result.index !== 0) {
return;
}
const [matched, embed, reference] = result;
return eat(matched)({
children: [
{type: 'text', value: embed},
],
data: {
discussion_id: embed,
},
reference,
type: 'embed',
});
}
// Ideally 'Parser' here should be typed like Parser from 'remark-parse', but the provided types appear wonky --
// they causes issues with the inlineTokenizer definition below, so we're gonna leave it as an implicit 'any' for now.
const Parser = this.Parser;
const inlineTokenizers = Parser.prototype.inlineTokenizers;
const inlineMethods = Parser.prototype.inlineMethods;
// Inject inlineTokenizer
inlineTokenizer.locator = locator;
inlineTokenizers.embed = inlineTokenizer;
inlineMethods.unshift('embed');
}
module.exports = embedTokenizer;
| Clean up tokenizer a bit | Clean up tokenizer a bit
| TypeScript | agpl-3.0 | LiquidPL/osu-web,omkelderman/osu-web,LiquidPL/osu-web,ppy/osu-web,nanaya/osu-web,notbakaneko/osu-web,omkelderman/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,nanaya/osu-web,LiquidPL/osu-web,ppy/osu-web,nekodex/osu-web,notbakaneko/osu-web,nekodex/osu-web,omkelderman/osu-web,notbakaneko/osu-web,nekodex/osu-web,omkelderman/osu-web,nanaya/osu-web,ppy/osu-web,LiquidPL/osu-web,ppy/osu-web,nekodex/osu-web,nekodex/osu-web,nanaya/osu-web,ppy/osu-web,nanaya/osu-web | ---
+++
@@ -1,18 +1,19 @@
-import * as remarkParse from 'remark-parse';
+import { Eat } from 'remark-parse';
+import { Node } from 'unist';
function embedTokenizer() {
function locator(value: string, fromIndex: number) {
return value.indexOf('%[', fromIndex);
}
- function inlineTokenizer(eat: remarkParse.Eat, value: string, silent: true): boolean | void {
+ function inlineTokenizer(eat: Eat, value: string, silent?: true): Node | boolean | void {
// Custom Markdown to Embed a Discussion
// e.g. given a discussion_id of 123: %[](#123)
const regex = new RegExp(/%\[\]\(#(\d+)\)\n*/);
const result = regex.exec(value);
if (silent) {
- return silent;
+ return true;
}
if (!result || result.index !== 0) {
@@ -33,6 +34,8 @@
});
}
+ // Ideally 'Parser' here should be typed like Parser from 'remark-parse', but the provided types appear wonky --
+ // they causes issues with the inlineTokenizer definition below, so we're gonna leave it as an implicit 'any' for now.
const Parser = this.Parser;
const inlineTokenizers = Parser.prototype.inlineTokenizers;
const inlineMethods = Parser.prototype.inlineMethods;
@@ -40,7 +43,7 @@
// Inject inlineTokenizer
inlineTokenizer.locator = locator;
inlineTokenizers.embed = inlineTokenizer;
- inlineMethods.splice(0, 0, 'embed');
+ inlineMethods.unshift('embed');
}
module.exports = embedTokenizer; |
55288757a2e5d0401350e94fa182c59bbe0c358c | client/local-storage.ts | client/local-storage.ts | import logger from './logging/logger'
// TODO(tec27): Move this to a more common location
export class JsonLocalStorageValue<T> {
constructor(readonly name: string) {}
/**
* Retrieves the current `localStorage` value (parsed as JSON).
* @returns the parsed value, or `undefined` if it isn't set or fails to parse.
*/
getValue(): T | undefined {
const valueJson = localStorage.getItem(this.name)
if (valueJson === null) {
return undefined
}
try {
return JSON.parse(valueJson)
} catch (err) {
logger.error(`error parsing value for ${this.name}: ${(err as any).stack ?? err}`)
return undefined
}
}
/**
* Sets the current `localStorage` value, encoding it as JSON.
*/
setValue(value: T): void {
localStorage.setItem(this.name, JSON.stringify(value))
}
/**
* Clears (unsets) the current `localStorage` value.
*/
clear(): void {
localStorage.removeItem(this.name)
}
}
| import logger from './logging/logger'
/**
* A manager for a JSON value stored in local storage. Provides easy methods to set and retrieve
* the value (if any), doing the necessary parsing/encoding.
*/
export class JsonLocalStorageValue<T> {
constructor(readonly name: string) {}
/**
* Retrieves the current `localStorage` value (parsed as JSON).
* @returns the parsed value, or `undefined` if it isn't set or fails to parse.
*/
getValue(): T | undefined {
const valueJson = localStorage.getItem(this.name)
if (valueJson === null) {
return undefined
}
try {
return JSON.parse(valueJson)
} catch (err) {
logger.error(`error parsing value for ${this.name}: ${(err as any).stack ?? err}`)
return undefined
}
}
/**
* Sets the current `localStorage` value, encoding it as JSON.
*/
setValue(value: T): void {
localStorage.setItem(this.name, JSON.stringify(value))
}
/**
* Clears (unsets) the current `localStorage` value.
*/
clear(): void {
localStorage.removeItem(this.name)
}
}
| Replace a TODO that is now done with a doc comment instead :) | Replace a TODO that is now done with a doc comment instead :)
| TypeScript | mit | ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery | ---
+++
@@ -1,6 +1,9 @@
import logger from './logging/logger'
-// TODO(tec27): Move this to a more common location
+/**
+ * A manager for a JSON value stored in local storage. Provides easy methods to set and retrieve
+ * the value (if any), doing the necessary parsing/encoding.
+ */
export class JsonLocalStorageValue<T> {
constructor(readonly name: string) {}
|
95c025a56f6f9368ad420ab19d9f72cba3ee4550 | src/application/commands/index.ts | src/application/commands/index.ts | import RentMovieCommandHandler from './RentMovieCommandHandler';
import AddMovieCommandHandler from './AddMovieCommandHandler';
export {
RentMovieCommandHandler,
AddMovieCommandHandler,
};
| import AddCustomerCommandHandler from './AddCustomerCommandHandler';
import AddMovieCommandHandler from './AddMovieCommandHandler';
import AddOrderCommandHandler from './AddOrderCommandHandler';
import RentMovieCommandHandler from './RentMovieCommandHandler';
export {
AddCustomerCommandHandler,
AddMovieCommandHandler,
AddOrderCommandHandler,
RentMovieCommandHandler,
};
| Add command handlers to bus | Add command handlers to bus
| TypeScript | mit | MarcAtrapalo/webflix-js-ports-adapters,MarcAtrapalo/webflix-js-ports-adapters | ---
+++
@@ -1,7 +1,11 @@
+import AddCustomerCommandHandler from './AddCustomerCommandHandler';
+import AddMovieCommandHandler from './AddMovieCommandHandler';
+import AddOrderCommandHandler from './AddOrderCommandHandler';
import RentMovieCommandHandler from './RentMovieCommandHandler';
-import AddMovieCommandHandler from './AddMovieCommandHandler';
export {
+ AddCustomerCommandHandler,
+ AddMovieCommandHandler,
+ AddOrderCommandHandler,
RentMovieCommandHandler,
- AddMovieCommandHandler,
}; |
c0bde6af9224a47d4f0b3a9f9e5f5738d8a9877b | src/app/models/add-tab-button.ts | src/app/models/add-tab-button.ts | import { TweenLite } from 'gsap';
// Constants and defaults
import { TOOLBAR_BUTTON_WIDTH } from '../constants/design';
import tabAnimations from '../defaults/tab-animations';
import Store from '../store';
export default class AddTabButton {
public left: number | 'auto' = 0;
public ref: HTMLDivElement;
public updateLeft(left: number, animation = true) {
const containerWidth = Store.getTabBarWidth();
if (left >= containerWidth - TOOLBAR_BUTTON_WIDTH) {
if (this.left !== 'auto') {
if (animation) {
this.setLeft(containerWidth - TOOLBAR_BUTTON_WIDTH, true);
setTimeout(() => {
this.setLeft('auto');
}, tabAnimations.left.duration * 1000);
} else {
this.setLeft('auto');
}
}
} else {
if (this.left === 'auto') {
this.setLeft(containerWidth - TOOLBAR_BUTTON_WIDTH, animation);
}
this.setLeft(left, animation);
}
}
public setLeft(left: 'auto' | number, animation = false) {
if (!animation) {
this.ref.style.left = (left === 'auto' ? 'auto' : `${left}px`);
} else {
TweenLite.to(this.ref, tabAnimations.left.duration, {
left,
ease: tabAnimations.left.easing,
});
}
this.left = left;
}
}
| import { TweenLite } from 'gsap';
// Constants and defaults
import { TOOLBAR_BUTTON_WIDTH } from '../constants/design';
import tabAnimations from '../defaults/tab-animations';
import Store from '../store';
export default class AddTabButton {
public left: number | 'auto' = 0;
public ref: HTMLDivElement;
public updateLeft(left: number, animation = true) {
const containerWidth = Store.getTabBarWidth();
if (left >= containerWidth - TOOLBAR_BUTTON_WIDTH) {
if (this.left !== 'auto') {
if (animation) {
this.setLeft(containerWidth - TOOLBAR_BUTTON_WIDTH, true);
setTimeout(() => {
this.setLeft('auto');
}, tabAnimations.left.duration * 1000);
} else {
this.setLeft('auto');
}
}
} else {
if (this.left === 'auto') {
this.setLeft(containerWidth - TOOLBAR_BUTTON_WIDTH, animation);
}
this.setLeft(left, animation);
}
}
public setLeft(left: 'auto' | number, animation = false) {
if (!animation) {
TweenLite.to(this.ref, 0, {
left,
});
} else {
TweenLite.to(this.ref, tabAnimations.left.duration, {
left,
ease: tabAnimations.left.easing,
});
}
this.left = left;
}
}
| Fix add tab button positioning | :bug: Fix add tab button positioning
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -35,7 +35,9 @@
public setLeft(left: 'auto' | number, animation = false) {
if (!animation) {
- this.ref.style.left = (left === 'auto' ? 'auto' : `${left}px`);
+ TweenLite.to(this.ref, 0, {
+ left,
+ });
} else {
TweenLite.to(this.ref, tabAnimations.left.duration, {
left, |
64eccdfcb734df89956a8b3db75d9aa0c185f88f | assertsharp/assertsharp.d.ts | assertsharp/assertsharp.d.ts | // Type definitions for assertsharp
// Project: https://www.npmjs.com/package/assertsharp
// Definitions by: Bruno Leonardo Michels <https://github.com/brunolm>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "assertsharp" {
export default class Assert {
static AreEqual<T>(expected: T, actual: T, message?: string): void;
static AreNotEqual<T>(notExpected: T, actual: T, message?: string): void;
static AreNotSame<T>(notExpected: T, actual: T, message?: string): void;
static AreSequenceEqual<T>(expected: T[], actual: T[], equals?: (x, y) => boolean, message?: string): void;
static Fail(message?: string): void;
static IsFalse(actual: boolean, message?: string): void;
static IsInstanceOfType(actual: any, expectedType: Function, message?: string): void;
static IsNotInstanceOfType(actual: any, wrongType: Function, message?: string): void;
static IsNotNull(actual: any, message?: string): void;
static IsNull(actual: any, message?: string): void;
static IsTrue(actual: boolean, message?: string): void;
static Throws(fn: () => void, message?: string): void;
}
}
| // Type definitions for assertsharp
// Project: https://www.npmjs.com/package/assertsharp
// Definitions by: Bruno Leonardo Michels <https://github.com/brunolm>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "assertsharp" {
export default class Assert {
static AreEqual<T>(expected: T, actual: T, message?: string): void;
static AreNotEqual<T>(notExpected: T, actual: T, message?: string): void;
static AreNotSame<T>(notExpected: T, actual: T, message?: string): void;
static AreSequenceEqual<T>(expected: T[], actual: T[], equals?: (x: any, y: any) => boolean, message?: string): void;
static Fail(message?: string): void;
static IsFalse(actual: boolean, message?: string): void;
static IsInstanceOfType(actual: any, expectedType: Function, message?: string): void;
static IsNotInstanceOfType(actual: any, wrongType: Function, message?: string): void;
static IsNotNull(actual: any, message?: string): void;
static IsNull(actual: any, message?: string): void;
static IsTrue(actual: boolean, message?: string): void;
static Throws(fn: () => void, message?: string): void;
}
}
| Fix implicit types on assertsharp | Fix implicit types on assertsharp
| TypeScript | mit | hellopao/DefinitelyTyped,vagarenko/DefinitelyTyped,Syati/DefinitelyTyped,ryan10132/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,elisee/DefinitelyTyped,drinchev/DefinitelyTyped,gcastre/DefinitelyTyped,rcchen/DefinitelyTyped,bdoss/DefinitelyTyped,olemp/DefinitelyTyped,chrootsu/DefinitelyTyped,mjjames/DefinitelyTyped,elisee/DefinitelyTyped,Litee/DefinitelyTyped,daptiv/DefinitelyTyped,reppners/DefinitelyTyped,hatz48/DefinitelyTyped,chrootsu/DefinitelyTyped,onecentlin/DefinitelyTyped,dsebastien/DefinitelyTyped,rschmukler/DefinitelyTyped,herrmanno/DefinitelyTyped,Karabur/DefinitelyTyped,nmalaguti/DefinitelyTyped,use-strict/DefinitelyTyped,pwelter34/DefinitelyTyped,bdoss/DefinitelyTyped,borisyankov/DefinitelyTyped,greglo/DefinitelyTyped,jasonswearingen/DefinitelyTyped,stacktracejs/DefinitelyTyped,mhegazy/DefinitelyTyped,YousefED/DefinitelyTyped,nainslie/DefinitelyTyped,dydek/DefinitelyTyped,fredgalvao/DefinitelyTyped,ajtowf/DefinitelyTyped,smrq/DefinitelyTyped,jsaelhof/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,reppners/DefinitelyTyped,takenet/DefinitelyTyped,OpenMaths/DefinitelyTyped,drinchev/DefinitelyTyped,jimthedev/DefinitelyTyped,progre/DefinitelyTyped,rolandzwaga/DefinitelyTyped,pwelter34/DefinitelyTyped,UzEE/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,yuit/DefinitelyTyped,tan9/DefinitelyTyped,teves-castro/DefinitelyTyped,musicist288/DefinitelyTyped,arusakov/DefinitelyTyped,subash-a/DefinitelyTyped,shlomiassaf/DefinitelyTyped,dydek/DefinitelyTyped,mshmelev/DefinitelyTyped,danfma/DefinitelyTyped,arusakov/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,optical/DefinitelyTyped,Zzzen/DefinitelyTyped,pocesar/DefinitelyTyped,georgemarshall/DefinitelyTyped,paulmorphy/DefinitelyTyped,glenndierckx/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,HPFOD/DefinitelyTyped,mareek/DefinitelyTyped,Zorgatone/DefinitelyTyped,schmuli/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,zuzusik/DefinitelyTyped,emanuelhp/DefinitelyTyped,nitintutlani/DefinitelyTyped,onecentlin/DefinitelyTyped,martinduparc/DefinitelyTyped,EnableSoftware/DefinitelyTyped,shlomiassaf/DefinitelyTyped,alextkachman/DefinitelyTyped,alvarorahul/DefinitelyTyped,sclausen/DefinitelyTyped,rolandzwaga/DefinitelyTyped,flyfishMT/DefinitelyTyped,nainslie/DefinitelyTyped,esperco/DefinitelyTyped,hellopao/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,pocesar/DefinitelyTyped,RX14/DefinitelyTyped,arcticwaters/DefinitelyTyped,donnut/DefinitelyTyped,EnableSoftware/DefinitelyTyped,alexdresko/DefinitelyTyped,Dominator008/DefinitelyTyped,damianog/DefinitelyTyped,jimthedev/DefinitelyTyped,isman-usoh/DefinitelyTyped,abner/DefinitelyTyped,greglo/DefinitelyTyped,AgentME/DefinitelyTyped,mareek/DefinitelyTyped,mattanja/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,subash-a/DefinitelyTyped,trystanclarke/DefinitelyTyped,wilfrem/DefinitelyTyped,alainsahli/DefinitelyTyped,dmoonfire/DefinitelyTyped,mattblang/DefinitelyTyped,martinduparc/DefinitelyTyped,whoeverest/DefinitelyTyped,newclear/DefinitelyTyped,Syati/DefinitelyTyped,jsaelhof/DefinitelyTyped,MugeSo/DefinitelyTyped,borisyankov/DefinitelyTyped,rcchen/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,arcticwaters/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,abbasmhd/DefinitelyTyped,yuit/DefinitelyTyped,benishouga/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,Pro/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,amir-arad/DefinitelyTyped,davidpricedev/DefinitelyTyped,optical/DefinitelyTyped,takenet/DefinitelyTyped,nakakura/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,pocesar/DefinitelyTyped,abner/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,jimthedev/DefinitelyTyped,nitintutlani/DefinitelyTyped,vagarenko/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,magny/DefinitelyTyped,hatz48/DefinitelyTyped,nycdotnet/DefinitelyTyped,mcrawshaw/DefinitelyTyped,Dashlane/DefinitelyTyped,egeland/DefinitelyTyped,psnider/DefinitelyTyped,flyfishMT/DefinitelyTyped,scriby/DefinitelyTyped,egeland/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,jraymakers/DefinitelyTyped,applesaucers/lodash-invokeMap,davidpricedev/DefinitelyTyped,minodisk/DefinitelyTyped,markogresak/DefinitelyTyped,minodisk/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,mhegazy/DefinitelyTyped,philippstucki/DefinitelyTyped,tan9/DefinitelyTyped,Dominator008/DefinitelyTyped,sledorze/DefinitelyTyped,chbrown/DefinitelyTyped,hellopao/DefinitelyTyped,nobuoka/DefinitelyTyped,QuatroCode/DefinitelyTyped,dsebastien/DefinitelyTyped,olemp/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,raijinsetsu/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,arma-gast/DefinitelyTyped,nmalaguti/DefinitelyTyped,amanmahajan7/DefinitelyTyped,magny/DefinitelyTyped,YousefED/DefinitelyTyped,teves-castro/DefinitelyTyped,applesaucers/lodash-invokeMap,smrq/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,psnider/DefinitelyTyped,Zorgatone/DefinitelyTyped,eugenpodaru/DefinitelyTyped,ashwinr/DefinitelyTyped,georgemarshall/DefinitelyTyped,esperco/DefinitelyTyped,psnider/DefinitelyTyped,syuilo/DefinitelyTyped,MugeSo/DefinitelyTyped,zuzusik/DefinitelyTyped,wilfrem/DefinitelyTyped,alextkachman/DefinitelyTyped,HPFOD/DefinitelyTyped,stephenjelfs/DefinitelyTyped,gyohk/DefinitelyTyped,gyohk/DefinitelyTyped,nfriend/DefinitelyTyped,fredgalvao/DefinitelyTyped,scriby/DefinitelyTyped,Pro/DefinitelyTyped,progre/DefinitelyTyped,Litee/DefinitelyTyped,sixinli/DefinitelyTyped,mattblang/DefinitelyTyped,behzad888/DefinitelyTyped,bennett000/DefinitelyTyped,newclear/DefinitelyTyped,frogcjn/DefinitelyTyped,chrismbarr/DefinitelyTyped,arusakov/DefinitelyTyped,chrismbarr/DefinitelyTyped,axelcostaspena/DefinitelyTyped,ajtowf/DefinitelyTyped,damianog/DefinitelyTyped,emanuelhp/DefinitelyTyped,paulmorphy/DefinitelyTyped,UzEE/DefinitelyTyped,Ptival/DefinitelyTyped,danfma/DefinitelyTyped,benishouga/DefinitelyTyped,gandjustas/DefinitelyTyped,frogcjn/DefinitelyTyped,mjjames/DefinitelyTyped,schmuli/DefinitelyTyped,raijinsetsu/DefinitelyTyped,mcrawshaw/DefinitelyTyped,sledorze/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,gandjustas/DefinitelyTyped,abbasmhd/DefinitelyTyped,xStrom/DefinitelyTyped,alvarorahul/DefinitelyTyped,johan-gorter/DefinitelyTyped,syuilo/DefinitelyTyped,Ptival/DefinitelyTyped,Dashlane/DefinitelyTyped,AgentME/DefinitelyTyped,philippstucki/DefinitelyTyped,aciccarello/DefinitelyTyped,donnut/DefinitelyTyped,behzad888/DefinitelyTyped,rschmukler/DefinitelyTyped,bennett000/DefinitelyTyped,aciccarello/DefinitelyTyped,stephenjelfs/DefinitelyTyped,QuatroCode/DefinitelyTyped,gcastre/DefinitelyTyped,georgemarshall/DefinitelyTyped,johan-gorter/DefinitelyTyped,mshmelev/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,amanmahajan7/DefinitelyTyped,RX14/DefinitelyTyped,jasonswearingen/DefinitelyTyped,florentpoujol/DefinitelyTyped,martinduparc/DefinitelyTyped,alexdresko/DefinitelyTyped,arma-gast/DefinitelyTyped,ashwinr/DefinitelyTyped,one-pieces/DefinitelyTyped,isman-usoh/DefinitelyTyped,xStrom/DefinitelyTyped,sclausen/DefinitelyTyped,trystanclarke/DefinitelyTyped,Zzzen/DefinitelyTyped,zuzusik/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,nycdotnet/DefinitelyTyped,Karabur/DefinitelyTyped,aciccarello/DefinitelyTyped,florentpoujol/DefinitelyTyped,jraymakers/DefinitelyTyped,dmoonfire/DefinitelyTyped,Penryn/DefinitelyTyped,mattanja/DefinitelyTyped,micurs/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,schmuli/DefinitelyTyped,use-strict/DefinitelyTyped,benishouga/DefinitelyTyped,OpenMaths/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,benliddicott/DefinitelyTyped,stacktracejs/DefinitelyTyped,Penryn/DefinitelyTyped,nobuoka/DefinitelyTyped,nakakura/DefinitelyTyped,glenndierckx/DefinitelyTyped | ---
+++
@@ -8,7 +8,7 @@
static AreEqual<T>(expected: T, actual: T, message?: string): void;
static AreNotEqual<T>(notExpected: T, actual: T, message?: string): void;
static AreNotSame<T>(notExpected: T, actual: T, message?: string): void;
- static AreSequenceEqual<T>(expected: T[], actual: T[], equals?: (x, y) => boolean, message?: string): void;
+ static AreSequenceEqual<T>(expected: T[], actual: T[], equals?: (x: any, y: any) => boolean, message?: string): void;
static Fail(message?: string): void;
static IsFalse(actual: boolean, message?: string): void;
static IsInstanceOfType(actual: any, expectedType: Function, message?: string): void; |
010c394513f779d12558dc4a4cd6e46eb86f47d5 | src/renderers/canvas/color-pixel/color-pixel-world-renderer.ts | src/renderers/canvas/color-pixel/color-pixel-world-renderer.ts | import Locator from '../../../locator';
import Dimensions from '../../../world/dimensions.type';
import WorldPosition from '../../../world/world-position.type';
import World from '../../../world/world.interface';
import ColorPixelRepresentation from './color-pixel-representation.type';
export default class ColorPixelWorldRenderer {
private context: CanvasRenderingContext2D;
private world: World;
private tileSize: Dimensions;
private resolution: Dimensions;
public constructor(context: CanvasRenderingContext2D, world: World) {
this.context = context;
this.world = world;
this.resolution = Locator.getGameResolution();
this.loadTileSize();
}
public render(): void {
for (const worldObject of this.world.getWorldObjects()) {
const worldObjectPosition: WorldPosition = worldObject.getPosition();
const representation: ColorPixelRepresentation =
worldObject.getRepresentation('ColorPixel') as ColorPixelRepresentation;
this.context.fillStyle = representation.color;
this.context.fillRect(
worldObjectPosition.x * this.tileSize.width,
worldObjectPosition.y * this.tileSize.height,
this.tileSize.width,
this.tileSize.height,
);
}
}
private loadTileSize(): void {
const worldResolution: Dimensions = Locator.getGameResolution();
const worldSize: Dimensions = this.world.getSize();
this.tileSize = {
width: worldResolution.width / worldSize.width,
height: worldResolution.height / worldSize.height,
};
}
}
| import Locator from '../../../locator';
import Dimensions from '../../../world/dimensions.type';
import WorldPosition from '../../../world/world-position.type';
import World from '../../../world/world.interface';
import ColorPixelRepresentation from './color-pixel-representation.type';
export default class ColorPixelWorldRenderer {
private context: CanvasRenderingContext2D;
private world: World;
private tileSize: Dimensions;
private resolution: Dimensions;
public constructor(context: CanvasRenderingContext2D, world: World) {
this.context = context;
this.world = world;
this.resolution = Locator.getGameResolution();
this.loadTileSize();
}
public render(): void {
for (const worldObject of this.world.getWorldObjects()) {
const worldObjectPosition: WorldPosition = worldObject.getPosition();
const representation: ColorPixelRepresentation =
worldObject.getRepresentation('ColorPixel') as ColorPixelRepresentation;
this.context.fillStyle = representation.color;
this.context.fillRect(
Math.floor(worldObjectPosition.x * this.tileSize.width),
Math.floor(worldObjectPosition.y * this.tileSize.height),
Math.ceil(this.tileSize.width),
Math.ceil(this.tileSize.height),
);
}
}
private loadTileSize(): void {
const worldResolution: Dimensions = Locator.getGameResolution();
const worldSize: Dimensions = this.world.getSize();
this.tileSize = {
width: worldResolution.width / worldSize.width,
height: worldResolution.height / worldSize.height,
};
}
}
| Fix unwanted World grid gap when rendering (ColorPixel). | Fix unwanted World grid gap when rendering (ColorPixel).
| TypeScript | isc | kamsac/angleworms-game,kamsac/angleworms-game | ---
+++
@@ -26,10 +26,10 @@
worldObject.getRepresentation('ColorPixel') as ColorPixelRepresentation;
this.context.fillStyle = representation.color;
this.context.fillRect(
- worldObjectPosition.x * this.tileSize.width,
- worldObjectPosition.y * this.tileSize.height,
- this.tileSize.width,
- this.tileSize.height,
+ Math.floor(worldObjectPosition.x * this.tileSize.width),
+ Math.floor(worldObjectPosition.y * this.tileSize.height),
+ Math.ceil(this.tileSize.width),
+ Math.ceil(this.tileSize.height),
);
}
} |
25a0be656025a85ddc0a5bd210cb47765f80aef0 | src/index.ts | src/index.ts | import Btn from './components/Btn'
import Modal from './components/Modal'
export { Btn, Modal }
| import Badge from './components/Badge'
import Btn from './components/Btn'
import Modal from './components/Modal'
export { Badge, Btn, Modal }
| Add Badge to script entry | Add Badge to script entry
| TypeScript | mit | IsaacLean/bolt-ui,IsaacLean/bolt-ui | ---
+++
@@ -1,4 +1,5 @@
+import Badge from './components/Badge'
import Btn from './components/Btn'
import Modal from './components/Modal'
-export { Btn, Modal }
+export { Badge, Btn, Modal } |
44b69fee93cfdea0be7812b8fbd40c1ba6ad521c | src/router/index.ts | src/router/index.ts | import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
export default new Router({
mode: process.env.IS_ELECTRON ? 'hash' : 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'Home',
component: () => import('@/views/AppInfo.vue'),
props: {
includeProjectButtons: true,
},
},
{
path: '/project',
name: 'Project',
component: () => import('@/views/Project.vue'),
},
{
path: '/project/:id',
name: 'ProjectId',
component: () => import('@/views/Project.vue'),
props: true,
},
{
path: '/model',
name: 'Model',
component: () => import('@/views/Model.vue'),
},
{
path: '/model/:id',
name: 'ModelId',
component: () => import('@/views/Model.vue'),
props: true,
},
{
path: '/settings',
name: 'Settings',
component: () => import('@/views/Settings.vue'),
},
{
path: '/about',
name: 'About',
component: () => import('@/views/AppInfo.vue'),
props: {
includeProjectButtons: false,
},
},
],
});
| import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
export default new Router({
mode: 'hash',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'Home',
component: () => import('@/views/AppInfo.vue'),
props: {
includeProjectButtons: true,
},
},
{
path: '/project',
name: 'Project',
component: () => import('@/views/Project.vue'),
},
{
path: '/project/:id',
name: 'ProjectId',
component: () => import('@/views/Project.vue'),
props: true,
},
{
path: '/model',
name: 'Model',
component: () => import('@/views/Model.vue'),
},
{
path: '/model/:id',
name: 'ModelId',
component: () => import('@/views/Model.vue'),
props: true,
},
{
path: '/settings',
name: 'Settings',
component: () => import('@/views/Settings.vue'),
},
{
path: '/about',
name: 'About',
component: () => import('@/views/AppInfo.vue'),
props: {
includeProjectButtons: false,
},
},
],
});
| Use hash for router history | Use hash for router history
| TypeScript | mit | babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop | ---
+++
@@ -4,7 +4,7 @@
Vue.use(Router);
export default new Router({
- mode: process.env.IS_ELECTRON ? 'hash' : 'history',
+ mode: 'hash',
base: process.env.BASE_URL,
routes: [
{ |
9a7ea51be30b0f24cf6f1b452d01c791e6e1b5e4 | src/app/components/broadcast-card/broadcast-card.ts | src/app/components/broadcast-card/broadcast-card.ts | import View from '!view!./broadcast-card.html?style=./broadcast-card.styl';
import { AppCard } from 'game-jolt-frontend-lib/components/card/card';
import { FiresidePost } from 'game-jolt-frontend-lib/components/fireside/post/post-model';
import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';
@View
@Component({
components: {
AppCard,
},
})
export class AppBroadcastCard extends Vue {
@Prop(FiresidePost)
post!: FiresidePost;
}
| import View from '!view!./broadcast-card.html?style=./broadcast-card.styl';
import { AppTrackEvent } from 'game-jolt-frontend-lib/components/analytics/track-event.directive.vue';
import { AppCard } from 'game-jolt-frontend-lib/components/card/card';
import { FiresidePost } from 'game-jolt-frontend-lib/components/fireside/post/post-model';
import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';
@View
@Component({
components: {
AppCard,
},
directives: {
AppTrackEvent,
},
})
export class AppBroadcastCard extends Vue {
@Prop(FiresidePost)
post!: FiresidePost;
}
| Fix track event directive not imported into broadcast card | Fix track event directive not imported into broadcast card
| TypeScript | mit | gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt | ---
+++
@@ -1,4 +1,5 @@
import View from '!view!./broadcast-card.html?style=./broadcast-card.styl';
+import { AppTrackEvent } from 'game-jolt-frontend-lib/components/analytics/track-event.directive.vue';
import { AppCard } from 'game-jolt-frontend-lib/components/card/card';
import { FiresidePost } from 'game-jolt-frontend-lib/components/fireside/post/post-model';
import Vue from 'vue';
@@ -9,6 +10,9 @@
components: {
AppCard,
},
+ directives: {
+ AppTrackEvent,
+ },
})
export class AppBroadcastCard extends Vue {
@Prop(FiresidePost) |
e4dc6c60dbcc968e628c964d36ac5a6472793c3a | functions/utils.ts | functions/utils.ts | import { Request, Response } from "express";
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
const cacheSeconds = 24 * 60 * 60;
const origins = functions.config().cors.origins.split(",");
export function httpsFunction(handler: (request: Request, response: Response) => void | Promise<void>) {
return functions.https.onRequest(
async (request: Request, response: Response) => {
const origin = request.get("Origin");
if (origins.includes(request.get("Origin"))) {
response.set("Access-Control-Allow-Origin", origin);
}
response.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.set("Access-Control-Allow-Headers", "Authorization");
if (request.method === "OPTIONS") {
response.end();
return;
}
await admin.auth().verifyIdToken(request.get("Authorization").split(" ")[1]);
response.set(
"Cache-Control",
`private, max-age=${cacheSeconds}, s-maxage=${cacheSeconds}`);
await handler(request, response);
});
}
| import { Request, Response } from "express";
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
const cacheSeconds = 24 * 60 * 60;
const origins = functions.config().cors.origins.split(",");
export function httpsFunction(handler: (request: Request, response: Response) => void | Promise<void>) {
return functions.https.onRequest(
async (request: Request, response: Response) => {
const origin = request.get("Origin");
if (origins.includes(request.get("Origin"))) {
response.set("Access-Control-Allow-Origin", origin);
}
response.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.set("Access-Control-Allow-Headers", "Authorization");
if (request.method === "OPTIONS") {
response.end();
return;
}
await admin.auth().verifyIdToken(request.get("Authorization").split(" ")[1]);
response.set(
"Cache-Control",
`private, max-age=${cacheSeconds}, s-maxage=${cacheSeconds}`);
try {
await handler(request, response);
} catch (error) {
console.error(error);
response.sendStatus(500);
}
});
}
| Return 500 on error with proper headers | Return 500 on error with proper headers
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -28,6 +28,11 @@
"Cache-Control",
`private, max-age=${cacheSeconds}, s-maxage=${cacheSeconds}`);
- await handler(request, response);
+ try {
+ await handler(request, response);
+ } catch (error) {
+ console.error(error);
+ response.sendStatus(500);
+ }
});
} |
d6cfabce314da408e0f01b261ab7abe92ad228d2 | packages/ag-grid-docs/src/_assets/ts/ag-grid-enterprise-main.ts | packages/ag-grid-docs/src/_assets/ts/ag-grid-enterprise-main.ts | import "../../../../ag-grid-enterprise/src/main.ts";
| import "../../../../ag-grid-enterprise/src/modules/chartsModule.ts";
import "../../../../ag-grid-enterprise/src/main.ts";
| Add charts module to runner | Add charts module to runner
| TypeScript | mit | ceolter/ag-grid,ceolter/ag-grid,ceolter/angular-grid,ceolter/angular-grid | ---
+++
@@ -1 +1,3 @@
+import "../../../../ag-grid-enterprise/src/modules/chartsModule.ts";
+
import "../../../../ag-grid-enterprise/src/main.ts"; |
998d926d40892f56d431e690f8ccdf131723f57d | src/booking/BookingStateField.tsx | src/booking/BookingStateField.tsx | import { FunctionComponent } from 'react';
import { translate } from '@waldur/i18n';
import { ResourceStateField } from '@waldur/marketplace/resources/list/ResourceStateField';
export const bookingStateAliases = (state: string): string => {
switch (state) {
case 'Creating': {
return translate('Unconfirmed');
}
case 'OK': {
return translate('Accepted');
}
case 'Terminated': {
return translate('Rejected');
}
default: {
return state;
}
}
};
export const BookingStateField: FunctionComponent<{ row }> = ({ row }) => (
<ResourceStateField
row={{
...row,
state: bookingStateAliases(row.state),
}}
/>
);
| import { FunctionComponent } from 'react';
import { StateIndicator } from '@waldur/core/StateIndicator';
import { translate } from '@waldur/i18n';
export const bookingStateAliases = (state: string): string => {
switch (state) {
case 'Creating': {
return translate('Unconfirmed');
}
case 'OK': {
return translate('Accepted');
}
case 'Terminated': {
return translate('Rejected');
}
default: {
return state;
}
}
};
export const BookingStateField: FunctionComponent<{ row }> = ({ row }) => {
const state = bookingStateAliases(row.state);
return (
<StateIndicator
label={state}
variant={
state === 'Rejected'
? 'danger'
: state === 'Unconfirmed'
? 'warning'
: 'primary'
}
active={state === 'Unconfirmed'}
/>
);
};
| Use different colors for bookings list states | Use different colors for bookings list states
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -1,7 +1,7 @@
import { FunctionComponent } from 'react';
+import { StateIndicator } from '@waldur/core/StateIndicator';
import { translate } from '@waldur/i18n';
-import { ResourceStateField } from '@waldur/marketplace/resources/list/ResourceStateField';
export const bookingStateAliases = (state: string): string => {
switch (state) {
@@ -20,11 +20,19 @@
}
};
-export const BookingStateField: FunctionComponent<{ row }> = ({ row }) => (
- <ResourceStateField
- row={{
- ...row,
- state: bookingStateAliases(row.state),
- }}
- />
-);
+export const BookingStateField: FunctionComponent<{ row }> = ({ row }) => {
+ const state = bookingStateAliases(row.state);
+ return (
+ <StateIndicator
+ label={state}
+ variant={
+ state === 'Rejected'
+ ? 'danger'
+ : state === 'Unconfirmed'
+ ? 'warning'
+ : 'primary'
+ }
+ active={state === 'Unconfirmed'}
+ />
+ );
+}; |
e195983fc67e44b65201af4cc6d7ce3bf3189f2e | src/app.ts | src/app.ts | import "source-map-support/register";
import log from "fancy-log";
import path from "path";
import process from "process";
try {
// Fallback for Windows backs out of node_modules folder to root of project.
process.env.PWD = process.env.PWD || path.resolve(process.cwd(), "../../");
// Change working directory.
process.chdir(process.env.PWD as string);
} catch (err) {
log.error(`chdir: ${err}`);
}
import TaskFactory from "./modules/task-factory";
// Load all tasks.
const factory: TaskFactory = new TaskFactory();
factory.createAllTasks();
| import "source-map-support/register";
import log from "fancy-log";
import path from "path";
import process from "process";
try {
// Fallback for Windows backs out of node_modules folder to root of project.
process.env.PWD = process.env.PWD || path.resolve(process.cwd(), "../../../");
// Change working directory.
process.chdir(process.env.PWD as string);
} catch (err) {
log.error(`chdir: ${err}`);
}
import TaskFactory from "./modules/task-factory";
// Load all tasks.
const factory: TaskFactory = new TaskFactory();
factory.createAllTasks();
| Fix root directory for Windows | Fix root directory for Windows
| TypeScript | mit | cyrale/gulpfile.js,cyrale/gulpfile.js | ---
+++
@@ -6,7 +6,7 @@
try {
// Fallback for Windows backs out of node_modules folder to root of project.
- process.env.PWD = process.env.PWD || path.resolve(process.cwd(), "../../");
+ process.env.PWD = process.env.PWD || path.resolve(process.cwd(), "../../../");
// Change working directory.
process.chdir(process.env.PWD as string); |
5d589edc46815a0f92802ab04ca3649f81df6a1c | src/app/leaflet/leaflet-button/leaflet-button.component.spec.ts | src/app/leaflet/leaflet-button/leaflet-button.component.spec.ts | /* tslint:disable:no-unused-variable */
/*!
* Leaflet Button Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, fakeAsync, tick, inject } from '@angular/core/testing';
import { LeafletButtonComponent } from './leaflet-button.component';
describe('Component: LeafletButton', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
Renderer,
LeafletButtonComponent
]
}));
it('should create an instance', inject([LeafletButtonComponent], (component: LeafletButtonComponent) => {
expect(component).toBeTruthy();
}));
});
| /* tslint:disable:no-unused-variable */
/*!
* Leaflet Button Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { LeafletButtonComponent } from './leaflet-button.component';
import { TooltipModule } from 'ng2-bootstrap';
describe('Component: LeafletButton', () => {
beforeEach(() => TestBed.configureTestingModule({
declarations: [
LeafletButtonComponent
],
imports: [
TooltipModule.forRoot()
],
providers: [
Renderer,
LeafletButtonComponent
]
}));
it('should create an instance', inject([LeafletButtonComponent], (component: LeafletButtonComponent) => {
expect(component).toBeTruthy();
}));
it('should emit buttonClick', async(inject([LeafletButtonComponent], (component: LeafletButtonComponent) => {
component.buttonClick.subscribe((event: Event) => {
expect(event).toBeTruthy();
});
component.onClick(new Event('click'));
}));
it('should toggle active state', async(() => {
// assemble the component
let fixture = TestBed.createComponent(LeafletButtonComponent);
fixture.detectChanges();
// get the instance of the component
let component: LeafletButtonComponent = fixture.componentInstance;
// trigger toggle of active state
component.toggleActiveState();
expect(component.active).toBe(true);
}));
});
| Add more tests for LeafletButtonComponent | Add more tests for LeafletButtonComponent
| TypeScript | mit | ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps | ---
+++
@@ -8,12 +8,19 @@
*/
import { Renderer } from '@angular/core';
-import { TestBed, fakeAsync, tick, inject } from '@angular/core/testing';
+import { TestBed, async, inject } from '@angular/core/testing';
import { LeafletButtonComponent } from './leaflet-button.component';
+import { TooltipModule } from 'ng2-bootstrap';
describe('Component: LeafletButton', () => {
beforeEach(() => TestBed.configureTestingModule({
+ declarations: [
+ LeafletButtonComponent
+ ],
+ imports: [
+ TooltipModule.forRoot()
+ ],
providers: [
Renderer,
LeafletButtonComponent
@@ -24,6 +31,28 @@
expect(component).toBeTruthy();
}));
+ it('should emit buttonClick', async(inject([LeafletButtonComponent], (component: LeafletButtonComponent) => {
+ component.buttonClick.subscribe((event: Event) => {
+ expect(event).toBeTruthy();
+ });
+
+ component.onClick(new Event('click'));
+ }));
+
+ it('should toggle active state', async(() => {
+ // assemble the component
+ let fixture = TestBed.createComponent(LeafletButtonComponent);
+ fixture.detectChanges();
+
+ // get the instance of the component
+ let component: LeafletButtonComponent = fixture.componentInstance;
+
+ // trigger toggle of active state
+ component.toggleActiveState();
+
+ expect(component.active).toBe(true);
+ }));
+
});
|
c82cd070be37b39676d130e4185535c840a1aee0 | packages/extraterm-ace-terminal-renderer/src/TerminalRenderer.ts | packages/extraterm-ace-terminal-renderer/src/TerminalRenderer.ts | /**
* Copyright 2015-2018 Simon Edwards <simon@simonzone.com>
*/
import { Renderer, HScrollBar, VScrollBar } from "ace-ts";
export class TerminalRenderer extends Renderer {
constructor(container: HTMLElement) {
super(container, { injectCss: false });
}
protected createVScrollBar(container: HTMLElement): VScrollBar {
return new HiddenVScrollBar(container, this);
}
protected createHScrollBar(container: HTMLElement): HScrollBar {
return new HiddenHScrollBar(container, this);
}
}
class HiddenVScrollBar extends VScrollBar {
setVisible(isVisible: boolean): this {
if (isVisible === false) {
super.setVisible(false); // Stop the scrollbar from ever being visible.
}
return this;
}
}
class HiddenHScrollBar extends HScrollBar {
setVisible(isVisible: boolean): this {
if (isVisible === false) {
super.setVisible(false); // Stop the scrollbar from ever being visible.
}
return this;
}
}
| /**
* Copyright 2015-2018 Simon Edwards <simon@simonzone.com>
*/
import { Renderer, HScrollBar, VScrollBar } from "ace-ts";
export class TerminalRenderer extends Renderer {
constructor(container: HTMLElement) {
super(container, { injectCss: false, fontSize: null });
}
protected createVScrollBar(container: HTMLElement): VScrollBar {
return new HiddenVScrollBar(container, this);
}
protected createHScrollBar(container: HTMLElement): HScrollBar {
return new HiddenHScrollBar(container, this);
}
}
class HiddenVScrollBar extends VScrollBar {
setVisible(isVisible: boolean): this {
if (isVisible === false) {
super.setVisible(false); // Stop the scrollbar from ever being visible.
}
return this;
}
}
class HiddenHScrollBar extends HScrollBar {
setVisible(isVisible: boolean): this {
if (isVisible === false) {
super.setVisible(false); // Stop the scrollbar from ever being visible.
}
return this;
}
}
| Stop Ace from manually setting the font size. | Stop Ace from manually setting the font size.
| TypeScript | mit | sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm | ---
+++
@@ -7,7 +7,7 @@
export class TerminalRenderer extends Renderer {
constructor(container: HTMLElement) {
- super(container, { injectCss: false });
+ super(container, { injectCss: false, fontSize: null });
}
protected createVScrollBar(container: HTMLElement): VScrollBar { |
f9fbe23cec7458dec01b2237d6efa0e76a5bc01b | transpilation/deploy.ts | transpilation/deploy.ts | import fs = require("fs");
import { exec } from "shelljs";
function cmd(command: string): string {
const result: any = exec(command);
return result.stdout.trim().replace("\r\n", "\n");
}
const currentBranch = cmd("git rev-parse --abbrev-ref HEAD");
if (currentBranch !== "master") {
throw new Error("This script should only be run on master. You're on " + currentBranch);
}
const changes = cmd("git status --porcelain");
if (changes) {
throw new Error("This script shouldn't be run when you've got working copy changes.");
}
cmd("git branch -f gh-pages");
cmd("git checkout gh-pages");
const toDeploy = [ "index.html", "dist/slime.js", ".gitignore", "transpilation/deploy.ts" ];
const gitignore = ["*"].concat(toDeploy.map(f => "!" + f)).join("\r\n");
fs.writeFileSync(".gitignore", gitignore, "utf8");
const trackedFiles = cmd("git ls-files").split("\n");
const toRemove = trackedFiles.filter(f => toDeploy.indexOf(f) === -1)
toRemove.forEach(f => cmd(`git rm -rf ${f} --dry-run`));
// cmd("git rm -rf * --dry-run");
toDeploy.forEach(f => cmd(`git add ${f}`));
console.log(cmd("git status")); | import fs = require("fs");
import { exec } from "shelljs";
function cmd(command: string): string {
const result: any = exec(command);
return result.stdout.trim().replace("\r\n", "\n");
}
const currentBranch = cmd("git rev-parse --abbrev-ref HEAD");
if (currentBranch !== "master") {
throw new Error("This script should only be run on master. You're on " + currentBranch);
}
const changes = cmd("git status --porcelain");
if (changes) {
throw new Error("This script shouldn't be run when you've got working copy changes.");
}
cmd("git branch -f gh-pages");
cmd("git checkout gh-pages");
const toDeploy = [ "index.html", "dist/slime.js", ".gitignore", "transpilation/deploy.ts" ];
const gitignore = ["*"].concat(toDeploy.map(f => "!" + f)).join("\r\n");
fs.writeFileSync(".gitignore", gitignore, "utf8");
const trackedFiles = cmd("git ls-files").split("\n");
const toRemove = trackedFiles.filter(f => toDeploy.indexOf(f) === -1)
toRemove.forEach(f => cmd(`git rm -rf ${f}`));
toDeploy.forEach(f => cmd(`git add ${f}`));
console.log(cmd("git status")); | Remove --dry-run to try for real. | Remove --dry-run to try for real.
| TypeScript | mit | mmkal/slimejs,mmkal/slimejs,mmkal/slimejs,mmkal/slimejs | ---
+++
@@ -27,9 +27,7 @@
const trackedFiles = cmd("git ls-files").split("\n");
const toRemove = trackedFiles.filter(f => toDeploy.indexOf(f) === -1)
-toRemove.forEach(f => cmd(`git rm -rf ${f} --dry-run`));
-
-// cmd("git rm -rf * --dry-run");
+toRemove.forEach(f => cmd(`git rm -rf ${f}`));
toDeploy.forEach(f => cmd(`git add ${f}`));
|
c476ad32a38ea7f582c0f5c70b21492f362e39db | src/Apps/Collect/Components/Filters/TimePeriodFilter.tsx | src/Apps/Collect/Components/Filters/TimePeriodFilter.tsx | import React from "react"
import { FilterState } from "../../FilterState"
import { Radio, RadioGroup } from "@artsy/palette"
export const TimePeriodFilter: React.SFC<{
filters: FilterState
timePeriods?: string[]
}> = ({ filters, timePeriods }) => {
const periods = (timePeriods || allowedPeriods).filter(timePeriod =>
allowedPeriods.includes(timePeriod)
)
const radioButtons = periods.map((timePeriod, index) => {
const isSelected = filters.state.major_periods[0] === timePeriod
return (
<Radio
my={0.3}
selected={isSelected}
value={timePeriod}
key={index}
label={timePeriod}
/>
)
})
return (
<RadioGroup
deselectable
onSelect={selectedOption => {
filters.setFilter("major_periods", selectedOption)
}}
>
{radioButtons}
</RadioGroup>
)
}
const allowedPeriods = [
"2010",
"2000",
"1990",
"1980",
"1970",
"1960",
"1950",
"1940",
"1930",
"1920",
"1910",
"1900",
"Late 19th Century",
"Mid 19th Century",
"Early 19th Century",
]
| import React from "react"
import { FilterState } from "../../FilterState"
import { Radio, RadioGroup } from "@artsy/palette"
import { get } from "Utils/get"
export const TimePeriodFilter: React.SFC<{
filters: FilterState
timePeriods?: string[]
}> = ({ filters, timePeriods }) => {
const periods = (timePeriods || allowedPeriods).filter(timePeriod =>
allowedPeriods.includes(timePeriod)
)
const defaultValue = get(filters.state, x => x.major_periods[0], "")
const radioButtons = periods.map((timePeriod, index) => {
return <Radio my={0.3} value={timePeriod} key={index} label={timePeriod} />
})
return (
<RadioGroup
deselectable
onSelect={selectedOption => {
filters.setFilter("major_periods", selectedOption)
}}
defaultValue={defaultValue}
>
{radioButtons}
</RadioGroup>
)
}
const allowedPeriods = [
"2010",
"2000",
"1990",
"1980",
"1970",
"1960",
"1950",
"1940",
"1930",
"1920",
"1910",
"1900",
"Late 19th Century",
"Mid 19th Century",
"Early 19th Century",
]
| Select default time period filter selection via RadioGroup instead of Radio | Select default time period filter selection via RadioGroup instead of Radio
Radio.selected is overridden by RadioGroup.defaultValue, so we should use that instead.
| TypeScript | mit | artsy/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction,artsy/reaction-force | ---
+++
@@ -2,6 +2,7 @@
import { FilterState } from "../../FilterState"
import { Radio, RadioGroup } from "@artsy/palette"
+import { get } from "Utils/get"
export const TimePeriodFilter: React.SFC<{
filters: FilterState
@@ -10,26 +11,19 @@
const periods = (timePeriods || allowedPeriods).filter(timePeriod =>
allowedPeriods.includes(timePeriod)
)
+ const defaultValue = get(filters.state, x => x.major_periods[0], "")
const radioButtons = periods.map((timePeriod, index) => {
- const isSelected = filters.state.major_periods[0] === timePeriod
+ return <Radio my={0.3} value={timePeriod} key={index} label={timePeriod} />
+ })
- return (
- <Radio
- my={0.3}
- selected={isSelected}
- value={timePeriod}
- key={index}
- label={timePeriod}
- />
- )
- })
return (
<RadioGroup
deselectable
onSelect={selectedOption => {
filters.setFilter("major_periods", selectedOption)
}}
+ defaultValue={defaultValue}
>
{radioButtons}
</RadioGroup> |
2953d1092efb56d4d674fe2d3e17b10fdefe81c4 | app/config.ts | app/config.ts | const path = electronRequire('path');
// appveyor/travisci sets this var
const CI_MOD = process.env['CI'] ? 3 : 1;
const omnisharpPath = path.resolve((IS_LINUX ? `${process.env.HOME}/.ream-editor/` :
`${process.env.LOCALAPPDATA}\\ReamEditor\\`) + 'omnisharp');
// todo some of this is mirrored in int-helpers.js
const unitTestData = {
backendTimeout: 10 * 1000 * CI_MOD
};
export default {
unitTestData,
omnisharpPort: 2000,
queryEnginePort: 8111,
omnisharpProjectPath: omnisharpPath,
dotnetDebugPath: IS_LINUX ? path.normalize('/dotnetpreview2/dotnet')
: path.normalize('C:/Program Files/dotnet/dotnet.exe')
};
| const path = electronRequire('path');
// appveyor/travisci sets this var
const CI_MOD = process.env['CI'] ? 3 : 1;
const omnisharpPath = path.resolve((IS_LINUX ? `${process.env.HOME}/.ream-editor/` :
`${process.env.LOCALAPPDATA}\\ReamEditor\\`) + 'omnisharp');
// todo some of this is mirrored in int-helpers.js
const unitTestData = {
backendTimeout: 10 * 1000 * CI_MOD
};
export default {
unitTestData,
omnisharpPort: 2000,
queryEnginePort: 8111,
omnisharpProjectPath: omnisharpPath,
dotnetDebugPath: IS_LINUX ? path.normalize('/usr/bin/dotnet')
: path.normalize('C:/Program Files/dotnet/dotnet.exe')
};
| Adjust runtime path for test | Adjust runtime path for test
| TypeScript | mit | stofte/ream-editor,stofte/ream-editor,stofte/linq-editor,stofte/ream-editor,stofte/ream-editor | ---
+++
@@ -15,6 +15,6 @@
omnisharpPort: 2000,
queryEnginePort: 8111,
omnisharpProjectPath: omnisharpPath,
- dotnetDebugPath: IS_LINUX ? path.normalize('/dotnetpreview2/dotnet')
+ dotnetDebugPath: IS_LINUX ? path.normalize('/usr/bin/dotnet')
: path.normalize('C:/Program Files/dotnet/dotnet.exe')
}; |
5a215cbdb13ddef7b248f69df2c5fc4b573f568e | dom_hr.ts | dom_hr.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="hr_HR">
<context>
<name>TreeWindow</name>
<message>
<location filename="../../../treewindow.ui" line="14"/>
<source>Panel DOM tree</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="63"/>
<location filename="../../../treewindow.ui" line="96"/>
<source>Property</source>
<translation type="unfinished">Svojstvo</translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="68"/>
<source>Value</source>
<translation type="unfinished">Vrijednost</translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="76"/>
<source>All properties</source>
<translation type="unfinished">Sva svojstva</translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="101"/>
<source>Type</source>
<translation type="unfinished">Vrsta</translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="106"/>
<source>String value</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="hr">
<context>
<name>TreeWindow</name>
<message>
<location filename="../../../treewindow.ui" line="14"/>
<source>Panel DOM tree</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="63"/>
<location filename="../../../treewindow.ui" line="96"/>
<source>Property</source>
<translation type="unfinished">Svojstvo</translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="68"/>
<source>Value</source>
<translation type="unfinished">Vrijednost</translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="76"/>
<source>All properties</source>
<translation type="unfinished">Sva svojstva</translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="101"/>
<source>Type</source>
<translation type="unfinished">Vrsta</translation>
</message>
<message>
<location filename="../../../treewindow.ui" line="106"/>
<source>String value</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| Fix language vs. name discrepancies | Fix language vs. name discrepancies
...revealed by auto testing
| TypeScript | lgpl-2.1 | stefonarch/lxqt-panel,stefonarch/lxqt-panel,lxde/lxqt-panel,stefonarch/lxqt-panel,lxde/lxqt-panel | ---
+++
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
-<TS version="2.0" language="hr_HR">
+<TS version="2.0" language="hr">
<context>
<name>TreeWindow</name>
<message> |
33268ee36e9790d2f9647ec4f74f8b0a672e5fd6 | components/youtube/channel/channel-model.ts | components/youtube/channel/channel-model.ts | import { Injectable } from 'ng-metadata/core';
import { Model } from './../../model/model-service';
export function Youtube_ChannelFactory( Model )
{
return Model.create( Youtube_Channel, {
} );
}
@Injectable()
export class Youtube_Channel extends Model
{
user_id: number;
channel_id: string;
title: string;
constructor( data?: any )
{
super( data );
}
$remove()
{
return this.$_remove( '/web/dash/linked-accounts/unlink/youtube-channel/' + this.channel_id, 'user' );
}
}
// angular.module( 'gj.Youtube.Channel' ).factory( 'Youtube_Channel', function( Model, User, Api )
// {
// function Youtube_Channel( data )
// {
// if ( data ) {
// angular.extend( this, data );
// }
// if ( this.user ) {
// this.user = new User( this.user );
// }
// }
// Youtube_Channel.prototype.$remove = function()
// {
// return this.$_remove( '/web/dash/linked-accounts/unlink/youtube-channel/' + this.channel_id, 'user' );
// };
// return Model.create( Youtube_Channel );
// } );
| import { Injectable } from 'ng-metadata/core';
import { Model } from './../../model/model-service';
export function Youtube_ChannelFactory( Model )
{
return Model.create( Youtube_Channel, {
} );
}
@Injectable()
export class Youtube_Channel extends Model
{
user_id: number;
channel_id: string;
title: string;
constructor( data?: any )
{
super( data );
}
$remove()
{
return this.$_remove( '/web/dash/linked-accounts/unlink/youtube-channel/' + this.channel_id );
}
}
| Fix remove method in youtube channel model. | Fix remove method in youtube channel model.
| TypeScript | mit | gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib | ---
+++
@@ -21,27 +21,6 @@
$remove()
{
- return this.$_remove( '/web/dash/linked-accounts/unlink/youtube-channel/' + this.channel_id, 'user' );
+ return this.$_remove( '/web/dash/linked-accounts/unlink/youtube-channel/' + this.channel_id );
}
}
-
-// angular.module( 'gj.Youtube.Channel' ).factory( 'Youtube_Channel', function( Model, User, Api )
-// {
-// function Youtube_Channel( data )
-// {
-// if ( data ) {
-// angular.extend( this, data );
-// }
-
-// if ( this.user ) {
-// this.user = new User( this.user );
-// }
-// }
-
-// Youtube_Channel.prototype.$remove = function()
-// {
-// return this.$_remove( '/web/dash/linked-accounts/unlink/youtube-channel/' + this.channel_id, 'user' );
-// };
-
-// return Model.create( Youtube_Channel );
-// } ); |
83d1e61b2f4b4671ae1dc392c71f1cc082af4c8b | src/randomstring.ts | src/randomstring.ts | /*
Copyright 2018 New Vector Ltd
Copyright 2019 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.
*/
export function randomString(len: number): string {
let ret = "";
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < len; ++i) {
ret += chars.charAt(Math.floor(Math.random() * chars.length));
}
return ret;
}
| /*
Copyright 2018 New Vector Ltd
Copyright 2019 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.
*/
const LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
const UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const DIGITS = "0123456789";
export function randomString(len: number): string {
return randomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);
}
export function randomLowercaseString(len: number): string {
return randomStringFrom(len, LOWERCASE);
}
export function randomUppercaseString(len: number): string {
return randomStringFrom(len, UPPERCASE);
}
function randomStringFrom(len: number, chars: string): string {
let ret = "";
for (let i = 0; i < len; ++i) {
ret += chars.charAt(Math.floor(Math.random() * chars.length));
}
return ret;
}
| Add functions for upper & lowercase random strings | Add functions for upper & lowercase random strings
| TypeScript | apache-2.0 | matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk | ---
+++
@@ -15,9 +15,24 @@
limitations under the License.
*/
+const LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
+const UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+const DIGITS = "0123456789";
+
export function randomString(len: number): string {
+ return randomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);
+}
+
+export function randomLowercaseString(len: number): string {
+ return randomStringFrom(len, LOWERCASE);
+}
+
+export function randomUppercaseString(len: number): string {
+ return randomStringFrom(len, UPPERCASE);
+}
+
+function randomStringFrom(len: number, chars: string): string {
let ret = "";
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < len; ++i) {
ret += chars.charAt(Math.floor(Math.random() * chars.length)); |
d97e3c1153fd35ac41de7822326184af960dc0b4 | desktop/core/src/desktop/js/ext/aceHelper.ts | desktop/core/src/desktop/js/ext/aceHelper.ts | import 'ext/ace/ace'
import 'ext/ace/ext-language_tools';
import 'ext/ace/ext-searchbox';
import 'ext/ace/ext-settings_menu';
import 'ext/ace/mode-bigquery';
import 'ext/ace/mode-druid';
import 'ext/ace/mode-elasticsearch';
import 'ext/ace/mode-flink';
import 'ext/ace/mode-hive';
import 'ext/ace/mode-impala';
import 'ext/ace/mode-ksql';
import 'ext/ace/mode-phoenix';
import 'ext/ace/mode-presto';
import 'ext/ace/mode-pgsql'
import 'ext/ace/mode-sql';
import 'ext/ace/mode-text';
import 'ext/ace/snippets/bigquery';
import 'ext/ace/snippets/druid';
import 'ext/ace/snippets/elasticsearch';
import 'ext/ace/snippets/flink';
import 'ext/ace/snippets/hive';
import 'ext/ace/snippets/impala';
import 'ext/ace/snippets/ksql';
import 'ext/ace/snippets/phoenix';
import 'ext/ace/snippets/presto';
import 'ext/ace/snippets/pgsql';
import 'ext/ace/snippets/sql';
import 'ext/ace/snippets/text';
import 'ext/ace/theme-hue';
import 'ext/ace/theme-hue_dark';
import './aceExtensions';
export default (window as any).ace;
| import 'ext/ace/ace'
import 'ext/ace/ext-language_tools';
import 'ext/ace/ext-searchbox';
import 'ext/ace/ext-settings_menu';
import 'ext/ace/mode-bigquery';
import 'ext/ace/mode-druid';
import 'ext/ace/mode-elasticsearch';
import 'ext/ace/mode-flink';
import 'ext/ace/mode-hive';
import 'ext/ace/mode-impala';
import 'ext/ace/mode-ksql';
import 'ext/ace/mode-mysql';
import 'ext/ace/mode-phoenix';
import 'ext/ace/mode-presto';
import 'ext/ace/mode-pgsql'
import 'ext/ace/mode-sql';
import 'ext/ace/mode-text';
import 'ext/ace/snippets/bigquery';
import 'ext/ace/snippets/druid';
import 'ext/ace/snippets/elasticsearch';
import 'ext/ace/snippets/flink';
import 'ext/ace/snippets/hive';
import 'ext/ace/snippets/impala';
import 'ext/ace/snippets/ksql';
import 'ext/ace/snippets/mysql';
import 'ext/ace/snippets/phoenix';
import 'ext/ace/snippets/presto';
import 'ext/ace/snippets/pgsql';
import 'ext/ace/snippets/sql';
import 'ext/ace/snippets/text';
import 'ext/ace/theme-hue';
import 'ext/ace/theme-hue_dark';
import './aceExtensions';
export default (window as any).ace;
| Include the mysql Ace editor mode | [editor] Include the mysql Ace editor mode
| TypeScript | apache-2.0 | kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue | ---
+++
@@ -9,6 +9,7 @@
import 'ext/ace/mode-hive';
import 'ext/ace/mode-impala';
import 'ext/ace/mode-ksql';
+import 'ext/ace/mode-mysql';
import 'ext/ace/mode-phoenix';
import 'ext/ace/mode-presto';
import 'ext/ace/mode-pgsql'
@@ -21,6 +22,7 @@
import 'ext/ace/snippets/hive';
import 'ext/ace/snippets/impala';
import 'ext/ace/snippets/ksql';
+import 'ext/ace/snippets/mysql';
import 'ext/ace/snippets/phoenix';
import 'ext/ace/snippets/presto';
import 'ext/ace/snippets/pgsql'; |
ff7058dcc617182fdfe874920c156a3a8bc70842 | types/ember-data/test/model.ts | types/ember-data/test/model.ts | import Ember from 'ember';
import DS from 'ember-data';
import { assertType } from "./lib/assert";
const Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
title: DS.attr({ defaultValue: "The default" }),
title2: DS.attr({ defaultValue: () => "The default" }),
fullName: Ember.computed('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`;
})
});
const User = DS.Model.extend({
username: DS.attr('string'),
email: DS.attr('string'),
verified: DS.attr('boolean', { defaultValue: false }),
createdAt: DS.attr('date', {
defaultValue() { return new Date(); }
})
});
const user = User.create({ username: 'dwickern' });
assertType<string>(user.get('id'));
assertType<string>(user.get('username'));
assertType<boolean>(user.get('verified'));
assertType<Date>(user.get('createdAt'));
user.serialize();
user.serialize({ someOption: 'neat' });
| import Ember from 'ember';
import DS from 'ember-data';
import { assertType } from "./lib/assert";
const Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
title: DS.attr({ defaultValue: "The default" }),
title2: DS.attr({ defaultValue: () => "The default" }),
fullName: Ember.computed('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`;
})
});
const User = DS.Model.extend({
username: DS.attr('string'),
email: DS.attr('string'),
verified: DS.attr('boolean', { defaultValue: false }),
createdAt: DS.attr('date', {
defaultValue() { return new Date(); }
})
});
const user = User.create({ username: 'dwickern' });
assertType<string>(user.get('id'));
assertType<string>(user.get('username'));
assertType<boolean>(user.get('verified'));
assertType<Date>(user.get('createdAt'));
user.serialize();
user.serialize({ includeId: true });
| Fix a test for last added Ember Data fix. | Fix a test for last added Ember Data fix.
| TypeScript | mit | georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,alexdresko/DefinitelyTyped,arusakov/DefinitelyTyped,zuzusik/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,alexdresko/DefinitelyTyped,magny/DefinitelyTyped,zuzusik/DefinitelyTyped,chrootsu/DefinitelyTyped,mcliment/DefinitelyTyped,arusakov/DefinitelyTyped,chrootsu/DefinitelyTyped,one-pieces/DefinitelyTyped,georgemarshall/DefinitelyTyped,rolandzwaga/DefinitelyTyped,markogresak/DefinitelyTyped,rolandzwaga/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,zuzusik/DefinitelyTyped,dsebastien/DefinitelyTyped | ---
+++
@@ -29,4 +29,5 @@
assertType<Date>(user.get('createdAt'));
user.serialize();
-user.serialize({ someOption: 'neat' });
+user.serialize({ includeId: true });
+ |
5af58734bb7e8563dff82818c6f05f7486045c7a | client/Commands/Prompts/ConcentrationPrompt.ts | client/Commands/Prompts/ConcentrationPrompt.ts | import { Combatant } from "../../Combatant/Combatant";
import { Prompt } from "./Prompt";
export class ConcentrationPrompt implements Prompt {
public static Tag = "Concentrating";
public InputSelector = ".passcheck";
public ComponentName = "concentrationprompt";
public Prompt: string;
public Resolve = () => {};
public FailCheck: () => void;
constructor(combatant: Combatant, damageAmount: number) {
const concentrationDC =
damageAmount > 20 ? Math.floor(damageAmount / 2) : 10;
const autoRoll = combatant.GetConcentrationRoll();
this.Prompt = `${combatant.DisplayName()} DC <strong>${concentrationDC}</strong> concentration check (Constitution save). Auto-roll: <strong>${autoRoll}</strong>`;
this.FailCheck = () => {
combatant
.Tags()
.filter(t => t.Text === ConcentrationPrompt.Tag)
.forEach(tag => combatant.Tags.remove(tag));
return true;
};
}
}
| import { Combatant } from "../../Combatant/Combatant";
import { Prompt } from "./Prompt";
export class ConcentrationPrompt implements Prompt {
public static Tag = "Concentrating";
public InputSelector = ".passcheck";
public ComponentName = "concentrationprompt";
public Prompt: string;
public Resolve = () => {};
public FailCheck: () => void;
constructor(combatant: Combatant, damageAmount: number) {
const concentrationDC =
damageAmount > 20 ? Math.floor(damageAmount / 2) : 10;
const autoRoll = combatant.GetConcentrationRoll();
this.Prompt = `${combatant.DisplayName()} DC <strong>${concentrationDC}</strong> concentration check (Constitution save). Auto-roll: <strong>${autoRoll}</strong>`;
this.FailCheck = () => {
combatant
.Tags()
.filter(t => t.Text === ConcentrationPrompt.Tag)
.forEach(tag => combatant.Tags.remove(tag));
combatant.Encounter.QueueEmitEncounter();
return true;
};
}
}
| Update player view when concentration check fails | Update player view when concentration check fails
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -21,6 +21,7 @@
.Tags()
.filter(t => t.Text === ConcentrationPrompt.Tag)
.forEach(tag => combatant.Tags.remove(tag));
+ combatant.Encounter.QueueEmitEncounter();
return true;
};
} |
a98bb3b3e0453753a7a79efd7158baf807f2b2ad | server/test/services/test-project-catalog-service.ts | server/test/services/test-project-catalog-service.ts | let assert = require('assert');
import projectCatalogService = require('../../services/project-catalog-service');
describe('GetProjectrs', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal(-1, [1,2,3].indexOf(4));
});
});
}); | let assert = require('assert');
import projectCatalogService = require('../../services/project-catalog-service');
describe('ProjectCatalogTest', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal(-1, [1,2,3].indexOf(4));
});
});
}); | Remove .ds_store.. not sure why it was there | Remove .ds_store.. not sure why it was there
| TypeScript | mit | scottrehlander/angular2-expressjs-brd,scottrehlander/angular2-expressjs-brd,scottrehlander/angular2-expressjs-brd | ---
+++
@@ -2,7 +2,7 @@
import projectCatalogService = require('../../services/project-catalog-service');
-describe('GetProjectrs', function() {
+describe('ProjectCatalogTest', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal(-1, [1,2,3].indexOf(4)); |
b62adbfbfedbf4ccd9f1055ddf705020b9a95ff3 | test-ts/example.ts | test-ts/example.ts | import * as jsc from "../lib/jsverify.js";
describe("basic jsverify usage", () => {
jsc.property("(b && b) === b", jsc.bool, b => (b && b) === b);
jsc.property("boolean fn thrice", jsc.fn(jsc.bool), jsc.bool, (f, b) =>
f(f(f(b))) === f(b)
);
it("async evaluation has no effect on pure computation", done => {
const property = jsc.forall(jsc.fn(jsc.nat), jsc.json, jsc.nat(20), (f, x, t) => {
const sync = f(x);
return new Promise(resolve => {
setTimeout(() => resolve(f(x)), t);
}).then(val => val === sync);
});
jsc.assert(property)
.then(val => val ? done(val) : done())
.catch(error => done(error));
});
});
| import * as jsc from "../lib/jsverify.js";
describe("basic jsverify usage", () => {
jsc.property("(b && b) === b", jsc.bool, b => (b && b) === b);
jsc.property("boolean fn thrice", jsc.fn(jsc.bool), jsc.bool, (f, b) =>
f(f(f(b))) === f(b)
);
it("async evaluation has no effect on pure computation", done => {
const property = jsc.forall(jsc.fn(jsc.nat), jsc.json, jsc.nat(20), (f, x, t) => {
const sync = f(x);
return new Promise(resolve => {
setTimeout(() => resolve(f(x)), t);
}).then(val => val === sync);
});
jsc.assert(property)
.then(val => val ? done(val) : done())
.catch(error => done(error));
});
// You may simply return a promise with mocha
jsc.property("async evaluation...", jsc.fun(jsc.nat), jsc.json, jsc.nat(20), (f, x, t) => {
const sync = f(x);
return new Promise(resolve => {
setTimeout(() => resolve(f(x)), t);
}).then(val => val === sync);
});
});
| Simplify async typescript test, cc @jvanbruegge | Simplify async typescript test, cc @jvanbruegge
| TypeScript | mit | jsverify/jsverify,StoneCypher/jsverify,StoneCypher/jsverify,jsverify/jsverify | ---
+++
@@ -19,4 +19,13 @@
.then(val => val ? done(val) : done())
.catch(error => done(error));
});
+
+ // You may simply return a promise with mocha
+ jsc.property("async evaluation...", jsc.fun(jsc.nat), jsc.json, jsc.nat(20), (f, x, t) => {
+ const sync = f(x);
+
+ return new Promise(resolve => {
+ setTimeout(() => resolve(f(x)), t);
+ }).then(val => val === sync);
+ });
}); |
5169c7946ec7e034247952db486ba5d6726bf3d1 | server/scuffled.ts | server/scuffled.ts | require('look').start()
var fs = require('fs')
var net = require('net')
var app = require('http').createServer()
var io = require('socket.io').listen(app)
io.set('log level', 2)
app.listen(1337)
var opts = {
key: fs.readFileSync(__dirname + '/ssl/server.key'),
cert: fs.readFileSync(__dirname + '/ssl/server.crt'),
ca: fs.readFileSync(__dirname + '/ssl/ca.crt')
}
require('tls').createServer(opts, stream => {
var req = net.connect({ port: 1337, host: '127.0.0.1'}, () => {
stream.pipe(req)
req.pipe(stream)
})
}).listen(1338)
setImmediate(() => {
var game = new Scuffle.ServerGame()
game.start(io)
})
| require('look').start()
var fs = require('fs')
var net = require('net')
var app = require('http').createServer()
var io = require('socket.io').listen(app)
io.set('log level', 2)
io.set('close timeout', 5)
io.set('heartbeat timeout', 10)
io.set('heartbeat interval', 5)
app.listen(1337)
var opts = {
key: fs.readFileSync(__dirname + '/ssl/server.key'),
cert: fs.readFileSync(__dirname + '/ssl/server.crt'),
ca: fs.readFileSync(__dirname + '/ssl/ca.crt')
}
require('tls').createServer(opts, stream => {
var req = net.connect({ port: 1337, host: '127.0.0.1'}, () => {
stream.pipe(req)
req.pipe(stream)
})
}).listen(1338)
setImmediate(() => {
var game = new Scuffle.ServerGame()
game.start(io)
})
| Set socket.io timeout options on server | Set socket.io timeout options on server
| TypeScript | apache-2.0 | shockkolate/scuffle,shockkolate/scuffle,shockkolate/scuffle | ---
+++
@@ -4,6 +4,9 @@
var app = require('http').createServer()
var io = require('socket.io').listen(app)
io.set('log level', 2)
+io.set('close timeout', 5)
+io.set('heartbeat timeout', 10)
+io.set('heartbeat interval', 5)
app.listen(1337)
var opts = { |
27d5ef5a2543fa546fd5f56a41039ec3113286e4 | src/lib/registerLanguages.ts | src/lib/registerLanguages.ts | import hljs from 'highlight.js/lib/highlight';
import { HLJSLang } from '../types';
/**
* Register Highlight.js languages.
*
* @export
* @param {Record<string, HLJSLang>} languages Highlight.js languages
*/
export default function registerLanguages(
languages: Record<string, HLJSLang>
): void {
Object.keys(languages).forEach(languageName => {
const language = languages[languageName];
hljs.registerLanguage(languageName, language);
});
}
| import hljs from 'highlight.js/lib/highlight';
import { HLJSLang } from '../types';
/**
* Register Highlight.js languages.
*
* @export
* @param {Record<string, HLJSLang>} languages Highlight.js languages
*/
export default function registerLanguages(
languages: Record<string, HLJSLang>
): void {
if (typeof languages !== 'object') {
return;
}
Object.keys(languages).forEach(languageName => {
const language = languages[languageName];
hljs.registerLanguage(languageName, language);
});
}
| Fix error when no languages given | :bug: Fix error when no languages given
| TypeScript | mit | gluons/vue-highlight.js | ---
+++
@@ -11,6 +11,10 @@
export default function registerLanguages(
languages: Record<string, HLJSLang>
): void {
+ if (typeof languages !== 'object') {
+ return;
+ }
+
Object.keys(languages).forEach(languageName => {
const language = languages[languageName];
|
6c93388d32f394cddd38c1d2470823de33ec9ec4 | src/app/alveo/listindex/listtable/listtable.component.ts | src/app/alveo/listindex/listtable/listtable.component.ts | import { Component, OnInit, ViewChild, Input, Output, EventEmitter } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
@Component({
selector: 'listtable',
templateUrl: './listtable.component.html',
styleUrls: ['./listtable.component.css'],
})
export class ListTableComponent implements OnInit {
@Input() tableData: any;
@Output() onSelection = new EventEmitter<any>();
selection: any;
displayedColumns = ['listName', 'items', 'shared'];
dataSource: ListDataSource = null;
@ViewChild(MatPaginator) paginator: MatPaginator;
ngOnInit(): void {
this.dataSource = new ListDataSource(this.paginator, this.tableData);
}
onSelect(item): void {
this.selection = item;
this.onSelection.emit(item);
}
}
export class ListDataSource extends DataSource<any> {
dataChange: BehaviorSubject<any> = new BehaviorSubject<any>([]);
get data(): any { return this.dataChange.value; }
constructor(private _paginator: MatPaginator, tableData: any) {
super();
for (const list of tableData) {
this.addList(list);
}
}
addList(list: any) {
const copiedData = this.data.slice();
copiedData.push(list);
this.dataChange.next(copiedData);
}
/* This is based on the material.angular.io pagination example */
connect(): Observable<any[]> {
const displayDataChanges = [
this.dataChange,
this._paginator.page,
];
return Observable.merge(...displayDataChanges).map(() => {
const data = this.data.slice();
const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
return data.splice(startIndex, this._paginator.pageSize);
});
}
disconnect() {}
}
| import { Component, ViewChild, Input, Output, EventEmitter } from '@angular/core';
import { MatPaginator, MatTableDataSource } from '@angular/material';
@Component({
selector: 'listtable',
templateUrl: './listtable.component.html',
styleUrls: ['./listtable.component.css'],
})
export class ListTableComponent {
@Input() tableData: any;
@Output() onSelection = new EventEmitter<any>();
private displayedColumns = ['listName', 'items', 'shared'];
private dataSource = new MatTableDataSource<Element>();
@ViewChild(MatPaginator) paginator: MatPaginator;
ngAfterViewInit() {
this.dataSource = new MatTableDataSource<Element>(this.tableData);
this.dataSource.paginator = this.paginator;
}
onSelect(item): void {
this.onSelection.emit(item);
}
}
| Simplify using new data source methods | Simplify using new data source methods
| TypeScript | bsd-3-clause | Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber | ---
+++
@@ -1,11 +1,5 @@
-import { Component, OnInit, ViewChild, Input, Output, EventEmitter } from '@angular/core';
-import { BehaviorSubject } from 'rxjs/BehaviorSubject';
-import { DataSource } from '@angular/cdk/collections';
-import { MatPaginator } from '@angular/material';
-import { Observable } from 'rxjs/Observable';
-import 'rxjs/add/operator/startWith';
-import 'rxjs/add/observable/merge';
-import 'rxjs/add/operator/map';
+import { Component, ViewChild, Input, Output, EventEmitter } from '@angular/core';
+import { MatPaginator, MatTableDataSource } from '@angular/material';
@Component({
selector: 'listtable',
@@ -13,58 +7,21 @@
styleUrls: ['./listtable.component.css'],
})
-export class ListTableComponent implements OnInit {
+export class ListTableComponent {
@Input() tableData: any;
@Output() onSelection = new EventEmitter<any>();
- selection: any;
- displayedColumns = ['listName', 'items', 'shared'];
- dataSource: ListDataSource = null;
+ private displayedColumns = ['listName', 'items', 'shared'];
+ private dataSource = new MatTableDataSource<Element>();
@ViewChild(MatPaginator) paginator: MatPaginator;
- ngOnInit(): void {
- this.dataSource = new ListDataSource(this.paginator, this.tableData);
+ ngAfterViewInit() {
+ this.dataSource = new MatTableDataSource<Element>(this.tableData);
+ this.dataSource.paginator = this.paginator;
}
onSelect(item): void {
- this.selection = item;
this.onSelection.emit(item);
}
}
-
-export class ListDataSource extends DataSource<any> {
- dataChange: BehaviorSubject<any> = new BehaviorSubject<any>([]);
- get data(): any { return this.dataChange.value; }
-
- constructor(private _paginator: MatPaginator, tableData: any) {
- super();
-
- for (const list of tableData) {
- this.addList(list);
- }
- }
-
- addList(list: any) {
- const copiedData = this.data.slice();
- copiedData.push(list);
- this.dataChange.next(copiedData);
- }
-
- /* This is based on the material.angular.io pagination example */
- connect(): Observable<any[]> {
- const displayDataChanges = [
- this.dataChange,
- this._paginator.page,
- ];
-
- return Observable.merge(...displayDataChanges).map(() => {
- const data = this.data.slice();
-
- const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
- return data.splice(startIndex, this._paginator.pageSize);
- });
- }
-
- disconnect() {}
-} |
9149d43ac2d803f7b1aefd6869dbcf395c89b914 | clients/client-web-vue3/src/index.ts | clients/client-web-vue3/src/index.ts | import { Client, InitConfig } from '@jovotech/client-web';
import { Plugin, reactive, ref } from 'vue';
declare global {
interface Window {
JovoWebClientVue?: typeof import('.');
}
}
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$client: Client;
}
}
export interface JovoWebClientVueConfig {
url: string;
client?: InitConfig;
}
const plugin: Plugin = {
install: (app, config) => {
if (!config?.url) {
throw new Error(
`At least the 'url' option has to be set in order to use the JovoWebClientPlugin. `,
);
}
// this is probably not working because the new reactivity system of vue is much worse in v3
app.config.globalProperties.$client = reactive(new Client(config.url, config.client));
},
};
export default plugin;
export * from '@jovotech/client-web';
| import { Client, InitConfig } from '@jovotech/client-web';
import { Plugin, reactive, ref } from 'vue';
declare global {
interface Window {
JovoWebClientVue?: typeof import('.');
}
}
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$client: Client;
}
}
export interface JovoWebClientVueConfig {
url: string;
client?: InitConfig;
}
const plugin: Plugin = {
install: (app, config) => {
if (!config?.url) {
throw new Error(
`At least the 'url' option has to be set in order to use the JovoWebClientPlugin. `,
);
}
// Issue: It seems like it is impossible to attach reactive data to jovo from a plugin.
// This means that compared to the vue2-variant, this will require workarounds to use properties of the client.
// Another solution would be to simply add the client to the data of the Root-component and provide it from there.
// This would fix the reactivity issue.
app.config.globalProperties.$client = reactive(new Client(config.url, config.client));
},
};
export default plugin;
export * from '@jovotech/client-web';
| Add comment describing caveats of the Vue3 plugin | :bulb: Add comment describing caveats of the Vue3 plugin
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -26,7 +26,10 @@
);
}
- // this is probably not working because the new reactivity system of vue is much worse in v3
+ // Issue: It seems like it is impossible to attach reactive data to jovo from a plugin.
+ // This means that compared to the vue2-variant, this will require workarounds to use properties of the client.
+ // Another solution would be to simply add the client to the data of the Root-component and provide it from there.
+ // This would fix the reactivity issue.
app.config.globalProperties.$client = reactive(new Client(config.url, config.client));
},
}; |
e549bb1523f5ce45ad092a0d937e7260169e3f58 | app/messages/services/letterHistogramService.ts | app/messages/services/letterHistogramService.ts | import * as _ from 'lodash';
export class LetterHistogramService {
create(sentences: string[]): any {
let letters = _.flatMap(sentences, sentence => sentence.split(''));
let formattedLetters = _
.chain(letters)
.map(s => s.toLowerCase())
.filter(s => s.match(/[a-z]/i))
.value();
let histogram = _.reduce(formattedLetters, (acc, letter) => {
acc[letter] = (acc[letter] || 0) + 1;
return acc;
}, {});
return histogram;
}
}; | import * as _ from 'lodash';
export class LetterHistogramService {
create(sentences: string[]): {[key: string]: number} {
let letters = _.flatMap(sentences, sentence => sentence.split(''));
let formattedLetters = _
.chain(letters)
.map(s => s.toLowerCase())
.filter(s => s.match(/[a-z]/i))
.value();
let initHistogram: {[key: string]: number} = { };
let histogram = _.reduce(formattedLetters, (acc, letter) => {
acc[letter] = (acc[letter] || 0) + 1;
return acc;
}, initHistogram);
return histogram;
}
}; | Make the letter histograms service create method more explicit. | Make the letter histograms service create method more explicit.
| TypeScript | mit | s-soltys/GmailStats,s-soltys/GmailStats,s-soltys/GmailStats | ---
+++
@@ -1,7 +1,7 @@
import * as _ from 'lodash';
export class LetterHistogramService {
- create(sentences: string[]): any {
+ create(sentences: string[]): {[key: string]: number} {
let letters = _.flatMap(sentences, sentence => sentence.split(''));
let formattedLetters = _
@@ -9,11 +9,13 @@
.map(s => s.toLowerCase())
.filter(s => s.match(/[a-z]/i))
.value();
-
+
+ let initHistogram: {[key: string]: number} = { };
+
let histogram = _.reduce(formattedLetters, (acc, letter) => {
acc[letter] = (acc[letter] || 0) + 1;
return acc;
- }, {});
+ }, initHistogram);
return histogram;
} |
f3e39fd6c76f3c47805fc371ed4c8b98640a34cc | packages/element-preact/src/index.ts | packages/element-preact/src/index.ts | import define, { getName } from '@skatejs/define';
import Element from '@skatejs/element';
import { h as preactH, render } from 'preact';
const mapDom = new WeakMap();
export default class extends Element {
disconnectedCallback() {
if (super.disconnectedCallback) {
super.disconnectedCallback();
}
render(null, this.renderRoot, mapDom.get(this));
}
renderer() {
const dom = mapDom.get(this);
mapDom.set(this, render(this.render(), this.renderRoot, dom));
}
}
export function h(name, props, ...chren) {
if (name.prototype instanceof HTMLElement) {
define(name);
name = getName(name);
}
return preactH(name, props, ...chren);
}
| /** @jsx h */
import define, { getName } from '@skatejs/define';
import Element from '@skatejs/element';
import { h as preactH, render } from 'preact';
const mapDom = new WeakMap();
export default class extends Element {
disconnectedCallback() {
if (super.disconnectedCallback) {
super.disconnectedCallback();
}
render(null, this.renderRoot, mapDom.get(this));
}
renderer() {
const dom = mapDom.get(this);
mapDom.set(this, render(this.render(), this.renderRoot, dom));
}
}
export function h(name, props, ...chren) {
if (name.prototype instanceof HTMLElement) {
define(name);
name = getName(name);
}
return preactH(name, props, ...chren);
}
export declare namespace h {
namespace JSX {
interface Element {}
type LibraryManagedAttributes<E, _> = E extends { props: infer Props; prototype: infer Prototype; } ? Pick<Prototype, Extract<keyof Prototype, keyof Props>> : _;
}
}
| Add type to map props to instance properties so they type in JSX. | Add type to map props to instance properties so they type in JSX.
| TypeScript | mit | skatejs/skatejs,skatejs/skatejs,skatejs/skatejs | ---
+++
@@ -1,3 +1,5 @@
+/** @jsx h */
+
import define, { getName } from '@skatejs/define';
import Element from '@skatejs/element';
import { h as preactH, render } from 'preact';
@@ -24,3 +26,10 @@
}
return preactH(name, props, ...chren);
}
+
+export declare namespace h {
+ namespace JSX {
+ interface Element {}
+ type LibraryManagedAttributes<E, _> = E extends { props: infer Props; prototype: infer Prototype; } ? Pick<Prototype, Extract<keyof Prototype, keyof Props>> : _;
+ }
+} |
121f9e60a4da922469d7aefde1e2cf9027eb093c | packages/components/containers/keys/AddressKeysHeaderActions.tsx | packages/components/containers/keys/AddressKeysHeaderActions.tsx | import * as React from 'react';
import { c } from 'ttag';
import isTruthy from '@proton/shared/lib/helpers/isTruthy';
import { Address } from '@proton/shared/lib/interfaces';
import { DropdownActions, Select } from '../../components';
interface Props {
addresses: Address[];
addressIndex: number;
onAddKey?: () => void;
onImportKey?: () => void;
onChangeAddress: (event: React.ChangeEvent<HTMLSelectElement>) => void;
}
const AddressKeysHeaderActions = ({ addresses, addressIndex, onAddKey, onImportKey, onChangeAddress }: Props) => {
const createActions = [
onAddKey && {
text: c('Action').t`Create key`,
onClick: onAddKey,
},
onImportKey && {
text: c('Action').t`Import key`,
onClick: onImportKey,
},
].filter(isTruthy);
if (!createActions.length) {
return null;
}
return (
<div className="mb1 flex flex-align-items-start">
{addresses.length > 1 && (
<div className="mr1 mb0-5">
<Select
value={addressIndex}
options={addresses.map(({ Email }, i) => ({ text: Email, value: i }))}
onChange={onChangeAddress}
/>
</div>
)}
{createActions.length ? (
<span className="inline-flex mr1 mb0-5">
<DropdownActions list={createActions} />
</span>
) : null}
</div>
);
};
export default AddressKeysHeaderActions;
| import * as React from 'react';
import { c } from 'ttag';
import isTruthy from '@proton/shared/lib/helpers/isTruthy';
import { Address } from '@proton/shared/lib/interfaces';
import { DropdownActions, Select } from '../../components';
interface Props {
addresses: Address[];
addressIndex: number;
onAddKey?: () => void;
onImportKey?: () => void;
onChangeAddress: (event: React.ChangeEvent<HTMLSelectElement>) => void;
}
const AddressKeysHeaderActions = ({ addresses, addressIndex, onAddKey, onImportKey, onChangeAddress }: Props) => {
const createActions = [
onAddKey && {
text: c('Action').t`Create key`,
onClick: onAddKey,
},
onImportKey && {
text: c('Action').t`Import key`,
onClick: onImportKey,
},
].filter(isTruthy);
if (!createActions.length && addresses.length <= 1) {
return null;
}
return (
<div className="mb1 flex flex-align-items-start">
{addresses.length > 1 && (
<div className="mr1 mb0-5">
<Select
value={addressIndex}
options={addresses.map(({ Email }, i) => ({ text: Email, value: i }))}
onChange={onChangeAddress}
/>
</div>
)}
{createActions.length ? (
<span className="inline-flex mr1 mb0-5">
<DropdownActions list={createActions} />
</span>
) : null}
</div>
);
};
export default AddressKeysHeaderActions;
| Fix display address keys condition | Fix display address keys condition
Should still see the address selector even when no actions exists
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -25,7 +25,7 @@
},
].filter(isTruthy);
- if (!createActions.length) {
+ if (!createActions.length && addresses.length <= 1) {
return null;
}
|
cf4ec8179c319fbe512f25889e58b60f14ba0253 | AzureFunctions.Client/app/pipes/sidebar.pipe.ts | AzureFunctions.Client/app/pipes/sidebar.pipe.ts | import {Injectable, Pipe, PipeTransform} from '@angular/core';
import {FunctionInfo} from '../models/function-info';
@Pipe({
name: 'sidebarFilter',
pure: false
})
@Injectable()
export class SideBarFilterPipe implements PipeTransform {
transform(items: FunctionInfo[], args: string[] | string): any {
var query = typeof args === 'string' ? args : args[0];
if (args && args.length > 0 && args[0] && args[0].length > 0) {
return items.filter(item => !item.clientOnly && item.name.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) !== -1);
} else {
return items;
}
}
} | import {Injectable, Pipe, PipeTransform} from '@angular/core';
import {FunctionInfo} from '../models/function-info';
@Pipe({
name: 'sidebarFilter',
pure: false
})
@Injectable()
export class SideBarFilterPipe implements PipeTransform {
transform(items: FunctionInfo[], args: string[] | string): any {
if (args && args.length > 0) {
var query = typeof args === 'string' ? args : args[0];
if (query) {
return items.filter(item => !item.clientOnly && item.name.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) !== -1);
}
}
return items;
}
} | Fix search filter on the sidebar regression | Fix search filter on the sidebar regression
| TypeScript | apache-2.0 | projectkudu/WebJobsPortal,projectkudu/AzureFunctions,projectkudu/AzureFunctions,agruning/azure-functions-ux,chunye/azure-functions-ux,agruning/azure-functions-ux,chunye/azure-functions-ux,projectkudu/WebJobsPortal,agruning/azure-functions-ux,projectkudu/AzureFunctions,projectkudu/WebJobsPortal,agruning/azure-functions-ux,projectkudu/AzureFunctions,chunye/azure-functions-ux,chunye/azure-functions-ux,chunye/azure-functions-ux,projectkudu/WebJobsPortal,agruning/azure-functions-ux | ---
+++
@@ -8,11 +8,12 @@
@Injectable()
export class SideBarFilterPipe implements PipeTransform {
transform(items: FunctionInfo[], args: string[] | string): any {
- var query = typeof args === 'string' ? args : args[0];
- if (args && args.length > 0 && args[0] && args[0].length > 0) {
- return items.filter(item => !item.clientOnly && item.name.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) !== -1);
- } else {
- return items;
+ if (args && args.length > 0) {
+ var query = typeof args === 'string' ? args : args[0];
+ if (query) {
+ return items.filter(item => !item.clientOnly && item.name.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) !== -1);
+ }
}
+ return items;
}
} |
33e62f73c89c69130add3b0a78efec2934f6e402 | TypeScript/TableTennis/Equipments/BallSize.ts | TypeScript/TableTennis/Equipments/BallSize.ts | /**
* Size of the ball, in cm.
*/
enum BallSize {
ThrityEight = 0.38,
Fourty = 0.4,
FourtyPlus = 0.4025,
FourtyFour = 0.44
}
export default BallSize; | // define as object literal for demo purpose
/**
* Size of the ball, in cm.
*/
var BallSize = {
ThrityEight: 0.38,
Fourty: 0.4,
FourtyPlus: 0.4025,
FourtyFour: 0.44
}
export default BallSize; | Add export default object literal usage | Add export default object literal usage
| TypeScript | mit | unional/coolCodeExamples | ---
+++
@@ -1,11 +1,13 @@
+// define as object literal for demo purpose
+
/**
* Size of the ball, in cm.
*/
-enum BallSize {
- ThrityEight = 0.38,
- Fourty = 0.4,
- FourtyPlus = 0.4025,
- FourtyFour = 0.44
+var BallSize = {
+ ThrityEight: 0.38,
+ Fourty: 0.4,
+ FourtyPlus: 0.4025,
+ FourtyFour: 0.44
}
export default BallSize; |
3452c99e77f5dc02e108aa2b4c790262035d4471 | src/services/main-service.ts | src/services/main-service.ts | // https://angular.io/docs/ts/latest/guide/server-communication.html#!#http-client
import {Injectable, Inject} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class MainService {
constructor(@Inject(Http) private http) { }
private _serviceUrl = 'http://www.youtubeinmp3.com/fetch/?format=JSON&video=';
getFakeElements(query: string) {
return new Observable(observer =>
observer.next(['Element 1', 'Element 2', 'Element 3'])).share();
}
getMusicLink(videoUrl: string) {
return this.http.get(this._serviceUrl + videoUrl)
.map(res => res.text())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
} | // https://angular.io/docs/ts/latest/guide/server-communication.html#!#http-client
import {Injectable, Inject} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class MainService {
constructor(@Inject(Http) private http) { }
private _serviceUrl = 'http://www.youtubeinmp3.com/fetch/?format=JSON&video=';
getFakeElements(query: string) {
return new Observable(observer =>
observer.next(['Query: ' + query, 'Element 1', 'Element 2', 'Element 3'])).share();
}
getMusicLink(videoUrl: string) {
return this.http.get(this._serviceUrl + videoUrl)
.map(res => res.text())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
} | Add query element to make fake data a little bit more dynamic | Add query element to make fake data a little bit more dynamic
| TypeScript | mit | astagi/angular2-workbench,astagi/angular2-workbench,astagi/angular2-workbench | ---
+++
@@ -13,7 +13,7 @@
getFakeElements(query: string) {
return new Observable(observer =>
- observer.next(['Element 1', 'Element 2', 'Element 3'])).share();
+ observer.next(['Query: ' + query, 'Element 1', 'Element 2', 'Element 3'])).share();
}
|
59f43192f802d0dea4140e4ce6862d4d611bb9d2 | lib/interfaces/IIncludeOptions.ts | lib/interfaces/IIncludeOptions.ts | import {Model} from "../models/Model";
import {IIncludeAssociation} from "./IIncludeAssociation";
import {IBaseIncludeOptions} from "./IBaseIncludeOptions";
/**
* Complex include options
*/
export interface IIncludeOptions extends IBaseIncludeOptions {
/**
* The model you want to eagerly load
*/
model?: typeof Model;
/**
* The association you want to eagerly load. (This can be used instead of providing a model/as pair)
*/
association?: IIncludeAssociation;
/**
* Load further nested related models
*/
include?: Array<typeof Model | IIncludeOptions>;
}
| import {Model} from "../models/Model";
import {IIncludeAssociation} from "./IIncludeAssociation";
import {IBaseIncludeOptions} from "./IBaseIncludeOptions";
/**
* Complex include options
*/
export interface IIncludeOptions extends IBaseIncludeOptions {
/**
* The model you want to eagerly load
*/
model?: typeof Model;
/**
* The association you want to eagerly load. (This can be used instead of providing a model/as pair)
*/
association?: IIncludeAssociation;
/**
* Load further nested related models
*/
include?: Array<typeof Model | IIncludeOptions>;
/**
* If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will
* be returned. Only applies if `options.paranoid` is true for the model.
*/
paranoid?: boolean;
}
| Add paranoid in IncludeOptions interface | Add paranoid in IncludeOptions interface
| TypeScript | mit | RobinBuschmann/sequelize-typescript,RobinBuschmann/sequelize-typescript,RobinBuschmann/sequelize-typescript | ---
+++
@@ -22,4 +22,10 @@
*/
include?: Array<typeof Model | IIncludeOptions>;
+ /**
+ * If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will
+ * be returned. Only applies if `options.paranoid` is true for the model.
+ */
+ paranoid?: boolean;
+
} |
1cfe9350bbc174d957c263c7eb2a39c206af7cba | types/react-navigation/react-navigation-tests.tsx | types/react-navigation/react-navigation-tests.tsx | import * as React from 'react';
import { View } from 'react-native';
import {
addNavigationHelpers,
StackNavigator,
} from 'react-navigation';
const Start = (
<View />
);
export const AppNavigator = StackNavigator({
StartImage: {
path: 'startImage',
screen: Start,
},
}, {
initialRouteName: 'StartImage',
});
const Router = (props: any) => (
<AppNavigator
navigation={
addNavigationHelpers({
dispatch: {},
state: {},
})
}
/>
);
const tabNavigatorScreenOptions: TabNavigatorScreenOptions = {
title: 'title',
tabBarVisible: true,
tabBarIcon: <View />,
tabBarLabel: 'label'
}
| import * as React from 'react';
import { View } from 'react-native';
import {
addNavigationHelpers,
StackNavigator,
TabNavigatorScreenOptions
} from 'react-navigation';
const Start = (
<View />
);
export const AppNavigator = StackNavigator({
StartImage: {
path: 'startImage',
screen: Start,
},
}, {
initialRouteName: 'StartImage',
});
const Router = (props: any) => (
<AppNavigator
navigation={
addNavigationHelpers({
dispatch: {},
state: {},
})
}
/>
);
const tabNavigatorScreenOptions: TabNavigatorScreenOptions = {
title: 'title',
tabBarVisible: true,
tabBarIcon: <View />,
tabBarLabel: 'label'
}
| Fix missing import in the test | Fix missing import in the test
| TypeScript | mit | AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,benliddicott/DefinitelyTyped,QuatroCode/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,minodisk/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,benishouga/DefinitelyTyped,borisyankov/DefinitelyTyped,aciccarello/DefinitelyTyped,alexdresko/DefinitelyTyped,QuatroCode/DefinitelyTyped,georgemarshall/DefinitelyTyped,jimthedev/DefinitelyTyped,jimthedev/DefinitelyTyped,borisyankov/DefinitelyTyped,markogresak/DefinitelyTyped,aciccarello/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,georgemarshall/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,ashwinr/DefinitelyTyped,arusakov/DefinitelyTyped,abbasmhd/DefinitelyTyped,amir-arad/DefinitelyTyped,georgemarshall/DefinitelyTyped,nycdotnet/DefinitelyTyped,aciccarello/DefinitelyTyped,isman-usoh/DefinitelyTyped,arusakov/DefinitelyTyped,magny/DefinitelyTyped,zuzusik/DefinitelyTyped,nycdotnet/DefinitelyTyped,rolandzwaga/DefinitelyTyped,dsebastien/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,zuzusik/DefinitelyTyped,jimthedev/DefinitelyTyped,georgemarshall/DefinitelyTyped,abbasmhd/DefinitelyTyped,chrootsu/DefinitelyTyped,benishouga/DefinitelyTyped,mcliment/DefinitelyTyped,isman-usoh/DefinitelyTyped,alexdresko/DefinitelyTyped,ashwinr/DefinitelyTyped,chrootsu/DefinitelyTyped,one-pieces/DefinitelyTyped,benishouga/DefinitelyTyped,arusakov/DefinitelyTyped,minodisk/DefinitelyTyped,AbraaoAlves/DefinitelyTyped | ---
+++
@@ -3,6 +3,7 @@
import {
addNavigationHelpers,
StackNavigator,
+ TabNavigatorScreenOptions
} from 'react-navigation';
const Start = ( |
83443cfc709b11d87f53d7f8a564142b3b88d9e6 | src/CringeProvider.ts | src/CringeProvider.ts | import * as sockjs from "sockjs"
import { Server } from "http";
import fs = require('fs');
import { settings } from "./settings";
class CringeProvider {
clients: sockjs.Connection[] = [];
cringeserver: sockjs.Server;
ncringes: number;
constructor() {
this.ncringes = fs.readdirSync(settings.ressources + '/public/cringec').length;
this.cringeserver = sockjs.createServer({ sockjs_url: "https://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js" });
this.cringeserver.on('connection', (conn: sockjs.Connection) => {
this.clients.push(conn);
conn.on('close', () => {
console.log('cringy disconnection');
let idx = this.clients.findIndex(cli => cli.id == conn.id);
idx >= 0 && this.clients.splice(idx, 1);
});
conn.write(JSON.stringify(this.ncringes));
});
}
pushNewCringe(c: number) {
this.ncringes = c;
for(let conn of this.clients)
conn.write(JSON.stringify(this.ncringes));
}
install(server: Server) {
this.cringeserver.installHandlers(server, { prefix: '/cringep' });
}
}
export let Cringer = new CringeProvider; | import * as sockjs from "sockjs"
import { Server } from "http";
import fs = require('fs');
import { settings } from "./settings";
class CringeProvider {
clients: sockjs.Connection[] = [];
cringeserver: sockjs.Server;
ncringes: number;
constructor() {
this.ncringes = fs.readdirSync(settings.ressources + '/public/cringec').length;
this.cringeserver = sockjs.createServer({ sockjs_url: "https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.5/sockjs.min.js" });
this.cringeserver.on('connection', (conn: sockjs.Connection) => {
this.clients.push(conn);
conn.on('close', () => {
console.log('cringy disconnection');
let idx = this.clients.findIndex(cli => cli.id == conn.id);
idx >= 0 && this.clients.splice(idx, 1);
});
conn.write(JSON.stringify(this.ncringes));
});
}
pushNewCringe(c: number) {
this.ncringes = c;
for(let conn of this.clients)
conn.write(JSON.stringify(this.ncringes));
}
install(server: Server) {
this.cringeserver.installHandlers(server, { prefix: '/cringep' });
}
}
export let Cringer = new CringeProvider; | Use proper CDN because fuck everything | Use proper CDN because fuck everything
| TypeScript | agpl-3.0 | shoedrip-unbound/dogars,shoedrip-unbound/dogars,shoedrip-unbound/dogars | ---
+++
@@ -9,7 +9,7 @@
ncringes: number;
constructor() {
this.ncringes = fs.readdirSync(settings.ressources + '/public/cringec').length;
- this.cringeserver = sockjs.createServer({ sockjs_url: "https://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js" });
+ this.cringeserver = sockjs.createServer({ sockjs_url: "https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.5/sockjs.min.js" });
this.cringeserver.on('connection', (conn: sockjs.Connection) => {
this.clients.push(conn);
conn.on('close', () => { |
546df299c5afb2e1fdc5a8db53978aae661517a5 | src/aba-validation.ts | src/aba-validation.ts | "use strict";
module.exports = {
validate: (routingNumber: string) => {
const match = routingNumber.match(/^\s*([\d]{9})\s*$/);
if (!match) {
return false;
}
const weights = [3, 7 ,1];
const aba = match[1];
let sum = 0;
for (let i=0 ; i<9 ; ++i) {
sum += +aba.charAt(i) * weights[i % 3];
}
return (sum !== 0 && sum % 10 === 0);
}
}; | "use strict";
export function validate(routingNumber: string): boolean {
const match = routingNumber.match(/^\s*([\d]{9})\s*$/);
if (!match) {
return false;
}
const weights = [3, 7 ,1];
const aba = match[1];
let sum = 0;
for (let i=0 ; i<9 ; ++i) {
sum += +aba.charAt(i) * weights[i % 3];
}
return (sum !== 0 && sum % 10 === 0);
}
| Use export instead of module.exports | Use export instead of module.exports
Typedefinitions are not generated whe using module.exports, see
https://github.com/Microsoft/TypeScript/issues/11451
To fix that, used export directly on the main ts file.
| TypeScript | mit | JamesEggers1/node-ABAValidator | ---
+++
@@ -1,19 +1,17 @@
"use strict";
-module.exports = {
- validate: (routingNumber: string) => {
- const match = routingNumber.match(/^\s*([\d]{9})\s*$/);
- if (!match) {
- return false;
- }
+export function validate(routingNumber: string): boolean {
+ const match = routingNumber.match(/^\s*([\d]{9})\s*$/);
+ if (!match) {
+ return false;
+ }
- const weights = [3, 7 ,1];
- const aba = match[1];
+ const weights = [3, 7 ,1];
+ const aba = match[1];
- let sum = 0;
- for (let i=0 ; i<9 ; ++i) {
- sum += +aba.charAt(i) * weights[i % 3];
- }
+ let sum = 0;
+ for (let i=0 ; i<9 ; ++i) {
+ sum += +aba.charAt(i) * weights[i % 3];
+ }
- return (sum !== 0 && sum % 10 === 0);
- }
-};
+ return (sum !== 0 && sum % 10 === 0);
+} |
5f238ee78ed77134e9d097863a698d3f3641cf36 | rundeckapp/grails-spa/packages/ui/src/components/project-picker/main.ts | rundeckapp/grails-spa/packages/ui/src/components/project-picker/main.ts | import Vue from 'vue'
import { getRundeckContext, url } from '@rundeck/ui-trellis'
import ProjectPicker from '@rundeck/ui-trellis/lib/components/widgets/project-select/ProjectSelectButton.vue'
import { Project } from '@rundeck/ui-trellis/lib/stores/Projects'
const rootStore = getRundeckContext().rootStore
window.addEventListener('DOMContentLoaded', init)
function init() {
const el = document.getElementById('projectPicker') as HTMLElement
if (!el)
return
const component = new Vue({
el,
components: {ProjectPicker},
provide: {rootStore},
template: `<ProjectPicker projectLabel="${el.dataset.projectLabel}" @project:selected="handleSelect" @project:select-all="handleSelectAll"/>`,
methods: {
handleSelect(project: Project) {
window.location.assign(url(`project/${project.name}/home`).href)
},
handleSelectAll() {
window.location.assign(url('').href)
}
}
})
} | import Vue from 'vue'
import { getRundeckContext, url } from '@rundeck/ui-trellis'
import ProjectPicker from '@rundeck/ui-trellis/lib/components/widgets/project-select/ProjectSelectButton.vue'
import { Project } from '@rundeck/ui-trellis/lib/stores/Projects'
const rootStore = getRundeckContext().rootStore
window.addEventListener('DOMContentLoaded', init)
function init() {
const el = document.getElementById('projectPicker') as HTMLElement
if (!el)
return
const component = new Vue({
el,
components: {ProjectPicker},
provide: {rootStore},
template: `<ProjectPicker projectLabel="${el.dataset.projectLabel}" @project:selected="handleSelect" @project:select-all="handleSelectAll"/>`,
methods: {
handleSelect(project: Project) {
window.location.assign(url(`?project=${project.name}`).href)
},
handleSelectAll() {
window.location.assign(url('').href)
}
}
})
} | Use special project endpoint for picker links | Use special project endpoint for picker links
Fixes #7214
| TypeScript | apache-2.0 | rundeck/rundeck,variacode/rundeck,rundeck/rundeck,variacode/rundeck,rundeck/rundeck,variacode/rundeck,rundeck/rundeck,rundeck/rundeck,variacode/rundeck,variacode/rundeck | ---
+++
@@ -22,7 +22,7 @@
template: `<ProjectPicker projectLabel="${el.dataset.projectLabel}" @project:selected="handleSelect" @project:select-all="handleSelectAll"/>`,
methods: {
handleSelect(project: Project) {
- window.location.assign(url(`project/${project.name}/home`).href)
+ window.location.assign(url(`?project=${project.name}`).href)
},
handleSelectAll() {
window.location.assign(url('').href) |
26bf7b02dde5a0a92d9f56c7ee5927440be0c519 | resources/app/auth/auth.ts | resources/app/auth/auth.ts | export interface IAuthService {
isLoggedIn();
register(user);
login(user);
} | export interface IAuthService {
isLoggedIn();
register(user);
login(user);
}
export interface IHttpRegisterResponse {
data: {
message: string;
};
status: string;
}
export interface IHttpLoginResponse {
data: {
token: string;
message: string;
},
status: string;
} | Add interface for register and login http response | Add interface for register and login http response
| TypeScript | mit | ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io | ---
+++
@@ -3,3 +3,18 @@
register(user);
login(user);
}
+
+export interface IHttpRegisterResponse {
+ data: {
+ message: string;
+ };
+ status: string;
+}
+
+export interface IHttpLoginResponse {
+ data: {
+ token: string;
+ message: string;
+ },
+ status: string;
+} |
29b809956f783996204b6607dd1302c68e47d1a0 | packages/slack/src/api/base/index.ts | packages/slack/src/api/base/index.ts | import { map, isObject } from 'lodash'
import { request } from './request'
import { APIError } from '../../errors'
import { camel, snake } from '../../helpers/case'
const stringify = (object: object) =>
map(snake(object), v => isObject(v) ? JSON.stringify(v) : v)
const URI = (ns: string, method: string, token: string) =>
`https://slack.com/api/${ns}.${method}?token=${token}`
export abstract class APIModule {
protected namespace: string
constructor(private token: string) {
this.namespace = this.constructor.name.toLowerCase()
}
protected async request(method: string, form: object = {}) {
const uri = URI(this.namespace, method, this.token)
const response = await request(uri, stringify(form))
if (!response.ok) throw new APIError(response.error)
return camel(response)
}
}
| import { mapValues, isObject } from 'lodash'
import { request } from './request'
import { APIError } from '../../errors'
import { camel, snake } from '../../helpers/case'
const stringify = (object: object) =>
mapValues(snake(object), v => isObject(v) ? JSON.stringify(v) : v)
const URI = (ns: string, method: string, token: string) =>
`https://slack.com/api/${ns}.${method}?token=${token}`
export abstract class APIModule {
protected namespace: string
constructor(private token: string) {
this.namespace = this.constructor.name.toLowerCase()
}
protected async request(method: string, form: object = {}) {
const uri = URI(this.namespace, method, this.token)
const response = await request(uri, stringify(form))
if (!response.ok) throw new APIError(response.error)
return camel(response)
}
}
| Fix minor issue with stringify | Fix minor issue with stringify
| TypeScript | apache-2.0 | dempfi/xene | ---
+++
@@ -1,10 +1,10 @@
-import { map, isObject } from 'lodash'
+import { mapValues, isObject } from 'lodash'
import { request } from './request'
import { APIError } from '../../errors'
import { camel, snake } from '../../helpers/case'
const stringify = (object: object) =>
- map(snake(object), v => isObject(v) ? JSON.stringify(v) : v)
+ mapValues(snake(object), v => isObject(v) ? JSON.stringify(v) : v)
const URI = (ns: string, method: string, token: string) =>
`https://slack.com/api/${ns}.${method}?token=${token}` |
d3bc9c6d38ec0fa8c9a91e70fe648aefdfcde418 | src/app/search/search.component.ts | src/app/search/search.component.ts | import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
categories = [
{value: 'All'},
{value: 'Data sources'},
{value: 'Facilities'},
{value: 'Guides'},
{value: 'Instrument'},
{value: 'Knowledge articles'},
{value: 'People'},
{value: 'Policies'},
{value: 'Software'},
{value: 'Training'},
{value: 'Services'}
];
searchTextValue;
categoryValue;
@Output() searchTextChange = new EventEmitter();
@Output() categoryChange = new EventEmitter();
constructor() {
}
ngOnInit() {
}
@Input()
get searchText() {
return this.searchTextValue;
}
@Input()
get category() {
return this.categoryValue;
}
set searchText(val) {
this.searchTextValue = val;
this.searchTextChange.emit(val);
}
set category(val) {
this.categoryValue = val;
this.categoryChange.emit(val);
}
}
| import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {AnalyticsService} from '../app.analytics.service';
import {SearchService} from '../app.search.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
categories = [
{value: 'All'},
{value: 'Data sources'},
{value: 'Facilities'},
{value: 'Guides'},
{value: 'Instrument'},
{value: 'Knowledge articles'},
{value: 'People'},
{value: 'Policies'},
{value: 'Software'},
{value: 'Training'},
{value: 'Services'}
];
searchTextValue;
categoryValue;
@Output() searchTextChange = new EventEmitter();
@Output() categoryChange = new EventEmitter();
searchTextSubject: Subject<String> = new Subject();
constructor(private analyticsService: AnalyticsService, private searchService: SearchService) {
}
ngOnInit() {
this.searchTextSubject.debounceTime(1000).subscribe((searchText) => this.analyticsService.trackSearch(this.categoryValue, searchText));
}
@Input()
get searchText() {
return this.searchTextValue;
}
@Input()
get category() {
return this.categoryValue;
}
set searchText(val) {
this.searchTextValue = val;
this.searchTextChange.emit(val);
this.searchTextSubject.next(val);
this.searchService.setSearchText(val);
}
set category(val) {
this.categoryValue = val;
this.categoryChange.emit(val);
this.searchService.setSearchCategory(val);
}
}
| Use search service and analytics service | Use search service and analytics service
| TypeScript | bsd-3-clause | UoA-eResearch/research-hub,UoA-eResearch/research-hub,UoA-eResearch/research-hub | ---
+++
@@ -1,4 +1,8 @@
import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
+import {Subject} from 'rxjs/Subject';
+import {AnalyticsService} from '../app.analytics.service';
+import {SearchService} from '../app.search.service';
+
@Component({
selector: 'app-search',
@@ -25,13 +29,14 @@
categoryValue;
@Output() searchTextChange = new EventEmitter();
@Output() categoryChange = new EventEmitter();
+ searchTextSubject: Subject<String> = new Subject();
- constructor() {
+ constructor(private analyticsService: AnalyticsService, private searchService: SearchService) {
}
ngOnInit() {
-
+ this.searchTextSubject.debounceTime(1000).subscribe((searchText) => this.analyticsService.trackSearch(this.categoryValue, searchText));
}
@Input()
@@ -47,10 +52,13 @@
set searchText(val) {
this.searchTextValue = val;
this.searchTextChange.emit(val);
+ this.searchTextSubject.next(val);
+ this.searchService.setSearchText(val);
}
set category(val) {
this.categoryValue = val;
this.categoryChange.emit(val);
+ this.searchService.setSearchCategory(val);
}
} |
270be8c9d4bef4310ce22de24dcff21b0cf08f29 | purple-raven-client/src/constants.ts | purple-raven-client/src/constants.ts | import { isLocalhost } from './registerServiceWorker';
export const SETTINGS = 'Connection Settings';
export const VALIDATION_ERROR = 'VALIDATION_ERROR';
export const CHANNEL_FIELD = 'channel';
export const NAME_FIELD = 'name';
export const KEY_FIELD = 'key';
export const RANDOM_STRING_LENGTH = 255;
export let SERVER_URL = isLocalhost ? 'http://localhost:8080' : '';
export const CHANNELS_API_URL = `${SERVER_URL}/api/channels`;
| import { isLocalhost } from './registerServiceWorker';
export const SETTINGS = 'Connection Settings';
export const VALIDATION_ERROR = 'VALIDATION_ERROR';
export const CHANNEL_FIELD = 'channel';
export const NAME_FIELD = 'name';
export const KEY_FIELD = 'key';
export const RANDOM_STRING_LENGTH = 255;
export let SERVER_URL = isLocalhost && window.location.port !== '8080' ? 'http://localhost:8080' : '';
export const CHANNELS_API_URL = `${SERVER_URL}/api/channels`;
| Use base URL as SERVER_URL if served from port 8080. | Use base URL as SERVER_URL if served from port 8080.
| TypeScript | mit | undefeat/purple-raven,undefeat/purple-raven,undefeat/purple-raven | ---
+++
@@ -9,5 +9,5 @@
export const RANDOM_STRING_LENGTH = 255;
-export let SERVER_URL = isLocalhost ? 'http://localhost:8080' : '';
+export let SERVER_URL = isLocalhost && window.location.port !== '8080' ? 'http://localhost:8080' : '';
export const CHANNELS_API_URL = `${SERVER_URL}/api/channels`; |
0921a5479ec0a595f30d0614d672b8806bf50d34 | src/environments/environment.staging-local.ts | src/environments/environment.staging-local.ts | export const environment = {
production: true,
backend_url: 'http://localhost:8080',
auth_clientID: 'xwMK322G3bOF4OV20tqDlaMx2TMYjc32',
auth_domain: 'c4sg-staging.auth0.com,
auth_tenant_shared: true,
auth_api: 'https://c4sg-api',
auth_callback_env: 'staging',
auth_silenturl: 'silent-loc.html',
AWS_IMAGE_BUCKET: 'c4sg.dev.images',
AWS_DOCS_BUCKET: 'c4sg.dev.docs',
AWS_REGION: 'us-west-2',
AWS_SIGNATURE_VERSION: 'v4'
};
| export const environment = {
production: true,
backend_url: 'http://localhost:8080',
auth_clientID: 'xwMK322G3bOF4OV20tqDlaMx2TMYjc32',
auth_domain: 'c4sg-staging.auth0.com',
auth_tenant_shared: true,
auth_api: 'https://c4sg-api',
auth_callback_env: 'staging',
auth_silenturl: 'silent-loc.html',
AWS_IMAGE_BUCKET: 'c4sg.dev.images',
AWS_DOCS_BUCKET: 'c4sg.dev.docs',
AWS_REGION: 'us-west-2',
AWS_SIGNATURE_VERSION: 'v4'
};
| Fix auth in staging environment | Fix auth in staging environment
| TypeScript | mit | bingxuren/c4sg-web,Code4SocialGood/c4sg-web,jxwang16/c4sg-web,Code4SocialGood/c4sg-web,jekcosty/c4sg-web,Code4SocialGood/c4sg-web,bingxuren/c4sg-web,bingxuren/c4sg-web,jxwang16/c4sg-web,jxwang16/c4sg-web,jekcosty/c4sg-web,jekcosty/c4sg-web | ---
+++
@@ -2,7 +2,7 @@
production: true,
backend_url: 'http://localhost:8080',
auth_clientID: 'xwMK322G3bOF4OV20tqDlaMx2TMYjc32',
- auth_domain: 'c4sg-staging.auth0.com,
+ auth_domain: 'c4sg-staging.auth0.com',
auth_tenant_shared: true,
auth_api: 'https://c4sg-api',
auth_callback_env: 'staging', |
9f0fe1c7d57cc3fab807e5cf662f102cf8df60b4 | bot/handlers/messages/dm/remove-me.ts | bot/handlers/messages/dm/remove-me.ts | import { DiscordDBUser } from "../../../../typeorm/models/discord-db-user";
import { Message } from "discord.js";
import { getMongoRepository } from "typeorm";
import { DiscordDBUserHelper } from "../../../../typeorm/helpers/discord-db-user-helper";
import { GameTime } from "../../../../typeorm/models/game-time";
export default async function renmoveMeHandler(message: Message) {
try {
const discordUser = message.author;
const userRepository = getMongoRepository(DiscordDBUser);
const timeRepository = getMongoRepository(GameTime);
const gameTimes = await timeRepository.find({ userId: discordUser.id });
timeRepository.delete(gameTimes.map(time => time._id));
const users = await userRepository.find({ userId: discordUser.id });
users.forEach(user => DiscordDBUserHelper.removeUser(user));
console.log(`Removed ${discordUser.username}#${discordUser.discriminator}`);
message.reply(`${discordUser.username}#${discordUser.discriminator} has been removed. All your game stats are gone.`);
} catch (err) {
message.reply("Something went wrong. Your stats have not yet been deleted yet.")
console.error(err);
}
} | import { DiscordDBUser } from "../../../../typeorm/models/discord-db-user";
import { Message } from "discord.js";
import { getMongoRepository } from "typeorm";
import { DiscordDBUserHelper } from "../../../../typeorm/helpers/discord-db-user-helper";
import { GameTime } from "../../../../typeorm/models/game-time";
export default async function renmoveMeHandler(message: Message) {
try {
const discordUser = message.author;
const userRepository = getMongoRepository(DiscordDBUser);
const timeRepository = getMongoRepository(GameTime);
const gameTimes = await timeRepository.find({ userId: discordUser.id });
// Doing it the right way caused some unintended casualties.
gameTimes.forEach(time => timeRepository.delete(time));
const users = await userRepository.find({ userId: discordUser.id });
users.forEach(user => DiscordDBUserHelper.removeUser(user));
console.log(`Removed ${discordUser.username}#${discordUser.discriminator}`);
message.reply(`${discordUser.username}#${discordUser.discriminator} has been removed. All your game stats are gone.`);
} catch (err) {
message.reply("Something went wrong. Your stats have not yet been deleted yet.")
console.error(err);
}
} | Fix the removeme method to delete specific times | Fix the removeme method to delete specific times
| TypeScript | apache-2.0 | Goyatuzo/LurkerBot,Goyatuzo/LurkerBot | ---
+++
@@ -11,7 +11,9 @@
const timeRepository = getMongoRepository(GameTime);
const gameTimes = await timeRepository.find({ userId: discordUser.id });
- timeRepository.delete(gameTimes.map(time => time._id));
+
+ // Doing it the right way caused some unintended casualties.
+ gameTimes.forEach(time => timeRepository.delete(time));
const users = await userRepository.find({ userId: discordUser.id });
users.forEach(user => DiscordDBUserHelper.removeUser(user)); |
54bb91ae330088a55bb6dd413f56b7d9e55550a9 | applications/calendar/src/app/components/events/PopoverCloseButton.tsx | applications/calendar/src/app/components/events/PopoverCloseButton.tsx | import { c } from 'ttag';
import { Button, Icon, Tooltip } from '@proton/components';
interface Props {
onClose: () => void;
}
const PopoverCloseButton = ({ onClose }: Props) => {
return (
<Tooltip title={c('Event popover close button').t`Close popover`}>
<Button icon shape="ghost" size="small" onClick={onClose}>
<Icon name="cross" alt={c('Action').t`Close event popover`} />
</Button>
</Tooltip>
);
};
export default PopoverCloseButton;
| import { c } from 'ttag';
import { Button, Icon, Tooltip } from '@proton/components';
interface Props {
onClose: () => void;
}
const PopoverCloseButton = ({ onClose }: Props) => {
return (
<Tooltip title={c('Event popover close button').t`Close popover`}>
<Button icon shape="ghost" size="small" onClick={onClose}>
<Icon name="cross-big" alt={c('Action').t`Close event popover`} />
</Button>
</Tooltip>
);
};
export default PopoverCloseButton;
| Increase size of popover close icon to 'cross-big' | Increase size of popover close icon to 'cross-big'
CALWEB-3542
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -9,7 +9,7 @@
return (
<Tooltip title={c('Event popover close button').t`Close popover`}>
<Button icon shape="ghost" size="small" onClick={onClose}>
- <Icon name="cross" alt={c('Action').t`Close event popover`} />
+ <Icon name="cross-big" alt={c('Action').t`Close event popover`} />
</Button>
</Tooltip>
); |
c284b8f0d027e07348d6300f0f4fc231030ad80e | client/LauncherViewModel.ts | client/LauncherViewModel.ts | import * as ko from "knockout";
import { env } from "./Environment";
import { Metrics } from "./Utility/Metrics";
import { TransferLocalStorageToCanonicalURLIfNeeded } from "./Utility/TransferLocalStorage";
export class LauncherViewModel {
constructor() {
const pageLoadData = {
referrer: document.referrer,
userAgent: navigator.userAgent
};
Metrics.TrackEvent("LandingPageLoad", pageLoadData);
TransferLocalStorageToCanonicalURLIfNeeded(env.CanonicalURL);
}
public GeneratedEncounterId = env.EncounterId;
public JoinEncounterInput = ko.observable<string>("");
public StartEncounter = () => {
let encounterId = this.JoinEncounterInput().split("/").pop();
window.location.href = `e/${encounterId || this.GeneratedEncounterId}`;
}
public JoinEncounter = () => {
let encounterId = this.JoinEncounterInput().split("/").pop();
if (encounterId) {
window.location.href = `p/${encounterId}`;
}
}
public JoinEncounterButtonClass = () => {
let encounterId = this.JoinEncounterInput().split("/").pop();
return encounterId ? "enabled" : "disabled";
}
}
| import * as ko from "knockout";
import { env } from "./Environment";
import { Metrics } from "./Utility/Metrics";
import { Store } from "./Utility/Store";
import { TransferLocalStorageToCanonicalURLIfNeeded } from "./Utility/TransferLocalStorage";
export class LauncherViewModel {
constructor() {
const pageLoadData = {
referrer: document.referrer,
userAgent: navigator.userAgent
};
Metrics.TrackEvent("LandingPageLoad", pageLoadData);
TransferLocalStorageToCanonicalURLIfNeeded(env.CanonicalURL);
}
public GeneratedEncounterId = env.EncounterId;
public JoinEncounterInput = ko.observable<string>("");
public StartEncounter = () => {
const encounterId = this.JoinEncounterInput().split("/").pop();
Store.Delete(Store.AutoSavedEncounters, Store.DefaultSavedEncounterId);
window.location.href = `e/${encounterId || this.GeneratedEncounterId}`;
}
public JoinEncounter = () => {
const encounterId = this.JoinEncounterInput().split("/").pop();
Store.Delete(Store.AutoSavedEncounters, Store.DefaultSavedEncounterId);
if (encounterId) {
window.location.href = `p/${encounterId}`;
}
}
public JoinEncounterButtonClass = () => {
const encounterId = this.JoinEncounterInput().split("/").pop();
return encounterId ? "enabled" : "disabled";
}
}
| Clear autosaved encounter when launching encounter from landing page | Clear autosaved encounter when launching encounter from landing page
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -2,6 +2,7 @@
import { env } from "./Environment";
import { Metrics } from "./Utility/Metrics";
+import { Store } from "./Utility/Store";
import { TransferLocalStorageToCanonicalURLIfNeeded } from "./Utility/TransferLocalStorage";
export class LauncherViewModel {
@@ -19,19 +20,21 @@
public JoinEncounterInput = ko.observable<string>("");
public StartEncounter = () => {
- let encounterId = this.JoinEncounterInput().split("/").pop();
+ const encounterId = this.JoinEncounterInput().split("/").pop();
+ Store.Delete(Store.AutoSavedEncounters, Store.DefaultSavedEncounterId);
window.location.href = `e/${encounterId || this.GeneratedEncounterId}`;
}
public JoinEncounter = () => {
- let encounterId = this.JoinEncounterInput().split("/").pop();
+ const encounterId = this.JoinEncounterInput().split("/").pop();
+ Store.Delete(Store.AutoSavedEncounters, Store.DefaultSavedEncounterId);
if (encounterId) {
window.location.href = `p/${encounterId}`;
}
}
public JoinEncounterButtonClass = () => {
- let encounterId = this.JoinEncounterInput().split("/").pop();
+ const encounterId = this.JoinEncounterInput().split("/").pop();
return encounterId ? "enabled" : "disabled";
}
} |
400e51abe0667c5b4735cc67847f0a12c1ca6dca | source/rxjs-operators.ts | source/rxjs-operators.ts | // import 'rxjs/Rx'; // adds ALL RxJS statics & operators to Observable
// See node_module/rxjs/Rxjs.js
// Import just the rxjs statics and operators we need for THIS app.
// Statics
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/of';
// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap'; | // import 'rxjs/Rx'; // adds ALL RxJS statics & operators to Observable
// See node_module/rxjs/Rxjs.js
// Import just the rxjs statics and operators we need for THIS app.
// Statics
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/of';
// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
| Drop switchMap from the operators used | Drop switchMap from the operators used
We aren't using this anymore since the category view now resolves its data and then pulls it straight from the activated route.
| TypeScript | mit | SamGraber/codemash-angular-app,SamGraber/codemash-angular-app,SamGraber/codemash-angular-app | ---
+++
@@ -10,4 +10,3 @@
// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
-import 'rxjs/add/operator/switchMap'; |
1682181b783813fbd4e0f9c4595345009d719b36 | packages/common/index.ts | packages/common/index.ts | /*
* Nest @common
* Copyright(c) 2017 - 2019 Kamil Mysliwiec
* https://nestjs.com
* MIT Licensed
*/
import 'reflect-metadata';
export * from './cache';
export * from './decorators';
export * from './enums';
export * from './exceptions';
export * from './http';
export {
Abstract,
ArgumentMetadata,
ArgumentsHost,
BeforeApplicationShutdown,
CallHandler,
CanActivate,
DynamicModule,
ExceptionFilter,
ExecutionContext,
ForwardReference,
HttpServer,
INestApplication,
INestApplicationContext,
INestMicroservice,
MiddlewareConsumer,
NestInterceptor,
NestMiddleware,
NestModule,
OnApplicationBootstrap,
OnApplicationShutdown,
OnModuleDestroy,
OnModuleInit,
Paramtype,
PipeTransform,
Provider,
RpcExceptionFilter,
Scope,
Type,
ValidationError,
WebSocketAdapter,
WsExceptionFilter,
WsMessageHandler,
} from './interfaces';
export * from './pipes';
export * from './serializer';
export * from './services';
export * from './utils';
| /*
* Nest @common
* Copyright(c) 2017 - 2019 Kamil Mysliwiec
* https://nestjs.com
* MIT Licensed
*/
import 'reflect-metadata';
export * from './cache';
export * from './decorators';
export * from './enums';
export * from './exceptions';
export * from './http';
export {
Abstract,
ArgumentMetadata,
ArgumentsHost,
BeforeApplicationShutdown,
CallHandler,
CanActivate,
DynamicModule,
ExceptionFilter,
ExecutionContext,
ForwardReference,
HttpServer,
INestApplication,
INestApplicationContext,
INestMicroservice,
MiddlewareConsumer,
NestInterceptor,
NestMiddleware,
NestModule,
OnApplicationBootstrap,
OnApplicationShutdown,
OnModuleDestroy,
OnModuleInit,
Paramtype,
PipeTransform,
Provider,
RpcExceptionFilter,
Scope,
Type,
ValidationError,
WebSocketAdapter,
WsExceptionFilter,
WsMessageHandler,
ScopeOptions,
} from './interfaces';
export * from './pipes';
export * from './serializer';
export * from './services';
export * from './utils';
| Add `ScopeOptions` to public API | feat(): Add `ScopeOptions` to public API
| TypeScript | mit | kamilmysliwiec/nest,kamilmysliwiec/nest | ---
+++
@@ -44,6 +44,7 @@
WebSocketAdapter,
WsExceptionFilter,
WsMessageHandler,
+ ScopeOptions,
} from './interfaces';
export * from './pipes';
export * from './serializer'; |
4e500eee2c3507817571b203c8e3ca860f9511d6 | web-ng/src/app/services/data-import/data-import.service.ts | web-ng/src/app/services/data-import/data-import.service.ts | /**
* Copyright 2020 Google LLC
*
* 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
*
* https://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 { environment } from '../../../environments/environment';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
const IMPORT_CSV_URL = `${environment.cloudFunctionsUrl}/importCsv`;
export interface ImportCsvResponse {
message?: string;
}
@Injectable({
providedIn: 'root',
})
export class DataImportService {
constructor(private httpClient: HttpClient) {}
importCsv(
projectId: string,
layerId: string,
file: File
): Promise<ImportCsvResponse> {
const formData = new FormData();
formData.set('project', projectId);
formData.set('layer', layerId);
formData.append('file', file);
return this.httpClient
.post<ImportCsvResponse>(IMPORT_CSV_URL, formData)
.toPromise();
}
}
| /**
* Copyright 2020 Google LLC
*
* 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
*
* https://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 { environment } from '../../../environments/environment';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
const IMPORT_CSV_URL = `${environment.cloudFunctionsUrl}/importCsv`;
const IMPORT_GEOJSON_URL = `${environment.cloudFunctionsUrl}/importGeoJson`;
export interface ImportResponse {
message?: string;
}
@Injectable({
providedIn: 'root',
})
export class DataImportService {
constructor(private httpClient: HttpClient) {}
importCsv(
projectId: string,
layerId: string,
file: File
): Promise<ImportResponse> {
const formData = new FormData();
formData.set('project', projectId);
formData.set('layer', layerId);
formData.append('file', file);
let importUrl;
if (file.name.endsWith('.geojson')) {
importUrl = IMPORT_GEOJSON_URL;
} else if (file.name.endsWith('.csv')) {
importUrl = IMPORT_CSV_URL;
} else {
throw new Error('Invalid file format');
}
return this.httpClient
.post<ImportResponse>(importUrl, formData)
.toPromise();
}
}
| Select endpoint based on file extension | Select endpoint based on file extension
| TypeScript | apache-2.0 | google/ground-platform,google/ground-platform,google/ground-platform,google/ground-platform | ---
+++
@@ -20,7 +20,9 @@
const IMPORT_CSV_URL = `${environment.cloudFunctionsUrl}/importCsv`;
-export interface ImportCsvResponse {
+const IMPORT_GEOJSON_URL = `${environment.cloudFunctionsUrl}/importGeoJson`;
+
+export interface ImportResponse {
message?: string;
}
@@ -34,13 +36,21 @@
projectId: string,
layerId: string,
file: File
- ): Promise<ImportCsvResponse> {
+ ): Promise<ImportResponse> {
const formData = new FormData();
formData.set('project', projectId);
formData.set('layer', layerId);
formData.append('file', file);
+ let importUrl;
+ if (file.name.endsWith('.geojson')) {
+ importUrl = IMPORT_GEOJSON_URL;
+ } else if (file.name.endsWith('.csv')) {
+ importUrl = IMPORT_CSV_URL;
+ } else {
+ throw new Error('Invalid file format');
+ }
return this.httpClient
- .post<ImportCsvResponse>(IMPORT_CSV_URL, formData)
+ .post<ImportResponse>(importUrl, formData)
.toPromise();
}
} |
b1c382653182fd69bad7f7882aaeca55eeaea3d2 | src/fast-string-array.ts | src/fast-string-array.ts | /**
* Puts `key` into the backing array, if it is not already present. Returns
* the index of the `key` in the backing array.
*/
export let put: (strarr: FastStringArray, key: string) => number;
/**
* FastStringArray acts like a `Set` (allowing only one occurrence of a string
* `key`), but provides the index of the `key` in the backing array.
*
* This is designed to allow synchronizing a second array with the contents of
* the backing array, like how `sourcesContent[i]` is the source content
* associated with `source[i]`, and there are never duplicates.
*/
export class FastStringArray {
indexes = Object.create(null) as { [key: string]: number };
array = [] as ReadonlyArray<string>;
static {
put = (strarr, key) => {
const { array, indexes } = strarr;
// The key may or may not be present. If it is present, it's a number.
let index = indexes[key] as number | undefined;
// If it's not yet present, we need to insert it and track the index in the
// indexes.
if (index === undefined) {
index = indexes[key] = array.length;
(array as string[]).push(key);
}
return index;
};
}
}
| /**
* FastStringArray acts like a `Set` (allowing only one occurrence of a string
* `key`), but provides the index of the `key` in the backing array.
*
* This is designed to allow synchronizing a second array with the contents of
* the backing array, like how `sourcesContent[i]` is the source content
* associated with `source[i]`, and there are never duplicates.
*/
export class FastStringArray {
indexes = Object.create(null) as { [key: string]: number };
array = [] as ReadonlyArray<string>;
}
/**
* Puts `key` into the backing array, if it is not already present. Returns
* the index of the `key` in the backing array.
*/
export function put(strarr: FastStringArray, key: string): number {
const { array, indexes } = strarr;
// The key may or may not be present. If it is present, it's a number.
let index = indexes[key] as number | undefined;
// If it's not yet present, we need to insert it and track the index in the
// indexes.
if (index === undefined) {
index = indexes[key] = array.length;
(array as string[]).push(key);
}
return index;
}
| Remove unneeded static initializer block | Remove unneeded static initializer block
| TypeScript | apache-2.0 | ampproject/remapping,ampproject/remapping,ampproject/remapping | ---
+++
@@ -1,9 +1,3 @@
-/**
- * Puts `key` into the backing array, if it is not already present. Returns
- * the index of the `key` in the backing array.
- */
-export let put: (strarr: FastStringArray, key: string) => number;
-
/**
* FastStringArray acts like a `Set` (allowing only one occurrence of a string
* `key`), but provides the index of the `key` in the backing array.
@@ -15,21 +9,24 @@
export class FastStringArray {
indexes = Object.create(null) as { [key: string]: number };
array = [] as ReadonlyArray<string>;
+}
- static {
- put = (strarr, key) => {
- const { array, indexes } = strarr;
- // The key may or may not be present. If it is present, it's a number.
- let index = indexes[key] as number | undefined;
+/**
+ * Puts `key` into the backing array, if it is not already present. Returns
+ * the index of the `key` in the backing array.
+ */
+export function put(strarr: FastStringArray, key: string): number {
+ const { array, indexes } = strarr;
+ // The key may or may not be present. If it is present, it's a number.
+ let index = indexes[key] as number | undefined;
- // If it's not yet present, we need to insert it and track the index in the
- // indexes.
- if (index === undefined) {
- index = indexes[key] = array.length;
- (array as string[]).push(key);
- }
+ // If it's not yet present, we need to insert it and track the index in the
+ // indexes.
+ if (index === undefined) {
+ index = indexes[key] = array.length;
+ (array as string[]).push(key);
+ }
- return index;
- };
- }
+ return index;
}
+ |
321e157633e67e64102fe5e9f720cfddae74d335 | Foundation/HtmlClient/Foundation.ViewModel.HtmlClient/Implementations/defaultDateTimeService.ts | Foundation/HtmlClient/Foundation.ViewModel.HtmlClient/Implementations/defaultDateTimeService.ts | module Foundation.ViewModel.Implementations {
@Core.Injectable()
export class DefaultDateTimeService implements Contracts.IDateTimeService {
public constructor( @Core.Inject("ClientAppProfileManager") public clientAppProfileManager: Core.ClientAppProfileManager) {
}
public getFormattedDate(date?: Date, culture?: string): string {
if (date == null)
return null;
date = this.parseDate(date);
culture = culture == null ? this.clientAppProfileManager.getClientAppProfile().culture : culture;
if (culture == "FaIr") {
return persianDate(date).format('YYYY/MM/DD') as string;
}
else {
return kendo.toString(date, "yyyy/dd/MM");
}
}
public getFormattedDateTime(date?: Date, culture?: string): string {
if (date == null)
return null;
date = this.parseDate(date);
culture = culture == null ? this.clientAppProfileManager.getClientAppProfile().culture : culture;
if (culture == "FaIr") {
return persianDate(date).format('DD MMMM YYYY, hh:mm a') as string;
}
else {
return kendo.toString(date, "yyyy/dd/MM, hh:mm tt");
}
}
public getCurrentDate(): Date {
return new Date();
}
public parseDate(date: any): Date {
return kendo.parseDate(date);
}
}
} | module Foundation.ViewModel.Implementations {
@Core.Injectable()
export class DefaultDateTimeService implements Contracts.IDateTimeService {
public constructor( @Core.Inject("ClientAppProfileManager") public clientAppProfileManager: Core.ClientAppProfileManager) {
}
public getFormattedDate(date?: Date, culture?: string): string {
if (date == null)
return null;
date = this.parseDate(date);
culture = culture == null ? this.clientAppProfileManager.getClientAppProfile().culture : culture;
if (culture == "FaIr") {
return persianDate(date).format('YYYY/MM/DD') as string;
}
else {
return kendo.toString(date, "yyyy/dd/MM");
}
}
public getFormattedDateTime(date?: Date, culture?: string): string {
if (date == null)
return null;
date = this.parseDate(date);
culture = culture == null ? this.clientAppProfileManager.getClientAppProfile().culture : culture;
if (culture == "FaIr") {
return persianDate(date).format('DD MMMM YYYY, hh:mm a') as string;
}
else {
return kendo.toString(date, "yyyy/dd/MM, hh:mm tt");
}
}
public getCurrentDate(): Date {
return new Date();
}
public parseDate(date: any): Date {
if (date == null)
return null;
return kendo.parseDate(date);
}
}
} | Return null for null object in date time service's parse method | Return null for null object in date time service's parse method
| TypeScript | mit | bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework | ---
+++
@@ -45,6 +45,8 @@
}
public parseDate(date: any): Date {
+ if (date == null)
+ return null;
return kendo.parseDate(date);
}
|
e36c8883231276a41e877c7a87e1bfe2bb0db1ce | application/confagrid-frontend/src/main/frontend/root/modules/main/views/intro/intro.component.ts | application/confagrid-frontend/src/main/frontend/root/modules/main/views/intro/intro.component.ts | /*
* intro.component.ts
*
* Copyright (C) 2017-2018 [ A Legge Up ]
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
import { Component, Inject, OnInit, AfterViewInit } from '@angular/core';
import { AuthenticationService } from '../../services/authentication.service';
import { BrowserStorageService } from '../../services/browser-storage.service';
@Component({
selector: 'app-intro-content',
templateUrl: './intro.component.html',
styleUrls: ['./intro.component.css']
})
export class IntroComponent implements OnInit, AfterViewInit {
title = 'Confagrid';
subtitle = 'Word Grid Generator';
constructor(private authenticationService: AuthenticationService, private browserStorageService: BrowserStorageService) {
}
ngOnInit() {
}
ngAfterViewInit() {
if (this.browserStorageService.getString('token')) {
this.authenticationService.currentToken = this.browserStorageService.getString('token');
}
this.authenticationService.check()
.subscribe(data => console.log(data));
}
}
| /*
* intro.component.ts
*
* Copyright (C) 2017-2018 [ A Legge Up ]
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
import { Component, Inject, OnInit, AfterViewInit } from '@angular/core';
import { AuthenticationService } from '../../services/authentication.service';
import { BrowserStorageService } from '../../services/browser-storage.service';
@Component({
selector: 'app-intro-content',
templateUrl: './intro.component.html',
styleUrls: ['./intro.component.css']
})
export class IntroComponent implements OnInit, AfterViewInit {
title = 'Confagrid';
subtitle = 'Word Grid Generator';
constructor(private authenticationService: AuthenticationService, private browserStorageService: BrowserStorageService) {
}
ngOnInit() {
}
ngAfterViewInit() {
if (this.browserStorageService.getString('token')) {
this.authenticationService.currentToken = this.browserStorageService.getString('token');
this.authenticationService.check()
.subscribe(data => {
if (data.token !== this.authenticationService.currentToken) {
console.log('token has changed: ' + data);
this.authenticationService.currentToken = data.token;
}
}
);
}
}
}
| Set auth token if a different one is returned | Set auth token if a different one is returned
| TypeScript | mit | ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid | ---
+++
@@ -30,8 +30,15 @@
ngAfterViewInit() {
if (this.browserStorageService.getString('token')) {
this.authenticationService.currentToken = this.browserStorageService.getString('token');
+
+ this.authenticationService.check()
+ .subscribe(data => {
+ if (data.token !== this.authenticationService.currentToken) {
+ console.log('token has changed: ' + data);
+ this.authenticationService.currentToken = data.token;
+ }
+ }
+ );
}
- this.authenticationService.check()
- .subscribe(data => console.log(data));
}
} |
9ba6b6667922d245f678aadbdb2c0cc1d2afdae3 | index.d.ts | index.d.ts | import type {Root} from 'mdast'
import type {ReactElement} from 'react'
import type {Plugin} from 'unified'
import type {Options} from './lib/index.js'
/**
* Plugin to compile to React
*
* @param options
* Configuration.
*/
// Note: defining all react nodes as result value seems to trip TS up.
const remarkReact: Plugin<[Options], Root, ReactElement<unknown>>
export default remarkReact
export type {Options}
| import type {Root} from 'mdast'
import type {ReactElement} from 'react'
import type {Plugin} from 'unified'
import type {Options} from './lib/index.js'
/**
* Plugin to compile to React
*
* @param options
* Configuration.
*/
// Note: defining all react nodes as result value seems to trip TS up.
declare const remarkReact: Plugin<[Options], Root, ReactElement<unknown>>
export default remarkReact
export type {Options}
| Fix parse warning in types | Fix parse warning in types
| TypeScript | mit | mapbox/mdast-react,mapbox/remark-react,mapbox/remark-react,mapbox/mdast-react | ---
+++
@@ -10,6 +10,6 @@
* Configuration.
*/
// Note: defining all react nodes as result value seems to trip TS up.
-const remarkReact: Plugin<[Options], Root, ReactElement<unknown>>
+declare const remarkReact: Plugin<[Options], Root, ReactElement<unknown>>
export default remarkReact
export type {Options} |
2735af754f160564b70c0eb64a9f151aef4ffdc9 | src/attach/attach.ts | src/attach/attach.ts | import { createConnection } from 'net';
import child from 'child_process';
import { NeovimClient } from './../api/client';
import { logger } from '../utils/logger';
export interface Attach {
reader?: NodeJS.ReadableStream;
writer?: NodeJS.WritableStream;
proc?: NodeJS.Process | child.ChildProcess;
socket?: string;
}
export function attach({
reader: _reader,
writer: _writer,
proc,
socket,
}: Attach) {
let writer;
let reader;
logger.debug('proc');
logger.debug(proc);
if (socket) {
const client = createConnection(socket);
writer = client;
reader = client;
} else if (_reader && _writer) {
writer = _writer;
reader = _reader;
} else if (proc) {
writer = proc.stdin;
reader = proc.stdout;
}
if (writer && reader) {
const neovim = new NeovimClient({ logger });
neovim.attachSession({
writer,
reader,
});
return neovim;
}
throw new Error('Invalid arguments, could not attach');
}
| import { createConnection } from 'net';
import * as child from 'child_process';
import { NeovimClient } from './../api/client';
import { logger } from '../utils/logger';
export interface Attach {
reader?: NodeJS.ReadableStream;
writer?: NodeJS.WritableStream;
proc?: NodeJS.Process | child.ChildProcess;
socket?: string;
}
export function attach({
reader: _reader,
writer: _writer,
proc,
socket,
}: Attach) {
let writer;
let reader;
logger.debug('proc');
logger.debug(proc);
if (socket) {
const client = createConnection(socket);
writer = client;
reader = client;
} else if (_reader && _writer) {
writer = _writer;
reader = _reader;
} else if (proc) {
writer = proc.stdin;
reader = proc.stdout;
}
if (writer && reader) {
const neovim = new NeovimClient({ logger });
neovim.attachSession({
writer,
reader,
});
return neovim;
}
throw new Error('Invalid arguments, could not attach');
}
| Fix child_process imported as default import | Fix child_process imported as default import
| TypeScript | mit | rhysd/node-client,neovim/node-client,neovim/node-client | ---
+++
@@ -1,5 +1,5 @@
import { createConnection } from 'net';
-import child from 'child_process';
+import * as child from 'child_process';
import { NeovimClient } from './../api/client';
import { logger } from '../utils/logger'; |
9285c6c16723ebb34c9d68d3f063f24ca6e2879f | src/definitions/Views.ts | src/definitions/Views.ts | import * as ViewsDirectory from "../definitions/ViewsDirectory";
import {ResponseBody} from "./Common";
import {ResponseModel} from "./Handler";
export class View {
constructor(id: string, render: RendersResponse) {
this.id = id;
this.render = render;
ViewsDirectory[id] = this;
}
id: string;
render: RendersResponse;
}
export interface RendersResponse {
(model: ResponseModel): ResponseBody | Promise<ResponseBody>;
} | import * as ViewsDirectory from "../definitions/ViewsDirectory";
import {BotFrameworkActivity} from "./BotFrameworkService";
import {ResponseBody} from "./Common";
import {ResponseModel} from "./Handler";
export class View {
constructor(id: string, render: RendersResponse) {
this.id = id;
this.render = render;
ViewsDirectory[id] = this;
}
id: string;
render: RendersResponse;
}
export interface RendersResponse {
(model: ResponseModel, request?: BotFrameworkActivity): ResponseBody | Promise<ResponseBody>;
} | Add optional parameter for bot framework requests. | Add optional parameter for bot framework requests.
| TypeScript | agpl-3.0 | deegles/cookietime,deegles/cookietime | ---
+++
@@ -1,4 +1,5 @@
import * as ViewsDirectory from "../definitions/ViewsDirectory";
+import {BotFrameworkActivity} from "./BotFrameworkService";
import {ResponseBody} from "./Common";
import {ResponseModel} from "./Handler";
@@ -16,5 +17,5 @@
}
export interface RendersResponse {
- (model: ResponseModel): ResponseBody | Promise<ResponseBody>;
+ (model: ResponseModel, request?: BotFrameworkActivity): ResponseBody | Promise<ResponseBody>;
} |
35c217ab6ab9da060069cf298343f4e28fc51968 | app/src/ui/preferences/advanced.tsx | app/src/ui/preferences/advanced.tsx | import * as React from 'react'
import { DialogContent } from '../dialog'
import { Checkbox, CheckboxValue } from '../lib/checkbox'
import { LinkButton } from '../lib/link-button'
interface IAdvancedPreferencesProps {
readonly isOptedOut: boolean,
readonly onOptOutSet: (checked: boolean) => void
}
interface IAdvancedPreferencesState {
readonly reportingOptOut: boolean
}
const SamplesURL = 'https://desktop.github.com/samples/'
export class Advanced extends React.Component<IAdvancedPreferencesProps, IAdvancedPreferencesState> {
public constructor(props: IAdvancedPreferencesProps) {
super(props)
this.state = {
reportingOptOut: this.props.isOptedOut,
}
}
private onChange = (event: React.FormEvent<HTMLInputElement>) => {
const value = !event.currentTarget.checked
this.setState({ reportingOptOut: value })
this.props.onOptOutSet(value)
}
public render() {
return (
<DialogContent>
<div>
Would you like to help us improve GitHub Desktop by periodically submitting <LinkButton uri={SamplesURL}>anonymous usage data</LinkButton>?
</div>
<br />
<Checkbox
label='Yes, submit anonymized usage data'
value={this.state.reportingOptOut ? CheckboxValue.Off : CheckboxValue.On}
onChange={this.onChange} />
</DialogContent>
)
}
}
| import * as React from 'react'
import { DialogContent } from '../dialog'
import { Checkbox, CheckboxValue } from '../lib/checkbox'
import { LinkButton } from '../lib/link-button'
interface IAdvancedPreferencesProps {
readonly isOptedOut: boolean,
readonly confirmRepoRemoval: boolean,
readonly onOptOutSet: (checked: boolean) => void
readonly onConfirmRepoRemovalSet: (checked: boolean) => void
}
interface IAdvancedPreferencesState {
readonly reportingOptOut: boolean
}
const SamplesURL = 'https://desktop.github.com/samples/'
export class Advanced extends React.Component<IAdvancedPreferencesProps, IAdvancedPreferencesState> {
public constructor(props: IAdvancedPreferencesProps) {
super(props)
this.state = {
reportingOptOut: this.props.isOptedOut,
}
}
private onChange = (event: React.FormEvent<HTMLInputElement>) => {
const value = !event.currentTarget.checked
this.setState({ reportingOptOut: value })
this.props.onOptOutSet(value)
}
public render() {
return (
<DialogContent>
<div>
Would you like to help us improve GitHub Desktop by periodically submitting <LinkButton uri={SamplesURL}>anonymous usage data</LinkButton>?
</div>
<br />
<Checkbox
label='Yes, submit anonymized usage data'
value={this.state.reportingOptOut ? CheckboxValue.Off : CheckboxValue.On}
onChange={this.onChange} />
</DialogContent>
)
}
}
| Add props to support repo removal confirmation | Add props to support repo removal confirmation
| TypeScript | mit | kactus-io/kactus,hjobrien/desktop,desktop/desktop,j-f1/forked-desktop,gengjiawen/desktop,shiftkey/desktop,hjobrien/desktop,hjobrien/desktop,gengjiawen/desktop,desktop/desktop,desktop/desktop,desktop/desktop,gengjiawen/desktop,say25/desktop,kactus-io/kactus,BugTesterTest/desktops,gengjiawen/desktop,artivilla/desktop,hjobrien/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,BugTesterTest/desktops,artivilla/desktop,BugTesterTest/desktops,say25/desktop,BugTesterTest/desktops,shiftkey/desktop,say25/desktop,shiftkey/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus | ---
+++
@@ -5,7 +5,9 @@
interface IAdvancedPreferencesProps {
readonly isOptedOut: boolean,
+ readonly confirmRepoRemoval: boolean,
readonly onOptOutSet: (checked: boolean) => void
+ readonly onConfirmRepoRemovalSet: (checked: boolean) => void
}
interface IAdvancedPreferencesState { |
bc15aef5706d32579cc657cffc20f121e0aad861 | tests/unit/mixins/createParentMixin.ts | tests/unit/mixins/createParentMixin.ts | import * as registerSuite from 'intern!object';
import * as assert from 'intern/chai!assert';
import createParentMixin from 'src/mixins/createParentMixin';
registerSuite({
name: 'mixins/createParentMixin',
creation() {
const parent = createParentMixin();
assert.isFunction(parent.append);
assert.isFunction(parent.insert);
assert.isObject(parent.children);
}
});
| import * as registerSuite from 'intern!object';
import * as assert from 'intern/chai!assert';
import createParentMixin from 'src/mixins/createParentMixin';
import createRenderable from 'src/mixins/createRenderable';
import { List } from 'immutable/immutable';
registerSuite({
name: 'mixins/createParentMixin',
creation() {
const parent = createParentMixin();
assert.isFunction(parent.append);
assert.isFunction(parent.insert);
assert.isObject(parent.children);
},
'on("childlist")': {
'append()'() {
const dfd = this.async();
const parent = createParentMixin();
const child = createRenderable();
parent.on('childlist', dfd.callback((event: any) => {
assert.strictEqual(event.type, 'childlist');
assert.strictEqual(event.target, parent);
assert.strictEqual(event.children, parent.children);
assert.isTrue(event.children.equals(List([ child ])));
}));
parent.append(child);
}
}
});
| Add initial test for 'childlist' event | Add initial test for 'childlist' event
| TypeScript | bsd-3-clause | edhager/widget-core,edhager/widget-core,edhager/widget-core,edhager/widget-core | ---
+++
@@ -1,6 +1,8 @@
import * as registerSuite from 'intern!object';
import * as assert from 'intern/chai!assert';
import createParentMixin from 'src/mixins/createParentMixin';
+import createRenderable from 'src/mixins/createRenderable';
+import { List } from 'immutable/immutable';
registerSuite({
name: 'mixins/createParentMixin',
@@ -9,5 +11,20 @@
assert.isFunction(parent.append);
assert.isFunction(parent.insert);
assert.isObject(parent.children);
+ },
+ 'on("childlist")': {
+ 'append()'() {
+ const dfd = this.async();
+ const parent = createParentMixin();
+ const child = createRenderable();
+ parent.on('childlist', dfd.callback((event: any) => {
+ assert.strictEqual(event.type, 'childlist');
+ assert.strictEqual(event.target, parent);
+ assert.strictEqual(event.children, parent.children);
+ assert.isTrue(event.children.equals(List([ child ])));
+ }));
+
+ parent.append(child);
+ }
}
}); |
4c8ace776f24d34122fd23b5b03efb5f2824089b | lib.d.ts | lib.d.ts | declare module "time-since" {
export interface timeSince {
since: {
millis: number;
secs: number;
mins: number;
hours: number;
days: number;
weeks: number;
};
}
}
| declare module "time-since" {
export function since (timestamp: Date): {
"millis": ()=>number,
"secs": ()=>number,
"mins": ()=>number,
"hours": ()=>number,
"days": ()=>number,
"weeks": ()=>number,
}
} | Change types to anonymous functions that return number | Change types to anonymous functions that return number | TypeScript | apache-2.0 | tombailey/Time-Since | ---
+++
@@ -1,12 +1,10 @@
declare module "time-since" {
- export interface timeSince {
- since: {
- millis: number;
- secs: number;
- mins: number;
- hours: number;
- days: number;
- weeks: number;
- };
- }
+ export function since (timestamp: Date): {
+ "millis": ()=>number,
+ "secs": ()=>number,
+ "mins": ()=>number,
+ "hours": ()=>number,
+ "days": ()=>number,
+ "weeks": ()=>number,
}
+} |
101d3ad633d7baa7edea9cfd6bed2d65fd44ee6f | src/customer/details/CustomerMarketplacePanel.tsx | src/customer/details/CustomerMarketplacePanel.tsx | import { FunctionComponent } from 'react';
import { translate } from '@waldur/i18n';
import { ServiceProviderManagement } from '@waldur/marketplace/service-providers/ServiceProviderManagement';
export const CustomerMarketplacePanel: FunctionComponent = () => (
<div className="highlight">
<h3>{translate('Marketplace service provider')}</h3>
<p>
{translate(
'You can register organization as a marketplace service provider by pressing the button below',
)}
</p>
<ServiceProviderManagement />
</div>
);
| import { FunctionComponent } from 'react';
import { useSelector } from 'react-redux';
import { translate } from '@waldur/i18n';
import { ServiceProviderManagement } from '@waldur/marketplace/service-providers/ServiceProviderManagement';
import { getCustomer } from '@waldur/workspace/selectors';
export const CustomerMarketplacePanel: FunctionComponent = () => {
const customer = useSelector(getCustomer);
return (
<div className="highlight">
<h3>{translate('Marketplace service provider')}</h3>
{!customer.is_service_provider && (
<p>
{translate(
'You can register organization as a marketplace service provider by pressing the button below',
)}
</p>
)}
<ServiceProviderManagement />
</div>
);
};
| Call for registration should not be shown for a registered service provider | Call for registration should not be shown for a registered service provider
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -1,16 +1,23 @@
import { FunctionComponent } from 'react';
+import { useSelector } from 'react-redux';
import { translate } from '@waldur/i18n';
import { ServiceProviderManagement } from '@waldur/marketplace/service-providers/ServiceProviderManagement';
+import { getCustomer } from '@waldur/workspace/selectors';
-export const CustomerMarketplacePanel: FunctionComponent = () => (
- <div className="highlight">
- <h3>{translate('Marketplace service provider')}</h3>
- <p>
- {translate(
- 'You can register organization as a marketplace service provider by pressing the button below',
+export const CustomerMarketplacePanel: FunctionComponent = () => {
+ const customer = useSelector(getCustomer);
+ return (
+ <div className="highlight">
+ <h3>{translate('Marketplace service provider')}</h3>
+ {!customer.is_service_provider && (
+ <p>
+ {translate(
+ 'You can register organization as a marketplace service provider by pressing the button below',
+ )}
+ </p>
)}
- </p>
- <ServiceProviderManagement />
- </div>
-);
+ <ServiceProviderManagement />
+ </div>
+ );
+}; |
87f0d482ebd840d299428244826169f3566b9d74 | types/next/app.d.ts | types/next/app.d.ts | import * as React from "react";
import { NextContext } from ".";
import { SingletonRouter } from "./router";
export interface AppComponentProps {
Component: React.ComponentType<any>;
pageProps: any;
}
export interface AppComponentContext {
Component: React.ComponentType<any>;
router: SingletonRouter;
ctx: NextContext;
}
export class Container extends React.Component {}
export default class App<TProps = {}> extends React.Component<TProps & AppComponentProps> {}
| import * as React from "react";
import { NextContext } from ".";
import { RouterProps } from "./router";
export interface AppComponentProps {
Component: React.ComponentType<any>;
pageProps: any;
}
export interface AppComponentContext {
Component: React.ComponentType<any>;
router: RouterProps;
ctx: NextContext;
}
export class Container extends React.Component {}
export default class App<TProps = {}> extends React.Component<TProps & AppComponentProps> {}
| Fix wrong router Type in app | Fix wrong router Type in app
| TypeScript | mit | borisyankov/DefinitelyTyped,markogresak/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,mcliment/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped | ---
+++
@@ -1,6 +1,6 @@
import * as React from "react";
import { NextContext } from ".";
-import { SingletonRouter } from "./router";
+import { RouterProps } from "./router";
export interface AppComponentProps {
Component: React.ComponentType<any>;
@@ -9,7 +9,7 @@
export interface AppComponentContext {
Component: React.ComponentType<any>;
- router: SingletonRouter;
+ router: RouterProps;
ctx: NextContext;
}
|
c95e6d8b683dbe2d4f04e219d1c86dea5990fb70 | Clients/webfrontauth-ngx/projects/webfrontauth-ngx/src/lib/AuthServiceClientConfiguration.ts | Clients/webfrontauth-ngx/projects/webfrontauth-ngx/src/lib/AuthServiceClientConfiguration.ts | import { IAuthServiceConfiguration, IEndPoint } from '@signature/webfrontauth';
/**
* WebFrontAuth configuration class.
*
* @export
*/
export class AuthServiceClientConfiguration implements IAuthServiceConfiguration {
/**
* Creates an instance of AuthServiceClientConfiguration using the provided login route and endpoint.
* @param identityEndPoint The identity endpoint to use in WebFrontAuth
* @param [loginPath='/login'] The route path WebFrontAuth should redirect to when authentication is required.
*/
constructor(
public readonly identityEndPoint: IEndPoint,
public readonly loginPath: string = '/login'
) {
}
}
/**
* Creates an instance of AuthServiceClientConfiguration using the specified login route,
* and the current host as identity endpoint.
*
* @export
* @param [loginPath='/login'] The route path WebFrontAuth should redirect to when authentication is required.
*/
export function createAuthConfigUsingCurrentHost(
loginPath: string = '/login'
): AuthServiceClientConfiguration {
const isHttps = window.location.protocol.toLowerCase() === 'https:';
const identityEndPoint: IEndPoint = {
hostname: window.location.hostname,
port: window.location.port
? Number(window.location.port)
: isHttps
? 443
: 80,
disableSsl: !isHttps
};
return new AuthServiceClientConfiguration(identityEndPoint, loginPath);
}
| import { IAuthServiceConfiguration, IEndPoint } from '@signature/webfrontauth';
/**
* WebFrontAuth configuration class.
*
* @export
*/
export class AuthServiceClientConfiguration implements IAuthServiceConfiguration {
/**
* Creates an instance of AuthServiceClientConfiguration using the provided login route and endpoint.
* @param identityEndPoint The identity endpoint to use in WebFrontAuth
* @param [loginPath='/login'] The route path WebFrontAuth should redirect to when authentication is required.
*/
constructor(
public readonly identityEndPoint: IEndPoint,
public readonly loginPath: string = '/login'
) {
}
}
/**
* Creates an instance of AuthServiceClientConfiguration using the specified login route,
* and the current host as identity endpoint.
*
* @export
* @param [loginPath='/login'] The route path WebFrontAuth should redirect to when authentication is required.
*/
export function createAuthConfigUsingCurrentHost(
loginPath: string = '/login'
): AuthServiceClientConfiguration {
const isHttps = window.location.protocol.toLowerCase() === 'https:';
const identityEndPoint: IEndPoint = {
hostname: window.location.hostname,
port: window.location.port
? Number(window.location.port)
: undefined,
disableSsl: !isHttps
};
return new AuthServiceClientConfiguration(identityEndPoint, loginPath);
}
| Fix wfa-ngx specifying default port when it shouldn't in createAuthConfigUsingCurrentHost() | Fix wfa-ngx specifying default port when it shouldn't in createAuthConfigUsingCurrentHost()
| TypeScript | mit | Invenietis/CK-AspNet-Auth,Invenietis/CK-AspNet-Auth,Invenietis/CK-AspNet-Auth,Invenietis/CK-AspNet-Auth | ---
+++
@@ -33,9 +33,7 @@
hostname: window.location.hostname,
port: window.location.port
? Number(window.location.port)
- : isHttps
- ? 443
- : 80,
+ : undefined,
disableSsl: !isHttps
};
return new AuthServiceClientConfiguration(identityEndPoint, loginPath); |
8e7a1c9c65c3259ceff2d6f0f8c37560674b64c8 | src/mlkit/imagelabeling/imagelabeling-common.ts | src/mlkit/imagelabeling/imagelabeling-common.ts | import { Property } from "tns-core-modules/ui/core/properties";
import { MLKitCameraView } from "../mlkit-cameraview";
export const confidenceThresholdProperty = new Property<MLKitImageLabeling, number>({
name: "confidenceThreshold",
defaultValue: 0.5,
});
export abstract class MLKitImageLabeling extends MLKitCameraView {
static scanResultEvent: string = "scanResult";
protected confidenceThreshold: number;
[confidenceThresholdProperty.setNative](value: number) {
this.confidenceThreshold = value;
}
}
confidenceThresholdProperty.register(MLKitImageLabeling);
| import { Property } from "tns-core-modules/ui/core/properties";
import { MLKitCameraView } from "../mlkit-cameraview";
export const confidenceThresholdProperty = new Property<MLKitImageLabeling, number>({
name: "confidenceThreshold",
defaultValue: 0.5,
});
export abstract class MLKitImageLabeling extends MLKitCameraView {
static scanResultEvent: string = "scanResult";
protected confidenceThreshold: number;
[confidenceThresholdProperty.setNative](value: any) {
this.confidenceThreshold = parseFloat(value);
}
}
confidenceThresholdProperty.register(MLKitImageLabeling);
| Make sure this is numeric | Make sure this is numeric
| TypeScript | mit | EddyVerbruggen/nativescript-plugin-firebase,EddyVerbruggen/nativescript-plugin-firebase,EddyVerbruggen/nativescript-plugin-firebase,EddyVerbruggen/nativescript-plugin-firebase,EddyVerbruggen/nativescript-plugin-firebase,EddyVerbruggen/nativescript-plugin-firebase | ---
+++
@@ -11,8 +11,8 @@
protected confidenceThreshold: number;
- [confidenceThresholdProperty.setNative](value: number) {
- this.confidenceThreshold = value;
+ [confidenceThresholdProperty.setNative](value: any) {
+ this.confidenceThreshold = parseFloat(value);
}
}
|
d5f9b28a988e30d97504f70a2eafcc6b9d4f488a | index.ts | index.ts | require('dotenv').load();
// Export the module from the base level for ease of use
export { Hue } from './src/hue-node';
export * from './src/hue-interfaces';
| // Export the module from the base level for ease of use
export { Hue } from './src/hue-node';
export * from './src/hue-interfaces';
| Remove usage of removed dependency | Remove usage of removed dependency
| TypeScript | mit | bjohnso5/hue-hacking-npm,bjohnso5/hue-hacking-npm | ---
+++
@@ -1,5 +1,3 @@
-require('dotenv').load();
-
// Export the module from the base level for ease of use
export { Hue } from './src/hue-node';
export * from './src/hue-interfaces'; |
cfacefe922f0a7657e23a80bdd0dc90baf7f41fe | src/app/modules/zone/zone.module.ts | src/app/modules/zone/zone.module.ts | import { FormsModule } from '@angular/forms';
import { MdIconModule, MdButtonModule, MdMenuModule, MdSlideToggleModule, MdDialogModule, MdInputModule } from '@angular/material';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SharedModule } from '../shared/shared.module';
import { ZoneMessageModule } from './../zone-message/zone-message.module';
/* Components */
import { ZoneComponent } from './zone.component';
import { AddResultDialogComponent } from './add-result.dialog.component';
const routes: Routes = [
{ path: '', component: ZoneComponent }
]
@NgModule({
imports: [
SharedModule,
RouterModule.forChild(routes),
FormsModule,
MdIconModule,
MdButtonModule,
MdMenuModule,
MdSlideToggleModule,
MdDialogModule,
MdInputModule,
ZoneMessageModule
],
declarations: [
ZoneComponent,
AddResultDialogComponent
],
entryComponents: [
AddResultDialogComponent
]
})
export class ZoneModule {} | import { FormsModule } from '@angular/forms';
import { MdIconModule, MdButtonModule, MdMenuModule, MdSlideToggleModule, MdDialogModule, MdInputModule, MdCheckboxModule } from '@angular/material';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SharedModule } from '../shared/shared.module';
import { ZoneMessageModule } from './../zone-message/zone-message.module';
/* Components */
import { ZoneComponent } from './zone.component';
import { AddResultDialogComponent } from './add-result.dialog.component';
const routes: Routes = [
{ path: '', component: ZoneComponent }
]
@NgModule({
imports: [
SharedModule,
RouterModule.forChild(routes),
FormsModule,
MdIconModule,
MdButtonModule,
MdMenuModule,
MdSlideToggleModule,
MdDialogModule,
MdInputModule,
MdCheckboxModule,
ZoneMessageModule
],
declarations: [
ZoneComponent,
AddResultDialogComponent
],
entryComponents: [
AddResultDialogComponent
]
})
export class ZoneModule {} | Add drop solution on result | Add drop solution on result
| TypeScript | mit | AurelieV/end-of-round,AurelieV/end-of-round,AurelieV/end-of-round | ---
+++
@@ -1,5 +1,5 @@
import { FormsModule } from '@angular/forms';
-import { MdIconModule, MdButtonModule, MdMenuModule, MdSlideToggleModule, MdDialogModule, MdInputModule } from '@angular/material';
+import { MdIconModule, MdButtonModule, MdMenuModule, MdSlideToggleModule, MdDialogModule, MdInputModule, MdCheckboxModule } from '@angular/material';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
@@ -25,6 +25,7 @@
MdSlideToggleModule,
MdDialogModule,
MdInputModule,
+ MdCheckboxModule,
ZoneMessageModule
],
declarations: [ |
02e629308fcf80f45bbc4fe9ebcab3e6ad847220 | src/websockets/interfaces/index.ts | src/websockets/interfaces/index.ts | export * from './gateway-metadata.interface';
export * from './nest-gateway.interface';
export * from './observable-socket-server.interface';
export * from './web-socket-server.interface';
export * from './on-gateway-init.interface';
export * from './on-gateway-connection.interface';
export * from './on-gateway-disconnect.interface'; | export * from './gateway-metadata.interface';
export * from './nest-gateway.interface';
export * from './observable-socket-server.interface';
export * from './web-socket-server.interface';
export * from './on-gateway-init.interface';
export * from './on-gateway-connection.interface';
export * from './on-gateway-disconnect.interface';
export * from './gateway-middleware.interface'; | Fix gateway middleware interface export | Fix gateway middleware interface export
| TypeScript | mit | kamilmysliwiec/nest,kamilmysliwiec/nest | ---
+++
@@ -5,3 +5,4 @@
export * from './on-gateway-init.interface';
export * from './on-gateway-connection.interface';
export * from './on-gateway-disconnect.interface';
+export * from './gateway-middleware.interface'; |
9c1999acf0b4b9e0d4a427d050e33c4d2fb7cfbb | src/testing/support/elementsAreEqual.ts | src/testing/support/elementsAreEqual.ts | const {assert} = intern.getPlugin('chai')
/**
* Check if two HTML or SVG elements are exactly equal.
*/
export function elementsAreEqual(actual: Element, expected: Element): void {
assert.notEqual(actual, expected, `trying to test if an element is equal to itself (tag <${actual.tagName}>)`)
assert.isNotEmpty(actual.outerHTML, `the HTML of the created element is empty (tag <${actual.tagName}>)`)
assert.strictEqual(actual.outerHTML, expected.outerHTML, `the HTML of the two elements created is different (tag <${actual.tagName}>)`)
assert.isTrue(actual.isEqualNode(expected), `elements are not deeply equal (tag <${actual.tagName}>)`)
} | const {assert} = intern.getPlugin('chai')
/**
* Check if two HTML or SVG elements are exactly equal.
*/
export function elementsAreEqual(actual: Element, expected: Element, skipDeepEquality = false): void {
assert.notEqual(actual, expected, `trying to test if an element is equal to itself (tag <${actual.tagName}>)`)
assert.isNotEmpty(actual.outerHTML, `the HTML of the created element is empty (tag <${actual.tagName}>)`)
assert.strictEqual(actual.outerHTML, expected.outerHTML, `the HTML of the two elements created is different (tag <${actual.tagName}>)`)
if (!skipDeepEquality) {
assert.isTrue(actual.isEqualNode(expected), `elements are not deeply equal (tag <${actual.tagName}>)`)
}
} | Allow skipping native deep equality check | Allow skipping native deep equality check
| TypeScript | agpl-3.0 | inad9300/Soil,inad9300/Soil | ---
+++
@@ -3,9 +3,11 @@
/**
* Check if two HTML or SVG elements are exactly equal.
*/
-export function elementsAreEqual(actual: Element, expected: Element): void {
+export function elementsAreEqual(actual: Element, expected: Element, skipDeepEquality = false): void {
assert.notEqual(actual, expected, `trying to test if an element is equal to itself (tag <${actual.tagName}>)`)
assert.isNotEmpty(actual.outerHTML, `the HTML of the created element is empty (tag <${actual.tagName}>)`)
assert.strictEqual(actual.outerHTML, expected.outerHTML, `the HTML of the two elements created is different (tag <${actual.tagName}>)`)
- assert.isTrue(actual.isEqualNode(expected), `elements are not deeply equal (tag <${actual.tagName}>)`)
+ if (!skipDeepEquality) {
+ assert.isTrue(actual.isEqualNode(expected), `elements are not deeply equal (tag <${actual.tagName}>)`)
+ }
} |
a489439b12225b93e4d5b5784498b78e11a597fb | step-release-vis/src/app/components/form/dataSubmissionForm.ts | step-release-vis/src/app/components/form/dataSubmissionForm.ts | import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './dataSubmissionForm.html',
styleUrls: ['./dataSubmissionForm.css'],
})
export class DataSubmissionFormComponent implements OnInit {
dataForm: FormGroup;
file: File;
constructor(private router: Router) {
this.dataForm = new FormGroup({
file: new FormControl(null),
text: new FormControl(''),
});
}
ngOnInit(): void {}
onFileChange(event): void {
this.file = event.target.files[0];
}
onSubmit(): void {
if (this.dataForm.value.text) {
window.localStorage.setItem('data', this.dataForm.value.text);
} else {
const fileReader: FileReader = new FileReader();
fileReader.onload = event => {
window.localStorage.setItem('data', event.target.result.toString());
};
fileReader.readAsText(this.file);
}
this.router.navigate(['env']);
}
}
| import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './dataSubmissionForm.html',
styleUrls: ['./dataSubmissionForm.css'],
})
export class DataSubmissionFormComponent implements OnInit {
dataForm: FormGroup;
file: File = null;
constructor(private router: Router) {
this.dataForm = new FormGroup({
file: new FormControl(null),
text: new FormControl(''),
});
}
ngOnInit(): void {}
onFileChange(event): void {
this.file = event.target.files[0];
}
onSubmit(): void {
if (!this.dataForm.value.text && this.file == null) {
window.alert(
'Both fields are empty!\nPlease select a file or paste the data in the text box!'
);
return;
}
if (this.dataForm.value.text) {
window.localStorage.setItem('data', this.dataForm.value.text);
} else {
const fileReader: FileReader = new FileReader();
fileReader.onload = event => {
window.localStorage.setItem('data', event.target.result.toString());
};
fileReader.readAsText(this.file);
}
this.router.navigate(['env']);
}
}
| Add alert if both fields are empty. | Add alert if both fields are empty.
| TypeScript | apache-2.0 | googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020 | ---
+++
@@ -9,7 +9,7 @@
})
export class DataSubmissionFormComponent implements OnInit {
dataForm: FormGroup;
- file: File;
+ file: File = null;
constructor(private router: Router) {
this.dataForm = new FormGroup({
@@ -25,6 +25,13 @@
}
onSubmit(): void {
+ if (!this.dataForm.value.text && this.file == null) {
+ window.alert(
+ 'Both fields are empty!\nPlease select a file or paste the data in the text box!'
+ );
+ return;
+ }
+
if (this.dataForm.value.text) {
window.localStorage.setItem('data', this.dataForm.value.text);
} else { |
446aa35d97de0cb5bd8e4995b6dc8791118a30cc | src/flutter/capabilities.ts | src/flutter/capabilities.ts | import { versionIsAtLeast } from "../utils";
export class FlutterCapabilities {
public static get empty() { return new FlutterCapabilities("0.0.0"); }
public version: string;
constructor(flutterVersion: string) {
this.version = flutterVersion;
}
get supportsPidFileForMachine() { return versionIsAtLeast(this.version, "0.10.0"); }
get trackWidgetCreationDefault() { return versionIsAtLeast(this.version, "0.10.2-pre"); }
get supportsCreatingSamples() { return versionIsAtLeast(this.version, "1.0.0"); }
get supportsMultipleSamplesPerElement() { return versionIsAtLeast(this.version, "1.2.2"); }
get supportsDevTools() { return versionIsAtLeast(this.version, "1.1.0"); }
get hasTestGroupFix() { return versionIsAtLeast(this.version, "1.3.4"); } // TODO: Confirm this when Flutter fix lands
}
| import { versionIsAtLeast } from "../utils";
export class FlutterCapabilities {
public static get empty() { return new FlutterCapabilities("0.0.0"); }
public version: string;
constructor(flutterVersion: string) {
this.version = flutterVersion;
}
get supportsPidFileForMachine() { return versionIsAtLeast(this.version, "0.10.0"); }
get trackWidgetCreationDefault() { return versionIsAtLeast(this.version, "0.10.2-pre"); }
get supportsCreatingSamples() { return versionIsAtLeast(this.version, "1.0.0"); }
get supportsMultipleSamplesPerElement() { return versionIsAtLeast(this.version, "1.2.2"); }
get supportsDevTools() { return versionIsAtLeast(this.version, "1.1.0"); }
get hasTestGroupFix() { return versionIsAtLeast(this.version, "1.3.4"); }
}
| Remove TODO (version is correct) | Remove TODO (version is correct)
| TypeScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -14,5 +14,5 @@
get supportsCreatingSamples() { return versionIsAtLeast(this.version, "1.0.0"); }
get supportsMultipleSamplesPerElement() { return versionIsAtLeast(this.version, "1.2.2"); }
get supportsDevTools() { return versionIsAtLeast(this.version, "1.1.0"); }
- get hasTestGroupFix() { return versionIsAtLeast(this.version, "1.3.4"); } // TODO: Confirm this when Flutter fix lands
+ get hasTestGroupFix() { return versionIsAtLeast(this.version, "1.3.4"); }
} |
24a7d35313d619df6e4d9d2f944cf7d47d59f074 | src/helloWorld.component.ts | src/helloWorld.component.ts | import {
Component
} from '@angular/core';
@Component({
selector: 'hello-world',
template: 'Hello world from the {{ projectTitle }} module!'
})
export class HelloWorld {
projectTitle: string = 'weighted screen';
}
| import {
Component,
OnInit
} from '@angular/core';
import d3 from './d3';
@Component({
selector: 'hello-world',
template: 'Hello world from the {{ projectTitle }} module!'
})
export class HelloWorld implements OnInit {
projectTitle: string = 'weighted screen';
ngOnInit() {
d3.select("body").transition()
.style("background-color", "black");
}
}
| Add test code to try out imported d3 module | Add test code to try out imported d3 module
| TypeScript | mit | grow-design/weighted-screen,grow-design/weighted-screen | ---
+++
@@ -1,11 +1,19 @@
import {
- Component
+ Component,
+ OnInit
} from '@angular/core';
+
+import d3 from './d3';
@Component({
selector: 'hello-world',
template: 'Hello world from the {{ projectTitle }} module!'
})
-export class HelloWorld {
+export class HelloWorld implements OnInit {
projectTitle: string = 'weighted screen';
+
+ ngOnInit() {
+ d3.select("body").transition()
+ .style("background-color", "black");
+ }
} |
de396b2625e7276b821bcf966f84d83ba5e47469 | modules/interfaces/src/query-result.ts | modules/interfaces/src/query-result.ts | import { Entity } from "./entity";
import { GeneralUpdateOperation } from "sp2";
export type CustomQueryResult<QR extends Object = Object> = {
result: QR;
};
export type QueryResult<E extends Entity> = {
entities: E[];
versionsById: { [entityId: string]: string | null };
};
export type SingleQueryResult<E extends Entity> = {
entity: E;
versionId: string | null;
};
export type PullQueryResult<E extends Entity> =
| {
pulled: 1;
operations: GeneralUpdateOperation[];
versionId: string | null;
}
| SingleQueryResult<E>;
| import { Entity } from "./entity";
import { GeneralUpdateOperation } from "sp2";
export type CustomQueryResult<QR extends Object = Object> = {
result: QR;
};
export type QueryResult<E extends Entity = Entity> = {
entities: E[];
versionsById: { [entityId: string]: string | null };
};
export type SingleQueryResult<E extends Entity = Entity> = {
entity: E;
versionId: string | null;
};
export type PullQueryResult<E extends Entity = Entity> =
| {
pulled: 1;
operations: GeneralUpdateOperation[];
versionId: string | null;
}
| SingleQueryResult<E>;
| Add default types to QueryResults | Add default types to QueryResults
| TypeScript | apache-2.0 | phenyl-js/phenyl,phenyl-js/phenyl,phenyl-js/phenyl,phenyl-js/phenyl | ---
+++
@@ -5,17 +5,17 @@
result: QR;
};
-export type QueryResult<E extends Entity> = {
+export type QueryResult<E extends Entity = Entity> = {
entities: E[];
versionsById: { [entityId: string]: string | null };
};
-export type SingleQueryResult<E extends Entity> = {
+export type SingleQueryResult<E extends Entity = Entity> = {
entity: E;
versionId: string | null;
};
-export type PullQueryResult<E extends Entity> =
+export type PullQueryResult<E extends Entity = Entity> =
| {
pulled: 1;
operations: GeneralUpdateOperation[]; |
247fc04cbce882b71b0204039f04c71283e6087b | vscode-extensions/vscode-manifest-yaml/lib/Main.ts | vscode-extensions/vscode-manifest-yaml/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-manifest-yaml',
launcher: (context: VSCode.ExtensionContext) => Path.resolve(context.extensionPath, 'jars/language-server.jar'),
jvmHeap: '64m',
clientOptions: {
documentSelector: ["manifest-yaml"]
}
};
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-manifest-yaml',
jvmHeap: '64m',
clientOptions: {
documentSelector: ["manifest-yaml"]
}
};
commons.activate(options, context);
}
| Fix compile error in vscode-manifest.yml | Fix compile error in vscode-manifest.yml
| 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-manifest-yaml',
- launcher: (context: VSCode.ExtensionContext) => Path.resolve(context.extensionPath, 'jars/language-server.jar'),
jvmHeap: '64m',
clientOptions: {
documentSelector: ["manifest-yaml"] |
560029eae3ce844c5e26bb737b17cce7bd857d0a | addon-test-support/@ember/test-helpers/dom/find-all.ts | addon-test-support/@ember/test-helpers/dom/find-all.ts | import getElements from './-get-elements';
import toArray from './-to-array';
/**
Find all elements matched by the given selector. Equivalent to calling
`querySelectorAll()` on the test root element.
@public
@param {string} selector the selector to search for
@return {Array} array of matched elements
*/
export default function find(selector: string): Element[] {
if (!selector) {
throw new Error('Must pass a selector to `findAll`.');
}
if (arguments.length > 1) {
throw new Error('The `findAll` test helper only takes a single argument.');
}
return toArray(getElements(selector));
}
| import getElements from './-get-elements';
import toArray from './-to-array';
/**
Find all elements matched by the given selector. Similar to calling
`querySelectorAll()` on the test root element, but returns an array instead
of a `NodeList`.
@public
@param {string} selector the selector to search for
@return {Array} array of matched elements
*/
export default function findAll(selector: string): Element[] {
if (!selector) {
throw new Error('Must pass a selector to `findAll`.');
}
if (arguments.length > 1) {
throw new Error('The `findAll` test helper only takes a single argument.');
}
return toArray(getElements(selector));
}
| Fix lying doc block on findAll test helper | Fix lying doc block on findAll test helper
| TypeScript | apache-2.0 | switchfly/ember-test-helpers,switchfly/ember-test-helpers | ---
+++
@@ -2,14 +2,15 @@
import toArray from './-to-array';
/**
- Find all elements matched by the given selector. Equivalent to calling
- `querySelectorAll()` on the test root element.
+ Find all elements matched by the given selector. Similar to calling
+ `querySelectorAll()` on the test root element, but returns an array instead
+ of a `NodeList`.
@public
@param {string} selector the selector to search for
@return {Array} array of matched elements
*/
-export default function find(selector: string): Element[] {
+export default function findAll(selector: string): Element[] {
if (!selector) {
throw new Error('Must pass a selector to `findAll`.');
} |
9600cdb1f7c824da050d44b25dac733285d347ea | src/index.ts | src/index.ts | export { Status, getStatusText, isSuccess, STATUS_CODE_INFO } from './http-status-codes';
export { Request } from './request';
export { Response } from './response';
export {
HttpMethod,
Logger,
NodeRequest,
NodeResponse,
NodeReqToken,
NodeResToken,
Router,
RouteParam,
RouterReturns,
RequestListener,
Fn,
LoggerMethod,
RedirectStatusCodes,
BodyParserConfig,
RouteConfig
} from './types/types';
export { Module } from './decorators/module';
export { RootModule } from './decorators/root-module';
export { Controller } from './decorators/controller';
export { Route } from './decorators/route';
export { Entity } from './decorators/entity';
export { Column } from './decorators/column';
export { AppFactory } from './app-factory';
export { ModuleFactory } from './module-factory';
export { pickProperties } from './utils/pick-properties';
export { BodyParser } from './services/body-parser';
| export { Status, getStatusText, isSuccess, STATUS_CODE_INFO } from './http-status-codes';
export { Request } from './request';
export { Response } from './response';
export {
HttpMethod,
Logger,
NodeRequest,
NodeResponse,
NodeReqToken,
NodeResToken,
Router,
RouteParam,
RouterReturns,
RequestListener,
Fn,
LoggerMethod,
RedirectStatusCodes,
BodyParserConfig,
RouteConfig
} from './types/types';
export { Column } from './decorators/column';
export { Controller } from './decorators/controller';
export { Entity } from './decorators/entity';
export { Module } from './decorators/module';
export { RootModule } from './decorators/root-module';
export { Route } from './decorators/route';
export { AppFactory } from './app-factory';
export { ModuleFactory } from './module-factory';
export { pickProperties } from './utils/pick-properties';
export { BodyParser } from './services/body-parser';
| Change order for decorators export | Change order for decorators export
| TypeScript | mit | restify-ts/core,restify-ts/core,restify-ts/core,restify-ts/core | ---
+++
@@ -18,12 +18,12 @@
BodyParserConfig,
RouteConfig
} from './types/types';
+export { Column } from './decorators/column';
+export { Controller } from './decorators/controller';
+export { Entity } from './decorators/entity';
export { Module } from './decorators/module';
export { RootModule } from './decorators/root-module';
-export { Controller } from './decorators/controller';
export { Route } from './decorators/route';
-export { Entity } from './decorators/entity';
-export { Column } from './decorators/column';
export { AppFactory } from './app-factory';
export { ModuleFactory } from './module-factory';
export { pickProperties } from './utils/pick-properties'; |
f3c33d64f8f5c827e234ddd48f7ce4b26e6a2f9b | src/app/map-type/map-type.component.ts | src/app/map-type/map-type.component.ts | /*!
* Map Type Component
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Component, OnInit, AfterViewInit, ContentChild } from '@angular/core';
import { LeafletControlPanelComponent } from '../leaflet-control-panel/leaflet-control-panel.component';
import 'jquery';
@Component({
selector: 'app-map-type',
templateUrl: './map-type.component.html',
styleUrls: ['./map-type.component.sass']
})
export class MapTypeComponent implements OnInit, AfterViewInit {
public panelVisible: boolean = false;
private _$panel: JQuery;
@ContentChild(LeafletControlPanelComponent) panel: LeafletControlPanelComponent;
constructor() { }
ngOnInit() { }
ngAfterViewInit() {
if (typeof this.panel === 'undefined') {
throw new Error('MapTypeComponent expects a child with a type of LeafletControlPanelComponent.');
}
this._$panel = $( this.panel.controlWrapper.nativeElement );
}
togglePanel(): Promise<void> {
return new Promise((resolve, reject) => {
if (typeof this._$panel === 'undefined') {
reject();
} else {
this._$panel
.fadeToggle()
.promise()
.then(() => {
// change the flag value of panelVisible property
this.panelVisible = !this._$panel.is(':hidden');
resolve();
}, () => {
reject();
})
;
}
});
}
}
| /*!
* Map Type Component
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Component, OnInit, AfterViewInit, ContentChild } from '@angular/core';
import 'jquery';
@Component({
selector: 'app-map-type',
templateUrl: './map-type.component.html',
styleUrls: ['./map-type.component.sass']
})
export class MapTypeComponent implements OnInit, AfterViewInit {
public panelVisible: boolean = false;
private _$panel: JQuery;
@ContentChild('panel') panel: any;
constructor() { }
ngOnInit() { }
ngAfterViewInit() {
if (typeof this.panel === 'undefined') {
throw new Error('MapTypeComponent expects a child with a type of LeafletControlPanelComponent.');
}
this._$panel = $( this.panel.controlWrapper.nativeElement );
}
togglePanel(): Promise<void> {
return new Promise((resolve, reject) => {
if (typeof this._$panel === 'undefined') {
reject();
} else {
this._$panel
.fadeToggle()
.promise()
.then(() => {
// change the flag value of panelVisible property
this.panelVisible = !this._$panel.is(':hidden');
resolve();
}, () => {
reject();
})
;
}
});
}
}
| Set the panel to any type | Set the panel to any type
| TypeScript | mit | ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2 | ---
+++
@@ -6,7 +6,6 @@
*/
import { Component, OnInit, AfterViewInit, ContentChild } from '@angular/core';
-import { LeafletControlPanelComponent } from '../leaflet-control-panel/leaflet-control-panel.component';
import 'jquery';
@Component({
@@ -18,7 +17,7 @@
public panelVisible: boolean = false;
private _$panel: JQuery;
- @ContentChild(LeafletControlPanelComponent) panel: LeafletControlPanelComponent;
+ @ContentChild('panel') panel: any;
constructor() { }
|
8f0d0e8c37bad5d069fdcb2a8bd516da8e78a129 | testutils/src/compare-lighthouse.ts | testutils/src/compare-lighthouse.ts | /**
* Compares two files lighthouse outputs, listing changes between the numeric audits.
*/
import { readFileSync } from 'fs';
const firstFilePath = process.argv[2];
const secondFilePath = process.argv[3];
console.log(`\`${firstFilePath}\` -> \`${secondFilePath}\`\n\n`);
interface IOutput {
audits: {
[name: string]: {
id: string;
title: string;
description: string;
scoreDisplayMode: string;
displayValue: string;
rawValue: number;
};
};
}
const first: IOutput = JSON.parse(readFileSync(firstFilePath).toString());
const second: IOutput = JSON.parse(readFileSync(secondFilePath).toString());
for (const auditName in first.audits) {
const firstAudit = first.audits[auditName];
// only compare numeric audits
if (firstAudit.scoreDisplayMode !== 'numeric') {
continue;
}
const secondAudit = second.audits[auditName];
const percentChange =
((secondAudit.rawValue - firstAudit.rawValue) / firstAudit.rawValue) * 100;
if (isNaN(percentChange)) {
continue;
}
console.log(
`**${firstAudit.title}**\n* ${percentChange.toFixed(0)}% Δ\n* ${
firstAudit.displayValue
} -> ${secondAudit.displayValue}\n* ${firstAudit.description}\n`
);
}
| /**
* Compares two files lighthouse outputs, listing changes between the numeric audits.
*
* Outputs in Markdown for easy posting in Github.
*/
import { readFileSync } from 'fs';
const firstFilePath = process.argv[2];
const secondFilePath = process.argv[3];
console.log(`\`${firstFilePath}\` -> \`${secondFilePath}\`\n\n`);
interface IOutput {
audits: {
[name: string]: {
id: string;
title: string;
description: string;
scoreDisplayMode: string;
displayValue: string;
rawValue: number;
};
};
}
const first: IOutput = JSON.parse(readFileSync(firstFilePath).toString());
const second: IOutput = JSON.parse(readFileSync(secondFilePath).toString());
for (const auditName in first.audits) {
const firstAudit = first.audits[auditName];
// only compare numeric audits
if (firstAudit.scoreDisplayMode !== 'numeric') {
continue;
}
const secondAudit = second.audits[auditName];
const percentChange =
((secondAudit.rawValue - firstAudit.rawValue) / firstAudit.rawValue) * 100;
if (isNaN(percentChange)) {
continue;
}
console.log(
`**${firstAudit.title}**\n* ${percentChange.toFixed(0)}% Δ\n* ${
firstAudit.displayValue
} -> ${secondAudit.displayValue}\n* ${firstAudit.description}\n`
);
}
| Add more docstring to module | Add more docstring to module
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -1,5 +1,7 @@
/**
* Compares two files lighthouse outputs, listing changes between the numeric audits.
+ *
+ * Outputs in Markdown for easy posting in Github.
*/
import { readFileSync } from 'fs';
|
5ded6834bfa4ee1acd958441be745db69ddd3a18 | src/app.ts | src/app.ts | import express from 'express';
import bodyParser from 'body-parser';
import mailRouter from './routes/mail';
import pushRouter from './routes/push';
const app: express.Application = express();
const port: string = process.env.PORT || '3000';
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/mails', mailRouter);
app.use('/push', pushRouter);
app.get('/', function (req, res) {
res.send('hello world!');
});
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}/`);
});
| import express from 'express';
import bodyParser from 'body-parser';
import swaggerUi from 'swagger-ui-express';
import mailRouter from './routes/mail';
import pushRouter from './routes/push';
const app: express.Application = express();
const port: string = process.env.PORT || '3000';
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/mails', mailRouter);
app.use('/push', pushRouter);
app.get('/', function (req, res) {
res.send('hello world!');
});
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(require('../swagger.json')));
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}/`);
});
| Add route to access swagger doc | Add route to access swagger doc
| TypeScript | mit | schulcloud/node-notification-service,schulcloud/node-notification-service,schulcloud/node-notification-service | ---
+++
@@ -1,5 +1,6 @@
import express from 'express';
import bodyParser from 'body-parser';
+import swaggerUi from 'swagger-ui-express';
import mailRouter from './routes/mail';
import pushRouter from './routes/push';
@@ -16,6 +17,8 @@
res.send('hello world!');
});
+app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(require('../swagger.json')));
+
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}/`);
}); |
526eebca3ce3ed317cf0c40b4e5298329ada456f | src/stores/model.ts | src/stores/model.ts | export interface Project {
id: string;
type: ProjectType;
}
export interface ProjectCategory {
id: string;
label: string;
description: string;
projectList?: Project[];
}
export interface JDKProject extends Project {
url: string;
readonly product: string;
readonly jobConfiguration: JobConfig;
}
export interface Item {
readonly id: string;
}
export enum TaskType {
BUILD = "BUILD",
TEST = "TEST"
}
export enum ProjectType {
JDK_PROJECT = "JDK_PROJECT"
}
export interface JobConfig {
platforms: { [id: string]: PlatformConfig };
}
export interface PlatformConfig {
tasks: { [id: string]: TaskConfig };
}
export interface TaskConfig {
variants: VariantsConfig[];
}
export interface VariantsConfig {
map: { [key: string]: string };
platforms?: { [id: string]: PlatformConfig };
}
export interface Task extends Item {
type: TaskType;
}
export interface Platform extends Item {
}
export interface Product extends Item {
}
export interface TaskVariant extends Item {
type: TaskType;
variants: Item[];
}
export type ProjectCategories = { [id: string]: ProjectCategory };
| export interface Project {
id: string;
type: ProjectType;
}
export interface ProjectCategory {
id: string;
label: string;
description: string;
projectList?: Project[];
}
export interface JDKProject extends Project {
url: string;
readonly product: string;
readonly jobConfiguration: JobConfig;
}
export interface Item {
id: string;
}
export enum TaskType {
BUILD = "BUILD",
TEST = "TEST"
}
export enum ProjectType {
JDK_PROJECT = "JDK_PROJECT"
}
export interface JobConfig {
platforms: { [id: string]: PlatformConfig };
}
export interface PlatformConfig {
tasks: { [id: string]: TaskConfig };
}
export interface TaskConfig {
variants: VariantsConfig[];
}
export interface VariantsConfig {
map: { [key: string]: string };
platforms?: { [id: string]: PlatformConfig };
}
export interface Task extends Item {
script: string;
type: TaskType;
machinePreference: "VM" | "VM_ONLY" | "HW" | "HW_ONLY";
productLimitation: Limitation;
platformLimitation: Limitation;
fileRequirements: FileRequirements;
xmlTemplate: string;
rpmLimitaion: RPMLimitaion;
}
export interface FileRequirements {
source: boolean;
binary: "NONE" | "BINARY" | "BINARIES";
}
export type LimitFlag = "BLACKLIST" | "WHITELIST";
export interface Limitation {
list: string[];
flag: LimitFlag;
}
export interface RPMLimitaion {
glob: string;
flag: LimitFlag;
}
export interface Platform extends Item {
}
export interface Product extends Item {
}
export interface TaskVariant extends Item {
type: TaskType;
variants: Item[];
}
export type ProjectCategories = { [id: string]: ProjectCategory };
| Add data structures for task | Add data structures for task
| TypeScript | mit | TheIndifferent/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,TheIndifferent/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin | ---
+++
@@ -17,7 +17,7 @@
}
export interface Item {
- readonly id: string;
+ id: string;
}
export enum TaskType {
@@ -48,7 +48,31 @@
}
export interface Task extends Item {
+ script: string;
type: TaskType;
+ machinePreference: "VM" | "VM_ONLY" | "HW" | "HW_ONLY";
+ productLimitation: Limitation;
+ platformLimitation: Limitation;
+ fileRequirements: FileRequirements;
+ xmlTemplate: string;
+ rpmLimitaion: RPMLimitaion;
+}
+
+export interface FileRequirements {
+ source: boolean;
+ binary: "NONE" | "BINARY" | "BINARIES";
+}
+
+export type LimitFlag = "BLACKLIST" | "WHITELIST";
+
+export interface Limitation {
+ list: string[];
+ flag: LimitFlag;
+}
+
+export interface RPMLimitaion {
+ glob: string;
+ flag: LimitFlag;
}
export interface Platform extends Item { |
11dd970564c5c843a0728422dcbab66cd38ffb68 | samples/win8/encyclopedia/Encyclopedia/js/win.ts | samples/win8/encyclopedia/Encyclopedia/js/win.ts | ///<reference path='..\..\..\..\..\typings\winrt.d.ts' static='true' />
///<reference path='..\..\..\..\..\typings\winjs.d.ts' static='true' />
declare var msSetImmediate: (expression: any) => void;
| ///<reference path='..\..\..\..\..\typings\winrt.d.ts'/>
///<reference path='..\..\..\..\..\typings\winjs.d.ts'/>
declare var msSetImmediate: (expression: any) => void;
| Remove deprecated attribute in triple slash reference for sample | Remove deprecated attribute in triple slash reference for sample
| TypeScript | apache-2.0 | mbrowne/typescript-dci,mbebenita/shumway.ts,mbrowne/typescript-dci,popravich/typescript,mbebenita/shumway.ts,mbrowne/typescript-dci,hippich/typescript,popravich/typescript,fdecampredon/jsx-typescript-old-version,fdecampredon/jsx-typescript-old-version,fdecampredon/jsx-typescript-old-version,popravich/typescript,hippich/typescript,mbebenita/shumway.ts,mbrowne/typescript-dci,hippich/typescript | ---
+++
@@ -1,5 +1,5 @@
-///<reference path='..\..\..\..\..\typings\winrt.d.ts' static='true' />
-///<reference path='..\..\..\..\..\typings\winjs.d.ts' static='true' />
+///<reference path='..\..\..\..\..\typings\winrt.d.ts'/>
+///<reference path='..\..\..\..\..\typings\winjs.d.ts'/>
declare var msSetImmediate: (expression: any) => void;
|
3e88a88805f9c5f0920957cbd517e85e9135421a | fake-cucumber/javascript/test/StepDefinitionTest.ts | fake-cucumber/javascript/test/StepDefinitionTest.ts | import assert from 'assert'
import StepDefinition from '../src/StepDefinition'
import { CucumberExpression, ParameterTypeRegistry } from 'cucumber-expressions'
describe('StepDefinition', () => {
describe('#match', () => {
it('returns null when there is no match', () => {
const expression = new CucumberExpression(
'banana',
new ParameterTypeRegistry()
)
const stepdef = new StepDefinition(expression, () => null)
const match = stepdef.match('apple')
assert.strictEqual(match, null)
})
it('returns null when there is no match', () => {
const expression = new CucumberExpression(
'I have {int} cukes',
new ParameterTypeRegistry()
)
const stepdef = new StepDefinition(
expression,
(cukeCount: number) => cukeCount
)
const match = stepdef.match('I have 7 cukes')
assert.strictEqual(match.execute(), 7)
})
})
})
| import assert from 'assert'
import { messages } from 'cucumber-messages'
import StepDefinition from '../src/StepDefinition'
import { CucumberExpression, ParameterTypeRegistry } from 'cucumber-expressions'
import RegularExpression from 'cucumber-expressions/dist/src/RegularExpression'
describe('StepDefinition', () => {
describe('#match', () => {
it('returns null when there is no match', () => {
const expression = new CucumberExpression(
'banana',
new ParameterTypeRegistry()
)
const stepdef = new StepDefinition(expression, () => null)
const match = stepdef.match('apple')
assert.strictEqual(match, null)
})
it('returns null when there is no match', () => {
const expression = new CucumberExpression(
'I have {int} cukes',
new ParameterTypeRegistry()
)
const stepdef = new StepDefinition(
expression,
(cukeCount: number) => cukeCount
)
const match = stepdef.match('I have 7 cukes')
assert.strictEqual(match.execute(), 7)
})
})
describe('#toMessage', () => {
it('generates an StepDefinitionConfig object for RegularExpression', () => {
const expression = new RegularExpression(
/banana/,
new ParameterTypeRegistry()
)
const stepdef = new StepDefinition(expression, () => null)
assert.deepStrictEqual(
stepdef.toMessage(),
new messages.StepDefinitionConfig({
pattern: new messages.StepDefinitionPattern({
type: messages.StepDefinitionPatternType.REGULAR_EXPRESSION,
}),
})
)
})
})
})
| Add failing test for next coding session | Add failing test for next coding session
| TypeScript | mit | cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber | ---
+++
@@ -1,6 +1,8 @@
import assert from 'assert'
+import { messages } from 'cucumber-messages'
import StepDefinition from '../src/StepDefinition'
import { CucumberExpression, ParameterTypeRegistry } from 'cucumber-expressions'
+import RegularExpression from 'cucumber-expressions/dist/src/RegularExpression'
describe('StepDefinition', () => {
describe('#match', () => {
@@ -27,4 +29,22 @@
assert.strictEqual(match.execute(), 7)
})
})
+
+ describe('#toMessage', () => {
+ it('generates an StepDefinitionConfig object for RegularExpression', () => {
+ const expression = new RegularExpression(
+ /banana/,
+ new ParameterTypeRegistry()
+ )
+ const stepdef = new StepDefinition(expression, () => null)
+ assert.deepStrictEqual(
+ stepdef.toMessage(),
+ new messages.StepDefinitionConfig({
+ pattern: new messages.StepDefinitionPattern({
+ type: messages.StepDefinitionPatternType.REGULAR_EXPRESSION,
+ }),
+ })
+ )
+ })
+ })
}) |
22aed0a41f51b0ae2ecc760f7c45e1b49ac7d48a | src/DiplomContentSystem/ClientApp/boot-client.ts | src/DiplomContentSystem/ClientApp/boot-client.ts | import 'chart.js';
import 'angular2-universal-polyfills/browser';
import { enableProdMode } from '@angular/core';
import { platformUniversalDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';
import 'bootstrap';
// Enable either Hot Module Reloading or production mode
if (module['hot']) {
module['hot'].accept();
module['hot'].dispose(() => { platform.destroy(); });
} else {
enableProdMode();
}
// Boot the application, either now or when the DOM content is loaded
const platform = platformUniversalDynamic();
const bootApplication = () => { platform.bootstrapModule(AppModule); };
if (document.readyState === 'complete') {
bootApplication();
} else {
document.addEventListener('DOMContentLoaded', bootApplication);
}
| import 'chart.js';
import "codemirror/mode/stex/stex";
import 'angular2-universal-polyfills/browser';
import { enableProdMode } from '@angular/core';
import { platformUniversalDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';
import 'bootstrap';
// Enable either Hot Module Reloading or production mode
if (module['hot']) {
module['hot'].accept();
module['hot'].dispose(() => { platform.destroy(); });
} else {
enableProdMode();
}
// Boot the application, either now or when the DOM content is loaded
const platform = platformUniversalDynamic();
const bootApplication = () => { platform.bootstrapModule(AppModule); };
if (document.readyState === 'complete') {
bootApplication();
} else {
document.addEventListener('DOMContentLoaded', bootApplication);
}
| Include STEX mode for colorize tex files. | DCS-24: Include STEX mode for colorize tex files.
| TypeScript | apache-2.0 | denismaster/DiplomContentSystem,denismaster/DiplomContentSystem,denismaster/DiplomContentSystem,denismaster/DiplomContentSystem | ---
+++
@@ -1,4 +1,5 @@
import 'chart.js';
+import "codemirror/mode/stex/stex";
import 'angular2-universal-polyfills/browser';
import { enableProdMode } from '@angular/core';
import { platformUniversalDynamic } from 'angular2-universal'; |
674598b8e4e5a99f82964d492f0b41670f6951ea | packages/components/components/sidebar/SidebarBackButton.tsx | packages/components/components/sidebar/SidebarBackButton.tsx | import React from 'react';
import AppLink, { Props as LinkProps } from '../link/AppLink';
import { ButtonLike } from '../button';
const SidebarBackButton = ({ children, ...rest }: LinkProps) => {
return (
<ButtonLike as={AppLink} size="large" color="norm" shape="outline" fullWidth className="mt0-25" {...rest}>
{children}
</ButtonLike>
);
};
export default SidebarBackButton;
| import React from 'react';
import AppLink, { Props as LinkProps } from '../link/AppLink';
import { ButtonLike } from '../button';
const SidebarBackButton = ({ children, ...rest }: LinkProps) => {
return (
<ButtonLike as={AppLink} size="large" color="weak" shape="solid" fullWidth className="mt0-25" {...rest}>
{children}
</ButtonLike>
);
};
export default SidebarBackButton;
| Change sidebar back button shape | Change sidebar back button shape
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -5,7 +5,7 @@
const SidebarBackButton = ({ children, ...rest }: LinkProps) => {
return (
- <ButtonLike as={AppLink} size="large" color="norm" shape="outline" fullWidth className="mt0-25" {...rest}>
+ <ButtonLike as={AppLink} size="large" color="weak" shape="solid" fullWidth className="mt0-25" {...rest}>
{children}
</ButtonLike>
); |
09a516da1aa9a567a1f994aa169f7d454c5410b4 | backend/src/utils.ts | backend/src/utils.ts | import * as jwt from 'jsonwebtoken';
import { Prisma } from './generated/prisma';
export interface Context {
db: Prisma;
request: any;
}
export function getUserId(ctx: Context) {
const Authorization = ctx.request.get('Authorization');
if (Authorization) {
const token = Authorization.replace('Bearer ', '');
const { userId } = jwt.verify(token, process.env.APP_SECRET) as { userId: string };
return userId;
}
throw new AuthError();
}
export class AuthError extends Error {
constructor() {
super('Not authorized');
}
}
| import * as jwt from 'jsonwebtoken';
import { Prisma } from './generated/prisma';
export interface Context {
db: Prisma;
request: any;
}
export function getUserId(ctx: Context) {
const Authorization = ctx.request.get('Authorization');
// Apollo Client sets header to the string 'null' when not logged in
if (Authorization && Authorization !== 'null') {
const token = Authorization.replace('Bearer ', '');
const { userId } = jwt.verify(token, process.env.APP_SECRET) as { userId: string };
return userId;
}
throw new AuthError();
}
export class AuthError extends Error {
constructor() {
super('Not authorized');
}
}
| Fix check for authorization in getUserId util func | Fix check for authorization in getUserId util func
| TypeScript | agpl-3.0 | iquabius/olimat,iquabius/olimat,iquabius/olimat | ---
+++
@@ -8,7 +8,8 @@
export function getUserId(ctx: Context) {
const Authorization = ctx.request.get('Authorization');
- if (Authorization) {
+ // Apollo Client sets header to the string 'null' when not logged in
+ if (Authorization && Authorization !== 'null') {
const token = Authorization.replace('Bearer ', '');
const { userId } = jwt.verify(token, process.env.APP_SECRET) as { userId: string };
return userId; |
647bb0cba533a9b58a062c7c31413e23b411bb5f | src/server/routes/hc-api/auth.ts | src/server/routes/hc-api/auth.ts | import * as cors from 'cors';
import * as passport from 'passport';
import { Strategy as BearerStrategy } from 'passport-http-bearer';
import { OauthAccessToken } from 'server/models';
passport.use(new BearerStrategy((token, done) => {
OauthAccessToken.getAdminFromTokenString(token)
.then(admin => {
if (!admin) {
done(null, false);
return;
}
done(null, admin, { message: undefined, scope: 'all' });
}, error => done(error));
}));
export const middleware = {
cors: cors({
origin: [
// Match an empty origin to allow external tools (like postman) to easily interact with the API
'',
// Match Heroku instances
/^https:\/\/hackcam(.*).herokuapp.com$/,
// Match *.hackcambridge.com
/^https:\/\/(.*\.)?hackcambridge\.com$/,
// Match local development environment
/^https?:\/\/localhost(:[0-9]+)?$/,
],
credentials: true,
}),
bearer: passport.authenticate('bearer', { session: false }),
};
| import * as cors from 'cors';
import * as passport from 'passport';
import { Strategy as BearerStrategy } from 'passport-http-bearer';
import { OauthAccessToken } from 'server/models';
passport.use(new BearerStrategy((token, done) => {
OauthAccessToken.getAdminFromTokenString(token)
.then(admin => {
if (!admin) {
done(null, false);
return;
}
done(null, admin, { message: undefined, scope: 'all' });
}, error => done(error));
}));
export const middleware = {
cors: cors({
origin: [
// Match an empty origin to allow external tools (like postman) to easily interact with the API
'',
// Match *.hackcambridge.com
/^https:\/\/(.*\.)?hackcambridge\.com$/,
// Match local development environment
/^https?:\/\/localhost(:[0-9]+)?$/,
],
credentials: true,
}),
bearer: passport.authenticate('bearer', { session: false }),
};
| Reduce URLs matched by CORS for HC API | Reduce URLs matched by CORS for HC API
| TypeScript | mit | hackcambridge/hack-cambridge-website,hackcambridge/hack-cambridge-website,hackcambridge/hack-cambridge-website,hackcambridge/hack-cambridge-website | ---
+++
@@ -21,8 +21,6 @@
origin: [
// Match an empty origin to allow external tools (like postman) to easily interact with the API
'',
- // Match Heroku instances
- /^https:\/\/hackcam(.*).herokuapp.com$/,
// Match *.hackcambridge.com
/^https:\/\/(.*\.)?hackcambridge\.com$/,
// Match local development environment |
e8081b2b37a76050eed35273fb6251ede25ca8a6 | ui/test/stubs.ts | ui/test/stubs.ts | import * as sinon from "sinon";
// tslint:disable:max-classes-per-file
export class LoggerStub {
public static create() {
return {
debug: () => {
// ignore
},
error: () => {
// ignore
},
fatal: () => {
// ignore
},
info: () => {
// ignore
},
warn: () => {
// ignore
}
};
}
}
| // tslint:disable:max-classes-per-file
export class LoggerStub {
public static create() {
return {
debug: () => {
// ignore
},
error: () => {
// ignore
},
fatal: () => {
// ignore
},
info: () => {
// ignore
},
warn: () => {
// ignore
}
};
}
}
| Remove no longer needed import. | Remove no longer needed import.
| TypeScript | mit | jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr | ---
+++
@@ -1,5 +1,3 @@
-import * as sinon from "sinon";
-
// tslint:disable:max-classes-per-file
export class LoggerStub { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.