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
|
---|---|---|---|---|---|---|---|---|---|---|
6e1352568f2e9a88d4947b9dd94e5ff63f3fd3a7 | app/src/main-process/shell.ts | app/src/main-process/shell.ts | import * as Url from 'url'
import { shell } from 'electron'
/**
* Wraps the inbuilt shell.openItem path to address a focus issue that affects macOS.
*
* When opening a folder in Finder, the window will appear behind the application
* window, which may confuse users. As a workaround, we will fallback to using
* shell.openExternal for macOS until it can be fixed upstream.
*
* @param path directory to open
*/
export function openDirectorySafe(path: string) {
if (__DARWIN__) {
const directoryURL = Url.format({
pathname: path,
protocol: 'file:',
slashes: true,
})
shell
.openExternal(directoryURL)
.catch(err => log.error(`Failed to open directory (${path})`, err))
} else {
shell.openItem(path)
}
}
| import * as Url from 'url'
import { shell } from 'electron'
/**
* Wraps the inbuilt shell.openItem path to address a focus issue that affects macOS.
*
* When opening a folder in Finder, the window will appear behind the application
* window, which may confuse users. As a workaround, we will fallback to using
* shell.openExternal for macOS until it can be fixed upstream.
*
* CAUTION: This method should never be used to open user-provided or derived
* paths. It's sole use is to open _directories_ that we know to be safe, no
* verification is performed to ensure that the provided path isn't actually
* an executable.
*
* @param path directory to open
*/
export function openDirectorySafe(path: string) {
if (__DARWIN__) {
const directoryURL = Url.format({
pathname: path,
protocol: 'file:',
slashes: true,
})
shell
.openExternal(directoryURL)
.catch(err => log.error(`Failed to open directory (${path})`, err))
} else {
shell.openItem(path)
}
}
| Add a word of caution | Add a word of caution
| TypeScript | mit | j-f1/forked-desktop,artivilla/desktop,desktop/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,kactus-io/kactus,kactus-io/kactus,artivilla/desktop,say25/desktop | ---
+++
@@ -7,6 +7,11 @@
* When opening a folder in Finder, the window will appear behind the application
* window, which may confuse users. As a workaround, we will fallback to using
* shell.openExternal for macOS until it can be fixed upstream.
+ *
+ * CAUTION: This method should never be used to open user-provided or derived
+ * paths. It's sole use is to open _directories_ that we know to be safe, no
+ * verification is performed to ensure that the provided path isn't actually
+ * an executable.
*
* @param path directory to open
*/ |
8857671105874c8bbc5b4aa717c447e38dcdbfc7 | resources/assets/lib/interfaces/score-json.ts | resources/assets/lib/interfaces/score-json.ts | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import BeatmapExtendedJson from './beatmap-extended-json';
import BeatmapsetJson from './beatmapset-json';
import GameMode from './game-mode';
import Rank from './rank';
import UserJson from './user-json';
export default interface ScoreJson {
accuracy: number;
beatmap?: BeatmapExtendedJson;
beatmapset?: BeatmapsetJson;
best_id: number | null;
created_at: string;
id: string;
max_combo: number;
mode?: GameMode;
mode_int?: number;
mods: string[];
passed: boolean;
pp?: number;
rank?: Rank;
rank_country?: number;
rank_global?: number;
replay: boolean;
score: number;
statistics: {
count_100: number;
count_300: number;
count_50: number;
count_geki: number;
count_katu: number;
count_miss: number;
};
user: UserJson;
user_id: number;
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import BeatmapExtendedJson from './beatmap-extended-json';
import BeatmapsetJson from './beatmapset-json';
import GameMode from './game-mode';
import Rank from './rank';
import UserJson from './user-json';
export default interface ScoreJson {
accuracy: number;
beatmap?: BeatmapExtendedJson;
beatmapset?: BeatmapsetJson;
best_id: number | null;
created_at: string;
id: number;
max_combo: number;
mode?: GameMode;
mode_int?: number;
mods: string[];
passed: boolean;
pp?: number;
rank?: Rank;
rank_country?: number;
rank_global?: number;
replay: boolean;
score: number;
statistics: {
count_100: number;
count_300: number;
count_50: number;
count_geki: number;
count_katu: number;
count_miss: number;
};
user: UserJson;
user_id: number;
}
| Fix typing for score id | Fix typing for score id
| TypeScript | agpl-3.0 | nanaya/osu-web,ppy/osu-web,notbakaneko/osu-web,nanaya/osu-web,nanaya/osu-web,ppy/osu-web,nanaya/osu-web,ppy/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,LiquidPL/osu-web,nanaya/osu-web,ppy/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,ppy/osu-web | ---
+++
@@ -13,7 +13,7 @@
beatmapset?: BeatmapsetJson;
best_id: number | null;
created_at: string;
- id: string;
+ id: number;
max_combo: number;
mode?: GameMode;
mode_int?: number; |
28e54447898f5eecfe46895066be845ecdca0833 | frontend/src/index.tsx | frontend/src/index.tsx | import '@blueprintjs/core/lib/css/blueprint.css';
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { Application } from './components/Application';
import { INITIAL_STATE } from './reducers';
import { configureStore } from './store';
const { store, history } = configureStore(INITIAL_STATE);
const rootElement = document.getElementById('root');
if (rootElement) {
ReactDOM.render(<Provider store={store}>
<ConnectedRouter history={history}>
<Application/>
</ConnectedRouter>
</Provider>, rootElement);
} else {
console.error('Element with ID "root" was not found, cannot bootstrap react app');
}
| import '@blueprintjs/core/lib/css/blueprint.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { Application } from './components/Application';
import { INITIAL_STATE } from './reducers';
import { configureStore } from './store';
const { store, history } = configureStore(INITIAL_STATE);
const rootElement = document.getElementById('root');
if (rootElement) {
ReactDOM.render(<Provider store={store}>
<ConnectedRouter history={history}>
<Application/>
</ConnectedRouter>
</Provider>, rootElement);
} else {
console.error('Element with ID "root" was not found, cannot bootstrap react app');
}
| Remove extra import of polyfills | Remove extra import of polyfills
| TypeScript | mit | luxons/seven-wonders,luxons/seven-wonders,luxons/seven-wonders | ---
+++
@@ -1,5 +1,4 @@
import '@blueprintjs/core/lib/css/blueprint.css';
-import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'; |
753c762f7837e2a924e16a7ef9020c417327b920 | src/app/manager/view-manager.service.ts | src/app/manager/view-manager.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class ViewManagerService {
public screen: { width: number, height: number } = {
width: 0,
height: 0,
};
public offset: { x: number, y: number } = {
x: 0,
y: 0,
};
constructor(
) {
this.bindEvents();
}
private bindEvents(): void {
const self = this;
self.setScreenSize();
self.setPageOffset();
window.addEventListener('resize', (event) => {
self.setScreenSize();
});
window.addEventListener('scroll', (event) => {
self.setPageOffset();
});
}
setScreenSize(): void {
const self = this;
self.screen.width = window.innerWidth || document.documentElement.clientWidth || 0;
self.screen.height = window.innerHeight || document.documentElement.clientHeight || 0;
}
setPageOffset(): void {
const self = this;
self.offset.x = window.pageXOffset;
self.offset.y = window.pageYOffset;
}
}
| import { Injectable } from '@angular/core';
@Injectable()
export class ViewManagerService {
public screen: { width: number, height: number } = {
width: 0,
height: 0,
};
public offset: { x: number, y: number } = {
x: 0,
y: 0,
};
constructor(
) {
this.bindEvents();
}
private bindEvents(): void {
const self = this;
self.setScreenSize();
self.setPageOffset();
window.addEventListener('resize', (event) => {
self.setScreenSize();
});
window.addEventListener('scroll', (event) => {
self.setPageOffset();
});
}
setScreenSize(): void {
const self = this;
self.screen.width = window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || 0;
self.screen.height = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || 0;
}
setPageOffset(): void {
const self = this;
self.offset.x = window.pageXOffset;
self.offset.y = window.pageYOffset;
}
}
| Add handler for the case document.documentElement is null | Add handler for the case document.documentElement is null
| TypeScript | mit | tsugitta/tsugitta.github.io,tsugitta/tsugitta.github.io,tsugitta/tsugitta.github.io,tsugitta/tsugitta.github.io | ---
+++
@@ -37,8 +37,8 @@
setScreenSize(): void {
const self = this;
- self.screen.width = window.innerWidth || document.documentElement.clientWidth || 0;
- self.screen.height = window.innerHeight || document.documentElement.clientHeight || 0;
+ self.screen.width = window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || 0;
+ self.screen.height = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || 0;
}
setPageOffset(): void { |
d9714ebf8f481bd6a219d31cbb031508f4c58dbd | VSCode_Extension/src/extension.ts | VSCode_Extension/src/extension.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 { spawn, ChildProcess } from 'child_process';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable = vscode.commands.registerCommand('extension.startMTA', () => {
// The code you place here will be executed every time your command is executed
const config = vscode.workspace.getConfiguration('launch');
const info = config.get('configurations');
if (info) {
// Display a message box to the user
vscode.window.showInformationMessage('TestServer started');
vscode.window.showInformationMessage(info[0].program);
spawn(info[0].program);
}
});
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate() {
} | '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 { exec, ChildProcess } from 'child_process';
import { normalize } from 'path';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable = vscode.commands.registerCommand('extension.startMTA', () => {
// The code you place here will be executed every time your command is executed
const config = vscode.workspace.getConfiguration('launch');
let info = config.get<Array<any>>('configurations');
if (info) {
info = info.filter(v => v.type === "mtasa");
if (info[0]) {
// Display a message box to the user
vscode.window.showInformationMessage('Starting MTA:SA server right now');
// Start server
const path = normalize(info[0].serverpath + '/MTA Server_d.exe');
exec(`start cmd.exe /K "${path}"`); // TODO: Insert packaged path here
}
}
});
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate() {
} | Add VSCode command that starts an MTA server | Add VSCode command that starts an MTA server
| TypeScript | mit | Jusonex/MTATD,Jusonex/MTATD,Jusonex/MTATD | ---
+++
@@ -4,7 +4,8 @@
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
-import { spawn, ChildProcess } from 'child_process';
+import { exec, ChildProcess } from 'child_process';
+import { normalize } from 'path';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
@@ -16,15 +17,19 @@
let disposable = vscode.commands.registerCommand('extension.startMTA', () => {
// The code you place here will be executed every time your command is executed
const config = vscode.workspace.getConfiguration('launch');
- const info = config.get('configurations');
+ let info = config.get<Array<any>>('configurations');
if (info) {
- // Display a message box to the user
- vscode.window.showInformationMessage('TestServer started');
+ info = info.filter(v => v.type === "mtasa");
- vscode.window.showInformationMessage(info[0].program);
- spawn(info[0].program);
+ if (info[0]) {
+ // Display a message box to the user
+ vscode.window.showInformationMessage('Starting MTA:SA server right now');
+
+ // Start server
+ const path = normalize(info[0].serverpath + '/MTA Server_d.exe');
+ exec(`start cmd.exe /K "${path}"`); // TODO: Insert packaged path here
+ }
}
-
});
context.subscriptions.push(disposable); |
2dd9ae5ff2b232272fc6c8de72aa2a5d28ddf145 | step-release-vis/src/testing/EnvironmentServiceStub.ts | step-release-vis/src/testing/EnvironmentServiceStub.ts | import {Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {Polygon} from '../app/models/Polygon';
import {EnvironmentService} from '../app/services/environment';
@Injectable()
export class EnvironmentServiceStub {
candName = 'test';
polygons = [
new Polygon(
[
{x: 0, y: 0},
{x: 0, y: 1},
{x: 1, y: 1},
{x: 1, y: 0},
],
this.candName
)
];
getPolygons(jsonFile: string): Observable<Polygon[]> {
return of(this.polygons);
}
}
| import {Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {Polygon} from '../app/models/Polygon';
import {EnvironmentService} from '../app/services/environment';
@Injectable()
export class EnvironmentServiceStub {
candName = 'test';
polygons = [
new Polygon(
[
{x: 0, y: 0},
{x: 0, y: 100},
{x: 100, y: 0},
],
this.candName
),
new Polygon(
[
{x: 0, y: 100},
{x: 100, y: 100},
{x: 100, y: 0},
],
this.candName
),
];
getPolygons(jsonFile: string): Observable<Polygon[]> {
return of(this.polygons);
}
}
| Add another polygon to stub. | Add another polygon to stub.
| TypeScript | apache-2.0 | googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020 | ---
+++
@@ -5,19 +5,25 @@
@Injectable()
export class EnvironmentServiceStub {
-
candName = 'test';
polygons = [
new Polygon(
[
{x: 0, y: 0},
- {x: 0, y: 1},
- {x: 1, y: 1},
- {x: 1, y: 0},
+ {x: 0, y: 100},
+ {x: 100, y: 0},
],
this.candName
- )
+ ),
+ new Polygon(
+ [
+ {x: 0, y: 100},
+ {x: 100, y: 100},
+ {x: 100, y: 0},
+ ],
+ this.candName
+ ),
];
getPolygons(jsonFile: string): Observable<Polygon[]> { |
ce41c989fc39e5eac6eba67f1b221f5b1c862b57 | common/settings/Settings.ts | common/settings/Settings.ts | import { ipcMain } from 'electron';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { Utilities } from '../Utilities';
export class Settings {
private settings: object;
private filePath: string;
constructor() {
this.filePath = Utilities.getWorkingFolder() + '/settings.json';
// Request from renderer to get settings file from main process
ipcMain.on('settings-get', (event, arg) => {
if (existsSync(this.filePath)) {
const newSettings = JSON.parse(readFileSync(this.filePath, 'utf8'));
event.sender.send('new-settings', newSettings);
}
});
ipcMain.on('settings-post', (event, settings) => {
this.settings = settings;
});
}
writeSettingsFile() {
if (this.settings) {
writeFileSync(this.filePath, JSON.stringify(this.settings), 'utf8');
}
}
}
| import { app, ipcMain } from 'electron';
import { existsSync, readFileSync, writeFileSync } from 'fs';
export class Settings {
private settings: object;
private filePath: string;
constructor() {
this.filePath = app.getPath('userData') + '/settings.json';
// Request from renderer to get settings file from main process
ipcMain.on('settings-get', (event, arg) => {
if (existsSync(this.filePath)) {
const newSettings = JSON.parse(readFileSync(this.filePath, 'utf8'));
event.sender.send('new-settings', newSettings);
}
});
ipcMain.on('settings-post', (event, settings) => {
this.settings = settings;
});
}
writeSettingsFile() {
if (this.settings) {
writeFileSync(this.filePath, JSON.stringify(this.settings), 'utf8');
}
}
}
| Save settings.json in userPath instead | Save settings.json in userPath instead
| TypeScript | mit | etaylor8086/prime-randomizer-web,etaylor8086/prime-randomizer-web,etaylor8086/prime-randomizer-web,etaylor8086/prime-randomizer-web,etaylor8086/prime-randomizer-web | ---
+++
@@ -1,14 +1,12 @@
-import { ipcMain } from 'electron';
+import { app, ipcMain } from 'electron';
import { existsSync, readFileSync, writeFileSync } from 'fs';
-
-import { Utilities } from '../Utilities';
export class Settings {
private settings: object;
private filePath: string;
constructor() {
- this.filePath = Utilities.getWorkingFolder() + '/settings.json';
+ this.filePath = app.getPath('userData') + '/settings.json';
// Request from renderer to get settings file from main process
ipcMain.on('settings-get', (event, arg) => { |
5b4e2c13f8199e6d1eead37c8712b27588d5e38d | capstone-project/src/main/angular-webapp/src/app/toast/toast.service.spec.ts | capstone-project/src/main/angular-webapp/src/app/toast/toast.service.spec.ts | import { Toast } from '@syncfusion/ej2-angular-notifications';
import { ToastService } from './toast.service';
describe('ToastService', () => {
let service: ToastService;
beforeEach(() => {
service = new ToastService();
});
it('Should create service', () => {
expect(service).toBeTruthy();
});
it('Should create toast', () => {
const htmlElement = document.createElement("div");
const model = {title: "title", content: "content"};
service.createToast(htmlElement, model);
expect(service['toastInstance'].title).toBe("title");
expect(service['toastInstance'].content).toBe("content");
});
it('Should show toast when toastInstance is defined', () => {
const htmlElement = document.createElement("div");
const model = {title: "title", content: "content"};
service.createToast(htmlElement, model);
spyOn(service['toastInstance'], 'show');
service.showToast(htmlElement, model);
expect(service['toastInstance'].show).toHaveBeenCalled();
});
it('Should show toast when toastInstance is not defined', () => {
// Create a Toast instance so we can spy on its show method
const toast = new Toast();
// Use the instance we created to initialize the service's toastInstance
spyOn(service, 'createToast').and.callFake(() => {
service["toastInstance"] = toast;
});
spyOn(toast, 'show');
const htmlElement = document.createElement("div");
const model = {title: "title", content: "content"};
service.showToast(htmlElement, model);
expect(toast.show).toHaveBeenCalled();
});
}); | import { Toast } from '@syncfusion/ej2-angular-notifications';
import { ToastService } from './toast.service';
describe('ToastService', () => {
let service: ToastService;
let htmlElement;
let model;
beforeEach(() => {
service = new ToastService();
htmlElement = document.createElement("div");
model = {title: "title", content: "content"};
});
it('Should create service', () => {
expect(service).toBeTruthy();
});
it('Should create toast', () => {
service.createToast(htmlElement, model);
expect(service['toastInstance'].title).toBe("title");
expect(service['toastInstance'].content).toBe("content");
});
it('Should show toast when toastInstance is defined', () => {
service.createToast(htmlElement, model);
spyOn(service['toastInstance'], 'show');
service.showToast(htmlElement, model);
expect(service['toastInstance'].show).toHaveBeenCalled();
});
it('Should show toast when toastInstance is not defined', () => {
// Create a Toast instance so we can spy on its show method
const toast = new Toast();
// Use the instance we created to initialize the service's toastInstance
spyOn(service, 'createToast').and.callFake(() => {
service["toastInstance"] = toast;
});
spyOn(toast, 'show');
service.showToast(htmlElement, model);
expect(toast.show).toHaveBeenCalled();
});
}); | Define htmlElement and model before each test | Define htmlElement and model before each test
| TypeScript | apache-2.0 | googleinterns/step263-2020,googleinterns/step263-2020,googleinterns/step263-2020,googleinterns/step263-2020 | ---
+++
@@ -4,9 +4,13 @@
describe('ToastService', () => {
let service: ToastService;
+ let htmlElement;
+ let model;
beforeEach(() => {
service = new ToastService();
+ htmlElement = document.createElement("div");
+ model = {title: "title", content: "content"};
});
it('Should create service', () => {
@@ -14,8 +18,6 @@
});
it('Should create toast', () => {
- const htmlElement = document.createElement("div");
- const model = {title: "title", content: "content"};
service.createToast(htmlElement, model);
@@ -24,8 +26,7 @@
});
it('Should show toast when toastInstance is defined', () => {
- const htmlElement = document.createElement("div");
- const model = {title: "title", content: "content"};
+
service.createToast(htmlElement, model);
spyOn(service['toastInstance'], 'show');
@@ -43,8 +44,6 @@
service["toastInstance"] = toast;
});
spyOn(toast, 'show');
- const htmlElement = document.createElement("div");
- const model = {title: "title", content: "content"};
service.showToast(htmlElement, model);
|
f543a299fccb218b585070b4acfe33ad38b1db59 | src/utils/invariant.ts | src/utils/invariant.ts | export function invariant(condition: boolean, message: string, context?: any) {
if (!condition) {
let errorMessage = message;
if (context) {
errorMessage = (message.indexOf('%s') != -1) ?
message.replace('%s', context) :
errorMessage = `${message}: ${context}`;
}
throw new Error(errorMessage);
}
}
| export function invariant(condition: boolean, message: string, context?: any) {
if (!condition) {
let errorMessage = message;
if (context) {
errorMessage = (message.indexOf('%s') !== -1) ?
message.replace('%s', context) :
errorMessage = `${message}: ${context}`;
}
throw new Error(errorMessage);
}
}
| Fix linter error upon rebase from master | Fix linter error upon rebase from master
| TypeScript | mit | angular-redux/store,wbuchwalter/ng2-redux,angular-redux/ng2-redux,angular-redux/store,angular-redux/ng2-redux | ---
+++
@@ -3,7 +3,7 @@
let errorMessage = message;
if (context) {
- errorMessage = (message.indexOf('%s') != -1) ?
+ errorMessage = (message.indexOf('%s') !== -1) ?
message.replace('%s', context) :
errorMessage = `${message}: ${context}`;
} |
0996bd3a20bfa8b7a2ccc74c526ecfd629070d49 | framework/src/decorators/PrioritizedOverUnhandled.ts | framework/src/decorators/PrioritizedOverUnhandled.ts | import { createHandlerOptionDecorator } from '../metadata/HandlerOptionMetadata';
export const PrioritizedOverUnhandled = (prioritizedOverUnhandled = true) =>
createHandlerOptionDecorator({ prioritizedOverUnhandled });
| import { createHandlerOptionDecorator } from '../metadata/HandlerOptionMetadata';
export const PrioritizedOverUnhandled: (prioritizedOverUnhandled?: boolean) => MethodDecorator = (
prioritizedOverUnhandled = true,
) => createHandlerOptionDecorator({ prioritizedOverUnhandled });
| Add missing return type to satisfy linter | :rotating_light: Add missing return type to satisfy linter
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -1,4 +1,5 @@
import { createHandlerOptionDecorator } from '../metadata/HandlerOptionMetadata';
-export const PrioritizedOverUnhandled = (prioritizedOverUnhandled = true) =>
- createHandlerOptionDecorator({ prioritizedOverUnhandled });
+export const PrioritizedOverUnhandled: (prioritizedOverUnhandled?: boolean) => MethodDecorator = (
+ prioritizedOverUnhandled = true,
+) => createHandlerOptionDecorator({ prioritizedOverUnhandled }); |
fde9ee25baa3e5d1b578cc7dbada1db8d9f440e8 | src/parser/core/modules/SpellInfo.ts | src/parser/core/modules/SpellInfo.ts | import SPELLS, { registerSpell } from 'common/SPELLS';
import Analyzer, { Options } from 'parser/core/Analyzer';
import Events, { Ability, AnyEvent } from 'parser/core/Events';
/**
* We automatically discover spell info from the combat log so we can avoid many
* calls to resolve missing spell info.
*/
class SpellInfo extends Analyzer {
constructor(options: Options) {
super(options);
this.addEventListener(Events.any, this.onEvent);
}
onEvent(event: AnyEvent) {
if ('ability' in event) {
this.addSpellInfo(event.ability);
}
if ('extraAbility' in event) {
this.addSpellInfo(event.extraAbility);
}
}
addSpellInfo(ability: Omit<Ability, 'type'>) {
if (SPELLS[ability.guid]) {
return;
}
registerSpell(ability.guid, ability.name, ability.abilityIcon.replace(/\.jpg$/, ''));
}
}
export default SpellInfo;
| import SPELLS, { registerSpell } from 'common/SPELLS';
import Analyzer, { Options } from 'parser/core/Analyzer';
import Events, { Ability, AnyEvent } from 'parser/core/Events';
/**
* We automatically discover spell info from the combat log so we can avoid many
* calls to resolve missing spell info.
*/
class SpellInfo extends Analyzer {
constructor(options: Options) {
super(options);
this.addEventListener(Events.any, this.onEvent);
}
onEvent(event: AnyEvent) {
if ('ability' in event) {
this.addSpellInfo(event.ability);
}
if ('extraAbility' in event) {
this.addSpellInfo(event.extraAbility);
}
}
addSpellInfo(ability: Omit<Ability, 'type'>) {
if (SPELLS[ability.guid] || !ability.name || !ability.abilityIcon) {
return;
}
registerSpell(ability.guid, ability.name, ability.abilityIcon.replace(/\.jpg$/, ''));
}
}
export default SpellInfo;
| Fix crash when ability object does not include name or icon | Fix crash when ability object does not include name or icon
| TypeScript | agpl-3.0 | WoWAnalyzer/WoWAnalyzer,sMteX/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,sMteX/WoWAnalyzer,Juko8/WoWAnalyzer,Juko8/WoWAnalyzer,sMteX/WoWAnalyzer,Juko8/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer | ---
+++
@@ -22,7 +22,7 @@
}
addSpellInfo(ability: Omit<Ability, 'type'>) {
- if (SPELLS[ability.guid]) {
+ if (SPELLS[ability.guid] || !ability.name || !ability.abilityIcon) {
return;
}
|
f8dc4ba86d47320282c62e6e12a07a0ad60e42d5 | src/marketplace/offerings/details/OfferingDetails.tsx | src/marketplace/offerings/details/OfferingDetails.tsx | import * as React from 'react';
import * as Col from 'react-bootstrap/lib/Col';
import * as Row from 'react-bootstrap/lib/Row';
import { OfferingTabsComponent, OfferingTab } from '@waldur/marketplace/details/OfferingTabsComponent';
import { Offering } from '@waldur/marketplace/types';
import { OfferingActions } from '../actions/OfferingActions';
import { OfferingHeader } from './OfferingHeader';
interface OfferingDetailsProps {
offering: Offering;
tabs: OfferingTab[];
}
export const OfferingDetails: React.FC<OfferingDetailsProps> = props => (
<div className="wrapper wrapper-content">
{props.offering.shared && (
<div className="pull-right m-r-md">
<OfferingActions row={props.offering}/>
</div>
)}
<OfferingHeader offering={props.offering}/>
<Row>
<Col lg={12}>
<OfferingTabsComponent tabs={props.tabs}/>
</Col>
</Row>
</div>
);
| import * as React from 'react';
import * as Col from 'react-bootstrap/lib/Col';
import * as Row from 'react-bootstrap/lib/Row';
import { OfferingTabsComponent, OfferingTab } from '@waldur/marketplace/details/OfferingTabsComponent';
import { Offering } from '@waldur/marketplace/types';
import { OfferingActions } from '../actions/OfferingActions';
import { OfferingHeader } from './OfferingHeader';
interface OfferingDetailsProps {
offering: Offering;
tabs: OfferingTab[];
}
export const OfferingDetails: React.FC<OfferingDetailsProps> = props => (
<div className="wrapper wrapper-content">
{props.offering.shared && (
<div className="pull-right m-r-md" style={{position: 'relative', zIndex: 100}}>
<OfferingActions row={props.offering}/>
</div>
)}
<OfferingHeader offering={props.offering}/>
<Row>
<Col lg={12}>
<OfferingTabsComponent tabs={props.tabs}/>
</Col>
</Row>
</div>
);
| Make offering actions button clickable in mobile view. | Make offering actions button clickable in mobile view.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -16,7 +16,7 @@
export const OfferingDetails: React.FC<OfferingDetailsProps> = props => (
<div className="wrapper wrapper-content">
{props.offering.shared && (
- <div className="pull-right m-r-md">
+ <div className="pull-right m-r-md" style={{position: 'relative', zIndex: 100}}>
<OfferingActions row={props.offering}/>
</div>
)} |
5a43acd42a1bc570611634b1e9c14abc35bb94d5 | src/stores/room-list/previews/ReactionEventPreview.ts | src/stores/room-list/previews/ReactionEventPreview.ts | /*
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { IPreview } from "./IPreview";
import { TagID } from "../models";
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { getSenderName, isSelf, shouldPrefixMessagesIn } from "./utils";
import { _t } from "../../../languageHandler";
export class ReactionEventPreview implements IPreview {
public getTextFor(event: MatrixEvent, tagId?: TagID): string {
const reaction = event.getRelation().key;
if (!reaction) return;
if (isSelf(event) || !shouldPrefixMessagesIn(event.getRoomId(), tagId)) {
return reaction;
} else {
return _t("%(senderName)s: %(reaction)s", {senderName: getSenderName(event), reaction});
}
}
}
| /*
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { IPreview } from "./IPreview";
import { TagID } from "../models";
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { getSenderName, isSelf, shouldPrefixMessagesIn } from "./utils";
import { _t } from "../../../languageHandler";
export class ReactionEventPreview implements IPreview {
public getTextFor(event: MatrixEvent, tagId?: TagID): string {
const relation = event.getRelation();
if (!relation) return null; // invalid reaction (probably redacted)
const reaction = relation.key;
if (!reaction) return null; // invalid reaction (unknown format)
if (isSelf(event) || !shouldPrefixMessagesIn(event.getRoomId(), tagId)) {
return reaction;
} else {
return _t("%(senderName)s: %(reaction)s", {senderName: getSenderName(event), reaction});
}
}
}
| Fix reaction event crashes in message previews | Fix reaction event crashes in message previews
Fixes https://github.com/vector-im/riot-web/issues/14224 | TypeScript | apache-2.0 | matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk | ---
+++
@@ -22,8 +22,11 @@
export class ReactionEventPreview implements IPreview {
public getTextFor(event: MatrixEvent, tagId?: TagID): string {
- const reaction = event.getRelation().key;
- if (!reaction) return;
+ const relation = event.getRelation();
+ if (!relation) return null; // invalid reaction (probably redacted)
+
+ const reaction = relation.key;
+ if (!reaction) return null; // invalid reaction (unknown format)
if (isSelf(event) || !shouldPrefixMessagesIn(event.getRoomId(), tagId)) {
return reaction; |
9be1e387e162f18196dcfc0dbea5da2d90b18ed8 | test/programs/force-type-imported/main.ts | test/programs/force-type-imported/main.ts | import { Widget } from './widget';
export interface MyObject {
name: string;
mainWidget: Widget;
otherWidgets: Widget[];
}
| import { Widget } from "./widget";
export interface MyObject {
name: string;
mainWidget: Widget;
otherWidgets: Widget[];
}
| Fix test "force-type-imported" lint error | Fix test "force-type-imported" lint error
| TypeScript | bsd-3-clause | YousefED/typescript-json-schema,YousefED/typescript-json-schema,HitkoDev/typescript-json-schema,HitkoDev/typescript-json-schema,benbabic/typescript-json-schema,benbabic/typescript-json-schema | ---
+++
@@ -1,4 +1,4 @@
-import { Widget } from './widget';
+import { Widget } from "./widget";
export interface MyObject {
name: string; |
017034401ff456f34243011451be3c4f24b25741 | visualization/app/codeCharta/codeCharta.api.model.ts | visualization/app/codeCharta/codeCharta.api.model.ts | import { AttributeTypes, CodeMapNode, Edge, MarkedPackage, RecursivePartial, Settings } from "./codeCharta.model"
export interface ExportCCFile {
projectName: string
apiVersion: string
nodes: CodeMapNode[]
attributeTypes?: AttributeTypes
edges?: Edge[]
markedPackages?: MarkedPackage[]
blacklist?: ExportBlacklistItem[]
}
export interface ExportBlacklistItem {
path: string
type: ExportBlacklistType
}
export enum ExportBlacklistType {
hide = "hide",
exclude = "exclude"
}
export enum APIVersions {
ZERO_POINT_ONE = "0.1",
ONE_POINT_ZERO = "1.0",
ONE_POINT_ONE = "1.1"
}
export interface ExportScenario {
name: string
settings: RecursivePartial<Settings>
}
| import { AttributeTypes, AttributeTypeValue, CodeMapNode, Edge, MarkedPackage, RecursivePartial, Settings } from "./codeCharta.model"
export interface ExportCCFile {
projectName: string
apiVersion: string
nodes: CodeMapNode[]
attributeTypes?: AttributeTypes | ExportAttributeTypes
edges?: Edge[]
markedPackages?: MarkedPackage[]
blacklist?: ExportBlacklistItem[]
}
export interface ExportBlacklistItem {
path: string
type: ExportBlacklistType
}
export enum ExportBlacklistType {
hide = "hide",
exclude = "exclude"
}
export enum APIVersions {
ZERO_POINT_ONE = "0.1",
ONE_POINT_ZERO = "1.0",
ONE_POINT_ONE = "1.1"
}
export interface ExportScenario {
name: string
settings: RecursivePartial<Settings>
}
export interface ExportAttributeTypes {
nodes?: [{ [key: string]: AttributeTypeValue }]
edges?: [{ [key: string]: AttributeTypeValue }]
}
| Update allow older attributeTypes as well | Update allow older attributeTypes as well
| TypeScript | bsd-3-clause | MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta | ---
+++
@@ -1,10 +1,10 @@
-import { AttributeTypes, CodeMapNode, Edge, MarkedPackage, RecursivePartial, Settings } from "./codeCharta.model"
+import { AttributeTypes, AttributeTypeValue, CodeMapNode, Edge, MarkedPackage, RecursivePartial, Settings } from "./codeCharta.model"
export interface ExportCCFile {
projectName: string
apiVersion: string
nodes: CodeMapNode[]
- attributeTypes?: AttributeTypes
+ attributeTypes?: AttributeTypes | ExportAttributeTypes
edges?: Edge[]
markedPackages?: MarkedPackage[]
blacklist?: ExportBlacklistItem[]
@@ -30,3 +30,8 @@
name: string
settings: RecursivePartial<Settings>
}
+
+export interface ExportAttributeTypes {
+ nodes?: [{ [key: string]: AttributeTypeValue }]
+ edges?: [{ [key: string]: AttributeTypeValue }]
+} |
f6853c9f20062b7c263c6812a76934ab0e7794e7 | packages/@sanity/initial-value-templates/src/builder.ts | packages/@sanity/initial-value-templates/src/builder.ts | import {Template, TemplateBuilder} from './Template'
import {Schema, SchemaType, getDefaultSchema} from './parts/Schema'
function defaultTemplateForType(
schemaType: string | SchemaType,
sanitySchema?: Schema
): TemplateBuilder {
let type: SchemaType
if (typeof schemaType === 'string') {
const schema = sanitySchema || getDefaultSchema()
type = schema.get(schemaType)
} else {
type = schemaType
}
return new TemplateBuilder({
id: type.name,
schemaType: type.name,
title: type.title || type.name,
icon: type.icon,
value: type.initialValue || {_type: type.name}
})
}
function defaults(sanitySchema?: Schema) {
const schema = sanitySchema || getDefaultSchema()
if (!schema) {
throw new Error(
'Unable to automatically resolve schema. Pass schema explicitly: `defaults(schema)`'
)
}
return schema
.getTypeNames()
.filter(typeName => isDocumentSchemaType(typeName, schema))
.map(typeName => defaultTemplateForType(schema.get(typeName), schema))
}
function isDocumentSchemaType(typeName: string, schema: Schema) {
const schemaType = schema.get(typeName)
return schemaType.type && schemaType.type.name === 'document'
}
export default {
template: (spec?: Template) => new TemplateBuilder(spec),
defaults,
defaultTemplateForType
}
| import {Template, TemplateBuilder} from './Template'
import {Schema, SchemaType, getDefaultSchema} from './parts/Schema'
function defaultTemplateForType(
schemaType: string | SchemaType,
sanitySchema?: Schema
): TemplateBuilder {
let type: SchemaType
if (typeof schemaType === 'string') {
const schema = sanitySchema || getDefaultSchema()
type = schema.get(schemaType)
} else {
type = schemaType
}
return new TemplateBuilder({
id: type.name,
schemaType: type.name,
title: type.title || type.name,
icon: type.icon,
value: type.initialValue || {_type: type.name}
})
}
function defaults(sanitySchema?: Schema) {
const schema = sanitySchema || getDefaultSchema()
if (!schema) {
throw new Error(
'Unable to automatically resolve schema. Pass schema explicitly: `defaults(schema)`'
)
}
return schema
.getTypeNames()
.filter(typeName => !/^sanity\./.test(typeName))
.filter(typeName => isDocumentSchemaType(typeName, schema))
.map(typeName => defaultTemplateForType(schema.get(typeName), schema))
}
function isDocumentSchemaType(typeName: string, schema: Schema) {
const schemaType = schema.get(typeName)
return schemaType.type && schemaType.type.name === 'document'
}
export default {
template: (spec?: Template) => new TemplateBuilder(spec),
defaults,
defaultTemplateForType
}
| Remove templates for asset types | [initial-value-templates] Remove templates for asset types
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -32,6 +32,7 @@
return schema
.getTypeNames()
+ .filter(typeName => !/^sanity\./.test(typeName))
.filter(typeName => isDocumentSchemaType(typeName, schema))
.map(typeName => defaultTemplateForType(schema.get(typeName), schema))
} |
80f42ed3bac03d619f0290b1ed88a3733c8d797b | src/index.ts | src/index.ts | /**
* This file is the entry-point to start Cerveau
*/
process.title = "Cerveau Game Server";
// Check for npm install first, as many developers forget this pre step
import { lstatSync } from "fs";
try {
const lstat = lstatSync("./node_modules/");
if (!lstat.isDirectory()) {
throw new Error(); // to trigger catch below
}
}
catch (err) {
// tslint:disable-next-line no-console
console.error(`ERROR: "node_modules/" not found.
Did you forget to run 'npm install'?`);
process.exit(1);
}
// if we get here then the node_modules should be installed, let's go!
// tslint:disable-next-line:no-import-side-effect - we want them below
import { setupThread } from "./core/setup-thread";
setupThread(); // we must do this before doing any aliased imports below
import { Lobby } from "./core/server";
Lobby.getInstance(); // this will create the singleton Lobby instance
import { setupWebServer } from "./web/app";
setupWebServer();
| /** This file is the entry-point to start Cerveau */
// first code to execute, like a mini sanity test
console.log("~~~ Cerveau is starting ~~~"); // tslint:disable-line:no-console
process.title = "Cerveau Game Server";
import { setupThread } from "./core/setup-thread";
setupThread(); // We must do this before doing any aliased imports below
import { Lobby } from "./core/server";
Lobby.getInstance(); // This will create the singleton Lobby instance
import { setupWebServer } from "./web/app";
setupWebServer();
| Disable node_modules check on code that requires node_modules to run | Disable node_modules check on code that requires node_modules to run
| TypeScript | mit | siggame/Cerveau,siggame/Cerveau,JacobFischer/Cerveau,JacobFischer/Cerveau | ---
+++
@@ -1,32 +1,15 @@
-/**
- * This file is the entry-point to start Cerveau
- */
+/** This file is the entry-point to start Cerveau */
+
+// first code to execute, like a mini sanity test
+console.log("~~~ Cerveau is starting ~~~"); // tslint:disable-line:no-console
+
process.title = "Cerveau Game Server";
-// Check for npm install first, as many developers forget this pre step
-import { lstatSync } from "fs";
-
-try {
- const lstat = lstatSync("./node_modules/");
- if (!lstat.isDirectory()) {
- throw new Error(); // to trigger catch below
- }
-}
-catch (err) {
- // tslint:disable-next-line no-console
- console.error(`ERROR: "node_modules/" not found.
- Did you forget to run 'npm install'?`);
- process.exit(1);
-}
-
-// if we get here then the node_modules should be installed, let's go!
-
-// tslint:disable-next-line:no-import-side-effect - we want them below
import { setupThread } from "./core/setup-thread";
-setupThread(); // we must do this before doing any aliased imports below
+setupThread(); // We must do this before doing any aliased imports below
import { Lobby } from "./core/server";
-Lobby.getInstance(); // this will create the singleton Lobby instance
+Lobby.getInstance(); // This will create the singleton Lobby instance
import { setupWebServer } from "./web/app";
setupWebServer(); |
4cdfe3976b38d985d4af86848124f4e58adca18a | src/index.ts | src/index.ts | import { render } from 'inferno'
import App from './components/app.ts'
const container = document.getElementById('app')
const app = new App()
render(app.render(), container)
| import { render } from 'inferno'
import h from 'inferno-hyperscript'
import App from './components/app.ts'
const container = document.getElementById('app')
render(h(App), container)
| Change the way of rendering App Component | Change the way of rendering App Component
| TypeScript | mit | y0za/typescript-inferno-todo,y0za/typescript-inferno-todo,y0za/typescript-inferno-todo | ---
+++
@@ -1,8 +1,7 @@
import { render } from 'inferno'
+import h from 'inferno-hyperscript'
import App from './components/app.ts'
const container = document.getElementById('app')
-const app = new App()
-
-render(app.render(), container)
+render(h(App), container) |
ac4e1ce71b5c2aadf86e75ebf60402cd8d6001fb | src/chrome/settings/ToggledSection.tsx | src/chrome/settings/ToggledSection.tsx | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {FlexColumn, styled, FlexRow, ToggleButton} from 'flipper';
import React from 'react';
const IndentedSection = styled(FlexColumn)({
paddingLeft: 50,
});
const GreyedOutOverlay = styled('div')({
backgroundColor: '#EFEEEF',
borderRadius: 4,
opacity: 0.6,
height: '100%',
position: 'absolute',
left: 0,
right: 0,
});
export default function ToggledSection(props: {
label: string;
toggled: boolean;
onChange?: (value: boolean) => void;
children?: React.ReactNode;
// Whether to disallow interactions with this toggle
frozen?: boolean;
}) {
return (
<FlexColumn>
<FlexRow>
<ToggleButton
label={props.label}
onClick={() => props.onChange && props.onChange(!props.toggled)}
toggled={props.toggled}
/>
{props.frozen && <GreyedOutOverlay />}
</FlexRow>
<IndentedSection>
{props.children}
{props.toggled || props.frozen ? null : <GreyedOutOverlay />}
</IndentedSection>
</FlexColumn>
);
}
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {FlexColumn, styled, FlexRow, ToggleButton} from 'flipper';
import React from 'react';
const IndentedSection = styled(FlexColumn)({
paddingLeft: 50,
paddingBottom: 10,
});
const GreyedOutOverlay = styled('div')({
backgroundColor: '#EFEEEF',
borderRadius: 4,
opacity: 0.6,
height: '100%',
position: 'absolute',
left: 0,
right: 0,
});
export default function ToggledSection(props: {
label: string;
toggled: boolean;
onChange?: (value: boolean) => void;
children?: React.ReactNode;
// Whether to disallow interactions with this toggle
frozen?: boolean;
}) {
return (
<FlexColumn>
<FlexRow>
<ToggleButton
label={props.label}
onClick={() => props.onChange && props.onChange(!props.toggled)}
toggled={props.toggled}
/>
{props.frozen && <GreyedOutOverlay />}
</FlexRow>
<IndentedSection>
{props.children}
{props.toggled || props.frozen ? null : <GreyedOutOverlay />}
</IndentedSection>
</FlexColumn>
);
}
| Add some padding between sections in settings | Add some padding between sections in settings
Reviewed By: priteshrnandgaonkar
Differential Revision: D18085724
fbshipit-source-id: d874a21399e86f0079bf1cc86d4b83be6ce5a5d7
| TypeScript | mit | facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper | ---
+++
@@ -12,6 +12,7 @@
const IndentedSection = styled(FlexColumn)({
paddingLeft: 50,
+ paddingBottom: 10,
});
const GreyedOutOverlay = styled('div')({
backgroundColor: '#EFEEEF', |
1b42d73f44811eec1b7ddd72dd0d640a57c3376c | server/lib/peertube-socket.ts | server/lib/peertube-socket.ts | import * as SocketIO from 'socket.io'
import { authenticateSocket } from '../middlewares'
import { UserNotificationModel } from '../models/account/user-notification'
import { logger } from '../helpers/logger'
import { Server } from 'http'
class PeerTubeSocket {
private static instance: PeerTubeSocket
private userNotificationSockets: { [ userId: number ]: SocketIO.Socket } = {}
private constructor () {}
init (server: Server) {
const io = SocketIO(server)
io.of('/user-notifications')
.use(authenticateSocket)
.on('connection', socket => {
const userId = socket.handshake.query.user.id
logger.debug('User %d connected on the notification system.', userId)
this.userNotificationSockets[userId] = socket
socket.on('disconnect', () => {
logger.debug('User %d disconnected from SocketIO notifications.', userId)
delete this.userNotificationSockets[userId]
})
})
}
sendNotification (userId: number, notification: UserNotificationModel) {
const socket = this.userNotificationSockets[userId]
if (!socket) return
socket.emit('new-notification', notification.toFormattedJSON())
}
static get Instance () {
return this.instance || (this.instance = new this())
}
}
// ---------------------------------------------------------------------------
export {
PeerTubeSocket
}
| import * as SocketIO from 'socket.io'
import { authenticateSocket } from '../middlewares'
import { UserNotificationModel } from '../models/account/user-notification'
import { logger } from '../helpers/logger'
import { Server } from 'http'
class PeerTubeSocket {
private static instance: PeerTubeSocket
private userNotificationSockets: { [ userId: number ]: SocketIO.Socket[] } = {}
private constructor () {}
init (server: Server) {
const io = SocketIO(server)
io.of('/user-notifications')
.use(authenticateSocket)
.on('connection', socket => {
const userId = socket.handshake.query.user.id
logger.debug('User %d connected on the notification system.', userId)
if (!this.userNotificationSockets[userId]) this.userNotificationSockets[userId] = []
this.userNotificationSockets[userId].push(socket)
socket.on('disconnect', () => {
logger.debug('User %d disconnected from SocketIO notifications.', userId)
this.userNotificationSockets[userId] = this.userNotificationSockets[userId].filter(s => s !== socket)
})
})
}
sendNotification (userId: number, notification: UserNotificationModel) {
const sockets = this.userNotificationSockets[userId]
if (!sockets) return
for (const socket of sockets) {
socket.emit('new-notification', notification.toFormattedJSON())
}
}
static get Instance () {
return this.instance || (this.instance = new this())
}
}
// ---------------------------------------------------------------------------
export {
PeerTubeSocket
}
| Fix socket notification with multiple user tabs | Fix socket notification with multiple user tabs
| TypeScript | agpl-3.0 | Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube | ---
+++
@@ -8,7 +8,7 @@
private static instance: PeerTubeSocket
- private userNotificationSockets: { [ userId: number ]: SocketIO.Socket } = {}
+ private userNotificationSockets: { [ userId: number ]: SocketIO.Socket[] } = {}
private constructor () {}
@@ -22,22 +22,26 @@
logger.debug('User %d connected on the notification system.', userId)
- this.userNotificationSockets[userId] = socket
+ if (!this.userNotificationSockets[userId]) this.userNotificationSockets[userId] = []
+
+ this.userNotificationSockets[userId].push(socket)
socket.on('disconnect', () => {
logger.debug('User %d disconnected from SocketIO notifications.', userId)
- delete this.userNotificationSockets[userId]
+ this.userNotificationSockets[userId] = this.userNotificationSockets[userId].filter(s => s !== socket)
})
})
}
sendNotification (userId: number, notification: UserNotificationModel) {
- const socket = this.userNotificationSockets[userId]
+ const sockets = this.userNotificationSockets[userId]
- if (!socket) return
+ if (!sockets) return
- socket.emit('new-notification', notification.toFormattedJSON())
+ for (const socket of sockets) {
+ socket.emit('new-notification', notification.toFormattedJSON())
+ }
}
static get Instance () { |
360f7afed51c62bbaa89e19c43838516cc84f63b | src/ts/index.ts | src/ts/index.ts | import * as logging from './core/log'
import * as charts from './charts/core'
import * as factory from './models/items/factory'
import * as app from './app/app'
import * as edit from './edit/edit'
import { actions } from './core/action'
import GraphiteChartRenderer from './charts/graphite'
import FlotChartRenderer from './charts/flot'
import PlaceholderChartRenderer from './charts/placeholder'
import manager from './app/manager'
import Config from './app/config'
declare var window, $, tessera
var log = logging.logger('main')
// Temporary, for compatibility with old templates
window.ts.app = app
window.ts.manager = manager
window.ts.templates = tessera.templates
window.ts.charts = charts
window.ts.factory = factory
window.ts.actions = actions
window.ts.edit = edit
app.config = window.ts.config
function setup(config: Config) {
log.info('Registering chart renderers')
charts.renderers.register(new GraphiteChartRenderer({
graphite_url: config.GRAPHITE_URL
}))
charts.renderers.register(new FlotChartRenderer())
charts.renderers.register(new PlaceholderChartRenderer())
log.info('Done.')
}
setup(app.config)
| import * as logging from './core/log'
import * as charts from './charts/core'
import * as factory from './models/items/factory'
import * as app from './app/app'
import * as edit from './edit/edit'
import { actions } from './core/action'
import { transforms } from './models/transform/transform'
import manager from './app/manager'
import Config from './app/config'
import GraphiteChartRenderer from './charts/graphite'
import FlotChartRenderer from './charts/flot'
import PlaceholderChartRenderer from './charts/placeholder'
declare var window, $, tessera
var log = logging.logger('main')
// Temporary, for compatibility with old templates
window.ts.app = app
window.ts.manager = manager
window.ts.templates = tessera.templates
window.ts.charts = charts
window.ts.factory = factory
window.ts.actions = actions
window.ts.edit = edit
window.ts.transforms = transforms
app.config = window.ts.config
function setup(config: Config) {
log.info('Registering chart renderers')
charts.renderers.register(new GraphiteChartRenderer({
graphite_url: config.GRAPHITE_URL
}))
charts.renderers.register(new FlotChartRenderer())
charts.renderers.register(new PlaceholderChartRenderer())
log.info('Done.')
}
setup(app.config)
| Fix direct load of transforms on URL - another missing global reference to be refactored | Fix direct load of transforms on URL - another missing global reference to be refactored
| TypeScript | apache-2.0 | section-io/tessera,urbanairship/tessera,jmptrader/tessera,aalpern/tessera,aalpern/tessera,tessera-metrics/tessera,section-io/tessera,urbanairship/tessera,jmptrader/tessera,jmptrader/tessera,Slach/tessera,tessera-metrics/tessera,tessera-metrics/tessera,section-io/tessera,section-io/tessera,jmptrader/tessera,aalpern/tessera,aalpern/tessera,Slach/tessera,aalpern/tessera,urbanairship/tessera,Slach/tessera,jmptrader/tessera,urbanairship/tessera,tessera-metrics/tessera,tessera-metrics/tessera,Slach/tessera,urbanairship/tessera | ---
+++
@@ -1,14 +1,15 @@
-import * as logging from './core/log'
-import * as charts from './charts/core'
-import * as factory from './models/items/factory'
-import * as app from './app/app'
-import * as edit from './edit/edit'
-import { actions } from './core/action'
+import * as logging from './core/log'
+import * as charts from './charts/core'
+import * as factory from './models/items/factory'
+import * as app from './app/app'
+import * as edit from './edit/edit'
+import { actions } from './core/action'
+import { transforms } from './models/transform/transform'
+import manager from './app/manager'
+import Config from './app/config'
import GraphiteChartRenderer from './charts/graphite'
import FlotChartRenderer from './charts/flot'
import PlaceholderChartRenderer from './charts/placeholder'
-import manager from './app/manager'
-import Config from './app/config'
declare var window, $, tessera
@@ -22,6 +23,7 @@
window.ts.factory = factory
window.ts.actions = actions
window.ts.edit = edit
+window.ts.transforms = transforms
app.config = window.ts.config
function setup(config: Config) { |
005c771566fb87cdbe54e1699b4bdf1ac1d7d00a | src/Theme/Container.ts | src/Theme/Container.ts | import ListenerAdapter from '../Observer/ListenerAdapter';
import Observer from '../Observer/Observer';
import ThemesManager from './ThemesManager';
import ThemesRegistry, {Theme} from './ThemesRegistry';
class Container {
registry: ThemesRegistry;
currentThemeAdapter: ListenerAdapter<Theme>;
currentTheme: Observer<Theme>;
manager: ThemesManager;
constructor() {
this.registry = new ThemesRegistry();
this.currentThemeAdapter = new ListenerAdapter<Theme>();
this.currentTheme = new Observer<Theme>(this.registry.getTheme('unknown'), this.currentThemeAdapter);
this.manager = new ThemesManager(this.currentTheme, this.registry);
this.setupDefaults();
}
protected setupDefaults(): void {
this.registry.registerTheme({
isBuildIn: true,
name: 'Google',
url: 'Theme/Google'
});
this.registry.registerTheme({
isBuildIn: true,
name: 'Codefrog',
url: 'Theme/Codefrog'
});
this.manager.changeTheme('Google');
}
}
export default new Container(); | import ListenerAdapter from '../Observer/ListenerAdapter';
import Observer from '../Observer/Observer';
import DataStorage from '../Storage/DataStorage';
import ThemesManager from './ThemesManager';
import ThemesRegistry, {Theme} from './ThemesRegistry';
class Container {
registry: ThemesRegistry;
currentThemeAdapter: ListenerAdapter<Theme>;
currentTheme: Observer<Theme>;
manager: ThemesManager;
storage: DataStorage;
constructor() {
this.storage = new DataStorage('theme', window.localStorage);
this.registry = new ThemesRegistry();
this.currentThemeAdapter = new ListenerAdapter<Theme>();
this.currentTheme = new Observer<Theme>(
this.storage.loadData<Theme>(
'currentTheme',
{
isBuildIn: true,
name: 'Google',
url: 'Theme/Google'
}
),
this.storage.attach<Theme>('currentTheme', this.currentThemeAdapter)
);
this.manager = new ThemesManager(this.currentTheme, this.registry);
this.setupDefaults();
}
protected setupDefaults(): void {
this.registry.registerTheme({
isBuildIn: true,
name: 'Google',
url: 'Theme/Google'
});
this.registry.registerTheme({
isBuildIn: true,
name: 'Codefrog',
url: 'Theme/Codefrog'
});
}
}
export default new Container(); | Connect store to themes manager. | Connect store to themes manager.
| TypeScript | mit | enbock/Time-Tracker,enbock/Time-Tracker,enbock/Time-Tracker,enbock/Time-Tracker | ---
+++
@@ -1,5 +1,6 @@
import ListenerAdapter from '../Observer/ListenerAdapter';
import Observer from '../Observer/Observer';
+import DataStorage from '../Storage/DataStorage';
import ThemesManager from './ThemesManager';
import ThemesRegistry, {Theme} from './ThemesRegistry';
@@ -8,11 +9,23 @@
currentThemeAdapter: ListenerAdapter<Theme>;
currentTheme: Observer<Theme>;
manager: ThemesManager;
+ storage: DataStorage;
constructor() {
+ this.storage = new DataStorage('theme', window.localStorage);
this.registry = new ThemesRegistry();
this.currentThemeAdapter = new ListenerAdapter<Theme>();
- this.currentTheme = new Observer<Theme>(this.registry.getTheme('unknown'), this.currentThemeAdapter);
+ this.currentTheme = new Observer<Theme>(
+ this.storage.loadData<Theme>(
+ 'currentTheme',
+ {
+ isBuildIn: true,
+ name: 'Google',
+ url: 'Theme/Google'
+ }
+ ),
+ this.storage.attach<Theme>('currentTheme', this.currentThemeAdapter)
+ );
this.manager = new ThemesManager(this.currentTheme, this.registry);
this.setupDefaults();
@@ -29,7 +42,6 @@
name: 'Codefrog',
url: 'Theme/Codefrog'
});
- this.manager.changeTheme('Google');
}
}
|
7ec143e90e11aaa5146e1eeff95d97d3e4dff1ab | ui/src/shared/components/threesizer/DivisionHeader.tsx | ui/src/shared/components/threesizer/DivisionHeader.tsx | import React, {PureComponent} from 'react'
import DivisionMenu, {
MenuItem,
} from 'src/shared/components/threesizer/DivisionMenu'
interface Props {
onMinimize: () => void
onMaximize: () => void
buttons: JSX.Element[]
menuOptions?: MenuItem[]
name?: string
}
class DivisionHeader extends PureComponent<Props> {
public render() {
const {name} = this.props
return (
<div className="threesizer--header">
{name && <div className="threesizer--header-name">{name}</div>}
<div className="threesizer--header-controls">
{this.props.buttons.map(b => b)}
<DivisionMenu menuItems={this.menuItems} />
</div>
</div>
)
}
private get menuItems(): MenuItem[] {
const {onMaximize, onMinimize, menuOptions} = this.props
return [
...menuOptions,
{
action: onMaximize,
text: 'Maximize',
},
{
action: onMinimize,
text: 'Minimize',
},
]
}
}
export default DivisionHeader
| import React, {PureComponent} from 'react'
import DivisionMenu, {
MenuItem,
} from 'src/shared/components/threesizer/DivisionMenu'
interface Props {
onMinimize: () => void
onMaximize: () => void
buttons: JSX.Element[]
menuOptions?: MenuItem[]
name?: string
}
class DivisionHeader extends PureComponent<Props> {
public render() {
return (
<div className="threesizer--header">
{this.renderName}
<div className="threesizer--header-controls">
{this.props.buttons.map(b => b)}
<DivisionMenu menuItems={this.menuItems} />
</div>
</div>
)
}
private get renderName(): JSX.Element {
const {name} = this.props
if (!name) {
return
}
return <div className="threesizer--header-name">{name}</div>
}
private get menuItems(): MenuItem[] {
const {onMaximize, onMinimize, menuOptions} = this.props
return [
...menuOptions,
{
action: onMaximize,
text: 'Maximize',
},
{
action: onMinimize,
text: 'Minimize',
},
]
}
}
export default DivisionHeader
| Move division name rendering into getter | Move division name rendering into getter
| TypeScript | mit | influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,li-ang/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb | ---
+++
@@ -13,17 +13,25 @@
class DivisionHeader extends PureComponent<Props> {
public render() {
- const {name} = this.props
-
return (
<div className="threesizer--header">
- {name && <div className="threesizer--header-name">{name}</div>}
+ {this.renderName}
<div className="threesizer--header-controls">
{this.props.buttons.map(b => b)}
<DivisionMenu menuItems={this.menuItems} />
</div>
</div>
)
+ }
+
+ private get renderName(): JSX.Element {
+ const {name} = this.props
+
+ if (!name) {
+ return
+ }
+
+ return <div className="threesizer--header-name">{name}</div>
}
private get menuItems(): MenuItem[] { |
c7bcf55e2fb1e904d058565905352d8da84a6ac4 | recaptcha/recaptcha-value-accessor.directive.ts | recaptcha/recaptcha-value-accessor.directive.ts | import { forwardRef, Directive } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { RecaptchaComponent } from './recaptcha.component';
export const RECAPTCHA_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RecaptchaValueAccessor),
multi: true
};
@Directive({
selector: 'recaptcha',
host: {'(resolved)': 'onResolve($event)'},
providers: [RECAPTCHA_VALUE_ACCESSOR]
})
export class RecaptchaValueAccessor implements ControlValueAccessor {
onChange = (value: any) => {};
onTouched = () => {};
constructor(private host: RecaptchaComponent) { }
writeValue(value: string): void {
if (value == null) {
this.host.reset();
}
}
onResolve($event: any) {
this.onChange($event);
this.onTouched();
}
registerOnChange(fn: (value: any) => void): void { this.onChange = fn; }
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
}
| import { forwardRef, Directive } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { RecaptchaComponent } from './recaptcha.component';
export const RECAPTCHA_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RecaptchaValueAccessor),
multi: true
};
@Directive({
selector: 'recaptcha',
host: {'(resolved)': 'onResolve($event)'},
providers: [RECAPTCHA_VALUE_ACCESSOR]
})
export class RecaptchaValueAccessor implements ControlValueAccessor {
onChange = (value: any) => {};
onTouched = () => {};
constructor(private host: RecaptchaComponent) { }
writeValue(value: string): void {
if (!value) {
this.host.reset();
}
}
onResolve($event: any) {
this.onChange($event);
this.onTouched();
}
registerOnChange(fn: (value: any) => void): void { this.onChange = fn; }
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
}
| Reset the captcha if its value it set to falsey | Reset the captcha if its value it set to falsey
| TypeScript | mit | DethAriel/ng-recaptcha,DethAriel/ng-recaptcha,DethAriel/ng-recaptcha,DethAriel/ng2-recaptcha,DethAriel/ng-recaptcha | ---
+++
@@ -20,7 +20,7 @@
constructor(private host: RecaptchaComponent) { }
writeValue(value: string): void {
- if (value == null) {
+ if (!value) {
this.host.reset();
}
} |
1cef63ff7984a5d32e1719b4abcb2f3fb502ba1e | src/Types.ts | src/Types.ts | import { IncomingMessage } from 'http';
import { Buffer } from 'buffer';
/**
* Simple utility Hash array type
*/
export type ObjectMap<T> = {[key: string]: T};
/**
* A Valid HTTP operation
*/
export type HttpVerb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'PATCH';
/**
* Enumaration of valid HTTP verbs.
*/
export const HttpVerbs: ObjectMap<HttpVerb> = {
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
OPTIONS: 'OPTIONS',
PATCH: 'PATCH'
};
/**
* An HTTP Request response containing both the response's message information and the response's body.
*
* Used by `ProxyHandler`.
* @type {IncomingMessage}
*/
export interface ProxyResponse {
message: IncomingMessage,
body: string | Buffer
}
/**
* Accessible types for a CORS Policy Access-Control headers.
*/
export type CorsAccessControlValue<T> = T[]|'*'|undefined;
| import { IncomingMessage } from 'http';
import { Buffer } from 'buffer';
/**
* Simple utility Hash array type
*/
export type ObjectMap<T> = {[key: string]: T};
/**
* A Valid HTTP operation
*/
export type HttpVerb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'PATCH';
/**
* Enumaration of valid HTTP verbs.
*/
export const HttpVerbs = Object.freeze({
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
OPTIONS: 'OPTIONS',
PATCH: 'PATCH'
});
/**
* An HTTP Request response containing both the response's message information and the response's body.
*
* Used by `ProxyHandler`.
* @type {IncomingMessage}
*/
export interface ProxyResponse {
message: IncomingMessage,
body: string | Buffer
}
/**
* Accessible types for a CORS Policy Access-Control headers.
*/
export type CorsAccessControlValue<T> = T[]|'*'|undefined;
| Update the HttpVerbs enum so intel sense will work with it. | Update the HttpVerbs enum so intel sense will work with it.
| TypeScript | mit | syrp-nz/ts-lambda-handler,syrp-nz/ts-lambda-handler | ---
+++
@@ -14,14 +14,14 @@
/**
* Enumaration of valid HTTP verbs.
*/
-export const HttpVerbs: ObjectMap<HttpVerb> = {
+export const HttpVerbs = Object.freeze({
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
OPTIONS: 'OPTIONS',
PATCH: 'PATCH'
-};
+});
/**
* An HTTP Request response containing both the response's message information and the response's body. |
7b97aa473ca8a9e6d98fa81583058c507a4a0885 | packages/ionic/src/layouts/vertical/vertical-layout.ts | packages/ionic/src/layouts/vertical/vertical-layout.ts | import { Component } from '@angular/core';
import { JsonFormsState, RankedTester, rankWith, uiTypeIs } from '@jsonforms/core';
import { JsonFormsIonicLayout } from '../JsonFormsIonicLayout';
import { NgRedux } from '@angular-redux/store';
@Component({
selector: 'jsonforms-vertical-layout',
template: `
<div *ngFor="let element of uischema?.elements">
<jsonforms-outlet
[uischema]="element"
[path]="path"
[schema]="schema"
></jsonforms-outlet>
</div>
`
})
export class VerticalLayoutRenderer extends JsonFormsIonicLayout {
constructor(ngRedux: NgRedux<JsonFormsState>) {
super(ngRedux);
}
}
export const verticalLayoutTester: RankedTester = rankWith(1, uiTypeIs('VerticalLayout'));
| import { Component } from '@angular/core';
import { JsonFormsState, RankedTester, rankWith, uiTypeIs } from '@jsonforms/core';
import { JsonFormsIonicLayout } from '../JsonFormsIonicLayout';
import { NgRedux } from '@angular-redux/store';
@Component({
selector: 'jsonforms-vertical-layout',
template: `
<ion-list *ngFor="let element of uischema?.elements">
<jsonforms-outlet
[uischema]="element"
[path]="path"
[schema]="schema"
></jsonforms-outlet>
</ion-list>
`
})
export class VerticalLayoutRenderer extends JsonFormsIonicLayout {
constructor(ngRedux: NgRedux<JsonFormsState>) {
super(ngRedux);
}
}
export const verticalLayoutTester: RankedTester = rankWith(1, uiTypeIs('VerticalLayout'));
| Make use of ion-list for vertical layout | [ionic] Make use of ion-list for vertical layout
| TypeScript | mit | qb-project/jsonforms,qb-project/jsonforms,qb-project/jsonforms | ---
+++
@@ -6,13 +6,13 @@
@Component({
selector: 'jsonforms-vertical-layout',
template: `
- <div *ngFor="let element of uischema?.elements">
+ <ion-list *ngFor="let element of uischema?.elements">
<jsonforms-outlet
[uischema]="element"
[path]="path"
[schema]="schema"
></jsonforms-outlet>
- </div>
+ </ion-list>
`
})
export class VerticalLayoutRenderer extends JsonFormsIonicLayout { |
3386f8286022d03880d30f7db9ffeed85af57262 | src/config/proxy-configuration.ts | src/config/proxy-configuration.ts | import { GraphQLSchema } from 'graphql';
import { FieldMetadata } from '../extended-schema/extended-schema';
export interface ProxyConfig {
endpoints: EndpointConfig[]
}
interface EndpointConfigBase {
namespace: string
typePrefix: string
fieldMetadata?: {[key: string]: FieldMetadata}
url?: string
schema?: GraphQLSchema
}
interface HttpEndpointConfig extends EndpointConfigBase {
url: string
}
interface LocalEndpointConfig extends EndpointConfigBase {
schema: GraphQLSchema
}
export type EndpointConfig = HttpEndpointConfig | LocalEndpointConfig;
| import { GraphQLSchema } from 'graphql';
import { FieldMetadata } from '../extended-schema/extended-schema';
export interface ProxyConfig {
endpoints: EndpointConfig[]
}
interface EndpointConfigBase {
namespace?: string
typePrefix?: string
fieldMetadata?: {[key: string]: FieldMetadata}
url?: string
schema?: GraphQLSchema
identifier?: string
}
interface HttpEndpointConfig extends EndpointConfigBase {
url: string
}
interface LocalEndpointConfig extends EndpointConfigBase {
schema: GraphQLSchema
}
export type EndpointConfig = HttpEndpointConfig | LocalEndpointConfig;
| Make schema namespacing optional and added schema identifier | Make schema namespacing optional and added schema identifier
| TypeScript | mit | AEB-labs/graphql-weaver,AEB-labs/graphql-weaver | ---
+++
@@ -6,11 +6,12 @@
}
interface EndpointConfigBase {
- namespace: string
- typePrefix: string
+ namespace?: string
+ typePrefix?: string
fieldMetadata?: {[key: string]: FieldMetadata}
url?: string
schema?: GraphQLSchema
+ identifier?: string
}
interface HttpEndpointConfig extends EndpointConfigBase { |
b25647f09203ebd6cc3a69fe45c2c8e31afdb3c5 | src/index.ts | src/index.ts | import { getAST } from './ast';
import { emit } from './emitter';
declare function require(name: string);
declare var process: any;
(function () {
if (typeof process !== 'undefined' && process.nextTick && !process.browser && typeof require !== "undefined") {
var fs = require('fs');
if (process.argv.length < 2)
process.exit();
var fileNames = process.argv.slice(2);
const sourceFile = getAST(fileNames);
const result = emit(sourceFile, {});
console.log(result.emitted_string);
process.exit();
}
})();
| import { getAST } from './ast';
import { emit } from './emitter';
declare function require(name: string);
declare var process: any;
(function () {
if (typeof process !== 'undefined' && process.nextTick && !process.browser && typeof require !== "undefined") {
var fs = require('fs');
if (process.argv.length < 2)
process.exit();
var fileNames = process.argv.slice(2);
const sourceFile = getAST(fileNames);
const result = emit(sourceFile, { run: '', run_wrapper: '' });
console.log(result.emitted_string);
process.exit();
}
})();
| Add run ad run_wrapper dummy to initial context | Add run ad run_wrapper dummy to initial context
| TypeScript | mit | AmnisIO/typewriter,AmnisIO/typewriter,AmnisIO/typewriter | ---
+++
@@ -11,7 +11,7 @@
process.exit();
var fileNames = process.argv.slice(2);
const sourceFile = getAST(fileNames);
- const result = emit(sourceFile, {});
+ const result = emit(sourceFile, { run: '', run_wrapper: '' });
console.log(result.emitted_string);
process.exit();
} |
428ac84c602f47df3a7edd6a704245f40736b5b6 | src/index.ts | src/index.ts | /**
* node-win32-api
*
* @author waiting
* @license MIT
* @link https://github.com/waitingsong/node-win32-api
*/
import {parse_windef} from './lib/helper';
import * as User32 from './lib/user32/index';
export {User32 as U};
export {User32};
import * as Kernel32 from './lib/kernel32/index';
export {Kernel32 as K};
export {Kernel32};
import * as Comctl32 from './lib/comctl32/index';
export {Comctl32 as C};
export {Comctl32};
import * as DStruct from './lib/struct';
export {DStruct as DS}; // Dict of Struct
export {DStruct};
import * as types from './lib/types';
export {types};
import * as windef from './lib/windef';
parse_windef(windef);
const foo = windef.HWND;
export {windef};
import * as Conf from './lib/conf';
export {Conf as conf}; | /**
* node-win32-api
*
* @author waiting
* @license MIT
* @link https://github.com/waitingsong/node-win32-api
*/
import {parse_windef} from './lib/helper';
import * as windef from './lib/windef';
parse_windef(windef); // must at top
export {windef};
import * as Conf from './lib/conf';
export {Conf as conf};
import * as User32 from './lib/user32/index';
export {User32 as U};
export {User32};
import * as Kernel32 from './lib/kernel32/index';
export {Kernel32 as K};
export {Kernel32};
import * as Comctl32 from './lib/comctl32/index';
export {Comctl32 as C};
export {Comctl32};
import * as DStruct from './lib/struct';
export {DStruct as DS}; // Dict of Struct
export {DStruct};
import * as types from './lib/types';
export {types};
| Set parse_windef(windef) at top for gloabl effect | Set parse_windef(windef) at top for gloabl effect
| TypeScript | mit | waitingsong/node-win32-api,waitingsong/node-win32-api,waitingsong/node-win32-api | ---
+++
@@ -7,6 +7,13 @@
*/
import {parse_windef} from './lib/helper';
+
+import * as windef from './lib/windef';
+parse_windef(windef); // must at top
+export {windef};
+
+import * as Conf from './lib/conf';
+export {Conf as conf};
import * as User32 from './lib/user32/index';
export {User32 as U};
@@ -26,11 +33,3 @@
import * as types from './lib/types';
export {types};
-
-import * as windef from './lib/windef';
-parse_windef(windef);
-const foo = windef.HWND;
-export {windef};
-
-import * as Conf from './lib/conf';
-export {Conf as conf}; |
36fec781975f405e102fc9c299b691b6b70d1671 | src/plan-parser.ts | src/plan-parser.ts | const readPlan = require('./hcl-hil.js').readPlan;
export namespace terraform {
enum DiffAttrType {
DiffAttrUnknown = 0,
DiffAttrInput,
DiffAttrOutput
}
export interface ResourceAttrDiff {
Old: string;
New: string;
NewComputed: boolean;
NewRemoved: boolean;
NewExtra: any;
RequiresNew: boolean;
Sensitive: boolean;
Diff: DiffAttrType;
}
export interface InstanceDiff {
Attributes: { [key: string]: ResourceAttrDiff };
Destroy: boolean;
DestroyDeposed: boolean;
DestroyTainted: boolean;
Meta: { [key: string]: any };
}
export interface ModuleDiff {
Path: string[];
Resources: { [key: string]: InstanceDiff }
Destroy: boolean
}
export interface Diff {
Modules: ModuleDiff[]
}
export interface Plan {
Diff: any;
Module: any;
State: any;
Vars: { [key: string]: any };
Targets: string[];
TerraformVersion: string;
ProviderSHA256s: { [key: string]: any };
Backend: any;
Destroy: boolean;
}
} // namespace terraform
export function parsePlan(buffer: Buffer): terraform.Plan {
let [rawPlan, error] = readPlan(buffer);
if (error) {
throw new Error(`Error: ${error.Err}`);
}
return <terraform.Plan>rawPlan;
}
| const readPlan = require('./hcl-hil.js').readPlan;
export namespace terraform {
enum DiffAttrType {
DiffAttrUnknown = 0,
DiffAttrInput,
DiffAttrOutput
}
export interface ResourceAttrDiff {
Old: string;
New: string;
NewComputed: boolean;
NewRemoved: boolean;
NewExtra: any;
RequiresNew: boolean;
Sensitive: boolean;
Diff: DiffAttrType;
}
export interface InstanceDiff {
Attributes: { [key: string]: ResourceAttrDiff };
Destroy: boolean;
DestroyDeposed: boolean;
DestroyTainted: boolean;
Meta: { [key: string]: any };
}
export interface ModuleDiff {
Path: string[];
Resources: { [key: string]: InstanceDiff }
Destroy: boolean
}
export interface Diff {
Modules: ModuleDiff[]
}
export interface Plan {
Diff: Diff;
Module: any;
State: any;
Vars: { [key: string]: any };
Targets: string[];
TerraformVersion: string;
ProviderSHA256s: { [key: string]: any };
Backend: any;
Destroy: boolean;
}
} // namespace terraform
export function parsePlan(buffer: Buffer): terraform.Plan {
let [rawPlan, error] = readPlan(buffer);
if (error) {
throw new Error(`Error: ${error.Err}`);
}
return <terraform.Plan>rawPlan;
}
| Add type info to terraform.Plan.Diff | Add type info to terraform.Plan.Diff
| TypeScript | mpl-2.0 | hashicorp/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform | ---
+++
@@ -38,7 +38,7 @@
}
export interface Plan {
- Diff: any;
+ Diff: Diff;
Module: any;
State: any;
Vars: { [key: string]: any }; |
47302147abed1381f87f8053d7c4cd58c9ca0c67 | tests/cases/fourslash/completionInFunctionLikeBody.ts | tests/cases/fourslash/completionInFunctionLikeBody.ts | /// <reference path='fourslash.ts'/>
//// class Foo {
//// bar () {
//// /*1*/
//// class Foo1 {
//// bar1 () {
//// /*2*/
//// }
//// /*3*/
//// }
//// }
//// /*4*/
//// }
verify.completions(
{
marker: ["1", "2"],
includes: "async",
excludes: ["public", "private", "protected", "constructor", "readonly", "static", "abstract", "get", "set"],
},
{ marker: ["3", "4"], exact: completion.classElementKeywords, isNewIdentifierLocation: true },
);
| /// <reference path='fourslash.ts'/>
//// class Foo {
//// bar () {
//// /*1*/
//// class Foo1 {
//// bar1 () {
//// /*2*/
//// }
//// /*3*/
//// }
//// }
//// /*4*/
//// }
verify.completions(
{
marker: ["1", "2"],
includes: ["async", "await"],
excludes: ["public", "private", "protected", "constructor", "readonly", "static", "abstract", "get", "set"],
},
{ marker: ["3", "4"], exact: completion.classElementKeywords, isNewIdentifierLocation: true },
);
| Move await keyword to inside of function and test | Move await keyword to inside of function and test
| TypeScript | apache-2.0 | kpreisser/TypeScript,weswigham/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,weswigham/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,weswigham/TypeScript,Microsoft/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,Microsoft/TypeScript,donaldpipowitch/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,SaschaNaz/TypeScript,kitsonk/TypeScript,alexeagle/TypeScript,SaschaNaz/TypeScript,microsoft/TypeScript,kpreisser/TypeScript,kpreisser/TypeScript,donaldpipowitch/TypeScript,RyanCavanaugh/TypeScript,RyanCavanaugh/TypeScript,minestarks/TypeScript,nojvek/TypeScript,minestarks/TypeScript | ---
+++
@@ -16,7 +16,7 @@
verify.completions(
{
marker: ["1", "2"],
- includes: "async",
+ includes: ["async", "await"],
excludes: ["public", "private", "protected", "constructor", "readonly", "static", "abstract", "get", "set"],
},
{ marker: ["3", "4"], exact: completion.classElementKeywords, isNewIdentifierLocation: true }, |
97d45ada47675c90900d7f30ee0b690ff5765636 | test/lib/states.ts | test/lib/states.ts | 'use strict';
import assert from 'assert';
import GitLabStateHelper from '../../src/lib/states';
const projectId = process.env.GITLAB_TEST_PROJECT;
describe('States', function () {
describe('constructor()', function () {
it('should throw an error with invalid url', function() {
assert.throws(() => {
new GitLabStateHelper('ftp://foo.bar', '****');
}, /Invalid url!/);
});
it('should throw an error without token', function() {
assert.throws(() => {
new GitLabStateHelper('http://localhost', '****');
}, /Invalid token!/);
});
});
describe('getState()', function() {
this.timeout(5000);
it('should work', projectId ? async function() {
const states = await new GitLabStateHelper();
const result1 = await states.getState(projectId, 'develop');
assert.strictEqual(typeof result1.status, 'string');
assert.ok(typeof result1.coverage === 'string' || result1.coverage === undefined);
const result2 = await states.getState(projectId, 'develop');
assert.strictEqual(result2.status, result1.status);
assert.strictEqual(result2.coverage, result1.coverage);
} : () => Promise.resolve());
});
});
| 'use strict';
import assert from 'assert';
import GitLabStateHelper from '../../src/lib/states';
const projectId = process.env.GITLAB_TEST_PROJECT;
describe('States', function () {
describe('constructor()', function () {
it('should throw an error with invalid url', function() {
assert.throws(() => {
new GitLabStateHelper('ftp://foo.bar', '****');
}, /Invalid url!/);
});
it('should throw an error without token', function() {
assert.throws(() => {
new GitLabStateHelper('http://localhost', '****');
}, /Invalid token!/);
});
});
describe('getState()', function() {
this.timeout(30000);
it('should work', projectId ? async function() {
const states = await new GitLabStateHelper();
const result1 = await states.getState(projectId, 'develop');
assert.strictEqual(typeof result1.status, 'string');
assert.ok(typeof result1.coverage === 'string' || result1.coverage === undefined);
const result2 = await states.getState(projectId, 'develop');
assert.strictEqual(result2.status, result1.status);
assert.strictEqual(result2.coverage, result1.coverage);
} : () => Promise.resolve());
});
});
| Extend getState() timeout from 5s to 30s | test: Extend getState() timeout from 5s to 30s
| TypeScript | mit | sebbo2002/gitlab-badges,sebbo2002/gitlab-badges | ---
+++
@@ -20,7 +20,7 @@
});
describe('getState()', function() {
- this.timeout(5000);
+ this.timeout(30000);
it('should work', projectId ? async function() {
const states = await new GitLabStateHelper();
|
bde150fbe877b977600aa8a9dd9ad6bc4373e807 | app/scripts/components/form-react/FormGroup.tsx | app/scripts/components/form-react/FormGroup.tsx | import * as React from 'react';
import { WrappedFieldMetaProps } from 'redux-form';
import { FieldError } from './FieldError';
import { FormField } from './types';
interface FormGroupProps extends FormField {
meta: WrappedFieldMetaProps;
children: React.ReactChildren;
}
export const FormGroup = (props: FormGroupProps) => {
const { input, required, label, meta: {error}, children, ...rest } = props;
return (
<div className="form-group">
<label className="control-label">
{label}{required && <span className="text-danger"> *</span>}
</label>
{React.cloneElement((children as any), {input, ...rest})}
<FieldError error={error}/>
</div>
);
};
| import * as React from 'react';
// @ts-ignore
import { clearFields, WrappedFieldMetaProps } from 'redux-form';
import { FieldError } from './FieldError';
import { FormField } from './types';
interface FormGroupProps extends FormField {
meta: WrappedFieldMetaProps;
children: React.ReactChildren;
}
export class FormGroup extends React.PureComponent<FormGroupProps> {
render() {
const { input, required, label, meta: {error}, children, ...rest } = this.props;
return (
<div className="form-group">
<label className="control-label">
{label}{required && <span className="text-danger"> *</span>}
</label>
{React.cloneElement((children as any), {input, ...rest})}
<FieldError error={error}/>
</div>
);
}
componentWillUnmount() {
const { meta, input } = this.props;
meta.dispatch(clearFields(meta.form, false, false, input.name));
}
}
| Clear field in Redux-Form when field is unmounted | Clear field in Redux-Form when field is unmounted [WAL-1343]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -1,5 +1,6 @@
import * as React from 'react';
-import { WrappedFieldMetaProps } from 'redux-form';
+// @ts-ignore
+import { clearFields, WrappedFieldMetaProps } from 'redux-form';
import { FieldError } from './FieldError';
import { FormField } from './types';
@@ -9,15 +10,22 @@
children: React.ReactChildren;
}
-export const FormGroup = (props: FormGroupProps) => {
- const { input, required, label, meta: {error}, children, ...rest } = props;
- return (
- <div className="form-group">
- <label className="control-label">
- {label}{required && <span className="text-danger"> *</span>}
- </label>
- {React.cloneElement((children as any), {input, ...rest})}
- <FieldError error={error}/>
- </div>
- );
-};
+export class FormGroup extends React.PureComponent<FormGroupProps> {
+ render() {
+ const { input, required, label, meta: {error}, children, ...rest } = this.props;
+ return (
+ <div className="form-group">
+ <label className="control-label">
+ {label}{required && <span className="text-danger"> *</span>}
+ </label>
+ {React.cloneElement((children as any), {input, ...rest})}
+ <FieldError error={error}/>
+ </div>
+ );
+ }
+
+ componentWillUnmount() {
+ const { meta, input } = this.props;
+ meta.dispatch(clearFields(meta.form, false, false, input.name));
+ }
+} |
e3b2753cace9a0b9854d18e633ef7cb3e8027ac9 | demo/app/app.routing.ts | demo/app/app.routing.ts | import {RouterModule, Routes} from '@angular/router';
import {ModuleWithProviders} from '@angular/core';
import {MessagesDemoComponent} from './messages-demo.component';
const routes: Routes = [
{path: '', redirectTo: 'edit', pathMatch: 'full'},
{path: 'messages', component: MessagesDemoComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes); | import {RouterModule, Routes} from '@angular/router';
import {ModuleWithProviders} from '@angular/core';
import {MessagesDemoComponent} from './messages-demo.component';
const routes: Routes = [
{ path: '', redirectTo: 'edit', pathMatch: 'full' },
{ path: 'messages', component: MessagesDemoComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes); | Adjust to code style rules | Adjust to code style rules
| TypeScript | apache-2.0 | dainst/idai-components-2,dainst/idai-components-2,dainst/idai-components-2 | ---
+++
@@ -3,8 +3,8 @@
import {MessagesDemoComponent} from './messages-demo.component';
const routes: Routes = [
- {path: '', redirectTo: 'edit', pathMatch: 'full'},
- {path: 'messages', component: MessagesDemoComponent}
+ { path: '', redirectTo: 'edit', pathMatch: 'full' },
+ { path: 'messages', component: MessagesDemoComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes); |
e0f837ca87aac19f1cd43f274c18bae11a3f4dae | pages/_app.tsx | pages/_app.tsx | import { Fragment } from "react"
import App, { Container } from "next/app"
import Head from "next/head"
import "normalize.css/normalize.css"
// A custom app to support importing CSS files globally
class MyApp extends App {
public render(): JSX.Element {
const { Component, pageProps } = this.props
return (
<Fragment>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<div>
<Component {...pageProps} />
</div>
<style jsx>{`
div {
width: 70vw;
}
`}</style>
<style jsx global>{`
body {
display: flex;
justify-content: center;
align-items: center;
background: black;
color: white;
}
a {
color: #ffcc00;
}
@media (prefers-color-scheme: light) {
body {
background: white;
color: black;
}
a {
color: #007aff;
}
}
`}</style>
</Fragment>
)
}
}
export default MyApp
| import { Fragment } from "react"
import App, { Container } from "next/app"
import Head from "next/head"
import "normalize.css/normalize.css"
// A custom app to support importing CSS files globally
class MyApp extends App {
public render(): JSX.Element {
const { Component, pageProps } = this.props
return (
<Fragment>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<div>
<Component {...pageProps} />
</div>
<style jsx>{`
div {
width: calc(100vw - 32px);
}
@media (min-width: 480px) {
div {
width: 90vw;
}
}
@media (min-width: 1024px) {
div {
width: 70vw;
}
}
`}</style>
<style jsx global>{`
body {
display: flex;
justify-content: center;
align-items: center;
background: black;
color: white;
}
a {
color: #ffcc00;
}
@media (prefers-color-scheme: light) {
body {
background: white;
color: black;
}
a {
color: #007aff;
}
}
`}</style>
</Fragment>
)
}
}
export default MyApp
| Increase width of content on smaller screens | Increase width of content on smaller screens
| TypeScript | mit | JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk | ---
+++
@@ -19,7 +19,19 @@
<style jsx>{`
div {
- width: 70vw;
+ width: calc(100vw - 32px);
+ }
+
+ @media (min-width: 480px) {
+ div {
+ width: 90vw;
+ }
+ }
+
+ @media (min-width: 1024px) {
+ div {
+ width: 70vw;
+ }
}
`}</style>
|
960dfb4b8980bed232e7361d99b23871c202e535 | src/app/auth.http.service.ts | src/app/auth.http.service.ts | import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
import { Headers, Http, Response, ResponseOptionsArgs } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthHttpService {
constructor(private http: Http, private authService: AuthService) {
}
private appendHeaders(options?: ResponseOptionsArgs) {
let _options: ResponseOptionsArgs = options || {};
_options.headers = _options.headers || new Headers();
_options.headers.append('Authorization', `Bearer ${this.authService.getToken()}`);
return _options;
}
get(url: string, options?: ResponseOptionsArgs): Observable<Response> {
let _options = this.appendHeaders(options);
return this.http.get(url, _options);
}
} | import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
import { Headers, Http, Response, ResponseOptionsArgs } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthHttpService {
constructor(private http: Http, private authService: AuthService) {
}
private appendHeaders(options?: ResponseOptionsArgs) {
let _options: ResponseOptionsArgs = options || {};
_options.headers = _options.headers || new Headers();
_options.headers.append('Authorization', `Bearer ${this.authService.getToken()}`);
return _options;
}
get(url: string, options?: ResponseOptionsArgs): Observable<Response> {
let _options = this.appendHeaders(options);
return this.http.get(url, _options);
}
post(url: string, body: any, options?: ResponseOptionsArgs): Observable<Response> {
let _options = this.appendHeaders(options);
return this.http.post(url, body, _options);
}
delete(url: string, options?: ResponseOptionsArgs): Observable<Response> {
let _options = this.appendHeaders(options);
return this.http.delete(url, _options);
}
put(url: string, body: any, options?: ResponseOptionsArgs): Observable<Response> {
let _options = this.appendHeaders(options);
return this.http.put(url, body, _options);
}
patch(url: string, body: any, options?: ResponseOptionsArgs): Observable<Response> {
let _options = this.appendHeaders(options);
return this.http.patch(url, body, _options);
}
head(url: string, options?: ResponseOptionsArgs): Observable<Response> {
let _options = this.appendHeaders(options);
return this.http.head(url, _options);
}
options(url: string, options?: ResponseOptionsArgs): Observable<Response> {
let _options = this.appendHeaders(options);
return this.http.options(url, _options);
}
} | Add other methods to AuthHttpService | Add other methods to AuthHttpService
| TypeScript | mit | alex-dmtr/roadmap-angular,alex-dmtr/roadmap-angular,alex-dmtr/roadmap-angular | ---
+++
@@ -24,4 +24,41 @@
return this.http.get(url, _options);
}
+
+ post(url: string, body: any, options?: ResponseOptionsArgs): Observable<Response> {
+ let _options = this.appendHeaders(options);
+
+ return this.http.post(url, body, _options);
+ }
+
+ delete(url: string, options?: ResponseOptionsArgs): Observable<Response> {
+ let _options = this.appendHeaders(options);
+
+ return this.http.delete(url, _options);
+ }
+
+ put(url: string, body: any, options?: ResponseOptionsArgs): Observable<Response> {
+ let _options = this.appendHeaders(options);
+
+ return this.http.put(url, body, _options);
+ }
+
+ patch(url: string, body: any, options?: ResponseOptionsArgs): Observable<Response> {
+ let _options = this.appendHeaders(options);
+
+ return this.http.patch(url, body, _options);
+ }
+
+ head(url: string, options?: ResponseOptionsArgs): Observable<Response> {
+ let _options = this.appendHeaders(options);
+
+ return this.http.head(url, _options);
+ }
+
+ options(url: string, options?: ResponseOptionsArgs): Observable<Response> {
+ let _options = this.appendHeaders(options);
+
+ return this.http.options(url, _options);
+ }
+
} |
55f4dac3d3569fb4b8c35f5e63ead24b97316921 | packages/tux/src/utils/accessors.ts | packages/tux/src/utils/accessors.ts | /**
* Gets the value of a property on an object.
*
* @param {Object} obj The value to be clamped
* @param {String} key The lower boundary of the output range
* @returns {Object} the property value or 'null'.
*/
export function get(obj: any, key: string | string[]): any {
if (key.length === 0 || !obj) {
return obj ? obj : null
}
const parts = _splitKey(key)
const nextLevel = obj[parts[0]]
const restOfKey = parts.slice(1, parts.length).join('.')
return get(nextLevel, restOfKey)
}
export function set(obj: any, key: string | string[], value: any): void {
const parts = _splitKey(key)
if (parts.length === 1) {
obj[parts[0]] = value
} else {
const lastKeyPartIndex = parts.length - 1
const parent = get(obj, parts.slice(0, lastKeyPartIndex))
const lastKeyPart = parts[lastKeyPartIndex]
parent[lastKeyPart] = value
}
}
function _splitKey(key: string | string[]): string[] {
if (key instanceof Array) {
return key
}
return key.split('.')
}
| /**
* Gets the value of a property on an object.
*
* @param {Object} obj The value to be clamped
* @param {String} key The lower boundary of the output range
* @returns {Object} the property value or 'null'.
*/
export function get(obj: any, key: string | string[]): any {
if (key.length === 0 || !obj) {
return obj ? obj : null
}
const parts = _splitKey(key)
const nextLevel = obj[parts[0]]
const restOfKey = parts.slice(1, parts.length).join('.')
return get(nextLevel, restOfKey)
}
export function set(obj: any, key: string | string[], value: any): void {
const parts = _splitKey(key)
if (parts.length === 1) {
obj[parts[0]] = value
} else if (parts.length > 1) {
const lastKeyPartIndex = parts.length - 1
const parent = get(obj, parts.slice(0, lastKeyPartIndex))
const lastKeyPart = parts[lastKeyPartIndex]
parent[lastKeyPart] = value
}
}
function _splitKey(key: string | string[]): string[] {
if (key instanceof Array) {
return key
}
return key.split('.')
}
| Add an empty-key guard around logic in set | Add an empty-key guard around logic in set
| TypeScript | mit | aranja/tux,aranja/tux,aranja/tux | ---
+++
@@ -20,7 +20,7 @@
const parts = _splitKey(key)
if (parts.length === 1) {
obj[parts[0]] = value
- } else {
+ } else if (parts.length > 1) {
const lastKeyPartIndex = parts.length - 1
const parent = get(obj, parts.slice(0, lastKeyPartIndex))
const lastKeyPart = parts[lastKeyPartIndex] |
22984387b04d0fc775d1b50c1a898a43737e1690 | src/loaders/typeormLoader.ts | src/loaders/typeormLoader.ts | import { MicroframeworkLoader, MicroframeworkSettings } from 'microframework-w3tec';
import { createConnection } from 'typeorm';
import { env } from '../env';
export const typeormLoader: MicroframeworkLoader = async (settings: MicroframeworkSettings | undefined) => {
const connection = await createConnection({
type: env.db.type as any, // See createConnection options for valid types
host: env.db.host,
port: env.db.port,
username: env.db.username,
password: env.db.password,
database: env.db.database,
synchronize: env.db.synchronize,
logging: env.db.logging,
entities: env.app.dirs.entities,
migrations: env.app.dirs.migrations,
});
if (settings) {
settings.setData('connection', connection);
settings.onShutdown(() => connection.close());
}
};
| import { MicroframeworkLoader, MicroframeworkSettings } from 'microframework-w3tec';
import { createConnection, getConnectionOptions } from 'typeorm';
import { env } from '../env';
export const typeormLoader: MicroframeworkLoader = async (settings: MicroframeworkSettings | undefined) => {
const loadedConnectionOptions = await getConnectionOptions();
const connectionOptions = Object.assign(loadedConnectionOptions, {
type: env.db.type as any, // See createConnection options for valid types
host: env.db.host,
port: env.db.port,
username: env.db.username,
password: env.db.password,
database: env.db.database,
synchronize: env.db.synchronize,
logging: env.db.logging,
entities: env.app.dirs.entities,
migrations: env.app.dirs.migrations,
});
const connection = await createConnection(connectionOptions);
if (settings) {
settings.setData('connection', connection);
settings.onShutdown(() => connection.close());
}
};
| Load options by type orm (e.g. env vars, config files) and then overwrite with env.ts | Load options by type orm (e.g. env vars, config files) and then overwrite with env.ts
| TypeScript | mit | w3tecch/express-typescript-boilerplate,w3tecch/express-typescript-boilerplate,w3tecch/express-typescript-boilerplate | ---
+++
@@ -1,11 +1,13 @@
import { MicroframeworkLoader, MicroframeworkSettings } from 'microframework-w3tec';
-import { createConnection } from 'typeorm';
+import { createConnection, getConnectionOptions } from 'typeorm';
import { env } from '../env';
export const typeormLoader: MicroframeworkLoader = async (settings: MicroframeworkSettings | undefined) => {
- const connection = await createConnection({
+ const loadedConnectionOptions = await getConnectionOptions();
+
+ const connectionOptions = Object.assign(loadedConnectionOptions, {
type: env.db.type as any, // See createConnection options for valid types
host: env.db.host,
port: env.db.port,
@@ -18,6 +20,8 @@
migrations: env.app.dirs.migrations,
});
+ const connection = await createConnection(connectionOptions);
+
if (settings) {
settings.setData('connection', connection);
settings.onShutdown(() => connection.close()); |
eeac1b49bc40fe6d8c43f0bf22405d21419fc482 | 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.1"); } // 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"); } // TODO: Confirm this when Flutter fix lands
}
| Fix version that has the test fix in | Fix version that has the test fix in
| 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.1"); } // TODO: Confirm this when Flutter fix lands
+ get hasTestGroupFix() { return versionIsAtLeast(this.version, "1.3.4"); } // TODO: Confirm this when Flutter fix lands
} |
f731317ef17457628ef32cd1f8d3454498ac6f95 | src/registerServiceWorker.ts | src/registerServiceWorker.ts | /* eslint-disable no-console */
import { register } from 'register-service-worker';
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready() {
console.log(
'App is being served from cache by a service worker.\n' +
'For more details, visit https://goo.gl/AFskqB'
);
},
registered() {
console.log('Service worker has been registered.');
},
cached() {
console.log('Content has been cached for offline use.');
},
updatefound() {
console.log('New content is downloading.');
},
updated() {
console.log('New content is available; refreshing...');
window.location.reload();
},
offline() {
console.log(
'No internet connection found. App is running in offline mode.'
);
},
error(error) {
console.error('Error during service worker registration:', error);
},
});
}
| /* eslint-disable no-console */
import { register } from 'register-service-worker';
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready() {
console.log(
'App is being served from cache by a service worker.\n' +
'For more details, visit https://goo.gl/AFskqB'
);
},
registered() {
console.log('Service worker has been registered.');
},
cached() {
console.log('Content has been cached for offline use.');
},
updatefound() {
console.log('New content is downloading.');
},
updated(registration) {
console.log('New content is available; please refresh.');
document.dispatchEvent(
new CustomEvent('swUpdated', { detail: registration })
);
},
offline() {
console.log(
'No internet connection found. App is running in offline mode.'
);
},
error(error) {
console.error('Error during service worker registration:', error);
},
});
}
| Add custom event for updated | Add custom event for updated
| TypeScript | mit | babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop | ---
+++
@@ -19,9 +19,11 @@
updatefound() {
console.log('New content is downloading.');
},
- updated() {
- console.log('New content is available; refreshing...');
- window.location.reload();
+ updated(registration) {
+ console.log('New content is available; please refresh.');
+ document.dispatchEvent(
+ new CustomEvent('swUpdated', { detail: registration })
+ );
},
offline() {
console.log( |
b35f7725d80c5c6f6a2bd3eda2ce91d6b63f0258 | src/client/components/Dropdown.tsx | src/client/components/Dropdown.tsx | import React from 'react'
import classnames from 'classnames'
import { Backdrop } from './Backdrop'
export interface DropdownProps {
label: string | React.ReactElement
children: React.ReactElement<{onClick: () => void}>[]
}
export interface DropdownState {
open: boolean
}
export class Dropdown
extends React.PureComponent<DropdownProps, DropdownState> {
state = { open: false }
handleClick = () => {
this.setState({ open: !this.state.open })
}
close = () => {
this.setState({ open: false })
}
render() {
const { handleClick } = this
const classNames = classnames('dropdown-list', {
'dropdown-list-open': this.state.open,
})
const menu = React.Children.map(
this.props.children,
child => {
const onClick = child.props.onClick
return React.cloneElement(child, {
...child.props,
onClick: () => {
handleClick()
onClick()
},
})
},
)
return (
<div className='dropdown'>
<button onClick={handleClick} >{this.props.label}</button>
<Backdrop visible={this.state.open} onClick={this.close} />
<ul className={classNames}>
{menu}
</ul>
</div>
)
}
}
| import React from 'react'
import classnames from 'classnames'
export interface DropdownProps {
label: string | React.ReactElement
children: React.ReactElement<{onClick: () => void}>[]
}
export interface DropdownState {
open: boolean
}
export class Dropdown
extends React.PureComponent<DropdownProps, DropdownState> {
state = { open: false }
handleClick = () => {
this.setState({ open: !this.state.open })
}
close = () => {
this.setState({ open: false })
}
render() {
const { handleClick } = this
const classNames = classnames('dropdown-list', {
'dropdown-list-open': this.state.open,
})
const menu = React.Children.map(
this.props.children,
child => {
const onClick = child.props.onClick
return React.cloneElement(child, {
...child.props,
onClick: () => {
handleClick()
onClick()
},
})
},
)
return (
<div className='dropdown'>
<button onClick={handleClick} >{this.props.label}</button>
<ul className={classNames}>
{menu}
</ul>
</div>
)
}
}
| Remove backdrop from regular dropdown | Remove backdrop from regular dropdown
Backdrop causes video menu to be unclickable
| TypeScript | mit | jeremija/peer-calls,jeremija/peer-calls,jeremija/peer-calls | ---
+++
@@ -1,6 +1,5 @@
import React from 'react'
import classnames from 'classnames'
-import { Backdrop } from './Backdrop'
export interface DropdownProps {
label: string | React.ReactElement
@@ -44,7 +43,6 @@
return (
<div className='dropdown'>
<button onClick={handleClick} >{this.props.label}</button>
- <Backdrop visible={this.state.open} onClick={this.close} />
<ul className={classNames}>
{menu}
</ul> |
8c5c59a02a636d5a08733d2477311fa82c82007e | src/Lime/Protocol/Security/Authentication.ts | src/Lime/Protocol/Security/Authentication.ts | export class Authentication {
scheme: AuthenticationScheme;
}
export class GuestAuthentication extends Authentication {
scheme = AuthenticationScheme.GUEST;
}
export class TransportAuthentication extends Authentication {
scheme = AuthenticationScheme.TRANSPORT;
}
export class PlainAuthentication extends Authentication {
scheme = AuthenticationScheme.PLAIN;
password: string;
}
export class KeyAuthentication extends Authentication {
scheme = AuthenticationScheme.KEY;
key: string;
}
export const AuthenticationScheme = {
GUEST: <AuthenticationScheme> "guest",
PLAIN: <AuthenticationScheme> "plain",
TRANSPORT: <AuthenticationScheme> "transport",
KEY: <AuthenticationScheme> "key"
};
export type AuthenticationScheme
= "guest"
| "plain"
| "transport"
| "key"
;
| export class Authentication {
scheme: AuthenticationScheme;
}
export class GuestAuthentication extends Authentication {
scheme = AuthenticationScheme.GUEST;
}
export class TransportAuthentication extends Authentication {
scheme = AuthenticationScheme.TRANSPORT;
}
export class PlainAuthentication extends Authentication {
scheme = AuthenticationScheme.PLAIN;
password: string;
constructor(password: string) {
super();
this.password = password;
}
}
export class KeyAuthentication extends Authentication {
scheme = AuthenticationScheme.KEY;
key: string;
constructor(key: string) {
super();
this.key = key;
}
}
export const AuthenticationScheme = {
GUEST: <AuthenticationScheme> "guest",
PLAIN: <AuthenticationScheme> "plain",
TRANSPORT: <AuthenticationScheme> "transport",
KEY: <AuthenticationScheme> "key"
};
export type AuthenticationScheme
= "guest"
| "plain"
| "transport"
| "key"
;
| Add parametrized constructors to plain and key authentications | Add parametrized constructors to plain and key authentications
| TypeScript | apache-2.0 | takenet/lime-js,takenet/lime-js | ---
+++
@@ -10,10 +10,18 @@
export class PlainAuthentication extends Authentication {
scheme = AuthenticationScheme.PLAIN;
password: string;
+ constructor(password: string) {
+ super();
+ this.password = password;
+ }
}
export class KeyAuthentication extends Authentication {
scheme = AuthenticationScheme.KEY;
key: string;
+ constructor(key: string) {
+ super();
+ this.key = key;
+ }
}
export const AuthenticationScheme = { |
d94c887c8e78e57565fe09714024d4b82cbc7cd7 | tests/cases/fourslash/extendArrayInterfaceMember.ts | tests/cases/fourslash/extendArrayInterfaceMember.ts | /// <reference path="fourslash.ts"/>
////var x = [1, 2, 3];
////var y/*y*/ = x./*1*/pop/*2*/(5);
////
/* BUG 703066
verify.errorExistsBetweenMarkers("1", "2");
verify.numberOfErrorsInCurrentFile(2);
// Expected errors are:
// - Supplied parameters do not match any signature of call target.
// - Could not select overload for 'call' expression.
goTo.marker("y");
verify.quickInfoIs("any");
goTo.eof();
edit.insert("interface Array<T> { pop(def: T): T; }");
verify.not.errorExistsBetweenMarkers("1", "2");
goTo.marker("y");
verify.quickInfoIs("number");
verify.numberOfErrorsInCurrentFile(0);
*/ | /// <reference path="fourslash.ts"/>
////var x = [1, 2, 3];
////var y/*y*/ = x./*1*/pop/*2*/(5);
////
//BUG 703066
verify.errorExistsBetweenMarkers("1", "2");
verify.numberOfErrorsInCurrentFile(2);
// Expected errors are:
// - Supplied parameters do not match any signature of call target.
// - Could not select overload for 'call' expression.
goTo.marker("y");
verify.quickInfoIs("any");
goTo.eof();
edit.insert("interface Array<T> { pop(def: T): T; }");
verify.not.errorExistsBetweenMarkers("1", "2");
goTo.marker("y");
verify.quickInfoIs("number");
verify.numberOfErrorsInCurrentFile(0);
| Update fourslash test for bug fixes | Update fourslash test for bug fixes
| TypeScript | apache-2.0 | mbrowne/typescript-dci,hippich/typescript,hippich/typescript,mbrowne/typescript-dci,hippich/typescript,popravich/typescript,popravich/typescript,mbebenita/shumway.ts,mbrowne/typescript-dci,popravich/typescript,fdecampredon/jsx-typescript-old-version,mbebenita/shumway.ts,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,fdecampredon/jsx-typescript-old-version,mbrowne/typescript-dci | ---
+++
@@ -4,7 +4,7 @@
////var y/*y*/ = x./*1*/pop/*2*/(5);
////
-/* BUG 703066
+//BUG 703066
verify.errorExistsBetweenMarkers("1", "2");
verify.numberOfErrorsInCurrentFile(2);
// Expected errors are:
@@ -21,4 +21,3 @@
goTo.marker("y");
verify.quickInfoIs("number");
verify.numberOfErrorsInCurrentFile(0);
-*/ |
5abc7f7cb883215eda1c64474448d041aee1d68b | lib/utils/Config.ts | lib/utils/Config.ts | import {ILogger} from "./ILogger";
import * as _ from "lodash";
import {genId} from "./uuid";
import {MutedLogger} from "./MutedLogger";
export type NeographyConfigParams = {
host:string;
username:string;
password:string;
uidGenerator?:() => string;
objectTransform?:((obj:any) => any)[];
sessionsPoolSize?:number;
logger?:ILogger;
debug?:boolean;
}
export class Config {
host:string;
username:string;
password:string;
uidGenerator:() => string;
objectTransform:((obj:any) => any)[];
sessionsPoolSize:number;
logger:ILogger;
debug:boolean;
constructor(private params:NeographyConfigParams) {
_.merge(this, {
objectTransform: [],
uidGenerator: genId,
poolSize: 10,
logger: new MutedLogger(),
debug: false
}, params);
}
} | import {ILogger} from "./ILogger";
import * as _ from "lodash";
import {genId} from "./uuid";
import {MutedLogger} from "./MutedLogger";
export type NeographyConfigParams = {
host:string;
username:string;
password:string;
uidGenerator?:() => string;
objectTransform?:((obj:any) => any)[];
sessionsPoolSize?:number;
logger?:ILogger;
debug?:boolean;
}
export class Config {
host:string;
username:string;
password:string;
uidGenerator:() => string;
objectTransform:((obj:any) => any)[];
sessionsPoolSize:number;
logger:ILogger;
debug:boolean;
constructor(private params:NeographyConfigParams) {
_.merge(this, {
objectTransform: [],
uidGenerator: genId,
sessionsPoolSize: 10,
logger: new MutedLogger(),
debug: false
}, params);
}
} | Fix wrong default property assignment | Fix wrong default property assignment
| TypeScript | mit | robak86/neography | ---
+++
@@ -28,7 +28,7 @@
_.merge(this, {
objectTransform: [],
uidGenerator: genId,
- poolSize: 10,
+ sessionsPoolSize: 10,
logger: new MutedLogger(),
debug: false
}, params); |
8068d5a72c5ce9ee6f2bf8668f4e41f1d2c86c56 | src/types/sdk.ts | src/types/sdk.ts | /**
* @license
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const enum Sdk {
App = 'firebase-app.js',
Auth = 'firebase-auth.js',
Database = 'firebase-database.js',
Firestore = 'firebase-firestore.js',
Functions = 'firebase-functions.js',
Messaging = 'firebase-messaging.js',
Storage = 'firebase-storage.js',
}
export const sdks = [
Sdk.App,
Sdk.Auth,
Sdk.Database,
Sdk.Firestore,
Sdk.Functions,
Sdk.Messaging,
Sdk.Storage,
];
export function deserialize(name: string): Sdk {
for (const sdk of sdks) {
if (sdk === name) {
return sdk;
}
}
return null;
}
| /**
* @license
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const enum Sdk {
App = 'firebase-app.js',
Auth = 'firebase-auth.js',
Database = 'firebase-database.js',
Firestore = 'firebase-firestore.js',
Functions = 'firebase-functions.js',
Messaging = 'firebase-messaging.js',
Performance = 'firebase-performance.js',
Storage = 'firebase-storage.js',
}
export const sdks = [
Sdk.App,
Sdk.Auth,
Sdk.Database,
Sdk.Firestore,
Sdk.Functions,
Sdk.Messaging,
Sdk.Performance,
Sdk.Storage,
];
export function deserialize(name: string): Sdk {
for (const sdk of sdks) {
if (sdk === name) {
return sdk;
}
}
return null;
}
| Include Firebase performance SDK in the test. | Include Firebase performance SDK in the test.
| TypeScript | apache-2.0 | FirebaseExtended/firebase-js-sdk-performance-dashboard,FirebaseExtended/firebase-js-sdk-performance-dashboard | ---
+++
@@ -22,6 +22,7 @@
Firestore = 'firebase-firestore.js',
Functions = 'firebase-functions.js',
Messaging = 'firebase-messaging.js',
+ Performance = 'firebase-performance.js',
Storage = 'firebase-storage.js',
}
@@ -32,6 +33,7 @@
Sdk.Firestore,
Sdk.Functions,
Sdk.Messaging,
+ Sdk.Performance,
Sdk.Storage,
];
|
987ad8d7b7361a95131d7033be00bbd850424644 | src/main.ts | src/main.ts |
///<reference path="../bower_components/babylonjs/dist/preview release/babylon.d.ts"/>
///<reference path="../typings/browser.d.ts"/>
import Nanoshooter from "./Nanoshooter"
// This main script is the entry point for the web browser.
// - Instantiate and start the Nanoshooter game.
// - Log some timing/profiling information.
// - Start running the game.
const timeBeforeInitialize = performance.now()
// Initialize the Nanoshooter game.
const nanoshooter = window["nanoshooter"] = new Nanoshooter({
log: (...messages: any[]) => console.log.apply(console, messages),
hostElement: <HTMLElement>document.querySelector(".game")
})
{ // Establish a framerate display.
const fps = <HTMLElement>document.querySelector(".fps")
setInterval(() => {
fps.textContent = nanoshooter.getFramerate().toFixed(0)
}, 100)
}
// Start running the game engine.
nanoshooter.start()
// Log the profiling results.
const timeAfterInitialize = performance.now()
const loadTime = (timeBeforeInitialize - performance.timing.navigationStart).toFixed(0)
const initializeTime = (timeAfterInitialize - timeBeforeInitialize).toFixed(0)
console.debug(`→ Page load ${loadTime} ms / Game initialization ${initializeTime} ms`)
|
///<reference path="../bower_components/babylonjs/dist/preview release/babylon.d.ts"/>
///<reference path="../typings/browser.d.ts"/>
import Nanoshooter from "./Nanoshooter"
// This main script is the entry point for the web browser.
// - Instantiate and start the Nanoshooter game.
// - Log some timing/profiling information.
// - Start running the game.
const timeBeforeInitialize = (+new Date)
// Initialize the Nanoshooter game.
const nanoshooter = window["nanoshooter"] = new Nanoshooter({
log: (...messages: any[]) => console.log.apply(console, messages),
hostElement: <HTMLElement>document.querySelector(".game")
})
{ // Establish a framerate display.
const fps = <HTMLElement>document.querySelector(".fps")
setInterval(() => {
fps.textContent = nanoshooter.getFramerate().toFixed(0)
}, 100)
}
// Start running the game engine.
nanoshooter.start()
// Log the profiling results.
const timeAfterInitialize = (+new Date)
const loadTime = (timeBeforeInitialize - performance.timing.navigationStart).toFixed(0)
const initializeTime = (timeAfterInitialize - timeBeforeInitialize).toFixed(0)
console.debug(`(→) Page load ${loadTime} ms / Game initialization ${initializeTime} ms`)
| Fix page load profiling debug log. | Fix page load profiling debug log.
| TypeScript | mit | ChaseMoskal/Nanoshooter,ChaseMoskal/Nanoshooter | ---
+++
@@ -9,7 +9,7 @@
// - Log some timing/profiling information.
// - Start running the game.
-const timeBeforeInitialize = performance.now()
+const timeBeforeInitialize = (+new Date)
// Initialize the Nanoshooter game.
const nanoshooter = window["nanoshooter"] = new Nanoshooter({
@@ -28,7 +28,7 @@
nanoshooter.start()
// Log the profiling results.
-const timeAfterInitialize = performance.now()
+const timeAfterInitialize = (+new Date)
const loadTime = (timeBeforeInitialize - performance.timing.navigationStart).toFixed(0)
const initializeTime = (timeAfterInitialize - timeBeforeInitialize).toFixed(0)
-console.debug(`→ Page load ${loadTime} ms / Game initialization ${initializeTime} ms`)
+console.debug(`(→) Page load ${loadTime} ms / Game initialization ${initializeTime} ms`) |
9a25649e2d28f777c9ef41d1f0545b2bda782fc2 | applications/mail/src/app/components/sidebar/MailSidebar.tsx | applications/mail/src/app/components/sidebar/MailSidebar.tsx | import React from 'react';
import { c } from 'ttag';
import { Location } from 'history';
import { Sidebar, SidebarPrimaryButton, SidebarNav } from 'react-components';
import { MESSAGE_ACTIONS } from '../../constants';
import MailSidebarList from './MailSidebarList';
import SidebarVersion from './SidebarVersion';
import { OnCompose } from '../../hooks/useCompose';
interface Props {
labelID: string;
expanded?: boolean;
location: Location;
onToggleExpand: () => void;
onCompose: OnCompose;
}
const MailSidebar = ({ labelID, expanded = false, location, onToggleExpand, onCompose }: Props) => {
const handleCompose = () => {
onCompose({ action: MESSAGE_ACTIONS.NEW });
};
return (
<Sidebar
expanded={expanded}
onToggleExpand={onToggleExpand}
primary={
<SidebarPrimaryButton onClick={handleCompose} data-test-id="sidebar:compose">
{c('Action').t`Compose`}
</SidebarPrimaryButton>
}
version={<SidebarVersion />}
>
<SidebarNav>
<MailSidebarList labelID={labelID} location={location} />
</SidebarNav>
</Sidebar>
);
};
export default MailSidebar;
| import React from 'react';
import { c } from 'ttag';
import { Location } from 'history';
import { Sidebar, SidebarPrimaryButton, SidebarNav, MainLogo } from 'react-components';
import { MESSAGE_ACTIONS } from '../../constants';
import MailSidebarList from './MailSidebarList';
import SidebarVersion from './SidebarVersion';
import { OnCompose } from '../../hooks/useCompose';
interface Props {
labelID: string;
expanded?: boolean;
location: Location;
onToggleExpand: () => void;
onCompose: OnCompose;
}
const MailSidebar = ({ labelID, expanded = false, location, onToggleExpand, onCompose }: Props) => {
const handleCompose = () => {
onCompose({ action: MESSAGE_ACTIONS.NEW });
};
return (
<Sidebar
expanded={expanded}
onToggleExpand={onToggleExpand}
primary={
<SidebarPrimaryButton onClick={handleCompose} data-test-id="sidebar:compose">
{c('Action').t`Compose`}
</SidebarPrimaryButton>
}
logo={<MainLogo to="/inbox" />}
version={<SidebarVersion />}
>
<SidebarNav>
<MailSidebarList labelID={labelID} location={location} />
</SidebarNav>
</Sidebar>
);
};
export default MailSidebar;
| Fix logo in mobile sidebar | [Hotfix] Fix logo in mobile sidebar
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,7 +1,7 @@
import React from 'react';
import { c } from 'ttag';
import { Location } from 'history';
-import { Sidebar, SidebarPrimaryButton, SidebarNav } from 'react-components';
+import { Sidebar, SidebarPrimaryButton, SidebarNav, MainLogo } from 'react-components';
import { MESSAGE_ACTIONS } from '../../constants';
import MailSidebarList from './MailSidebarList';
@@ -29,6 +29,7 @@
{c('Action').t`Compose`}
</SidebarPrimaryButton>
}
+ logo={<MainLogo to="/inbox" />}
version={<SidebarVersion />}
>
<SidebarNav> |
2a30c1ad011e31631f1b5d40bbd9799336422c20 | source/services/time/time.service.ts | source/services/time/time.service.ts | import { OpaqueToken, Provider } from 'angular2/core';
import * as moment from 'moment';
import { CompareResult } from '../../types/compareResult';
import { defaultFormats } from '../date/date.module';
export interface ITimeUtility {
compareTimes(time1: string, time2: string): CompareResult;
}
export class TimeUtility {
compareTimes(time1: string, time2: string): CompareResult {
let format: string = defaultFormats.timeFormat;
let start: moment.Moment = moment(time1, format);
let end: moment.Moment = moment(time2, format);
if (start.hours() == end.hours()
&& start.minutes() == end.minutes()) {
return CompareResult.equal;
} else if (start.hours() >= end.hours()
&& start.minutes() >= end.minutes()) {
return CompareResult.greater;
} else {
return CompareResult.less;
}
}
}
export let timeUtility: ITimeUtility = new TimeUtility();
export const timeToken: OpaqueToken = new OpaqueToken('A service for comparing times');
export const TIME_PROVIDER: Provider = new Provider(timeToken, {
useClass: TimeUtility,
});
| import { OpaqueToken, Provider } from 'angular2/core';
import * as moment from 'moment';
import { CompareResult } from '../../types/compareResult';
import { defaultFormats } from '../date/date.module';
export interface ITimeUtility {
compareTimes(time1: string, time2: string): CompareResult;
}
export class TimeUtility {
compareTimes(time1: string, time2: string): CompareResult {
let format: string = defaultFormats.timeFormat;
let start: moment.Moment = moment(time1, format);
let end: moment.Moment = moment(time2, format);
if (start.hours() === end.hours()
&& start.minutes() === end.minutes()) {
return CompareResult.equal;
} else if (start.hours() >= end.hours()
&& start.minutes() >= end.minutes()) {
return CompareResult.greater;
} else {
return CompareResult.less;
}
}
}
export let timeUtility: ITimeUtility = new TimeUtility();
export const timeToken: OpaqueToken = new OpaqueToken('A utility for working with time');
export const TIME_PROVIDER: Provider = new Provider(timeToken, {
useClass: TimeUtility,
});
| Migrate time utility to angular 2. | Migrate time utility to angular 2.
| TypeScript | mit | RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities | ---
+++
@@ -15,8 +15,8 @@
let start: moment.Moment = moment(time1, format);
let end: moment.Moment = moment(time2, format);
- if (start.hours() == end.hours()
- && start.minutes() == end.minutes()) {
+ if (start.hours() === end.hours()
+ && start.minutes() === end.minutes()) {
return CompareResult.equal;
} else if (start.hours() >= end.hours()
&& start.minutes() >= end.minutes()) {
@@ -29,7 +29,7 @@
export let timeUtility: ITimeUtility = new TimeUtility();
-export const timeToken: OpaqueToken = new OpaqueToken('A service for comparing times');
+export const timeToken: OpaqueToken = new OpaqueToken('A utility for working with time');
export const TIME_PROVIDER: Provider = new Provider(timeToken, {
useClass: TimeUtility, |
55e28a5872218548e9a29dda5d787205ecea3f0f | app/src/lib/markdown-filters/close-keyword-filter.ts | app/src/lib/markdown-filters/close-keyword-filter.ts | import { INodeFilter, MarkdownContext } from './node-filter'
export class CloseKeywordFilter implements INodeFilter {
public constructor(
/** The context from which the markdown content originated from - such as a PullRequest or PullRequest Comment */
private readonly markdownContext: MarkdownContext
) {}
/**
* Close keyword filter iterates on all text nodes that are not inside a pre,
* code, or anchor tag.
*/
public createFilterTreeWalker(doc: Document): TreeWalker {
return doc.createTreeWalker(doc, NodeFilter.SHOW_TEXT, {
acceptNode: node => {
return node.parentNode !== null &&
['CODE', 'PRE', 'A'].includes(node.parentNode.nodeName)
? NodeFilter.FILTER_SKIP
: NodeFilter.FILTER_ACCEPT
},
})
}
public async filter(node: Node): Promise<ReadonlyArray<Node> | null> {
if (
this.markdownContext !== 'Commit' &&
this.markdownContext !== 'PullRequest'
) {
return null
}
return null
}
}
| import { INodeFilter, MarkdownContext } from './node-filter'
export class CloseKeywordFilter implements INodeFilter {
/** Markdown locations that can have closing keywords */
private issueClosingLocations: ReadonlyArray<MarkdownContext> = [
'Commit',
'PullRequest',
]
public constructor(
/** The context from which the markdown content originated from - such as a PullRequest or PullRequest Comment */
private readonly markdownContext: MarkdownContext
) {}
/**
* Close keyword filter iterates on all text nodes that are not inside a pre,
* code, or anchor tag.
*/
public createFilterTreeWalker(doc: Document): TreeWalker {
return doc.createTreeWalker(doc, NodeFilter.SHOW_TEXT, {
acceptNode: node => {
return node.parentNode !== null &&
['CODE', 'PRE', 'A'].includes(node.parentNode.nodeName)
? NodeFilter.FILTER_SKIP
: NodeFilter.FILTER_ACCEPT
},
})
}
public async filter(node: Node): Promise<ReadonlyArray<Node> | null> {
if (!this.issueClosingLocations.includes(this.markdownContext)) {
return null
}
return null
}
}
| Add variable of types of context this filter accepts | Add variable of types of context this filter accepts
| TypeScript | mit | shiftkey/desktop,desktop/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,desktop/desktop | ---
+++
@@ -1,6 +1,12 @@
import { INodeFilter, MarkdownContext } from './node-filter'
export class CloseKeywordFilter implements INodeFilter {
+ /** Markdown locations that can have closing keywords */
+ private issueClosingLocations: ReadonlyArray<MarkdownContext> = [
+ 'Commit',
+ 'PullRequest',
+ ]
+
public constructor(
/** The context from which the markdown content originated from - such as a PullRequest or PullRequest Comment */
private readonly markdownContext: MarkdownContext
@@ -22,10 +28,7 @@
}
public async filter(node: Node): Promise<ReadonlyArray<Node> | null> {
- if (
- this.markdownContext !== 'Commit' &&
- this.markdownContext !== 'PullRequest'
- ) {
+ if (!this.issueClosingLocations.includes(this.markdownContext)) {
return null
}
|
02231f542cfbe4b88c6b28c13656a1ece0541d0b | addons/actions/src/preview/action.ts | addons/actions/src/preview/action.ts | import uuid from 'uuid/v1';
import { addons } from '@storybook/addons';
import { EVENT_ID } from '../constants';
import { ActionDisplay, ActionOptions, HandlerFunction } from '../models';
export function action(name: string, options: ActionOptions = {}): HandlerFunction {
const actionOptions = {
...options,
};
// tslint:disable-next-line:no-shadowed-variable
const handler = function action(...args: any[]) {
const channel = addons.getChannel();
const id = uuid();
const minDepth = 5; // anything less is really just storybook internals
const actionDisplayToEmit: ActionDisplay = {
id,
count: 0,
data: { name, args },
options: {
...actionOptions,
depth: minDepth + actionOptions.depth,
},
};
channel.emit(EVENT_ID, actionDisplayToEmit);
};
return handler;
}
| import uuid from 'uuid/v1';
import { addons } from '@storybook/addons';
import { EVENT_ID } from '../constants';
import { ActionDisplay, ActionOptions, HandlerFunction } from '../models';
export function action(name: string, options: ActionOptions = {}): HandlerFunction {
const actionOptions = {
...options,
};
// tslint:disable-next-line:no-shadowed-variable
const handler = function action(...args: any[]) {
const channel = addons.getChannel();
const id = uuid();
const minDepth = 5; // anything less is really just storybook internals
const actionDisplayToEmit: ActionDisplay = {
id,
count: 0,
data: { name, args },
options: {
...actionOptions,
depth: minDepth + (actionOptions.depth || 3),
},
};
channel.emit(EVENT_ID, actionDisplayToEmit);
};
return handler;
}
| Increase default minDepth to 8 & FIX depth becoming NaN | Increase default minDepth to 8 & FIX depth becoming NaN
| TypeScript | mit | storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook | ---
+++
@@ -20,7 +20,7 @@
data: { name, args },
options: {
...actionOptions,
- depth: minDepth + actionOptions.depth,
+ depth: minDepth + (actionOptions.depth || 3),
},
};
channel.emit(EVENT_ID, actionDisplayToEmit); |
9a7b4f7a1e98c7a6fc468b6670bd59ec9cd9709b | src/lib/indentCode.ts | src/lib/indentCode.ts | import detectIndent from 'detect-indent';
import redent from 'redent';
/**
* Indent code.
*
* @export
* @param {string} code Code.
* @returns {string}
*/
export default function indentCode(code: string): string {
if (typeof code === 'string') {
let indent = detectIndent(code).indent || '\t';
code = redent(code, 0, indent);
return code.trim();
} else {
return code;
}
}
| import detectIndent from 'detect-indent';
import redent from 'redent';
/**
* Indent code.
*
* @export
* @param {string} code Code.
* @returns {string}
*/
export default function indentCode(code: string): string {
if (typeof code === 'string') {
const indent = detectIndent(code).indent || '\t';
code = redent(code, 0, {
indent
});
return code.trim();
} else {
return code;
}
}
| Update code due to new `redent` | :alien: Update code due to new `redent`
| TypeScript | mit | gluons/vue-highlight.js | ---
+++
@@ -10,8 +10,11 @@
*/
export default function indentCode(code: string): string {
if (typeof code === 'string') {
- let indent = detectIndent(code).indent || '\t';
- code = redent(code, 0, indent);
+ const indent = detectIndent(code).indent || '\t';
+
+ code = redent(code, 0, {
+ indent
+ });
return code.trim();
} else { |
a9c143ef4311bc9c3f19add7812ae5750ccbf51a | src/delir-core/src/project/timelane.ts | src/delir-core/src/project/timelane.ts | // @flow
import * as _ from 'lodash'
import Layer from './layer'
import {TimelaneScheme} from './scheme/timelane'
export default class TimeLane
{
static deserialize(timelaneJson: TimelaneScheme)
{
const timelane = new TimeLane
const config = _.pick(timelaneJson.config, ['name']) as TimelaneScheme
const layers = timelaneJson.layers.map(layerJson => Layer.deserialize(layerJson))
Object.defineProperty(timelane, 'id', {value: timelaneJson.id})
timelane.layers = new Set<Layer>(layers)
Object.assign(timelane.config, config)
return timelane
}
id: string|null = null
layers: Set<Layer> = new Set()
config: {
name: string|null,
} = {
name: null
}
get name(): string { return (this.config.name as string) }
set name(name: string) { this.config.name = name }
constructor()
{
Object.seal(this)
}
toPreBSON(): Object
{
return {
id: this.id,
config: Object.assign({}, this.config),
layers: Array.from(this.layers.values()).map(layer => layer.toPreBSON()),
}
}
toJSON(): Object
{
return {
id: this.id,
config: Object.assign({}, this.config),
layers: Array.from(this.layers.values()).map(layer => layer.toJSON()),
}
}
}
| // @flow
import * as _ from 'lodash'
import Clip from './clip'
import {TimelaneScheme} from './scheme/timelane'
export default class TimeLane
{
static deserialize(timelaneJson: TimelaneScheme)
{
const timelane = new TimeLane
const config = _.pick(timelaneJson.config, ['name']) as TimelaneScheme
const layers = timelaneJson.layers.map(layerJson => Clip.deserialize(layerJson))
Object.defineProperty(timelane, 'id', {value: timelaneJson.id})
timelane.layers = new Set<Clip>(layers)
Object.assign(timelane.config, config)
return timelane
}
id: string|null = null
layers: Set<Clip> = new Set()
config: {
name: string|null,
} = {
name: null
}
get name(): string { return (this.config.name as string) }
set name(name: string) { this.config.name = name }
constructor()
{
Object.seal(this)
}
toPreBSON(): Object
{
return {
id: this.id,
config: Object.assign({}, this.config),
layers: Array.from(this.layers.values()).map(layer => layer.toPreBSON()),
}
}
toJSON(): Object
{
return {
id: this.id,
config: Object.assign({}, this.config),
layers: Array.from(this.layers.values()).map(layer => layer.toJSON()),
}
}
}
| Replace reference to clip on Timelane | Replace reference to clip on Timelane
| TypeScript | mit | Ragg-/Delir,Ragg-/Delir,Ragg-/Delir,Ragg-/Delir | ---
+++
@@ -1,6 +1,6 @@
// @flow
import * as _ from 'lodash'
-import Layer from './layer'
+import Clip from './clip'
import {TimelaneScheme} from './scheme/timelane'
export default class TimeLane
@@ -9,17 +9,17 @@
{
const timelane = new TimeLane
const config = _.pick(timelaneJson.config, ['name']) as TimelaneScheme
- const layers = timelaneJson.layers.map(layerJson => Layer.deserialize(layerJson))
+ const layers = timelaneJson.layers.map(layerJson => Clip.deserialize(layerJson))
Object.defineProperty(timelane, 'id', {value: timelaneJson.id})
- timelane.layers = new Set<Layer>(layers)
+ timelane.layers = new Set<Clip>(layers)
Object.assign(timelane.config, config)
return timelane
}
id: string|null = null
- layers: Set<Layer> = new Set()
+ layers: Set<Clip> = new Set()
config: {
name: string|null, |
6893e132909f9dc7d6df88f72279a8e9558628b0 | SorasNerdDen/Scripts/captureErrors.ts | SorasNerdDen/Scripts/captureErrors.ts | window.onerror = function (errorMsg, url, lineNumber, col, errorObj) {
"use strict";
try {
const xhr = new XMLHttpRequest();
xhr.open("POST", "/error/scripterror/", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.send(JSON.stringify({
"Page": url,
"Message": errorMsg,
"Line": lineNumber,
"Column": col,
"StackTrace": (errorObj && errorObj.stack ? errorObj.stack : null)
}));
}
catch (e) {
console.error(e);
}
return false;
}; | window.onerror = function (errorMsg, url, lineNumber, col, errorObj) {
"use strict";
try {
const xhr = new XMLHttpRequest();
xhr.open("POST", "/error/scripterror/", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.send(JSON.stringify({
"Page": url,
"Message": errorMsg,
"Line": lineNumber,
"Column": col,
"StackTrace": (errorObj && errorObj.stack ? errorObj.stack : null)
}));
}
catch (e) {
console.error(e);
}
return false;
};
window.name = "Sora's Nerd Den"; | Set window name so that hyperlink target attributes can target this window | Set window name so that hyperlink target attributes can target this window
| TypeScript | mit | Sora2455/Sora-s-Nerd-Den,Sora2455/Sora-s-Nerd-Den,Sora2455/Sora-s-Nerd-Den,Sora2455/Sora-s-Nerd-Den | ---
+++
@@ -17,3 +17,4 @@
}
return false;
};
+window.name = "Sora's Nerd Den"; |
0aea3d14ab58a37b5cc4c4f4a48464e7dcdec939 | src/vs/workbench/contrib/terminal/browser/links/terminalBaseLinkProvider.ts | src/vs/workbench/contrib/terminal/browser/links/terminalBaseLinkProvider.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type { ILinkProvider } from 'xterm';
import { TerminalLink } from 'vs/workbench/contrib/terminal/browser/links/terminalLink';
export abstract class TerminalBaseLinkProvider implements ILinkProvider {
private _activeLinks: TerminalLink[] | undefined;
async provideLinks(bufferLineNumber: number, callback: (links: TerminalLink[] | undefined) => void): Promise<void> {
this._activeLinks?.forEach(l => l.dispose);
this._activeLinks = await this._provideLinks(bufferLineNumber);
callback(this._activeLinks);
}
protected abstract _provideLinks(bufferLineNumber: number): Promise<TerminalLink[]> | TerminalLink[];
}
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { dispose } from 'vs/base/common/lifecycle';
import { TerminalLink } from 'vs/workbench/contrib/terminal/browser/links/terminalLink';
import type { ILinkProvider } from 'xterm';
export abstract class TerminalBaseLinkProvider implements ILinkProvider {
private _activeLinks: TerminalLink[] | undefined;
async provideLinks(bufferLineNumber: number, callback: (links: TerminalLink[] | undefined) => void): Promise<void> {
if (this._activeLinks) {
dispose(this._activeLinks);
}
this._activeLinks = await this._provideLinks(bufferLineNumber);
callback(this._activeLinks);
}
protected abstract _provideLinks(bufferLineNumber: number): Promise<TerminalLink[]> | TerminalLink[];
}
| Fix `_activeLinks` not being disposed of | Fix `_activeLinks` not being disposed of
Looks like we were calling forEach but not actually invoking `dispose` on the items. Switch to use `dispose(...)` to avoid this
| TypeScript | mit | eamodio/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode | ---
+++
@@ -3,14 +3,17 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
+import { dispose } from 'vs/base/common/lifecycle';
+import { TerminalLink } from 'vs/workbench/contrib/terminal/browser/links/terminalLink';
import type { ILinkProvider } from 'xterm';
-import { TerminalLink } from 'vs/workbench/contrib/terminal/browser/links/terminalLink';
export abstract class TerminalBaseLinkProvider implements ILinkProvider {
private _activeLinks: TerminalLink[] | undefined;
async provideLinks(bufferLineNumber: number, callback: (links: TerminalLink[] | undefined) => void): Promise<void> {
- this._activeLinks?.forEach(l => l.dispose);
+ if (this._activeLinks) {
+ dispose(this._activeLinks);
+ }
this._activeLinks = await this._provideLinks(bufferLineNumber);
callback(this._activeLinks);
} |
6fdc082bfdc1cad62a042cd53bdb2901274e9bfd | src/utils/saveCsvFile/saveCsvFile.ts | src/utils/saveCsvFile/saveCsvFile.ts | import { saveAs } from 'file-saver'
import { Parser } from 'json2csv'
import { CardData } from '../../types'
const saveCsvFile = (deckName: string, cardsData: CardData[]) => {
const json2csvParser = new Parser({
fields: Object.keys(cardsData[0]),
withBOM: true
})
const csv = json2csvParser.parse(cardsData)
const blob = new Blob([csv], { type: 'text/csv' })
saveAs(blob, `${deckName}.csv`)
}
export default saveCsvFile
| import { saveAs } from 'file-saver'
import { Parser } from 'json2csv'
import { CardData } from '../../types'
const saveCsvFile = (deckName: string, cardsData: CardData[]) => {
const json2csvParser = new Parser({
fields: [
'headword',
'form',
'example',
'definition',
'pronunciation',
'partOfSpeech',
'situation',
'geography',
'synonym',
'antonym',
'frequency'
],
withBOM: true
})
const csv = json2csvParser.parse(cardsData)
const blob = new Blob([csv], { type: 'text/csv' })
saveAs(blob, `${deckName}.csv`)
}
export default saveCsvFile
| Add fixed order of columns in CSV | Add fixed order of columns in CSV
| TypeScript | mit | yakhinvadim/longman-to-anki-web,yakhinvadim/longman-to-anki,yakhinvadim/longman-to-anki,yakhinvadim/longman-to-anki-web,yakhinvadim/longman-to-anki | ---
+++
@@ -4,7 +4,19 @@
const saveCsvFile = (deckName: string, cardsData: CardData[]) => {
const json2csvParser = new Parser({
- fields: Object.keys(cardsData[0]),
+ fields: [
+ 'headword',
+ 'form',
+ 'example',
+ 'definition',
+ 'pronunciation',
+ 'partOfSpeech',
+ 'situation',
+ 'geography',
+ 'synonym',
+ 'antonym',
+ 'frequency'
+ ],
withBOM: true
})
const csv = json2csvParser.parse(cardsData) |
0b5f8f3e0e017aecf5752eafd5f55d702bb74672 | hawtio-web/src/main/webapp/app/camel/js/pageTitle.ts | hawtio-web/src/main/webapp/app/camel/js/pageTitle.ts | module Core {
export class PageTitle {
private titleElements: { (): string } [] = [];
public addTitleElement(element:() => string):void {
this.titleElements.push(element);
}
public getTitle():string {
return this.getTitleExcluding([], ' ');
}
public getTitleWithSeparator(separator:string):string {
return this.getTitleExcluding([], separator);
}
public getTitleExcluding(excludes:string[], separator:string):string {
return this.getTitleArrayExcluding(excludes).join(separator);
}
public getTitleArrayExcluding(excludes:string[]):string[] {
return <string[]>this.titleElements.map((element):string => {
var answer:string = '';
if (element) {
answer = element();
if (answer === null) {
return '';
}
}
return answer;
}).exclude(excludes);
}
}
}
| module Core {
export class PageTitle {
private titleElements: { (): string } [] = [];
public addTitleElement(element:() => string):void {
this.titleElements.push(element);
}
public getTitle():string {
return this.getTitleExcluding([], ' ');
}
public getTitleWithSeparator(separator:string):string {
return this.getTitleExcluding([], separator);
}
public getTitleExcluding(excludes:string[], separator:string):string {
return this.getTitleArrayExcluding(excludes).join(separator);
}
public getTitleArrayExcluding(excludes:string[]):string[] {
return <string[]>this.titleElements.map((element):string => {
var answer:string = '';
if (element) {
answer = element();
if (answer === null) {
return '';
}
}
return answer;
}).exclude(excludes).exclude('');
}
}
}
| Make sure empty strings are excluded from title | Make sure empty strings are excluded from title
| TypeScript | apache-2.0 | andytaylor/hawtio,mposolda/hawtio,padmaragl/hawtio,rajdavies/hawtio,grgrzybek/hawtio,voipme2/hawtio,hawtio/hawtio,stalet/hawtio,mposolda/hawtio,uguy/hawtio,Fatze/hawtio,jfbreault/hawtio,grgrzybek/hawtio,andytaylor/hawtio,telefunken/hawtio,rajdavies/hawtio,voipme2/hawtio,uguy/hawtio,skarsaune/hawtio,padmaragl/hawtio,uguy/hawtio,tadayosi/hawtio,fortyrunner/hawtio,jfbreault/hawtio,andytaylor/hawtio,tadayosi/hawtio,stalet/hawtio,rajdavies/hawtio,hawtio/hawtio,Fatze/hawtio,jfbreault/hawtio,Fatze/hawtio,voipme2/hawtio,grgrzybek/hawtio,mposolda/hawtio,mposolda/hawtio,grgrzybek/hawtio,tadayosi/hawtio,padmaragl/hawtio,uguy/hawtio,uguy/hawtio,stalet/hawtio,telefunken/hawtio,telefunken/hawtio,andytaylor/hawtio,grgrzybek/hawtio,Fatze/hawtio,hawtio/hawtio,telefunken/hawtio,telefunken/hawtio,skarsaune/hawtio,jfbreault/hawtio,samkeeleyong/hawtio,voipme2/hawtio,samkeeleyong/hawtio,Fatze/hawtio,jfbreault/hawtio,samkeeleyong/hawtio,fortyrunner/hawtio,padmaragl/hawtio,tadayosi/hawtio,hawtio/hawtio,rajdavies/hawtio,padmaragl/hawtio,fortyrunner/hawtio,voipme2/hawtio,skarsaune/hawtio,hawtio/hawtio,skarsaune/hawtio,mposolda/hawtio,fortyrunner/hawtio,skarsaune/hawtio,samkeeleyong/hawtio,stalet/hawtio,samkeeleyong/hawtio,rajdavies/hawtio,tadayosi/hawtio,stalet/hawtio,andytaylor/hawtio | ---
+++
@@ -30,7 +30,7 @@
}
}
return answer;
- }).exclude(excludes);
+ }).exclude(excludes).exclude('');
}
}
|
304c3d7801dd788cb54ca32968ee5aea49538f50 | tools/env/base.ts | tools/env/base.ts | import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.5',
RELEASEVERSION: '1.0.5'
};
export = BaseConfig;
| import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.6',
RELEASEVERSION: '1.0.6'
};
export = BaseConfig;
| Update release version to 1.0.6 | Update release version to 1.0.6
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -3,8 +3,8 @@
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
- RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.5',
- RELEASEVERSION: '1.0.5'
+ RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.6',
+ RELEASEVERSION: '1.0.6'
};
export = BaseConfig; |
c31c75c02db9f4d95acf9714ca5f23a46d9641c1 | react-mobx-todos/src/components/FilteredTodoList.tsx | react-mobx-todos/src/components/FilteredTodoList.tsx | import * as React from "react"
import { Component } from "react"
import { Todo } from "../model/Todo"
import { TodoList } from "./TodoList"
import { Todos } from "../model/Todos"
import { TodosFilter } from "../model/TodosFilter"
interface Props {
activeFilter: TodosFilter
onTodoClick: (todo: Todo) => void,
todos: Todos
}
export class FilteredTodoList extends Component<Props, void> {
private getVisibleTodos(): Todos {
return this.props.activeFilter.filterTodos(this.props.todos)
}
public render() {
return (
<TodoList onTodoClick={this.props.onTodoClick} todos={this.getVisibleTodos()}/>
)
}
} | import * as React from "react"
import { Component } from "react"
import { Todo } from "../model/Todo"
import { TodoList } from "./TodoList"
import { Todos } from "../model/Todos"
import { TodosFilter } from "../model/TodosFilter"
interface Props {
activeFilter: TodosFilter
onTodoClick: (todo: Todo) => void,
todos: Todos
}
export class FilteredTodoList extends Component<Props, void> {
private getVisibleTodos(): Todos {
const visibleTodos = this.props.activeFilter.filterTodos(this.props.todos)
return visibleTodos
}
public render() {
return (
<TodoList onTodoClick={() => this.props.onTodoClick} todos={this.getVisibleTodos()}/>
)
}
} | Add variable for return value | Add variable for return value
| TypeScript | unlicense | janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations | ---
+++
@@ -14,12 +14,13 @@
export class FilteredTodoList extends Component<Props, void> {
private getVisibleTodos(): Todos {
- return this.props.activeFilter.filterTodos(this.props.todos)
+ const visibleTodos = this.props.activeFilter.filterTodos(this.props.todos)
+ return visibleTodos
}
public render() {
return (
- <TodoList onTodoClick={this.props.onTodoClick} todos={this.getVisibleTodos()}/>
+ <TodoList onTodoClick={() => this.props.onTodoClick} todos={this.getVisibleTodos()}/>
)
}
} |
e7b2790d9031b05266cfaef47f276d5fdd7c5de0 | problems/yoda-speak/solution.ts | problems/yoda-speak/solution.ts | import {ISolution} from '../solution.interface';
export class Solution implements ISolution<string, string> {
static PRONOUNS: string[] = [
"I", "YOU", "HE", "SHE", "IT", "WE", "THEY"
];
static INVALID: string = "Too difficult, this sentence is.";
solve(input: string) {
var parts = input.split(' ');
if (!Solution.EqualsAnyPronoun(parts[0])) {
return Solution.INVALID;
}
return "yoda text output";
}
static EqualsAnyPronoun(input: string): boolean {
for (var p of Solution.PRONOUNS) {
if (p === input.toUpperCase()) {
return true;
}
}
return false;
}
}
| import {ISolution} from '../solution.interface';
export class Solution implements ISolution<string, string> {
static PRONOUNS: string[] = [
"I", "YOU", "HE", "SHE", "IT", "WE", "THEY"
];
static INVALID: string = "Too difficult, this sentence is.";
solve(input: string) {
var parts = input.split(' ');
if (!Solution.EqualsAnyPronoun(parts[0])) {
return Solution.INVALID;
}
var rearranged = Solution.RearrangeParts(parts);
var end = rearranged.join(" ");
return end;
}
static EqualsAnyPronoun(input: string): boolean {
for (var p of Solution.PRONOUNS) {
if (p === input.toUpperCase()) {
return true;
}
}
return false;
}
static RearrangeParts(input: string[]): string[] {
var parts = [];
for (var i = 2; i < input.length; i++) {
parts.push(input[i]);
}
parts[parts.length - 1] = parts[parts.length - 1] + ',';
parts.push(input[0]);
parts.push(input[1]);
return parts;
}
}
| Rearrange the string into the right order | Rearrange the string into the right order
| TypeScript | unlicense | Jameskmonger/challenges | ---
+++
@@ -13,7 +13,11 @@
return Solution.INVALID;
}
- return "yoda text output";
+ var rearranged = Solution.RearrangeParts(parts);
+
+ var end = rearranged.join(" ");
+
+ return end;
}
static EqualsAnyPronoun(input: string): boolean {
@@ -25,4 +29,18 @@
return false;
}
+
+ static RearrangeParts(input: string[]): string[] {
+ var parts = [];
+ for (var i = 2; i < input.length; i++) {
+ parts.push(input[i]);
+ }
+
+ parts[parts.length - 1] = parts[parts.length - 1] + ',';
+
+ parts.push(input[0]);
+ parts.push(input[1]);
+
+ return parts;
+ }
} |
ca8f66105b5cd8183583579ee11a2fb1cc8e60e2 | client/Settings/components/Dropdown.tsx | client/Settings/components/Dropdown.tsx | import { Field } from "formik";
import React = require("react");
export const Dropdown = (props: {
fieldName: string;
options: {};
children: any;
}) => (
<div className="c-dropdown">
{props.children}
<SelectOptions {...props} />
</div>
);
const SelectOptions = (props: { fieldName: string; options: {} }) => (
<Field component="select" name={props.fieldName}>
{Object.keys(props.options).map(option => (
<option value={option}>{props.options[option]}</option>
))}
</Field>
);
| import { Field } from "formik";
import React = require("react");
export const Dropdown = (props: {
fieldName: string;
options: {};
children: any;
}) => (
<div className="c-dropdown">
{props.children}
<SelectOptions {...props} />
</div>
);
const SelectOptions = (props: { fieldName: string; options: {} }) => (
<Field component="select" name={props.fieldName}>
{Object.keys(props.options).map(option => (
<option value={option} key={option}>
{props.options[option]}
</option>
))}
</Field>
);
| Add react key to option elements | Add react key to option elements
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -15,7 +15,9 @@
const SelectOptions = (props: { fieldName: string; options: {} }) => (
<Field component="select" name={props.fieldName}>
{Object.keys(props.options).map(option => (
- <option value={option}>{props.options[option]}</option>
+ <option value={option} key={option}>
+ {props.options[option]}
+ </option>
))}
</Field>
); |
092f6a094b6f8b979a272b918921a174de610666 | home/utils/Environment.ts | home/utils/Environment.ts | import Constants from 'expo-constants';
import { Platform } from 'react-native';
import semver from 'semver';
import * as Kernel from '../kernel/Kernel';
const isProduction = !!(
Constants.manifest.id === '@exponent/home' && Constants.manifest.publishedTime
);
const IOSClientReleaseType = Kernel.iosClientReleaseType;
const IsIOSRestrictedBuild =
Platform.OS === 'ios' &&
Kernel.iosClientReleaseType === Kernel.ExpoClientReleaseType.APPLE_APP_STORE;
const SupportedExpoSdks = Constants.supportedExpoSdks || [];
// Constants.supportedExpoSdks is not guaranteed to be sorted!
const sortedSupportedExpoSdks = SupportedExpoSdks.sort();
let lowestSupportedSdkVersion: number = -1;
if (SupportedExpoSdks.length > 0) {
lowestSupportedSdkVersion = semver.major(sortedSupportedExpoSdks[0]);
}
const supportedSdksString = `SDK${
SupportedExpoSdks.length === 1 ? ':' : 's:'
} ${sortedSupportedExpoSdks.map(semver.major).join(', ')}`;
export default {
isProduction,
IOSClientReleaseType,
IsIOSRestrictedBuild,
lowestSupportedSdkVersion,
supportedSdksString,
};
| import Constants from 'expo-constants';
import { Platform } from 'react-native';
import semver from 'semver';
import * as Kernel from '../kernel/Kernel';
const isProduction = !!(
Constants.manifest?.id === '@exponent/home' && Constants.manifest?.publishedTime
);
const IOSClientReleaseType = Kernel.iosClientReleaseType;
const IsIOSRestrictedBuild =
Platform.OS === 'ios' &&
Kernel.iosClientReleaseType === Kernel.ExpoClientReleaseType.APPLE_APP_STORE;
const SupportedExpoSdks = Constants.supportedExpoSdks || [];
// Constants.supportedExpoSdks is not guaranteed to be sorted!
const sortedSupportedExpoSdks = SupportedExpoSdks.sort();
let lowestSupportedSdkVersion: number = -1;
if (SupportedExpoSdks.length > 0) {
lowestSupportedSdkVersion = semver.major(sortedSupportedExpoSdks[0]);
}
const supportedSdksString = `SDK${
SupportedExpoSdks.length === 1 ? ':' : 's:'
} ${sortedSupportedExpoSdks.map(semver.major).join(', ')}`;
export default {
isProduction,
IOSClientReleaseType,
IsIOSRestrictedBuild,
lowestSupportedSdkVersion,
supportedSdksString,
};
| Fix tsc error as Constants.manifest may be null after manifest2 landed | [home]: Fix tsc error as Constants.manifest may be null after manifest2 landed
| TypeScript | bsd-3-clause | exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent | ---
+++
@@ -5,7 +5,7 @@
import * as Kernel from '../kernel/Kernel';
const isProduction = !!(
- Constants.manifest.id === '@exponent/home' && Constants.manifest.publishedTime
+ Constants.manifest?.id === '@exponent/home' && Constants.manifest?.publishedTime
);
const IOSClientReleaseType = Kernel.iosClientReleaseType; |
2e4e35bd8d76192d987ced6e5ddcc92156459cdb | src/features/attributeCompleter.ts | src/features/attributeCompleter.ts | import * as vscode from 'vscode';
import { AsciidocParser } from '../text-parser';
export class AttributeCompleter {
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) {
const adoc = new AsciidocParser(document.uri.fsPath)
adoc.parseText(document.getText())
let attribs = []
for (const [key, value] of Object.entries(adoc.document.getAttributes()))
{
let attrib = new vscode.CompletionItem(key, vscode.CompletionItemKind.Variable)
attrib.detail = value.toString()
attribs.push(attrib)
}
return attribs
}
}
| import * as vscode from 'vscode';
import { AsciidocParser } from '../text-parser';
export class AttributeCompleter {
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) {
const adoc = new AsciidocParser(document.uri.fsPath)
adoc.parseText(document.getText())
const attributes = adoc.document.getAttributes()
let attribs = []
for (const key in attributes) {
let attrib = new vscode.CompletionItem(key, vscode.CompletionItemKind.Variable)
attrib.detail = attributes[key].toString()
attribs.push(attrib)
}
return attribs
}
}
| Change iteration to something TS likes better Correct version accidental mod | Change iteration to something TS likes better
Correct version accidental mod
| TypeScript | mit | joaompinto/asciidoctor-vscode,joaompinto/asciidoctor-vscode,joaompinto/asciidoctor-vscode | ---
+++
@@ -8,12 +8,12 @@
const adoc = new AsciidocParser(document.uri.fsPath)
adoc.parseText(document.getText())
-
+ const attributes = adoc.document.getAttributes()
let attribs = []
- for (const [key, value] of Object.entries(adoc.document.getAttributes()))
- {
+
+ for (const key in attributes) {
let attrib = new vscode.CompletionItem(key, vscode.CompletionItemKind.Variable)
- attrib.detail = value.toString()
+ attrib.detail = attributes[key].toString()
attribs.push(attrib)
}
|
eb5fe57e4e60069ca8ba06f2eec13437f109a34b | app/src/component/TwitterButton.tsx | app/src/component/TwitterButton.tsx | import * as React from "react";
export default class extends React.Component {
public render() {
// Load Twitter's widget.js in index.html.
return (
<a
href="https://twitter.com/share?ref_src=twsrc%5Etfw"
className="twitter-share-button"
data-show-count="false"
data-size="large"
>
Tweet
</a>
);
}
public componentWillMount() {
const script = document.createElement("script");
script.src = "//platform.twitter.com/widgets.js";
script.async = true;
document.body.appendChild(script);
}
}
| import * as React from "react";
export default class extends React.Component {
public render() {
// Load Twitter's widget.js in index.html.
return (
<a
href="https://twitter.com/share?ref_src=twsrc%5Etfw"
className="twitter-share-button"
data-show-count="false"
data-size="large"
>
Tweet
</a>
);
}
public componentWillMount() {
const script = document.createElement("script");
script.src = "https://platform.twitter.com/widgets.js";
script.async = true;
document.body.appendChild(script);
}
}
| Use HTTPS only to load Twitter script | Use HTTPS only to load Twitter script
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -19,7 +19,7 @@
public componentWillMount() {
const script = document.createElement("script");
- script.src = "//platform.twitter.com/widgets.js";
+ script.src = "https://platform.twitter.com/widgets.js";
script.async = true;
document.body.appendChild(script); |
0cc5c711dfde79acebb41a9f91a3002ec9fe80cf | src/type.ts | src/type.ts | namespace fun {
/**
* Returns true if the value passed in is either null or undefined.
*/
export function isVoid(value: any): value is void {
// See https://basarat.gitbooks.io/typescript/content/docs/tips/null.html
return value == undefined;
}
export function isString(value: any): value is string {
return typeof value === 'string';
}
export function isNumber(value: any): value is number {
return typeof value === 'number';
}
export function isBoolean(value: any): value is boolean {
return typeof value === 'boolean';
}
export function isArray<T>(value: any): value is Array<T> {
// See http://jsperf.com/is-array-tests
return value != undefined && value.constructor === Array;
}
export function isFunction(value: any): value is Function {
// See http://jsperf.com/is-function-tests
return value != undefined && value.constructor === Function;
}
/**
* Returns true if value is a plain object (e.g. {a: 1}), false otherwise.
*/
export function isObject(value: any): value is Object {
// See http://jsperf.com/is-object-tests
// See https://basarat.gitbooks.io/typescript/content/docs/tips/null.html
return value != undefined && value.constructor === Object;
}
} | namespace fun {
/**
* Returns true if the value passed in is either null or undefined.
*/
export function isVoid(value: any): value is void {
// See https://basarat.gitbooks.io/typescript/content/docs/tips/null.html
return value == undefined;
}
export function isString(value: any): value is string {
// See http://jsperf.com/is-string-tests
return typeof value === 'string';
}
export function isNumber(value: any): value is number {
return typeof value === 'number';
}
export function isBoolean(value: any): value is boolean {
return typeof value === 'boolean';
}
export function isArray<T>(value: any): value is Array<T> {
// See http://jsperf.com/is-array-tests
return value != undefined && value.constructor === Array;
}
export function isFunction(value: any): value is Function {
// See http://jsperf.com/is-function-tests
return value != undefined && value.constructor === Function;
}
/**
* Returns true if value is a plain object (e.g. {a: 1}), false otherwise.
*/
export function isObject(value: any): value is Object {
// See http://jsperf.com/is-object-tests
// See https://basarat.gitbooks.io/typescript/content/docs/tips/null.html
return value != undefined && value.constructor === Object;
}
} | Add link to benchmark for toString implementation | Add link to benchmark for toString implementation
| TypeScript | mit | federico-lox/fun.ts | ---
+++
@@ -8,6 +8,7 @@
}
export function isString(value: any): value is string {
+ // See http://jsperf.com/is-string-tests
return typeof value === 'string';
}
|
1e8e3923b3bfa621ab506bd5ef344ba04ed41d92 | app/components/renderForQuestions/answerState.ts | app/components/renderForQuestions/answerState.ts | import {Response} from "quill-marking-logic"
interface Attempt {
response: Response
}
function getAnswerState(attempt): boolean {
return (attempt.response.optimal && attempt.response.author === undefined && attempt.author === undefined)
}
export default getAnswerState; | import {Response} from "quill-marking-logic"
interface Attempt {
response: Response
}
function getAnswerState(attempt: Attempt|undefined): boolean {
if (attempt) {
return (!!attempt.response.optimal && attempt.response.author === undefined)
}
return false
}
export default getAnswerState; | Fix answer state null error. | Fix answer state null error.
| TypeScript | agpl-3.0 | empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core | ---
+++
@@ -4,8 +4,11 @@
response: Response
}
-function getAnswerState(attempt): boolean {
- return (attempt.response.optimal && attempt.response.author === undefined && attempt.author === undefined)
+function getAnswerState(attempt: Attempt|undefined): boolean {
+ if (attempt) {
+ return (!!attempt.response.optimal && attempt.response.author === undefined)
+ }
+ return false
}
export default getAnswerState; |
24d0bfc33d97c435372f8e4fa63da567e829ac38 | packages/schematics/src/scam/index.ts | packages/schematics/src/scam/index.ts | import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export function scam(options: ScamOptions): Rule {
if (!options.separateModule) {
throw new Error('😱 Not implemented yet!');
}
return chain([
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
}),
]);
}
| import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export function scam(options: ScamOptions): Rule {
const ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
throw new Error('😱 Not implemented yet!');
}
return chain(ruleList);
}
| Merge module and component as default behavior. | @wishtack/schematics:scam: Merge module and component as default behavior.
| TypeScript | mit | wishtack/ng-steroids,wishtack/wishtack-steroids,wishtack/wishtack-steroids,wishtack/ng-steroids,wishtack/wishtack-steroids | ---
+++
@@ -7,16 +7,18 @@
export function scam(options: ScamOptions): Rule {
- if (!options.separateModule) {
- throw new Error('😱 Not implemented yet!');
- }
-
- return chain([
+ const ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
- }),
- ]);
+ })
+ ];
+
+ if (!options.separateModule) {
+ throw new Error('😱 Not implemented yet!');
+ }
+
+ return chain(ruleList);
} |
c1e777490b9b6315e555de150f0badd894ab8fc2 | ui/src/index.tsx | ui/src/index.tsx | import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import './buttons.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
| import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import './buttons.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
| Remove unused reference to service worker | Remove unused reference to service worker
| TypeScript | apache-2.0 | dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web | ---
+++
@@ -4,7 +4,6 @@
import './index.css';
import './buttons.css';
import App from './App';
-import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode> |
2d66c9325386534068e0cfb8fce7fb4529048cd7 | app/angular/src/client/preview/types.ts | app/angular/src/client/preview/types.ts | import { StoryFn } from '@storybook/addons';
export declare const moduleMetadata: (
metadata: Partial<NgModuleMetadata>
) => (storyFn: StoryFn<StoryFnAngularReturnType>) => any;
export interface NgModuleMetadata {
declarations?: any[];
entryComponents?: any[];
imports?: any[];
schemas?: any[];
providers?: any[];
}
export interface ICollection {
[p: string]: any;
}
export interface IStorybookStory {
name: string;
render: () => any;
}
// @deprecated Use IStorybookSection instead
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface IStoribookSection extends IStorybookSection {}
export interface IStorybookSection {
kind: string;
stories: IStorybookStory[];
}
export interface StoryFnAngularReturnType {
component?: any;
props?: ICollection;
propsMeta?: ICollection;
moduleMetadata?: NgModuleMetadata;
template?: string;
styles?: string[];
}
| import { StoryFn } from '@storybook/addons';
export declare const moduleMetadata: (
metadata: Partial<NgModuleMetadata>
) => (storyFn: StoryFn<StoryFnAngularReturnType>) => any;
export interface NgModuleMetadata {
declarations?: any[];
entryComponents?: any[];
imports?: any[];
schemas?: any[];
providers?: any[];
}
export interface ICollection {
[p: string]: any;
}
export interface IStorybookStory {
name: string;
render: () => any;
}
export interface IStorybookSection {
kind: string;
stories: IStorybookStory[];
}
export interface StoryFnAngularReturnType {
component?: any;
props?: ICollection;
propsMeta?: ICollection;
moduleMetadata?: NgModuleMetadata;
template?: string;
styles?: string[];
}
| REMOVE deprecated APIs from app/angular | REMOVE deprecated APIs from app/angular
| TypeScript | mit | storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook | ---
+++
@@ -20,10 +20,6 @@
render: () => any;
}
-// @deprecated Use IStorybookSection instead
-// eslint-disable-next-line @typescript-eslint/no-empty-interface
-export interface IStoribookSection extends IStorybookSection {}
-
export interface IStorybookSection {
kind: string;
stories: IStorybookStory[]; |
b238b9c2357ed33e44bbcd48cffe6255c923dd5c | packages/core/src/presentation/hooks/useMountStatusRef.hook.ts | packages/core/src/presentation/hooks/useMountStatusRef.hook.ts | import { useEffect, useRef } from 'react';
export function useMountStatusRef() {
const mountStatusRef = useRef<'FIRST_RENDER' | 'MOUNTED' | 'UNMOUNTED'>('FIRST_RENDER');
useEffect(() => {
mountStatusRef.current = 'MOUNTED';
return () => (mountStatusRef.current = 'UNMOUNTED');
});
return mountStatusRef;
}
| import { useEffect, useRef } from 'react';
export function useMountStatusRef() {
const mountStatusRef = useRef<'FIRST_RENDER' | 'MOUNTED' | 'UNMOUNTED'>('FIRST_RENDER');
useEffect(() => {
mountStatusRef.current = 'MOUNTED';
return () => {
mountStatusRef.current = 'UNMOUNTED';
};
});
return mountStatusRef;
}
| Remove return value from useEffect in useMountStatusRef | fix(core/presentation): Remove return value from useEffect in useMountStatusRef
| TypeScript | apache-2.0 | spinnaker/deck,spinnaker/deck,spinnaker/deck,spinnaker/deck | ---
+++
@@ -4,7 +4,9 @@
const mountStatusRef = useRef<'FIRST_RENDER' | 'MOUNTED' | 'UNMOUNTED'>('FIRST_RENDER');
useEffect(() => {
mountStatusRef.current = 'MOUNTED';
- return () => (mountStatusRef.current = 'UNMOUNTED');
+ return () => {
+ mountStatusRef.current = 'UNMOUNTED';
+ };
});
return mountStatusRef;
} |
dd33b6c45cdbd42da8646f083cc4fffea105fea3 | source/parser/localgocadpusher.ts | source/parser/localgocadpusher.ts | import { Parser } from "./parser";
import { FilePusher } from "../gocadpusher/filepusher";
declare var proj4;
/**
* Uses the block reading parser in the current UI thread. in
* other words single threading. Mainly for debugging as its
* easier to debug.
*/
export class LocalGocadPusherParser extends Parser {
// Easier to debug when running local.
public parse(data: any): Promise<any> {
return new Promise<any>(resolve => {
new FilePusher(data.file, data.options, proj4).start().then(document => {
resolve(document);
});
});
}
} | import { Parser } from "./parser";
import { Event } from "../domain/event";
import { PipeToThreedObj } from "../push3js/pipetothreedobj";
import { DocumentPusher } from "../gocadpusher/documentpusher";
import { LinesToLinePusher } from "../util/linestolinepusher";
import { LinesPagedPusher } from "../util/linespagedpusher";
declare var proj4;
let eventList = [
"start",
"complete",
"bstones",
"borders",
"header",
"vertices",
"faces",
"lines",
"properties"
];
/**
* Uses the block reading parser in the current UI thread. in
* other words single threading. Mainly for debugging as its
* easier to debug.
*/
export class LocalGocadPusherParser extends Parser {
constructor(public options: any = {}) {
super();
}
public parse(data: any): Promise<any> {
let file = data.file;
let options = data.options;
return new Promise<any>((resolve, reject) => {
let pusher = new DocumentPusher(this.options, proj4);
// Turn blocks of lines into lines
let linesToLinePusher = new LinesToLinePusher(function (line) {
pusher.push(line);
});
let pipe = new PipeToThreedObj();
pipe.addEventListener("complete", (event) => {
resolve(event.data);
});
pipe.addEventListener("error", (event) => {
console.log("There is an error with your pipes!");
reject(event.data);
});
new LinesPagedPusher(file, options, function (lines) {
linesToLinePusher.receiver(lines);
}).start().then(function () {
console.log("******************* Local Kaput ****************************");
});
eventList.forEach(function (name) {
// console.log("Adding listener: " + name);
pusher.addEventListener(name,
function defaultHandler(event) {
console.log("GPW: " + event.type);
pipe.pipe({
eventName: event.type,
data: event.data
});
});
});
});
}
}
| Convert local pusher to use new style | Convert local pusher to use new style
| TypeScript | apache-2.0 | Tomella/explorer-3d,Tomella/explorer-3d,Tomella/explorer-3d | ---
+++
@@ -1,6 +1,23 @@
import { Parser } from "./parser";
-import { FilePusher } from "../gocadpusher/filepusher";
+import { Event } from "../domain/event";
+import { PipeToThreedObj } from "../push3js/pipetothreedobj";
+import { DocumentPusher } from "../gocadpusher/documentpusher";
+import { LinesToLinePusher } from "../util/linestolinepusher";
+import { LinesPagedPusher } from "../util/linespagedpusher";
+
declare var proj4;
+
+let eventList = [
+ "start",
+ "complete",
+ "bstones",
+ "borders",
+ "header",
+ "vertices",
+ "faces",
+ "lines",
+ "properties"
+];
/**
* Uses the block reading parser in the current UI thread. in
@@ -8,11 +25,48 @@
* easier to debug.
*/
export class LocalGocadPusherParser extends Parser {
- // Easier to debug when running local.
+ constructor(public options: any = {}) {
+ super();
+ }
+
public parse(data: any): Promise<any> {
- return new Promise<any>(resolve => {
- new FilePusher(data.file, data.options, proj4).start().then(document => {
- resolve(document);
+ let file = data.file;
+ let options = data.options;
+
+ return new Promise<any>((resolve, reject) => {
+ let pusher = new DocumentPusher(this.options, proj4);
+
+ // Turn blocks of lines into lines
+ let linesToLinePusher = new LinesToLinePusher(function (line) {
+ pusher.push(line);
+ });
+
+ let pipe = new PipeToThreedObj();
+ pipe.addEventListener("complete", (event) => {
+ resolve(event.data);
+ });
+
+ pipe.addEventListener("error", (event) => {
+ console.log("There is an error with your pipes!");
+ reject(event.data);
+ });
+
+ new LinesPagedPusher(file, options, function (lines) {
+ linesToLinePusher.receiver(lines);
+ }).start().then(function () {
+ console.log("******************* Local Kaput ****************************");
+ });
+
+ eventList.forEach(function (name) {
+ // console.log("Adding listener: " + name);
+ pusher.addEventListener(name,
+ function defaultHandler(event) {
+ console.log("GPW: " + event.type);
+ pipe.pipe({
+ eventName: event.type,
+ data: event.data
+ });
+ });
});
});
} |
624047ad980c0a43cc8d86ace21ae178314f31a0 | packages/data-mate/src/function-configs/repository.ts | packages/data-mate/src/function-configs/repository.ts | import { booleanRepository } from './boolean';
import { geoRepository } from './geo';
import { jsonRepository } from './json';
import { numberRepository } from './number';
import { objectRepository } from './object';
import { stringRepository } from './string';
export const functionConfigRepository = {
...booleanRepository,
...geoRepository,
...jsonRepository,
...numberRepository,
...objectRepository,
...stringRepository
} as const;
| import { booleanRepository } from './boolean';
import { geoRepository } from './geo';
import { jsonRepository } from './json';
import { numericRepository } from './numeric';
import { objectRepository } from './object';
import { stringRepository } from './string';
export const functionConfigRepository = {
...booleanRepository,
...geoRepository,
...jsonRepository,
...numericRepository,
...objectRepository,
...stringRepository
} as const;
| Fix rename of number to numeric | Fix rename of number to numeric
| TypeScript | apache-2.0 | terascope/teraslice,terascope/teraslice,terascope/teraslice,terascope/teraslice | ---
+++
@@ -1,7 +1,7 @@
import { booleanRepository } from './boolean';
import { geoRepository } from './geo';
import { jsonRepository } from './json';
-import { numberRepository } from './number';
+import { numericRepository } from './numeric';
import { objectRepository } from './object';
import { stringRepository } from './string';
@@ -9,7 +9,7 @@
...booleanRepository,
...geoRepository,
...jsonRepository,
- ...numberRepository,
+ ...numericRepository,
...objectRepository,
...stringRepository
} as const; |
fea34788c7ba37f72838cebd97184132fe16339f | src/app/app.module.ts | src/app/app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MaterialModule, MdIconRegistry } from '@angular/material';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { HeaderComponent } from './layout/header/header.component';
import { FooterComponent } from './layout/footer/footer.component';
@NgModule({
declarations: [
AppComponent,
AboutComponent,
HeaderComponent,
FooterComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule,
MaterialModule
],
providers: [
MdIconRegistry
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
| import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MaterialModule, MdIconRegistry } from '@angular/material';
import * as firebase from 'firebase'; // See https://github.com/angular/angularfire2/issues/529
import { AngularFireModule } from 'angularfire2';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { HeaderComponent } from './layout/header/header.component';
import { FooterComponent } from './layout/footer/footer.component';
import { config } from './config/config';
@NgModule({
declarations: [
AppComponent,
AboutComponent,
HeaderComponent,
FooterComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule,
MaterialModule.forRoot(),
AngularFireModule.initializeApp(config.FIREBASE_CONFIG, config.FIREBASE_AUTH_CONFIG),
],
providers: [
MdIconRegistry,
],
bootstrap: [
AppComponent,
]
})
export class AppModule { }
| Initialize of Firebase with custom configuration. | Initialize of Firebase with custom configuration.
| TypeScript | mit | tarlepp/angular2-firebase-material-demo,tarlepp/Angular-Firebase-Material-Demo,tarlepp/Angular-Firebase-Material-Demo,tarlepp/angular2-firebase-material-demo,tarlepp/angular2-firebase-material-demo | ---
+++
@@ -3,12 +3,15 @@
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MaterialModule, MdIconRegistry } from '@angular/material';
+import * as firebase from 'firebase'; // See https://github.com/angular/angularfire2/issues/529
+import { AngularFireModule } from 'angularfire2';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { HeaderComponent } from './layout/header/header.component';
import { FooterComponent } from './layout/footer/footer.component';
+import { config } from './config/config';
@NgModule({
declarations: [
@@ -22,13 +25,14 @@
FormsModule,
HttpModule,
AppRoutingModule,
- MaterialModule
+ MaterialModule.forRoot(),
+ AngularFireModule.initializeApp(config.FIREBASE_CONFIG, config.FIREBASE_AUTH_CONFIG),
],
providers: [
- MdIconRegistry
+ MdIconRegistry,
],
bootstrap: [
- AppComponent
+ AppComponent,
]
})
|
c9bc8427f9c9ed0ff9b128b0b0a3fc9f52fa4cee | src/custom-error.spec.ts | src/custom-error.spec.ts | import { checkProtoChain, checkProperties } from './spec.utils'
import { CustomError } from './custom-error'
test('Instance', () => checkProtoChain(CustomError, Error))
test('Instance pre ES6 environment', () => {
const O = Object as any
const E = Error as any
const setPrototypeOf = O.setPrototypeOf
const captureStackTrace = E.captureStackTrace
delete O.setPrototypeOf
delete E.captureStackTrace
checkProtoChain(CustomError, Error)
O.setPrototypeOf = setPrototypeOf
E.captureStackTrace = captureStackTrace
})
test('Extended', () => {
class SubError extends CustomError {}
checkProtoChain(SubError, CustomError, Error)
})
test('Basic properties', () => checkProperties(CustomError))
| import { checkProtoChain, checkProperties } from './spec.utils'
import { CustomError } from './custom-error'
test('Instance', () => checkProtoChain(CustomError, Error))
test('Instance pre ES6 environment', () => {
const O = Object as any
const E = Error as any
const setPrototypeOf = O.setPrototypeOf
const captureStackTrace = E.captureStackTrace
delete O.setPrototypeOf
delete E.captureStackTrace
checkProtoChain(CustomError, Error)
O.setPrototypeOf = setPrototypeOf
E.captureStackTrace = captureStackTrace
})
test('Extended', () => {
class SubError extends CustomError {}
checkProtoChain(SubError, CustomError, Error)
})
test('Extended with constructor', () => {
class HttpError extends CustomError {
constructor(public code: number, message?: string) {
super(message)
}
}
checkProtoChain(HttpError, CustomError, Error)
})
test('Basic properties', () => checkProperties(CustomError))
| Add class test with custom constructor | test: Add class test with custom constructor
| TypeScript | mit | adriengibrat/ts-custom-error | ---
+++
@@ -22,4 +22,13 @@
checkProtoChain(SubError, CustomError, Error)
})
+test('Extended with constructor', () => {
+ class HttpError extends CustomError {
+ constructor(public code: number, message?: string) {
+ super(message)
+ }
+ }
+ checkProtoChain(HttpError, CustomError, Error)
+})
+
test('Basic properties', () => checkProperties(CustomError)) |
7e66879fb7cc0c8385ec31cedc609167fd8f181b | src/app/map/home/home.component.spec.ts | src/app/map/home/home.component.spec.ts | /* tslint:disable:no-unused-variable */
/*!
* Home Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <[email protected]>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { Http, HttpModule} from '@angular/http';
import { CookieService } from 'angular2-cookie/core';
import { TranslateModule, TranslateLoader, TranslateStaticLoader, TranslateService } from 'ng2-translate';
import { WindowService } from '../window.service';
import { AppLoggerService } from '../../app-logger.service';
import { HomeComponent } from './home.component';
describe('Component: Home', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpModule,
TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
deps: [Http]
}),
],
providers: [
CookieService,
TranslateService,
AppLoggerService,
Renderer,
WindowService,
HomeComponent
]
});
});
it('should create an instance', inject([HomeComponent], (component: HomeComponent) => {
expect(component).toBeTruthy();
}));
});
| /* tslint:disable:no-unused-variable */
/*!
* Home Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <[email protected]>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { Http, HttpModule} from '@angular/http';
import { Router } from '@angular/router';
import { CookieService } from 'angular2-cookie/core';
import { TranslateModule, TranslateLoader, TranslateStaticLoader, TranslateService } from 'ng2-translate';
import { WindowService } from '../window.service';
import { AppLoggerService } from '../../app-logger.service';
import { MockRouter } from '../../mocks/router';
import { HomeComponent } from './home.component';
describe('Component: Home', () => {
let mockRouter: MockRouter;
beforeEach(() => {
mockRouter = new MockRouter();
TestBed.configureTestingModule({
imports: [
HttpModule,
TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
deps: [Http]
}),
],
providers: [
CookieService,
TranslateService,
AppLoggerService,
Renderer,
WindowService,
HomeComponent,
{ provide: Router, useValue: mockRouter },
]
});
});
it('should create an instance', inject([HomeComponent], (component: HomeComponent) => {
expect(component).toBeTruthy();
}));
});
| Fix no provider for Router error | Fix no provider for Router error
| TypeScript | mit | ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2 | ---
+++
@@ -10,15 +10,20 @@
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { Http, HttpModule} from '@angular/http';
+import { Router } from '@angular/router';
import { CookieService } from 'angular2-cookie/core';
import { TranslateModule, TranslateLoader, TranslateStaticLoader, TranslateService } from 'ng2-translate';
import { WindowService } from '../window.service';
import { AppLoggerService } from '../../app-logger.service';
+import { MockRouter } from '../../mocks/router';
import { HomeComponent } from './home.component';
describe('Component: Home', () => {
+ let mockRouter: MockRouter;
beforeEach(() => {
+ mockRouter = new MockRouter();
+
TestBed.configureTestingModule({
imports: [
HttpModule,
@@ -35,7 +40,9 @@
AppLoggerService,
Renderer,
WindowService,
- HomeComponent
+ HomeComponent,
+
+ { provide: Router, useValue: mockRouter },
]
});
}); |
217d0c690ded16f4b2e0b705ba69fe788532bd69 | front/polyfill/index.ts | front/polyfill/index.ts | import 'd3'
import 'c3'
import './promise'
import './find'
import './event-listener'
import './custom-event'
import './starts-with'
import './fetch' | import './promise'
import './find'
import './event-listener'
import './custom-event'
import './starts-with'
import './fetch' | Remove c3 and d3 from polyfills | Remove c3 and d3 from polyfills
| TypeScript | mit | the-concierge/concierge,the-concierge/concierge,the-concierge/concierge | ---
+++
@@ -1,5 +1,3 @@
-import 'd3'
-import 'c3'
import './promise'
import './find'
import './event-listener' |
d8760f06e8e2c6cd09491db7dde57d399c9eef2c | src/index.ts | src/index.ts | import { Document } from './document'
import { SortData } from './types/types'
import { binaryInsert, binarySearch, quickSort } from './utils'
class Index {
public name:string
private _index:Document[]
private _sortData:SortData[]
constructor (name:string, sortData?:SortData[]) {
this.name = name
this._index = []
this._sortData = sortData
}
public empty():void {
this._index.length = 0
}
public insert(doc:Document):void {
if (this._sortData && this._index.length > 0) {
// Work out where the doc goes based on the sort data
binaryInsert(this._index, doc, this._sortData)
} else {
this._index.push(doc)
}
}
public remove(doc:Document):void {
if (this._sortData) {
let i = binarySearch(this._index, doc, this._sortData)
} else {
this._index.splice(this._index.findIndex(d => d._id === doc._id), 1)
}
}
public values():Document[] {
return this._index
}
}
export { Index }
| import { Document } from './document'
import { SortData } from './types/types'
import { binaryInsert, binarySearch } from './utils'
class Index {
public name:string
private _index:Document[]
private _sortData:SortData[]
constructor (name:string, sortData?:SortData[]) {
this.name = name
this._index = []
this._sortData = sortData
}
public empty():void {
this._index.length = 0
}
public insert(doc:Document):void {
if (this._sortData && this._index.length > 0) {
// Work out where the doc goes based on the sort data
binaryInsert(this._index, doc, this._sortData)
} else {
this._index.push(doc)
}
}
public remove(doc:Document):void {
if (this._sortData) {
let i = binarySearch(this._index, doc, this._sortData)
} else {
this._index.splice(this._index.findIndex(d => d._id === doc._id), 1)
}
}
public values():Document[] {
return this._index
}
}
export { Index }
| Remove unused and deprecated 'quickSort' import | Remove unused and deprecated 'quickSort' import
| TypeScript | mit | varbrad/mindb,varbrad/mindb | ---
+++
@@ -2,7 +2,7 @@
import { SortData } from './types/types'
-import { binaryInsert, binarySearch, quickSort } from './utils'
+import { binaryInsert, binarySearch } from './utils'
class Index {
public name:string |
9ca5621e47793cf900d8fba64d4bd035ea647431 | src/index.ts | src/index.ts | export { RESTError } from './error';
export { SchemaRegistry } from './schema';
export { API } from './api';
export { Resource } from './resource';
export * from './mongo';
| export { RESTError } from './error';
export { SchemaRegistry } from './schema';
export { API } from './api';
export { Resource } from './resource';
export { Operation } from './operation';
export * from './mongo';
| Add missing export of the Operation class | feat(module): Add missing export of the Operation class
| TypeScript | mit | vivocha/arrest,vivocha/arrest | ---
+++
@@ -2,4 +2,5 @@
export { SchemaRegistry } from './schema';
export { API } from './api';
export { Resource } from './resource';
+export { Operation } from './operation';
export * from './mongo'; |
bf57f5542a69ac7a6a209552f7255c665169ad05 | {{cookiecutter.github_project_name}}/src/extension.ts | {{cookiecutter.github_project_name}}/src/extension.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// Entry point for the notebook bundle containing custom model definitions.
//
// Setup notebook base URL
//
// Some static assets may be required by the custom widget javascript. The base
// url for the notebook is not known at build time and is therefore computed
// dynamically.
__webpack_public_path__ = document.querySelector('body')!.getAttribute('data-base-url') + 'nbextensions/{{ cookiecutter.npm_package_name }}';
export * from './index';
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// Entry point for the notebook bundle containing custom model definitions.
//
// Setup notebook base URL
//
// Some static assets may be required by the custom widget javascript. The base
// url for the notebook is not known at build time and is therefore computed
// dynamically.
(window as any).__webpack_public_path__ = document.querySelector('body')!.getAttribute('data-base-url') + 'nbextensions/{{ cookiecutter.npm_package_name }}';
export * from './index';
| Fix webpack public path error. | Fix webpack public path error. | TypeScript | bsd-3-clause | jupyter-widgets/widget-ts-cookiecutter,jupyter-widgets/widget-ts-cookiecutter,jupyter-widgets/widget-ts-cookiecutter | ---
+++
@@ -8,6 +8,6 @@
// Some static assets may be required by the custom widget javascript. The base
// url for the notebook is not known at build time and is therefore computed
// dynamically.
-__webpack_public_path__ = document.querySelector('body')!.getAttribute('data-base-url') + 'nbextensions/{{ cookiecutter.npm_package_name }}';
+(window as any).__webpack_public_path__ = document.querySelector('body')!.getAttribute('data-base-url') + 'nbextensions/{{ cookiecutter.npm_package_name }}';
export * from './index'; |
f4cdc78c9f74d5918d40b03a526c1cef17b3a9e6 | src/js/View/Container.tsx | src/js/View/Container.tsx | import * as React from 'react';
import { connect } from 'react-redux';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import { AppLoading } from 'View/Ui/Index';
interface IContainerProps
{
store: Redux.Store<any>;
history: ReactRouterRedux.ReactRouterReduxHistory;
routes: ReactRouter.PlainRoute;
setup?: IStateSetup;
};
class Container extends React.Component<IContainerProps, any>
{
render()
{
return (
<div className="app">
{this.props.setup.isLoading
? <AppLoading show={this.props.setup.showLoading} />
: undefined}
{this.props.setup.renderApp
? (
<Provider store={this.props.store}>
<Router history={this.props.history}
routes={this.props.routes} />
</Provider>
)
: undefined}
</div>
);
}
};
export default connect(
(state: IState) => ({
setup : state.setup
})
)(Container as any); // @todo: Fix. Caused by 'setup?' | import * as React from 'react';
import { connect } from 'react-redux';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import { AppLoading } from 'View/Ui/Index';
interface IContainerProps
{
store: Redux.Store<any>;
history: ReactRouterRedux.ReactRouterReduxHistory;
routes: ReactRouter.PlainRoute;
setup?: IStateSetup;
};
class Container extends React.Component<IContainerProps, any>
{
render()
{
return (
<div className="app">
{this.props.setup.isLoading
? <AppLoading show={this.props.setup.showLoading} />
: undefined}
{this.props.setup.renderApp
? (
<Provider store={this.props.store}>
<Router history={this.props.history}
routes={this.props.routes} />
</Provider>
)
: undefined}
</div>
);
}
};
export default connect<{}, {}, IContainerProps>(
(state: IState) => ({
setup : state.setup
})
)(Container); | Fix Connect messing up type signatures | Fix Connect messing up type signatures
| TypeScript | mit | harksys/HawkEye,harksys/HawkEye,harksys/HawkEye | ---
+++
@@ -38,8 +38,8 @@
}
};
-export default connect(
+export default connect<{}, {}, IContainerProps>(
(state: IState) => ({
setup : state.setup
})
-)(Container as any); // @todo: Fix. Caused by 'setup?'
+)(Container); |
a00b6ff71c389d889a5bcb807dd0c543389d61a3 | src/TinyORM.ts | src/TinyORM.ts | import { camelCase, snakeCase } from 'change-case';
import { changeCaseDeep, getObject, validate, SchemaType } from './utils';
interface TinyProps {
[key: string]: { schema: SchemaType, value: any };
}
export class TinyORM<T> {
private _props: TinyProps;
constructor(model: T) {
for (let key in model) {
(<any>this)[key] = model[key];
}
}
static getInstance(model: any) {
model = changeCaseDeep(model, camelCase);
return new this(model);
}
validate() {
for (let key in this._props) {
if (this._props[key].schema) {
const propName = this.constructor.name + '.' + key;
return validate(this._props[key].value, this._props[key].schema, propName);
}
}
return true;
}
toObject(snakeCased = false) {
const obj = getObject(this._props);
if (snakeCased) {
return changeCaseDeep(obj, snakeCase) as T;
}
return obj as T;
}
toString(snakeCased = false) {
return JSON.stringify(this.toObject(snakeCased));
}
}
| import { camelCase, snakeCase } from 'change-case';
import { changeCaseDeep, getObject, validate, SchemaType } from './utils';
interface TinyProps {
[key: string]: { schema: SchemaType, value: any };
}
export class TinyORM<T> {
private _props: TinyProps;
constructor(model: T) {
for (let key in model) {
(<any>this)[key] = model[key];
}
}
static getInstance(model: any) {
model = changeCaseDeep(model, camelCase);
return new this(model);
}
validate() {
for (let key in this._props) {
if (this._props[key].schema) {
const propName = this.constructor.name + '.' + key;
return validate(this._props[key].value, this._props[key].schema, propName);
}
}
return true;
}
toObject() {
return getObject(this._props) as T;
}
toDBObject() {
const obj = getObject(this._props);
return changeCaseDeep(obj, snakeCase);
}
toString() {
return JSON.stringify(this.toObject());
}
}
| Refactor - toObject into toDBObject - remove toString override | Refactor
- toObject into toDBObject
- remove toString override
| TypeScript | mit | prashaantt/tiny-orm,prashaantt/tiny-orm | ---
+++
@@ -33,17 +33,17 @@
return true;
}
- toObject(snakeCased = false) {
+ toObject() {
+ return getObject(this._props) as T;
+ }
+
+ toDBObject() {
const obj = getObject(this._props);
- if (snakeCased) {
- return changeCaseDeep(obj, snakeCase) as T;
- }
-
- return obj as T;
+ return changeCaseDeep(obj, snakeCase);
}
- toString(snakeCased = false) {
- return JSON.stringify(this.toObject(snakeCased));
+ toString() {
+ return JSON.stringify(this.toObject());
}
} |
d92759ff7271ab4d818b7416ffc385ca80191064 | src/index.ts | src/index.ts | import * as Hapi from 'hapi';
import Logger from './helper/logger';
import * as Router from './router';
import Plugins from './plugins';
class Server {
public static init() : void {
const server = new Hapi.Server();
server.connection({
host: process.env.HOST,
port: process.env.PORT
});
if (process.env.NODE_ENV === 'development') {
Plugins.status(server);
Plugins.swagger(server);
}
Router.register(server);
server.start(error => {
if (error) {
Logger.info(`There was something wrong: ${error}`);
}
Logger.info('Server is up and running!');
});
}
}
export default Server.init(); | import * as Hapi from 'hapi';
import Logger from './helper/logger';
import * as Router from './router';
import Plugins from './plugins';
class Server {
public static init() : void {
try {
const server = new Hapi.Server();
server.connection({
host: process.env.HOST,
port: process.env.PORT
});
if (process.env.NODE_ENV === 'development') {
Plugins.status(server);
Plugins.swagger(server);
}
Router.register(server);
await server.start();
Logger.info('Server is up and running!');
} catch(error) {
Logger.info(`There was something wrong: ${error}`);
}
}
}
export default Server.init();
| Move server to async/await syntax | Move server to async/await syntax | TypeScript | mit | BlackBoxVision/typescript-hapi-starter,BlackBoxVision/typescript-hapi-starter,BlackBoxVision/typescript-hapi-starter | ---
+++
@@ -6,27 +6,27 @@
class Server {
public static init() : void {
- const server = new Hapi.Server();
+ try {
+ const server = new Hapi.Server();
- server.connection({
- host: process.env.HOST,
- port: process.env.PORT
- });
+ server.connection({
+ host: process.env.HOST,
+ port: process.env.PORT
+ });
- if (process.env.NODE_ENV === 'development') {
- Plugins.status(server);
- Plugins.swagger(server);
- }
-
- Router.register(server);
-
- server.start(error => {
- if (error) {
- Logger.info(`There was something wrong: ${error}`);
+ if (process.env.NODE_ENV === 'development') {
+ Plugins.status(server);
+ Plugins.swagger(server);
}
+ Router.register(server);
+
+ await server.start();
+
Logger.info('Server is up and running!');
- });
+ } catch(error) {
+ Logger.info(`There was something wrong: ${error}`);
+ }
}
}
|
79f51c009d8b4f2b8447f99fb2c94714229f9771 | src/spec.utils.ts | src/spec.utils.ts | export const checkProtoChain = (contructor, ...chain) => {
const error = new contructor()
expect(error).toBeInstanceOf(contructor)
chain.forEach(c => expect(error).toBeInstanceOf(c))
}
export const checkProperties = (contructor, message = 'foo') => {
const error = new contructor(message)
expect(error.message).toBe(message)
expect(error).toHaveProperty('stack')
}
| export const checkProtoChain = (contructor, ...chain) => {
const error = new contructor()
expect(error).toBeInstanceOf(contructor)
chain.forEach(type => expect(error).toBeInstanceOf(type))
}
export const checkProperties = (contructor, message = 'foo') => {
const error = new contructor(message)
expect(error.message).toBe(message)
expect(error).toHaveProperty('stack')
}
| Use more readable var name | style: Use more readable var name
| TypeScript | mit | adriengibrat/ts-custom-error | ---
+++
@@ -1,7 +1,7 @@
export const checkProtoChain = (contructor, ...chain) => {
const error = new contructor()
expect(error).toBeInstanceOf(contructor)
- chain.forEach(c => expect(error).toBeInstanceOf(c))
+ chain.forEach(type => expect(error).toBeInstanceOf(type))
}
export const checkProperties = (contructor, message = 'foo') => { |
1fb98a4303e5e55acca78d7e97a2d6a917a705eb | src/app/app.component.ts | src/app/app.component.ts | import { Component, OnInit } from '@angular/core';
import { ViewManagerService } from './manager/view-manager.service';
declare var smoothScroll: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less'],
})
export class AppComponent implements OnInit {
constructor(
private viewManager: ViewManagerService,
) { }
public get isRoot(): boolean {
// Router's url isn't resolved just after visited, so use window.location.pathname
return window.location.pathname === '/';
}
public get showBackToTop(): boolean {
return this.viewManager.offset.y > 80;
}
ngOnInit() {
}
public onPressBackToTop(): void {
smoothScroll.animateScroll(0);
}
}
| import { Component, OnInit } from '@angular/core';
import { ViewManagerService } from './manager/view-manager.service';
declare var SmoothScroll: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less'],
})
export class AppComponent implements OnInit {
constructor(
private viewManager: ViewManagerService,
) { }
public get isRoot(): boolean {
// Router's url isn't resolved just after visited, so use window.location.pathname
return window.location.pathname === '/';
}
public get showBackToTop(): boolean {
return this.viewManager.offset.y > 80;
}
ngOnInit() {
}
public onPressBackToTop(): void {
const scroll = new SmoothScroll();
scroll.animateScroll(0);
}
}
| Update the way to use smooth-scroll according to its new manual | Update the way to use smooth-scroll according to its new manual
| TypeScript | mit | tsugitta/tsugitta.github.io,tsugitta/tsugitta.github.io,tsugitta/tsugitta.github.io,tsugitta/tsugitta.github.io | ---
+++
@@ -1,7 +1,7 @@
import { Component, OnInit } from '@angular/core';
import { ViewManagerService } from './manager/view-manager.service';
-declare var smoothScroll: any;
+declare var SmoothScroll: any;
@Component({
selector: 'app-root',
@@ -26,6 +26,7 @@
}
public onPressBackToTop(): void {
- smoothScroll.animateScroll(0);
+ const scroll = new SmoothScroll();
+ scroll.animateScroll(0);
}
} |
bfe4eb7edff77eef43e45daf2a4251e12ff4ada7 | src/application/index.ts | src/application/index.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Application
} from 'phosphor/lib/ui/application';
import {
ApplicationShell
} from './shell';
/**
* The type for all JupyterLab plugins.
*/
export
type JupyterLabPlugin<T> = Application.IPlugin<JupyterLab, T>;
/**
* JupyterLab is the main application class. It is instantiated once and shared.
*/
export
class JupyterLab extends Application<ApplicationShell> {
/**
* Create a new JupyterLab instance.
*/
constructor() {
super();
this._startedPromise = new Promise(fn => { this._startedResolve = fn; });
}
/**
* A promise that resolves when the JupyterLab application is started.
*/
get started(): Promise<void> {
return this._startedPromise;
}
/**
* Start the JupyterLab application.
*/
start(options: Application.IStartOptions = {}): Promise<void> {
return super.start(options).then(() => { this._startedResolve(); });
}
/**
* Create the application shell for the JupyterLab application.
*/
protected createShell(): ApplicationShell {
return new ApplicationShell();
}
private _startedResolve: () => void;
private _startedPromise: Promise<void> = null;
}
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Application
} from 'phosphor/lib/ui/application';
import {
ApplicationShell
} from './shell';
/**
* The type for all JupyterLab plugins.
*/
export
type JupyterLabPlugin<T> = Application.IPlugin<JupyterLab, T>;
/**
* JupyterLab is the main application class. It is instantiated once and shared.
*/
export
class JupyterLab extends Application<ApplicationShell> {
/**
* Create a new JupyterLab instance.
*/
constructor() {
super();
this._startedPromise = new Promise(fn => { this._startedResolve = fn; });
}
/**
* A promise that resolves when the JupyterLab application is started.
*/
get started(): Promise<void> {
return this._startedPromise;
}
/**
* Start the JupyterLab application.
*/
start(options: Application.IStartOptions = {}): Promise<void> {
if (this._startedFlag) {
return Promise.resolve(void 0);
}
this._startedFlag = true;
return super.start(options).then(() => { this._startedResolve(); });
}
/**
* Create the application shell for the JupyterLab application.
*/
protected createShell(): ApplicationShell {
return new ApplicationShell();
}
private _startedFlag = false;
private _startedPromise: Promise<void> = null;
private _startedResolve: () => void = null;
}
| Use flag to only start once. | Use flag to only start once.
| TypeScript | bsd-3-clause | charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab | ---
+++
@@ -41,6 +41,10 @@
* Start the JupyterLab application.
*/
start(options: Application.IStartOptions = {}): Promise<void> {
+ if (this._startedFlag) {
+ return Promise.resolve(void 0);
+ }
+ this._startedFlag = true;
return super.start(options).then(() => { this._startedResolve(); });
}
@@ -51,6 +55,7 @@
return new ApplicationShell();
}
- private _startedResolve: () => void;
+ private _startedFlag = false;
private _startedPromise: Promise<void> = null;
+ private _startedResolve: () => void = null;
} |
86fc55e14254ceb3a980575e76bdc415e3b621b8 | src/options.ts | src/options.ts | module Rimu.Options {
export interface Values {
safeMode?: number;
htmlReplacement?: string;
}
// Option values.
export var safeMode: number;
export var htmlReplacement: string;
// Set options to values in 'options', those not in 'options' are set to
// their default value.
export function update(options: Values): void {
safeMode = ('safeMode' in options) ? options.safeMode : 0;
htmlReplacement = ('htmlReplacement' in options) ? options.htmlReplacement : '<mark>replaced HTML<mark>';
}
export function safeModeFilter(text: string): string {
switch (safeMode) {
case 0: // Raw HTML (default behavior).
return text;
case 1: // Drop HTML.
return '';
case 2: // Replace HTML with 'htmlReplacement' option string.
return htmlReplacement;
case 3: // Render HTML as text.
return replaceSpecialChars(text);
default:
throw 'illegal safeMode value';
}
}
update({}); // Initialize options to default values.
}
| module Rimu.Options {
export interface Values {
safeMode?: number;
htmlReplacement?: string;
}
// Option values.
export var safeMode: number;
export var htmlReplacement: string;
// Set options to values in 'options', those not in 'options' are set to
// their default value.
export function update(options: Values): void {
safeMode = ('safeMode' in options) ? options.safeMode : 0;
htmlReplacement = ('htmlReplacement' in options) ? options.htmlReplacement : '<mark>replaced HTML</mark>';
}
export function safeModeFilter(text: string): string {
switch (safeMode) {
case 0: // Raw HTML (default behavior).
return text;
case 1: // Drop HTML.
return '';
case 2: // Replace HTML with 'htmlReplacement' option string.
return htmlReplacement;
case 3: // Render HTML as text.
return replaceSpecialChars(text);
default:
throw 'illegal safeMode value';
}
}
update({}); // Initialize options to default values.
}
| Fix default API htmlReplacement option value. | Fix default API htmlReplacement option value.
| TypeScript | mit | srackham/rimu | ---
+++
@@ -13,7 +13,7 @@
// their default value.
export function update(options: Values): void {
safeMode = ('safeMode' in options) ? options.safeMode : 0;
- htmlReplacement = ('htmlReplacement' in options) ? options.htmlReplacement : '<mark>replaced HTML<mark>';
+ htmlReplacement = ('htmlReplacement' in options) ? options.htmlReplacement : '<mark>replaced HTML</mark>';
}
export function safeModeFilter(text: string): string { |
7453fca0196db941888430a75ca6036ee37bff1b | client/src/app/users/user-list.service.ts | client/src/app/users/user-list.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { User } from './user';
import { Observable } from "rxjs";
@Injectable()
export class UserListService {
private userUrl: string = API_URL + "users/";
constructor(private http:Http) { }
getUsers(): Observable<User[]> {
return this.http.request(this.userUrl + 'users').map(res => res.json());
}
getUserById(id: string): Observable<User> {
return this.http.request(this.userUrl + id).map(res => res.json());
}
} | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { User } from './user';
import { Observable } from "rxjs";
@Injectable()
export class UserListService {
private userUrl: string = API_URL + "users";
constructor(private http:Http) { }
getUsers(): Observable<User[]> {
return this.http.request(this.userUrl).map(res => res.json());
}
getUserById(id: string): Observable<User> {
return this.http.request(this.userUrl + "/" + id).map(res => res.json());
}
} | Fix URL bug in `UserListService` | Fix URL bug in `UserListService`
I had tried to clean up the URL handling in `UserListService`, but didn't
test it properly and we rolled it out in a broken state.
We probably want to add some tests for the service to catch problems
like this in the future.
Fixes #24
| TypeScript | mit | UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601/3601-lab4_mongo | ---
+++
@@ -5,14 +5,14 @@
@Injectable()
export class UserListService {
- private userUrl: string = API_URL + "users/";
+ private userUrl: string = API_URL + "users";
constructor(private http:Http) { }
getUsers(): Observable<User[]> {
- return this.http.request(this.userUrl + 'users').map(res => res.json());
+ return this.http.request(this.userUrl).map(res => res.json());
}
getUserById(id: string): Observable<User> {
- return this.http.request(this.userUrl + id).map(res => res.json());
+ return this.http.request(this.userUrl + "/" + id).map(res => res.json());
}
} |
1f104389d9872df308fe4ae255f07f00100b61f6 | tools/env/base.ts | tools/env/base.ts | import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.13.0',
RELEASEVERSION: '0.13.0'
};
export = BaseConfig;
| import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.13.1',
RELEASEVERSION: '0.13.1'
};
export = BaseConfig;
| Update release version to 0.13.1 | Update release version to 0.13.1
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -3,8 +3,8 @@
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
- RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.13.0',
- RELEASEVERSION: '0.13.0'
+ RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.13.1',
+ RELEASEVERSION: '0.13.1'
};
export = BaseConfig; |
cdd31d87e362dd306db6692961b067d099c0f895 | configloader.ts | configloader.ts | import RoutingServer from './routingserver';
export interface ConfigServer {
listenPort: number;
routingServers: RoutingServer[];
}
export interface LogOptions {
clientTimeouts: boolean;
clientConnect: boolean;
clientDisconnect: boolean;
clientError: boolean;
tServerConnect: boolean;
tServerDisconnect: boolean;
tServerError: boolean;
}
export interface ConfigOptions {
clientTimeout: number;
fakeVersion: boolean;
fakeVersionNum: number;
blockInvis: boolean;
useBlacklist: boolean;
blacklistAPIKey: string;
log: LogOptions;
}
export interface Config {
servers: ConfigServer[];
options: ConfigOptions;
}
export const ConfigSettings: Config = require(`../config.js`).ConfigSettings; | import RoutingServer from './routingserver';
export interface ConfigServer {
listenPort: number;
routingServers: RoutingServer[];
}
export interface LogOptions {
clientTimeouts: boolean;
clientConnect: boolean;
clientDisconnect: boolean;
clientError: boolean;
tServerConnect: boolean;
tServerDisconnect: boolean;
tServerError: boolean;
clientBlocked: boolean;
}
export interface ConfigOptions {
clientTimeout: number;
fakeVersion: boolean;
fakeVersionNum: number;
blockInvis: boolean;
useBlacklist: boolean;
blacklistAPIKey: string;
log: LogOptions;
}
export interface Config {
servers: ConfigServer[];
options: ConfigOptions;
}
export const ConfigSettings: Config = require(`../config.js`).ConfigSettings; | Add blocking to log options | Add blocking to log options
| TypeScript | mit | popstarfreas/Dimensions,popstarfreas/Dimensions,popstarfreas/Dimensions | ---
+++
@@ -13,6 +13,7 @@
tServerConnect: boolean;
tServerDisconnect: boolean;
tServerError: boolean;
+ clientBlocked: boolean;
}
export interface ConfigOptions { |
1d11074a36d8d75c7b5070ba4e818e8849a33f73 | projects/sample-code-flow-azuread/src/app/app.routes.ts | projects/sample-code-flow-azuread/src/app/app.routes.ts | import { RouterModule, Routes } from '@angular/router';
import { AutoLoginGuard } from 'angular-auth-oidc-client';
import { ForbiddenComponent } from './forbidden/forbidden.component';
import { HomeComponent } from './home/home.component';
import { ProtectedComponent } from './protected/protected.component';
import { UnauthorizedComponent } from './unauthorized/unauthorized.component';
const appRoutes: Routes = [
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'home', component: HomeComponent, canActivate: [AutoLoginGuard] },
{ path: 'forbidden', component: ForbiddenComponent, canActivate: [AutoLoginGuard] },
{ path: 'protected', component: ProtectedComponent, canActivate: [AutoLoginGuard] },
{ path: 'unauthorized', component: UnauthorizedComponent },
];
export const routing = RouterModule.forRoot(appRoutes);
| import { RouterModule, Routes } from '@angular/router';
import { AutoLoginGuard } from 'angular-auth-oidc-client';
import { ForbiddenComponent } from './forbidden/forbidden.component';
import { HomeComponent } from './home/home.component';
import { ProtectedComponent } from './protected/protected.component';
import { UnauthorizedComponent } from './unauthorized/unauthorized.component';
const appRoutes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'home' },
{ path: 'home', component: HomeComponent, canActivate: [AutoLoginGuard] },
{ path: 'forbidden', component: ForbiddenComponent, canActivate: [AutoLoginGuard] },
{ path: 'protected', component: ProtectedComponent, canActivate: [AutoLoginGuard] },
{ path: 'unauthorized', component: UnauthorizedComponent },
];
export const routing = RouterModule.forRoot(appRoutes);
| Add this to the DOCS, redirect path to an auto login guard | Add this to the DOCS, redirect path to an auto login guard
| TypeScript | mit | damienbod/angular-auth-oidc-client,damienbod/angular-auth-oidc-client,damienbod/angular-auth-oidc-client | ---
+++
@@ -6,7 +6,7 @@
import { UnauthorizedComponent } from './unauthorized/unauthorized.component';
const appRoutes: Routes = [
- { path: '', component: HomeComponent, pathMatch: 'full' },
+ { path: '', pathMatch: 'full', redirectTo: 'home' },
{ path: 'home', component: HomeComponent, canActivate: [AutoLoginGuard] },
{ path: 'forbidden', component: ForbiddenComponent, canActivate: [AutoLoginGuard] },
{ path: 'protected', component: ProtectedComponent, canActivate: [AutoLoginGuard] }, |
fbd0c27a4ef52e73c0fab9c9cc86aa9ccd1f8b45 | addon/models/sku.ts | addon/models/sku.ts | import DS from "ember-data";
import { computed, get } from "@ember/object";
import Price from "./price";
import Product from "./product";
import Bom from "./bom";
import SkuImage from "./sku-image";
import SkuField from "./sku-field";
export default class Sku extends DS.Model {
@DS.attr("number") stockQuantity!: number;
@DS.belongsTo("price") price!: Price;
@DS.belongsTo("product") product!: Product;
@DS.belongsTo("bom", { async: false }) bom!: Bom;
@DS.hasMany("sku-image") skuImages!: SkuImage[];
@DS.hasMany("sku-field") skuFields!: SkuField[];
@computed("skuFields.[]")
get attributes(): any {
return this.skuFields.reduce((hash: any, attribute: any) => {
hash[get(attribute, "slug")] = get(attribute, "values");
return hash;
}, {});
}
}
declare module "ember-data/types/registries/model" {
export default interface ModelRegistry {
sku: Sku;
}
}
| import DS from "ember-data";
import Price from "./price";
import Product from "./product";
import Bom from "./bom";
export default class Sku extends DS.Model {
@DS.attr("number") stockQuantity!: number;
@DS.attr() attrs!: any;
@DS.belongsTo("price") price!: Price;
@DS.belongsTo("product") product!: Product;
@DS.belongsTo("bom", { async: false }) bom!: Bom;
}
declare module "ember-data/types/registries/model" {
export default interface ModelRegistry {
sku: Sku;
}
}
| Remove computed attributes from SKU model | Remove computed attributes from SKU model
| TypeScript | mit | goods/ember-goods,goods/ember-goods,goods/ember-goods | ---
+++
@@ -1,26 +1,14 @@
import DS from "ember-data";
-import { computed, get } from "@ember/object";
import Price from "./price";
import Product from "./product";
import Bom from "./bom";
-import SkuImage from "./sku-image";
-import SkuField from "./sku-field";
export default class Sku extends DS.Model {
@DS.attr("number") stockQuantity!: number;
+ @DS.attr() attrs!: any;
@DS.belongsTo("price") price!: Price;
@DS.belongsTo("product") product!: Product;
@DS.belongsTo("bom", { async: false }) bom!: Bom;
- @DS.hasMany("sku-image") skuImages!: SkuImage[];
- @DS.hasMany("sku-field") skuFields!: SkuField[];
-
- @computed("skuFields.[]")
- get attributes(): any {
- return this.skuFields.reduce((hash: any, attribute: any) => {
- hash[get(attribute, "slug")] = get(attribute, "values");
- return hash;
- }, {});
- }
}
declare module "ember-data/types/registries/model" { |
e8605f71a9fb400963f99cfbca9d07050a15e8fa | test/storage/CompressedStorageTest.ts | test/storage/CompressedStorageTest.ts | import { expect } from "chai";
import { capture, spy } from "ts-mockito";
import { InMemoryStorage } from "storage/Storage";
import { CompressedStorage } from "storage/CompressedStorage";
function sizeOf(data: any): number {
return new TextEncoder().encode(JSON.stringify(data)).length;
}
describe("CompressedStorage", () => {
it("should compress the data", async () => {
const data: string[] = new Array(100).fill("woop");
const baseStorage = new InMemoryStorage<string>();
const spiedStorage = spy(baseStorage);
const cachedStorage = new CompressedStorage<string[]>(baseStorage);
await cachedStorage.save(data);
const compressed = capture(spiedStorage.save).first()[ 0 ];
expect(sizeOf(compressed)).to.be.lessThan(sizeOf(data));
});
it("should not save original data", async () => {
const data = "woop";
const baseStorage = new InMemoryStorage<string>();
const spiedStorage = spy(baseStorage);
const cachedStorage = new CompressedStorage<string>(baseStorage);
await cachedStorage.save(data);
const compressed = capture(spiedStorage.save).first()[ 0 ];
expect(data).to.not.equal(compressed);
});
});
| import { expect } from "chai";
import { capture, spy } from "ts-mockito";
import { InMemoryStorage } from "storage/Storage";
import { CompressedStorage } from "storage/CompressedStorage";
function sizeOf(data: any): number {
return Buffer.byteLength(JSON.stringify(data), "utf8");
}
describe("CompressedStorage", () => {
it("should compress the data", async () => {
const data: string[] = new Array(100).fill("woop");
const baseStorage = new InMemoryStorage<string>();
const spiedStorage = spy(baseStorage);
const cachedStorage = new CompressedStorage<string[]>(baseStorage);
await cachedStorage.save(data);
const compressed = capture(spiedStorage.save).first()[ 0 ];
expect(sizeOf(compressed)).to.be.lessThan(sizeOf(data));
});
it("should not save original data", async () => {
const data = "woop";
const baseStorage = new InMemoryStorage<string>();
const spiedStorage = spy(baseStorage);
const cachedStorage = new CompressedStorage<string>(baseStorage);
await cachedStorage.save(data);
const compressed = capture(spiedStorage.save).first()[ 0 ];
expect(data).to.not.equal(compressed);
});
});
| Fix broken tests due to TextEncoder not available in node | Fix broken tests due to TextEncoder not available in node
| TypeScript | mit | easyfuckingpeasy/chrome-reddit-comment-highlights,easyfuckingpeasy/chrome-reddit-comment-highlights | ---
+++
@@ -4,7 +4,7 @@
import { CompressedStorage } from "storage/CompressedStorage";
function sizeOf(data: any): number {
- return new TextEncoder().encode(JSON.stringify(data)).length;
+ return Buffer.byteLength(JSON.stringify(data), "utf8");
}
describe("CompressedStorage", () => { |
4e1b0b95ef909e3e82a9be03281320229394c43f | app/src/lib/welcome.ts | app/src/lib/welcome.ts | /** The `localStorage` key for whether we've shown the Welcome flow yet. */
const HasShownWelcomeFlowKey = 'has-shown-welcome-flow'
/**
* Check if the current user has completed the welcome flow.
*/
export function hasShownWelcomeFlow(): boolean {
const hasShownWelcomeFlow = localStorage.getItem(HasShownWelcomeFlowKey)
if (!hasShownWelcomeFlow) {
return false
}
const value = parseInt(hasShownWelcomeFlow, 10)
return value === 1
}
/**
* Update local storage to indicate the welcome flow has been completed.
*/
export function markWelcomeFlowComplete() {
localStorage.setItem(HasShownWelcomeFlowKey, '1')
}
| import { getBoolean, setBoolean } from './local-storage'
/** The `localStorage` key for whether we've shown the Welcome flow yet. */
const HasShownWelcomeFlowKey = 'has-shown-welcome-flow'
/**
* Check if the current user has completed the welcome flow.
*/
export function hasShownWelcomeFlow(): boolean {
return getBoolean(HasShownWelcomeFlowKey, false)
}
/**
* Update local storage to indicate the welcome flow has been completed.
*/
export function markWelcomeFlowComplete() {
setBoolean(HasShownWelcomeFlowKey, true)
}
| Update usage in Welcome wizard | Update usage in Welcome wizard
| TypeScript | mit | kactus-io/kactus,j-f1/forked-desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,shiftkey/desktop,artivilla/desktop,kactus-io/kactus,shiftkey/desktop,shiftkey/desktop,say25/desktop,desktop/desktop,say25/desktop,desktop/desktop,say25/desktop,desktop/desktop,j-f1/forked-desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop | ---
+++
@@ -1,3 +1,5 @@
+import { getBoolean, setBoolean } from './local-storage'
+
/** The `localStorage` key for whether we've shown the Welcome flow yet. */
const HasShownWelcomeFlowKey = 'has-shown-welcome-flow'
@@ -5,18 +7,12 @@
* Check if the current user has completed the welcome flow.
*/
export function hasShownWelcomeFlow(): boolean {
- const hasShownWelcomeFlow = localStorage.getItem(HasShownWelcomeFlowKey)
- if (!hasShownWelcomeFlow) {
- return false
- }
-
- const value = parseInt(hasShownWelcomeFlow, 10)
- return value === 1
+ return getBoolean(HasShownWelcomeFlowKey, false)
}
/**
* Update local storage to indicate the welcome flow has been completed.
*/
export function markWelcomeFlowComplete() {
- localStorage.setItem(HasShownWelcomeFlowKey, '1')
+ setBoolean(HasShownWelcomeFlowKey, true)
} |
20880a949b764ae35c9d69b55358f932094a6621 | core/modules/catalog/components/ProductGallery.ts | core/modules/catalog/components/ProductGallery.ts | import VueOffline from 'vue-offline'
import store from '@vue-storefront/store'
export const ProductGallery = {
name: 'ProductGallery',
components: {
VueOffline
},
props: {
gallery: {
type: Array,
required: true
},
configuration: {
type: Object,
required: true
},
offline: {
type: Object,
required: true
},
product: {
type: Object,
required: true
}
},
beforeMount () {
this.$bus.$on('filter-changed-product', this.selectVariant)
this.$bus.$on('product-after-load', this.selectVariant)
},
mounted () {
this.$forceUpdate()
document.addEventListener('keydown', this.handleEscKey)
},
beforeDestroy () {
this.$bus.$off('filter-changed-product', this.selectVariant)
this.$bus.$off('product-after-load', this.selectVariant)
document.removeEventListener('keydown', this.handleEscKey)
},
computed: {
defaultImage () {
return this.gallery.length ? this.gallery[0] : false
}
},
methods: {
toggleZoom () {
this.isZoomOpen = !this.isZoomOpen
},
handleEscKey (event) {
if (this.isZoomOpen && event.keyCode === 27) {
this.toggleZoom()
}
}
}
}
| import VueOffline from 'vue-offline'
import store from '@vue-storefront/store'
export const ProductGallery = {
name: 'ProductGallery',
components: {
VueOffline
},
props: {
gallery: {
type: Array,
required: true
},
configuration: {
type: Object,
required: true
},
offline: {
type: Object,
required: true
},
product: {
type: Object,
required: true
}
},
beforeMount () {
this.$bus.$on('filter-changed-product', this.selectVariant)
this.$bus.$on('product-after-load', this.selectVariant)
},
mounted () {
document.addEventListener('keydown', this.handleEscKey)
},
beforeDestroy () {
this.$bus.$off('filter-changed-product', this.selectVariant)
this.$bus.$off('product-after-load', this.selectVariant)
document.removeEventListener('keydown', this.handleEscKey)
},
computed: {
defaultImage () {
return this.gallery.length ? this.gallery[0] : false
}
},
methods: {
toggleZoom () {
this.isZoomOpen = !this.isZoomOpen
},
handleEscKey (event) {
if (this.isZoomOpen && event.keyCode === 27) {
this.toggleZoom()
}
}
}
}
| Remove forceUpdate from mounted and removed whitespace | Remove forceUpdate from mounted and removed whitespace
| TypeScript | mit | DivanteLtd/vue-storefront,DivanteLtd/vue-storefront,DivanteLtd/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,pkarw/vue-storefront,pkarw/vue-storefront,pkarw/vue-storefront | ---
+++
@@ -29,7 +29,6 @@
this.$bus.$on('product-after-load', this.selectVariant)
},
mounted () {
- this.$forceUpdate()
document.addEventListener('keydown', this.handleEscKey)
},
beforeDestroy () {
@@ -50,6 +49,6 @@
if (this.isZoomOpen && event.keyCode === 27) {
this.toggleZoom()
}
- }
+ }
}
} |
40b36eebfb02e6ff1869ed2283245f0f46fa302f | app/src/lib/fix-emoji-spacing.ts | app/src/lib/fix-emoji-spacing.ts | // This module renders an element with an emoji using
// a non system-default font to workaround an Chrome
// issue that causes unexpected spacing on emojis.
// More info:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1113293
const container = document.createElement('div')
container.setAttribute(
'style',
'visibility: hidden; font-family: Arial !important;'
)
// Keep this array synced with the font size variables
// in _variables.scss
const fontSizes = [
'--font-size',
'--font-size-sm',
'--font-size-md',
'--font-size-lg',
'--font-size-xl',
'--font-size-xxl',
'--font-size-xs',
]
for (const fontSize of fontSizes) {
const span = document.createElement('span')
span.style.setProperty('fontSize', `var(${fontSize}`)
span.style.setProperty('font-family', 'Arial', 'important')
span.textContent = '🤦🏿♀️'
container.appendChild(span)
}
document.body.appendChild(container)
// Read the dimensions of the element to force the browser to do a layout.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
container.offsetHeight
// Browser has rendered the emojis, now we can remove them.
document.body.removeChild(container)
| // This module renders an element with an emoji using
// a non system-default font to workaround an Chrome
// issue that causes unexpected spacing on emojis.
// More info:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1113293
const container = document.createElement('div')
container.style.setProperty('visibility', 'hidden')
container.style.setProperty('position', 'absolute')
// Keep this array synced with the font size variables
// in _variables.scss
const fontSizes = [
'--font-size',
'--font-size-sm',
'--font-size-md',
'--font-size-lg',
'--font-size-xl',
'--font-size-xxl',
'--font-size-xs',
]
for (const fontSize of fontSizes) {
const span = document.createElement('span')
span.style.setProperty('fontSize', `var(${fontSize}`)
span.style.setProperty('font-family', 'Arial', 'important')
span.textContent = '🤦🏿♀️'
container.appendChild(span)
}
document.body.appendChild(container)
// Read the dimensions of the element to force the browser to do a layout.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
container.offsetHeight
// Browser has rendered the emojis, now we can remove them.
document.body.removeChild(container)
| Use `style.setProperty()` method to apply style | Use `style.setProperty()` method to apply style
Co-authored-by: Markus Olsson <[email protected]> | TypeScript | mit | say25/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,shiftkey/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,kactus-io/kactus,desktop/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop,kactus-io/kactus,say25/desktop,say25/desktop,artivilla/desktop | ---
+++
@@ -5,10 +5,8 @@
// https://bugs.chromium.org/p/chromium/issues/detail?id=1113293
const container = document.createElement('div')
-container.setAttribute(
- 'style',
- 'visibility: hidden; font-family: Arial !important;'
-)
+container.style.setProperty('visibility', 'hidden')
+container.style.setProperty('position', 'absolute')
// Keep this array synced with the font size variables
// in _variables.scss |
e87521a0fd7ac14660a8bf265df3aa93f7516a5b | tests/cases/fourslash/restParametersTypeValidation_1.ts | tests/cases/fourslash/restParametersTypeValidation_1.ts | /// <reference path="../fourslash.ts" />
//// function f18(a?:string, ...b){}
////
//// function f19(a?:string, b?){}
////
//// function f20(a:string, b?:string, ...c:number[]){}
////
//// function f21(a:string, b?:string, ...d:number[]){}
edit.disableFormatting();
//diagnostics.validateTypesAtPositions(48,100,43,133,47);
| /// <reference path="../fourslash.ts" />
//// function f18(a?:string, ...b){}
////
//// function f19(a?:string, b?){}
////
//// function f20(a:string, b?:string, ...c:number[]){}
////
//// function f21(a:string, b?:string, ...d:number[]){}
edit.disableFormatting();
diagnostics.validateTypesAtPositions(48,100,43,133,47);
| Update testcase to function as regression test | Update testcase to function as regression test
| TypeScript | apache-2.0 | hippich/typescript,mbebenita/shumway.ts,mbrowne/typescript-dci,mbrowne/typescript-dci,fdecampredon/jsx-typescript-old-version,popravich/typescript,hippich/typescript,mbebenita/shumway.ts,mbrowne/typescript-dci,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,hippich/typescript,mbrowne/typescript-dci,popravich/typescript,fdecampredon/jsx-typescript-old-version,popravich/typescript | ---
+++
@@ -9,4 +9,4 @@
//// function f21(a:string, b?:string, ...d:number[]){}
edit.disableFormatting();
-//diagnostics.validateTypesAtPositions(48,100,43,133,47);
+diagnostics.validateTypesAtPositions(48,100,43,133,47); |
074da24c780ef0ef3a81d8c014deb859f73a4cd8 | ui/src/app/app-config.ts | ui/src/app/app-config.ts | import { environment } from '../environments/environment';
export class AppConfig {
public static K8S_REST_URL = environment.prefix + 'k8s/';
public static VPP_REST_URL = environment.prefix + 'contiv/';
public static API_V1 = 'api/v1/';
public static API_V1_NETWORKING = 'apis/networking.k8s.io/v1/';
public static API_V1_CONTIV = 'contiv/v1/';
public static API_V1_VPP = 'vpp/dump/v1/';
public static API_V2_VPP = 'vpp/dump/v2/';
}
| import { environment } from '../environments/environment';
export class AppConfig {
public static K8S_REST_URL = environment.prefix + 'k8s/';
public static VPP_REST_URL = environment.prefix + 'contiv/';
public static API_V1 = 'api/v1/';
public static API_V1_NETWORKING = 'apis/networking.k8s.io/v1/';
public static API_V1_CONTIV = 'contiv/v1/';
public static API_V1_VPP = 'vpp/dump/v1/';
public static API_V2_VPP = 'dump/vpp/v2/';
}
| Fix rest url in UI | Fix rest url in UI
| TypeScript | apache-2.0 | rastislavszabo/vpp,rastislavszabo/vpp,rastislavszabo/vpp,brecode/vpp,brecode/vpp,rastislavszabo/vpp,rastislavszabo/vpp,rastislavszabo/vpp,rastislavszabo/vpp,brecode/vpp,brecode/vpp,brecode/vpp | ---
+++
@@ -7,5 +7,5 @@
public static API_V1_NETWORKING = 'apis/networking.k8s.io/v1/';
public static API_V1_CONTIV = 'contiv/v1/';
public static API_V1_VPP = 'vpp/dump/v1/';
- public static API_V2_VPP = 'vpp/dump/v2/';
+ public static API_V2_VPP = 'dump/vpp/v2/';
} |
40ac3bd9e28c76551fe7dbb2ade8cde0fd71f1aa | src/app/views/dashboard/developer/games/manage/site/site.state.ts | src/app/views/dashboard/developer/games/manage/site/site.state.ts | import { Transition } from 'angular-ui-router';
import { Api } from '../../../../../../../lib/gj-lib-client/components/api/api.service';
import { makeState } from '../../../../../../../lib/gj-lib-client/utils/angular-facade';
makeState( 'dashboard.developer.games.manage.site', {
url: '/site',
lazyLoad: () => $import( './site.module' ),
resolve: {
payload: function( $transition$: Transition )
{
return Api.sendRequest( '/web/dash/sites/' + $transition$.params().id );
},
}
} );
| import { Transition } from 'angular-ui-router';
import { Api } from '../../../../../../../lib/gj-lib-client/components/api/api.service';
import { makeState } from '../../../../../../../lib/gj-lib-client/utils/angular-facade';
makeState( 'dashboard.developer.games.manage.site', {
url: '/site',
lazyLoad: () => $import( './site.module' ),
resolve: {
/*@ngInject*/
payload: function( $transition$: Transition )
{
return Api.sendRequest( '/web/dash/sites/' + $transition$.params().id );
},
}
} );
| Fix sites resolve for ng inject | Fix sites resolve for ng inject
| TypeScript | mit | gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt | ---
+++
@@ -6,6 +6,8 @@
url: '/site',
lazyLoad: () => $import( './site.module' ),
resolve: {
+
+ /*@ngInject*/
payload: function( $transition$: Transition )
{
return Api.sendRequest( '/web/dash/sites/' + $transition$.params().id ); |
d093295d2a63add1bdef03a0388367851a83c687 | modules/interfaces/type-test/helpers/sample-type-map.ts | modules/interfaces/type-test/helpers/sample-type-map.ts | import { GeneralTypeMap } from "../../src";
export interface SampleTypeMap extends GeneralTypeMap {
entities: {
member: { id: string; name: string };
message: {
id: string;
body: string;
};
};
customQueries: {
countMessagesOfMember: {
params: { memberId: string };
result: { count: number };
};
getCurrentVersion: {
result: { version: string };
};
};
customCommands: {
register: { params: { name: string }; result: { ok: 1 } };
};
auths: {
member: {
credentials: { email: string; password: string };
};
};
}
| import { GeneralTypeMap } from "../../src";
export interface SampleTypeMap extends GeneralTypeMap {
entities: {
member: { id: string; name: string };
message: {
id: string;
body: string;
};
};
customQueries: {
countMessagesOfMember: {
params: { memberId: string };
result: { count: number };
};
getCurrentVersion: {
result: { version: string };
};
};
customCommands: {
register: { params: { name: string }; result: { ok: 1 } };
};
auths: {
member: {
credentials: { email: string; password: string };
session: { externalId: string; ttl: number };
};
};
}
| Add test for custom session values | feat(interfaces): Add test for custom session values
| TypeScript | apache-2.0 | phenyl-js/phenyl,phenyl-js/phenyl,phenyl-js/phenyl,phenyl-js/phenyl | ---
+++
@@ -23,6 +23,7 @@
auths: {
member: {
credentials: { email: string; password: string };
+ session: { externalId: string; ttl: number };
};
};
} |
fb4510fdcbc336c801347545ca20534d9a49a065 | app/core/datastore/field/field-name-migrator.ts | app/core/datastore/field/field-name-migrator.ts | import {Document} from 'idai-components-2';
import {migrationMap, subFieldsMigrationMap} from './migration-map';
/**
* @author Thomas Kleinke
*/
export module FieldNameMigrator {
export function migrate(document: Document): Document {
const resource: any = {};
Object.keys(document.resource).forEach((fieldName: string) => {
const newFieldName: string = migrationMap[fieldName] ? migrationMap[fieldName] : fieldName;
let field: any = document.resource[fieldName];
if (Array.isArray(field)) {
if (!field.some(_ => typeof _ === 'string')) {
field = migrateArrayField(field);
}
}
resource[newFieldName] = field;
});
document.resource = resource;
return document;
}
function migrateArrayField(arrayField: any[]): any[] {
const result: any[] = [];
arrayField.forEach(entry => {
result.push(migrateSubFieldNames(entry));
});
return result;
}
function migrateSubFieldNames(object: any): any {
const result: any = {};
Object.keys(object).forEach((fieldName: string) => {
const newFieldName: string = subFieldsMigrationMap[fieldName]
? subFieldsMigrationMap[fieldName]
: fieldName;
result[newFieldName] = object[fieldName];
});
return result;
}
} | import {Document} from 'idai-components-2';
import {migrationMap, subFieldsMigrationMap} from './migration-map';
import {isObject} from 'tsfun';
/**
* @author Thomas Kleinke
*/
export module FieldNameMigrator {
export function migrate(document: Document): Document {
const resource: any = {};
Object.keys(document.resource).forEach((fieldName: string) => {
const newFieldName: string = migrationMap[fieldName] ? migrationMap[fieldName] : fieldName;
let field: any = document.resource[fieldName];
if (Array.isArray(field) && (field.some(isObject))) field = migrateArrayField(field);
resource[newFieldName] = field;
});
document.resource = resource;
return document;
}
function migrateArrayField(arrayField: any[]): any[] {
const result: any[] = [];
arrayField.forEach(entry => {
result.push(migrateSubFieldNames(entry));
});
return result;
}
function migrateSubFieldNames(object: any): any {
const result: any = {};
Object.keys(object).forEach((fieldName: string) => {
const newFieldName: string = subFieldsMigrationMap[fieldName]
? subFieldsMigrationMap[fieldName]
: fieldName;
result[newFieldName] = object[fieldName];
});
return result;
}
} | Change check for contained objects | Change check for contained objects
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -1,5 +1,6 @@
import {Document} from 'idai-components-2';
import {migrationMap, subFieldsMigrationMap} from './migration-map';
+import {isObject} from 'tsfun';
/**
@@ -15,11 +16,7 @@
const newFieldName: string = migrationMap[fieldName] ? migrationMap[fieldName] : fieldName;
let field: any = document.resource[fieldName];
- if (Array.isArray(field)) {
- if (!field.some(_ => typeof _ === 'string')) {
- field = migrateArrayField(field);
- }
- }
+ if (Array.isArray(field) && (field.some(isObject))) field = migrateArrayField(field);
resource[newFieldName] = field;
}); |
b8c3a0cda06ee6033c2ca59cf6ef44d102ace935 | src/services/slack/emoji.service.ts | src/services/slack/emoji.service.ts | import { defaultEmojis } from './default_emoji';
import { SlackClient } from './slack-client';
import * as emojione from 'emojione';
export class EmojiService {
emojiList: { string: string };
defaultEmojis = defaultEmojis;
get allEmojis(): string[] {
return defaultEmojis.concat(Object.keys(this.emojiList));
}
constructor(private client: SlackClient) {
this.initExternalEmojis();
}
async initExternalEmojis(): Promise<void> {
if (!this.emojiList) {
this.emojiList = await this.client.getEmoji();
}
}
convertEmoji(emoji: string): string {
if (this.emojiList && !!this.emojiList[emoji.substr(1, emoji.length - 2)]) {
const image_url = this.emojiList[emoji.substr(1, emoji.length - 2)];
if (image_url.substr(0, 6) === 'alias:') {
return this.convertEmoji(`:${image_url.substr(6)}:`);
} else {
return `<img class="emojione" src="${image_url}" />`;
}
} else if (emoji !== emojione.shortnameToImage(emoji)) {
return emojione.shortnameToImage(emoji);
} else {
return emoji;
}
}
}
| import { defaultEmojis } from './default_emoji';
import { SlackClient } from './slack-client';
import * as emojione from 'emojione';
export class EmojiService {
emojiList: { string: string };
defaultEmojis = defaultEmojis;
get allEmojis(): string[] {
return defaultEmojis.concat(Object.keys(this.emojiList));
}
constructor(private client: SlackClient) {
this.initExternalEmojis();
}
async initExternalEmojis(): Promise<void> {
if (!this.emojiList) {
this.emojiList = await this.client.getEmoji();
}
}
convertEmoji(emoji: string): string {
if (this.emojiList && !!this.emojiList[emoji.substr(1, emoji.length - 2)]) {
const image_url = this.emojiList[emoji.substr(1, emoji.length - 2)];
if (image_url.substr(0, 6) === 'alias:') {
return this.convertEmoji(`:${image_url.substr(6)}:`);
} else {
return `<img class="emojione" title="${emoji.substr(1, emoji.length - 2)}" src="${image_url}" />`;
}
} else if (emoji !== emojione.shortnameToImage(emoji)) {
return emojione.shortnameToImage(emoji);
} else {
return emoji;
}
}
}
| Add title attribute to custom emojis. | Add title attribute to custom emojis.
| TypeScript | mit | mazun/SlackStream,mazun/SlackStream,mazun/ASlack-Stream,mazun/ASlack-Stream,mazun/ASlack-Stream,mazun/SlackStream,mazun/SlackStream,mazun/ASlack-Stream | ---
+++
@@ -27,7 +27,7 @@
if (image_url.substr(0, 6) === 'alias:') {
return this.convertEmoji(`:${image_url.substr(6)}:`);
} else {
- return `<img class="emojione" src="${image_url}" />`;
+ return `<img class="emojione" title="${emoji.substr(1, emoji.length - 2)}" src="${image_url}" />`;
}
} else if (emoji !== emojione.shortnameToImage(emoji)) {
return emojione.shortnameToImage(emoji); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.