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 |
|---|---|---|---|---|---|---|---|---|---|---|
42d0b16fde8eed3cd81a55577187cb4fb1fc09e5 | templates/expo-template-tabs/screens/ModalScreen.tsx | templates/expo-template-tabs/screens/ModalScreen.tsx | import * as React from 'react';
import { StyleSheet } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
export default function ModalScreen() {
return (
<View style={styles.container}>
<Text style={styles.title}>Modal</Text>
<View style={styles.separator} lightColor="#eee" darkColor="rgba(255,255,255,0.1)" />
<EditScreenInfo path="/screens/ModalScreen.tsx" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
separator: {
marginVertical: 30,
height: 1,
width: '80%',
},
});
| import { StatusBar } from 'expo-status-bar';
import * as React from 'react';
import { Platform, StyleSheet } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
export default function ModalScreen() {
return (
<View style={styles.container}>
<Text style={styles.title}>Modal</Text>
<View style={styles.separator} lightColor="#eee" darkColor="rgba(255,255,255,0.1)" />
<EditScreenInfo path="/screens/ModalScreen.tsx" />
{/* Use a light status bar on iOS to account for the black space above the modal */}
<StatusBar style={Platform.OS === 'ios' ? 'light' : 'auto'} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
separator: {
marginVertical: 30,
height: 1,
width: '80%',
},
});
| Add light status bar for modal | [template] Add light status bar for modal
| TypeScript | bsd-3-clause | exponent/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent | ---
+++
@@ -1,5 +1,6 @@
+import { StatusBar } from 'expo-status-bar';
import * as React from 'react';
-import { StyleSheet } from 'react-native';
+import { Platform, StyleSheet } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
@@ -10,6 +11,9 @@
<Text style={styles.title}>Modal</Text>
<View style={styles.separator} lightColor="#eee" darkColor="rgba(255,255,255,0.1)" />
<EditScreenInfo path="/screens/ModalScreen.tsx" />
+
+ {/* Use a light status bar on iOS to account for the black space above the modal */}
+ <StatusBar style={Platform.OS === 'ios' ? 'light' : 'auto'} />
</View>
);
} |
5915b48f6c719a51faf5baae5e7f057d2533b6cd | Web/js/Visibility.ts | Web/js/Visibility.ts |
class Visibility {
private static isHidden: boolean;
static changed = new Signal();
static visible() {
return !Visibility.isHidden;
}
static hidden() {
return Visibility.isHidden;
}
private static _ctor = (() => {
Visibility.isHidden = false;
if (document.addEventListener) {
window.addEventListener('focus', Visibility.onFocus, true);
window.addEventListener('blur', Visibility.onBlur, true);
} else {
document.attachEvent('onfocusin', Visibility.onFocus);
document.attachEvent('onfocusout', Visibility.onBlur);
}
})();
private static onFocus() {
Visibility.isHidden = false;
Visibility.changed.dispatch();
}
private static onBlur() {
Visibility.isHidden = true;
Visibility.changed.dispatch();
}
}
|
class Visibility {
private static isHidden: boolean;
static changed = new Signal();
static visible() {
return !Visibility.isHidden;
}
static hidden() {
return Visibility.isHidden;
}
private static _ctor = (() => {
Visibility.isHidden = false;
if (document.addEventListener) {
window.addEventListener('focus', Visibility.onFocus, true);
window.addEventListener('blur', Visibility.onBlur, true);
} else {
document.attachEvent('onfocusin', Visibility.onFocus);
document.attachEvent('onfocusout', Visibility.onBlur);
}
})();
private static onFocus(e: any) {
var target = e.target || e.srcTarget;
if (target != window)
return;
Visibility.isHidden = false;
Visibility.changed.dispatch();
}
private static onBlur(e: any) {
var target = e.target || e.srcTarget;
if (target != window)
return;
Visibility.isHidden = true;
Visibility.changed.dispatch();
}
}
| Improve visibility reliability, fixes selection issues in IE | Improve visibility reliability, fixes selection issues in IE
| TypeScript | mit | Rohansi/RohBot,arcaneex/hash,arcaneex/hash,Rohansi/RohBot,arcaneex/hash,Rohansi/RohBot,arcaneex/hash,Rohansi/RohBot | ---
+++
@@ -25,12 +25,20 @@
}
})();
- private static onFocus() {
+ private static onFocus(e: any) {
+ var target = e.target || e.srcTarget;
+ if (target != window)
+ return;
+
Visibility.isHidden = false;
Visibility.changed.dispatch();
}
- private static onBlur() {
+ private static onBlur(e: any) {
+ var target = e.target || e.srcTarget;
+ if (target != window)
+ return;
+
Visibility.isHidden = true;
Visibility.changed.dispatch();
} |
57606db7ccb839e063f046527376f45defe50ea7 | src/auth-module/auth-module.state.ts | src/auth-module/auth-module.state.ts | /*
eslint
@typescript-eslint/explicit-function-return-type: 0,
@typescript-eslint/no-explicit-any: 0
*/
export default function setupAuthState({ userService, serverAlias }) {
const state = {
accessToken: null, // The JWT
payload: null, // The JWT payload
entityIdField: 'userId',
responseEntityField: 'user',
isAuthenticatePending: false,
isLogoutPending: false,
errorOnAuthenticate: null,
errorOnLogout: null,
user: null, // For a reactive user object, use the `user` getter.
serverAlias
}
// If a userService string was passed, add a user attribute
if (userService) {
Object.assign(state, { userService })
}
return state
}
| /*
eslint
@typescript-eslint/explicit-function-return-type: 0,
@typescript-eslint/no-explicit-any: 0
*/
export default function setupAuthState({
userService,
serverAlias,
responseEntityField = 'user',
entityIdField = 'userId'
}) {
const state = {
accessToken: null, // The JWT
payload: null, // The JWT payload
entityIdField,
responseEntityField,
isAuthenticatePending: false,
isLogoutPending: false,
errorOnAuthenticate: null,
errorOnLogout: null,
user: null, // For a reactive user object, use the `user` getter.
serverAlias
}
// If a userService string was passed, add a user attribute
if (userService) {
Object.assign(state, { userService })
}
return state
}
| Allow customizing the entityIdField and responseEntityField | Allow customizing the entityIdField and responseEntityField
| TypeScript | mit | feathers-plus/feathers-vuex,feathers-plus/feathers-vuex | ---
+++
@@ -3,12 +3,17 @@
@typescript-eslint/explicit-function-return-type: 0,
@typescript-eslint/no-explicit-any: 0
*/
-export default function setupAuthState({ userService, serverAlias }) {
+export default function setupAuthState({
+ userService,
+ serverAlias,
+ responseEntityField = 'user',
+ entityIdField = 'userId'
+}) {
const state = {
accessToken: null, // The JWT
payload: null, // The JWT payload
- entityIdField: 'userId',
- responseEntityField: 'user',
+ entityIdField,
+ responseEntityField,
isAuthenticatePending: false,
isLogoutPending: false, |
fc1d833490d8cee11e9f271b100690f00bab81c6 | Mechanism/Texture.ts | Mechanism/Texture.ts | class Texture {
source: HTMLImageElement;
constructor(source: HTMLImageElement = undefined) {
this.source = source;
}
static fromImage(url: string): Texture {
const image = new Image();
const texture = new Texture(image);
image.src = url;
return texture;
}
get width(): number {
return this.source.width;
}
get height(): number {
return this.source.height;
}
} | class Texture {
source: HTMLImageElement;
constructor(source: HTMLImageElement = undefined) {
this.source = source;
}
static fromImage(url: string): Texture {
const image = new Image();
const texture = new Texture(image);
image.src = url;
image.onerror = () => { texture.source = undefined };
return texture;
}
get width(): number {
return this.source.width;
}
get height(): number {
return this.source.height;
}
} | Add handling of image loading error. | Add handling of image loading error.
| TypeScript | apache-2.0 | Dia6lo/Mechanism,Dia6lo/Mechanism,Dia6lo/Mechanism | ---
+++
@@ -9,6 +9,7 @@
const image = new Image();
const texture = new Texture(image);
image.src = url;
+ image.onerror = () => { texture.source = undefined };
return texture;
}
|
4c1af878eb19e18f52c911ba30fb11ce9070781e | src/editorManager.ts | src/editorManager.ts | import Atom from './editors/atom'
import SublimeText2 from './editors/sublime-text2'
import SublimeText3 from './editors/sublime-text3'
import Vim from './editors/vim'
export default class EditorManager {
editors: Object
constructor() {
this.editors = {
'Atom': new Atom(),
'SublimeText2': new SublimeText2(),
'SublimeText3': new SublimeText3(),
'Vim': new Vim(),
};
}
}
| import Atom from './editors/atom'
import SublimeText2 from './editors/sublimeText2'
import SublimeText3 from './editors/sublimeText3'
import Vim from './editors/vim'
export default class EditorManager {
editors: Object
constructor() {
this.editors = {
'Atom': new Atom(),
'SublimeText2': new SublimeText2(),
'SublimeText3': new SublimeText3(),
'Vim': new Vim(),
};
}
}
| Update Sublime ts files name to match the current | Update Sublime ts files name to match the current
The name of Sublime Text ts files is not identical with the actual file name, which generate error while running npm run build | TypeScript | bsd-3-clause | wakatime/desktop,wakatime/wakatime-desktop,wakatime/wakatime-desktop,wakatime/desktop,wakatime/desktop | ---
+++
@@ -1,6 +1,6 @@
import Atom from './editors/atom'
-import SublimeText2 from './editors/sublime-text2'
-import SublimeText3 from './editors/sublime-text3'
+import SublimeText2 from './editors/sublimeText2'
+import SublimeText3 from './editors/sublimeText3'
import Vim from './editors/vim'
|
d1e58637ec667b2108964b3d4d847b0c2f91bd6c | PublicApiV1/index.ts | PublicApiV1/index.ts | /**
* Main entrypoint for the public APIs handlers
*/
import { createAzureFunctionHandler } from "azure-function-express";
import * as express from "express";
const app = express();
import * as mongoose from "mongoose";
import { IProfileModel, ProfileModel } from "./models/profile";
import { profileSchema } from "./schemas/profile";
import debugHandler from "./debugHandler";
import { getProfileHandler } from "./profilesApi";
// Use native promises
( mongoose as any ).Promise = global.Promise;
const MONGODB_CONNECTION: string = process.env.CUSTOMCONNSTR_development;
const connection: mongoose.Connection = mongoose.createConnection(
MONGODB_CONNECTION,
{
config: {
autoIndex: false, // do not autoIndex on connect, see http://mongoosejs.com/docs/guide.html#autoIndex
},
},
);
const profileModel = new ProfileModel(connection.model<IProfileModel>("Profile", profileSchema));
app.get("/api/v1/debug", debugHandler);
app.get("/api/v1/profiles/:fiscalcode", getProfileHandler(profileModel));
// app.post("/api/v1/users/:fiscalcode", updateProfileHandler(profileModel));
// Binds the express app to an Azure Function handler
module.exports = createAzureFunctionHandler(app);
| /**
* Main entrypoint for the public APIs handlers
*/
import { createAzureFunctionHandler } from "azure-function-express";
import * as express from "express";
const app = express();
import * as mongoose from "mongoose";
import { IProfileModel, ProfileModel } from "./models/profile";
import { profileSchema } from "./schemas/profile";
import debugHandler from "./debugHandler";
import { getProfileHandler } from "./profilesApi";
// Use native promises
( mongoose as any ).Promise = global.Promise;
const MONGODB_CONNECTION: string = process.env.CUSTOMCONNSTR_development;
const connection: mongoose.Connection = mongoose.createConnection(
MONGODB_CONNECTION,
{
config: {
autoIndex: false, // do not autoIndex on connect, see http://mongoosejs.com/docs/guide.html#autoIndex
},
},
);
const profileModel = new ProfileModel(connection.model<IProfileModel>("Profile", profileSchema));
app.get("/api/v1/debug", debugHandler);
app.post("/api/v1/debug", debugHandler);
app.get("/api/v1/profiles/:fiscalcode", getProfileHandler(profileModel));
// app.post("/api/v1/users/:fiscalcode", updateProfileHandler(profileModel));
// Binds the express app to an Azure Function handler
module.exports = createAzureFunctionHandler(app);
| Allow POST to debug endpoint | Allow POST to debug endpoint
| TypeScript | mit | teamdigitale/digital-citizenship-functions,teamdigitale/digital-citizenship-functions,teamdigitale/digital-citizenship-functions | ---
+++
@@ -30,6 +30,7 @@
const profileModel = new ProfileModel(connection.model<IProfileModel>("Profile", profileSchema));
app.get("/api/v1/debug", debugHandler);
+app.post("/api/v1/debug", debugHandler);
app.get("/api/v1/profiles/:fiscalcode", getProfileHandler(profileModel));
// app.post("/api/v1/users/:fiscalcode", updateProfileHandler(profileModel)); |
025009b50f2b8ad20405e21652c610413411e0ad | src/vs/workbench/parts/terminal/electron-browser/terminalActions.ts | src/vs/workbench/parts/terminal/electron-browser/terminalActions.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {TPromise} from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import {Action} from 'vs/base/common/actions';
import {ITerminalService} from 'vs/workbench/parts/terminal/common/terminal';
export class ToggleTerminalAction extends Action {
public static ID = 'workbench.action.terminal.toggleTerminal';
public static LABEL = nls.localize('toggleTerminal', "Toggle Terminal");
constructor(
id: string, label: string,
@ITerminalService private terminalService: ITerminalService
) {
super(id, label);
}
public run(event?: any): TPromise<any> {
return this.terminalService.show();
}
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {TPromise} from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import {Action} from 'vs/base/common/actions';
import {ITerminalService} from 'vs/workbench/parts/terminal/common/terminal';
export class ToggleTerminalAction extends Action {
public static ID = 'workbench.action.terminal.toggleTerminal';
public static LABEL = nls.localize('toggleTerminal', "Toggle Integrated Terminal");
constructor(
id: string, label: string,
@ITerminalService private terminalService: ITerminalService
) {
super(id, label);
}
public run(event?: any): TPromise<any> {
return this.terminalService.show();
}
} | Add 'Integrated' to toggle terminal action | Add 'Integrated' to toggle terminal action
Fixes #6706
| TypeScript | mit | gagangupt16/vscode,microsoft/vscode,bsmr-x-script/vscode,zyml/vscode,hungys/vscode,Zalastax/vscode,matthewshirley/vscode,ups216/vscode,DustinCampbell/vscode,zyml/vscode,williamcspace/vscode,zyml/vscode,KattMingMing/vscode,stringham/vscode,rishii7/vscode,stringham/vscode,the-ress/vscode,mjbvz/vscode,0xmohit/vscode,jchadwick/vscode,veeramarni/vscode,matthewshirley/vscode,landonepps/vscode,gagangupt16/vscode,KattMingMing/vscode,bsmr-x-script/vscode,landonepps/vscode,mjbvz/vscode,veeramarni/vscode,bsmr-x-script/vscode,microsoft/vscode,eamodio/vscode,joaomoreno/vscode,jchadwick/vscode,jchadwick/vscode,hashhar/vscode,williamcspace/vscode,joaomoreno/vscode,bsmr-x-script/vscode,Krzysztof-Cieslak/vscode,eklavyamirani/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,hungys/vscode,bsmr-x-script/vscode,eamodio/vscode,Zalastax/vscode,cleidigh/vscode,ups216/vscode,radshit/vscode,hoovercj/vscode,DustinCampbell/vscode,jchadwick/vscode,microsoft/vscode,jchadwick/vscode,zyml/vscode,hoovercj/vscode,williamcspace/vscode,Zalastax/vscode,charlespierce/vscode,landonepps/vscode,Microsoft/vscode,hoovercj/vscode,eamodio/vscode,the-ress/vscode,radshit/vscode,veeramarni/vscode,DustinCampbell/vscode,hoovercj/vscode,radshit/vscode,hoovercj/vscode,williamcspace/vscode,KattMingMing/vscode,eklavyamirani/vscode,KattMingMing/vscode,gagangupt16/vscode,matthewshirley/vscode,microsoft/vscode,zyml/vscode,matthewshirley/vscode,DustinCampbell/vscode,bsmr-x-script/vscode,eamodio/vscode,0xmohit/vscode,stringham/vscode,joaomoreno/vscode,jchadwick/vscode,charlespierce/vscode,0xmohit/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,veeramarni/vscode,joaomoreno/vscode,0xmohit/vscode,gagangupt16/vscode,charlespierce/vscode,ups216/vscode,gagangupt16/vscode,hungys/vscode,mjbvz/vscode,zyml/vscode,rishii7/vscode,hungys/vscode,bsmr-x-script/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,veeramarni/vscode,zyml/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,radshit/vscode,matthewshirley/vscode,gagangupt16/vscode,cleidigh/vscode,rishii7/vscode,rishii7/vscode,veeramarni/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,eklavyamirani/vscode,microsoft/vscode,jchadwick/vscode,ups216/vscode,microlv/vscode,veeramarni/vscode,eklavyamirani/vscode,the-ress/vscode,the-ress/vscode,cleidigh/vscode,jchadwick/vscode,bsmr-x-script/vscode,williamcspace/vscode,microsoft/vscode,zyml/vscode,cleidigh/vscode,joaomoreno/vscode,0xmohit/vscode,veeramarni/vscode,KattMingMing/vscode,eamodio/vscode,eklavyamirani/vscode,landonepps/vscode,veeramarni/vscode,microlv/vscode,gagangupt16/vscode,radshit/vscode,stringham/vscode,KattMingMing/vscode,rishii7/vscode,0xmohit/vscode,eamodio/vscode,KattMingMing/vscode,radshit/vscode,cleidigh/vscode,cleidigh/vscode,microsoft/vscode,microlv/vscode,cleidigh/vscode,hungys/vscode,hashhar/vscode,joaomoreno/vscode,hoovercj/vscode,gagangupt16/vscode,Microsoft/vscode,eklavyamirani/vscode,Zalastax/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,DustinCampbell/vscode,eamodio/vscode,stringham/vscode,Krzysztof-Cieslak/vscode,matthewshirley/vscode,joaomoreno/vscode,bsmr-x-script/vscode,zyml/vscode,ups216/vscode,DustinCampbell/vscode,jchadwick/vscode,jchadwick/vscode,0xmohit/vscode,landonepps/vscode,eamodio/vscode,veeramarni/vscode,eklavyamirani/vscode,hoovercj/vscode,eamodio/vscode,microlv/vscode,zyml/vscode,DustinCampbell/vscode,stringham/vscode,Krzysztof-Cieslak/vscode,hungys/vscode,rishii7/vscode,eklavyamirani/vscode,microsoft/vscode,DustinCampbell/vscode,veeramarni/vscode,hashhar/vscode,mjbvz/vscode,microlv/vscode,joaomoreno/vscode,gagangupt16/vscode,landonepps/vscode,DustinCampbell/vscode,cleidigh/vscode,0xmohit/vscode,Zalastax/vscode,the-ress/vscode,radshit/vscode,Zalastax/vscode,williamcspace/vscode,eklavyamirani/vscode,landonepps/vscode,0xmohit/vscode,stringham/vscode,charlespierce/vscode,joaomoreno/vscode,rishii7/vscode,microlv/vscode,zyml/vscode,bsmr-x-script/vscode,KattMingMing/vscode,mjbvz/vscode,ups216/vscode,eamodio/vscode,zyml/vscode,Microsoft/vscode,williamcspace/vscode,eamodio/vscode,mjbvz/vscode,Zalastax/vscode,rishii7/vscode,bsmr-x-script/vscode,hashhar/vscode,hungys/vscode,hoovercj/vscode,ups216/vscode,Krzysztof-Cieslak/vscode,gagangupt16/vscode,Zalastax/vscode,jchadwick/vscode,matthewshirley/vscode,0xmohit/vscode,landonepps/vscode,bsmr-x-script/vscode,hoovercj/vscode,williamcspace/vscode,hungys/vscode,Microsoft/vscode,DustinCampbell/vscode,cleidigh/vscode,gagangupt16/vscode,williamcspace/vscode,matthewshirley/vscode,joaomoreno/vscode,stringham/vscode,landonepps/vscode,mjbvz/vscode,cleidigh/vscode,microsoft/vscode,mjbvz/vscode,hashhar/vscode,landonepps/vscode,jchadwick/vscode,hungys/vscode,microsoft/vscode,williamcspace/vscode,cleidigh/vscode,rishii7/vscode,0xmohit/vscode,ups216/vscode,KattMingMing/vscode,0xmohit/vscode,williamcspace/vscode,charlespierce/vscode,hashhar/vscode,KattMingMing/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,hoovercj/vscode,radshit/vscode,cleidigh/vscode,cleidigh/vscode,KattMingMing/vscode,hashhar/vscode,hungys/vscode,Zalastax/vscode,williamcspace/vscode,ups216/vscode,0xmohit/vscode,gagangupt16/vscode,mjbvz/vscode,the-ress/vscode,hashhar/vscode,joaomoreno/vscode,cleidigh/vscode,cleidigh/vscode,joaomoreno/vscode,williamcspace/vscode,ups216/vscode,veeramarni/vscode,the-ress/vscode,the-ress/vscode,eamodio/vscode,KattMingMing/vscode,eamodio/vscode,Zalastax/vscode,zyml/vscode,microlv/vscode,williamcspace/vscode,veeramarni/vscode,cleidigh/vscode,bsmr-x-script/vscode,gagangupt16/vscode,williamcspace/vscode,rkeithhill/VSCode,KattMingMing/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,matthewshirley/vscode,Microsoft/vscode,stringham/vscode,landonepps/vscode,charlespierce/vscode,charlespierce/vscode,0xmohit/vscode,hoovercj/vscode,microsoft/vscode,bsmr-x-script/vscode,stringham/vscode,radshit/vscode,williamcspace/vscode,joaomoreno/vscode,stringham/vscode,bsmr-x-script/vscode,eklavyamirani/vscode,0xmohit/vscode,Microsoft/vscode,zyml/vscode,matthewshirley/vscode,Microsoft/vscode,hashhar/vscode,microlv/vscode,eklavyamirani/vscode,charlespierce/vscode,radshit/vscode,gagangupt16/vscode,hungys/vscode,Zalastax/vscode,zyml/vscode,jchadwick/vscode,microlv/vscode,hungys/vscode,DustinCampbell/vscode,ups216/vscode,hoovercj/vscode,gagangupt16/vscode,radshit/vscode,hashhar/vscode,gagangupt16/vscode,hungys/vscode,microsoft/vscode,Microsoft/vscode,hoovercj/vscode,Microsoft/vscode,microsoft/vscode,Zalastax/vscode,charlespierce/vscode,DustinCampbell/vscode,radshit/vscode,microlv/vscode,cra0zy/VSCode,Krzysztof-Cieslak/vscode,ups216/vscode,joaomoreno/vscode,Microsoft/vscode,the-ress/vscode,williamcspace/vscode,hashhar/vscode,stringham/vscode,mjbvz/vscode,microlv/vscode,hungys/vscode,veeramarni/vscode,microsoft/vscode,charlespierce/vscode,veeramarni/vscode,hungys/vscode,rishii7/vscode,ups216/vscode,eklavyamirani/vscode,landonepps/vscode,eklavyamirani/vscode,matthewshirley/vscode,eamodio/vscode,eamodio/vscode,rishii7/vscode,stringham/vscode,matthewshirley/vscode,matthewshirley/vscode,mjbvz/vscode,eamodio/vscode,matthewshirley/vscode,veeramarni/vscode,mjbvz/vscode,zyml/vscode,jchadwick/vscode,Microsoft/vscode,hashhar/vscode,charlespierce/vscode,KattMingMing/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,hashhar/vscode,DustinCampbell/vscode,mjbvz/vscode,hashhar/vscode,DustinCampbell/vscode,matthewshirley/vscode,landonepps/vscode,mjbvz/vscode,charlespierce/vscode,ups216/vscode,hoovercj/vscode,hungys/vscode,hashhar/vscode,hashhar/vscode,landonepps/vscode,gagangupt16/vscode,eamodio/vscode,charlespierce/vscode,0xmohit/vscode,ups216/vscode,radshit/vscode,jchadwick/vscode,the-ress/vscode,mjbvz/vscode,jchadwick/vscode,KattMingMing/vscode,charlespierce/vscode,KattMingMing/vscode,microlv/vscode,microlv/vscode,microsoft/vscode,joaomoreno/vscode,Zalastax/vscode,Microsoft/vscode,stringham/vscode,0xmohit/vscode,the-ress/vscode,Microsoft/vscode,eklavyamirani/vscode,stringham/vscode,ups216/vscode,Zalastax/vscode,microsoft/vscode,KattMingMing/vscode,eklavyamirani/vscode,matthewshirley/vscode,radshit/vscode,joaomoreno/vscode,charlespierce/vscode,eklavyamirani/vscode,mjbvz/vscode,rishii7/vscode,charlespierce/vscode,hungys/vscode,DustinCampbell/vscode,zyml/vscode,Zalastax/vscode,mjbvz/vscode,hoovercj/vscode,bsmr-x-script/vscode,joaomoreno/vscode,rishii7/vscode,cleidigh/vscode,charlespierce/vscode,rishii7/vscode,hashhar/vscode,stringham/vscode,radshit/vscode,rishii7/vscode,stringham/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,veeramarni/vscode,the-ress/vscode,rishii7/vscode,the-ress/vscode,matthewshirley/vscode,rishii7/vscode,hoovercj/vscode,microsoft/vscode,radshit/vscode,ups216/vscode,radshit/vscode,the-ress/vscode,microlv/vscode,the-ress/vscode,Zalastax/vscode,jchadwick/vscode,Microsoft/vscode,eklavyamirani/vscode,Microsoft/vscode,landonepps/vscode,microlv/vscode,microlv/vscode,Zalastax/vscode | ---
+++
@@ -11,7 +11,7 @@
export class ToggleTerminalAction extends Action {
public static ID = 'workbench.action.terminal.toggleTerminal';
- public static LABEL = nls.localize('toggleTerminal', "Toggle Terminal");
+ public static LABEL = nls.localize('toggleTerminal', "Toggle Integrated Terminal");
constructor(
id: string, label: string, |
807a7766c99890440b6d96a6f99b1b165a3ee5a0 | packages/lesswrong/components/common/AnalyticsClient.tsx | packages/lesswrong/components/common/AnalyticsClient.tsx | import React, {useCallback, useEffect} from 'react';
import { registerComponent } from '../../lib/vulcan-lib';
import { useMutation, gql } from '@apollo/client';
import { AnalyticsUtil } from '../../lib/analyticsEvents';
import { useCurrentUser } from './withUser';
import { useCookies } from 'react-cookie'
import withErrorBoundary from './withErrorBoundary';
export const AnalyticsClient = () => {
const currentUser = useCurrentUser();
const [cookies] = useCookies(['clientId']);
const query = gql`
mutation analyticsEventMutation($events: [JSON!], $now: Date) {
analyticsEvent(events: $events, now: $now)
}
`;
const [mutate] = useMutation(query, {
ignoreResults: true
});
const flushEvents = useCallback((events) => {
void mutate({
variables: {
events,
now: new Date(),
}
});
}, [mutate]);
const currentUserId = currentUser?._id;
const clientId = cookies.cilentId;
useEffect(() => {
AnalyticsUtil.clientWriteEvents = flushEvents;
AnalyticsUtil.clientContextVars.userId = currentUserId;
AnalyticsUtil.clientContextVars.clientId = clientId;
return function cleanup() {
AnalyticsUtil.clientWriteEvents = null;
}
}, [flushEvents, currentUserId, clientId]);
return <div/>;
}
const AnalyticsClientComponent = registerComponent("AnalyticsClient", AnalyticsClient, {
hocs: [withErrorBoundary]
});
declare global {
interface ComponentTypes {
AnalyticsClient: typeof AnalyticsClientComponent
}
}
| import React, {useCallback, useEffect} from 'react';
import { registerComponent } from '../../lib/vulcan-lib';
import { useMutation, gql } from '@apollo/client';
import { AnalyticsUtil } from '../../lib/analyticsEvents';
import { useCurrentUser } from './withUser';
import { useCookies } from 'react-cookie'
import withErrorBoundary from './withErrorBoundary';
export const AnalyticsClient = () => {
const currentUser = useCurrentUser();
const [cookies] = useCookies(['clientId']);
const query = gql`
mutation analyticsEventMutation($events: [JSON!], $now: Date) {
analyticsEvent(events: $events, now: $now)
}
`;
const [mutate] = useMutation(query, {
ignoreResults: true
});
const flushEvents = useCallback((events) => {
void mutate({
variables: {
events,
now: new Date(),
}
});
}, [mutate]);
const currentUserId = currentUser?._id;
const clientId = cookies.clientId;
useEffect(() => {
AnalyticsUtil.clientWriteEvents = flushEvents;
AnalyticsUtil.clientContextVars.userId = currentUserId;
AnalyticsUtil.clientContextVars.clientId = clientId;
return function cleanup() {
AnalyticsUtil.clientWriteEvents = null;
}
}, [flushEvents, currentUserId, clientId]);
return <div/>;
}
const AnalyticsClientComponent = registerComponent("AnalyticsClient", AnalyticsClient, {
hocs: [withErrorBoundary]
});
declare global {
interface ComponentTypes {
AnalyticsClient: typeof AnalyticsClientComponent
}
}
| Fix missing client IDs in analytics events | Fix missing client IDs in analytics events
| TypeScript | mit | Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2 | ---
+++
@@ -29,7 +29,7 @@
}, [mutate]);
const currentUserId = currentUser?._id;
- const clientId = cookies.cilentId;
+ const clientId = cookies.clientId;
useEffect(() => {
AnalyticsUtil.clientWriteEvents = flushEvents;
AnalyticsUtil.clientContextVars.userId = currentUserId; |
883a5a9f69de89a554c9b3c7936023792e9fe777 | src/app/shared/reducers/app.store.ts | src/app/shared/reducers/app.store.ts | import { Assignment, Class } from "../models";
export interface AppStore {
CURRENT_ASSIGNMENT: Assignment,
CURRENT_CLASS: Class
}
| import { Assignment, Class } from "../models";
export interface AppStore {
CURRENT_ASSIGNMENT: Assignment,
CURRENT_CLASS: Class,
All_CLASSES: Array<Class>
}
| Add all classes property in AppStore interface | Add all classes property in AppStore interface
| TypeScript | mit | bryant-pham/brograder,bryant-pham/brograder,bryant-pham/brograder,bryant-pham/brograder | ---
+++
@@ -2,5 +2,6 @@
export interface AppStore {
CURRENT_ASSIGNMENT: Assignment,
- CURRENT_CLASS: Class
+ CURRENT_CLASS: Class,
+ All_CLASSES: Array<Class>
} |
a6443f83d48b67e2362b5b708109f4bd4472420d | src/components/basics/gif-marker.tsx | src/components/basics/gif-marker.tsx |
import * as React from "react";
import styled from "../styles";
const GifMarkerSpan = styled.span`
position: absolute;
top: 5px;
right: 5px;
background: #333333;
color: rgba(253, 253, 253, 0.74);
font-size: 12px;
padding: 2px 4px;
border-radius: 2px;
font-weight: bold;
opacity: .8;
`;
class GifMarker extends React.PureComponent<void, void> {
render() {
return <GifMarkerSpan>GIF</GifMarkerSpan>
}
}
export default GifMarker;
|
import * as React from "react";
import styled from "../styles";
const GifMarkerSpan = styled.span`
position: absolute;
top: 5px;
right: 5px;
background: #333333;
color: rgba(253, 253, 253, 0.74);
font-size: 12px;
padding: 2px 4px;
border-radius: 2px;
font-weight: bold;
opacity: .8;
`;
class GifMarker extends React.PureComponent<{}, void> {
render() {
return <GifMarkerSpan>GIF</GifMarkerSpan>;
}
}
export default GifMarker;
| Adjust typings of gifmarker so it can actually be used. | Adjust typings of gifmarker so it can actually be used.
| TypeScript | mit | itchio/itch,itchio/itch,itchio/itch,leafo/itchio-app,leafo/itchio-app,itchio/itchio-app,leafo/itchio-app,itchio/itch,itchio/itchio-app,itchio/itch,itchio/itch,itchio/itchio-app | ---
+++
@@ -15,9 +15,9 @@
opacity: .8;
`;
-class GifMarker extends React.PureComponent<void, void> {
+class GifMarker extends React.PureComponent<{}, void> {
render() {
- return <GifMarkerSpan>GIF</GifMarkerSpan>
+ return <GifMarkerSpan>GIF</GifMarkerSpan>;
}
}
|
468801e4ebfe636095d637e3290dcfa74383f9f6 | packages/apputils/src/index.ts | packages/apputils/src/index.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import '../style/index.css';
export * from './clientsession';
export * from './clipboard';
export * from './collapse';
export * from './commandlinker';
export * from './commandpalette';
export * from './dialog';
export * from './domutils';
export * from './hoverbox';
export * from './iframe';
export * from './inputdialog';
export * from './instancetracker';
export * from './mainareawidget';
export * from './printing';
export * from './sanitizer';
export * from './spinner';
export * from './splash';
export * from './styling';
export * from './thememanager';
export * from './toolbar';
export * from './vdom';
export * from './windowresolver';
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import '../style/index.css';
export * from './clientsession';
export * from './clipboard';
export * from './collapse';
export * from './commandlinker';
export * from './commandpalette';
export * from './dialog';
export * from './domutils';
export * from './hoverbox';
export * from './iframe';
export * from './inputdialog';
export * from './instancetracker';
export * from './mainareawidget';
export * from './printing';
export * from './sanitizer';
export * from './spinner';
export * from './splash';
export * from './styling';
export * from './thememanager';
export * from './tokens';
export * from './toolbar';
export * from './vdom';
export * from './windowresolver';
| Fix missing export of IThemeManager token | Fix missing export of IThemeManager token
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -21,6 +21,7 @@
export * from './splash';
export * from './styling';
export * from './thememanager';
+export * from './tokens';
export * from './toolbar';
export * from './vdom';
export * from './windowresolver'; |
9589778597f660d3f1fa78c347186c6d0931dd9a | developer/js/tests/test-punctuation.ts | developer/js/tests/test-punctuation.ts | import LexicalModelCompiler from '../';
import {assert} from 'chai';
import 'mocha';
const path = require('path');
describe('LexicalModelCompiler', function () {
describe('#generateLexicalModelCode', function () {
const MODEL_ID = 'example.qaa.trivial';
const PATH = path.join(__dirname, 'fixtures', MODEL_ID)
it('should compile a trivial word list', function () {
let compiler = new LexicalModelCompiler;
let code = compiler.generateLexicalModelCode(MODEL_ID, {
format: 'trie-1.0',
sources: ['wordlist.tsv']
}, PATH) as string;
assert.doesNotThrow(function evalModelCode() {
eval(code);
}, SyntaxError);
// TODO: Mock LMLayerWorker.loadModel()
// Sanity check: the word list has three total unweighted words, with a
// total weight of 3!
assert.match(code, /\btotalWeight\b["']?:\s*3\b/);
});
})
});
| import LexicalModelCompiler from '../';
import {assert} from 'chai';
import 'mocha';
const path = require('path');
describe('LexicalModelCompiler', function () {
describe('spefifying punctuation', function () {
const MODEL_ID = 'example.qaa.punctuation';
const PATH = path.join(__dirname, 'fixtures', MODEL_ID)
it('should compile a trivial word list', function () {
let compiler = new LexicalModelCompiler;
let code = compiler.generateLexicalModelCode(MODEL_ID, {
format: 'trie-1.0',
sources: ['wordlist.tsv'],
punctuation: {
quotesForKeepSuggestion: [`«`, `»`],
insertAfterWord: " " ,
}
}, PATH) as string;
// Check that the punctuation actually made into the code:
assert.match(code, /«/);
assert.match(code, /»/);
// TODO: more robust assertions?
});
})
});
| Test that the compiler adds the punctuation. | Test that the compiler adds the punctuation.
| TypeScript | apache-2.0 | tavultesoft/keymanweb,tavultesoft/keymanweb | ---
+++
@@ -6,24 +6,25 @@
describe('LexicalModelCompiler', function () {
- describe('#generateLexicalModelCode', function () {
- const MODEL_ID = 'example.qaa.trivial';
+ describe('spefifying punctuation', function () {
+ const MODEL_ID = 'example.qaa.punctuation';
const PATH = path.join(__dirname, 'fixtures', MODEL_ID)
+
it('should compile a trivial word list', function () {
let compiler = new LexicalModelCompiler;
let code = compiler.generateLexicalModelCode(MODEL_ID, {
format: 'trie-1.0',
- sources: ['wordlist.tsv']
+ sources: ['wordlist.tsv'],
+ punctuation: {
+ quotesForKeepSuggestion: [`«`, `»`],
+ insertAfterWord: " " ,
+ }
}, PATH) as string;
- assert.doesNotThrow(function evalModelCode() {
- eval(code);
- }, SyntaxError);
- // TODO: Mock LMLayerWorker.loadModel()
-
- // Sanity check: the word list has three total unweighted words, with a
- // total weight of 3!
- assert.match(code, /\btotalWeight\b["']?:\s*3\b/);
+ // Check that the punctuation actually made into the code:
+ assert.match(code, /«/);
+ assert.match(code, /»/);
+ // TODO: more robust assertions?
});
})
}); |
c47c1c3da508e5e5b5ea3a31417103a3befbbfd3 | transpiler/src/emitter/statements.ts | transpiler/src/emitter/statements.ts | import { ReturnStatement } from 'typescript';
import { Context } from '../contexts';
import { EmitResult, emit } from './';
export const emitReturnStatement = ({ expression }: ReturnStatement, context: Context): EmitResult => {
const emit_result = emit(expression, context);
return {
...emit_result,
emitted_string: `return ${emit_result.emitted_string};`
};
};
| import { ReturnStatement, VariableStatement } from 'typescript';
import { Context } from '../contexts';
import { EmitResult, emit } from './';
export const emitReturnStatement = ({ expression }: ReturnStatement, context: Context): EmitResult => {
const emit_result = emit(expression, context);
return {
...emit_result,
emitted_string: `return ${emit_result.emitted_string};`
};
};
export const emitVariableStatement = ({ declarationList: { declarations } }: VariableStatement, context: Context): EmitResult => {
const emit_result =
declarations
.reduce<EmitResult>(({ context, emitted_string }, node) => {
const result = emit(node, context);
result.emitted_string = emitted_string + ';\n ' + result.emitted_string;
return result;
}, { context, emitted_string: '' });
return {
...emit_result,
emitted_string: `${emit_result.emitted_string};`
};
};
| Add emit for variable statement | Add emit for variable statement
| TypeScript | mit | artfuldev/RIoT | ---
+++
@@ -1,4 +1,4 @@
-import { ReturnStatement } from 'typescript';
+import { ReturnStatement, VariableStatement } from 'typescript';
import { Context } from '../contexts';
import { EmitResult, emit } from './';
@@ -9,3 +9,17 @@
emitted_string: `return ${emit_result.emitted_string};`
};
};
+
+export const emitVariableStatement = ({ declarationList: { declarations } }: VariableStatement, context: Context): EmitResult => {
+ const emit_result =
+ declarations
+ .reduce<EmitResult>(({ context, emitted_string }, node) => {
+ const result = emit(node, context);
+ result.emitted_string = emitted_string + ';\n ' + result.emitted_string;
+ return result;
+ }, { context, emitted_string: '' });
+ return {
+ ...emit_result,
+ emitted_string: `${emit_result.emitted_string};`
+ };
+}; |
f9e273739dc2604db47b3e67578aac3a78c8792e | src/dashboard/login/login.ts | src/dashboard/login/login.ts | namespace DashboardHome {
angular.module("dashboard.login",
[
"auth0",
"ui.router"
])
.config(function myAppConfig($stateProvider) {
$stateProvider
.state("login", {
url: "/login",
templateUrl: "login/login.html",
controller: "LoginCtrl"
});
})
.controller("LoginCtrl", function($scope, auth) {
$scope.signin = function() {
auth.signin({
authParams: {
scope: "openid name email app_metadata" // Specify the scopes you want to retrieve
}
});
};
});
}
| namespace DashboardLogin {
angular.module("dashboard.login",
[
"auth0",
"ui.router"
])
.config(dashboardLoginConfig)
.controller("LoginCtrl", LoginController);
function dashboardLoginConfig($stateProvider) {
$stateProvider
.state("login", {
url: "/login",
templateUrl: "login/login.html",
controller: "LoginCtrl"
});
}
function LoginController($scope, auth) {
$scope.signin = function() {
auth.signin({
authParams: {
scope: "openid name email app_metadata" // Specify the scopes you want to retrieve
}
});
};
}
}
| Move logic out of angular setup | Move logic out of angular setup
| TypeScript | mit | MrHen/hen-auth,MrHen/hen-auth,MrHen/hen-auth | ---
+++
@@ -1,26 +1,30 @@
-namespace DashboardHome {
+namespace DashboardLogin {
angular.module("dashboard.login",
[
"auth0",
"ui.router"
])
- .config(function myAppConfig($stateProvider) {
- $stateProvider
- .state("login", {
- url: "/login",
- templateUrl: "login/login.html",
- controller: "LoginCtrl"
- });
- })
- .controller("LoginCtrl", function($scope, auth) {
+ .config(dashboardLoginConfig)
+ .controller("LoginCtrl", LoginController);
- $scope.signin = function() {
- auth.signin({
- authParams: {
- scope: "openid name email app_metadata" // Specify the scopes you want to retrieve
- }
- });
- };
+ function dashboardLoginConfig($stateProvider) {
+ $stateProvider
+ .state("login", {
+ url: "/login",
+ templateUrl: "login/login.html",
+ controller: "LoginCtrl"
+ });
+ }
- });
+ function LoginController($scope, auth) {
+
+ $scope.signin = function() {
+ auth.signin({
+ authParams: {
+ scope: "openid name email app_metadata" // Specify the scopes you want to retrieve
+ }
+ });
+ };
+
+ }
} |
25659a79343ed5b7805427f697602e193d89ddf9 | packages/examples/src/app/my-module/services/user2.controller.ts | packages/examples/src/app/my-module/services/user2.controller.ts | import { Service } from '@foal/core';
import { Sequelize, SequelizeConnectionService, SequelizeService } from '@foal/sequelize';
@Service()
export class Connection extends SequelizeConnectionService {
constructor() {
super('postgres://postgres:LoicPoullain@localhost:5432/foal_test_db');
}
}
@Service()
export class User2 extends SequelizeService {
constructor(protected connection: Connection) {
super('users', {
firstName: Sequelize.STRING,
lastName: Sequelize.STRING
}, connection);
}
}
| import { Service } from '@foal/core';
import { Sequelize, SequelizeConnectionService, SequelizeService } from '@foal/sequelize';
export interface User {
firstName: string;
lastName: string;
}
@Service()
export class Connection extends SequelizeConnectionService {
constructor() {
super('postgres://postgres:LoicPoullain@localhost:5432/foal_test_db');
}
}
@Service()
export class User2 extends SequelizeService<User> {
constructor(protected connection: Connection) {
super('users', {
firstName: Sequelize.STRING,
lastName: Sequelize.STRING
}, connection);
}
}
| Fix sequelize generic class issue in @foal/examples | Fix sequelize generic class issue in @foal/examples
| TypeScript | mit | FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal | ---
+++
@@ -1,5 +1,10 @@
import { Service } from '@foal/core';
import { Sequelize, SequelizeConnectionService, SequelizeService } from '@foal/sequelize';
+
+export interface User {
+ firstName: string;
+ lastName: string;
+}
@Service()
export class Connection extends SequelizeConnectionService {
@@ -9,7 +14,7 @@
}
@Service()
-export class User2 extends SequelizeService {
+export class User2 extends SequelizeService<User> {
constructor(protected connection: Connection) {
super('users', { |
a1fa3d0be5b14070c35232180da861923306107f | packages/components/containers/referral/rewards/table/ActivityCell.tsx | packages/components/containers/referral/rewards/table/ActivityCell.tsx | import { c } from 'ttag';
import { Referral, ReferralState } from '@proton/shared/lib/interfaces';
interface Props {
referral: Referral;
}
const ActivityCell = ({ referral }: Props) => {
let message: React.ReactNode = null;
switch (referral.State) {
case ReferralState.INVITED:
message = referral.Email
? // translator : We are in a table cell. A user referee has been invited via mail
c('Info').t`Invited via email`
: // translator : We are in a table cell. A user referee has signed up via his referral link
c('Info').t`Signed up via your link`;
break;
case ReferralState.SIGNED_UP:
case ReferralState.TRIAL:
// translator : We are in a table cell. A user referee has signed up
message = c('Info').t`Signed up`;
break;
case ReferralState.COMPLETED:
case ReferralState.REWARDED:
message =
(referral.RewardMonths || 0) === 1
? // translator : We are in a table cell. We inform user that a referred user has paid for a monthly plan
c('Info').t`Paid for a monthly plan`
: // translator : We are in a table cell. We inform user that a referred user has paid for 12months plan
c('Info').t`Paid for a 12 months plan`;
break;
}
return <>{message}</>;
};
export default ActivityCell;
| import { c } from 'ttag';
import { Referral, ReferralState } from '@proton/shared/lib/interfaces';
interface Props {
referral: Referral;
}
const ActivityCell = ({ referral }: Props) => {
let message: React.ReactNode = null;
switch (referral.State) {
case ReferralState.INVITED:
message = referral.Email
? // translator : We are in a table cell. A user referee has been invited via mail
c('Info').t`Invited via email`
: // translator : We are in a table cell. A user referee has signed up via his referral link
c('Info').t`Signed up via your link`;
break;
case ReferralState.SIGNED_UP:
case ReferralState.TRIAL:
// translator : We are in a table cell. A user referee has signed up
message = c('Info').t`Signed up`;
break;
case ReferralState.COMPLETED:
case ReferralState.REWARDED:
message =
(referral.RewardMonths || 0) === 1
? // translator : We are in a table cell. We inform user that a referred user has paid for a monthly plan
c('Info').t`Paid for a monthly plan`
: // translator : We are in a table cell. We inform user that a referred user has paid for 12months plan
c('Info').t`Paid for a ${referral.RewardMonths} months plan`;
break;
}
return <>{message}</>;
};
export default ActivityCell;
| Add dynamic months to actity cell message | Add dynamic months to actity cell message
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -28,7 +28,7 @@
? // translator : We are in a table cell. We inform user that a referred user has paid for a monthly plan
c('Info').t`Paid for a monthly plan`
: // translator : We are in a table cell. We inform user that a referred user has paid for 12months plan
- c('Info').t`Paid for a 12 months plan`;
+ c('Info').t`Paid for a ${referral.RewardMonths} months plan`;
break;
}
|
c923621226e0b5626f00d0bb9d42b7477f321d83 | polygerrit-ui/app/services/flags/flags.ts | polygerrit-ui/app/services/flags/flags.ts | /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* 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 {Finalizable} from '../registry';
export interface FlagsService extends Finalizable {
isEnabled(experimentId: string): boolean;
enabledExperiments: string[];
}
/**
* @desc Experiment ids used in Gerrit.
*/
export enum KnownExperimentId {
NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui',
CHECKS_DEVELOPER = 'UiFeature__checks_developer',
SUBMIT_REQUIREMENTS_UI = 'UiFeature__submit_requirements_ui',
TOPICS_PAGE = 'UiFeature__topics_page',
}
| /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* 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 {Finalizable} from '../registry';
export interface FlagsService extends Finalizable {
isEnabled(experimentId: string): boolean;
enabledExperiments: string[];
}
/**
* @desc Experiment ids used in Gerrit.
*/
export enum KnownExperimentId {
NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui',
CHECKS_DEVELOPER = 'UiFeature__checks_developer',
SUBMIT_REQUIREMENTS_UI = 'UiFeature__submit_requirements_ui',
TOPICS_PAGE = 'UiFeature__topics_page',
CHECK_RESULTS_IN_DIFFS = 'UiFeature__check_results_in_diffs',
}
| Add experiment for showing check results in diffs | Add experiment for showing check results in diffs
Change-Id: If5b657bf2658109c9b0fd69ef9a5b87f5b7e220c
| TypeScript | apache-2.0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit | ---
+++
@@ -30,4 +30,5 @@
CHECKS_DEVELOPER = 'UiFeature__checks_developer',
SUBMIT_REQUIREMENTS_UI = 'UiFeature__submit_requirements_ui',
TOPICS_PAGE = 'UiFeature__topics_page',
+ CHECK_RESULTS_IN_DIFFS = 'UiFeature__check_results_in_diffs',
} |
d6b1a70910906aa2b2ea9004efffe1b456c39a35 | src/LondonTravel.Site/assets/scripts/ts/Swagger.ts | src/LondonTravel.Site/assets/scripts/ts/Swagger.ts | // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
declare var SwaggerUIBundle: any;
declare var SwaggerUIStandalonePreset: any;
function HideTopbarPlugin(): any {
return {
components: {
Topbar: (): any => {
return null;
}
}
};
}
window.onload = () => {
if ("SwaggerUIBundle" in window) {
const url: string = $("link[rel='swagger']").attr("href");
const ui: any = SwaggerUIBundle({
url: url,
dom_id: "#swagger-ui",
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
HideTopbarPlugin
],
layout: "StandaloneLayout",
booleanValues: ["false", "true"],
defaultModelRendering: "schema",
displayRequestDuration: true,
jsonEditor: true,
showRequestHeaders: true,
supportedSubmitMethods: ["get"],
validatorUrl: null,
responseInterceptor: (response: any): any => {
// Delete overly-verbose headers from the UI
delete response.headers["content-security-policy"];
delete response.headers["content-security-policy-report-only"];
delete response.headers["feature-policy"];
}
});
(window as any).ui = ui;
}
};
| // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
declare var SwaggerUIBundle: any;
declare var SwaggerUIStandalonePreset: any;
function HideTopbarPlugin(): any {
return {
components: {
Topbar: (): any => {
return null;
}
}
};
}
window.onload = () => {
if ("SwaggerUIBundle" in window) {
const url: string = $("link[rel='swagger']").attr("href");
const ui: any = SwaggerUIBundle({
url: url,
dom_id: "#swagger-ui",
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
HideTopbarPlugin
],
layout: "StandaloneLayout",
booleanValues: ["false", "true"],
defaultModelRendering: "schema",
displayRequestDuration: true,
jsonEditor: true,
showRequestHeaders: true,
supportedSubmitMethods: ["get"],
tryItOutEnabled: true,
validatorUrl: null,
responseInterceptor: (response: any): any => {
// Delete overly-verbose headers from the UI
delete response.headers["content-security-policy"];
delete response.headers["content-security-policy-report-only"];
delete response.headers["feature-policy"];
}
});
(window as any).ui = ui;
}
};
| Enable Try It Out by default | Enable Try It Out by default
Automatically enable the Try It Out functionality in the OpenAPI pages.
| TypeScript | apache-2.0 | martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site | ---
+++
@@ -36,6 +36,7 @@
jsonEditor: true,
showRequestHeaders: true,
supportedSubmitMethods: ["get"],
+ tryItOutEnabled: true,
validatorUrl: null,
responseInterceptor: (response: any): any => {
// Delete overly-verbose headers from the UI |
5cf588a1b3dbc8cd8e479236e0228bb4044afc37 | src/app/leaflet-button/leaflet-button.component.ts | src/app/leaflet-button/leaflet-button.component.ts | /*!
* Leaflet Button Component
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Component, OnInit, Input, Output, ViewChild, EventEmitter } from '@angular/core';
@Component({
selector: 'app-leaflet-button',
templateUrl: './leaflet-button.component.html',
styleUrls: ['./leaflet-button.component.sass'],
})
export class LeafletButtonComponent implements OnInit {
@Input('control-class') controlClass: string;
@Output() buttonClick: EventEmitter<Event> = new EventEmitter();
@ViewChild('controlwrapper') controlWrapper;
constructor() { }
ngOnInit() {
if (typeof this.controlClass !== 'undefined') {
let split = this.controlClass.split(' ');
// add the class to the content
this.controlWrapper.nativeElement.classList.add(...split);
}
}
onClick(event) {
this.buttonClick.emit(event);
}
}
| /*!
* Leaflet Button Component
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Component, OnInit, Input, Output, ViewChild, EventEmitter } from '@angular/core';
@Component({
selector: 'app-leaflet-button',
templateUrl: './leaflet-button.component.html',
styleUrls: ['./leaflet-button.component.sass'],
})
export class LeafletButtonComponent implements OnInit {
@Input('control-class') controlClass: string;
@Output() buttonClick: EventEmitter<Event> = new EventEmitter();
@ViewChild('controlwrapper') controlWrapper;
constructor() { }
ngOnInit() {
if (typeof this.controlClass !== 'undefined' && this.controlClass !== '') {
let split = this.controlClass.split(' ');
// add the class to the content
this.controlWrapper.nativeElement.classList.add(...split);
}
}
onClick(event) {
this.buttonClick.emit(event);
}
}
| Add check if not empty | Add check if not empty
| TypeScript | mit | ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2 | ---
+++
@@ -20,7 +20,7 @@
constructor() { }
ngOnInit() {
- if (typeof this.controlClass !== 'undefined') {
+ if (typeof this.controlClass !== 'undefined' && this.controlClass !== '') {
let split = this.controlClass.split(' ');
// add the class to the content |
c29ea6e4906c466f550c1bd12d27ceb1f12de10e | packages/react-sequential-id/src/index.ts | packages/react-sequential-id/src/index.ts | import {
Component,
ComponentElement,
createContext,
createElement as r,
Props,
ReactElement,
ReactPortal,
SFCElement,
} from 'react'
import uniqueid = require('uniqueid')
export interface IIdProviderProps {
factory?: () => string
}
export interface ISequentialIdProps {
children?: (id: string) => ReactElement<any> | null
}
export { Component, ComponentElement, ReactPortal, SFCElement }
const IdContext = createContext(createIdFactory())
export function IdProvider(props: IIdProviderProps & Props<{}>) {
const { children, factory = createIdFactory() } = props
return r(IdContext.Provider, { value: factory }, children)
}
function SequentialId(props: ISequentialIdProps) {
const { children = () => null } = props
if (typeof children !== 'function') {
return null
}
return r(IdContext.Consumer, {}, (factory: () => string) =>
children(factory()),
)
}
export function createIdFactory() {
return uniqueid('i')
}
export default SequentialId
| import {
Component,
ComponentElement,
createContext,
createElement as r,
Props,
ReactElement,
ReactPortal,
SFCElement,
} from 'react'
import uniqueid = require('uniqueid')
export interface IIdProviderProps {
factory?: () => string
}
export interface ISequentialIdProps {
children?: (id: string) => ReactElement<any> | null
}
export { Component, ComponentElement, ReactPortal, SFCElement }
const IdContext = createContext(createIdFactory())
export function IdProvider(props: IIdProviderProps & Props<{}>) {
const { children, factory = createIdFactory() } = props
return r(IdContext.Provider, { value: factory }, children)
}
export function SequentialId(props: ISequentialIdProps) {
const { children = () => null } = props
if (typeof children !== 'function') {
return null
}
return r(IdContext.Consumer, {}, (factory: () => string) =>
children(factory()),
)
}
export function createIdFactory() {
return uniqueid('i')
}
export default SequentialId
| Make SequentialId a named export as well as the default export | Make SequentialId a named export as well as the default export
| TypeScript | mit | thirdhand/components,thirdhand/components | ---
+++
@@ -27,7 +27,7 @@
return r(IdContext.Provider, { value: factory }, children)
}
-function SequentialId(props: ISequentialIdProps) {
+export function SequentialId(props: ISequentialIdProps) {
const { children = () => null } = props
if (typeof children !== 'function') {
return null |
ebb8d80d1182319ee49feb3e11f8fe45751b6034 | client/InitiativeList/CombatantRow.tsx | client/InitiativeList/CombatantRow.tsx | import * as React from "react";
import { CombatantState } from "../../common/CombatantState";
export function CombatantRow(props: {
combatantState: CombatantState;
isActive: boolean;
isSelected: boolean;
showIndexLabel: boolean;
}) {
const displayName = props.combatantState.Alias.length
? props.combatantState.Alias
: props.combatantState.StatBlock.Name +
" " +
props.combatantState.IndexLabel;
return (
<span className="combatant">
<span className="combatant__leftsection">
<span className="combatant__name" title={displayName}>
{displayName}
</span>
</span>
</span>
);
}
| import * as React from "react";
import { CombatantState } from "../../common/CombatantState";
export function CombatantRow(props: {
combatantState: CombatantState;
isActive: boolean;
isSelected: boolean;
showIndexLabel: boolean;
}) {
const classNames = ["combatant"];
if (props.isActive) {
classNames.push("active");
}
if (props.isSelected) {
classNames.push("selected");
}
const displayName = props.combatantState.Alias.length
? props.combatantState.Alias
: props.combatantState.StatBlock.Name +
" " +
props.combatantState.IndexLabel;
return (
<span className={classNames.join(" ")}>
<span className="combatant__leftsection">
<span className="combatant__name" title={displayName}>
{displayName}
</span>
</span>
</span>
);
}
| Add active and selected classNames to combatant | Add active and selected classNames to combatant
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -8,13 +8,21 @@
isSelected: boolean;
showIndexLabel: boolean;
}) {
+ const classNames = ["combatant"];
+ if (props.isActive) {
+ classNames.push("active");
+ }
+ if (props.isSelected) {
+ classNames.push("selected");
+ }
+
const displayName = props.combatantState.Alias.length
? props.combatantState.Alias
: props.combatantState.StatBlock.Name +
" " +
props.combatantState.IndexLabel;
return (
- <span className="combatant">
+ <span className={classNames.join(" ")}>
<span className="combatant__leftsection">
<span className="combatant__name" title={displayName}>
{displayName} |
f1a882a5dc8eff0f6efa8f302bfa0ee0beab4800 | capstone-project/src/main/angular-webapp/src/app/mock-http-interceptor.ts | capstone-project/src/main/angular-webapp/src/app/mock-http-interceptor.ts | import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";
import { BlobAction } from "./blob-action";
// Mock the HttpClient's interceptor so that HTTP requests are handled locally and not in the real back end.
@Injectable()
export class MockHttpInterceptor implements HttpInterceptor {
private responseUrl = {
imageUrl: "imageUrl"
}
private responseKey = {
blobKey: "blobKey"
}
constructor() { }
// Handles get / post requests
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method === "GET" && req.url === '/blob-service?blobAction=' + BlobAction.GET_URL) {
return of(new HttpResponse({ status: 200, body: this.responseUrl }));
}
else if (req.method === "POST" && req.url === this.responseUrl.imageUrl) {
return of(new HttpResponse({ status: 200, body: this.responseKey }));
}
next.handle(req);
}
} | import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";
import { BlobAction } from "./blob-action";
// Mock the HttpClient's interceptor so that HTTP requests are handled locally and not in the real back end.
@Injectable()
export class MockHttpInterceptor implements HttpInterceptor {
private static responseUrl = {
imageUrl: "imageUrl"
}
private static responseKey = {
blobKey: "blobKey"
}
constructor() { }
// Handles get / post requests
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method === "GET" && req.url === '/blob-service?blobAction=' + BlobAction.GET_URL) {
return of(new HttpResponse({ status: 200, body: MockHttpInterceptor.responseUrl }));
}
else if (req.method === "POST" && req.url === MockHttpInterceptor.responseUrl.imageUrl) {
return of(new HttpResponse({ status: 200, body: MockHttpInterceptor.responseKey }));
}
next.handle(req);
}
} | Make constants in MockHttpInterceptor static | Make constants in MockHttpInterceptor static
| TypeScript | apache-2.0 | googleinterns/step263-2020,googleinterns/step263-2020,googleinterns/step263-2020,googleinterns/step263-2020 | ---
+++
@@ -7,10 +7,10 @@
@Injectable()
export class MockHttpInterceptor implements HttpInterceptor {
- private responseUrl = {
+ private static responseUrl = {
imageUrl: "imageUrl"
}
- private responseKey = {
+ private static responseKey = {
blobKey: "blobKey"
}
@@ -20,10 +20,10 @@
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method === "GET" && req.url === '/blob-service?blobAction=' + BlobAction.GET_URL) {
- return of(new HttpResponse({ status: 200, body: this.responseUrl }));
+ return of(new HttpResponse({ status: 200, body: MockHttpInterceptor.responseUrl }));
}
- else if (req.method === "POST" && req.url === this.responseUrl.imageUrl) {
- return of(new HttpResponse({ status: 200, body: this.responseKey }));
+ else if (req.method === "POST" && req.url === MockHttpInterceptor.responseUrl.imageUrl) {
+ return of(new HttpResponse({ status: 200, body: MockHttpInterceptor.responseKey }));
}
next.handle(req); |
4a96b42d61c9c08ac649d207557af04c96c990ad | src/app/reuse-strategy.ts | src/app/reuse-strategy.ts | import {
ActivatedRouteSnapshot,
DetachedRouteHandle,
RouteReuseStrategy,
} from '@angular/router';
/* reuse the SearchComponent instead of recreating it */
export class CustomRouteReuseStrategy implements RouteReuseStrategy {
private detachedRouteHandle: DetachedRouteHandle;
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return route.url.length === 0;
}
store(
route: ActivatedRouteSnapshot,
detachedTree: DetachedRouteHandle,
): void {
this.detachedRouteHandle = detachedTree;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!route.routeConfig &&
this.shouldDetach(route) &&
!!this.detachedRouteHandle;
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null {
if (!route.routeConfig) {
return null;
}
return this.detachedRouteHandle;
}
shouldReuseRoute(
future: ActivatedRouteSnapshot,
curr: ActivatedRouteSnapshot,
): boolean {
return false;
}
}
| import {
ActivatedRouteSnapshot,
DetachedRouteHandle,
RouteReuseStrategy,
} from '@angular/router';
/* reuse the SearchComponent instead of recreating it */
export class CustomRouteReuseStrategy implements RouteReuseStrategy {
private detachedRouteHandle: DetachedRouteHandle;
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return route.routeConfig.path === '';
}
store(
route: ActivatedRouteSnapshot,
detachedTree: DetachedRouteHandle,
): void {
if (this.shouldDetach(route)) {
this.detachedRouteHandle = detachedTree;
}
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!route.routeConfig &&
this.shouldDetach(route) &&
!!this.detachedRouteHandle;
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null {
if (!route.routeConfig || !this.shouldDetach(route)) {
return null;
}
return this.detachedRouteHandle;
}
shouldReuseRoute(
future: ActivatedRouteSnapshot,
curr: ActivatedRouteSnapshot,
): boolean {
return false;
}
}
| Fix a bug in RouteReuseStrategy | Fix a bug in RouteReuseStrategy
| TypeScript | mit | ksmai/spotify-clone,ksmai/spotify-clone,ksmai/spotify-clone | ---
+++
@@ -9,14 +9,16 @@
private detachedRouteHandle: DetachedRouteHandle;
shouldDetach(route: ActivatedRouteSnapshot): boolean {
- return route.url.length === 0;
+ return route.routeConfig.path === '';
}
store(
route: ActivatedRouteSnapshot,
detachedTree: DetachedRouteHandle,
): void {
- this.detachedRouteHandle = detachedTree;
+ if (this.shouldDetach(route)) {
+ this.detachedRouteHandle = detachedTree;
+ }
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
@@ -26,7 +28,7 @@
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null {
- if (!route.routeConfig) {
+ if (!route.routeConfig || !this.shouldDetach(route)) {
return null;
}
|
155f428f2debd2729eb0972a2795998095f431bf | front/src/app/shared/base.service.ts | front/src/app/shared/base.service.ts | import { Injectable } from '@angular/core';
import { Error } from './error/error';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { environment } from '../../environments/environment';
@Injectable()
export class BaseService {
private static DEFAULT_ERROR = 'Something went horribly wrong...';
protected extractArray(res: Response) {
let body = res.json();
return body || [];
}
protected extractObject(res: Response) {
let body = res.json();
return body || {};
}
protected extractError(res: Response) {
let error: Error = new Error();
if (res instanceof Response) {
// Extract error message
error.status = res.status
error.message = res.statusText || BaseService.DEFAULT_ERROR;
error.details = res.json().message || '';
} else {
error.message = BaseService.DEFAULT_ERROR;
error.details = res as string || '';
}
return Observable.throw(error);
}
protected buildUrl(endpoint: string): string {
return environment.serverUrl + endpoint;
}
} | import { Injectable } from '@angular/core';
import { Error } from './error/error';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { environment } from '../../environments/environment';
@Injectable()
export class BaseService {
private static DEFAULT_ERROR = 'Something went horribly wrong...';
private static DEFAULT_DETAILS = 'A team of highly trained monkeys has been dispatched to deal with this situation.'
protected extractArray(res: Response) {
let body = res.json();
return body || [];
}
protected extractObject(res: Response) {
let body = res.json();
return body || {};
}
protected extractError(res: Response) {
let error: Error = new Error();
if (res instanceof Response) {
// Extract error message
error.status = res.status
error.message = res.statusText || BaseService.DEFAULT_ERROR;
error.details = res.json().message || BaseService.DEFAULT_DETAILS;
} else {
error.message = BaseService.DEFAULT_ERROR;
error.details = res as string || BaseService.DEFAULT_DETAILS;
}
return Observable.throw(error);
}
protected buildUrl(endpoint: string): string {
return environment.serverUrl + endpoint;
}
} | Use funny default details in error message | Use funny default details in error message
| TypeScript | mit | Crunchy-Torch/coddy,Crunchy-Torch/coddy,Crunchy-Torch/coddy,Crunchy-Torch/coddy,Crunchy-Torch/coddy | ---
+++
@@ -8,6 +8,7 @@
export class BaseService {
private static DEFAULT_ERROR = 'Something went horribly wrong...';
+ private static DEFAULT_DETAILS = 'A team of highly trained monkeys has been dispatched to deal with this situation.'
protected extractArray(res: Response) {
let body = res.json();
@@ -26,10 +27,10 @@
// Extract error message
error.status = res.status
error.message = res.statusText || BaseService.DEFAULT_ERROR;
- error.details = res.json().message || '';
+ error.details = res.json().message || BaseService.DEFAULT_DETAILS;
} else {
error.message = BaseService.DEFAULT_ERROR;
- error.details = res as string || '';
+ error.details = res as string || BaseService.DEFAULT_DETAILS;
}
return Observable.throw(error);
} |
c4971f5d62cc09a3d1d6356822f494697d602776 | projects/angular2-cookie-law/src/lib/angular2-cookie-law.service.ts | projects/angular2-cookie-law/src/lib/angular2-cookie-law.service.ts | /**
* angular2-cookie-law
*
* Copyright 2016-2018, @andreasonny83, All rights reserved.
*
* @author: @andreasonny83 <andreasonny83@gmail.com>
*/
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Angular2CookieLawService {
public seen(cookieName: string = 'cookieLawSeen'): boolean {
const cookies: Array<string> = document.cookie.split(';');
return this.cookieExisits(cookieName, cookies);
}
public storeCookie(cookieName: string, expiration?: number): void {
return this.setCookie(cookieName, expiration);
}
private cookieExisits(name: string, cookies: Array<string>): boolean {
const cookieName = `${name}=`;
return cookies.reduce((prev, curr) =>
prev || curr.trim().search(cookieName) > -1, false);
}
private setCookie(name: string, expiration?: number): void {
const now: Date = new Date();
const exp: Date = new Date(now.getTime() + expiration * 86400000);
const cookieString = encodeURIComponent(name) +
`=true;path=/;expires=${exp.toUTCString()};`;
document.cookie = cookieString;
}
}
| /**
* angular2-cookie-law
*
* Copyright 2016-2018, @andreasonny83, All rights reserved.
*
* @author: @andreasonny83 <andreasonny83@gmail.com>
*/
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class Angular2CookieLawService {
constructor(
@Inject(DOCUMENT) private doc: Document,
@Inject(PLATFORM_ID) private platform: Object
) { }
public seen(cookieName: string = 'cookieLawSeen'): boolean {
let cookies: Array<string> = [];
if (isPlatformBrowser(this.platform)) {
cookies = this.doc.cookie.split(';');
}
return this.cookieExisits(cookieName, cookies);
}
public storeCookie(cookieName: string, expiration?: number): void {
return this.setCookie(cookieName, expiration);
}
private cookieExisits(name: string, cookies: Array<string>): boolean {
const cookieName = `${name}=`;
return cookies.reduce((prev, curr) =>
prev || curr.trim().search(cookieName) > -1, false);
}
private setCookie(name: string, expiration?: number): void {
const now: Date = new Date();
const exp: Date = new Date(now.getTime() + expiration * 86400000);
const cookieString = encodeURIComponent(name) +
`=true;path=/;expires=${exp.toUTCString()};`;
if (isPlatformBrowser(this.platform)) {
this.doc.cookie = cookieString;
}
}
}
| Fix Angular2CookieLawService to be compatible with Angular Universal | Fix Angular2CookieLawService to be compatible with Angular Universal
| TypeScript | mit | andreasonny83/angular2-cookie-law,andreasonny83/angular2-cookie-law,andreasonny83/angular2-cookie-law | ---
+++
@@ -6,14 +6,25 @@
* @author: @andreasonny83 <andreasonny83@gmail.com>
*/
-import { Injectable } from '@angular/core';
+import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
+import { DOCUMENT, isPlatformBrowser } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class Angular2CookieLawService {
+
+ constructor(
+ @Inject(DOCUMENT) private doc: Document,
+ @Inject(PLATFORM_ID) private platform: Object
+ ) { }
+
public seen(cookieName: string = 'cookieLawSeen'): boolean {
- const cookies: Array<string> = document.cookie.split(';');
+ let cookies: Array<string> = [];
+
+ if (isPlatformBrowser(this.platform)) {
+ cookies = this.doc.cookie.split(';');
+ }
return this.cookieExisits(cookieName, cookies);
}
@@ -36,6 +47,8 @@
const cookieString = encodeURIComponent(name) +
`=true;path=/;expires=${exp.toUTCString()};`;
- document.cookie = cookieString;
+ if (isPlatformBrowser(this.platform)) {
+ this.doc.cookie = cookieString;
+ }
}
} |
e85e9cc8c9e340c171c0ad871e635547c883611b | webpack/__test_support__/fake_resource.ts | webpack/__test_support__/fake_resource.ts | import {
Resource as Res,
ResourceName as Name,
SpecialStatus,
TaggedResource
} from "farmbot";
import { generateUuid } from "../resources/util";
let ID_COUNTER = 0;
export function fakeResource<T extends Name,
U extends TaggedResource["body"]>(kind: T, body: U): Res<T, U> {
return {
specialStatus: SpecialStatus.SAVED,
kind,
uuid: generateUuid(ID_COUNTER++, kind),
body
};
}
| import { Resource as Res, TaggedResource } from "farmbot";
import { arrayUnwrap } from "../resources/util";
import { newTaggedResource } from "../sync/actions";
export function fakeResource<T extends TaggedResource>(kind: T["kind"],
body: T["body"]): Res<T["kind"], T["body"]> {
return arrayUnwrap(newTaggedResource(kind, body));
}
| Fix log test. TODO: Huge type errors | Fix log test. TODO: Huge type errors
| TypeScript | mit | RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app | ---
+++
@@ -1,19 +1,8 @@
-import {
- Resource as Res,
- ResourceName as Name,
- SpecialStatus,
- TaggedResource
-} from "farmbot";
-import { generateUuid } from "../resources/util";
+import { Resource as Res, TaggedResource } from "farmbot";
+import { arrayUnwrap } from "../resources/util";
+import { newTaggedResource } from "../sync/actions";
-let ID_COUNTER = 0;
-
-export function fakeResource<T extends Name,
- U extends TaggedResource["body"]>(kind: T, body: U): Res<T, U> {
- return {
- specialStatus: SpecialStatus.SAVED,
- kind,
- uuid: generateUuid(ID_COUNTER++, kind),
- body
- };
+export function fakeResource<T extends TaggedResource>(kind: T["kind"],
+ body: T["body"]): Res<T["kind"], T["body"]> {
+ return arrayUnwrap(newTaggedResource(kind, body));
} |
9a8153718990fbcdbacc4ea62c45b95762933a97 | src/Apps/Artwork/Components/TrustSignals/__stories__/TrustSignals.story.tsx | src/Apps/Artwork/Components/TrustSignals/__stories__/TrustSignals.story.tsx | import { SecurePayment_artwork } from "__generated__/SecurePayment_artwork.graphql"
import React from "react"
import { storiesOf } from "storybook/storiesOf"
import { Section } from "Utils/Section"
import { SecurePayment } from "../SecurePayment"
storiesOf("Apps/Artwork/Components", module).add("Trust Signals", () => {
return (
<Section title="Secure Payment">
<SecurePayment
artwork={
{
is_acquireable: true,
is_offerable: true,
} as SecurePayment_artwork
}
/>
</Section>
)
})
| import { Flex } from "@artsy/palette"
import { AuthenticityCertificate_artwork } from "__generated__/AuthenticityCertificate_artwork.graphql"
import { SecurePayment_artwork } from "__generated__/SecurePayment_artwork.graphql"
import { VerifiedSeller_artwork } from "__generated__/VerifiedSeller_artwork.graphql"
import React from "react"
import { storiesOf } from "storybook/storiesOf"
import { Section } from "Utils/Section"
import { AuthenticityCertificate } from "../AuthenticityCertificate"
import { SecurePayment } from "../SecurePayment"
import { VerifiedSeller } from "../VerifiedSeller"
storiesOf("Apps/Artwork/Components", module).add("Trust Signals", () => {
return (
<>
<Section title="Secure Payment">
<Flex width="100%">
<SecurePayment
artwork={
{
is_acquireable: true,
is_offerable: true,
} as SecurePayment_artwork
}
/>
</Flex>
</Section>
<Section title="Verified Seller">
<Flex width="100%">
<VerifiedSeller
artwork={
{
is_biddable: false,
partner: {
name: "Test gallery",
isVerifiedSeller: true,
},
} as VerifiedSeller_artwork
}
/>
</Flex>
</Section>
<Section title="Authenticity certificate">
<Flex width="100%">
<AuthenticityCertificate
artwork={
{
hasCertificateOfAuthenticity: true,
} as AuthenticityCertificate_artwork
}
/>
</Flex>
</Section>
</>
)
})
| Add sotries for other trust signals | Add sotries for other trust signals
| TypeScript | mit | xtina-starr/reaction,artsy/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction,artsy/reaction-force | ---
+++
@@ -1,20 +1,55 @@
+import { Flex } from "@artsy/palette"
+import { AuthenticityCertificate_artwork } from "__generated__/AuthenticityCertificate_artwork.graphql"
import { SecurePayment_artwork } from "__generated__/SecurePayment_artwork.graphql"
+import { VerifiedSeller_artwork } from "__generated__/VerifiedSeller_artwork.graphql"
import React from "react"
import { storiesOf } from "storybook/storiesOf"
import { Section } from "Utils/Section"
+import { AuthenticityCertificate } from "../AuthenticityCertificate"
import { SecurePayment } from "../SecurePayment"
+import { VerifiedSeller } from "../VerifiedSeller"
storiesOf("Apps/Artwork/Components", module).add("Trust Signals", () => {
return (
- <Section title="Secure Payment">
- <SecurePayment
- artwork={
- {
- is_acquireable: true,
- is_offerable: true,
- } as SecurePayment_artwork
- }
- />
- </Section>
+ <>
+ <Section title="Secure Payment">
+ <Flex width="100%">
+ <SecurePayment
+ artwork={
+ {
+ is_acquireable: true,
+ is_offerable: true,
+ } as SecurePayment_artwork
+ }
+ />
+ </Flex>
+ </Section>
+ <Section title="Verified Seller">
+ <Flex width="100%">
+ <VerifiedSeller
+ artwork={
+ {
+ is_biddable: false,
+ partner: {
+ name: "Test gallery",
+ isVerifiedSeller: true,
+ },
+ } as VerifiedSeller_artwork
+ }
+ />
+ </Flex>
+ </Section>
+ <Section title="Authenticity certificate">
+ <Flex width="100%">
+ <AuthenticityCertificate
+ artwork={
+ {
+ hasCertificateOfAuthenticity: true,
+ } as AuthenticityCertificate_artwork
+ }
+ />
+ </Flex>
+ </Section>
+ </>
)
}) |
96d9393e65ba50198632a39f35bb9293660ebb8d | src/utils/search.ts | src/utils/search.ts | import { SearchResult, TOpticonMap } from '../types';
import { SearchSuccess } from '../actions/search';
export const updateTurkopticon = (data: TOpticonMap) => (
hit: SearchResult
): SearchResult => ({
...hit,
requester: {
...hit.requester,
turkopticon: data.get(hit.requester.id)
}
});
export const rejectInvalidGroupId = (hit: SearchResult) =>
!hit.groupId.startsWith('[Error:');
/**
* Returns true if a search result in a successful search has an entry that
* exists in prevSearchResult.
* @param action
*/
export const resultsThatAppearInBoth = (action: SearchSuccess) => (
prevSearchResult: SearchResult
): boolean => action.data.has(prevSearchResult.groupId);
export const conflictsUpdateOnlyIndexes = (
oldResult: SearchResult,
newResult: SearchResult
): SearchResult => {
return {
...oldResult,
index: newResult.index,
requester: oldResult.requester
};
};
export const conflictsUseOldExpandedProp = (
oldResult: SearchResult,
newResult: SearchResult
): SearchResult => {
return {
...newResult,
expanded: oldResult.expanded,
markedAsRead: oldResult.markedAsRead,
requester: oldResult.requester
};
};
export const markAsRead = (hit: SearchResult): SearchResult => ({
...hit,
markedAsRead: new Date()
});
| import { SearchResult, TOpticonMap } from '../types';
import { SearchSuccess } from '../actions/search';
export const updateTurkopticon = (data: TOpticonMap) => (
hit: SearchResult
): SearchResult => ({
...hit,
requester: {
...hit.requester,
turkopticon: data.get(hit.requester.id)
}
});
export const rejectInvalidGroupId = (hit: SearchResult) =>
!hit.groupId.startsWith('[Error:');
/**
* Returns true if a search result in a successful search has an entry that
* exists in prevSearchResult.
* @param action
*/
export const resultsThatAppearInBoth = (action: SearchSuccess) => (
prevSearchResult: SearchResult
): boolean => action.data.has(prevSearchResult.groupId);
export const conflictsUpdateOnlyIndexes = (
oldResult: SearchResult,
newResult: SearchResult
): SearchResult => ({
...oldResult,
index: newResult.index,
requester: oldResult.requester
});
export const conflictsUseOldExpandedProp = (
oldResult: SearchResult,
newResult: SearchResult
): SearchResult => ({
...newResult,
expanded: oldResult.expanded,
markedAsRead: oldResult.markedAsRead,
requester: oldResult.requester
});
export const markAsRead = (hit: SearchResult): SearchResult => ({
...hit,
markedAsRead: new Date()
});
| Use implicit object return syntax. | Use implicit object return syntax.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -15,9 +15,9 @@
!hit.groupId.startsWith('[Error:');
/**
- * Returns true if a search result in a successful search has an entry that
- * exists in prevSearchResult.
- * @param action
+ * Returns true if a search result in a successful search has an entry that
+ * exists in prevSearchResult.
+ * @param action
*/
export const resultsThatAppearInBoth = (action: SearchSuccess) => (
prevSearchResult: SearchResult
@@ -26,25 +26,21 @@
export const conflictsUpdateOnlyIndexes = (
oldResult: SearchResult,
newResult: SearchResult
-): SearchResult => {
- return {
- ...oldResult,
- index: newResult.index,
- requester: oldResult.requester
- };
-};
+): SearchResult => ({
+ ...oldResult,
+ index: newResult.index,
+ requester: oldResult.requester
+});
export const conflictsUseOldExpandedProp = (
oldResult: SearchResult,
newResult: SearchResult
-): SearchResult => {
- return {
- ...newResult,
- expanded: oldResult.expanded,
- markedAsRead: oldResult.markedAsRead,
- requester: oldResult.requester
- };
-};
+): SearchResult => ({
+ ...newResult,
+ expanded: oldResult.expanded,
+ markedAsRead: oldResult.markedAsRead,
+ requester: oldResult.requester
+});
export const markAsRead = (hit: SearchResult): SearchResult => ({
...hit, |
62d7f8370b73f5c353185eb763cbdae78fdbf73b | src/flutter/daemon_message_handler.ts | src/flutter/daemon_message_handler.ts | import { ExtensionContext, window } from "vscode";
import { getChannel } from "../commands/channels";
import { logError } from "../utils/log";
import { FlutterDaemon } from "./flutter_daemon";
import { LogMessage, ShowMessage } from "./flutter_types";
export function setUpDaemonMessageHandler(context: ExtensionContext, daemon: FlutterDaemon) {
context.subscriptions.push(daemon.registerForDaemonLogMessage((l: LogMessage) => {
const channel = getChannel("Flutter Daemon");
// Don't show, as we get errors from this just when disconnected devices!
// channel.show(true);
channel.appendLine(`[${l.level}] ${l.message}`);
}));
context.subscriptions.push(daemon.registerForDaemonShowMessage((l: ShowMessage) => {
const title = l.title.trim().endsWith(".") ? l.title.trim() : `${l.title.trim()}.`;
const message = `${title} ${l.message}`.trim();
switch (l.level) {
case "info":
window.showInformationMessage(message);
break;
case "warning":
window.showWarningMessage(message);
break;
case "error":
window.showErrorMessage(message);
break;
default:
logError({ message: `Unexpected daemon.showMessage type: ${l.level}` });
}
}));
}
| import { ExtensionContext, window } from "vscode";
import { getChannel } from "../commands/channels";
import { logWarn } from "../utils/log";
import { FlutterDaemon } from "./flutter_daemon";
import { LogMessage, ShowMessage } from "./flutter_types";
export function setUpDaemonMessageHandler(context: ExtensionContext, daemon: FlutterDaemon) {
context.subscriptions.push(daemon.registerForDaemonLogMessage((l: LogMessage) => {
const channel = getChannel("Flutter Daemon");
// Don't show, as we get errors from this just when disconnected devices!
// channel.show(true);
channel.appendLine(`[${l.level}] ${l.message}`);
}));
context.subscriptions.push(daemon.registerForDaemonShowMessage((l: ShowMessage) => {
const title = l.title.trim().endsWith(".") ? l.title.trim() : `${l.title.trim()}.`;
const message = `${title} ${l.message}`.trim();
switch (l.level) {
case "info":
window.showInformationMessage(message);
break;
case "warning":
window.showWarningMessage(message);
break;
case "error":
window.showErrorMessage(message);
break;
default:
logWarn(`Unexpected daemon.showMessage type: ${l.level}`);
}
}));
}
| Fix for log change before rebase | Fix for log change before rebase
| TypeScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -1,6 +1,6 @@
import { ExtensionContext, window } from "vscode";
import { getChannel } from "../commands/channels";
-import { logError } from "../utils/log";
+import { logWarn } from "../utils/log";
import { FlutterDaemon } from "./flutter_daemon";
import { LogMessage, ShowMessage } from "./flutter_types";
@@ -25,7 +25,7 @@
window.showErrorMessage(message);
break;
default:
- logError({ message: `Unexpected daemon.showMessage type: ${l.level}` });
+ logWarn(`Unexpected daemon.showMessage type: ${l.level}`);
}
}));
} |
60866568f29422ca66bd220e9702298f8aefafeb | src/createLocation.ts | src/createLocation.ts | import * as messages from '@cucumber/messages'
export default function createLocation(props: {
line?: number
column?: number
}): messages.Location {
const location: messages.Location = { ...props }
if (location.line === 0) {
location.line = undefined
}
if (location.column === 0) {
location.column = undefined
}
return location
}
| import * as messages from '@cucumber/messages'
export default function createLocation(props: {
line: number
column?: number
}): messages.Location {
return { ...props }
}
| Change schema to make more properties required | Change schema to make more properties required
| TypeScript | mit | cucumber/gherkin-javascript,cucumber/gherkin-javascript | ---
+++
@@ -1,16 +1,8 @@
import * as messages from '@cucumber/messages'
export default function createLocation(props: {
- line?: number
+ line: number
column?: number
}): messages.Location {
- const location: messages.Location = { ...props }
- if (location.line === 0) {
- location.line = undefined
- }
- if (location.column === 0) {
- location.column = undefined
- }
-
- return location
+ return { ...props }
} |
3c4c67365c3857679d21c90c7c0c9de22b85bfd1 | src/emitter/source.ts | src/emitter/source.ts | import { EmitResult, emit } from './';
import { Context } from '../contexts';
import { SourceFile } from 'typescript';
export const emitSourceFile = (node: SourceFile, context): EmitResult =>
node.statements
.reduce((result, node) => {
const emit_result = emit(node, context);
emit_result.emitted_string = result.emitted_string + '\n' + emit_result.emitted_string;
return emit_result;
}, { context, emitted_string: '' });
| import { EmitResult, emit } from './';
import { Context } from '../contexts';
import { SourceFile } from 'typescript';
export const emitSourceFile = (node: SourceFile, context: Context): EmitResult =>
node.statements
.reduce<EmitResult>(({ context, emitted_string }, node) => {
const result = emit(node, context);
result.emitted_string = emitted_string + '\n' + result.emitted_string;
return result;
}, { context, emitted_string: '' });
| Fix issue with context not being updated | Fix issue with context not being updated
| TypeScript | mit | AmnisIO/typewriter,AmnisIO/typewriter,AmnisIO/typewriter | ---
+++
@@ -2,10 +2,10 @@
import { Context } from '../contexts';
import { SourceFile } from 'typescript';
-export const emitSourceFile = (node: SourceFile, context): EmitResult =>
+export const emitSourceFile = (node: SourceFile, context: Context): EmitResult =>
node.statements
- .reduce((result, node) => {
- const emit_result = emit(node, context);
- emit_result.emitted_string = result.emitted_string + '\n' + emit_result.emitted_string;
- return emit_result;
+ .reduce<EmitResult>(({ context, emitted_string }, node) => {
+ const result = emit(node, context);
+ result.emitted_string = emitted_string + '\n' + result.emitted_string;
+ return result;
}, { context, emitted_string: '' }); |
2e0142f8a9afb756c56211c9214880ed48bb6e1f | src/app/bootstrap.ts | src/app/bootstrap.ts | import '../lib/gj-lib-client/utils/polyfills';
import './main.styl';
import { store } from './store/index';
import { router } from './views/index';
import { App } from './app';
import { bootstrapShortkey } from '../lib/gj-lib-client/vue/shortkey';
import { Registry } from '../lib/gj-lib-client/components/registry/registry.service';
import { GamePlayModal } from '../lib/gj-lib-client/components/game/play-modal/play-modal.service';
import { Ads } from '../lib/gj-lib-client/components/ad/ads.service';
import { bootstrapCommon } from '../_common/bootstrap';
const _createApp = bootstrapCommon(App, store, router);
export function createApp() {
return { app: _createApp(), store, router };
}
if (GJ_IS_CLIENT) {
require('./bootstrap-client');
}
Ads.init(router);
GamePlayModal.init({ canMinimize: true });
bootstrapShortkey();
Registry.setConfig('Game', { maxItems: 100 });
Registry.setConfig('User', { maxItems: 50 });
Registry.setConfig('FiresidePost', { maxItems: 50 });
| import { Ads } from '../lib/gj-lib-client/components/ad/ads.service';
import { GamePlayModal } from '../lib/gj-lib-client/components/game/play-modal/play-modal.service';
import { Registry } from '../lib/gj-lib-client/components/registry/registry.service';
import '../lib/gj-lib-client/utils/polyfills';
import { bootstrapShortkey } from '../lib/gj-lib-client/vue/shortkey';
import { bootstrapCommon } from '../_common/bootstrap';
import { App } from './app';
import './main.styl';
import { store } from './store/index';
import { router } from './views/index';
const _createApp = bootstrapCommon(App, store, router);
export function createApp() {
return { app: _createApp(), store, router };
}
if (GJ_IS_CLIENT) {
require('./bootstrap-client');
}
Ads.init(router);
GamePlayModal.init({ canMinimize: true });
bootstrapShortkey();
Registry.setConfig('Game', { maxItems: 100 });
Registry.setConfig('User', { maxItems: 150 });
Registry.setConfig('FiresidePost', { maxItems: 50 });
| Set registry to store more users. | Set registry to store more users.
| TypeScript | mit | gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt | ---
+++
@@ -1,14 +1,13 @@
+import { Ads } from '../lib/gj-lib-client/components/ad/ads.service';
+import { GamePlayModal } from '../lib/gj-lib-client/components/game/play-modal/play-modal.service';
+import { Registry } from '../lib/gj-lib-client/components/registry/registry.service';
import '../lib/gj-lib-client/utils/polyfills';
+import { bootstrapShortkey } from '../lib/gj-lib-client/vue/shortkey';
+import { bootstrapCommon } from '../_common/bootstrap';
+import { App } from './app';
import './main.styl';
-
import { store } from './store/index';
import { router } from './views/index';
-import { App } from './app';
-import { bootstrapShortkey } from '../lib/gj-lib-client/vue/shortkey';
-import { Registry } from '../lib/gj-lib-client/components/registry/registry.service';
-import { GamePlayModal } from '../lib/gj-lib-client/components/game/play-modal/play-modal.service';
-import { Ads } from '../lib/gj-lib-client/components/ad/ads.service';
-import { bootstrapCommon } from '../_common/bootstrap';
const _createApp = bootstrapCommon(App, store, router);
export function createApp() {
@@ -25,5 +24,5 @@
bootstrapShortkey();
Registry.setConfig('Game', { maxItems: 100 });
-Registry.setConfig('User', { maxItems: 50 });
+Registry.setConfig('User', { maxItems: 150 });
Registry.setConfig('FiresidePost', { maxItems: 50 }); |
5afe9ca2752d8f92f099dd2e1c11a76b28a9c1ab | lib/msal-browser/src/event/EventMessage.ts | lib/msal-browser/src/event/EventMessage.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { AuthenticationResult, AuthError, CommonEndSessionRequest } from "@azure/msal-common";
import { EventType } from "./EventType";
import { InteractionType } from "../utils/BrowserConstants";
import { PopupRequest, RedirectRequest, SilentRequest, SsoSilentRequest } from "..";
export type EventMessage = {
eventType: EventType;
interactionType: InteractionType | null;
payload: EventPayload;
error: EventError;
timestamp: number;
};
export type EventPayload = PopupRequest | RedirectRequest | SilentRequest | SsoSilentRequest | CommonEndSessionRequest | AuthenticationResult | null;
export type EventError = AuthError | Error | null;
export type EventCallbackFunction = (message: EventMessage) => void;
| /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { AuthenticationResult, AuthError } from "@azure/msal-common";
import { EventType } from "./EventType";
import { InteractionType } from "../utils/BrowserConstants";
import { PopupRequest, RedirectRequest, SilentRequest, SsoSilentRequest, EndSessionRequest } from "..";
export type EventMessage = {
eventType: EventType;
interactionType: InteractionType | null;
payload: EventPayload;
error: EventError;
timestamp: number;
};
export type EventPayload = PopupRequest | RedirectRequest | SilentRequest | SsoSilentRequest | EndSessionRequest | AuthenticationResult | null;
export type EventError = AuthError | Error | null;
export type EventCallbackFunction = (message: EventMessage) => void;
| Update request type in `angular` | Update request type in `angular`
| TypeScript | mit | AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js | ---
+++
@@ -3,10 +3,10 @@
* Licensed under the MIT License.
*/
-import { AuthenticationResult, AuthError, CommonEndSessionRequest } from "@azure/msal-common";
+import { AuthenticationResult, AuthError } from "@azure/msal-common";
import { EventType } from "./EventType";
import { InteractionType } from "../utils/BrowserConstants";
-import { PopupRequest, RedirectRequest, SilentRequest, SsoSilentRequest } from "..";
+import { PopupRequest, RedirectRequest, SilentRequest, SsoSilentRequest, EndSessionRequest } from "..";
export type EventMessage = {
eventType: EventType;
@@ -16,7 +16,7 @@
timestamp: number;
};
-export type EventPayload = PopupRequest | RedirectRequest | SilentRequest | SsoSilentRequest | CommonEndSessionRequest | AuthenticationResult | null;
+export type EventPayload = PopupRequest | RedirectRequest | SilentRequest | SsoSilentRequest | EndSessionRequest | AuthenticationResult | null;
export type EventError = AuthError | Error | null;
|
d6df1876c805eebc765aa23c73dd1c356ef82531 | lib/core-server/src/utils/output-stats.ts | lib/core-server/src/utils/output-stats.ts | import chalk from 'chalk';
import path from 'path';
import { logger } from '@storybook/node-logger';
import { Stats } from 'webpack';
import fs from 'fs-extra';
export async function outputStats(directory: string, previewStats?: any, managerStats?: any) {
if (previewStats) {
const filePath = await writeStats(directory, 'preview', previewStats as Stats);
logger.info(`=> preview stats written to ${chalk.cyan(filePath)}`);
}
if (managerStats) {
const filePath = await writeStats(directory, 'manager', managerStats as Stats);
logger.info(`=> manager stats written to ${chalk.cyan(filePath)}`);
}
}
export const writeStats = async (directory: string, name: string, stats: Stats) => {
const filePath = path.join(directory, `${name}-stats.json`);
await fs.writeFile(filePath, JSON.stringify(stats.toJson(), null, 2), 'utf8');
return filePath;
};
| import chalk from 'chalk';
import path from 'path';
import { logger } from '@storybook/node-logger';
import { Stats } from 'webpack';
import fs from 'fs-extra';
export async function outputStats(directory: string, previewStats?: any, managerStats?: any) {
if (previewStats) {
const filePath = await writeStats(directory, 'preview', previewStats as Stats);
logger.info(`=> preview stats written to ${chalk.cyan(filePath)}`);
}
if (managerStats) {
const filePath = await writeStats(directory, 'manager', managerStats as Stats);
logger.info(`=> manager stats written to ${chalk.cyan(filePath)}`);
}
}
export const writeStats = async (directory: string, name: string, stats: Stats) => {
const filePath = path.join(directory, `${name}-stats.json`);
await fs.outputFile(filePath, JSON.stringify(stats.toJson(), null, 2), 'utf8');
return filePath;
};
| Create directory for stats files if it doesn't exist | Create directory for stats files if it doesn't exist
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -18,6 +18,6 @@
export const writeStats = async (directory: string, name: string, stats: Stats) => {
const filePath = path.join(directory, `${name}-stats.json`);
- await fs.writeFile(filePath, JSON.stringify(stats.toJson(), null, 2), 'utf8');
+ await fs.outputFile(filePath, JSON.stringify(stats.toJson(), null, 2), 'utf8');
return filePath;
}; |
992a927d5dff73a8b8a4e80647edb7747a060b26 | src/requests/fetchQueue.ts | src/requests/fetchQueue.ts | import { Dispatch } from 'react-redux';
import { Hit, Requester } from '../types';
import { Map } from 'immutable';
import {
HitPageAction,
getHitPageSuccess,
getHitPageFailure
} from '../actions/hits';
import {
TOpticonAction,
fetchTOpticonSuccess,
fetchTOpticonFailure
} from '../actions/turkopticon';
import { batchFetchTOpticon, hitMapToRequesterIdsArray } from '../utils/turkopticon';
export type FetchAction = HitPageAction | TOpticonAction;
export const queryMturkAndTOpticon = (
dispatch: Dispatch<FetchAction>
) => async () => {
/**
* Credit to: https://www.bignerdranch.com/blog/cross-stitching-elegant-concurrency-patterns-for-javascript/
*/
const fetchHits = (async () => {
try {
const hitData = await Promise.resolve(Map<string, Hit>());
hitData.isEmpty()
? dispatch(getHitPageFailure())
: dispatch(getHitPageSuccess(hitData));
return hitData;
} catch (e) {
/**
* Return an empty set on error to simplify function signature.
*/
dispatch(getHitPageFailure());
return Map<string, Hit>();
}
})();
const fetchTopticonData = (async () => {
try {
/**
* We cannot know what to query Turkopticon with until fetchHits resolves.
* After fetchHits resolves we query Turkopticon with the ids of each
* requester returned by fetchHits.
*/
const hits = await fetchHits;
if (hits.isEmpty()) {
/**
* Immediately exit without sending network request
* and return an empty map to simply function signature.
*/
return Map<string, Requester>();
}
const requesterIds = hitMapToRequesterIdsArray(hits);
return await batchFetchTOpticon(requesterIds);
} catch (e) {
dispatch(fetchTOpticonFailure());
return Map<string, Requester>();
}
})();
const topticonData = await fetchTopticonData;
topticonData && !topticonData.isEmpty()
? dispatch(fetchTOpticonSuccess(topticonData))
: dispatch(fetchTOpticonFailure());
};
| import { Dispatch } from 'react-redux';
import { Hit } from '../types';
import { Map } from 'immutable';
import { fetchQueueSuccess, fetchQueueFailure, QueueAction } from '../actions/queue';
export const fetchQueue = (dispatch: Dispatch<QueueAction>) => async () => {
try {
const queueData = await Promise.resolve(Map<string, Hit>());
queueData.isEmpty()
? dispatch(fetchQueueFailure())
: dispatch(fetchQueueSuccess(queueData));
return queueData;
} catch (e) {
dispatch(fetchQueueFailure());
return Map<string, Hit>();
}
};
| Add function to make network requests for fetching a queue page. | Add function to make network requests for fetching a queue page.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -1,67 +1,17 @@
import { Dispatch } from 'react-redux';
-import { Hit, Requester } from '../types';
+import { Hit } from '../types';
import { Map } from 'immutable';
-import {
- HitPageAction,
- getHitPageSuccess,
- getHitPageFailure
-} from '../actions/hits';
-import {
- TOpticonAction,
- fetchTOpticonSuccess,
- fetchTOpticonFailure
-} from '../actions/turkopticon';
-import { batchFetchTOpticon, hitMapToRequesterIdsArray } from '../utils/turkopticon';
+import { fetchQueueSuccess, fetchQueueFailure, QueueAction } from '../actions/queue';
-export type FetchAction = HitPageAction | TOpticonAction;
-
-export const queryMturkAndTOpticon = (
- dispatch: Dispatch<FetchAction>
-) => async () => {
- /**
- * Credit to: https://www.bignerdranch.com/blog/cross-stitching-elegant-concurrency-patterns-for-javascript/
- */
- const fetchHits = (async () => {
- try {
- const hitData = await Promise.resolve(Map<string, Hit>());
- hitData.isEmpty()
- ? dispatch(getHitPageFailure())
- : dispatch(getHitPageSuccess(hitData));
- return hitData;
- } catch (e) {
- /**
- * Return an empty set on error to simplify function signature.
- */
- dispatch(getHitPageFailure());
- return Map<string, Hit>();
- }
- })();
-
- const fetchTopticonData = (async () => {
- try {
- /**
- * We cannot know what to query Turkopticon with until fetchHits resolves.
- * After fetchHits resolves we query Turkopticon with the ids of each
- * requester returned by fetchHits.
- */
- const hits = await fetchHits;
- if (hits.isEmpty()) {
- /**
- * Immediately exit without sending network request
- * and return an empty map to simply function signature.
- */
- return Map<string, Requester>();
- }
- const requesterIds = hitMapToRequesterIdsArray(hits);
- return await batchFetchTOpticon(requesterIds);
- } catch (e) {
- dispatch(fetchTOpticonFailure());
- return Map<string, Requester>();
- }
- })();
-
- const topticonData = await fetchTopticonData;
- topticonData && !topticonData.isEmpty()
- ? dispatch(fetchTOpticonSuccess(topticonData))
- : dispatch(fetchTOpticonFailure());
+export const fetchQueue = (dispatch: Dispatch<QueueAction>) => async () => {
+ try {
+ const queueData = await Promise.resolve(Map<string, Hit>());
+ queueData.isEmpty()
+ ? dispatch(fetchQueueFailure())
+ : dispatch(fetchQueueSuccess(queueData));
+ return queueData;
+ } catch (e) {
+ dispatch(fetchQueueFailure());
+ return Map<string, Hit>();
+ }
}; |
93d5d645d3c2dcf32f2d199d14e0208e9d85a889 | types/async-retry/index.d.ts | types/async-retry/index.d.ts | // Type definitions for async-retry 1.2
// Project: https://github.com/zeit/async-retry#readme
// Definitions by: Albert Wu <https://github.com/albertywu>
// Pablo Rodríguez <https://github.com/MeLlamoPablo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function AsyncRetry<A>(
fn: AsyncRetry.RetryFunction<A>,
opts: AsyncRetry.Options
): Promise<A>;
declare namespace AsyncRetry {
function retry<A>(fn: RetryFunction<A>, opts: Options): Promise<A>;
interface Options {
retries?: number;
factor?: number;
minTimeout?: number;
maxTimeout?: number;
randomize?: boolean;
onRetry?: (e: Error) => any;
}
type RetryFunction<A> = (bail: (e: Error) => A, attempt: number) => A|Promise<A>;
}
export = AsyncRetry;
| // Type definitions for async-retry 1.2
// Project: https://github.com/zeit/async-retry#readme
// Definitions by: Albert Wu <https://github.com/albertywu>
// Pablo Rodríguez <https://github.com/MeLlamoPablo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function AsyncRetry<A>(
fn: AsyncRetry.RetryFunction<A>,
opts: AsyncRetry.Options
): Promise<A>;
declare namespace AsyncRetry {
interface Options {
retries?: number;
factor?: number;
minTimeout?: number;
maxTimeout?: number;
randomize?: boolean;
onRetry?: (e: Error) => any;
}
type RetryFunction<A> = (bail: (e: Error) => A, attempt: number) => A|Promise<A>;
}
export = AsyncRetry;
| Remove retry from the AsyncRetry namespace | Remove retry from the AsyncRetry namespace
| TypeScript | mit | georgemarshall/DefinitelyTyped,one-pieces/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,markogresak/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,rolandzwaga/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,rolandzwaga/DefinitelyTyped,borisyankov/DefinitelyTyped | ---
+++
@@ -10,8 +10,6 @@
): Promise<A>;
declare namespace AsyncRetry {
- function retry<A>(fn: RetryFunction<A>, opts: Options): Promise<A>;
-
interface Options {
retries?: number;
factor?: number; |
9678199ae0909d5ff7c3d82469ea46e8bbce968e | src/pages/home-page/home-page.component.ts | src/pages/home-page/home-page.component.ts | import { Component, OnInit } from '@angular/core';
import { AppService } from '../../shared/app.service';
import { TranslateService } from '@ngx-translate/core';
let readme = require('html-loader!markdown-loader!./../../../README.md');
@Component({
selector: 'home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent implements OnInit {
public title: string;
public readme: string = readme;
constructor(public app: AppService,
public translateService: TranslateService) {
this.title = this.translateService.instant('Home');
}
ngOnInit() {
this.init();
}
init() {
this.app.currentPageName = 'home';
this.app.currentPageTitle = this.title;
}
}
| import { Component, OnInit } from '@angular/core';
import { AppService } from '../../shared/app.service';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent implements OnInit {
public title: string;
public readme: string = '';//require('html-loader!markdown-loader!./../../../README.md');
constructor(public app: AppService,
public translateService: TranslateService) {
this.title = this.translateService.instant('Home');
}
ngOnInit() {
this.init();
}
init() {
this.app.currentPageName = 'home';
this.app.currentPageTitle = this.title;
}
}
| Remove include README.md on home page | fix(home-page): Remove include README.md on home page
| TypeScript | mit | site15/rucken,site15/rucken,rucken/core,site15/rucken,site15/rucken,rucken/core,rucken/core,rucken/core | ---
+++
@@ -1,8 +1,6 @@
import { Component, OnInit } from '@angular/core';
import { AppService } from '../../shared/app.service';
import { TranslateService } from '@ngx-translate/core';
-
-let readme = require('html-loader!markdown-loader!./../../../README.md');
@Component({
selector: 'home-page',
@@ -13,7 +11,7 @@
export class HomePageComponent implements OnInit {
public title: string;
- public readme: string = readme;
+ public readme: string = '';//require('html-loader!markdown-loader!./../../../README.md');
constructor(public app: AppService,
public translateService: TranslateService) {
this.title = this.translateService.instant('Home'); |
f504fd07f880149161a7d20149ad13f9e2ff5d3f | src/Types.ts | src/Types.ts | /**
* Types.ts
* Author: David de Regt
* Copyright: Microsoft 2016
*
* Shared basic types for ReSub.
*/
export type SubscriptionCallbackFunction = { (keys?: string[]): void; }
export type SubscriptionCallbackBuildStateFunction<S> = { (keys?: string[]): S | void; }
export interface StoreSubscription<S> {
store: any; // Should be StoreBase but not a good way to do the interfaces that I could find for that to work...
callbackBuildState?: SubscriptionCallbackBuildStateFunction<S>;
callback?: SubscriptionCallbackFunction;
autoForceUpdate?: boolean;
// If we're subscribing to a specific key of a type, what's the name of the React property that we're subscribing
// against (and detecting changes to)
keyPropertyName?: string;
// To subscribe to a specific key instead of the contents of a property, use this
specificKeyValue?: string|number;
// Allow toggling of subscription based on prop
enablePropertyName?: string;
}
| /**
* Types.ts
* Author: David de Regt
* Copyright: Microsoft 2016
*
* Shared basic types for ReSub.
*/
import { StoreBase } from './StoreBase';
export type SubscriptionCallbackFunction = { (keys?: string[]): void; }
export type SubscriptionCallbackBuildStateFunction<S> = { (keys?: string[]): S | void; }
export interface StoreSubscription<S> {
store: StoreBase;
callbackBuildState?: SubscriptionCallbackBuildStateFunction<S>;
callback?: SubscriptionCallbackFunction;
autoForceUpdate?: boolean;
// If we're subscribing to a specific key of a type, what's the name of the React property that we're subscribing
// against (and detecting changes to)
keyPropertyName?: string;
// To subscribe to a specific key instead of the contents of a property, use this
specificKeyValue?: string|number;
// Allow toggling of subscription based on prop
enablePropertyName?: string;
}
| Update typings on StoreSubscription to properly use StoreBase | Update typings on StoreSubscription to properly use StoreBase
| TypeScript | mit | berickson1/ReSub,berickson1/ReSub,berickson1/ReSub | ---
+++
@@ -6,11 +6,12 @@
* Shared basic types for ReSub.
*/
+import { StoreBase } from './StoreBase';
export type SubscriptionCallbackFunction = { (keys?: string[]): void; }
export type SubscriptionCallbackBuildStateFunction<S> = { (keys?: string[]): S | void; }
export interface StoreSubscription<S> {
- store: any; // Should be StoreBase but not a good way to do the interfaces that I could find for that to work...
+ store: StoreBase;
callbackBuildState?: SubscriptionCallbackBuildStateFunction<S>;
callback?: SubscriptionCallbackFunction;
autoForceUpdate?: boolean; |
ad843c6397a12db25539fea020156ed34c999fb1 | src/app/common/first-letter.pipe.spec.ts | src/app/common/first-letter.pipe.spec.ts | import {FirstLetterPipe} from './first-letter.pipe';
fdescribe('FirstLetterPipe', () => {
it('should return empty string for null', () => {
const pipe = new FirstLetterPipe();
const val = pipe.transform(null);
expect(val).toEqual('');
});
it('should return empty string for undefined', () => {
const pipe = new FirstLetterPipe();
const val = pipe.transform(undefined);
expect(val).toEqual('');
});
it('should return empty string for empty string', () => {
const pipe = new FirstLetterPipe();
const val = pipe.transform('');
expect(val).toEqual('');
});
it('should return first letter for non-empty string', () => {
const pipe = new FirstLetterPipe();
const val = pipe.transform('John Doe');
expect(val).toEqual('J');
});
});
| import {FirstLetterPipe} from './first-letter.pipe';
describe('FirstLetterPipe', () => {
it('should return empty string for null', () => {
const pipe = new FirstLetterPipe();
const val = pipe.transform(null);
expect(val).toEqual('');
});
it('should return empty string for undefined', () => {
const pipe = new FirstLetterPipe();
const val = pipe.transform(undefined);
expect(val).toEqual('');
});
it('should return empty string for empty string', () => {
const pipe = new FirstLetterPipe();
const val = pipe.transform('');
expect(val).toEqual('');
});
it('should return first letter for non-empty string', () => {
const pipe = new FirstLetterPipe();
const val = pipe.transform('John Doe');
expect(val).toEqual('J');
});
});
| Remove focused describe from first letter pipe unit test | app: Remove focused describe from first letter pipe unit test
| TypeScript | mit | lukaszkostrzewa/graphy,lukaszkostrzewa/graphy,lukaszkostrzewa/graphy | ---
+++
@@ -1,6 +1,6 @@
import {FirstLetterPipe} from './first-letter.pipe';
-fdescribe('FirstLetterPipe', () => {
+describe('FirstLetterPipe', () => {
it('should return empty string for null', () => {
const pipe = new FirstLetterPipe();
const val = pipe.transform(null); |
f2f518c4ed1312e96a97529f5e103d7e912f5869 | src/app/paginator/paginator.component.ts | src/app/paginator/paginator.component.ts | import {
Component,
Input,
Output,
EventEmitter,
OnInit,
OnChanges,
SimpleChange
} from '@angular/core';
@Component({
selector: 'mrs-paginator',
template: require('./paginator.component.html'),
styles: [require('./paginator.component.scss')]
})
export class PaginatorComponent implements OnInit, OnChanges {
@Input() pageQuantity: number = 0;
@Input() currentPage: number = 0;
@Output() selectPage: EventEmitter<any>;
pageList: number[];
constructor() {
this.selectPage = new EventEmitter();
}
ngOnInit(): void {
this.setPageList(this.pageQuantity);
}
ngOnChanges(changes: {[propName: string]: SimpleChange}): void {
this.setPageList(changes['pageQuantity'].currentValue);
}
setPageList(pageQuantity): void {
if (pageQuantity && pageQuantity > 1) {
this.pageList = new Array(pageQuantity);
} else {
this.pageList = null;
}
}
select(ev, page): void {
ev.preventDefault();
this.selectPage.emit(page);
}
}
| import {
Component,
Input,
Output,
EventEmitter,
OnInit,
OnChanges,
SimpleChange
} from '@angular/core';
@Component({
selector: 'mrs-paginator',
template: require('./paginator.component.html'),
styles: [require('./paginator.component.scss')]
})
export class PaginatorComponent implements OnInit, OnChanges {
@Input() pageQuantity: number = 0;
@Input() currentPage: number = 0;
@Output() selectPage: EventEmitter<any>;
pageList: number[];
constructor() {
this.selectPage = new EventEmitter();
}
ngOnInit(): void {
this.setPageList(this.pageQuantity);
}
ngOnChanges(changes: {[propName: string]: SimpleChange}): void {
if (changes['pageQuantity']) {
this.setPageList(changes['pageQuantity'].currentValue);
}
}
setPageList(pageQuantity): void {
if (pageQuantity && pageQuantity > 1) {
this.pageList = new Array(pageQuantity);
} else {
this.pageList = null;
}
}
select(ev, page): void {
ev.preventDefault();
this.selectPage.emit(page);
}
}
| Test if object exist before acessing it in paginator onChange | Test if object exist before acessing it in paginator onChange
| TypeScript | mit | SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend | ---
+++
@@ -28,7 +28,9 @@
}
ngOnChanges(changes: {[propName: string]: SimpleChange}): void {
- this.setPageList(changes['pageQuantity'].currentValue);
+ if (changes['pageQuantity']) {
+ this.setPageList(changes['pageQuantity'].currentValue);
+ }
}
setPageList(pageQuantity): void { |
fa95641f88df107abd17d8218272b40888e8535c | src/client/app/common/scripts/get-kao.ts | src/client/app/common/scripts/get-kao.ts | export default () => [
'(=^・・^=)',
'v(\'ω\')v',
'🐡( \'-\' 🐡 )フグパンチ!!!!',
'🖕(´・_・`)🖕'
][Math.floor(Math.random() * 4)];
| const kaos = [
'(=^・・^=)',
'v(\'ω\')v',
'🐡( \'-\' 🐡 )フグパンチ!!!!',
'🖕(´・_・`)🖕',
];
export default () => kaos[Math.floor(Math.random() * kaos.length)];
| Use Array.prototype.length to avoid magic number | Use Array.prototype.length to avoid magic number
| TypeScript | mit | Tosuke/misskey,ha-dai/Misskey,syuilo/Misskey,syuilo/Misskey,Tosuke/misskey,Tosuke/misskey,ha-dai/Misskey,Tosuke/misskey,Tosuke/misskey | ---
+++
@@ -1,6 +1,8 @@
-export default () => [
+const kaos = [
'(=^・・^=)',
'v(\'ω\')v',
'🐡( \'-\' 🐡 )フグパンチ!!!!',
- '🖕(´・_・`)🖕'
-][Math.floor(Math.random() * 4)];
+ '🖕(´・_・`)🖕',
+];
+
+export default () => kaos[Math.floor(Math.random() * kaos.length)]; |
e5f0ee373b66063f9304cd93ae4875aed5346138 | src/index.ts | src/index.ts | import { ConfigService } from './config.service';
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
export * from './log.service';
export function fatoryConfig(isProduction: boolean): ConfigService {
return {
isProduction: isProduction
};
}
@NgModule({
imports: [
CommonModule
],
declarations: [
],
exports: [
]
})
export class LogModule {
static forRoot(isProduction: boolean): ModuleWithProviders {
return {
ngModule: LogModule,
providers: [{ provide: ConfigService, useValue: fatoryConfig(isProduction) }]
};
}
}
| import { ConfigService } from './config.service';
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LogService } from './log.service';
export * from './log.service';
export function fatoryConfig(isProduction: boolean): ConfigService {
return {
isProduction: isProduction
};
}
@NgModule({
imports: [
CommonModule
],
declarations: [
],
exports: [
],
providers: [
LogService
]
})
export class LogModule {
static forRoot(isProduction: boolean): ModuleWithProviders {
return {
ngModule: LogModule,
providers: [{ provide: ConfigService, useValue: fatoryConfig(isProduction) }]
};
}
}
| Fix add LogService to providers | Fix add LogService to providers
| TypeScript | mit | nguyentk90/ngx-log,nguyentk90/ngx-log | ---
+++
@@ -1,6 +1,7 @@
import { ConfigService } from './config.service';
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
+import { LogService } from './log.service';
export * from './log.service';
@@ -19,6 +20,9 @@
],
exports: [
+ ],
+ providers: [
+ LogService
]
})
export class LogModule { |
9da964f019b60880516d549b39849caf23e97a89 | scripts/tslint/typeOperatorSpacingRule.ts | scripts/tslint/typeOperatorSpacingRule.ts | /// <reference path="../../node_modules/tslint/typings/typescriptServices.d.ts" />
/// <reference path="../../node_modules/tslint/lib/tslint.d.ts" />
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "Place spaces around the '|' and '&' type operators";;
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new TypeOperatorSpacingWalker(sourceFile, this.getOptions()));
}
}
class TypeOperatorSpacingWalker extends Lint.RuleWalker {
public visitNode(node: ts.Node) {
if(node.kind === ts.SyntaxKind.UnionType || node.kind === ts.SyntaxKind.IntersectionType) {
let typeNode = <ts.UnionOrIntersectionTypeNode>node;
let expectedStart = typeNode.types[0].end + 2; // space, | or &
for (let i = 1; i < typeNode.types.length; i++) {
if(expectedStart !== typeNode.types[i].pos || typeNode.types[i].getLeadingTriviaWidth() !== 1) {
const failure = this.createFailure(typeNode.types[i].pos, typeNode.types[i].getWidth(), Rule.FAILURE_STRING);
this.addFailure(failure);
}
expectedStart = typeNode.types[i].end + 2;
}
}
super.visitNode(node);
}
}
| /// <reference path="../../node_modules/tslint/typings/typescriptServices.d.ts" />
/// <reference path="../../node_modules/tslint/lib/tslint.d.ts" />
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "Place spaces around the '|' and '&' type operators";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new TypeOperatorSpacingWalker(sourceFile, this.getOptions()));
}
}
class TypeOperatorSpacingWalker extends Lint.RuleWalker {
public visitNode(node: ts.Node) {
if(node.kind === ts.SyntaxKind.UnionType || node.kind === ts.SyntaxKind.IntersectionType) {
let typeNode = <ts.UnionOrIntersectionTypeNode>node;
let expectedStart = typeNode.types[0].end + 2; // space, | or &
for (let i = 1; i < typeNode.types.length; i++) {
if(expectedStart !== typeNode.types[i].pos || typeNode.types[i].getLeadingTriviaWidth() !== 1) {
const failure = this.createFailure(typeNode.types[i].pos, typeNode.types[i].getWidth(), Rule.FAILURE_STRING);
this.addFailure(failure);
}
expectedStart = typeNode.types[i].end + 2;
}
}
super.visitNode(node);
}
}
| Remove extra semicolon (the irony) | Remove extra semicolon (the irony)
| TypeScript | apache-2.0 | weswigham/TypeScript,donaldpipowitch/TypeScript,samuelhorwitz/typescript,alexeagle/TypeScript,vilic/TypeScript,alexeagle/TypeScript,TukekeSoft/TypeScript,donaldpipowitch/TypeScript,fabioparra/TypeScript,mihailik/TypeScript,thr0w/Thr0wScript,blakeembrey/TypeScript,kimamula/TypeScript,basarat/TypeScript,erikmcc/TypeScript,mihailik/TypeScript,nycdotnet/TypeScript,vilic/TypeScript,mmoskal/TypeScript,mmoskal/TypeScript,samuelhorwitz/typescript,donaldpipowitch/TypeScript,ziacik/TypeScript,nycdotnet/TypeScript,minestarks/TypeScript,kitsonk/TypeScript,kimamula/TypeScript,ionux/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,mihailik/TypeScript,DLehenbauer/TypeScript,vilic/TypeScript,nycdotnet/TypeScript,DLehenbauer/TypeScript,jeremyepling/TypeScript,jwbay/TypeScript,synaptek/TypeScript,mmoskal/TypeScript,kpreisser/TypeScript,samuelhorwitz/typescript,nojvek/TypeScript,evgrud/TypeScript,chuckjaz/TypeScript,microsoft/TypeScript,evgrud/TypeScript,vilic/TypeScript,yortus/TypeScript,ionux/TypeScript,fabioparra/TypeScript,microsoft/TypeScript,weswigham/TypeScript,Eyas/TypeScript,minestarks/TypeScript,Eyas/TypeScript,nojvek/TypeScript,kitsonk/TypeScript,RyanCavanaugh/TypeScript,chuckjaz/TypeScript,ziacik/TypeScript,mihailik/TypeScript,weswigham/TypeScript,kpreisser/TypeScript,synaptek/TypeScript,kpreisser/TypeScript,AbubakerB/TypeScript,blakeembrey/TypeScript,evgrud/TypeScript,basarat/TypeScript,alexeagle/TypeScript,kimamula/TypeScript,DLehenbauer/TypeScript,ionux/TypeScript,erikmcc/TypeScript,DLehenbauer/TypeScript,nojvek/TypeScript,fabioparra/TypeScript,erikmcc/TypeScript,plantain-00/TypeScript,TukekeSoft/TypeScript,Eyas/TypeScript,jwbay/TypeScript,ziacik/TypeScript,SaschaNaz/TypeScript,AbubakerB/TypeScript,jeremyepling/TypeScript,blakeembrey/TypeScript,kimamula/TypeScript,jwbay/TypeScript,yortus/TypeScript,Microsoft/TypeScript,thr0w/Thr0wScript,AbubakerB/TypeScript,SaschaNaz/TypeScript,chuckjaz/TypeScript,Microsoft/TypeScript,basarat/TypeScript,mmoskal/TypeScript,Eyas/TypeScript,Microsoft/TypeScript,AbubakerB/TypeScript,ionux/TypeScript,basarat/TypeScript,synaptek/TypeScript,blakeembrey/TypeScript,synaptek/TypeScript,jeremyepling/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,evgrud/TypeScript,chuckjaz/TypeScript,SaschaNaz/TypeScript,samuelhorwitz/typescript,thr0w/Thr0wScript,nojvek/TypeScript,plantain-00/TypeScript,plantain-00/TypeScript,kitsonk/TypeScript,fabioparra/TypeScript,thr0w/Thr0wScript,ziacik/TypeScript,plantain-00/TypeScript,RyanCavanaugh/TypeScript,nycdotnet/TypeScript,jwbay/TypeScript,erikmcc/TypeScript,RyanCavanaugh/TypeScript,yortus/TypeScript,yortus/TypeScript,TukekeSoft/TypeScript | ---
+++
@@ -3,7 +3,7 @@
export class Rule extends Lint.Rules.AbstractRule {
- public static FAILURE_STRING = "Place spaces around the '|' and '&' type operators";;
+ public static FAILURE_STRING = "Place spaces around the '|' and '&' type operators";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new TypeOperatorSpacingWalker(sourceFile, this.getOptions())); |
dfad6c77093888cb596a3e0f288891a764632980 | src/app/components/test.component.ts | src/app/components/test.component.ts | import { Component } from '../infrastructure/component';
export class TestComponent extends Component {
tag(): string {
return 'test';
}
template(): string {
return '<h1>This component is a little test to start the project !</h1>';
}
} | import { Component } from '../infrastructure/component';
import { VirtualDOM } from "../infrastructure/dom";
export class TestComponent extends Component {
tag(): string {
return 'test';
}
template(): VirtualDOM {
return {
tag: 'test',
childs: [{
tag: 'h1',
childs: [
'This component is a little test to start the project !'
]
}, {
tag: 'span',
childs: [
'This is awesome to render a Virtual DOM component !!', {
tag: 'ul',
childs: [{
tag: 'li',
childs: ['test1']
}, {
tag: 'li',
childs: ['test2']
}, {
tag: 'li',
childs: ['test2']
}
]
}
]
}
]
};
}
} | Rewrite template return of TestComponent | Rewrite template return of TestComponent
| TypeScript | mit | Vtek/frameworkless,Vtek/frameworkless,Vtek/frameworkless | ---
+++
@@ -1,10 +1,38 @@
import { Component } from '../infrastructure/component';
+import { VirtualDOM } from "../infrastructure/dom";
export class TestComponent extends Component {
tag(): string {
return 'test';
}
- template(): string {
- return '<h1>This component is a little test to start the project !</h1>';
+ template(): VirtualDOM {
+ return {
+ tag: 'test',
+ childs: [{
+ tag: 'h1',
+ childs: [
+ 'This component is a little test to start the project !'
+ ]
+ }, {
+ tag: 'span',
+ childs: [
+ 'This is awesome to render a Virtual DOM component !!', {
+ tag: 'ul',
+ childs: [{
+ tag: 'li',
+ childs: ['test1']
+ }, {
+ tag: 'li',
+ childs: ['test2']
+ }, {
+ tag: 'li',
+ childs: ['test2']
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ };
}
} |
bd7dc86c1252d4ecb623c5ad5638baf588edc214 | app/services/lastfm.ts | app/services/lastfm.ts | import {Request} from '../libs/request';
let API_ROOT = 'ws.audioscrobbler.com'
let API_VERSION = '2.0'
let API_KEY = '59f553e943f2ea7c9e83f19e113b21b8'
export class LastFMClient {
apiRoot: string
protocol: string = 'http://'
request: Request;
constructor() {
this.request = Request.getInstance()
this.apiRoot = [this.protocol, API_ROOT, API_VERSION].join('/')
}
geEvent(location){
let endpoint = `?method=geo.getevents&location=${location}&api_key=${API_KEY}&format=json`
return this.request.jsonp(this.apiRoot + endpoint)
}
}
| import {Request} from '../libs/request';
let API_ROOT = 'ws.audioscrobbler.com'
let API_VERSION = '2.0'
let API_KEY = '59f553e943f2ea7c9e83f19e113b21b8'
export class LastFMClient {
apiRoot: string
protocol: string = 'http://'
request: Request;
constructor() {
this.request = Request.getInstance()
this.apiRoot = [this.protocol, API_ROOT, API_VERSION].join('/')
}
getEvents(location){
let endpoint = `?method=geo.getevents&location=${location}&api_key=${API_KEY}&format=json`
console.log(endpoint)
return this.request.get(this.apiRoot + endpoint).then(JSON.parse)
}
}
| Use GET request instead of JSONP and parse JSON | Use GET request instead of JSONP and parse JSON
Since LastFM allow CORS Request
| TypeScript | mit | yadomi/lastagram,yadomi/lastagram,yadomi/lastagram | ---
+++
@@ -16,9 +16,10 @@
this.apiRoot = [this.protocol, API_ROOT, API_VERSION].join('/')
}
- geEvent(location){
+ getEvents(location){
let endpoint = `?method=geo.getevents&location=${location}&api_key=${API_KEY}&format=json`
- return this.request.jsonp(this.apiRoot + endpoint)
+ console.log(endpoint)
+ return this.request.get(this.apiRoot + endpoint).then(JSON.parse)
}
} |
432958e814c7af4f5670f134b7a310adf47b44ce | src/parsers/index.ts | src/parsers/index.ts | export type ParserInput = any;
export type ParseFn<T> = (x: ParserInput) => T;
export class ParserError extends Error {
constructor(
public readonly expected: string,
public readonly found: string
) {
super(`Expected ${expected} but found ${found}`);
}
}
export function parse<T>(input: ParserInput, parser: ParseFn<T>): T {
return parser(input);
}
| /**
* A `ParseInput` can be transformed using a `ParseFn`.
*/
export type ParserInput = any;
/**
* A `ParseFn` transforms a `ParseInput` to type `T`. It must throw a `ParseError` if the transformation can not be
* done.
*/
export type ParseFn<T> = (x: ParserInput) => T;
/**
* A `ParseFn` throws a `ParseError` when the `ParseInput` cannot be transformed to the parsers target type.
*/
export class ParserError extends Error {
constructor(
public readonly expected: string,
public readonly found: string
) {
super(`Expected ${expected} but found ${found}`);
}
}
/**
* A quick way to apply a `ParseFn` to a given `ParseInput`.
*/
export function parse<T>(input: ParserInput, parser: ParseFn<T>): T {
return parser(input);
}
| Add Documentation to Parser Types | docs(type): Add Documentation to Parser Types
Give the documentation of ParseInput, ParseFn, ParseError and parse some
love ❤️
| TypeScript | mit | swissmanu/spicery,swissmanu/spicery,swissmanu/spicery | ---
+++
@@ -1,6 +1,17 @@
+/**
+ * A `ParseInput` can be transformed using a `ParseFn`.
+ */
export type ParserInput = any;
+
+/**
+ * A `ParseFn` transforms a `ParseInput` to type `T`. It must throw a `ParseError` if the transformation can not be
+ * done.
+ */
export type ParseFn<T> = (x: ParserInput) => T;
+/**
+ * A `ParseFn` throws a `ParseError` when the `ParseInput` cannot be transformed to the parsers target type.
+ */
export class ParserError extends Error {
constructor(
public readonly expected: string,
@@ -10,6 +21,9 @@
}
}
+/**
+ * A quick way to apply a `ParseFn` to a given `ParseInput`.
+ */
export function parse<T>(input: ParserInput, parser: ParseFn<T>): T {
return parser(input);
} |
d2513fa18a86c3a179b42f046c6e6a0edaf02357 | src/shims/pdfmake.ts | src/shims/pdfmake.ts | import { ENV } from '@waldur/core/services';
// Avoid to re-download the fonts every time pdfmake is used, useful for SPA.
let pdfMakeInstance: any = null;
export async function loadPdfMake() {
if (!pdfMakeInstance) {
const fontFamilies = ENV.fontFamilies;
const pdfMake = (await import(/* webpackChunkName: "pdfmake" */ 'pdfmake/build/pdfmake')).default;
pdfMake.fonts = fontFamilies;
pdfMake.vfs = await loadVfs(fontFamilies);
pdfMakeInstance = pdfMake;
}
return pdfMakeInstance;
}
async function loadVfs(fontFamilies) {
// Load fonts into Virtual File System for pdfkit
const baseURL = 'fonts/';
const vfs = {};
// tslint:disable-next-line: forin
for (const fontFamily in fontFamilies) {
// tslint:disable-next-line: forin
for (const font in fontFamilies[fontFamily]) {
const file = fontFamilies[fontFamily][font];
vfs[file] = await getAsDataURL(baseURL + file);
}
}
return vfs;
}
async function getAsDataURL(url: string): Promise<string> {
// Given the URL load base64-encoded data using fetch and FileReader API.
// Please note that it would not work in older browsers without polyfill
const res = await fetch(url, { method: 'GET' });
const blob = await res.blob();
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
// Strip data URL so that only base64-encoded data is returned
reader.onloadend = () => resolve((reader.result as string).split(',')[1]);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
| import { ENV, $http } from '@waldur/core/services';
// Avoid to re-download the fonts every time pdfmake is used, useful for SPA.
let pdfMakeInstance: any = null;
export async function loadPdfMake() {
if (!pdfMakeInstance) {
const fontFamilies = ENV.fontFamilies;
const pdfMake = (await import(/* webpackChunkName: "pdfmake" */ 'pdfmake/build/pdfmake')).default;
pdfMake.fonts = fontFamilies;
pdfMake.vfs = await loadVfs(fontFamilies);
pdfMakeInstance = pdfMake;
}
return pdfMakeInstance;
}
async function loadVfs(fontFamilies) {
// Load fonts into Virtual File System for pdfkit
const baseURL = 'fonts/';
const vfs = {};
// tslint:disable-next-line: forin
for (const fontFamily in fontFamilies) {
// tslint:disable-next-line: forin
for (const font in fontFamilies[fontFamily]) {
const file = fontFamilies[fontFamily][font];
const response = await $http.get(baseURL + file, {responseType: 'arraybuffer'});
vfs[file] = response.data;
}
}
return vfs;
}
| Use AngularJS $http service instead of WHATWG fetch for compatibility with IE 10 | Use AngularJS $http service instead of WHATWG fetch for compatibility with IE 10 [WAL-2273]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -1,4 +1,4 @@
-import { ENV } from '@waldur/core/services';
+import { ENV, $http } from '@waldur/core/services';
// Avoid to re-download the fonts every time pdfmake is used, useful for SPA.
let pdfMakeInstance: any = null;
@@ -24,22 +24,9 @@
// tslint:disable-next-line: forin
for (const font in fontFamilies[fontFamily]) {
const file = fontFamilies[fontFamily][font];
- vfs[file] = await getAsDataURL(baseURL + file);
+ const response = await $http.get(baseURL + file, {responseType: 'arraybuffer'});
+ vfs[file] = response.data;
}
}
return vfs;
}
-
-async function getAsDataURL(url: string): Promise<string> {
- // Given the URL load base64-encoded data using fetch and FileReader API.
- // Please note that it would not work in older browsers without polyfill
- const res = await fetch(url, { method: 'GET' });
- const blob = await res.blob();
- return new Promise<string>((resolve, reject) => {
- const reader = new FileReader();
- // Strip data URL so that only base64-encoded data is returned
- reader.onloadend = () => resolve((reader.result as string).split(',')[1]);
- reader.onerror = reject;
- reader.readAsDataURL(blob);
- });
-} |
0255f2827d1e9b4de4aeef9b1ab9aaffa55b1ee1 | src/app/auth/auth.service.ts | src/app/auth/auth.service.ts | namespace Core {
const DEFAULT_USER: string = 'public';
/**
* @deprecated TODO Temporal type alias to avoid breaking existing code
*/
export type UserDetails = AuthService;
/**
* UserDetails service that represents user credentials and login/logout actions.
*/
export class AuthService {
username: string = DEFAULT_USER;
password: string = null;
token: string = null;
constructor(
private postLoginTasks: Tasks,
private preLogoutTasks: Tasks,
private postLogoutTasks: Tasks,
private localStorage: Storage) {
'ngInject';
}
/**
* Log in as a specific user.
*/
login(username: string, password: string, token?: string): void {
this.username = username;
this.password = password;
if (token) {
this.token = token;
}
this.postLoginTasks.execute(() => {
log.info('Logged in as', this.username);
});
}
/**
* Log out the current user.
*/
logout(): void {
this.preLogoutTasks.execute(() => {
let username = this.username;
this.clear();
this.postLogoutTasks.execute(() => {
log.info('Logged out:', username);
});
});
}
private clear(): void {
this.username = DEFAULT_USER;
this.password = null;
this.token = null;
}
}
}
| namespace Core {
const DEFAULT_USER: string = 'public';
/**
* @deprecated TODO Temporal type alias to avoid breaking existing code
*/
export type UserDetails = AuthService;
/**
* UserDetails service that represents user credentials and login/logout actions.
*/
export class AuthService {
private _username: string = DEFAULT_USER;
private _password: string = null;
private _token: string = null;
private _loggedIn: boolean = false;
constructor(
private postLoginTasks: Tasks,
private preLogoutTasks: Tasks,
private postLogoutTasks: Tasks,
private localStorage: Storage) {
'ngInject';
}
/**
* Log in as a specific user.
*/
login(username: string, password: string, token?: string): void {
this._username = username;
this._password = password;
if (token) {
this._token = token;
}
this.postLoginTasks.execute(() => {
log.info('Logged in as', this._username);
this._loggedIn = true;
});
}
/**
* Log out the current user.
*/
logout(): void {
this.preLogoutTasks.execute(() => {
let username = this._username;
this.clear();
this.postLogoutTasks.execute(() => {
log.info('Logged out:', username);
});
});
}
private clear(): void {
this._username = DEFAULT_USER;
this._password = null;
this._token = null;
this._loggedIn = false;
}
get username(): string {
return this._username;
}
get password(): string {
return this._password;
}
get token(): string {
return this._token;
}
get loggedIn(): boolean {
return this._loggedIn;
}
}
}
| Add loggedIn property and expose only getters for AuthService | Add loggedIn property and expose only getters for AuthService
| TypeScript | apache-2.0 | hawtio/hawtio-core,hawtio/hawtio-core,hawtio/hawtio-core | ---
+++
@@ -12,9 +12,10 @@
*/
export class AuthService {
- username: string = DEFAULT_USER;
- password: string = null;
- token: string = null;
+ private _username: string = DEFAULT_USER;
+ private _password: string = null;
+ private _token: string = null;
+ private _loggedIn: boolean = false;
constructor(
private postLoginTasks: Tasks,
@@ -28,13 +29,14 @@
* Log in as a specific user.
*/
login(username: string, password: string, token?: string): void {
- this.username = username;
- this.password = password;
+ this._username = username;
+ this._password = password;
if (token) {
- this.token = token;
+ this._token = token;
}
this.postLoginTasks.execute(() => {
- log.info('Logged in as', this.username);
+ log.info('Logged in as', this._username);
+ this._loggedIn = true;
});
}
@@ -43,7 +45,7 @@
*/
logout(): void {
this.preLogoutTasks.execute(() => {
- let username = this.username;
+ let username = this._username;
this.clear();
this.postLogoutTasks.execute(() => {
log.info('Logged out:', username);
@@ -52,9 +54,26 @@
}
private clear(): void {
- this.username = DEFAULT_USER;
- this.password = null;
- this.token = null;
+ this._username = DEFAULT_USER;
+ this._password = null;
+ this._token = null;
+ this._loggedIn = false;
+ }
+
+ get username(): string {
+ return this._username;
+ }
+
+ get password(): string {
+ return this._password;
+ }
+
+ get token(): string {
+ return this._token;
+ }
+
+ get loggedIn(): boolean {
+ return this._loggedIn;
}
}
|
11542041993730cb75e652fd66980406ccc7592e | src/utils/hitItem.ts | src/utils/hitItem.ts | import { SearchItem, Requester } from '../types';
import { generateBadges } from './badges';
import { truncate } from './formatting';
type ExceptionStatus = 'neutral' | 'warning' | 'critical';
export interface ExceptionDescriptor {
status?: ExceptionStatus;
title?: string;
description?: string;
}
const generateExceptions = (groupId: string): ExceptionDescriptor[] => {
return groupId.startsWith('[Error:groupId]-')
? [ { status: 'warning', title: 'You are not qualified.' } ]
: [];
};
export const generateItemProps = (hit: SearchItem, requester: Requester | undefined) => {
const { requesterName, groupId, title } = hit;
const actions = [
// {
// icon: 'view',
// external: true,
// url: `https://www.mturk.com/mturk/preview?groupId=${groupId}`
// },
{
primary: true,
external: true,
content: 'Accept',
accessibilityLabel: 'Accept',
icon: 'add',
url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}`
}
];
return {
attributeOne: truncate(requesterName, 40),
attributeTwo: truncate(title, 80),
badges: generateBadges(requester),
actions,
exceptions: generateExceptions(groupId)
};
};
| import { Props as ItemProps } from '@shopify/polaris/types/components/ResourceList/Item';
import { SearchItem, Requester } from '../types';
import { generateBadges } from './badges';
import { truncate } from './formatting';
type ExceptionStatus = 'neutral' | 'warning' | 'critical';
export interface ExceptionDescriptor {
status?: ExceptionStatus;
title?: string;
description?: string;
}
const generateExceptions = (groupId: string): ExceptionDescriptor[] => {
return groupId.startsWith('[Error:groupId]-')
? [ { status: 'warning', title: 'You are not qualified.' } ]
: [];
};
export const generateItemProps = (
hit: SearchItem,
requester: Requester | undefined
): ItemProps => {
const { requesterName, groupId, title } = hit;
const actions = [
// {
// icon: 'view',
// external: true,
// url: `https://www.mturk.com/mturk/preview?groupId=${groupId}`
// },
{
primary: true,
external: true,
content: 'Accept',
accessibilityLabel: 'Accept',
icon: 'add',
url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}`
}
];
return {
attributeOne: truncate(requesterName, 40),
attributeTwo: truncate(title, 80),
badges: generateBadges(requester),
actions,
exceptions: generateExceptions(groupId)
};
};
| Add stricter type checking to generateItemProps | Add stricter type checking to generateItemProps
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -1,3 +1,4 @@
+import { Props as ItemProps } from '@shopify/polaris/types/components/ResourceList/Item';
import { SearchItem, Requester } from '../types';
import { generateBadges } from './badges';
import { truncate } from './formatting';
@@ -15,7 +16,10 @@
: [];
};
-export const generateItemProps = (hit: SearchItem, requester: Requester | undefined) => {
+export const generateItemProps = (
+ hit: SearchItem,
+ requester: Requester | undefined
+): ItemProps => {
const { requesterName, groupId, title } = hit;
const actions = [ |
1dd399dbaed510088c4ddf9bcf0e5235e7ec9b80 | chrome-extension/src/index.ts | chrome-extension/src/index.ts | import * as firebase from "firebase";
import * as url from "url";
const config = require("../config.json");
firebase.initializeApp({
apiKey: config.firebase.apiKey,
authDomain: `${config.firebase.projectId}.firebaseapp.com`,
});
async function getCurrentTabUrl(): Promise<string> {
return await new Promise((resolve) =>
chrome.tabs.query(
{ active: true, currentWindow: true },
(tabs) => resolve(tabs[0].url))) as string;
}
document.addEventListener("DOMContentLoaded", async () => {
const button = document.getElementById("sign-in-button") as HTMLButtonElement;
const message = document.getElementById("message");
button.addEventListener("click", async () =>
await firebase.auth().signInWithPopup(new firebase.auth.GithubAuthProvider()));
firebase.auth().onAuthStateChanged((user) => {
if (user === null) {
button.style.display = "initial";
message.style.display = "none";
} else {
button.style.display = "none";
message.style.display = "initial";
message.appendChild(document.createTextNode("Signed in!"));
setTimeout(() => window.close(), 5000);
}
});
});
| import * as firebase from "firebase";
import * as url from "url";
const config = require("../config.json");
firebase.initializeApp({
apiKey: config.firebase.apiKey,
authDomain: `${config.firebase.projectId}.firebaseapp.com`,
});
async function getCurrentTabUrl(): Promise<string> {
return await new Promise((resolve) =>
chrome.tabs.query(
{ active: true, currentWindow: true },
(tabs) => resolve(tabs[0].url))) as string;
}
document.addEventListener("DOMContentLoaded", async () => {
const button = document.getElementById("sign-in-button") as HTMLButtonElement;
const message = document.getElementById("message");
let signingIn = false;
button.addEventListener("click", async () => {
signingIn = true;
await firebase.auth().signInWithPopup(new firebase.auth.GithubAuthProvider());
});
firebase.auth().onAuthStateChanged((user) => {
if (user === null) {
button.style.display = "initial";
message.style.display = "none";
} else {
button.style.display = "none";
message.style.display = "initial";
message.appendChild(document.createTextNode(signingIn ? "Signed in!" : "Item added"));
setTimeout(() => window.close(), 5000);
}
});
});
| Change message when items are added | Change message when items are added
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -19,8 +19,12 @@
const button = document.getElementById("sign-in-button") as HTMLButtonElement;
const message = document.getElementById("message");
- button.addEventListener("click", async () =>
- await firebase.auth().signInWithPopup(new firebase.auth.GithubAuthProvider()));
+ let signingIn = false;
+
+ button.addEventListener("click", async () => {
+ signingIn = true;
+ await firebase.auth().signInWithPopup(new firebase.auth.GithubAuthProvider());
+ });
firebase.auth().onAuthStateChanged((user) => {
if (user === null) {
@@ -29,7 +33,7 @@
} else {
button.style.display = "none";
message.style.display = "initial";
- message.appendChild(document.createTextNode("Signed in!"));
+ message.appendChild(document.createTextNode(signingIn ? "Signed in!" : "Item added"));
setTimeout(() => window.close(), 5000);
}
}); |
0be9d7a8ff62f5f8805108e377e12f41ee017a11 | applications/vpn-settings/src/app/App.tsx | applications/vpn-settings/src/app/App.tsx | import { hot } from 'react-hot-loader/root';
import React from 'react';
import { ProtonApp, useAuthentication, PublicAuthenticationStore, PrivateAuthenticationStore } from 'react-components';
import sentry from 'proton-shared/lib/helpers/sentry';
import * as config from './config';
import PrivateApp from './PrivateApp';
import PublicApp from './PublicApp';
import './app.scss';
sentry(config);
const Setup = () => {
const { UID, login, logout } = useAuthentication() as PublicAuthenticationStore & PrivateAuthenticationStore;
if (UID) {
return <PrivateApp onLogout={logout} />;
}
return <PublicApp onLogin={login} />;
};
const App = () => {
return (
<ProtonApp config={config}>
<Setup />
</ProtonApp>
);
};
export default hot(App);
| import React from 'react';
import { ProtonApp, useAuthentication, PublicAuthenticationStore, PrivateAuthenticationStore } from 'react-components';
import sentry from 'proton-shared/lib/helpers/sentry';
import * as config from './config';
import PrivateApp from './PrivateApp';
import PublicApp from './PublicApp';
import './app.scss';
sentry(config);
const Setup = () => {
const { UID, login, logout } = useAuthentication() as PublicAuthenticationStore & PrivateAuthenticationStore;
if (UID) {
return <PrivateApp onLogout={logout} />;
}
return <PublicApp onLogin={login} />;
};
const App = () => {
return (
<ProtonApp config={config}>
<Setup />
</ProtonApp>
);
};
export default App;
| Use fast-refresh instead of hot-loader | Use fast-refresh instead of hot-loader
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,4 +1,3 @@
-import { hot } from 'react-hot-loader/root';
import React from 'react';
import { ProtonApp, useAuthentication, PublicAuthenticationStore, PrivateAuthenticationStore } from 'react-components';
import sentry from 'proton-shared/lib/helpers/sentry';
@@ -27,4 +26,4 @@
);
};
-export default hot(App);
+export default App; |
f7d91081831e85de1b93a4e8ce3da443a62924c9 | src/list.ts | src/list.ts | export function shuffle<T>(xs: T[]): T[] {
'use strict';
let n = xs.length;
while (n) {
const i = Math.floor(Math.random() * n--);
const t = xs[n];
xs[n] = xs[i];
xs[i] = t;
}
return xs;
}
export function sum(xs: number[]): number {
'use strict';
let result = 0;
for (let i = 0, len = xs.length; i < len; ++i) {
result += xs[i];
}
return result;
}
export function product(xs: number[]): number {
'use strict';
let result = 0;
for (let i = 0, len = xs.length; i < len; ++i) {
result *= xs[i];
}
return result;
}
export function range(from: number, to: number): number[] {
'use strict';
let result: number[] = [];
for (let i = from; i <= to; ++i) {
result.push(i);
}
return result;
}
| import Task from './task';
export function shuffle<T>(xs: T[]): Task<T[]> {
'use strict';
let n = xs.length;
while (n) {
const i = Math.floor(Math.random() * n--);
const t = xs[n];
xs[n] = xs[i];
xs[i] = t;
}
return Task.resolve(xs);
}
export function sum(xs: number[]): number {
'use strict';
let result = 0;
for (let i = 0, len = xs.length; i < len; ++i) {
result += xs[i];
}
return result;
}
export function product(xs: number[]): number {
'use strict';
let result = 0;
for (let i = 0, len = xs.length; i < len; ++i) {
result *= xs[i];
}
return result;
}
export function range(from: number, to: number): number[] {
'use strict';
let result: number[] = [];
for (let i = from; i <= to; ++i) {
result.push(i);
}
return result;
}
| Clarify that List.shuffle has a side effect | Clarify that List.shuffle has a side effect
| TypeScript | mit | AyaMorisawa/node-powerful | ---
+++
@@ -1,4 +1,6 @@
-export function shuffle<T>(xs: T[]): T[] {
+import Task from './task';
+
+export function shuffle<T>(xs: T[]): Task<T[]> {
'use strict';
let n = xs.length;
while (n) {
@@ -7,7 +9,7 @@
xs[n] = xs[i];
xs[i] = t;
}
- return xs;
+ return Task.resolve(xs);
}
export function sum(xs: number[]): number { |
2f5c54ee206d06e607074413fed8c5db2ead0937 | src/app/app.routes.ts | src/app/app.routes.ts | import { Routes, RouterModule } from '@angular/router';
import { Home } from './home';
import { About } from './about';
import { NoContent } from './no-content';
import { RacersComponent } from './racers';
import { TeamsComponent } from './teams';
import { DashboardComponent } from './dashboard';
import { DataResolver } from './app.resolver';
export const ROUTES: Routes = [
{ path: '', component: DashboardComponent },
{ path: 'home', component: Home },
{ path: 'about', component: About },
{ path: 'racers', component: RacersComponent },
{ path: 'teams', component: TeamsComponent },
{
path: 'detail', loadChildren: () => System.import('./+detail')
},
{ path: 'dashboard', component: DashboardComponent },
{ path: '**', component: NoContent },
];
| import { Routes, RouterModule } from '@angular/router';
import { Home } from './home';
import { About } from './about';
import { NoContent } from './no-content';
import { RacersComponent } from './racers';
import { TeamsComponent } from './teams';
import { DashboardComponent } from './dashboard';
import { RacerDetailComponent } from './racer-detail';
import { TeamDetailComponent } from './team-detail';
import { DataResolver } from './app.resolver';
export const ROUTES: Routes = [
{ path: '', component: DashboardComponent },
{ path: 'home', component: Home },
{ path: 'about', component: About },
{ path: 'racers', component: RacersComponent },
{ path: 'teams', component: TeamsComponent },
{ path: 'racer/:id', component: RacerDetailComponent },
{ path: 'team/:id', component: TeamDetailComponent },
{
path: 'detail', loadChildren: () => System.import('./+detail')
},
{ path: 'dashboard', component: DashboardComponent },
{ path: '**', component: NoContent },
];
| Add racer and team detail components to router | Add racer and team detail components to router
| TypeScript | mit | MarkProvanP/racetrack,MarkProvanP/racetrack,MarkProvanP/racetrack,MarkProvanP/racetrack | ---
+++
@@ -6,6 +6,8 @@
import { RacersComponent } from './racers';
import { TeamsComponent } from './teams';
import { DashboardComponent } from './dashboard';
+import { RacerDetailComponent } from './racer-detail';
+import { TeamDetailComponent } from './team-detail';
import { DataResolver } from './app.resolver';
@@ -16,6 +18,8 @@
{ path: 'about', component: About },
{ path: 'racers', component: RacersComponent },
{ path: 'teams', component: TeamsComponent },
+ { path: 'racer/:id', component: RacerDetailComponent },
+ { path: 'team/:id', component: TeamDetailComponent },
{
path: 'detail', loadChildren: () => System.import('./+detail')
}, |
742b2725245158bd5d9051ed00f6afcb593c5b7d | packages/chatbox/src/index.ts | packages/chatbox/src/index.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
export * from './panel';
export * from './chatbox';
export * from './entry'
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import '../style/index.css';
export * from './panel';
export * from './chatbox';
export * from './entry'
| Update theme loading for chatbox. | Update theme loading for chatbox.
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -1,5 +1,7 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
+
+import '../style/index.css';
export * from './panel';
export * from './chatbox'; |
5818c7c3290cce5d138441e29500f6c535c0bf14 | src/app/item-dialog-modal/item-dialog-modal.component.ts | src/app/item-dialog-modal/item-dialog-modal.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { Mage } from '../model/mage.model';
import { EquipmentVault } from '../model/equipmentvault.model';
import { Equipment } from '../model/equipment.model';
@Component({
selector: 'app-item-dialog-modal',
templateUrl: './item-dialog-modal.component.html',
styleUrls: ['./item-dialog-modal.component.css']
})
export class ItemDialogModalComponent implements OnInit {
@Input() userMage : Mage;
constructor() { }
ngOnInit() {
}
getAvailableItems(): Array<Equipment>{
return EquipmentVault.items;
}
addItem(item: Equipment){
this.userMage.addItemToInventory(item);
}
}
| import { Component, OnInit, Input } from '@angular/core';
import { Mage } from '../model/mage.model';
import { EquipmentVault } from '../model/equipmentVault.model';
import { Equipment } from '../model/equipment.model';
@Component({
selector: 'app-item-dialog-modal',
templateUrl: './item-dialog-modal.component.html',
styleUrls: ['./item-dialog-modal.component.css']
})
export class ItemDialogModalComponent implements OnInit {
@Input() userMage : Mage;
constructor() { }
ngOnInit() {
}
getAvailableItems(): Array<Equipment>{
return EquipmentVault.items;
}
addItem(item: Equipment){
this.userMage.addItemToInventory(item);
}
}
| Fix for casing issue throwing a warning | Fix for casing issue throwing a warning
Fix for casing issue throwing a warning. file declarations need to match
file letter casing.
| TypeScript | mit | ChargerIIC/Frostgrave-WarRoster,ChargerIIC/Frostgrave-WarRoster,ChargerIIC/Frostgrave-WarRoster | ---
+++
@@ -1,7 +1,7 @@
import { Component, OnInit, Input } from '@angular/core';
import { Mage } from '../model/mage.model';
-import { EquipmentVault } from '../model/equipmentvault.model';
+import { EquipmentVault } from '../model/equipmentVault.model';
import { Equipment } from '../model/equipment.model';
@Component({ |
3ef95e663fa12b2ceeed76e55367fcc03daec4bf | electron/src/storage/repository-healer.ts | electron/src/storage/repository-healer.ts | import * as fs from "fs-extra";
import {LocalRepository} from "./types/local-repository";
export function heal(repository: LocalRepository, key?: keyof LocalRepository): Promise<boolean> {
const fixes = [] as Promise<any>[];
let modified = false;
return new Promise((resolve, reject) => {
if (key === "localFolders" || !key) {
if (!Array.isArray(repository.localFolders)) {
repository.localFolders = [];
}
const checks = [];
repository.localFolders = repository.localFolders.filter((v, i, arr) => {
return typeof v === "string" && arr.indexOf(v) === i;
});
for (let i = 0; i < repository.localFolders.length; i++) {
const dirPath = repository.localFolders[i];
const access = new Promise((res, rej) => {
fs.stat(dirPath, (err, stats) => {
if (err || !stats.isDirectory()) {
repository.localFolders.splice(i, 1);
modified = true;
}
res();
});
});
checks.push(access);
}
fixes.push(Promise.all(checks));
}
Promise.all(fixes).then(() => resolve(modified), reject);
});
}
| import * as fs from "fs-extra";
import {LocalRepository} from "./types/local-repository";
import {defaultExecutionOutputDirectory} from "../controllers/execution-results.controller";
export function heal(repository: LocalRepository, key?: keyof LocalRepository): Promise<boolean> {
const fixes = [] as Promise<any>[];
let modified = false;
return new Promise((resolve, reject) => {
if (key === "localFolders" || !key) {
if (!Array.isArray(repository.localFolders)) {
repository.localFolders = [];
}
const checks = [];
repository.localFolders = repository.localFolders.filter((v, i, arr) => {
return typeof v === "string" && arr.indexOf(v) === i;
});
for (let i = 0; i < repository.localFolders.length; i++) {
const dirPath = repository.localFolders[i];
const access = new Promise((res, rej) => {
fs.stat(dirPath, (err, stats) => {
if (err || !stats.isDirectory()) {
repository.localFolders.splice(i, 1);
modified = true;
}
res();
});
});
checks.push(access);
}
fixes.push(Promise.all(checks));
}
if (key === "executorConfig" || !key) {
if (!repository.executorConfig.outDir) {
fixes.push(new Promise((res, rej) => {
repository.executorConfig.outDir = defaultExecutionOutputDirectory;
modified = true;
res();
}));
}
}
Promise.all(fixes).then(() => resolve(modified), reject);
});
}
| Set default executor outDir if none exists | fix(executor-config): Set default executor outDir if none exists
| TypeScript | apache-2.0 | rabix/composer,rabix/cottontail-frontend,rabix/cottontail-frontend,rabix/cottontail-frontend,rabix/composer,rabix/cottontail-frontend,rabix/composer | ---
+++
@@ -1,5 +1,6 @@
import * as fs from "fs-extra";
import {LocalRepository} from "./types/local-repository";
+import {defaultExecutionOutputDirectory} from "../controllers/execution-results.controller";
export function heal(repository: LocalRepository, key?: keyof LocalRepository): Promise<boolean> {
@@ -41,6 +42,19 @@
fixes.push(Promise.all(checks));
}
+ if (key === "executorConfig" || !key) {
+
+ if (!repository.executorConfig.outDir) {
+ fixes.push(new Promise((res, rej) => {
+
+ repository.executorConfig.outDir = defaultExecutionOutputDirectory;
+ modified = true;
+
+ res();
+ }));
+ }
+ }
+
Promise.all(fixes).then(() => resolve(modified), reject);
|
c42e16edaaaa032ab64ef08ea3765dda2b19392f | src/templates/customTemplate.ts | src/templates/customTemplate.ts | import * as ts from 'typescript'
import { BaseTemplate } from './baseTemplates'
import { CompletionItemBuilder } from '../completionItemBuilder'
export class CustomTemplate extends BaseTemplate {
private conditionsMap = new Map<string, (node: ts.Node) => boolean>([
['identifier', (node: ts.Node) => this.isIdentifier(node)],
['expression', (node: ts.Node) => this.isExpression(node)],
['binary-expression', (node: ts.Node) => this.isBinaryExpression(node)],
['unary-expression', (node: ts.Node) => this.isUnaryExpression(node.parent)],
['new-expression', (node: ts.Node) => this.isNewExpression(node)],
['function-call', (node: ts.Node) => this.isCallExpression(node)]
])
constructor (private name: string, private description: string, private body: string, private conditions: string[]) {
super()
}
buildCompletionItem(node: ts.Node, indentSize?: number) {
let currentNode = this.getCurrentNode(node)
return CompletionItemBuilder
.create(this.name, currentNode, indentSize)
.description(this.description)
.replace(this.body, true)
.build()
}
canUse (node: ts.Node): boolean {
return node.parent && (this.conditions.length === 0 || this.conditions.some(c => this.condition(node, c)))
}
condition = (node: ts.Node, condition: string) => {
const callback = this.conditionsMap.get(condition)
return callback && callback(node)
}
}
| import * as ts from 'typescript'
import { BaseTemplate } from './baseTemplates'
import { CompletionItemBuilder } from '../completionItemBuilder'
export class CustomTemplate extends BaseTemplate {
private conditionsMap = new Map<string, (node: ts.Node) => boolean>([
['identifier', (node: ts.Node) => this.isIdentifier(node)],
['expression', (node: ts.Node) => this.isExpression(node)],
['binary-expression', (node: ts.Node) => this.isBinaryExpression(node)],
['unary-expression', (node: ts.Node) => this.isUnaryExpression(node.parent)],
['new-expression', (node: ts.Node) => this.isNewExpression(node)],
['function-call', (node: ts.Node) => this.isCallExpression(node)]
])
constructor (private name: string, private description: string, private body: string, private when: string[]) {
super()
}
buildCompletionItem(node: ts.Node, indentSize?: number) {
let currentNode = this.getCurrentNode(node)
return CompletionItemBuilder
.create(this.name, currentNode, indentSize)
.description(this.description)
.replace(this.body, true)
.build()
}
canUse (node: ts.Node): boolean {
return node.parent && (this.when.length === 0 || this.when.some(w => this.condition(node, w)))
}
condition = (node: ts.Node, when: string) => {
const callback = this.conditionsMap.get(when)
return callback && callback(node)
}
}
| Rename CustomTemplate to use `when` instead of `condition` | Rename CustomTemplate to use `when` instead of `condition`
It maps to what's in the configuration better and should be less confusing.
Actually got confused myself after longer break.
| TypeScript | mit | ipatalas/vscode-postfix-ts,ipatalas/vscode-postfix-ts | ---
+++
@@ -12,7 +12,7 @@
['function-call', (node: ts.Node) => this.isCallExpression(node)]
])
- constructor (private name: string, private description: string, private body: string, private conditions: string[]) {
+ constructor (private name: string, private description: string, private body: string, private when: string[]) {
super()
}
@@ -27,11 +27,11 @@
}
canUse (node: ts.Node): boolean {
- return node.parent && (this.conditions.length === 0 || this.conditions.some(c => this.condition(node, c)))
+ return node.parent && (this.when.length === 0 || this.when.some(w => this.condition(node, w)))
}
- condition = (node: ts.Node, condition: string) => {
- const callback = this.conditionsMap.get(condition)
+ condition = (node: ts.Node, when: string) => {
+ const callback = this.conditionsMap.get(when)
return callback && callback(node)
}
} |
4839dd275adecbc8688151a5b0a17aa455fcfa39 | src/explorer.ts | src/explorer.ts | import react = require("react");
import Explorer = require("./components/explorer");
/**
* Creates and renders the API Explorer component.
*/
export function run(): void {
react.render(Explorer.create(), document.getElementById("container"));
}
| import react = require("react");
import Explorer = require("./components/explorer");
/**
* Creates and renders the API Explorer component.
*/
export function run(initial_resource?: string, initial_route?: string): void {
react.render(Explorer.create({
initial_resource_string: initial_resource,
initial_route: initial_route
}), document.getElementById("container"));
}
| Add optional parameter to specify resource/route | Add optional parameter to specify resource/route
The actual react compoent already had these via an optional Prop, so
we only need to pass it in in the initial `run()` function. Just
pass the string you want to add in and it will adjust the choices.
For example, `AsanaTester.Explorer.run("Projects", "/teams/%d/projects")`
| TypeScript | mit | Asana/api-explorer,Asana/api-explorer | ---
+++
@@ -5,6 +5,9 @@
/**
* Creates and renders the API Explorer component.
*/
-export function run(): void {
- react.render(Explorer.create(), document.getElementById("container"));
+export function run(initial_resource?: string, initial_route?: string): void {
+ react.render(Explorer.create({
+ initial_resource_string: initial_resource,
+ initial_route: initial_route
+ }), document.getElementById("container"));
} |
bc9e3e31b0cf1fe3c8387c4e5b555ff3900b98f0 | applications/vpn-settings/src/app/containers/GeneralContainer.tsx | applications/vpn-settings/src/app/containers/GeneralContainer.tsx | import React from 'react';
import { c } from 'ttag';
import { LanguageSection, ThemesSection, SettingsPropsShared } from 'react-components';
import locales from 'proton-shared/lib/i18n/locales';
import PrivateMainSettingsAreaWithPermissions from '../components/page/PrivateMainSettingsAreaWithPermissions';
export const getGeneralPage = () => {
return {
text: c('Title').t`General`,
to: '/general',
icon: 'general',
subsections: [
{
text: c('Title').t`Language`,
id: 'language',
},
{
text: c('Title').t`Themes`,
id: 'themes',
},
],
};
};
const GeneralContainer = ({ setActiveSection, location }: SettingsPropsShared) => {
return (
<PrivateMainSettingsAreaWithPermissions
location={location}
config={getGeneralPage()}
setActiveSection={setActiveSection}
>
<LanguageSection locales={locales} />
<ThemesSection />
</PrivateMainSettingsAreaWithPermissions>
);
};
export default GeneralContainer;
| import React from 'react';
import { c } from 'ttag';
import { LanguageSection, ThemesSection, SettingsPropsShared, EarlyAccessSection } from 'react-components';
import locales from 'proton-shared/lib/i18n/locales';
import PrivateMainSettingsAreaWithPermissions from '../components/page/PrivateMainSettingsAreaWithPermissions';
export const getGeneralPage = () => {
return {
text: c('Title').t`General`,
to: '/general',
icon: 'general',
subsections: [
{
text: c('Title').t`Language`,
id: 'language',
},
{
text: c('Title').t`Themes`,
id: 'themes',
},
{
text: c('Title').t`Early Access`,
id: 'early-access',
},
],
};
};
const GeneralContainer = ({ setActiveSection, location }: SettingsPropsShared) => {
return (
<PrivateMainSettingsAreaWithPermissions
location={location}
config={getGeneralPage()}
setActiveSection={setActiveSection}
>
<LanguageSection locales={locales} />
<ThemesSection />
<EarlyAccessSection />
</PrivateMainSettingsAreaWithPermissions>
);
};
export default GeneralContainer;
| Add early access to general settings | Add early access to general settings
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,6 +1,6 @@
import React from 'react';
import { c } from 'ttag';
-import { LanguageSection, ThemesSection, SettingsPropsShared } from 'react-components';
+import { LanguageSection, ThemesSection, SettingsPropsShared, EarlyAccessSection } from 'react-components';
import locales from 'proton-shared/lib/i18n/locales';
import PrivateMainSettingsAreaWithPermissions from '../components/page/PrivateMainSettingsAreaWithPermissions';
@@ -19,6 +19,10 @@
text: c('Title').t`Themes`,
id: 'themes',
},
+ {
+ text: c('Title').t`Early Access`,
+ id: 'early-access',
+ },
],
};
};
@@ -32,6 +36,7 @@
>
<LanguageSection locales={locales} />
<ThemesSection />
+ <EarlyAccessSection />
</PrivateMainSettingsAreaWithPermissions>
);
}; |
46df75d002cb7342423ec3fd5ce545db36ccf39c | test/runTest.ts | test/runTest.ts | import {
downloadAndUnzipVSCode,
resolveCliPathFromVSCodeExecutablePath,
runTests,
} from "@vscode/test-electron";
import * as cp from "child_process";
import * as path from "path";
async function main() {
try {
const extensionDevelopmentPath = path.resolve(__dirname, "..", "..");
const extensionTestsPath = path.resolve(__dirname, "index");
const vscodeExecutablePath = await downloadAndUnzipVSCode("insiders");
const cliPath = resolveCliPathFromVSCodeExecutablePath(vscodeExecutablePath, "linux-x64");
// Add the dependent extension for test coverage preview functionality
cp.spawnSync(cliPath, ["--install-extension", "ms-vscode.live-server"], {
encoding: "utf-8",
stdio: "inherit",
});
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
launchArgs: ["example/example.code-workspace"],
vscodeExecutablePath,
});
console.info("Success!");
process.exit(0);
} catch (err) {
console.error("Failed to run tests");
process.exit(1);
}
}
main();
| import {
downloadAndUnzipVSCode,
resolveCliArgsFromVSCodeExecutablePath,
runTests,
} from "@vscode/test-electron";
import * as cp from "child_process";
import * as path from "path";
async function main() {
try {
const extensionDevelopmentPath = path.resolve(__dirname, "..", "..");
const extensionTestsPath = path.resolve(__dirname, "index");
const vscodeExecutablePath = await downloadAndUnzipVSCode("insiders");
// Add the dependent extension for test coverage preview functionality
const [cli, ...args] = resolveCliArgsFromVSCodeExecutablePath(vscodeExecutablePath);
cp.spawnSync(cli, [...args, "--install-extension", "ms-vscode.live-server"], {
encoding: "utf-8",
stdio: "inherit",
});
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
launchArgs: ["example/example.code-workspace"],
vscodeExecutablePath,
});
console.info("Success!");
process.exit(0);
} catch (err) {
console.error("Failed to run tests");
process.exit(1);
}
}
main();
| Fix live preview install for tests | Fix live preview install for tests
| TypeScript | mit | ryanluker/vscode-coverage-gutters,ryanluker/vscode-coverage-gutters,ryanluker/vscode-coverage-gutters,ryanluker/vscode-coverage-gutters,ryanluker/vscode-coverage-gutters,ryanluker/vscode-coverage-gutters,ryanluker/vscode-coverage-gutters,ryanluker/vscode-coverage-gutters,ryanluker/vscode-coverage-gutters | ---
+++
@@ -1,6 +1,6 @@
import {
downloadAndUnzipVSCode,
- resolveCliPathFromVSCodeExecutablePath,
+ resolveCliArgsFromVSCodeExecutablePath,
runTests,
} from "@vscode/test-electron";
import * as cp from "child_process";
@@ -11,10 +11,10 @@
const extensionDevelopmentPath = path.resolve(__dirname, "..", "..");
const extensionTestsPath = path.resolve(__dirname, "index");
const vscodeExecutablePath = await downloadAndUnzipVSCode("insiders");
- const cliPath = resolveCliPathFromVSCodeExecutablePath(vscodeExecutablePath, "linux-x64");
// Add the dependent extension for test coverage preview functionality
- cp.spawnSync(cliPath, ["--install-extension", "ms-vscode.live-server"], {
+ const [cli, ...args] = resolveCliArgsFromVSCodeExecutablePath(vscodeExecutablePath);
+ cp.spawnSync(cli, [...args, "--install-extension", "ms-vscode.live-server"], {
encoding: "utf-8",
stdio: "inherit",
}); |
97f2d9e79d97a11a50c6b7a42fbd0b8abd826c73 | tests/_utils.ts | tests/_utils.ts | /// <reference path="./../typings/index.d.ts" />
const config: {[prop: string]: string} = process.env;
// Grab secret keys
const apiKey = config["gearworks-apiKey"] || config["apiKey"] ;
const secretKey = config["gearworks-secretKey"] || config["secretKey"];
const shopDomain = config["gearworks-shopDomain"] || config["shopDomain"];
const accessToken = config["gearworks-accessToken"] || config["accessToken"];
if (!apiKey)
{
throw new Error(`Expected 'apiKey' in process.env to exist.`);
}
if (!secretKey)
{
throw new Error(`Expected 'secretKey' in process.env to exist.`);
}
if (!shopDomain)
{
throw new Error(`Expected 'shopDomain' in process.env to exist.`);
}
if (!accessToken)
{
throw new Error(`Expected 'accessToken' in process.env to exist.`);
}
export {apiKey, secretKey, shopDomain, accessToken}; | /// <reference path="./../typings/index.d.ts" />
const config: {[prop: string]: string} = process.env;
// Grab secret keys
const apiKey = config["shopify-prime-apiKey"] || config["apiKey"] ;
const secretKey = config["shopify-prime-secretKey"] || config["secretKey"];
const shopDomain = config["shopify-prime-shopDomain"] || config["shopDomain"];
const accessToken = config["shopify-prime-accessToken"] || config["accessToken"];
if (!apiKey)
{
throw new Error(`Expected 'apiKey' in process.env to exist.`);
}
if (!secretKey)
{
throw new Error(`Expected 'secretKey' in process.env to exist.`);
}
if (!shopDomain)
{
throw new Error(`Expected 'shopDomain' in process.env to exist.`);
}
if (!accessToken)
{
throw new Error(`Expected 'accessToken' in process.env to exist.`);
}
export {apiKey, secretKey, shopDomain, accessToken}; | Change test environment variable names | Change test environment variable names
| TypeScript | mit | nozzlegear/Shopify-Prime | ---
+++
@@ -3,10 +3,10 @@
const config: {[prop: string]: string} = process.env;
// Grab secret keys
-const apiKey = config["gearworks-apiKey"] || config["apiKey"] ;
-const secretKey = config["gearworks-secretKey"] || config["secretKey"];
-const shopDomain = config["gearworks-shopDomain"] || config["shopDomain"];
-const accessToken = config["gearworks-accessToken"] || config["accessToken"];
+const apiKey = config["shopify-prime-apiKey"] || config["apiKey"] ;
+const secretKey = config["shopify-prime-secretKey"] || config["secretKey"];
+const shopDomain = config["shopify-prime-shopDomain"] || config["shopDomain"];
+const accessToken = config["shopify-prime-accessToken"] || config["accessToken"];
if (!apiKey)
{ |
3bf1feb090378c2ed96f7c5317ca9e11a7078224 | src/shared/components/ContextMenu/Separator/index.tsx | src/shared/components/ContextMenu/Separator/index.tsx | import * as React from 'react';
import { StyledSeparator } from './styles';
export interface IProps {
i?: number;
visible?: boolean;
menuVisible: boolean;
}
export default class MenuSeparator extends React.Component<IProps, {}> {
private timeout: any;
public static defaultProps = {
visible: true,
};
public state = {
animation: false,
};
public componentWillReceiveProps(nextProps: IProps) {
const { menuVisible } = this.props;
if (nextProps.menuVisible && !menuVisible) {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this.setState({ animation: true });
}, nextProps.i * 25);
} else if (!nextProps.menuVisible) {
clearTimeout(this.timeout);
this.setState({ animation: false });
}
}
public render() {
const { visible } = this.props;
const { animation } = this.state;
return <StyledSeparator animation={animation} visible={visible} />;
}
}
| import * as React from 'react';
import { StyledSeparator } from './styles';
export interface IProps {
i?: number;
visible?: boolean;
menuVisible?: boolean;
}
export default class MenuSeparator extends React.Component<IProps, {}> {
private timeout: any;
public static defaultProps = {
visible: true,
};
public state = {
animation: false,
};
public componentWillReceiveProps(nextProps: IProps) {
const { menuVisible } = this.props;
if (nextProps.menuVisible && !menuVisible) {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this.setState({ animation: true });
}, nextProps.i * 25);
} else if (!nextProps.menuVisible) {
clearTimeout(this.timeout);
this.setState({ animation: false });
}
}
public render() {
const { visible } = this.props;
const { animation } = this.state;
return <StyledSeparator animation={animation} visible={visible} />;
}
}
| Fix error with context menu separator | Fix error with context menu separator
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -5,7 +5,7 @@
export interface IProps {
i?: number;
visible?: boolean;
- menuVisible: boolean;
+ menuVisible?: boolean;
}
export default class MenuSeparator extends React.Component<IProps, {}> { |
4cf6e3423db960cb14fcc3a720a6b4d522f37355 | config/runtimeExamples/configLoader.ts | config/runtimeExamples/configLoader.ts | import { IConfig } from "@cfg/index.d";
export const loadConfig = (url: string): Promise<IConfig<any>> =>
new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(parsedConfig => {
resolve(parsedConfig);
})
.catch(reject);
});
| import { IConfig } from "@cfg/index.d";
export const loadConfig = (url: string): Promise<IConfig<any>> =>
new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.catch(reject)
.then(parsedConfig => {
resolve(parsedConfig);
});
});
| Fix runtime config loader example promise rejection being called too late | Fix runtime config loader example promise rejection being called too late
| TypeScript | mit | gyng/jsapp-boilerplate,gyng/jsapp-boilerplate,gyng/jsapp-boilerplate,gyng/jsapp-boilerplate | ---
+++
@@ -4,8 +4,8 @@
new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
+ .catch(reject)
.then(parsedConfig => {
resolve(parsedConfig);
- })
- .catch(reject);
+ });
}); |
b4d591ca7e6364a4951bdc44e4365b7e28d7b60c | src/elements/import-exports/import-named.ts | src/elements/import-exports/import-named.ts | import {emit_elements} from '../../helpers/emit-elements';
import {Stack} from '../../stack';
import {ImportExport} from '../import-export';
import {ImportMember} from '../members/import-member';
export interface IImportNamedRequiredParameters {
members: ImportMember[];
from: string;
}
// tslint:disable-next-line no-empty-interface
export interface IImportNamedOptionalParameters {}
export class ImportNamed extends ImportExport<IImportNamedRequiredParameters, IImportNamedOptionalParameters> {
private _instance_of_import_named: true;
public get default_parameters(): IImportNamedOptionalParameters {
return {};
}
public _emit(stack: Stack): string {
const {members, from} = this.parameters;
return `import {${emit_elements(members, stack, ', ')}} from ${JSON.stringify(from)};`;
}
}
| import {emit_elements} from '../../helpers/emit-elements';
import {Stack} from '../../stack';
import {ImportExport} from '../import-export';
import {ImportMember} from '../members/import-member';
export interface IImportNamedRequiredParameters {
from: string;
}
export interface IImportNamedOptionalParameters {
members: ImportMember[];
}
export class ImportNamed extends ImportExport<IImportNamedRequiredParameters, IImportNamedOptionalParameters> {
private _instance_of_import_named: true;
public get default_parameters(): IImportNamedOptionalParameters {
return {
members: [],
};
}
public _emit(stack: Stack): string {
const {members, from} = this.parameters;
return `import {${emit_elements(members, stack, ', ')}} from ${JSON.stringify(from)};`;
}
}
| Update ImportNamd members should be an optional parameter | Update ImportNamd
members should be an optional parameter
| TypeScript | mit | ikatyang/dts-element,ikatyang/dts-element | ---
+++
@@ -4,19 +4,21 @@
import {ImportMember} from '../members/import-member';
export interface IImportNamedRequiredParameters {
- members: ImportMember[];
from: string;
}
-// tslint:disable-next-line no-empty-interface
-export interface IImportNamedOptionalParameters {}
+export interface IImportNamedOptionalParameters {
+ members: ImportMember[];
+}
export class ImportNamed extends ImportExport<IImportNamedRequiredParameters, IImportNamedOptionalParameters> {
private _instance_of_import_named: true;
public get default_parameters(): IImportNamedOptionalParameters {
- return {};
+ return {
+ members: [],
+ };
}
public _emit(stack: Stack): string { |
53530f59565dda0e74f6b64971c7a8b6839a5f76 | tests/test-components/CommitBox.spec.tsx | tests/test-components/CommitBox.spec.tsx | import 'jest';
import { CommitBox } from '../../src/components/CommitBox';
import { classes } from 'typestyle';
import {
stagedCommitButtonStyle,
stagedCommitButtonReadyStyle,
stagedCommitButtonDisabledStyle
} from '../../src/style/BranchHeaderStyle';
describe('CommitBox', () => {
describe('#checkReadyForSubmit()', () => {
it('should update commit box state to be ready when changes are staged', () => {
const box = new CommitBox({
onCommit: async () => {},
hasFiles: true
});
// TODO: this sort of testing should be performed during UI/UX testing, not unit testing
let actual = box._commitButtonStyle(true);
let expected = classes(
stagedCommitButtonStyle,
stagedCommitButtonReadyStyle
);
expect(actual).toEqual(expected);
});
it('should update commit box state to be disabled when no changes are staged', () => {
const box = new CommitBox({
onCommit: async () => {},
hasFiles: true
});
// TODO: this sort of testing should be performed during UI/UX testing, not unit testing
let actual = box._commitButtonStyle(false);
let expected = classes(
stagedCommitButtonStyle,
stagedCommitButtonDisabledStyle
);
expect(actual).toEqual(expected);
});
it('should be ready to commit with a message set', () => {
const box = new CommitBox({
onCommit: async () => {},
hasFiles: true
});
// can't use setState here, since the box hasn't actually mounted
box.state = { value: 'message' };
// TODO: this sort of testing should be performed during UI/UX testing, not unit testing
let actual = box._commitButtonStyle(true);
let expected = stagedCommitButtonStyle;
expect(actual).toEqual(expected);
});
});
});
| import * as React from 'react';
import 'jest';
import { shallow } from 'enzyme';
import { CommitBox } from '../../src/components/CommitBox';
describe('CommitBox', () => {
describe('#constructor()', () => {
it('should return a new instance', () => {
const box = new CommitBox({
onCommit: async () => {},
hasFiles: false
});
expect(box).toBeInstanceOf(CommitBox);
});
it('should set correct default commit message values', () => {
const box = new CommitBox({
onCommit: async () => {},
hasFiles: false
});
expect(box.state.summary).toEqual('');
expect(box.state.description).toEqual('');
});
});
describe('#render()', () => {
it('should display placeholder text for the commit message summary', () => {
const props = {
onCommit: async () => {},
hasFiles: false
};
const component = shallow(<CommitBox {...props} />);
const node = component.find('input[type="text"]').first();
expect(node.prop('placeholder')).toEqual('Summary (required)');
});
it('should display placeholder text for the commit message description', () => {
const props = {
onCommit: async () => {},
hasFiles: false
};
const component = shallow(<CommitBox {...props} />);
const node = component.find('TextareaAutosize').first();
expect(node.prop('placeholder')).toEqual('Description');
});
});
});
| Add initial commit box tests | Add initial commit box tests
| TypeScript | bsd-3-clause | jupyterlab/jupyterlab-git,jupyterlab/jupyterlab-git,jupyterlab/jupyterlab-git | ---
+++
@@ -1,57 +1,47 @@
+import * as React from 'react';
import 'jest';
+import { shallow } from 'enzyme';
import { CommitBox } from '../../src/components/CommitBox';
-import { classes } from 'typestyle';
-import {
- stagedCommitButtonStyle,
- stagedCommitButtonReadyStyle,
- stagedCommitButtonDisabledStyle
-} from '../../src/style/BranchHeaderStyle';
describe('CommitBox', () => {
- describe('#checkReadyForSubmit()', () => {
- it('should update commit box state to be ready when changes are staged', () => {
+ describe('#constructor()', () => {
+ it('should return a new instance', () => {
const box = new CommitBox({
onCommit: async () => {},
- hasFiles: true
+ hasFiles: false
});
-
- // TODO: this sort of testing should be performed during UI/UX testing, not unit testing
- let actual = box._commitButtonStyle(true);
-
- let expected = classes(
- stagedCommitButtonStyle,
- stagedCommitButtonReadyStyle
- );
- expect(actual).toEqual(expected);
+ expect(box).toBeInstanceOf(CommitBox);
});
- it('should update commit box state to be disabled when no changes are staged', () => {
+ it('should set correct default commit message values', () => {
const box = new CommitBox({
onCommit: async () => {},
- hasFiles: true
+ hasFiles: false
});
+ expect(box.state.summary).toEqual('');
+ expect(box.state.description).toEqual('');
+ });
+ });
- // TODO: this sort of testing should be performed during UI/UX testing, not unit testing
- let actual = box._commitButtonStyle(false);
- let expected = classes(
- stagedCommitButtonStyle,
- stagedCommitButtonDisabledStyle
- );
- expect(actual).toEqual(expected);
+ describe('#render()', () => {
+ it('should display placeholder text for the commit message summary', () => {
+ const props = {
+ onCommit: async () => {},
+ hasFiles: false
+ };
+ const component = shallow(<CommitBox {...props} />);
+ const node = component.find('input[type="text"]').first();
+ expect(node.prop('placeholder')).toEqual('Summary (required)');
});
- it('should be ready to commit with a message set', () => {
- const box = new CommitBox({
+ it('should display placeholder text for the commit message description', () => {
+ const props = {
onCommit: async () => {},
- hasFiles: true
- });
- // can't use setState here, since the box hasn't actually mounted
- box.state = { value: 'message' };
-
- // TODO: this sort of testing should be performed during UI/UX testing, not unit testing
- let actual = box._commitButtonStyle(true);
- let expected = stagedCommitButtonStyle;
- expect(actual).toEqual(expected);
+ hasFiles: false
+ };
+ const component = shallow(<CommitBox {...props} />);
+ const node = component.find('TextareaAutosize').first();
+ expect(node.prop('placeholder')).toEqual('Description');
});
});
}); |
2359ad4ad507406dff042a878632e20e6e9f02d6 | packages/components/containers/members/DeleteMemberModal.tsx | packages/components/containers/members/DeleteMemberModal.tsx | import React, { useState } from 'react';
import { c } from 'ttag';
import { Member } from 'proton-shared/lib/interfaces/Member';
import { Alert, Input, ErrorButton, DeleteModal } from '../../components';
interface Props {
member: Member;
onConfirm: () => void;
onClose: () => void;
}
const DeleteMemberModal = ({ member, onConfirm, onClose, ...rest }: Props) => {
const [username, setUsername] = useState('');
const title = c('Title').t`Delete "${member.Name}"?`;
const isValid = username === member.Name;
const handleSubmit = async () => {
if (!isValid) {
return;
}
onConfirm();
};
return (
<DeleteModal
title={title}
onConfirm={handleSubmit}
onClose={onClose}
confirm={<ErrorButton disabled={!isValid} type="submit">{c('Action').t`Delete`}</ErrorButton>}
{...rest}
>
<Alert>{c('Info')
.t`This will permanently delete the data and all email addresses associated with this user.`}</Alert>
<Alert type="error">{c('Info').t`To confirm, please enter the name of the user you wish to delete.`}</Alert>
<Input
autoComplete="false"
value={username}
onChange={({ target }) => setUsername(target.value)}
placeholder={c('Placeholder').t`Username`}
autoFocus
/>
</DeleteModal>
);
};
export default DeleteMemberModal;
| import React, { useState } from 'react';
import { c } from 'ttag';
import { Member } from 'proton-shared/lib/interfaces/Member';
import { Alert, Input, ErrorButton, DeleteModal, Card } from '../../components';
interface Props {
member: Member;
onConfirm: () => void;
onClose: () => void;
}
const DeleteMemberModal = ({ member, onConfirm, onClose, ...rest }: Props) => {
const [username, setUsername] = useState('');
const isValid = username === member.Name;
const handleSubmit = async () => {
if (!isValid) {
return;
}
onConfirm();
};
return (
<DeleteModal
title={c('Title').t`Delete user`}
onConfirm={handleSubmit}
onClose={onClose}
confirm={<ErrorButton disabled={!isValid} type="submit">{c('Action').t`Delete`}</ErrorButton>}
{...rest}
>
<div className="mb1">
{c('Info').t`This will permanently delete the data and all email addresses associated with this user.`}
</div>
<Card rounded className="text-break user-select mb1">
{member.Name}
</Card>
<Alert type="error">{c('Info').t`To confirm, please enter the name of the user you wish to delete.`}</Alert>
<Input
autoComplete="false"
value={username}
onChange={({ target }) => setUsername(target.value)}
placeholder={c('Placeholder').t`Username`}
autoFocus
/>
</DeleteModal>
);
};
export default DeleteMemberModal;
| Rework delete-user modal a bit | Rework delete-user modal a bit
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -2,7 +2,7 @@
import { c } from 'ttag';
import { Member } from 'proton-shared/lib/interfaces/Member';
-import { Alert, Input, ErrorButton, DeleteModal } from '../../components';
+import { Alert, Input, ErrorButton, DeleteModal, Card } from '../../components';
interface Props {
member: Member;
@@ -12,7 +12,6 @@
const DeleteMemberModal = ({ member, onConfirm, onClose, ...rest }: Props) => {
const [username, setUsername] = useState('');
- const title = c('Title').t`Delete "${member.Name}"?`;
const isValid = username === member.Name;
const handleSubmit = async () => {
@@ -24,14 +23,18 @@
return (
<DeleteModal
- title={title}
+ title={c('Title').t`Delete user`}
onConfirm={handleSubmit}
onClose={onClose}
confirm={<ErrorButton disabled={!isValid} type="submit">{c('Action').t`Delete`}</ErrorButton>}
{...rest}
>
- <Alert>{c('Info')
- .t`This will permanently delete the data and all email addresses associated with this user.`}</Alert>
+ <div className="mb1">
+ {c('Info').t`This will permanently delete the data and all email addresses associated with this user.`}
+ </div>
+ <Card rounded className="text-break user-select mb1">
+ {member.Name}
+ </Card>
<Alert type="error">{c('Info').t`To confirm, please enter the name of the user you wish to delete.`}</Alert>
<Input
autoComplete="false" |
a3f4c8a843d4e66218b489865eaea656e71a3a0b | functions/add-item.ts | functions/add-item.ts | import { Request, Response } from "express";
import * as admin from "firebase-admin";
import * as msgpack from "msgpack-lite";
import nanoid = require("nanoid");
import { parse } from "url";
import { convertUrlIntoArticle } from "./article";
import { httpsFunction } from "./utils";
import { convertUrlIntoVideo } from "./video";
class File {
private file;
constructor(path: string) {
this.file = admin.storage().bucket().file(path);
}
public read = async () => await msgpack.decode((await this.file.download())[0]);
public write = async (content: any) => await this.file.save(msgpack.encode(content));
}
export default httpsFunction(
async ({ query: { url } }: Request, response: Response, userId: string) => {
const isVideo = parse(url).hostname === "www.youtube.com";
const item = await (isVideo ? convertUrlIntoVideo : convertUrlIntoArticle)(url);
console.log("Item:", item);
const file = new File(`/users/${userId}/${isVideo ? "videos" : "articles"}/todo`);
await file.write([{ id: nanoid(), ...item }, ...(await file.read())]);
response.sendStatus(200);
});
| import { Request, Response } from "express";
import * as admin from "firebase-admin";
import * as msgpack from "msgpack-lite";
import nanoid = require("nanoid");
import { parse } from "url";
import { convertUrlIntoArticle } from "./article";
import { httpsFunction } from "./utils";
import { convertUrlIntoVideo } from "./video";
class File {
private file;
constructor(path: string) {
this.file = admin.storage().bucket().file(path);
}
public read = async () => await msgpack.decode((await this.file.download())[0]);
public write = async (content: any) => await this.file.save(msgpack.encode(content));
}
export default httpsFunction(
async ({ query: { url } }: Request, response: Response, userId: string) => {
const isVideo = parse(url).hostname === "www.youtube.com";
const item = await (isVideo ? convertUrlIntoVideo : convertUrlIntoArticle)(url);
console.log("Item:", item);
const file = new File(`/users/${userId}/${isVideo ? "videos" : "articles"}/todo`);
let items = [];
try {
items = await file.read();
} catch (error) {
console.error(error);
}
await file.write([{ id: nanoid(), ...item }, ...items]);
response.sendStatus(200);
});
| Handle errors when an articles file is missing | Handle errors when an articles file is missing
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -29,7 +29,15 @@
console.log("Item:", item);
const file = new File(`/users/${userId}/${isVideo ? "videos" : "articles"}/todo`);
- await file.write([{ id: nanoid(), ...item }, ...(await file.read())]);
+ let items = [];
+
+ try {
+ items = await file.read();
+ } catch (error) {
+ console.error(error);
+ }
+
+ await file.write([{ id: nanoid(), ...item }, ...items]);
response.sendStatus(200);
}); |
a806472a28d2e0d954abd75dc2c4f750bcd50a8a | src/main/ts/ephox/boss/api/Main.ts | src/main/ts/ephox/boss/api/Main.ts | import BasicPage from './BasicPage';
import CommentGene from './CommentGene';
import DomUniverse from './DomUniverse';
import Gene from './Gene';
import TestUniverse from './TestUniverse';
import TextGene from './TextGene';
// NON API USAGE
// used by phoenix
import Logger from '../mutant/Logger';
// used by soldier tests
import Locator from '../mutant/Locator';
export {
BasicPage,
CommentGene,
DomUniverse,
Gene,
TestUniverse,
TextGene,
Logger,
Locator
}; | import BasicPage from './BasicPage';
import CommentGene from './CommentGene';
import DomUniverse from './DomUniverse';
import Gene from './Gene';
import TestUniverse from './TestUniverse';
import TextGene from './TextGene';
// NON API USAGE
// used by soldier tests
import Locator from '../mutant/Locator';
export {
BasicPage,
CommentGene,
DomUniverse,
Gene,
TestUniverse,
TextGene,
Locator
}; | Remove Logger from boss API (which overlaps with agar Logger). The phoenix use has been resolved. | TBIO-5141: Remove Logger from boss API (which overlaps with agar Logger). The phoenix use has been resolved.
| TypeScript | lgpl-2.1 | TeamupCom/tinymce,FernCreek/tinymce,FernCreek/tinymce,tinymce/tinymce,tinymce/tinymce,tinymce/tinymce,FernCreek/tinymce,TeamupCom/tinymce | ---
+++
@@ -6,8 +6,6 @@
import TextGene from './TextGene';
// NON API USAGE
-// used by phoenix
-import Logger from '../mutant/Logger';
// used by soldier tests
import Locator from '../mutant/Locator';
@@ -18,6 +16,5 @@
Gene,
TestUniverse,
TextGene,
- Logger,
Locator
}; |
3d925d72f8113a14c8a7e86db60825b937e2a944 | server/src/routes/front.ts | server/src/routes/front.ts | import { Request, Response, Router } from 'express';
import * as path from 'path';
export function front(): Router {
const r = Router();
r.get('*', (req: Request, res: Response) => {
res.sendFile(path.join(__dirname, '../public/index.html'), (err: Error) => {
if (err) {
return res.status(500)
.contentType('text/plain')
.send('This website didn\'t go through its build process properly');
}
});
});
return r;
}
| import { Request, Response, Router } from 'express';
import * as path from 'path';
import { ErrorResponse } from '../common/responses';
export function front(): Router {
const r = Router();
r.get('*', (req: Request, res: Response) => {
if (req.accepts('html')) {
res.sendFile(path.join(__dirname, '../public/index.html'), (err: Error) => {
if (err) {
return res.status(500)
.contentType('text/plain')
.send('This website didn\'t go through its build process properly');
}
});
} else if (req.accepts('json')) {
const resp: ErrorResponse = {
message: 'Not found',
input: {}
};
return res.status(404).json(resp);
} else {
return res.status(404).send('Please specify an Accept header');
}
});
return r;
}
| Handle Accept: application/json for all routes | Handle Accept: application/json for all routes
| TypeScript | mit | mattbdean/Helium,mattbdean/Helium,mattbdean/Helium,mattbdean/Helium | ---
+++
@@ -1,17 +1,27 @@
import { Request, Response, Router } from 'express';
import * as path from 'path';
+import { ErrorResponse } from '../common/responses';
export function front(): Router {
const r = Router();
-
r.get('*', (req: Request, res: Response) => {
- res.sendFile(path.join(__dirname, '../public/index.html'), (err: Error) => {
- if (err) {
- return res.status(500)
- .contentType('text/plain')
- .send('This website didn\'t go through its build process properly');
- }
- });
+ if (req.accepts('html')) {
+ res.sendFile(path.join(__dirname, '../public/index.html'), (err: Error) => {
+ if (err) {
+ return res.status(500)
+ .contentType('text/plain')
+ .send('This website didn\'t go through its build process properly');
+ }
+ });
+ } else if (req.accepts('json')) {
+ const resp: ErrorResponse = {
+ message: 'Not found',
+ input: {}
+ };
+ return res.status(404).json(resp);
+ } else {
+ return res.status(404).send('Please specify an Accept header');
+ }
});
return r; |
66f1f5426d206652e748775ff1b0dc4530004fc6 | app/src/ui/history/drag-and-drop-intro.ts | app/src/ui/history/drag-and-drop-intro.ts | /** Type of the drag and drop intro popover. Each value represents a feature. */
export enum DragAndDropIntroType {
CherryPick = 'cherry-pick',
Squash = 'squash',
Reorder = 'reorder',
}
/** Structure to describe the drag and drop intro popover. */
export type DragAndDropIntro = {
readonly title: string
readonly body: string
}
/** List of all available drag and drop intro types. */
export const AvailableDragAndDropIntroKeys = Object.values(
DragAndDropIntroType
) as ReadonlyArray<DragAndDropIntroType>
/** Map with all available drag and drop intros. */
export const AvailableDragAndDropIntros: Record<
DragAndDropIntroType,
DragAndDropIntro
> = {
[DragAndDropIntroType.CherryPick]: {
title: 'Cherry-pick!',
body:
'Copy commits to another branch by dragging and dropping them onto a branch in the branch menu, or by right clicking on a commit.',
},
[DragAndDropIntroType.Squash]: {
title: 'Squash!',
body:
'Squash commits by dragging and dropping them onto another commit, or by right clicking on multiple commits.',
},
[DragAndDropIntroType.Reorder]: {
title: 'Reorder!',
body:
'Reorder commits to tidy up your history by dragging and dropping them to a different position.',
},
}
| /** Type of the drag and drop intro popover. Each value represents a feature. */
export enum DragAndDropIntroType {
CherryPick = 'cherry-pick',
Squash = 'squash',
Reorder = 'reorder',
}
/** Structure to describe the drag and drop intro popover. */
export type DragAndDropIntro = {
readonly title: string
readonly body: string
}
/** List of all available drag and drop intro types. */
export const AvailableDragAndDropIntroKeys = Object.values(
DragAndDropIntroType
) as ReadonlyArray<DragAndDropIntroType>
/** Map with all available drag and drop intros. */
export const AvailableDragAndDropIntros: Record<
DragAndDropIntroType,
DragAndDropIntro
> = {
[DragAndDropIntroType.CherryPick]: {
title: 'Drag and drop to cherry-pick!',
body:
'Copy commits to another branch by dragging and dropping them onto a branch in the branch menu, or by right clicking on a commit.',
},
[DragAndDropIntroType.Squash]: {
title: 'Drag and drop to squash!',
body:
'Squash commits by dragging and dropping them onto another commit, or by right clicking on multiple commits.',
},
[DragAndDropIntroType.Reorder]: {
title: 'Drag and drop to reorder!',
body:
'Reorder commits to tidy up your history by dragging and dropping them to a different position.',
},
}
| Update Intro Titles with "Drag and drop to" | Update Intro Titles with "Drag and drop to"
| TypeScript | mit | desktop/desktop,say25/desktop,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,j-f1/forked-desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,artivilla/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,say25/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop | ---
+++
@@ -22,17 +22,17 @@
DragAndDropIntro
> = {
[DragAndDropIntroType.CherryPick]: {
- title: 'Cherry-pick!',
+ title: 'Drag and drop to cherry-pick!',
body:
'Copy commits to another branch by dragging and dropping them onto a branch in the branch menu, or by right clicking on a commit.',
},
[DragAndDropIntroType.Squash]: {
- title: 'Squash!',
+ title: 'Drag and drop to squash!',
body:
'Squash commits by dragging and dropping them onto another commit, or by right clicking on multiple commits.',
},
[DragAndDropIntroType.Reorder]: {
- title: 'Reorder!',
+ title: 'Drag and drop to reorder!',
body:
'Reorder commits to tidy up your history by dragging and dropping them to a different position.',
}, |
65ff52fdfb8d6c424a722d6343f29fc49c255eb9 | src/messages/IPreMessageSentHandler.ts | src/messages/IPreMessageSentHandler.ts | import { IMessageExtend, IMessageRead, IRead } from '../accessors/index';
import { IRoom } from '../rooms/index';
import { IUser } from '../users/index';
import { IMessage } from './IMessage';
export interface IPreMessageSentHandler {
/**
* First step when a handler is executed: Enables the handler to signal
* to the Rocketlets framework whether handler shall actually execute for the message
* about to be sent.
*
* @param message The message which is being sent
* @param read An accessor to the environment
* @return true: run the pre-logic
*/
checkPreMessageSent(message: IMessage, read: IRead): boolean;
/**
* This method can be used to non-destructively modify the message
* Due to its nature, this method could be parallelized
* @param message The message about to be sent
* @param read An accessor to the environment
* @param extend An accessor for modifying the messages non-destructively
*/
extendMessage(message: IMessage, read: IMessageRead, extend: IMessageExtend): void;
/**
* This method allows for manipulation of the message to be sent
* @param message The message about to be sent
* @param read An accessor to the environment
* @return The modified message
*/
manipulateMessage(message: IMessage, read: IMessageRead): IMessage;
}
| import { IMessageExtend, IRead } from '../accessors/index';
import { IMessage } from './IMessage';
export interface IPreMessageSentHandler {
/**
* First step when a handler is executed: Enables the handler to signal
* to the Rocketlets framework whether handler shall actually execute for the message
* about to be sent.
*
* @param message The message which is being sent
* @param read An accessor to the environment
* @return true: run the pre-logic
*/
checkPreMessageSent(message: IMessage, read: IRead): boolean;
/**
* This method can be used to non-destructively modify the message
* Due to its nature, this method could be parallelized
* @param message The message about to be sent
* @param read An accessor to the environment
* @param extend An accessor for modifying the messages non-destructively
*/
extendMessage(message: IMessage, read: IRead, extend: IMessageExtend): void;
/**
* This method allows for manipulation of the message to be sent
* @param message The message about to be sent
* @param read An accessor to the environment
* @return The modified message
*/
manipulateMessage(message: IMessage, read: IRead): IMessage;
}
| Read should always provide a big context | Read should always provide a big context
| TypeScript | mit | graywolf336/temporary-rocketlets-ts-definition,graywolf336/temporary-rocketlets-ts-definition | ---
+++
@@ -1,6 +1,4 @@
-import { IMessageExtend, IMessageRead, IRead } from '../accessors/index';
-import { IRoom } from '../rooms/index';
-import { IUser } from '../users/index';
+import { IMessageExtend, IRead } from '../accessors/index';
import { IMessage } from './IMessage';
export interface IPreMessageSentHandler {
@@ -22,7 +20,7 @@
* @param read An accessor to the environment
* @param extend An accessor for modifying the messages non-destructively
*/
- extendMessage(message: IMessage, read: IMessageRead, extend: IMessageExtend): void;
+ extendMessage(message: IMessage, read: IRead, extend: IMessageExtend): void;
/**
* This method allows for manipulation of the message to be sent
@@ -30,5 +28,5 @@
* @param read An accessor to the environment
* @return The modified message
*/
- manipulateMessage(message: IMessage, read: IMessageRead): IMessage;
+ manipulateMessage(message: IMessage, read: IRead): IMessage;
} |
5ad17c059c099f0afcc5f97d5c29fc6b45c48230 | applications/drive/src/app/api/files.ts | applications/drive/src/app/api/files.ts | import { CreateDriveFile, UpdateFileRevision } from '../interfaces/file';
export const queryCreateFile = (shareId: string, data: CreateDriveFile) => {
return {
method: 'post',
url: `drive/shares/${shareId}/files`,
data
};
};
export const queryFileRevision = (shareId: string, linkId: string, revisionId: number) => {
return {
method: 'get',
url: `drive/shares/${shareId}/files/${linkId}/revisions/${revisionId}`
};
};
export const queryRequestUpload = (data: {
BlockList: { Hash: string; Size: number; Index: number }[];
AddressID: string;
Signature: string;
ShareID: string;
LinkID: string;
RevisionID: string;
}) => {
return {
method: 'post',
url: 'drive/blocks',
data: { ...data, V2: true }
};
};
export const queryFileBlock = (url: string) => {
return {
method: 'get',
output: 'stream',
url
};
};
export const queryUploadFileBlock = (url: string, chunk: Uint8Array) => {
return {
method: 'put',
input: 'binary',
data: new Blob([chunk]),
url
};
};
export const queryUpdateFileRevision = (
shareID: string,
linkID: string,
revisionID: string,
data: UpdateFileRevision
) => {
return {
method: 'put',
url: `drive/shares/${shareID}/files/${linkID}/revisions/${revisionID}`,
data
};
};
| import { CreateDriveFile, UpdateFileRevision } from '../interfaces/file';
export const queryCreateFile = (shareId: string, data: CreateDriveFile) => {
return {
method: 'post',
url: `drive/shares/${shareId}/files`,
data
};
};
export const queryFileRevision = (shareId: string, linkId: string, revisionId: number) => {
return {
method: 'get',
url: `drive/shares/${shareId}/files/${linkId}/revisions/${revisionId}`
};
};
export const queryRequestUpload = (data: {
BlockList: { Hash: string; Size: number; Index: number }[];
AddressID: string;
Signature: string;
ShareID: string;
LinkID: string;
RevisionID: string;
}) => {
return {
method: 'post',
url: 'drive/blocks',
data
};
};
export const queryFileBlock = (url: string) => {
return {
method: 'get',
output: 'stream',
url
};
};
export const queryUploadFileBlock = (url: string, chunk: Uint8Array) => {
return {
method: 'put',
input: 'binary',
data: new Blob([chunk]),
url
};
};
export const queryUpdateFileRevision = (
shareID: string,
linkID: string,
revisionID: string,
data: UpdateFileRevision
) => {
return {
method: 'put',
url: `drive/shares/${shareID}/files/${linkID}/revisions/${revisionID}`,
data
};
};
| Remove v2 from block request | Remove v2 from block request
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -26,7 +26,7 @@
return {
method: 'post',
url: 'drive/blocks',
- data: { ...data, V2: true }
+ data
};
};
|
96c233d576d63aaa9669e52c05115ab6f4d7b44e | 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">
<span>{props.children}</span>
<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>
);
| import { Field } from "formik";
import * as _ from "lodash";
import React = require("react");
export const Dropdown = (props: {
fieldName: string;
options: {};
children: any;
}) => (
<div className="c-dropdown">
<span>{props.children}</span>
<SelectOptions {...props} />
</div>
);
const SelectOptions = (props: { fieldName: string; options: {} }) => (
<Field component="select" name={props.fieldName}>
{_.values<string>(props.options).map(option => (
<option value={option} key={option}>
{option}
</option>
))}
</Field>
);
| Use enum values instead of keys | Use enum values instead of keys
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -1,4 +1,5 @@
import { Field } from "formik";
+import * as _ from "lodash";
import React = require("react");
export const Dropdown = (props: {
@@ -14,9 +15,9 @@
const SelectOptions = (props: { fieldName: string; options: {} }) => (
<Field component="select" name={props.fieldName}>
- {Object.keys(props.options).map(option => (
+ {_.values<string>(props.options).map(option => (
<option value={option} key={option}>
- {props.options[option]}
+ {option}
</option>
))}
</Field> |
98e6c2cd3c73ce7fb5661b691883428fc2ccfc39 | src/route_factories/presenter_route/pageable_data_layout_presenter.ts | src/route_factories/presenter_route/pageable_data_layout_presenter.ts | import { Presenter } from "./presenter";
export interface PagingEntity {
before?: string | null;
after?: string | null;
}
export interface PaginatedInput<DataInput> {
data: DataInput;
paging: PagingEntity;
}
export interface PaginatedOutput<DataOutput> {
data: DataOutput;
paging: PagingEntity;
}
// tslint:disable-next-line
export class PageableDataLayoutPresenter<DataInput, DataOutput> implements Presenter<PaginatedInput<DataInput>, PaginatedOutput<DataOutput>> {
private _outputJSONSchema = { // tslint:disable-line
type: "object",
properties: {
data: this.presenter.outputJSONSchema(),
paging: {
type: "object",
properties: {
before: {
type: "string",
description: "This field is nullable. Value can be null"
},
after: {
type: "string",
description: "This field is nullable. Value can be null"
},
},
},
},
};
constructor(
private presenter: Presenter<DataInput, DataOutput>,
) {}
public outputJSONSchema() {
return this._outputJSONSchema;
}
public async present(input: PaginatedInput<DataInput>) {
const dataOutput = await this.presenter.present(input.data);
return {
data: dataOutput,
paging: input.paging,
};
}
}
| import { Presenter } from "./presenter";
export interface PagingEntity {
before?: string;
after?: string;
}
export interface PaginatedInput<DataInput> {
data: DataInput;
paging: PagingEntity;
}
export interface PaginatedOutput<DataOutput> {
data: DataOutput;
paging: PagingEntity;
}
// tslint:disable-next-line
export class PageableDataLayoutPresenter<DataInput, DataOutput> implements Presenter<PaginatedInput<DataInput>, PaginatedOutput<DataOutput>> {
private _outputJSONSchema = { // tslint:disable-line
type: "object",
properties: {
data: this.presenter.outputJSONSchema(),
paging: {
type: "object",
properties: {
before: {
type: "string",
},
after: {
type: "string",
},
},
},
},
};
constructor(
private presenter: Presenter<DataInput, DataOutput>,
) {}
public outputJSONSchema() {
return this._outputJSONSchema;
}
public async present(input: PaginatedInput<DataInput>) {
const dataOutput = await this.presenter.present(input.data);
return {
data: dataOutput,
paging: input.paging,
};
}
}
| Revert "Update PagingEntity on PageableDataLayoutPresenter" | Revert "Update PagingEntity on PageableDataLayoutPresenter"
This reverts commit cddc1a357b525cb47253d238ac764e6b092cc578.
| TypeScript | mit | balmbees/corgi | ---
+++
@@ -1,8 +1,8 @@
import { Presenter } from "./presenter";
export interface PagingEntity {
- before?: string | null;
- after?: string | null;
+ before?: string;
+ after?: string;
}
export interface PaginatedInput<DataInput> {
@@ -26,11 +26,9 @@
properties: {
before: {
type: "string",
- description: "This field is nullable. Value can be null"
},
after: {
type: "string",
- description: "This field is nullable. Value can be null"
},
},
}, |
29771cbecc3ef6043e29c4a64a92746e0052c35f | backend/src/server.ts | backend/src/server.ts | import {NestFactory} from '@nestjs/core';
import {SwaggerModule, DocumentBuilder} from '@nestjs/swagger';
import {ValidationPipe, INestApplication} from '@nestjs/common';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
import {AppModule} from './app.module';
import {AuthGuard} from './auth/auth.guard';
import {AuthModule} from './auth/auth.module';
import {apiPath} from './api';
async function bootstrap() {
const app: INestApplication = await NestFactory.create(AppModule);
app.use(bodyParser.json());
app.useGlobalPipes(new ValidationPipe());
const authGuard = app.select(AuthModule).get(AuthGuard);
app.useGlobalGuards(authGuard);
// Allow CORS since frontend is served completely independently
app.use(cors());
const swaggerConfig = new DocumentBuilder()
.addBearerAuth()
.setTitle('tsmean sample api')
.setBasePath(apiPath(1, ''))
.addTag('Animals')
.addTag('Animal lists')
.addTag('Users')
.setDescription('Sample REST API that allows to manage list of animals')
.setVersion('1.0')
.build();
const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('/api/swagger', app, swaggerDocument);
const port: number = process.env.PORT ? parseInt(process.env.PORT, 10) : 4242;
await app.listen(port);
}
bootstrap();
| import {NestFactory} from '@nestjs/core';
import {SwaggerModule, DocumentBuilder} from '@nestjs/swagger';
import {ValidationPipe, INestApplication} from '@nestjs/common';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
import {AppModule} from './app.module';
import {AuthGuard} from './auth/auth.guard';
import {AuthModule} from './auth/auth.module';
import {apiPath} from './api';
async function bootstrap() {
const app: INestApplication = await NestFactory.create(AppModule);
app.use(bodyParser.json());
app.useGlobalPipes(new ValidationPipe());
const authGuard = app.select(AuthModule).get(AuthGuard);
app.useGlobalGuards(authGuard);
// Allow CORS since frontend is served completely independently
app.use(cors());
const swaggerConfig = new DocumentBuilder()
.addBearerAuth()
.setTitle('tsmean sample api')
.addTag('Animals')
.addTag('Animal lists')
.addTag('Users')
.setDescription('Sample REST API that allows to manage list of animals')
.setVersion('1.0')
.build();
const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('/api/swagger', app, swaggerDocument);
const port: number = process.env.PORT ? parseInt(process.env.PORT, 10) : 4242;
await app.listen(port);
}
bootstrap();
| Remove swagger base path - fix curl bug | Remove swagger base path - fix curl bug
| TypeScript | mit | tsmean/tsmean,tsmean/tsmean,tsmean/tsmean,tsmean/tsmean | ---
+++
@@ -24,7 +24,6 @@
const swaggerConfig = new DocumentBuilder()
.addBearerAuth()
.setTitle('tsmean sample api')
- .setBasePath(apiPath(1, ''))
.addTag('Animals')
.addTag('Animal lists')
.addTag('Users') |
46b935bce68581f5e648c020d75bb374a3b07b87 | leveldata.ts | leveldata.ts | var levels = {
"Entryway": {
"map": [ "####E###",
"#......#",
"#.@....#",
"#......#",
"#......E",
"#.#..#.#",
"#......#",
"########"],
"n_to": "Kitchen",
"e_to": "Vehicle maintenance",
},
"Kitchen": {
"map": [ "########",
"#.c.c..#",
"#...@..#",
"#......#",
"#......#",
"#. .. .#",
"#......#",
"####E###"],
"s_to": "Entryway",
},
"Vehicle maintenance": {
"map": [ "##EE####",
"#... .##",
"#......#",
"####...#",
"E .##..#",
"#. .. .#",
"#......#",
"########"],
"w_to": "Entryway",
"n_to": "Service entrance",
},
"Service entrance": {
"map": [ "########",
"#... . #",
"#......#",
"# ##..#",
"# .##..#",
"#. .. .#",
"#......#",
"##EE####"],
"s_to": "Vehicle maintenance"
}
};
| var levels = {
"Entryway": {
"map": [ "####EE######",
"#..........#",
"#..........#",
"#..........#",
"#..........#",
"#..........#",
"#.@........#",
"#..........E",
"#..........E",
"#.#..#.....#",
"#..........#",
"############"],
"n_to": "Kitchen",
"e_to": "Vehicle maintenance",
},
"Kitchen": {
"map": [ "############",
"#.c.c......#",
"#...@......#",
"#..........#",
"#..........#",
"#..........#",
"#..........#",
"#..........#",
"#..........#",
"#. ...... .#",
"#..........#",
"####EE######"],
"s_to": "Entryway",
},
"Vehicle maintenance": {
"map": [ "##EE########",
"#... .##",
"#..........#",
"#..........#",
"#..........#",
"####.......#",
"# .##......#",
"E..##... ..#",
"E..........#",
"#. .. .....#",
"#..........#",
"############"],
"w_to": "Entryway",
"n_to": "Service entrance",
},
"Service entrance": {
"map": [ "############",
"#... ..... #",
"#..........#",
"#..........#",
"#..........#",
"# ##......#",
"# .##......#",
"#..........#",
"#..........#",
"#. ...... .#",
"#..........#",
"##EE########"],
"s_to": "Vehicle maintenance"
}
};
| Convert levels to 12x12 layout | Convert levels to 12x12 layout
| TypeScript | mit | jmacarthur/ld37,jmacarthur/ld37 | ---
+++
@@ -1,48 +1,64 @@
var levels = {
"Entryway": {
- "map": [ "####E###",
- "#......#",
- "#.@....#",
- "#......#",
- "#......E",
- "#.#..#.#",
- "#......#",
- "########"],
+ "map": [ "####EE######",
+ "#..........#",
+ "#..........#",
+ "#..........#",
+ "#..........#",
+ "#..........#",
+ "#.@........#",
+ "#..........E",
+ "#..........E",
+ "#.#..#.....#",
+ "#..........#",
+ "############"],
"n_to": "Kitchen",
"e_to": "Vehicle maintenance",
},
"Kitchen": {
- "map": [ "########",
- "#.c.c..#",
- "#...@..#",
- "#......#",
- "#......#",
- "#. .. .#",
- "#......#",
- "####E###"],
+ "map": [ "############",
+ "#.c.c......#",
+ "#...@......#",
+ "#..........#",
+ "#..........#",
+ "#..........#",
+ "#..........#",
+ "#..........#",
+ "#..........#",
+ "#. ...... .#",
+ "#..........#",
+ "####EE######"],
"s_to": "Entryway",
},
"Vehicle maintenance": {
- "map": [ "##EE####",
- "#... .##",
- "#......#",
- "####...#",
- "E .##..#",
- "#. .. .#",
- "#......#",
- "########"],
+ "map": [ "##EE########",
+ "#... .##",
+ "#..........#",
+ "#..........#",
+ "#..........#",
+ "####.......#",
+ "# .##......#",
+ "E..##... ..#",
+ "E..........#",
+ "#. .. .....#",
+ "#..........#",
+ "############"],
"w_to": "Entryway",
"n_to": "Service entrance",
},
"Service entrance": {
- "map": [ "########",
- "#... . #",
- "#......#",
- "# ##..#",
- "# .##..#",
- "#. .. .#",
- "#......#",
- "##EE####"],
+ "map": [ "############",
+ "#... ..... #",
+ "#..........#",
+ "#..........#",
+ "#..........#",
+ "# ##......#",
+ "# .##......#",
+ "#..........#",
+ "#..........#",
+ "#. ...... .#",
+ "#..........#",
+ "##EE########"],
"s_to": "Vehicle maintenance"
}
}; |
ce92a0aa82af24077f5b07fbdb8fa45f55918cb6 | polygerrit-ui/app/api/core.ts | polygerrit-ui/app/api/core.ts | /**
* @fileoverview Core API types for Gerrit.
*
* Core types are types used in many places in Gerrit, such as the Side enum.
*
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* 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.
*/
/**
* The CommentRange entity describes the range of an inline comment.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#comment-range
*/
export interface CommentRange {
start_line: number;
start_character: number;
end_line: number;
end_character: number;
}
| /**
* @fileoverview Core API types for Gerrit.
*
* Core types are types used in many places in Gerrit, such as the Side enum.
*
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* 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.
*/
/**
* The CommentRange entity describes the range of an inline comment.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#comment-range
*
* The range includes all characters from the start position, specified by
* start_line and start_character, to the end position, specified by end_line
* and end_character. The start position is inclusive and the end position is
* exclusive.
*
* So, a range over part of a line will have start_line equal to end_line;
* however a range with end_line set to 5 and end_character equal to 0 will not
* include any characters on line 5.
*/
export interface CommentRange {
/** The start line number of the range. (1-based) */
start_line: number;
/** The character position in the start line. (0-based) */
start_character: number;
/** The end line number of the range. (1-based) */
end_line: number;
/** The character position in the end line. (0-based) */
end_character: number;
}
| Add some more docs about the range type | Add some more docs about the range type
Change-Id: I0586d9b71a4581ef56b902668c1020374020a195
| TypeScript | apache-2.0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit | ---
+++
@@ -22,10 +22,26 @@
/**
* The CommentRange entity describes the range of an inline comment.
* https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#comment-range
+ *
+ * The range includes all characters from the start position, specified by
+ * start_line and start_character, to the end position, specified by end_line
+ * and end_character. The start position is inclusive and the end position is
+ * exclusive.
+ *
+ * So, a range over part of a line will have start_line equal to end_line;
+ * however a range with end_line set to 5 and end_character equal to 0 will not
+ * include any characters on line 5.
*/
export interface CommentRange {
+ /** The start line number of the range. (1-based) */
start_line: number;
+
+ /** The character position in the start line. (0-based) */
start_character: number;
+
+ /** The end line number of the range. (1-based) */
end_line: number;
+
+ /** The character position in the end line. (0-based) */
end_character: number;
} |
577ca4a636e10fcba64e7e0cee6a546c0676ceda | polygerrit-ui/app/services/flags/flags.ts | polygerrit-ui/app/services/flags/flags.ts | /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* 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 interface FlagsService {
isEnabled(experimentId: string): boolean;
enabledExperiments: string[];
}
/**
* @desc Experiment ids used in Gerrit.
*/
export enum KnownExperimentId {
NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui',
TOKEN_HIGHLIGHTING = 'UiFeature__token_highlighting',
CHECKS_DEVELOPER = 'UiFeature__checks_developer',
NEW_REPLY_DIALOG = 'UiFeature__new_reply_dialog',
SUBMIT_REQUIREMENTS_UI = 'UiFeature__submit_requirements_ui',
}
| /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* 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 interface FlagsService {
isEnabled(experimentId: string): boolean;
enabledExperiments: string[];
}
/**
* @desc Experiment ids used in Gerrit.
*/
export enum KnownExperimentId {
NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui',
TOKEN_HIGHLIGHTING = 'UiFeature__token_highlighting',
CHECKS_DEVELOPER = 'UiFeature__checks_developer',
SUBMIT_REQUIREMENTS_UI = 'UiFeature__submit_requirements_ui',
}
| Remove new reply dialog experiment from KnownExperimentId | Remove new reply dialog experiment from KnownExperimentId
Finish cleanup partially completed in Change 314493.
Change-Id: I6af29c343f2832d198b4c2520a1a1be58ef8e64b
| TypeScript | apache-2.0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit | ---
+++
@@ -27,6 +27,5 @@
NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui',
TOKEN_HIGHLIGHTING = 'UiFeature__token_highlighting',
CHECKS_DEVELOPER = 'UiFeature__checks_developer',
- NEW_REPLY_DIALOG = 'UiFeature__new_reply_dialog',
SUBMIT_REQUIREMENTS_UI = 'UiFeature__submit_requirements_ui',
} |
4a7e1619bf746e28665f93a50f9156c1f3bd2a51 | tests/setupTestFramework.ts | tests/setupTestFramework.ts | /* eslint-env jest */
import {
NodePath as NodePathConstructor,
astNodesAreEquivalent,
ASTNode,
} from 'ast-types';
import { NodePath } from 'ast-types/lib/node-path';
import diff from 'jest-diff';
import utils from 'jest-matcher-utils';
const matchers = {
toEqualASTNode: function (received: NodePath, expected: NodePath | ASTNode) {
if (!expected || typeof expected !== 'object') {
throw new Error(
'Expected value must be an object representing an AST node.\n' +
'Got ' +
expected +
'(' +
typeof expected +
') instead.',
);
}
// Use value here instead of node, as node has some magic and always returns
// the next Node it finds even if value is an array
const receivedNode = received.value;
let expectedNode = expected;
if (expected instanceof NodePathConstructor) {
expectedNode = expected.value;
}
return {
pass: astNodesAreEquivalent(receivedNode, expectedNode),
message: () => {
const diffString = diff(expectedNode, receivedNode);
return (
'Expected value to be (using ast-types):\n' +
` ${utils.printExpected(expectedNode)}\n` +
'Received:\n' +
` ${utils.printReceived(receivedNode)}` +
(diffString ? `\n\nDifference:\n\n${diffString}` : '')
);
},
};
},
};
expect.extend(matchers);
| /* eslint-env jest */
import {
NodePath as NodePathConstructor,
astNodesAreEquivalent,
ASTNode,
} from 'ast-types';
import { NodePath } from 'ast-types/lib/node-path';
import { diff } from 'jest-diff';
import { printExpected, printReceived } from 'jest-matcher-utils';
const matchers = {
toEqualASTNode: function (received: NodePath, expected: NodePath | ASTNode) {
if (!expected || typeof expected !== 'object') {
throw new Error(
'Expected value must be an object representing an AST node.\n' +
'Got ' +
expected +
'(' +
typeof expected +
') instead.',
);
}
// Use value here instead of node, as node has some magic and always returns
// the next Node it finds even if value is an array
const receivedNode = received.value;
let expectedNode = expected;
if (expected instanceof NodePathConstructor) {
expectedNode = expected.value;
}
return {
pass: astNodesAreEquivalent(receivedNode, expectedNode),
message: () => {
const diffString = diff(expectedNode, receivedNode);
return (
'Expected value to be (using ast-types):\n' +
` ${printExpected(expectedNode)}\n` +
'Received:\n' +
` ${printReceived(receivedNode)}` +
(diffString ? `\n\nDifference:\n\n${diffString}` : '')
);
},
};
},
};
expect.extend(matchers);
| Fix custom matcher for new jest version | chore: Fix custom matcher for new jest version
| TypeScript | mit | reactjs/react-docgen,reactjs/react-docgen,reactjs/react-docgen | ---
+++
@@ -6,8 +6,8 @@
ASTNode,
} from 'ast-types';
import { NodePath } from 'ast-types/lib/node-path';
-import diff from 'jest-diff';
-import utils from 'jest-matcher-utils';
+import { diff } from 'jest-diff';
+import { printExpected, printReceived } from 'jest-matcher-utils';
const matchers = {
toEqualASTNode: function (received: NodePath, expected: NodePath | ASTNode) {
@@ -37,9 +37,9 @@
return (
'Expected value to be (using ast-types):\n' +
- ` ${utils.printExpected(expectedNode)}\n` +
+ ` ${printExpected(expectedNode)}\n` +
'Received:\n' +
- ` ${utils.printReceived(receivedNode)}` +
+ ` ${printReceived(receivedNode)}` +
(diffString ? `\n\nDifference:\n\n${diffString}` : '')
);
}, |
f5083e9074bc14a289c01a3e869a9635bbd3c458 | src/Cache/InMemoryCache.ts | src/Cache/InMemoryCache.ts | import { ICache } from './ICache';
export class InMemoryCache implements ICache {
private cache = {};
public set(key: string, value: any): void {
this.cache[key] = value;
}
public get(key: string): any {
return this.cache[key];
}
public getBatch(keys: string[]): any[] {
return keys.map((key: string) => {
return this.cache[key];
});
}
public remove(key: string): void {
delete this.cache[key];
}
public reset(): void {
this.cache = {};
}
}
| import { ICache } from './ICache';
export class InMemoryCache implements ICache {
private cache = {};
public set(key: string, value: any): any {
this.cache[key] = value;
return value !== null && typeof value === 'object' ? Object.assign({}, value) : value;
}
public get(key: string): any {
const value = this.cache[key];
if (!value) {
return null;
}
return typeof value === 'object' ? Object.assign({}, value) : value;
}
public getBatch(keys: string[]): any[] {
return keys.map((key: string) => this.get(key));
}
public remove(key: string): void {
delete this.cache[key];
}
public reset(): void {
this.cache = {};
}
}
| Update in memory cache to return cloned objects | Update in memory cache to return cloned objects
| TypeScript | mit | sygic-travel/js-sdk,sygic-travel/js-sdk,sygic-travel/js-sdk | ---
+++
@@ -3,18 +3,21 @@
export class InMemoryCache implements ICache {
private cache = {};
- public set(key: string, value: any): void {
+ public set(key: string, value: any): any {
this.cache[key] = value;
+ return value !== null && typeof value === 'object' ? Object.assign({}, value) : value;
}
public get(key: string): any {
- return this.cache[key];
+ const value = this.cache[key];
+ if (!value) {
+ return null;
+ }
+ return typeof value === 'object' ? Object.assign({}, value) : value;
}
public getBatch(keys: string[]): any[] {
- return keys.map((key: string) => {
- return this.cache[key];
- });
+ return keys.map((key: string) => this.get(key));
}
public remove(key: string): void { |
d5f285e74ed5d448d7f506b8a03610bcc8af9981 | src/server/src/healthcheck/topology-loaded.indicator.ts | src/server/src/healthcheck/topology-loaded.indicator.ts | import { Injectable } from "@nestjs/common";
import { HealthIndicator, HealthIndicatorResult, HealthCheckError } from "@nestjs/terminus";
import { TopologyService } from "../districts/services/topology.service";
@Injectable()
export default class TopologyLoadedIndicator extends HealthIndicator {
constructor(public topologyService: TopologyService) {
super();
}
async isHealthy(key: string): Promise<HealthIndicatorResult> {
const layers = this.topologyService.layers();
if (layers === undefined) {
const result = this.getStatus(key, false, {});
throw new HealthCheckError("Topology layers not intialized", result);
}
const layerEntries = (await Promise.all(
Object.entries(layers).map(([layerId, topology]) => {
return new Promise((resolve, reject) => {
// Promise.race should return the first already resolved promise
// immediately when provided at least one, so this shouldn't block
void Promise.race([topology, Promise.resolve(undefined)]).then(topology => {
resolve([layerId, topology !== undefined]);
});
});
})
)) as [string, boolean][];
const layerStatus = Object.fromEntries(layerEntries);
const isHealthy = Object.values(layerStatus).every(status => status);
const result = this.getStatus(key, isHealthy, layerStatus);
if (isHealthy) {
return result;
}
throw new HealthCheckError("Topology not fully loaded", result);
}
}
| import { Injectable } from "@nestjs/common";
import { HealthIndicator, HealthIndicatorResult, HealthCheckError } from "@nestjs/terminus";
import { TopologyService } from "../districts/services/topology.service";
@Injectable()
export default class TopologyLoadedIndicator extends HealthIndicator {
constructor(public topologyService: TopologyService) {
super();
}
async isHealthy(key: string): Promise<HealthIndicatorResult> {
const layers = this.topologyService.layers();
if (layers === undefined) {
const result = this.getStatus(key, false, {});
throw new HealthCheckError("Topology layers not intialized", result);
}
const layerEntries = (await Promise.all(
Object.entries(layers).map(([layerId, topology]) => {
return new Promise((resolve, reject) => {
// Promise.race should return the first already resolved promise
// immediately when provided at least one, so this shouldn't block
void Promise.race([topology, Promise.resolve(undefined)]).then(topology => {
resolve([layerId, topology !== undefined]);
});
});
})
)) as [string, boolean][];
const isHealthy = layerEntries.every(([_, status]) => status);
const pendingLayers = layerEntries.filter(([_, status]) => !status).map(([layer, _]) => layer);
const result = this.getStatus(key, isHealthy, {
total: layerEntries.length,
complete: layerEntries.length - pendingLayers.length,
pendingLayers
});
if (isHealthy) {
return result;
}
throw new HealthCheckError("Topology not fully loaded", result);
}
}
| Clean up health check output to be less verbose | Clean up health check output to be less verbose
| TypeScript | apache-2.0 | PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder | ---
+++
@@ -27,9 +27,14 @@
});
})
)) as [string, boolean][];
- const layerStatus = Object.fromEntries(layerEntries);
- const isHealthy = Object.values(layerStatus).every(status => status);
- const result = this.getStatus(key, isHealthy, layerStatus);
+
+ const isHealthy = layerEntries.every(([_, status]) => status);
+ const pendingLayers = layerEntries.filter(([_, status]) => !status).map(([layer, _]) => layer);
+ const result = this.getStatus(key, isHealthy, {
+ total: layerEntries.length,
+ complete: layerEntries.length - pendingLayers.length,
+ pendingLayers
+ });
if (isHealthy) {
return result; |
40da9ada036a5692c9863cddd0d25e75d1430f4c | src/Config/ProxyHandlerConfig.ts | src/Config/ProxyHandlerConfig.ts | import { HandlerConfig } from './HandlerConfig';
/**
* Configuration settings for a Handler object.
*/
export interface ProxyHandlerConfig extends HandlerConfig {
/**
* Remote root path where the request will be redirected. Defaults to '/'. e.g.
*/
remotePath?: string;
/**
* Name of the Path Parameter on the AWS request that contains the path of the request. This will default to `path`
* if not specified.
*/
pathParameterName?: string;
/**
* Whatever the request should be handle over HTTPS. Default to true.
*/
ssl?: boolean;
/**
* Remote Port where the request should be directed. Defaults to 443 for HTTPS request and 80 for HTTP request.
*/
remotePort?: number;
/**
* whatever OPTIONS request should be process locally. If set to `true`, pre-flight OPTIONS request will be handle
* locally. An empty response will be sent and the cors headers will be defined via the HandlerConfig options.
*
* If set to false, the the request will be relayed to the remtoe server.
*
* Defaults to true.
*/
processOptionsLocally?: boolean;
/**
* List of headers that should be copied over from the original request to the proxy request.
*/
whiteListedHeader?: string[];
}
| import { HandlerConfig } from './HandlerConfig';
/**
* Configuration settings for a Handler object.
*/
export interface ProxyHandlerConfig extends HandlerConfig {
/**
* Remote root path where the request will be redirected. Defaults to '/'. e.g.
*/
baseUrl?: string;
/**
* Name of the Path Parameter on the AWS request that contains the path of the request. This will default to `path`
* if not specified.
*/
pathParameterName?: string;
/**
* Whatever the request should be handle over HTTPS. Default to true.
*/
ssl?: boolean;
/**
* Remote Port where the request should be directed. Defaults to 443 for HTTPS request and 80 for HTTP request.
*/
port?: number;
/**
* whatever OPTIONS request should be process locally. If set to `true`, pre-flight OPTIONS request will be handle
* locally. An empty response will be sent and the cors headers will be defined via the HandlerConfig options.
*
* If set to false, the the request will be relayed to the remtoe server.
*
* Defaults to true.
*/
processOptionsLocally?: boolean;
/**
* List of headers that should be copied over from the original request to the proxy request.
*/
whiteListedHeader?: string[];
}
| Tweak the config to reflect the fact we are using the request library rather than the native node one. | Tweak the config to reflect the fact we are using the request library rather than the native node one.
| TypeScript | mit | syrp-nz/ts-lambda-handler,syrp-nz/ts-lambda-handler | ---
+++
@@ -8,7 +8,7 @@
/**
* Remote root path where the request will be redirected. Defaults to '/'. e.g.
*/
- remotePath?: string;
+ baseUrl?: string;
/**
* Name of the Path Parameter on the AWS request that contains the path of the request. This will default to `path`
@@ -24,7 +24,7 @@
/**
* Remote Port where the request should be directed. Defaults to 443 for HTTPS request and 80 for HTTP request.
*/
- remotePort?: number;
+ port?: number;
/**
* whatever OPTIONS request should be process locally. If set to `true`, pre-flight OPTIONS request will be handle
@@ -41,5 +41,4 @@
*/
whiteListedHeader?: string[];
-
} |
0c5272ac6ad4f64f85ec49a331fd9c5d9a64ff18 | lib/index.ts | lib/index.ts | import * as auto from 'autocreate';
import * as debug from 'debug';
import { Client } from './client';
import { BasiqAPIOptions } from './interfaces';
import { Account } from './resources/accounts';
import { Connection } from './resources/connections';
import { Institution } from './resources/institutions';
import { Transaction } from './resources/transactions';
const log = debug('basiq-api');
const resources = {
connections: Connection,
accounts: Account,
transactions: Transaction,
institutions: Institution,
};
const Basiq = auto(class BasiqAPI {
protected _client: Client;
constructor(options: BasiqAPIOptions) {
const client = new Client(options);
// log('Adding client', client);
Object.defineProperty(this, '_client', {
value: client,
writable: false,
enumerable: false,
configurable: false,
});
Object.keys(resources)
.forEach((resource: string) => {
// log('Adding property', resource, this);
Object.defineProperty(this, resource, {
value: new resources[resource](this._client),
writable: true,
enumerable: false,
configurable: true,
});
});
}
});
export {
BasiqAPIOptions,
AuthenticationOptions,
ConnectionCreateOptions,
ConnectionUpdateOptions,
BasiqResponse,
BasiqPromise,
} from './interfaces';
export { Basiq };
| import * as debug from 'debug';
import { Client } from './client';
import { BasiqAPIOptions } from './interfaces';
import { Account } from './resources/accounts';
import { Connection } from './resources/connections';
import { Institution } from './resources/institutions';
import { Transaction } from './resources/transactions';
const log = debug('basiq-api');
const resources = {
connections: Connection,
accounts: Account,
transactions: Transaction,
institutions: Institution,
};
class Basiq {
public accounts: Account;
public connections: Connection;
public transactions: Transaction;
public institutions: Institution;
protected _client: Client;
constructor(options: BasiqAPIOptions) {
if (this instanceof Basiq) {
const client = new Client(options);
// log('Adding client', client);
Object.defineProperty(this, '_client', {
value: client,
writable: false,
enumerable: false,
configurable: false,
});
Object.keys(resources)
.forEach((resource: string) => {
// log('Adding property', resource, this);
Object.defineProperty(this, resource, {
value: new resources[resource](this._client),
writable: true,
enumerable: false,
configurable: true,
});
});
} else {
return new Basiq(options);
}
}
}
export {
BasiqAPIOptions,
AuthenticationOptions,
ConnectionCreateOptions,
ConnectionUpdateOptions,
BasiqResponse,
BasiqPromise,
} from './interfaces';
export { Basiq };
| Remove autocreate dependency and output resource types | Remove autocreate dependency and output resource types
| TypeScript | bsd-2-clause | FluentDevelopment/basiq-api | ---
+++
@@ -1,4 +1,3 @@
-import * as auto from 'autocreate';
import * as debug from 'debug';
import { Client } from './client';
@@ -17,33 +16,46 @@
institutions: Institution,
};
-const Basiq = auto(class BasiqAPI {
+class Basiq {
+
+ public accounts: Account;
+
+ public connections: Connection;
+
+ public transactions: Transaction;
+
+ public institutions: Institution;
+
protected _client: Client;
constructor(options: BasiqAPIOptions) {
- const client = new Client(options);
+ if (this instanceof Basiq) {
+ const client = new Client(options);
- // log('Adding client', client);
- Object.defineProperty(this, '_client', {
- value: client,
- writable: false,
- enumerable: false,
- configurable: false,
- });
+ // log('Adding client', client);
+ Object.defineProperty(this, '_client', {
+ value: client,
+ writable: false,
+ enumerable: false,
+ configurable: false,
+ });
- Object.keys(resources)
- .forEach((resource: string) => {
- // log('Adding property', resource, this);
- Object.defineProperty(this, resource, {
- value: new resources[resource](this._client),
- writable: true,
- enumerable: false,
- configurable: true,
+ Object.keys(resources)
+ .forEach((resource: string) => {
+ // log('Adding property', resource, this);
+ Object.defineProperty(this, resource, {
+ value: new resources[resource](this._client),
+ writable: true,
+ enumerable: false,
+ configurable: true,
+ });
});
- });
+ } else {
+ return new Basiq(options);
+ }
}
-});
+}
export {
BasiqAPIOptions, |
7ac5d91a4892112fe8b041a39d3610764e32b02a | test/unittests/front_end/sdk/Issue_test.ts | test/unittests/front_end/sdk/Issue_test.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const {assert} = chai;
import {Issue, AggregatedIssue} from '../../../../front_end/sdk/Issue.js';
import {StubIssue} from './StubIssue.js';
describe('Issue', () => {
it('should always require a code', () => {
const issue = new Issue('code');
assert.strictEqual(issue.code(), 'code');
});
});
describe('AggregateIssue', () => {
it('deduplicates network requests across issues', () => {
const issue1 = new StubIssue(['id1', 'id2'], []);
const issue2 = new StubIssue(['id1'], []);
const aggregatedIssue = new AggregatedIssue('code');
aggregatedIssue.addInstance(issue1);
aggregatedIssue.addInstance(issue2);
const actualRequestIds = [...aggregatedIssue.requests()].map(r => r.requestId).sort();
assert.deepStrictEqual(actualRequestIds, ['id1', 'id2']);
});
});
| // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const {assert} = chai;
import {Issue, AggregatedIssue} from '../../../../front_end/sdk/Issue.js';
import {StubIssue} from './StubIssue.js';
describe('Issue', () => {
it('should always require a code', () => {
const issue = new Issue('code');
assert.strictEqual(issue.code(), 'code');
});
});
describe('AggregateIssue', () => {
it('deduplicates network requests across issues', () => {
const issue1 = new StubIssue(['id1', 'id2'], []);
const issue2 = new StubIssue(['id1'], []);
const aggregatedIssue = new AggregatedIssue('code');
aggregatedIssue.addInstance(issue1);
aggregatedIssue.addInstance(issue2);
const actualRequestIds = [...aggregatedIssue.requests()].map(r => r.requestId).sort();
assert.deepStrictEqual(actualRequestIds, ['id1', 'id2']);
});
it('deduplicates affected cookies across issues', () => {
const issue1 = new StubIssue([], ['cookie1']);
const issue2 = new StubIssue([], ['cookie2']);
const issue3 = new StubIssue([], ['cookie1', 'cookie2']);
const aggregatedIssue = new AggregatedIssue('code');
aggregatedIssue.addInstance(issue1);
aggregatedIssue.addInstance(issue2);
aggregatedIssue.addInstance(issue3);
const actualCookieNames = [...aggregatedIssue.cookies()].map(c => c.name).sort();
assert.deepStrictEqual(actualCookieNames, ['cookie1', 'cookie2']);
});
});
| Add test for de-duplication of cookies in AggregatedIssue | [issues] Add test for de-duplication of cookies in AggregatedIssue
R=f04d242e109628a27a0f75fd49a87722bcf291fd@chromium.org
Change-Id: Ia13d8ad4d0bd55ac139221db05ed00076da37b40
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2160940
Commit-Queue: Simon Zünd <38944668e9e2ca98ccd0275b53370f90fa55c113@chromium.org>
Auto-Submit: Simon Zünd <38944668e9e2ca98ccd0275b53370f90fa55c113@chromium.org>
Reviewed-by: Sigurd Schneider <f04d242e109628a27a0f75fd49a87722bcf291fd@chromium.org>
| TypeScript | bsd-3-clause | ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend | ---
+++
@@ -26,4 +26,18 @@
const actualRequestIds = [...aggregatedIssue.requests()].map(r => r.requestId).sort();
assert.deepStrictEqual(actualRequestIds, ['id1', 'id2']);
});
+
+ it('deduplicates affected cookies across issues', () => {
+ const issue1 = new StubIssue([], ['cookie1']);
+ const issue2 = new StubIssue([], ['cookie2']);
+ const issue3 = new StubIssue([], ['cookie1', 'cookie2']);
+
+ const aggregatedIssue = new AggregatedIssue('code');
+ aggregatedIssue.addInstance(issue1);
+ aggregatedIssue.addInstance(issue2);
+ aggregatedIssue.addInstance(issue3);
+
+ const actualCookieNames = [...aggregatedIssue.cookies()].map(c => c.name).sort();
+ assert.deepStrictEqual(actualCookieNames, ['cookie1', 'cookie2']);
+ });
}); |
78fa7ce3c1bee3d040f7c193fd92b62871de8626 | src/main/ts/talks.ts | src/main/ts/talks.ts | class TalksCtrl{
constructor() {
// const favoriteButtons = document.getElementsByClassName('mxt-img--favorite');
// Array.from(favoriteButtons).forEach((favoriteButton: HTMLElement) => favoriteButton.onclick= this.favoriteToggle);
}
favoriteToggle(event) {
const img = event.srcElement;
const email = <HTMLInputElement> document.getElementById('email');
event.stopPropagation();
fetch(`/api/favorites/${email.value}/talks/${img.id.substr(9,img.id.length)}/toggle`, {method: 'post'})
.then(response => response.json())
.then((json: any) => {
const imgPath = json.selected ? 'mxt-favorite.svg' : 'mxt-favorite-non.svg';
img.src = `/images/svg/favorites/${imgPath}`;
});
}
}
window.addEventListener("load", () => window['ctrl'] = new TalksCtrl()); | class TalksCtrl{
constructor() {
// const favoriteButtons = document.getElementsByClassName('mxt-img--favorite');
// Array.from(favoriteButtons).forEach((favoriteButton: HTMLElement) => favoriteButton.onclick= this.favoriteToggle);
}
favoriteToggle(event) {
const img = event.srcElement;
const email = <HTMLInputElement> document.getElementById('email');
fetch(`/api/favorites/${email.value}/talks/${img.id.substr(9,img.id.length)}/toggle`, {method: 'post'})
.then(response => response.json())
.then((json: any) => {
const imgPath = json.selected ? 'mxt-favorite.svg' : 'mxt-favorite-non.svg';
img.src = `/images/svg/favorites/${imgPath}`;
});
}
}
window.addEventListener("load", () => window['ctrl'] = new TalksCtrl()); | Fix top page redirection when user updates a favorite talk | Fix top page redirection when user updates a favorite talk
| TypeScript | apache-2.0 | mix-it/mixit,mixitconf/mixit,mixitconf/mixit,mixitconf/mixit,mix-it/mixit,mixitconf/mixit,mix-it/mixit,mix-it/mixit,mix-it/mixit | ---
+++
@@ -8,7 +8,6 @@
favoriteToggle(event) {
const img = event.srcElement;
const email = <HTMLInputElement> document.getElementById('email');
- event.stopPropagation();
fetch(`/api/favorites/${email.value}/talks/${img.id.substr(9,img.id.length)}/toggle`, {method: 'post'})
.then(response => response.json()) |
0db9ed24822374fcbfc4cd1a6d93b596a6f04531 | src/demo.tsx | src/demo.tsx | import * as React from 'react'
import * as ReactDOM from 'react-dom'
import DatePicker from 'react-datepicker'
import insertCss from 'insert-css'
import { IntlProvider, addLocaleData } from 'react-intl'
import de from 'react-intl/locale-data/de'
import 'moment/locale/de-ch'
import intlMessages from './intlMessages'
import { css, Locale, Day, Environment, Model, PeriodOfStayInput } from './index'
addLocaleData(de)
const environment = new Environment(true, new Day('1979-11-16'))
class Container extends React.Component<{}, State> {
constructor(props: any) {
super(props)
this.state = {
model: new Model(new Day('1979-11-16'), new Day('1979-11-17'))
}
}
render() {
return (
<IntlProvider locale='de' messages={intlMessages().de}>
<PeriodOfStayInput
locale={Locale.DE}
environment={environment}
model={this.state.model}
onChange={model => { this.setState({ model }) }} />
</IntlProvider>
)
}
}
interface State { model: Model }
insertCss(css)
ReactDOM.render(
<Container />,
document.getElementById('root')
)
| import * as React from 'react'
import * as ReactDOM from 'react-dom'
import insertCss from 'insert-css'
import { IntlProvider, addLocaleData } from 'react-intl'
import de from 'react-intl/locale-data/de'
import 'moment/locale/de-ch'
import intlMessages from './intlMessages'
import { css, Locale, Day, Environment, Model, PeriodOfStayInput } from './index'
addLocaleData(de)
const environment = new Environment(true, new Day('1979-11-16'))
class Container extends React.Component<{}, State> {
constructor(props: any) {
super(props)
this.state = {
model: new Model(new Day('1979-11-16'), new Day('1979-11-17'))
}
}
render() {
return (
<IntlProvider locale='de' messages={intlMessages().de}>
<PeriodOfStayInput
locale={Locale.DE}
environment={environment}
model={this.state.model}
onChange={model => { this.setState({ model }) }} />
</IntlProvider>
)
}
}
interface State { model: Model }
insertCss(css)
ReactDOM.render(
<Container />,
document.getElementById('root')
)
| Remove the obsolete DatePicker import | Remove the obsolete DatePicker import
| TypeScript | mit | ikr/react-period-of-stay-input,ikr/react-period-of-stay-input,ikr/react-period-of-stay-input | ---
+++
@@ -1,6 +1,5 @@
import * as React from 'react'
import * as ReactDOM from 'react-dom'
-import DatePicker from 'react-datepicker'
import insertCss from 'insert-css'
import { IntlProvider, addLocaleData } from 'react-intl'
import de from 'react-intl/locale-data/de' |
e31c9c2478929557f399b3e8b6e213305acbeb7b | app/services/users/user-service.ts | app/services/users/user-service.ts | import {Component} from 'angular2/angular2';
import {Http, HTTP_PROVIDERS, Headers, Response} from 'angular2/http';
import {AuthService} from './auth-service';
import {User} from './user';
@Component({
providers: [Http, HTTP_PROVIDERS]
})
export class UserService {
public users;
constructor(public http:Http, public auth:AuthService) {
};
getUsers() {
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.auth.accessToken);
var request = this.http.get('http://localhost:8000/user/',
{headers:headers}
);
request.subscribe(
(res:Response) => console.log(res.json()),
err => console.log('Erreur sur la récupération des utilisateurs')
);
return request;
}
}
| import {Component} from 'angular2/angular2';
import {Http, HTTP_PROVIDERS, Headers, Response} from 'angular2/http';
import {AuthService} from './auth-service';
import {User} from './user';
@Component({
providers: [Http, HTTP_PROVIDERS]
})
export class UserService {
public users;
constructor(public http:Http, public auth:AuthService) {
};
getUsers() {
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.auth.accessToken);
headers.append('Accept', 'application/json');
var request = this.http.get('http://localhost:8000/user/',
{headers:headers}
);
request.subscribe(
(res:Response) => console.log(res.json()),
err => console.log('Erreur sur la récupération des utilisateurs')
);
return request;
}
}
| Add a header to retrieve the data in json format rather than the whole html page | Add a header to retrieve the data in json format rather than the whole html page
| TypeScript | agpl-3.0 | ProjetSigma/frontend,ProjetSigma/frontend,ProjetSigma/frontend | ---
+++
@@ -15,6 +15,7 @@
getUsers() {
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.auth.accessToken);
+ headers.append('Accept', 'application/json');
var request = this.http.get('http://localhost:8000/user/',
{headers:headers} |
81b6ca90909c72306e9640a4ce087d7fcf192806 | app/src/ui/delete-branch/index.tsx | app/src/ui/delete-branch/index.tsx | import * as React from 'react'
import { Dispatcher } from '../../lib/dispatcher'
import { Repository } from '../../models/repository'
import { Branch } from '../../models/branch'
import { Button } from '../lib/button'
import { ButtonGroup } from '../lib/button-group'
import { Dialog, DialogContent, DialogFooter } from '../dialog'
interface IDeleteBranchProps {
readonly dispatcher: Dispatcher
readonly repository: Repository
readonly branch: Branch
readonly onDismissed: () => void
}
export class DeleteBranch extends React.Component<IDeleteBranchProps, void> {
public render() {
return (
<Dialog
id='delete-branch'
title={__DARWIN__ ? 'Delete Branch' : 'Delete branch'}
type='warning'
onDismissed={this.props.onDismissed}
>
<DialogContent>
<div>Delete branch "{this.props.branch.name}"?</div>
<div>This cannot be undone.</div>
</DialogContent>
<DialogFooter>
<ButtonGroup>
<Button type='submit'>Cancel</Button>
<Button onClick={this.deleteBranch}>Delete</Button>
</ButtonGroup>
</DialogFooter>
</Dialog>
)
}
private deleteBranch = () => {
this.props.dispatcher.deleteBranch(this.props.repository, this.props.branch)
this.props.dispatcher.closePopup()
}
}
| import * as React from 'react'
import { Dispatcher } from '../../lib/dispatcher'
import { Repository } from '../../models/repository'
import { Branch } from '../../models/branch'
import { Button } from '../lib/button'
import { ButtonGroup } from '../lib/button-group'
import { Dialog, DialogContent, DialogFooter } from '../dialog'
interface IDeleteBranchProps {
readonly dispatcher: Dispatcher
readonly repository: Repository
readonly branch: Branch
readonly onDismissed: () => void
}
export class DeleteBranch extends React.Component<IDeleteBranchProps, void> {
public render() {
return (
<Dialog
id='delete-branch'
title={__DARWIN__ ? 'Delete Branch' : 'Delete branch'}
type='warning'
onDismissed={this.props.onDismissed}
>
<DialogContent>
<p>Delete branch "{this.props.branch.name}"?</p>
<p>This cannot be undone.</p>
</DialogContent>
<DialogFooter>
<ButtonGroup>
<Button type='submit'>Cancel</Button>
<Button onClick={this.deleteBranch}>Delete</Button>
</ButtonGroup>
</DialogFooter>
</Dialog>
)
}
private deleteBranch = () => {
this.props.dispatcher.deleteBranch(this.props.repository, this.props.branch)
this.props.dispatcher.closePopup()
}
}
| Use paragraphs, as the good documentation suggests | Use paragraphs, as the good documentation suggests
| TypeScript | mit | desktop/desktop,hjobrien/desktop,gengjiawen/desktop,say25/desktop,artivilla/desktop,hjobrien/desktop,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,j-f1/forked-desktop,artivilla/desktop,gengjiawen/desktop,kactus-io/kactus,j-f1/forked-desktop,gengjiawen/desktop,BugTesterTest/desktops,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,BugTesterTest/desktops,shiftkey/desktop,gengjiawen/desktop,BugTesterTest/desktops,artivilla/desktop,BugTesterTest/desktops,desktop/desktop,hjobrien/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,kactus-io/kactus,kactus-io/kactus,desktop/desktop,hjobrien/desktop,say25/desktop,shiftkey/desktop | ---
+++
@@ -24,8 +24,8 @@
onDismissed={this.props.onDismissed}
>
<DialogContent>
- <div>Delete branch "{this.props.branch.name}"?</div>
- <div>This cannot be undone.</div>
+ <p>Delete branch "{this.props.branch.name}"?</p>
+ <p>This cannot be undone.</p>
</DialogContent>
<DialogFooter>
<ButtonGroup> |
09816540072664c56b4874a947c41078f2513238 | src/services/DeviceService.ts | src/services/DeviceService.ts | import winston from 'winston';
import DeviceModel from '../models/device';
export default class DeviceService {
// region public static methods
public static async addDevice(platform: string, mail: string, token: string) {
let device = await DeviceModel.findOne({ platform, mail });
if (!device) {
device = new DeviceModel({
platform,
mail,
tokens: [],
});
await device.save();
}
if (device.tokens.indexOf(token) !== -1) {
const errorMessage = `Could not add Device: Device (platform: ${platform}, mail: ${mail},
token: ${token}) already exists.`;
winston.error(errorMessage);
throw new Error(errorMessage);
}
device.tokens.push(token);
await device.save();
}
public static async getDevices(platform: string, mail: string): Promise<string[]> {
const device = await DeviceModel.findOne({ platform, mail });
if (!device) {
return new Promise<string[]>((resolve) => {
resolve([]);
});
}
return device.tokens;
}
// endregion
// region private static methods
// endregion
// region public members
// endregion
// region private members
// endregion
// region constructor
// endregion
// region public methods
// endregion
// region private methods
// endregion
}
| import winston from 'winston';
import DeviceModel from '../models/device';
export default class DeviceService {
// region public static methods
public static async addDevice(platform: string, mail: string, token: string) {
let device = await DeviceModel.findOne({ platform, mail });
if (!device) {
device = new DeviceModel({
platform,
mail,
tokens: [],
});
await device.save();
}
if (device.tokens.indexOf(token) !== -1) {
const errorMessage = `Could not add Device: Device (platform: ${platform}, mail: ${mail},
token: ${token}) already exists.`;
winston.error(errorMessage);
throw new Error(errorMessage);
}
device.tokens.push(token);
await device.save();
}
public static async getDevices(platform: string, mail: string): Promise<string[]> {
const device = await DeviceModel.findOne({ platform, mail });
if (!device) {
return [];
}
return device.tokens;
}
// endregion
// region private static methods
// endregion
// region public members
// endregion
// region private members
// endregion
// region constructor
// endregion
// region public methods
// endregion
// region private methods
// endregion
}
| Use more simple way to return an empty array | Use more simple way to return an empty array
| TypeScript | mit | schulcloud/node-notification-service,schulcloud/node-notification-service,schulcloud/node-notification-service | ---
+++
@@ -28,9 +28,7 @@
public static async getDevices(platform: string, mail: string): Promise<string[]> {
const device = await DeviceModel.findOne({ platform, mail });
if (!device) {
- return new Promise<string[]>((resolve) => {
- resolve([]);
- });
+ return [];
}
return device.tokens; |
5f1fe6835ddf51f4ea9155bde855e947e8063985 | src/components/BlockList/EmptyBlockList.tsx | src/components/BlockList/EmptyBlockList.tsx | import * as React from 'react';
import { connect, Dispatch } from 'react-redux';
import { changeTab } from '../../actions/updateValue';
import { Button } from '@shopify/polaris';
import { NonIdealState } from '@blueprintjs/core';
export interface Handlers {
onChangeTab: () => void;
}
// tslint:disable:jsx-curly-spacing
const EmptyQueue = ({ onChangeTab }: Handlers) => {
return (
<NonIdealState
title="Your blocklists are empty."
description="You can manage your block lists here once you've blocked a HIT or a requester."
visual="add-to-folder"
action={
<Button primary onClick={onChangeTab}>
Switch to search tab
</Button>
}
/>
);
};
const mapDispatch = (dispatch: Dispatch): Handlers => ({
onChangeTab: () => dispatch(changeTab(0))
});
export default connect(null, mapDispatch)(EmptyQueue);
| import * as React from 'react';
import { connect, Dispatch } from 'react-redux';
import { changeTab } from '../../actions/updateValue';
import { Button } from '@shopify/polaris';
import { NonIdealState } from '@blueprintjs/core';
import { TabIndex } from 'constants/enums';
export interface Handlers {
onChangeTab: () => void;
}
// tslint:disable:jsx-curly-spacing
const EmptyQueue = ({ onChangeTab }: Handlers) => {
return (
<NonIdealState
title="Your blocklists are empty."
description="You can manage your block lists here once you've blocked a HIT or a requester."
visual="add-to-folder"
action={
<Button primary onClick={onChangeTab}>
Switch to search tab
</Button>
}
/>
);
};
const mapDispatch = (dispatch: Dispatch): Handlers => ({
onChangeTab: () => dispatch(changeTab(TabIndex.SEARCH))
});
export default connect(null, mapDispatch)(EmptyQueue);
| Use TabIndex.SEARCH instead of 0. | Use TabIndex.SEARCH instead of 0.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -3,6 +3,7 @@
import { changeTab } from '../../actions/updateValue';
import { Button } from '@shopify/polaris';
import { NonIdealState } from '@blueprintjs/core';
+import { TabIndex } from 'constants/enums';
export interface Handlers {
onChangeTab: () => void;
@@ -25,7 +26,7 @@
};
const mapDispatch = (dispatch: Dispatch): Handlers => ({
- onChangeTab: () => dispatch(changeTab(0))
+ onChangeTab: () => dispatch(changeTab(TabIndex.SEARCH))
});
export default connect(null, mapDispatch)(EmptyQueue); |
d3cb7dd14cb91d379836c1e93226d1ac56942f0c | src/index.ts | src/index.ts | import LocalTimeElement from './local-time-element'
import RelativeTimeElement from './relative-time-element'
import TimeAgoElement from './time-ago-element'
import TimeUntilElement from './time-until-element'
export {LocalTimeElement, RelativeTimeElement, TimeAgoElement, TimeUntilElement}
| import LocalTimeElement from './local-time-element.js'
import RelativeTimeElement from './relative-time-element.js'
import TimeAgoElement from './time-ago-element.js'
import TimeUntilElement from './time-until-element.js'
export {LocalTimeElement, RelativeTimeElement, TimeAgoElement, TimeUntilElement}
| Add file extensions to imports for ES Module support | Add file extensions to imports for ES Module support
| TypeScript | mit | github/time-elements,github/time-elements | ---
+++
@@ -1,6 +1,6 @@
-import LocalTimeElement from './local-time-element'
-import RelativeTimeElement from './relative-time-element'
-import TimeAgoElement from './time-ago-element'
-import TimeUntilElement from './time-until-element'
+import LocalTimeElement from './local-time-element.js'
+import RelativeTimeElement from './relative-time-element.js'
+import TimeAgoElement from './time-ago-element.js'
+import TimeUntilElement from './time-until-element.js'
export {LocalTimeElement, RelativeTimeElement, TimeAgoElement, TimeUntilElement} |
2f4edc859e979dbb199d2cb1a97a3878dbfc7acf | src/index.ts | src/index.ts | import * as app from 'app';
import * as BrowserWindow from 'browser-window';
import * as Menu from 'menu';
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('ready', () => {
let mainWindow = new BrowserWindow({
width: 800,
height: 600,
title: 'Disskey',
frame: false,
show: false,
icon: './img/icon.png'
});
mainWindow.on('closed', () => {
mainWindow = null;
});
Menu.setApplicationMenu(Menu.buildFromTemplate([{
label: 'View',
submenu: [{
label: 'Reload',
accelerator: 'Ctrl+R',
click: () => mainWindow.reload()
}, {
label: 'Toggle &Developer Tools',
accelerator: 'Ctrl+Shift+I',
click: () => mainWindow.toggleDevTools()
}]
}]));
mainWindow.loadUrl(`file://${__dirname}/main/main.html`);
});
| import * as app from 'app';
import * as BrowserWindow from 'browser-window';
import * as Menu from 'menu';
if (process.platform !== 'darwin') {
app.on('window-all-closed', () => app.quit());
}
app.on('ready', () => {
let mainWindow = new BrowserWindow({
width: 800,
height: 600,
title: 'Disskey',
frame: false,
show: false,
icon: './img/icon.png'
});
mainWindow.on('closed', () => {
mainWindow = null;
});
Menu.setApplicationMenu(Menu.buildFromTemplate([{
label: 'View',
submenu: [{
label: 'Reload',
accelerator: 'Ctrl+R',
click: () => mainWindow.reload()
}, {
label: 'Toggle &Developer Tools',
accelerator: 'Ctrl+Shift+I',
click: () => mainWindow.toggleDevTools()
}]
}]));
mainWindow.loadUrl(`file://${__dirname}/main/main.html`);
});
| Check if platform is not darwin before adding listener | Check if platform is not darwin before adding listener
| TypeScript | mit | AyaMorisawa/Disskey,AyaMorisawa/Disskey,AyaMorisawa/Disskey | ---
+++
@@ -2,11 +2,9 @@
import * as BrowserWindow from 'browser-window';
import * as Menu from 'menu';
-app.on('window-all-closed', () => {
- if (process.platform !== 'darwin') {
- app.quit();
- }
-});
+if (process.platform !== 'darwin') {
+ app.on('window-all-closed', () => app.quit());
+}
app.on('ready', () => {
let mainWindow = new BrowserWindow({ |
5025b59b68d21384f5bdf7b48bd457b4fffbf94e | apprun-jsx/vdom.ts | apprun-jsx/vdom.ts | /// <reference path="../virtual-dom.d.ts" />
import h = require('virtual-dom/h');
import patch = require('virtual-dom/patch');
import diff = require('virtual-dom/diff');
import VNode = require('virtual-dom/vnode/vnode');
import VText = require('virtual-dom/vnode/vtext');
import createElement = require('virtual-dom/create-element');
import virtualize = require('vdom-virtualize');
export function updateElement(element, vtree) {
console.assert(!!element);
if (element.firstChild) {
const prev = element.firstChild.vtree || virtualize(element.firstChild);
const patches = diff(prev, vtree);
patch(element.firstChild, patches);
} else {
const node = createElement(vtree);
element.appendChild(node);
}
element.firstChild.vtree = vtree;
}
export function updateElementVtree(element) {
console.assert(!!element);
if (element.firstChild) {
element.firstChild.vtree = virtualize(element.firstChild);
}
}
import app from '../app';
app.h = (el, props, ...children) => h(el, props, children);
app.createElement = app.h; | /// <reference path="../virtual-dom.d.ts" />
import h = require('virtual-dom/h');
import patch = require('virtual-dom/patch');
import diff = require('virtual-dom/diff');
import VNode = require('virtual-dom/vnode/vnode');
import VText = require('virtual-dom/vnode/vtext');
import createElement = require('virtual-dom/create-element');
import virtualize = require('vdom-virtualize');
export function updateElement(element, vtree) {
console.assert(!!element);
if (element.firstChild) {
const prev = element.firstChild.vtree || virtualize(element.firstChild);
const patches = diff(prev, vtree);
patch(element.firstChild, patches);
} else {
const node = createElement(vtree);
element.appendChild(node);
}
element.firstChild.vtree = vtree;
}
export function updateElementVtree(element) {
console.assert(!!element);
if (element.firstChild) {
element.firstChild.vtree = virtualize(element.firstChild);
}
}
import app from '../app';
app.h = (el, props, ...children) => (typeof el === 'string') ?
h(el, props, children) : el(props, children);
app.createElement = app.h; | Support custom element in jsx/tsx | Support custom element in jsx/tsx
| TypeScript | mit | yysun/apprun,yysun/apprun,yysun/apprun | ---
+++
@@ -29,5 +29,7 @@
}
import app from '../app';
-app.h = (el, props, ...children) => h(el, props, children);
+app.h = (el, props, ...children) => (typeof el === 'string') ?
+ h(el, props, children) : el(props, children);
+
app.createElement = app.h; |
1675ed3cfc83e5698ac33bef1dc54f8d4ea2a227 | src/Autocompletion.ts | src/Autocompletion.ts | import {leafNodeAt, ASTNode} from "./shell/Parser";
import * as _ from "lodash";
import {Environment} from "./shell/Environment";
import {OrderedSet} from "./utils/OrderedSet";
import {Aliases} from "./shell/Aliases";
type GetSuggestionsOptions = {
currentText: string;
currentCaretPosition: number;
ast: ASTNode;
environment: Environment;
historicalPresentDirectoriesStack: OrderedSet<string>;
aliases: Aliases;
};
export async function getSuggestions({
currentCaretPosition,
ast,
environment,
historicalPresentDirectoriesStack,
aliases,
}: GetSuggestionsOptions): Promise<monaco.languages.CompletionList> {
const node = leafNodeAt(currentCaretPosition, ast);
const suggestions = await node.suggestions({
environment: environment,
historicalPresentDirectoriesStack: historicalPresentDirectoriesStack,
aliases: aliases,
});
const uniqueSuggestions = _.uniqBy(suggestions, suggestion => suggestion.label);
return {
isIncomplete: false,
items: <any>uniqueSuggestions,
};
}
| import {leafNodeAt, ASTNode} from "./shell/Parser";
import * as _ from "lodash";
import {Environment} from "./shell/Environment";
import {OrderedSet} from "./utils/OrderedSet";
import {Aliases} from "./shell/Aliases";
type GetSuggestionsOptions = {
currentText: string;
currentCaretPosition: number;
ast: ASTNode;
environment: Environment;
historicalPresentDirectoriesStack: OrderedSet<string>;
aliases: Aliases;
};
export async function getSuggestions({
currentCaretPosition,
ast,
environment,
historicalPresentDirectoriesStack,
aliases,
}: GetSuggestionsOptions): Promise<monaco.languages.CompletionList> {
const node = leafNodeAt(currentCaretPosition, ast);
const suggestions = await node.suggestions({
environment: environment,
historicalPresentDirectoriesStack: historicalPresentDirectoriesStack,
aliases: aliases,
});
const uniqueSuggestions = _.uniqBy(suggestions, suggestion => suggestion.label);
return {
isIncomplete: false,
items: uniqueSuggestions.map(suggestion => ({
...suggestion,
kind: suggestion.kind || monaco.languages.CompletionItemKind.Interface,
})),
};
}
| Add default icon to suggestions. | Add default icon to suggestions.
| TypeScript | mit | shockone/black-screen,shockone/black-screen,railsware/upterm,railsware/upterm,black-screen/black-screen,vshatskyi/black-screen,black-screen/black-screen,black-screen/black-screen,vshatskyi/black-screen,vshatskyi/black-screen,vshatskyi/black-screen | ---
+++
@@ -31,6 +31,9 @@
return {
isIncomplete: false,
- items: <any>uniqueSuggestions,
+ items: uniqueSuggestions.map(suggestion => ({
+ ...suggestion,
+ kind: suggestion.kind || monaco.languages.CompletionItemKind.Interface,
+ })),
};
} |
c37a604b597ee4d47c3079cf3705b36dfea5ba61 | src/dash-table/components/Table/style.ts | src/dash-table/components/Table/style.ts | import { library } from '@fortawesome/fontawesome-svg-core';
import { faEyeSlash, faTrashAlt } from '@fortawesome/free-regular-svg-icons';
import { faEraser, faPencilAlt, faSort, faSortDown, faSortUp } from '@fortawesome/free-solid-svg-icons';
library.add(
faEraser,
faEyeSlash,
faPencilAlt,
faSort,
faSortDown,
faSortUp,
faTrashAlt
);
| import { library } from '@fortawesome/fontawesome-svg-core';
import { faEyeSlash, faTrashAlt } from '@fortawesome/free-regular-svg-icons';
import { faEraser, faPencilAlt, faSort, faSortDown, faSortUp } from '@fortawesome/free-solid-svg-icons';
import { faAngleLeft, faAngleRight, faAngleDoubleLeft, faAngleDoubleRight } from '@fortawesome/free-solid-svg-icons';
library.add(
faEraser,
faEyeSlash,
faPencilAlt,
faSort,
faSortDown,
faSortUp,
faTrashAlt,
faAngleLeft,
faAngleRight,
faAngleDoubleLeft,
faAngleDoubleRight
);
| Add FA icons for previous/next/first/last page nav buttons. | Add FA icons for previous/next/first/last page nav buttons.
| TypeScript | mit | plotly/dash-table,plotly/dash-table,plotly/dash-table | ---
+++
@@ -1,6 +1,7 @@
import { library } from '@fortawesome/fontawesome-svg-core';
import { faEyeSlash, faTrashAlt } from '@fortawesome/free-regular-svg-icons';
import { faEraser, faPencilAlt, faSort, faSortDown, faSortUp } from '@fortawesome/free-solid-svg-icons';
+import { faAngleLeft, faAngleRight, faAngleDoubleLeft, faAngleDoubleRight } from '@fortawesome/free-solid-svg-icons';
library.add(
faEraser,
@@ -9,5 +10,9 @@
faSort,
faSortDown,
faSortUp,
- faTrashAlt
+ faTrashAlt,
+ faAngleLeft,
+ faAngleRight,
+ faAngleDoubleLeft,
+ faAngleDoubleRight
); |
1722da329195c797eb7a5a0def682edacc582de6 | src/components/app.ts | src/components/app.ts | import Component from 'inferno-component'
import h from 'inferno-hyperscript'
interface Props {}
export default class App extends Component<Props, {}> {
render() {
return h('p', 'hello')
}
}
| import Component from 'inferno-component'
import h from 'inferno-hyperscript'
import Input from './input.ts'
interface Props {}
interface State {
titles: string[]
}
export default class App extends Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
titles: []
}
}
addTitle(title: string) {
this.state.titles.push(title)
console.log(this.state.titles)
}
render() {
return h(Input, { add: this.addTitle.bind(this) })
}
}
| Add Input Component to App Component | Add Input Component to App Component
| TypeScript | mit | y0za/typescript-inferno-todo,y0za/typescript-inferno-todo,y0za/typescript-inferno-todo | ---
+++
@@ -1,10 +1,26 @@
import Component from 'inferno-component'
import h from 'inferno-hyperscript'
+import Input from './input.ts'
interface Props {}
+interface State {
+ titles: string[]
+}
-export default class App extends Component<Props, {}> {
+export default class App extends Component<Props, State> {
+ constructor(props: Props) {
+ super(props)
+ this.state = {
+ titles: []
+ }
+ }
+
+ addTitle(title: string) {
+ this.state.titles.push(title)
+ console.log(this.state.titles)
+ }
+
render() {
- return h('p', 'hello')
+ return h(Input, { add: this.addTitle.bind(this) })
}
} |
9c4b4ff5436b533b5ab15114455ea6b752688e0d | src/index.ts | src/index.ts | export * from "./beautifier";
export * from "./languages";
export * from "./options";
import {Unibeautify} from "./beautifier";
import {Options} from "./options";
import {Languages} from "./languages";
const unibeautify = new Unibeautify();
unibeautify.loadOptions(Options);
unibeautify.loadLanguages(Languages);
export default unibeautify;
| export * from "./beautifier";
export * from "./languages";
export * from "./options";
import {Unibeautify} from "./beautifier";
import {Options} from "./options";
import {Languages} from "./languages";
export function newUnibeautify(): Unibeautify {
const unibeautify = new Unibeautify();
unibeautify.loadOptions(Options);
unibeautify.loadLanguages(Languages);
return unibeautify;
}
export default newUnibeautify();
| Add newUnibeautify method for setting up Unibeautify instance | Add newUnibeautify method for setting up Unibeautify instance
Useful for testing
| TypeScript | mit | Unibeautify/unibeautify,Unibeautify/unibeautify | ---
+++
@@ -5,7 +5,11 @@
import {Unibeautify} from "./beautifier";
import {Options} from "./options";
import {Languages} from "./languages";
-const unibeautify = new Unibeautify();
-unibeautify.loadOptions(Options);
-unibeautify.loadLanguages(Languages);
-export default unibeautify;
+
+export function newUnibeautify(): Unibeautify {
+ const unibeautify = new Unibeautify();
+ unibeautify.loadOptions(Options);
+ unibeautify.loadLanguages(Languages);
+ return unibeautify;
+}
+export default newUnibeautify(); |
102530b1c86e014755696cebc7888c1620933967 | ui/src/shared/constants/queryBuilder.ts | ui/src/shared/constants/queryBuilder.ts | export interface QueryFn {
name: string
flux: string
aggregate: boolean
}
export const FUNCTIONS: QueryFn[] = [
{name: 'mean', flux: `|> mean()`, aggregate: true},
{name: 'median', flux: '|> toFloat()\n |> median()', aggregate: true},
{name: 'max', flux: '|> max()', aggregate: true},
{name: 'min', flux: '|> min()', aggregate: true},
{name: 'sum', flux: '|> sum()', aggregate: true},
{name: 'distinct', flux: '|> distinct()', aggregate: false},
{name: 'count', flux: '|> count()', aggregate: false},
{name: 'increase', flux: '|> increase()', aggregate: false},
{name: 'skew', flux: '|> skew()', aggregate: false},
{name: 'spread', flux: '|> spread()', aggregate: false},
{name: 'stddev', flux: '|> stddev()', aggregate: true},
{name: 'first', flux: '|> first()', aggregate: true},
{name: 'last', flux: '|> last()', aggregate: true},
{name: 'unique', flux: '|> unique()', aggregate: false},
{name: 'sort', flux: '|> sort()', aggregate: false},
]
| import {WINDOW_PERIOD} from 'src/shared/constants'
export interface QueryFn {
name: string
flux: string
aggregate: boolean
}
export const FUNCTIONS: QueryFn[] = [
{name: 'mean', flux: `|> mean()`, aggregate: true},
{name: 'median', flux: '|> toFloat()\n |> median()', aggregate: true},
{name: 'max', flux: '|> max()', aggregate: true},
{name: 'min', flux: '|> min()', aggregate: true},
{name: 'sum', flux: '|> sum()', aggregate: true},
{
name: 'derivative',
flux: `|> derivative(unit: ${WINDOW_PERIOD}, nonNegative: false)`,
aggregate: false,
},
{name: 'distinct', flux: '|> distinct()', aggregate: false},
{name: 'count', flux: '|> count()', aggregate: false},
{name: 'increase', flux: '|> increase()', aggregate: false},
{name: 'skew', flux: '|> skew()', aggregate: false},
{name: 'spread', flux: '|> spread()', aggregate: false},
{name: 'stddev', flux: '|> stddev()', aggregate: true},
{name: 'first', flux: '|> first()', aggregate: true},
{name: 'last', flux: '|> last()', aggregate: true},
{name: 'unique', flux: '|> unique()', aggregate: false},
{name: 'sort', flux: '|> sort()', aggregate: false},
]
| Enable selecting derivative function in query builder | Enable selecting derivative function in query builder
| TypeScript | mit | mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,nooproblem/influxdb,nooproblem/influxdb,li-ang/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb | ---
+++
@@ -1,3 +1,5 @@
+import {WINDOW_PERIOD} from 'src/shared/constants'
+
export interface QueryFn {
name: string
flux: string
@@ -10,6 +12,11 @@
{name: 'max', flux: '|> max()', aggregate: true},
{name: 'min', flux: '|> min()', aggregate: true},
{name: 'sum', flux: '|> sum()', aggregate: true},
+ {
+ name: 'derivative',
+ flux: `|> derivative(unit: ${WINDOW_PERIOD}, nonNegative: false)`,
+ aggregate: false,
+ },
{name: 'distinct', flux: '|> distinct()', aggregate: false},
{name: 'count', flux: '|> count()', aggregate: false},
{name: 'increase', flux: '|> increase()', aggregate: false}, |
057e1cfa9d184548d660437b457ff32cc511460f | test/test.ts | test/test.ts | // Reference mocha-typescript's global definitions:
/// <reference path="../node_modules/mocha-typescript/globals.d.ts" />
import { Unit } from "../src/index";
import { assert } from "chai";
declare var console;
before("start server", () => {
// Run express?
console.log("start server");
});
after("kill server", () => {
// Kill the server.
console.log("kill server");
});
describe("vanilla bdd", () => {
it("test", async () => {
await console.log(" vanilla bdd test");
});
});
suite("vanilla tdd", () => {
test("test", async () => {
await console.log(" vanilla tdd test");
});
});
@suite class UnitTest extends Unit {
@test "big is true with big number"() {
console.log(" UnitTest big is true with big number");
assert(this.big(200));
}
@test "big is false with small number"() {
console.log(" UnitTest big is false with small number");
assert(!this.big(50));
}
}
suite("nested class suite", () => {
@suite class NestedTest {
@test "a test"() {
console.log(" nested class suite NestedTest a test");
}
}
}); | // Reference mocha-typescript's global definitions:
/// <reference path="../node_modules/mocha-typescript/globals.d.ts" />
import { Unit } from "../src/index";
import { assert } from "chai";
declare var console, setTimeout;
function doWork(): Promise<void> {
return new Promise(resolve => setTimeout(resolve, 1000));
}
before("start server", async () => {
// Run express?
console.log("start server");
await doWork();
console.log("server started");
});
after("kill server", async () => {
// Kill the server.
console.log("kill server");
await doWork();
console.log("server killed");
});
describe("vanilla bdd", () => {
it("test", async () => {
await console.log(" vanilla bdd test");
});
});
suite("vanilla tdd", () => {
test("test", async () => {
await console.log(" vanilla tdd test");
});
});
@suite class UnitTest extends Unit {
@test "big is true with big number"() {
console.log(" UnitTest big is true with big number");
assert(this.big(200));
}
@test "big is false with small number"() {
console.log(" UnitTest big is false with small number");
assert(!this.big(50));
}
}
suite("nested class suite", () => {
@suite class NestedTest {
@test "a test"() {
console.log(" nested class suite NestedTest a test");
}
}
}); | Make the global hooks async | Make the global hooks async
| TypeScript | mit | pana-cc/mocha-typescript-seed | ---
+++
@@ -4,15 +4,22 @@
import { Unit } from "../src/index";
import { assert } from "chai";
-declare var console;
+declare var console, setTimeout;
-before("start server", () => {
+function doWork(): Promise<void> {
+ return new Promise(resolve => setTimeout(resolve, 1000));
+}
+before("start server", async () => {
// Run express?
console.log("start server");
+ await doWork();
+ console.log("server started");
});
-after("kill server", () => {
+after("kill server", async () => {
// Kill the server.
console.log("kill server");
+ await doWork();
+ console.log("server killed");
});
describe("vanilla bdd", () => { |
f4c9ab821e423565f009f37e0bf1864929b3d5b0 | app/javascript/retrospring/features/announcement/index.ts | app/javascript/retrospring/features/announcement/index.ts | import registerEvents from 'utilities/registerEvents';
import closeAnnouncementHandler from './close';
export default (): void => {
registerEvents([
{ type: 'click', target: document.querySelector('.announcement button.close'), handler: closeAnnouncementHandler },
]);
document.querySelectorAll('.announcement').forEach(function (el: HTMLDivElement) {
if (!window.localStorage.getItem(el.dataset.announcementId)) {
el.classList.remove('d-none');
}
});
}
| import registerEvents from 'utilities/registerEvents';
import closeAnnouncementHandler from './close';
export default (): void => {
registerEvents([
{ type: 'click', target: document.querySelector('.announcement button.close'), handler: closeAnnouncementHandler },
]);
document.querySelectorAll('.announcement').forEach(function (el: HTMLDivElement) {
if (!window.localStorage.getItem(`announcement${el.dataset.announcementId}`)) {
el.classList.remove('d-none');
}
});
}
| Fix incorrect localStorage key of announcement dismiss | Fix incorrect localStorage key of announcement dismiss
| TypeScript | agpl-3.0 | Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring | ---
+++
@@ -7,7 +7,7 @@
]);
document.querySelectorAll('.announcement').forEach(function (el: HTMLDivElement) {
- if (!window.localStorage.getItem(el.dataset.announcementId)) {
+ if (!window.localStorage.getItem(`announcement${el.dataset.announcementId}`)) {
el.classList.remove('d-none');
}
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.