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 |
|---|---|---|---|---|---|---|---|---|---|---|
3a4cb35d4857d1df65118f7c3266df0fc6f9df8d | applications/calendar/src/app/App.tsx | applications/calendar/src/app/App.tsx | import { hot } from 'react-hot-loader/root';
import React from 'react';
import { ProtonApp, StandardSetup } from 'react-components';
import locales from 'proton-shared/lib/i18n/locales';
import sentry from 'proton-shared/lib/helpers/sentry';
import * as config from './config';
import PrivateApp from './content/PrivateApp';
import './app.scss';
sentry(config);
const App = () => {
return (
<ProtonApp config={config}>
<StandardSetup PrivateApp={PrivateApp} locales={locales} />
</ProtonApp>
);
};
export default hot(App);
| import React from 'react';
import { ProtonApp, StandardSetup } from 'react-components';
import locales from 'proton-shared/lib/i18n/locales';
import sentry from 'proton-shared/lib/helpers/sentry';
import * as config from './config';
import PrivateApp from './content/PrivateApp';
import './app.scss';
sentry(config);
const App = () => {
return (
<ProtonApp config={config}>
<StandardSetup PrivateApp={PrivateApp} locales={locales} />
</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, StandardSetup } from 'react-components';
import locales from 'proton-shared/lib/i18n/locales';
@@ -19,4 +18,4 @@
);
};
-export default hot(App);
+export default App; |
ea5c4305a1a79ef4ad499af0536979d800b24233 | packages/elasticsearch-store/src/utils/retry-config.ts | packages/elasticsearch-store/src/utils/retry-config.ts | import { PRetryConfig, isTest } from '@terascope/utils';
export const MAX_RETRIES = isTest ? 2 : 100;
export const RETRY_DELAY = isTest ? 50 : 500;
export function getRetryConfig(): Partial<PRetryConfig> {
return {
retries: MAX_RETRIES,
delay: RETRY_DELAY,
matches: ['es_rejected_execution_exception', 'No Living connections'],
};
}
| import { PRetryConfig, isTest } from '@terascope/utils';
export const MAX_RETRIES = isTest ? 2 : 100;
export const RETRY_DELAY = isTest ? 50 : 500;
export function getRetryConfig(): Partial<PRetryConfig> {
return {
retries: MAX_RETRIES,
delay: RETRY_DELAY,
matches: [
'node_disconnect_exception',
'es_rejected_execution_exception',
'No Living connections'
],
};
}
| Add node_disconnect_exception to retry list in elasticsearch-store | Add node_disconnect_exception to retry list in elasticsearch-store
| TypeScript | apache-2.0 | terascope/teraslice,terascope/teraslice,terascope/teraslice,terascope/teraslice | ---
+++
@@ -7,6 +7,10 @@
return {
retries: MAX_RETRIES,
delay: RETRY_DELAY,
- matches: ['es_rejected_execution_exception', 'No Living connections'],
+ matches: [
+ 'node_disconnect_exception',
+ 'es_rejected_execution_exception',
+ 'No Living connections'
+ ],
};
} |
d644325b277a271a7ce8884126ffa25cf012e362 | packages/cli/src/lib/api.ts | packages/cli/src/lib/api.ts | import * as superagent from 'superagent';
import {
APIResponse,
APIResponseError,
APIResponseSuccess,
IClient,
IConfig
} from '../definitions';
const CONTENT_TYPE_JSON = 'application/json';
export const ERROR_UNKNOWN_CONTENT_TYPE = 'UNKNOWN_CONTENT_TYPE';
export const ERROR_UNKNOWN_RESPONSE_FORMAT = 'UNKNOWN_RESPONSE_FORMAT';
export class Client implements IClient {
constructor(public host: string) {}
make(method: string, path: string): superagent.Request {
return superagent(method, `${this.host}${path}`)
.set('Content-Type', CONTENT_TYPE_JSON)
.set('Accept', CONTENT_TYPE_JSON);
}
async do(req: superagent.Request): Promise<APIResponseSuccess> {
let res = await req;
if (res.type !== CONTENT_TYPE_JSON) {
throw ERROR_UNKNOWN_CONTENT_TYPE;
}
let j = <APIResponseSuccess>res.body;
if (!j.meta || !j.data) {
throw ERROR_UNKNOWN_RESPONSE_FORMAT;
}
return j;
}
is<T extends APIResponseSuccess>(r: APIResponseSuccess, predicate: (rs: APIResponseSuccess) => boolean): r is T {
return predicate(r);
}
}
| import * as superagent from 'superagent';
import {
APIResponse,
APIResponseError,
APIResponseSuccess,
IClient,
IConfig
} from '../definitions';
const CONTENT_TYPE_JSON = 'application/json';
export const ERROR_UNKNOWN_CONTENT_TYPE = 'UNKNOWN_CONTENT_TYPE';
export const ERROR_UNKNOWN_RESPONSE_FORMAT = 'UNKNOWN_RESPONSE_FORMAT';
export class Client implements IClient {
constructor(public host: string) {}
make(method: string, path: string): superagent.Request {
return superagent(method, `${this.host}${path}`)
.set('Content-Type', CONTENT_TYPE_JSON)
.set('Accept', CONTENT_TYPE_JSON);
}
async do(req: superagent.Request): Promise<APIResponseSuccess> {
let res = await Promise.resolve(req); // TODO: should be able to just do `await req`
if (res.type !== CONTENT_TYPE_JSON) {
throw ERROR_UNKNOWN_CONTENT_TYPE;
}
let j = <APIResponseSuccess>res.body;
if (!j.meta || !j.data) {
throw ERROR_UNKNOWN_RESPONSE_FORMAT;
}
return j;
}
is<T extends APIResponseSuccess>(r: APIResponseSuccess, predicate: (rs: APIResponseSuccess) => boolean): r is T {
return predicate(r);
}
}
| Fix compiler complaint for now | Fix compiler complaint for now
| TypeScript | mit | driftyco/ionic-cli,devtotvs/thf-mobile-cli,devtotvs/thf-mobile-cli,ricardo-mello/ionic-cli,driftyco/ionic-cli,ricardo-mello/ionic-cli,driftyco/ionic-cli,devtotvs/thf-mobile-cli,ricardo-mello/ionic-cli | ---
+++
@@ -22,7 +22,7 @@
}
async do(req: superagent.Request): Promise<APIResponseSuccess> {
- let res = await req;
+ let res = await Promise.resolve(req); // TODO: should be able to just do `await req`
if (res.type !== CONTENT_TYPE_JSON) {
throw ERROR_UNKNOWN_CONTENT_TYPE; |
af0258c8aaa529e71323315655b4faeec7e709d3 | app/javascript/retrospring/features/lists/create.ts | app/javascript/retrospring/features/lists/create.ts | import Rails from '@rails/ujs';
import { showNotification, showErrorNotification } from 'utilities/notifications';
import I18n from 'retrospring/i18n';
export function createListHandler(event: Event): void {
const button = event.target as HTMLButtonElement;
const input = document.querySelector<HTMLInputElement>('input#new-list-name');
Rails.ajax({
url: '/ajax/create_list',
type: 'POST',
data: new URLSearchParams({
name: input.value,
user: button.dataset.user
}).toString(),
success: (data) => {
if (data.success) {
document.querySelector('#lists-list ul.list-group').insertAdjacentHTML('beforeend', data.render);
}
showNotification(data.message, data.success);
},
error: (data, status, xhr) => {
console.log(data, status, xhr);
showErrorNotification(I18n.translate('frontend.error.message'));
}
});
}
export function createListInputHandler(event: KeyboardEvent): void {
// Return key
if (event.which === 13) {
event.preventDefault();
document.querySelector<HTMLButtonElement>('button#create-list').click();
}
} | import { post } from '@rails/request.js';
import { showNotification, showErrorNotification } from 'utilities/notifications';
import I18n from 'retrospring/i18n';
export function createListHandler(event: Event): void {
const button = event.target as HTMLButtonElement;
const input = document.querySelector<HTMLInputElement>('input#new-list-name');
post('/ajax/create_list', {
body: {
name: input.value,
user: button.dataset.user
},
contentType: 'application/json'
})
.then(async response => {
const data = await response.json;
if (data.success) {
document.querySelector('#lists-list ul.list-group').insertAdjacentHTML('beforeend', data.render);
}
showNotification(data.message, data.success);
})
.catch(err => {
console.log(err);
showErrorNotification(I18n.translate('frontend.error.message'));
});
}
export function createListInputHandler(event: KeyboardEvent): void {
// Return key
if (event.which === 13) {
event.preventDefault();
document.querySelector<HTMLButtonElement>('button#create-list').click();
}
} | Refactor list creation to use request.js | Refactor list creation to use request.js
| TypeScript | agpl-3.0 | Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring | ---
+++
@@ -1,4 +1,4 @@
-import Rails from '@rails/ujs';
+import { post } from '@rails/request.js';
import { showNotification, showErrorNotification } from 'utilities/notifications';
import I18n from 'retrospring/i18n';
@@ -6,25 +6,26 @@
const button = event.target as HTMLButtonElement;
const input = document.querySelector<HTMLInputElement>('input#new-list-name');
- Rails.ajax({
- url: '/ajax/create_list',
- type: 'POST',
- data: new URLSearchParams({
+ post('/ajax/create_list', {
+ body: {
name: input.value,
user: button.dataset.user
- }).toString(),
- success: (data) => {
+ },
+ contentType: 'application/json'
+ })
+ .then(async response => {
+ const data = await response.json;
+
if (data.success) {
document.querySelector('#lists-list ul.list-group').insertAdjacentHTML('beforeend', data.render);
}
showNotification(data.message, data.success);
- },
- error: (data, status, xhr) => {
- console.log(data, status, xhr);
+ })
+ .catch(err => {
+ console.log(err);
showErrorNotification(I18n.translate('frontend.error.message'));
- }
- });
+ });
}
export function createListInputHandler(event: KeyboardEvent): void { |
edec01f4c51d4d2f14631a3f851954d0dc047a83 | data/static/codefixes/registerAdminChallenge_4.ts | data/static/codefixes/registerAdminChallenge_4.ts | /* Generated API endpoints */
finale.initialize({ app, sequelize: models.sequelize })
const autoModels = [
{ name: 'User', exclude: ['password', 'totpSecret', 'role'] },
{ name: 'Product', exclude: [] },
{ name: 'Feedback', exclude: [] },
{ name: 'BasketItem', exclude: [] },
{ name: 'Challenge', exclude: [] },
{ name: 'Complaint', exclude: [] },
{ name: 'Recycle', exclude: [] },
{ name: 'SecurityQuestion', exclude: [] },
{ name: 'SecurityAnswer', exclude: [] },
{ name: 'Address', exclude: [] },
{ name: 'PrivacyRequest', exclude: [] },
{ name: 'Card', exclude: [] },
{ name: 'Quantity', exclude: [] }
]
for (const { name, exclude } of autoModels) {
const resource = finale.resource({
model: models[name],
endpoints: [`/api/${name}s`, `/api/${name}s/:id`],
excludeAttributes: exclude
})
// create a wallet when a new user is registered using API
if (name === 'User') {
resource.create.send.before((req, res, context) => {
models.Wallet.create({ UserId: context.instance.id }).catch((err) => {
console.log(err)
})
return context.continue
})
} | /* Generated API endpoints */
finale.initialize({ app, sequelize: models.sequelize })
const autoModels = [
{ name: 'User', exclude: ['password', 'totpSecret', 'role'] },
{ name: 'Product', exclude: [] },
{ name: 'Feedback', exclude: [] },
{ name: 'BasketItem', exclude: [] },
{ name: 'Challenge', exclude: [] },
{ name: 'Complaint', exclude: [] },
{ name: 'Recycle', exclude: [] },
{ name: 'SecurityQuestion', exclude: [] },
{ name: 'SecurityAnswer', exclude: [] },
{ name: 'Address', exclude: [] },
{ name: 'PrivacyRequest', exclude: [] },
{ name: 'Card', exclude: [] },
{ name: 'Quantity', exclude: [] }
]
for (const { name, exclude } of autoModels) {
const resource = finale.resource({
model: models[name],
endpoints: [`/api/${name}s`, `/api/${name}s/:id`],
excludeAttributes: exclude
})
// create a wallet when a new user is registered using API
if (name === 'User') {
resource.create.send.before((req, res, context) => {
models.Wallet.create({ UserId: context.instance.id }).catch((err) => {
console.log(err)
})
return context.continue
})
} | Fix indentation to match original code | Fix indentation to match original code
| TypeScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -1,35 +1,35 @@
-/* Generated API endpoints */
-finale.initialize({ app, sequelize: models.sequelize })
+ /* Generated API endpoints */
+ finale.initialize({ app, sequelize: models.sequelize })
-const autoModels = [
- { name: 'User', exclude: ['password', 'totpSecret', 'role'] },
- { name: 'Product', exclude: [] },
- { name: 'Feedback', exclude: [] },
- { name: 'BasketItem', exclude: [] },
- { name: 'Challenge', exclude: [] },
- { name: 'Complaint', exclude: [] },
- { name: 'Recycle', exclude: [] },
- { name: 'SecurityQuestion', exclude: [] },
- { name: 'SecurityAnswer', exclude: [] },
- { name: 'Address', exclude: [] },
- { name: 'PrivacyRequest', exclude: [] },
- { name: 'Card', exclude: [] },
- { name: 'Quantity', exclude: [] }
-]
+ const autoModels = [
+ { name: 'User', exclude: ['password', 'totpSecret', 'role'] },
+ { name: 'Product', exclude: [] },
+ { name: 'Feedback', exclude: [] },
+ { name: 'BasketItem', exclude: [] },
+ { name: 'Challenge', exclude: [] },
+ { name: 'Complaint', exclude: [] },
+ { name: 'Recycle', exclude: [] },
+ { name: 'SecurityQuestion', exclude: [] },
+ { name: 'SecurityAnswer', exclude: [] },
+ { name: 'Address', exclude: [] },
+ { name: 'PrivacyRequest', exclude: [] },
+ { name: 'Card', exclude: [] },
+ { name: 'Quantity', exclude: [] }
+ ]
-for (const { name, exclude } of autoModels) {
- const resource = finale.resource({
- model: models[name],
- endpoints: [`/api/${name}s`, `/api/${name}s/:id`],
- excludeAttributes: exclude
- })
+ for (const { name, exclude } of autoModels) {
+ const resource = finale.resource({
+ model: models[name],
+ endpoints: [`/api/${name}s`, `/api/${name}s/:id`],
+ excludeAttributes: exclude
+ })
- // create a wallet when a new user is registered using API
- if (name === 'User') {
- resource.create.send.before((req, res, context) => {
- models.Wallet.create({ UserId: context.instance.id }).catch((err) => {
- console.log(err)
+ // create a wallet when a new user is registered using API
+ if (name === 'User') {
+ resource.create.send.before((req, res, context) => {
+ models.Wallet.create({ UserId: context.instance.id }).catch((err) => {
+ console.log(err)
+ })
+ return context.continue
})
- return context.continue
- })
- }
+ } |
f6299343538458384b9e83294260297bb13a82b5 | src/api.ts | src/api.ts | import * as stringify from "json-stringify-pretty-compact";
import { JSONKifuFormat } from "./shogiUtils";
export default class Api {
static fetchJKF() {
const begin = new Date();
return fetch('/jkf')
.then(response => response.json())
.then(json => {
const end = new Date();
console.log(`fetchJKF ${end.getTime() - begin.getTime()}ms`);
return json;
});
}
static storeJKF(jkf: JSONKifuFormat) {
const body = stringify(jkf);
function preserveFailedData(e: Error | Response) {
console.error(e);
window.sessionStorage.setItem('lastFailedJKF', body);
console.log('Failed to save. You can get the last JKF by: console.log(sessionStorage.getItem("lastFailedJKF"))');
}
return new Promise((resolve, reject) => {
fetch('/jkf', { method: 'PUT', body: body })
.then((response) => {
if (response.ok) {
resolve();
} else {
preserveFailedData(response);
reject(response);
}
})
.catch((e) => {
preserveFailedData(e);
reject(e);
});
});
}
}
| import * as stringify from "json-stringify-pretty-compact";
import { JSONKifuFormat } from "./shogiUtils";
export default class Api {
static fetchJKF() {
const begin = new Date();
return fetch('/jkf')
.then(response => response.json())
.then(json => {
const end = new Date();
console.log(`fetchJKF ${end.getTime() - begin.getTime()}ms`);
return json;
});
}
static storeJKF(jkf: JSONKifuFormat) {
const body = stringify(jkf) + '\n'; // Add newline at end of file
function preserveFailedData(e: Error | Response) {
console.error(e);
window.sessionStorage.setItem('lastFailedJKF', body);
console.log('Failed to save. You can get the last JKF by: console.log(sessionStorage.getItem("lastFailedJKF"))');
}
return new Promise((resolve, reject) => {
fetch('/jkf', { method: 'PUT', body: body })
.then((response) => {
if (response.ok) {
resolve();
} else {
preserveFailedData(response);
reject(response);
}
})
.catch((e) => {
preserveFailedData(e);
reject(e);
});
});
}
}
| Add newline at end of file in JKF | Add newline at end of file in JKF
| TypeScript | mit | orangain/kifu-notebook,orangain/kifu-notebook,orangain/kifu-notebook,orangain/kifu-notebook,orangain/kifu-notebook | ---
+++
@@ -13,7 +13,7 @@
});
}
static storeJKF(jkf: JSONKifuFormat) {
- const body = stringify(jkf);
+ const body = stringify(jkf) + '\n'; // Add newline at end of file
function preserveFailedData(e: Error | Response) {
console.error(e); |
1d08fec807d09fb4fa4b96408aca19c742b71066 | src/app/components/pricing-card/pricing-card.ts | src/app/components/pricing-card/pricing-card.ts | import Vue from 'vue';
import { Component } from 'vue-property-decorator';
import { State } from 'vuex-class';
import View from '!view!./pricing-card.html?style=./pricing-card.styl';
import { Store } from '../../store/index';
import { currency } from '../../../lib/gj-lib-client/vue/filters/currency';
@View
@Component({
filters: {
currency,
},
})
export class AppPricingCard extends Vue {
@State sellable: Store['sellable'];
@State price: Store['price'];
@State originalPrice: Store['originalPrice'];
get discount() {
const price = this.price!;
const originalPrice = this.originalPrice!;
return ((originalPrice - price) / originalPrice).toFixed(0);
}
}
| import Vue from 'vue';
import { Component } from 'vue-property-decorator';
import { State } from 'vuex-class';
import View from '!view!./pricing-card.html?style=./pricing-card.styl';
import { Store } from '../../store/index';
import { currency } from '../../../lib/gj-lib-client/vue/filters/currency';
@View
@Component({
filters: {
currency,
},
})
export class AppPricingCard extends Vue {
@State
sellable: Store['sellable'];
@State
price: Store['price'];
@State
originalPrice: Store['originalPrice'];
get discount() {
const price = this.price!;
const originalPrice = this.originalPrice!;
return (((originalPrice - price) / originalPrice) * 100).toFixed(0);
}
}
| Fix the pricing card discount percentage. | Fix the pricing card discount percentage.
It was showing 0% because it wasn't multplied by 100.
| TypeScript | mit | gamejolt/widgets,gamejolt/widgets,gamejolt/widgets | ---
+++
@@ -13,14 +13,19 @@
},
})
export class AppPricingCard extends Vue {
- @State sellable: Store['sellable'];
- @State price: Store['price'];
- @State originalPrice: Store['originalPrice'];
+ @State
+ sellable: Store['sellable'];
+
+ @State
+ price: Store['price'];
+
+ @State
+ originalPrice: Store['originalPrice'];
get discount() {
const price = this.price!;
const originalPrice = this.originalPrice!;
- return ((originalPrice - price) / originalPrice).toFixed(0);
+ return (((originalPrice - price) / originalPrice) * 100).toFixed(0);
}
} |
d63a17cd51246073be5b59e290b6dd1b4edcb515 | src/settings/ISetting.ts | src/settings/ISetting.ts | import { SettingType } from './SettingType';
export interface ISetting {
/** The id of this setting. */
id: string;
/** Type of setting this is. */
type: SettingType;
/** What is the default value (allows a reset button). */
packageValue: any;
/** Will be the value of this setting. Should nothing be set here the "packageValue" will be used. */
value?: any;
/** Whether this setting is required or not. */
required: boolean;
/** Whether this setting is a public setting or not - administrators can see ones which are not public but users can't. */
public: boolean;
/** Whether this setting should be hidden from the user/administrator's eyes (can't be hidden and required). */
hidden?: boolean;
/** The selectable values when the setting's type is "select". */
values?: Array<ISettingSelectValue>;
/** The name of the section where to put this setting under. */
section?: string;
/** Name of the setting in the form of a i18n string. */
i18nLabel: string;
/** Description of the setting in the form of a i18n string. */
i18nDescription?: string;
/** An optional alert messages which is shown to the user on this setting. */
i18nAlert?: string;
/** Date in which this setting was created. */
createdAt?: Date;
/** The last time the setting was updated at. */
updatedAt?: Date;
}
export interface ISettingSelectValue {
key: string;
i18nLabel: string;
}
| import { SettingType } from './SettingType';
export interface ISetting {
/** The id of this setting. */
id: string;
/** Type of setting this is. */
type: SettingType;
/** What is the default value (allows a reset button). */
packageValue: any;
/** Will be the value of this setting. If nothing is set here, then the "packageValue" will be used. */
value?: any;
/** Whether this setting is required or not. */
required: boolean;
/** Whether this setting is a public setting or not - administrators can see ones which are not public but users can't. */
public: boolean;
/** Whether this setting should be hidden from the user/administrator's eyes (can't be hidden and required). */
hidden?: boolean;
/** The selectable values when the setting's type is "select". */
values?: Array<ISettingSelectValue>;
/** The name of the section where to put this setting under. */
section?: string;
/** Name of the setting in the form of a i18n string. */
i18nLabel: string;
/** Description of the setting in the form of a i18n string. */
i18nDescription?: string;
/** An optional alert messages which is shown to the user on this setting. */
i18nAlert?: string;
/** An optional placeholder which will be shown in the form input field, should be an i18n string. */
i18nPlaceholder?: string;
/** Date in which this setting was created. */
createdAt?: Date;
/** The last time the setting was updated at. */
updatedAt?: Date;
}
export interface ISettingSelectValue {
key: string;
i18nLabel: string;
}
| Add optional i18n placeholder setting to the settings | Add optional i18n placeholder setting to the settings
| TypeScript | mit | graywolf336/temporary-rocketlets-ts-definition,graywolf336/temporary-rocketlets-ts-definition | ---
+++
@@ -7,7 +7,7 @@
type: SettingType;
/** What is the default value (allows a reset button). */
packageValue: any;
- /** Will be the value of this setting. Should nothing be set here the "packageValue" will be used. */
+ /** Will be the value of this setting. If nothing is set here, then the "packageValue" will be used. */
value?: any;
/** Whether this setting is required or not. */
required: boolean;
@@ -25,6 +25,8 @@
i18nDescription?: string;
/** An optional alert messages which is shown to the user on this setting. */
i18nAlert?: string;
+ /** An optional placeholder which will be shown in the form input field, should be an i18n string. */
+ i18nPlaceholder?: string;
/** Date in which this setting was created. */
createdAt?: Date;
/** The last time the setting was updated at. */ |
333990d1510f95b76f9659f13b524a31978523ef | src/api/applications/get.ts | src/api/applications/get.ts | import { RequestHandler } from 'express'
import * as get from './db'
export const one: RequestHandler = async (req, res) => {
const application = await get.one(req.params.id)
res.json(application)
}
export const all: RequestHandler = async (req, res) => {
const applications = await get.all()
res.json(applications)
} | import { RequestHandler } from 'express'
import * as get from './db'
export const one: RequestHandler = async (req, res) => {
const application = await get.one(req.params.id)
application.key = ''
res.json(application)
}
export const all: RequestHandler = async (req, res) => {
const applications = await get.all()
for (const app of applications) {
app.key = ''
}
res.json(applications)
} | Remove key from application DTO | Remove key from application DTO
| TypeScript | mit | the-concierge/concierge,the-concierge/concierge,the-concierge/concierge | ---
+++
@@ -3,10 +3,16 @@
export const one: RequestHandler = async (req, res) => {
const application = await get.one(req.params.id)
+ application.key = ''
res.json(application)
}
export const all: RequestHandler = async (req, res) => {
const applications = await get.all()
+
+ for (const app of applications) {
+ app.key = ''
+ }
+
res.json(applications)
} |
fa67c980a277de8c6194d67bcee0a2fec9739ef8 | applications/mail/src/app/components/sidebar/LocationAside.tsx | applications/mail/src/app/components/sidebar/LocationAside.tsx | import React from 'react';
import { Icon, classnames } from 'react-components';
import './RefreshRotation.scss';
interface Props {
unreadCount?: number;
active?: boolean;
refreshing?: boolean;
}
const LocationAside = ({ unreadCount, active = false, refreshing = false }: Props) => {
return (
<>
{active && (
<Icon
className={classnames(['mr0-5 color-global-light', refreshing && 'location-refresh-rotate'])}
name="reload"
/>
)}
{unreadCount ? (
<span className="navigation__counterItem flex-item-noshrink rounded">{unreadCount}</span>
) : null}
</>
);
};
export default LocationAside;
| import React from 'react';
import { Icon, classnames } from 'react-components';
import { c, msgid } from 'ttag';
import './RefreshRotation.scss';
interface Props {
unreadCount?: number;
active?: boolean;
refreshing?: boolean;
}
const UNREAD_LIMIT = 999;
const LocationAside = ({ unreadCount, active = false, refreshing = false }: Props) => {
const unreadTitle = unreadCount
? c('Info').ngettext(msgid`${unreadCount} unread element`, `${unreadCount} unread elements`, unreadCount)
: undefined;
return (
<>
{active && (
<Icon
className={classnames(['mr0-5 color-global-light', refreshing && 'location-refresh-rotate'])}
name="reload"
/>
)}
{unreadCount ? (
<span className="navigation__counterItem flex-item-noshrink rounded" title={unreadTitle}>
{unreadCount > UNREAD_LIMIT ? '+999' : unreadCount}
</span>
) : null}
</>
);
};
export default LocationAside;
| Update the unread counter to be limited at 999 | [MAILWEB-980] Update the unread counter to be limited at 999
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,5 +1,6 @@
import React from 'react';
import { Icon, classnames } from 'react-components';
+import { c, msgid } from 'ttag';
import './RefreshRotation.scss';
@@ -9,7 +10,12 @@
refreshing?: boolean;
}
+const UNREAD_LIMIT = 999;
+
const LocationAside = ({ unreadCount, active = false, refreshing = false }: Props) => {
+ const unreadTitle = unreadCount
+ ? c('Info').ngettext(msgid`${unreadCount} unread element`, `${unreadCount} unread elements`, unreadCount)
+ : undefined;
return (
<>
{active && (
@@ -19,7 +25,9 @@
/>
)}
{unreadCount ? (
- <span className="navigation__counterItem flex-item-noshrink rounded">{unreadCount}</span>
+ <span className="navigation__counterItem flex-item-noshrink rounded" title={unreadTitle}>
+ {unreadCount > UNREAD_LIMIT ? '+999' : unreadCount}
+ </span>
) : null}
</>
); |
fd08ac356a47d3430ec9bc1f22b527984fd877ff | src/ng2-restangular-http.ts | src/ng2-restangular-http.ts | import {Injectable} from '@angular/core';
import {Http, Request} from '@angular/http';
import {Observable} from 'rxjs';
import {RestangularHelper} from './ng2-restangular-helper';
@Injectable()
export class RestangularHttp {
constructor(public http: Http) {
}
createRequest(options) {
let requestOptions = RestangularHelper.createRequestOptions(options);
let request = new Request(requestOptions);
return this.request(request);
}
request(request) {
return this.http.request(request)
.map((response: any) => {
response.config = {params: request};
return response;
})
.map((response: any) => {
if (response._body) {
response.data = typeof response._body == 'string' ? JSON.parse(response._body) : response._body;
} else {
response.data = null
}
return response;
})
.catch(err => {
err.data = typeof err._body == 'string' ? JSON.parse(err._body) : err._body;
err.request = request;
err.repeatRequest = (newRequest?) => {
return this.request(newRequest || request);
};
return Observable.throw(err);
})
}
}
| import {Injectable} from '@angular/core';
import {Http, Request} from '@angular/http';
import {Observable} from 'rxjs';
import {RestangularHelper} from './ng2-restangular-helper';
@Injectable()
export class RestangularHttp {
constructor(public http: Http) {
}
createRequest(options) {
let requestOptions = RestangularHelper.createRequestOptions(options);
let request = new Request(requestOptions);
return this.request(request);
}
request(request) {
return this.http.request(request)
.map((response: any) => {
response.config = {params: request};
return response;
})
.map((response: any) => {
if (response._body) {
response.data = typeof response._body == 'string' ? JSON.parse(response._body) : response._body;
} else {
response.data = null
}
return response;
})
.catch(err => {
err.data = typeof err._body == 'string' && err._body.length > 0 ? JSON.parse(err._body) : err._body;
err.request = request;
err.repeatRequest = (newRequest?) => {
return this.request(newRequest || request);
};
return Observable.throw(err);
})
}
}
| Check error response before parsing | Check error response before parsing
| TypeScript | mit | 2muchcoffeecom/ngx-restangular,2muchcoffeecom/ngx-restangular,2muchcoffeecom/ng2-restangular,2muchcoffeecom/ng2-restangular | ---
+++
@@ -33,7 +33,7 @@
return response;
})
.catch(err => {
- err.data = typeof err._body == 'string' ? JSON.parse(err._body) : err._body;
+ err.data = typeof err._body == 'string' && err._body.length > 0 ? JSON.parse(err._body) : err._body;
err.request = request;
err.repeatRequest = (newRequest?) => {
return this.request(newRequest || request); |
8c1584003341eefa95b6cdf940bcfb9cca206cea | src/Model.ts | src/Model.ts | import Day from './Day'
export default class Model {
private _checkInDate: Day
private _checkOutDate: Day
constructor(checkInDate: Day, checkOutDate: Day) {
if (checkOutDate.toMoment().isBefore(checkInDate.toMoment())) {
throw new Error(
`Check-out date can be before check-in. Got ${checkInDate}, ${checkOutDate}`
)
}
this._checkInDate = checkInDate
this._checkOutDate = checkOutDate
}
get checkInDate(): Day {
return this._checkInDate
}
get checkOutDate(): Day {
return this._checkOutDate
}
}
| import Day from './Day'
export default class Model {
private _checkInDate: Day
private _checkOutDate: Day
constructor(checkInDate: Day, checkOutDate: Day) {
if (checkOutDate.toMoment().isBefore(checkInDate.toMoment())) {
throw new Error(
`Check-out date can't be before check-in. Got ${checkInDate}, ${checkOutDate}`
)
}
this._checkInDate = checkInDate
this._checkOutDate = checkOutDate
}
get checkInDate(): Day {
return this._checkInDate
}
get checkOutDate(): Day {
return this._checkOutDate
}
}
| Fix a mistake in an Error message | Fix a mistake in an Error message
| TypeScript | mit | ikr/react-period-of-stay-input,ikr/react-period-of-stay-input,ikr/react-period-of-stay-input | ---
+++
@@ -7,7 +7,7 @@
constructor(checkInDate: Day, checkOutDate: Day) {
if (checkOutDate.toMoment().isBefore(checkInDate.toMoment())) {
throw new Error(
- `Check-out date can be before check-in. Got ${checkInDate}, ${checkOutDate}`
+ `Check-out date can't be before check-in. Got ${checkInDate}, ${checkOutDate}`
)
}
|
7bbc1a971b70964e3c609ebd8a69e22564ebf4cc | Spa/NakedObjects.Spa/Scripts/nakedobjects.config.ts | Spa/NakedObjects.Spa/Scripts/nakedobjects.config.ts | // Copyright 2013-2014 Naked Objects Group Ltd
// 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.
module NakedObjects {
"use strict";
// custom configuration for a particular implementation
// path to Restful Objects server
export var appPath = "http://mvc.nakedobjects.net:1081/RestDemo";
// export var appPath = "http://localhost:61546";
// path local server (ie ~) only needed if you want to hard code paths for some reason
export var svrPath = "";
}
| // Copyright 2013-2014 Naked Objects Group Ltd
// 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.
module NakedObjects {
"use strict";
// custom configuration for a particular implementation
// path to Restful Objects server
export var appPath = "http://nakedobjectsrodemo.azurewebsites.net";
// export var appPath = "http://localhost:61546";
// path local server (ie ~) only needed if you want to hard code paths for some reason
export var svrPath = "";
}
| Update spa to point at azure rest demo | Update spa to point at azure rest demo
| TypeScript | apache-2.0 | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | ---
+++
@@ -15,7 +15,7 @@
// custom configuration for a particular implementation
// path to Restful Objects server
- export var appPath = "http://mvc.nakedobjects.net:1081/RestDemo";
+ export var appPath = "http://nakedobjectsrodemo.azurewebsites.net";
// export var appPath = "http://localhost:61546";
// path local server (ie ~) only needed if you want to hard code paths for some reason |
60595a002b439dda178bbec17289b02cf32db316 | src/icons.ts | src/icons.ts | import { TResponse, TResponseItem } from "./alfred/response";
import { getAllIconsObject, TIconObject } from "./assets/icons_object";
export const toResponseItem = (iconObject: TIconObject): TResponseItem => {
return {
title: iconObject.name,
subtitle: `Paste class name: fa-${iconObject.name}`,
arg: iconObject.name,
icon: {
path: `./icons/${iconObject.name}.png`,
},
} as TResponseItem;
};
export const getAllIcons = (): TResponse => {
const iconObject = getAllIconsObject();
const allIcons = iconObject.map((value) => {
return toResponseItem(value);
});
const response: TResponse = {
items: allIcons,
} as TResponse;
return response;
};
| import { TResponse, TResponseItem } from "./alfred/response";
import { getAllIconsObject, TIconObject } from "./assets/icons_object";
export const toResponseItem = (iconObject: TIconObject): TResponseItem => {
const prefix = (style: TIconObject["style"]) => {
switch (style) {
case "brands":
return "fab";
case "regular":
return "far";
case "solid":
return "fas";
default:
return style as never;
}
};
const classes = `${prefix(iconObject.style)} fa-${iconObject.name}`;
const argObj = { name: iconObject.name, style: iconObject.style };
const arg = JSON.stringify(argObj);
return {
title: iconObject.name,
subtitle: `Paste class name: ${classes}`,
arg: arg,
icon: {
path: `./icons/${iconObject.style}/${iconObject.name}.png`,
},
} as TResponseItem;
};
export const getAllIcons = (): TResponse => {
const iconObject = getAllIconsObject();
const allIcons = iconObject.map((value) => {
return toResponseItem(value);
});
const response: TResponse = {
items: allIcons,
} as TResponse;
return response;
};
| Add style parameter to TResponseItem | feat(src): Add style parameter to TResponseItem
| TypeScript | mit | ruedap/alfred-font-awesome-workflow,ruedap/alfred-font-awesome-workflow,ruedap/alfred-font-awesome-workflow | ---
+++
@@ -2,12 +2,29 @@
import { getAllIconsObject, TIconObject } from "./assets/icons_object";
export const toResponseItem = (iconObject: TIconObject): TResponseItem => {
+ const prefix = (style: TIconObject["style"]) => {
+ switch (style) {
+ case "brands":
+ return "fab";
+ case "regular":
+ return "far";
+ case "solid":
+ return "fas";
+ default:
+ return style as never;
+ }
+ };
+
+ const classes = `${prefix(iconObject.style)} fa-${iconObject.name}`;
+ const argObj = { name: iconObject.name, style: iconObject.style };
+ const arg = JSON.stringify(argObj);
+
return {
title: iconObject.name,
- subtitle: `Paste class name: fa-${iconObject.name}`,
- arg: iconObject.name,
+ subtitle: `Paste class name: ${classes}`,
+ arg: arg,
icon: {
- path: `./icons/${iconObject.name}.png`,
+ path: `./icons/${iconObject.style}/${iconObject.name}.png`,
},
} as TResponseItem;
}; |
8d9cf180e671d9e332afb2f3c4b04f4ddee6409a | packages/web-api/src/response/TeamProfileGetResponse.ts | packages/web-api/src/response/TeamProfileGetResponse.ts | /* eslint-disable */
/////////////////////////////////////////////////////////////////////////////////////////
// //
// !!! DO NOT EDIT THIS FILE !!! //
// //
// This file is auto-generated by scripts/generate-web-api-types.sh in the repository. //
// Please refer to the script code to learn how to update the source data. //
// //
/////////////////////////////////////////////////////////////////////////////////////////
import { WebAPICallResult } from '../WebClient';
export type TeamProfileGetResponse = WebAPICallResult & {
ok?: boolean;
profile?: Profile;
error?: string;
needed?: string;
provided?: string;
};
export interface Profile {
fields?: Field[];
sections?: Section[];
}
export interface Field {
id?: string;
ordering?: number;
field_name?: string;
label?: string;
hint?: string;
type?: string;
is_hidden?: boolean;
}
export interface Section {
id?: string;
team_id?: string;
section_type?: string;
label?: string;
order?: number;
is_hidden?: boolean;
}
| /* eslint-disable */
/////////////////////////////////////////////////////////////////////////////////////////
// //
// !!! DO NOT EDIT THIS FILE !!! //
// //
// This file is auto-generated by scripts/generate-web-api-types.sh in the repository. //
// Please refer to the script code to learn how to update the source data. //
// //
/////////////////////////////////////////////////////////////////////////////////////////
import { WebAPICallResult } from '../WebClient';
export type TeamProfileGetResponse = WebAPICallResult & {
ok?: boolean;
profile?: Profile;
error?: string;
needed?: string;
provided?: string;
};
export interface Profile {
fields?: Field[];
sections?: Section[];
}
export interface Field {
id?: string;
ordering?: number;
field_name?: string;
label?: string;
hint?: string;
type?: string;
is_hidden?: boolean;
possible_values?: string[];
}
export interface Section {
id?: string;
team_id?: string;
section_type?: string;
label?: string;
order?: number;
is_hidden?: boolean;
}
| Update the web-api response types using the latest source | Update the web-api response types using the latest source
| TypeScript | mit | slackapi/node-slack-sdk,slackapi/node-slack-sdk,slackapi/node-slack-sdk,slackapi/node-slack-sdk | ---
+++
@@ -23,13 +23,14 @@
}
export interface Field {
- id?: string;
- ordering?: number;
- field_name?: string;
- label?: string;
- hint?: string;
- type?: string;
- is_hidden?: boolean;
+ id?: string;
+ ordering?: number;
+ field_name?: string;
+ label?: string;
+ hint?: string;
+ type?: string;
+ is_hidden?: boolean;
+ possible_values?: string[];
}
export interface Section { |
afa242e9c03e609d5e9a5c53caffbfe7e60d1848 | src/store.ts | src/store.ts | import {applyMiddleware, createStore} from 'redux'
import flowRight from 'lodash-es/flowRight'
import * as firebase from 'firebase/app'
import {reducer} from './reducer'
import {reactReduxFirebase} from 'react-redux-firebase'
const middlewares = []
// Redux-logger plugin
if (process.env.NODE_ENV === 'development') {
// tslint:disable-next-line:no-var-requires
const {createLogger} = require('redux-logger')
const logger = createLogger({
collapsed: true
})
middlewares.push(logger)
}
// Firebase plugin
const firebaseConfig = {
enableLogging: true,
userProfile: 'users'
}
export const store = flowRight(
(reactReduxFirebase as any)(firebase, firebaseConfig),
applyMiddleware(...middlewares)
)(createStore)(reducer)
| import {applyMiddleware, createStore} from 'redux'
import flowRight from 'lodash-es/flowRight'
import * as firebase from 'firebase/app'
import {reducer} from './reducer'
import {reactReduxFirebase} from 'react-redux-firebase'
const middlewares = []
// Redux-logger plugin
if (process.env.NODE_ENV === 'development') {
// tslint:disable-next-line:no-var-requires
const {createLogger} = require('redux-logger')
const logger = createLogger({
collapsed: true
})
middlewares.push(logger)
}
// Firebase plugin
const firebaseConfig = {
enableLogging: process.env.NODE_ENV === 'development',
userProfile: 'users'
}
export const store = flowRight(
(reactReduxFirebase as any)(firebase, firebaseConfig),
applyMiddleware(...middlewares)
)(createStore)(reducer)
| Disable firebase logging on production | Disable firebase logging on production
| TypeScript | mit | jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend | ---
+++
@@ -18,7 +18,7 @@
// Firebase plugin
const firebaseConfig = {
- enableLogging: true,
+ enableLogging: process.env.NODE_ENV === 'development',
userProfile: 'users'
}
|
a20600e20aed6cf4d7ef2ade188bfe615c8b8c74 | src/index.ts | src/index.ts | export {default as Size} from './size'
export {default as Point} from './point'
export {default as Scale} from './scale'
export {default as Rectangle, Rectangular } from './rectangle'
export {default as Borders} from './borders'
export {default as BorderedRectangle} from './bordered-rectangle'
| export {default as BorderedRectangle} from './bordered-rectangle'
export {default as Borders} from './borders'
export {default as Rectangle, Rectangular } from './rectangle'
export {default as Scale} from './scale'
export {default as Point} from './point'
export {default as Size} from './size'
| Reorder exports to fix inheritance bug | Reorder exports to fix inheritance bug
| TypeScript | mit | romancow/ts-geometry,romancow/ts-geometry | ---
+++
@@ -1,6 +1,6 @@
+export {default as BorderedRectangle} from './bordered-rectangle'
+export {default as Borders} from './borders'
+export {default as Rectangle, Rectangular } from './rectangle'
+export {default as Scale} from './scale'
+export {default as Point} from './point'
export {default as Size} from './size'
-export {default as Point} from './point'
-export {default as Scale} from './scale'
-export {default as Rectangle, Rectangular } from './rectangle'
-export {default as Borders} from './borders'
-export {default as BorderedRectangle} from './bordered-rectangle' |
2fd0ce9e2e049ab165a1fa016b54cb1f75db23c0 | src/queue.ts | src/queue.ts | class Queue {
private _running = false;
private _queue: Function[] = [];
public push(f: Function) {
this._queue.push(f);
if (!this._running) {
// if nothing is running, then start the engines!
this._next();
}
return this; // for chaining fun!
}
private _next() {
this._running = false;
// get the first element off the queue
let action = this._queue.shift();
if (action) {
this._running = true;
new Promise((reject, resolve) => action(resolve)).then(this._next)
// action(() => {
// this._next();
// });
}
}
}
export default Queue;
| class Queue {
private _running = false;
private _queue: Function[] = [];
public push(f: Function) {
this._queue.push(f);
if (!this._running) {
// if nothing is running, then start the engines!
this._next();
}
return this; // for chaining fun!
}
private _next() {
this._running = false;
// get the first element off the queue
let action = this._queue.shift();
if (action) {
this._running = true;
new Promise((resolve, reject) => action(resolve)).then(this._next.bind(this));
// action(() => {
// this._next();
// });
}
}
}
export default Queue;
| Switch 'resolve' and 'reject' declaration + context binding in then | Switch 'resolve' and 'reject' declaration + context binding in then
| TypeScript | apache-2.0 | KamiKillertO/vscode-colorize,KamiKillertO/vscode-colorize | ---
+++
@@ -20,7 +20,7 @@
let action = this._queue.shift();
if (action) {
this._running = true;
- new Promise((reject, resolve) => action(resolve)).then(this._next)
+ new Promise((resolve, reject) => action(resolve)).then(this._next.bind(this));
// action(() => {
// this._next();
// }); |
d7c68a6853b87e4e453835830e5fee4d17833645 | server/util/credentials.ts | server/util/credentials.ts | /* Copyright 2019 Google Inc. All Rights Reserved.
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 * as path from "https://deno.land/std@0.132.0/path/mod.ts";
const creds: Record<string, string> = {};
export function get(name: string) {
return creds[name];
}
// Loads every .json file in the specified dir. Credentials are stored under
// the key related to the filename.
export function loadFromDir(dir: string) {
for (
const p of [...Deno.readDirSync(dir)].filter((p) =>
p.name.endsWith(".json")
)
) {
const contents = Deno.readFileSync(path.join(dir, p.name));
const decoder = new TextDecoder();
const cred = JSON.parse(decoder.decode(contents));
creds[p.name.replace(".json", "")] = cred;
}
}
| /* Copyright 2019 Google Inc. All Rights Reserved.
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 * as path from "https://deno.land/std@0.132.0/path/mod.ts";
const creds: Record<string, unknown> = {};
export function get(name: string) {
return creds[name];
}
// Loads every .json file in the specified dir. Credentials are stored under
// the key related to the filename.
export function loadFromDir(dir: string) {
for (
const p of [...Deno.readDirSync(dir)].filter((p) =>
p.name.endsWith(".json")
)
) {
const contents = Deno.readFileSync(path.join(dir, p.name));
const decoder = new TextDecoder();
const cred = JSON.parse(decoder.decode(contents));
creds[p.name.replace(".json", "")] = cred;
}
}
| Fix type of fetched creds. - The framework has no idea what are in the creds file. | Fix type of fetched creds.
- The framework has no idea what are in the creds file.
| TypeScript | apache-2.0 | google/chicago-brick,google/chicago-brick,google/chicago-brick,google/chicago-brick | ---
+++
@@ -15,7 +15,7 @@
import * as path from "https://deno.land/std@0.132.0/path/mod.ts";
-const creds: Record<string, string> = {};
+const creds: Record<string, unknown> = {};
export function get(name: string) {
return creds[name]; |
e1239b6c5a7cdb8f34751971d0c7b8b3e64870e2 | packages/web-client/app/utils/web3-strategies/ethereum.ts | packages/web-client/app/utils/web3-strategies/ethereum.ts | import { tracked } from '@glimmer/tracking';
import { Layer1Web3Strategy, TransactionHash } from './types';
import BN from 'bn.js';
import { WalletProvider } from '../wallet-providers';
import { defer } from 'rsvp';
import { TransactionReceipt } from 'web3-core';
import { getConstantByNetwork } from '@cardstack/cardpay-sdk/index.js';
import { UnbindEventListener } from '@cardstack/web-client/utils/events';
export default class EthereumWeb3Strategy implements Layer1Web3Strategy {
chainName = 'Ethereum mainnet';
chainId = 1;
isConnected: boolean = false;
walletConnectUri: string | undefined;
#waitForAccountDeferred = defer<void>();
get waitForAccount(): Promise<void> {
return this.#waitForAccountDeferred.promise;
}
@tracked currentProviderId: string | undefined;
@tracked defaultTokenBalance: BN | undefined;
@tracked daiBalance: BN | undefined;
@tracked cardBalance: BN | undefined;
connect(walletProvider: WalletProvider): Promise<void> {
throw new Error(`Method not implemented. ${walletProvider}`);
}
disconnect(): Promise<void> {
throw new Error(`Method not implemented.`);
}
// eslint-disable-next-line no-unused-vars
on(event: string, cb: Function): UnbindEventListener {
throw new Error('Method not implemented');
}
approve(
_amountInWei: BN, // eslint-disable-line no-unused-vars
_token: string // eslint-disable-line no-unused-vars
): Promise<TransactionReceipt> {
throw new Error('Method not implemented.');
}
relayTokens(
_token: string, // eslint-disable-line no-unused-vars
_destinationAddress: string, // eslint-disable-line no-unused-vars
_amountInWei: BN // eslint-disable-line no-unused-vars
): Promise<TransactionReceipt> {
throw new Error('Method not implemented.');
}
refreshBalances() {}
blockExplorerUrl(txnHash: TransactionHash) {
return `${getConstantByNetwork('blockExplorer', 'mainnet')}/tx/${txnHash}`;
}
bridgeExplorerUrl(txnHash: TransactionHash): string {
return `${getConstantByNetwork('bridgeExplorer', 'mainnet')}/${txnHash}`;
}
}
| import Layer1ChainWeb3Strategy from './layer1-chain';
export default class EthereumWeb3Strategy extends Layer1ChainWeb3Strategy {
constructor() {
super('mainnet', 'Ethereum mainnet');
}
}
| Update Ethereum strategy to extend Layer1Chain | Update Ethereum strategy to extend Layer1Chain
We haven’t actually exercised this…?
| TypeScript | mit | cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack | ---
+++
@@ -1,63 +1,7 @@
-import { tracked } from '@glimmer/tracking';
-import { Layer1Web3Strategy, TransactionHash } from './types';
-import BN from 'bn.js';
-import { WalletProvider } from '../wallet-providers';
-import { defer } from 'rsvp';
-import { TransactionReceipt } from 'web3-core';
-import { getConstantByNetwork } from '@cardstack/cardpay-sdk/index.js';
-import { UnbindEventListener } from '@cardstack/web-client/utils/events';
+import Layer1ChainWeb3Strategy from './layer1-chain';
-export default class EthereumWeb3Strategy implements Layer1Web3Strategy {
- chainName = 'Ethereum mainnet';
- chainId = 1;
- isConnected: boolean = false;
- walletConnectUri: string | undefined;
- #waitForAccountDeferred = defer<void>();
-
- get waitForAccount(): Promise<void> {
- return this.#waitForAccountDeferred.promise;
- }
-
- @tracked currentProviderId: string | undefined;
- @tracked defaultTokenBalance: BN | undefined;
- @tracked daiBalance: BN | undefined;
- @tracked cardBalance: BN | undefined;
-
- connect(walletProvider: WalletProvider): Promise<void> {
- throw new Error(`Method not implemented. ${walletProvider}`);
- }
-
- disconnect(): Promise<void> {
- throw new Error(`Method not implemented.`);
- }
-
- // eslint-disable-next-line no-unused-vars
- on(event: string, cb: Function): UnbindEventListener {
- throw new Error('Method not implemented');
- }
-
- approve(
- _amountInWei: BN, // eslint-disable-line no-unused-vars
- _token: string // eslint-disable-line no-unused-vars
- ): Promise<TransactionReceipt> {
- throw new Error('Method not implemented.');
- }
-
- relayTokens(
- _token: string, // eslint-disable-line no-unused-vars
- _destinationAddress: string, // eslint-disable-line no-unused-vars
- _amountInWei: BN // eslint-disable-line no-unused-vars
- ): Promise<TransactionReceipt> {
- throw new Error('Method not implemented.');
- }
-
- refreshBalances() {}
-
- blockExplorerUrl(txnHash: TransactionHash) {
- return `${getConstantByNetwork('blockExplorer', 'mainnet')}/tx/${txnHash}`;
- }
-
- bridgeExplorerUrl(txnHash: TransactionHash): string {
- return `${getConstantByNetwork('bridgeExplorer', 'mainnet')}/${txnHash}`;
+export default class EthereumWeb3Strategy extends Layer1ChainWeb3Strategy {
+ constructor() {
+ super('mainnet', 'Ethereum mainnet');
}
} |
4029e7156141d2e0496738594e770c36ca4e615b | lib/utils.ts | lib/utils.ts | import {rtmClient, webClient} from './slack';
export class Deferred {
promise: Promise<any>;
private nativeReject: (...args: any[]) => any;
private nativeResolve: (...args: any[]) => any;
constructor() {
this.promise = new Promise((resolve, reject) => {
this.nativeReject = reject;
this.nativeResolve = resolve;
});
}
resolve(...args: any[]) {
this.nativeResolve(...args);
}
reject(...args: any[]) {
this.nativeReject(...args);
}
}
const loadMembersDeferred = new Deferred();
webClient.users.list().then(({members}: any) => {
loadMembersDeferred.resolve(members);
});
export const getMemberName = async (user: string) => {
const members = await loadMembersDeferred.promise;
const member = members.find(({id}: any) => id === user);
return member.profile.display_name || member.name;
};
export const getMemberIcon = async (user: string) => {
const members = await loadMembersDeferred.promise;
const member = members.find(({id}: any) => id === user);
return member.profile.image_24;
}; | import {rtmClient, webClient} from './slack';
export class Deferred {
promise: Promise<any>;
private nativeReject: (...args: any[]) => any;
private nativeResolve: (...args: any[]) => any;
constructor() {
this.promise = new Promise((resolve, reject) => {
this.nativeReject = reject;
this.nativeResolve = resolve;
});
}
resolve(...args: any[]) {
this.nativeResolve(...args);
}
reject(...args: any[]) {
this.nativeReject(...args);
}
}
const loadMembersDeferred = new Deferred();
webClient.users.list().then(({members}: any) => {
loadMembersDeferred.resolve(members);
});
const additionalMembers: any[] = [];
rtmClient.on('team_join', (event) => {
additionalMembers.push(event.user);
});
export const getMemberName = async (user: string) => {
const members = [
...(await loadMembersDeferred.promise),
...additionalMembers,
];
const member = members.find(({id}: any) => id === user);
return member.profile.display_name || member.name;
};
export const getMemberIcon = async (user: string) => {
const members = [
...(await loadMembersDeferred.promise),
...additionalMembers,
];
const member = members.find(({id}: any) => id === user);
return member.profile.image_24;
}; | Support for newcomers in getMemberName | Support for newcomers in getMemberName
| TypeScript | mit | tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot | ---
+++
@@ -25,13 +25,23 @@
webClient.users.list().then(({members}: any) => {
loadMembersDeferred.resolve(members);
});
+const additionalMembers: any[] = [];
+rtmClient.on('team_join', (event) => {
+ additionalMembers.push(event.user);
+});
export const getMemberName = async (user: string) => {
- const members = await loadMembersDeferred.promise;
+ const members = [
+ ...(await loadMembersDeferred.promise),
+ ...additionalMembers,
+ ];
const member = members.find(({id}: any) => id === user);
return member.profile.display_name || member.name;
};
export const getMemberIcon = async (user: string) => {
- const members = await loadMembersDeferred.promise;
+ const members = [
+ ...(await loadMembersDeferred.promise),
+ ...additionalMembers,
+ ];
const member = members.find(({id}: any) => id === user);
return member.profile.image_24;
}; |
8ade355abf632c3928ca3fd595505d36c257583a | infr_tests.ts | infr_tests.ts | import { sslTest, dnssec, headers } from './infr';
import * as assert from 'assert';
export async function testSslPositive() {
const result = await sslTest({ host: 'google.com' });
assert.equal(result.endpoints.length, 2);
assert.equal(result.endpoints[0].grade, 'A');
assert.equal(result.endpoints[1].grade, 'A');
assert.ok(result.endpoints[0].details.supportsAlpn);
assert.ok(result.endpoints[1].details.supportsAlpn);
}
export async function testDnssecPositive() {
const result = await dnssec({ host: 'verisigninc.com' });
assert.equal(result.secure, true);
}
export async function testDnssecNegative() {
const result = await dnssec({ host: 'google.com' });
assert.equal(result.secure, false);
}
export async function testHeadersPositive() {
const result = await headers({ url: 'https://securityheaders.io' });
const sts = result.get('strict-transport-security');
if (!sts) {
throw new assert.AssertionError('STS header should be set.');
} else {
assert.ok('preload' in sts);
assert.ok('includeSubDomains' in sts);
assert.ok(Number(sts['max-age']) >= 31536000);
}
}
| import { sslTest, dnssec, headers } from './infr';
import * as assert from 'assert';
export async function testSslPositive() {
const result = await sslTest({ host: 'google.com' });
assert.equal(result.endpoints.length, 2);
assert.equal(result.endpoints[0].grade, 'A');
assert.equal(result.endpoints[1].grade, 'A');
assert.ok(result.endpoints[0].details.supportsAlpn);
assert.ok(result.endpoints[1].details.supportsAlpn);
}
export async function testDnssecPositive() {
const result = await dnssec({ host: 'verisigninc.com' });
assert.equal(result.secure, true);
}
export async function testDnssecNegative() {
const result = await dnssec({ host: 'google.com' });
assert.equal(result.secure, false);
}
export async function testHeadersPositive() {
const result = await headers({ url: 'https://securityheaders.io' });
const sts = result.get('strict-transport-security');
if (!sts) {
throw new assert.AssertionError({
message: 'STS header should be set.'
});
} else {
assert.ok('preload' in sts);
assert.ok('includeSubDomains' in sts);
assert.ok(Number(sts['max-age']) >= 31536000);
}
}
| Fix type error on AssertionError constructor | Fix type error on AssertionError constructor
| TypeScript | apache-2.0 | wiktor-k/infrastructure-tests | ---
+++
@@ -25,7 +25,9 @@
const result = await headers({ url: 'https://securityheaders.io' });
const sts = result.get('strict-transport-security');
if (!sts) {
- throw new assert.AssertionError('STS header should be set.');
+ throw new assert.AssertionError({
+ message: 'STS header should be set.'
+ });
} else {
assert.ok('preload' in sts);
assert.ok('includeSubDomains' in sts); |
0d8ad4f4065a348a001df639de161aba78d8ccd1 | src/definitions/Handler.ts | src/definitions/Handler.ts | import {Context} from "./SkillContext";
let Frames = require("../definitions/FrameDirectory");
namespace Handlers {
export class FrameDirectory {
constructor() {
}
get(prop): Frame | undefined {
console.log(`Fetching frame ${prop}, ${prop in this ? "found" : "not found"}.`);
return this[prop];
}
set(prop, value): boolean {
console.log(`setting frame ${prop}, ${prop in this ? "overwritten" : "new frame"}.`);
return this[prop] = value;
}
}
export class Frame {
constructor(id: string, entry: ReturnsResponseContext, FrameMap: ActionMap) {
this.id = id;
this.entry = entry;
this.actions = FrameMap;
Frames[id] = this;
}
id: string;
entry: ReturnsResponseContext;
actions: ActionMap;
}
export class ResponseContext {
constructor() {
}
CurrentFrame: Frame;
model: ResponseModel;
}
export class ResponseModel {
speech: string;
reprompt: string;
}
export interface ReturnsResponseContext {
(Context: Context): ResponseContext | Promise<ResponseContext>;
}
export interface ActionMap {
[key: string]: ReturnsFrame | undefined;
}
export interface ReturnsFrame {
(Context: Context): Frame | Promise<Frame>;
}
}
export = Handlers; | import {Context} from "./SkillContext";
let Frames = require("../definitions/FrameDirectory");
namespace Handlers {
export class FrameDirectory {
constructor() {
}
get(prop): Frame | undefined {
console.log(`Fetching frame ${prop}, ${prop in this ? "found" : "not found"}.`);
return this[prop];
}
set(prop, value): boolean {
console.log(`setting frame ${prop}`);
if (prop in this) {
throw new Error(`Error, frame ${prop} already exists. All frame IDs must be unique.`);
}
return this[prop] = value;
}
}
export class Frame {
constructor(id: string, entry: ReturnsResponseContext, FrameMap: ActionMap) {
this.id = id;
this.entry = entry;
this.actions = FrameMap;
Frames[id] = this;
}
id: string;
entry: ReturnsResponseContext;
actions: ActionMap;
}
export class ResponseContext {
constructor() {
}
CurrentFrame: Frame;
model: ResponseModel;
}
export class ResponseModel {
speech: string;
reprompt: string;
}
export interface ReturnsResponseContext {
(Context: Context): ResponseContext | Promise<ResponseContext>;
}
export interface ActionMap {
[key: string]: ReturnsFrame | undefined;
}
export interface ReturnsFrame {
(Context: Context): Frame | Promise<Frame>;
}
}
export = Handlers; | Throw error if attempting to add duplicate frame. | Throw error if attempting to add duplicate frame.
| TypeScript | agpl-3.0 | deegles/cookietime,deegles/cookietime | ---
+++
@@ -13,7 +13,12 @@
}
set(prop, value): boolean {
- console.log(`setting frame ${prop}, ${prop in this ? "overwritten" : "new frame"}.`);
+ console.log(`setting frame ${prop}`);
+
+ if (prop in this) {
+ throw new Error(`Error, frame ${prop} already exists. All frame IDs must be unique.`);
+ }
+
return this[prop] = value;
}
} |
4ca67ab4633d4b316333a10246d041fd22b969bc | src/EDLog/ContinousReadStream.ts | src/EDLog/ContinousReadStream.ts | import { Readable, ReadableOptions } from 'stream';
import * as fs from 'fs';
export class ContinuesReadStream extends Readable {
private closed = false;
private offset = 0;
private file: number;
private poll: NodeJS.Timer;
private buffer: Buffer;
constructor (private fileName: string, opts?: ReadableOptions) {
super(opts);
this.closed = false;
}
public seekToEnd () {
this.offset = fs.statSync(this.fileName).size;
}
public close () {
if (this.closed) {
throw new Error('Already closed');
}
if (!this.file) {
return;
}
fs.closeSync(this.file);
clearInterval(this.poll);
this.closed = true;
}
protected _read () {
if (this.file) {
return;
}
this.buffer = Buffer.alloc(0xFFFF);
this.file = fs.openSync(this.fileName, 'r');
this.poll = setInterval(() => {
try {
const read = fs.readSync(this.file, this.buffer, 0, 0xFFFF, this.offset);
this.offset += read;
if(!this.push(this.buffer.toString('utf8', 0, read))) {
this.close();
}
} catch (e) {
process.nextTick(() => this.emit('error', e));
}
}, 100);
}
}
| import { Readable, ReadableOptions } from 'stream';
import * as fs from 'fs';
export class ContinuesReadStream extends Readable {
private closed = false;
private offset = 0;
private file: number;
private poll: NodeJS.Timer;
private buffer: Buffer;
constructor (public readonly fileName: string, opts?: ReadableOptions, public readonly pollInterval: number = 100) {
super(opts);
this.closed = false;
}
public seekToEnd () {
this.offset = fs.statSync(this.fileName).size;
}
public close () {
if (this.closed) {
throw new Error('Already closed');
}
if (!this.file) {
return;
}
fs.closeSync(this.file);
clearInterval(this.poll);
this.closed = true;
}
protected _read () {
if (this.file) {
return;
}
this.buffer = Buffer.alloc(0xFFFF);
this.file = fs.openSync(this.fileName, 'r');
this.poll = setInterval(() => {
try {
const read = fs.readSync(this.file, this.buffer, 0, 0xFFFF, this.offset);
this.offset += read;
if(!this.push(this.buffer.toString('utf8', 0, read))) {
this.close();
}
} catch (e) {
process.nextTick(() => this.emit('error', e));
}
}, this.pollInterval);
}
}
| Make some properties accessible, allow injection of poll interval | Make some properties accessible, allow injection of poll interval
| TypeScript | mit | SimonSchick/EliteDangerousUtils | ---
+++
@@ -7,7 +7,7 @@
private file: number;
private poll: NodeJS.Timer;
private buffer: Buffer;
- constructor (private fileName: string, opts?: ReadableOptions) {
+ constructor (public readonly fileName: string, opts?: ReadableOptions, public readonly pollInterval: number = 100) {
super(opts);
this.closed = false;
}
@@ -44,6 +44,6 @@
} catch (e) {
process.nextTick(() => this.emit('error', e));
}
- }, 100);
+ }, this.pollInterval);
}
} |
95450b68ef3a6ee9763e84794b86604375a887fe | jovo-integrations/jovo-db-cosmosdb/src/CosmosDb.ts | jovo-integrations/jovo-db-cosmosdb/src/CosmosDb.ts | import {BaseApp} from 'jovo-core';
import {MongoDb, Config} from 'jovo-db-mongodb';
import _get = require('lodash.get');
export class CosmosDb extends MongoDb {
constructor(config?: Config) {
super(config);
}
install(app: BaseApp) {
if (_get(app.config, 'db.default')) {
if (_get(app.config, 'db.default') === 'CosmosDb') {
app.$db = this;
}
} else {
app.$db = this;
}
}
}
| import {BaseApp} from 'jovo-core';
import {MongoDb, Config} from 'jovo-db-mongodb';
import _get = require('lodash.get');
export class CosmosDb extends MongoDb {
constructor(config?: Config) {
super(config);
}
async install(app: BaseApp) {
await super.install(app);
if (_get(app.config, 'db.default')) {
if (_get(app.config, 'db.default') === 'CosmosDb') {
app.$db = this;
}
} else {
app.$db = this;
}
}
}
| Add super.install() call to initialize MongoClient | :bug: Add super.install() call to initialize MongoClient
In commit a1dcc99d7409e91d4dcec740639f9483e7195a20 a public MongoDb connection was introcuded which broke this integration. The super.install() fixes that issue
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -7,7 +7,8 @@
super(config);
}
- install(app: BaseApp) {
+ async install(app: BaseApp) {
+ await super.install(app);
if (_get(app.config, 'db.default')) {
if (_get(app.config, 'db.default') === 'CosmosDb') {
app.$db = this; |
42700e2497ba60acf096569e0aa82524c94817bf | lib/Events.ts | lib/Events.ts | function call(target: any, type: string, listener: EventListener, standard: string, fallback: string): boolean {
let standardFn: any = target[standard];
let fallbackFn: any = target[fallback];
if (standardFn !== undefined) {
standardFn(type, listener);
return true;
} else if (fallbackFn !== undefined) {
fallbackFn(`on${type}`, listener);
return true;
} else {
return false;
}
}
function createEvent(type: string): Event {
if (typeof(Event) === 'function') {
return new Event(type);
} else {
let event: Event = document.createEvent('Event');
event.initEvent(type, false, false);
return event;
}
}
export function addEventListener(target: any, type: string, listener: EventListener): void {
if (!call(target, type, listener, 'addEventListener', 'attachEvent')) {
fireEventListener(type, listener);
}
}
export function removeEventListener(target: any, type: string, listener: EventListener): void {
call(target, type, listener, 'removeEventListener', 'detachEvent');
}
export function fireEventListener(type: string, listener: EventListener): void {
listener(createEvent(type));
}
| function call(target: any, type: string, listener: EventListener, standard: string, fallback: string): boolean {
let standardFn: any = target[standard];
let fallbackFn: any = target[fallback];
if (typeof standardFn === 'function') {
standardFn.call(target, type, listener);
return true;
} else if (typeof fallbackFn === 'function') {
fallbackFn.call(target, `on${type}`, listener);
return true;
} else {
return false;
}
}
function createEvent(type: string): Event {
if (typeof(Event) === 'function') {
return new Event(type);
} else {
let event: Event = document.createEvent('Event');
event.initEvent(type, false, false);
return event;
}
}
export function addEventListener(target: any, type: string, listener: EventListener): void {
if (!call(target, type, listener, 'addEventListener', 'attachEvent')) {
fireEventListener(type, listener);
}
}
export function removeEventListener(target: any, type: string, listener: EventListener): void {
call(target, type, listener, 'removeEventListener', 'detachEvent');
}
export function fireEventListener(type: string, listener: EventListener): void {
listener(createEvent(type));
}
| Correct event listener call context | Correct event listener call context
| TypeScript | unknown | michaelbull/zoom.ts,MikeBull94/zoom.ts,michaelbull/zoom.ts,MikeBull94/zoom.ts,MikeBull94/zoom.ts | ---
+++
@@ -2,11 +2,11 @@
let standardFn: any = target[standard];
let fallbackFn: any = target[fallback];
- if (standardFn !== undefined) {
- standardFn(type, listener);
+ if (typeof standardFn === 'function') {
+ standardFn.call(target, type, listener);
return true;
- } else if (fallbackFn !== undefined) {
- fallbackFn(`on${type}`, listener);
+ } else if (typeof fallbackFn === 'function') {
+ fallbackFn.call(target, `on${type}`, listener);
return true;
} else {
return false; |
7e32f5a46c438ef946c36e572b9a9bc01b3cc63d | src/app/bucketlists/bucketlists.component.ts | src/app/bucketlists/bucketlists.component.ts | import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-bucketlists',
templateUrl: './bucketlists.component.html',
styleUrls: ['./bucketlists.component.css']
})
export class BucketlistsComponent implements OnInit {
constructor() {
console.log(localStorage.getItem('currentuser'))
}
ngOnInit() {
console.log(localStorage.getItem('currentuser'));
}
}
| import { Component, OnInit } from '@angular/core';
import { NgForm} from '@angular/forms';
import { AuthService} from '../services/auth.service';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { BucketlistsService } from '../services/bucketlists.service'
@Component({
selector: 'app-bucketlists',
templateUrl: './bucketlists.component.html',
styleUrls: ['./bucketlists.component.css']
})
export class BucketlistsComponent implements OnInit {
constructor(private authService: AuthService,
private router: Router,
private bucketlistsService: BucketlistsService
) {
}
ngOnInit() {
}
}
| Set console log to see whther bucketlists cn retrive tokenfrom localStorage | Set console log to see whther bucketlists cn retrive tokenfrom localStorage
| TypeScript | mit | emugaya/bucketlist_frontend,emugaya/bucketlist_frontend,emugaya/bucketlist_frontend | ---
+++
@@ -1,4 +1,10 @@
import { Component, OnInit } from '@angular/core';
+import { NgForm} from '@angular/forms';
+import { AuthService} from '../services/auth.service';
+import { Http, Response } from '@angular/http';
+import { Router } from '@angular/router';
+import { BucketlistsService } from '../services/bucketlists.service'
+
@Component({
selector: 'app-bucketlists',
@@ -7,12 +13,15 @@
})
export class BucketlistsComponent implements OnInit {
- constructor() {
- console.log(localStorage.getItem('currentuser'))
+ constructor(private authService: AuthService,
+ private router: Router,
+ private bucketlistsService: BucketlistsService
+ ) {
+
}
ngOnInit() {
- console.log(localStorage.getItem('currentuser'));
+
}
} |
4695462cf532468595f236d25d85637b37630a4c | src/utils/addIcon.ts | src/utils/addIcon.ts | const faFontFamily = 'Font Awesome 5 Free';
export type FontAwesomeStyle = 'solid' | 'regular' | 'brands';
/**
* Add an icon into `sap.ui.core.IconPool`.
*
* @export
* @param {string} iconName Icon name.
* @param {string} unicode Icon unicode character.
* @param {FontAwesomeStyle} style Font Awesome icon style.
*/
export default function addIcon(iconName: string, unicode: string, style: FontAwesomeStyle): void {
sap.ui.core.IconPool.addIcon(
iconName,
`font-awesome-${style}`,
{
fontFamily: faFontFamily,
content: unicode,
overWrite: true
}
);
}
| const faFreeFontFamily = 'Font Awesome 5 Free';
const faBrandsFontFamily = 'Font Awesome 5 Brands';
export type FontAwesomeStyle = 'solid' | 'regular' | 'brands';
/**
* Add an icon into `sap.ui.core.IconPool`.
*
* @export
* @param {string} iconName Icon name.
* @param {string} unicode Icon unicode character.
* @param {FontAwesomeStyle} style Font Awesome icon style.
*/
export default function addIcon(iconName: string, unicode: string, style: FontAwesomeStyle): void {
sap.ui.core.IconPool.addIcon(
iconName,
`font-awesome-${style}`,
{
fontFamily: (style === 'brands') ? faBrandsFontFamily : faFreeFontFamily,
content: unicode,
overWrite: true
}
);
}
| Fix incorrect brands icon font | :bug: Fix incorrect brands icon font
| TypeScript | mit | gluons/font-awesome-openui5 | ---
+++
@@ -1,4 +1,5 @@
-const faFontFamily = 'Font Awesome 5 Free';
+const faFreeFontFamily = 'Font Awesome 5 Free';
+const faBrandsFontFamily = 'Font Awesome 5 Brands';
export type FontAwesomeStyle = 'solid' | 'regular' | 'brands';
@@ -15,7 +16,7 @@
iconName,
`font-awesome-${style}`,
{
- fontFamily: faFontFamily,
+ fontFamily: (style === 'brands') ? faBrandsFontFamily : faFreeFontFamily,
content: unicode,
overWrite: true
} |
f612fa625d91985257dd0acc4b2113993694deaa | packages/lesswrong/server/callbacks/sequenceCallbacks.ts | packages/lesswrong/server/callbacks/sequenceCallbacks.ts | import Chapters from '../../lib/collections/chapters/collection'
import Sequences, { makeEditableOptions } from '../../lib/collections/sequences/collection'
import { addEditableCallbacks } from '../editor/make_editable_callbacks';
import { getCollectionHooks } from '../mutationCallbacks';
getCollectionHooks("Sequences").newAsync.add(function SequenceNewCreateChapter(sequence) {
if (sequence._id && !sequence.chaptersDummy) {
Chapters.insert({sequenceId:sequence._id})
}
});
addEditableCallbacks({collection: Sequences, options: makeEditableOptions})
| import Chapters from '../../lib/collections/chapters/collection'
import Sequences, { makeEditableOptions } from '../../lib/collections/sequences/collection'
import { addEditableCallbacks } from '../editor/make_editable_callbacks';
import { getCollectionHooks } from '../mutationCallbacks';
getCollectionHooks("Sequences").newAsync.add(function SequenceNewCreateChapter(sequence) {
if (sequence._id) {
Chapters.insert({sequenceId:sequence._id})
}
});
addEditableCallbacks({collection: Sequences, options: makeEditableOptions})
| Fix type error due to reference to resolver-only field chaptersDummy | Fix type error due to reference to resolver-only field chaptersDummy
This was attempting to check whether a sequence already had a chapter in
it. But it was inside a creation callback, so it never would. Also, it
was checking by looking at the name of a resolver, rather than a field,
so the access would always result in undefined.
| TypeScript | mit | Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2 | ---
+++
@@ -4,7 +4,7 @@
import { getCollectionHooks } from '../mutationCallbacks';
getCollectionHooks("Sequences").newAsync.add(function SequenceNewCreateChapter(sequence) {
- if (sequence._id && !sequence.chaptersDummy) {
+ if (sequence._id) {
Chapters.insert({sequenceId:sequence._id})
}
}); |
d763f0bf594b2b7a8e618e2ae1d3f4ced173526c | tests/helpers/setup-pretender.ts | tests/helpers/setup-pretender.ts | import { TestContext } from 'ember-test-helpers';
import Pretender from 'pretender';
export default function setupPretender(hooks: NestedHooks) {
hooks.beforeEach(function(this: TestContext) {
this.server = new Pretender();
});
hooks.afterEach(function(this: TestContext) {
this.server.shutdown();
});
}
declare module 'ember-test-helpers' {
interface TestContext {
server: Pretender;
}
}
| import { TestContext } from '@ember/test-helpers';
import Pretender from 'pretender';
export default function setupPretender(hooks: NestedHooks) {
hooks.beforeEach(function(this: TestContext) {
this.server = new Pretender();
});
hooks.afterEach(function(this: TestContext) {
this.server.shutdown();
});
}
declare module 'ember-test-helpers' {
interface TestContext {
server: Pretender;
}
}
| Fix test helpers import path | chore: Fix test helpers import path
| TypeScript | mit | mike-north/ember-api-actions,mike-north/ember-api-actions,truenorth/ember-api-actions,mike-north/ember-api-actions,truenorth/ember-api-actions,mike-north/ember-api-actions | ---
+++
@@ -1,4 +1,4 @@
-import { TestContext } from 'ember-test-helpers';
+import { TestContext } from '@ember/test-helpers';
import Pretender from 'pretender';
export default function setupPretender(hooks: NestedHooks) { |
c8c72182da705f9a0b813ef18f7735eef050bbf4 | src/lib/finalMetrics.ts | src/lib/finalMetrics.ts | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Metric} from '../types.js';
export const finalMetrics: WeakSet<Metric> = new WeakSet();
| /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Metric} from '../types.js';
export const finalMetrics: WeakSet<Metric>|Set<Metric> = 'WeakSet' in window
? new WeakSet()
: new Set();
| Add support for Set in place of WeakSet | Add support for Set in place of WeakSet
| TypeScript | apache-2.0 | GoogleChrome/web-vitals,GoogleChrome/web-vitals | ---
+++
@@ -16,5 +16,6 @@
import {Metric} from '../types.js';
-
-export const finalMetrics: WeakSet<Metric> = new WeakSet();
+export const finalMetrics: WeakSet<Metric>|Set<Metric> = 'WeakSet' in window
+ ? new WeakSet()
+ : new Set(); |
2b1eba6964df6cd7c915fe40db02159a6c375d8e | src/marketplace/resources/change-limits/ChangeLimitsAction.ts | src/marketplace/resources/change-limits/ChangeLimitsAction.ts | import { ngInjector } from '@waldur/core/services';
import { translate } from '@waldur/i18n';
import { marketplaceIsVisible } from '@waldur/marketplace/utils';
import { validateState } from '@waldur/resource/actions/base';
import { ResourceAction } from '@waldur/resource/actions/types';
export default function createAction(ctx): ResourceAction {
return {
name: 'update_limits',
type: 'form',
method: 'POST',
component: 'marketplaceResourceChangeLimitsDialog',
title: translate('Change limits'),
useResolve: true,
dialogSize: 'lg',
isVisible: marketplaceIsVisible() && ctx.resource.marketplace_resource_uuid !== null && ngInjector.get('features').isVisible('marketplace.change_limits'),
validators: [validateState('OK')],
};
}
| import { translate } from '@waldur/i18n';
import { marketplaceIsVisible } from '@waldur/marketplace/utils';
import { validateState } from '@waldur/resource/actions/base';
import { ResourceAction } from '@waldur/resource/actions/types';
export default function createAction(ctx): ResourceAction {
return {
name: 'update_limits',
type: 'form',
method: 'POST',
component: 'marketplaceResourceChangeLimitsDialog',
title: translate('Change limits'),
useResolve: true,
dialogSize: 'lg',
isVisible: marketplaceIsVisible() && ctx.resource.marketplace_resource_uuid !== null,
validators: [validateState('OK')],
};
}
| Enable Change limits action by default. | Enable Change limits action by default.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -1,4 +1,3 @@
-import { ngInjector } from '@waldur/core/services';
import { translate } from '@waldur/i18n';
import { marketplaceIsVisible } from '@waldur/marketplace/utils';
import { validateState } from '@waldur/resource/actions/base';
@@ -13,7 +12,7 @@
title: translate('Change limits'),
useResolve: true,
dialogSize: 'lg',
- isVisible: marketplaceIsVisible() && ctx.resource.marketplace_resource_uuid !== null && ngInjector.get('features').isVisible('marketplace.change_limits'),
+ isVisible: marketplaceIsVisible() && ctx.resource.marketplace_resource_uuid !== null,
validators: [validateState('OK')],
};
} |
962c475f7e36ce774f8fb3ff426218cdbf4182a1 | Wallet/OnlineWallet.Web.Core/ClientApp/actions/wallets.ts | Wallet/OnlineWallet.Web.Core/ClientApp/actions/wallets.ts | import { Dispatch } from "redux";
import { Actions } from "../constants/actions";
import { Wallet, walletService } from "walletApi";
import { createAction } from "redux-actions";
import { AlertsActions } from "./alerts";
export const loadWalletSuccess = createAction<Wallet[]>(Actions.loadWallets);
export function loadWallets() {
return async (dispatch: Dispatch<any>) => {
try {
const wallets = await walletService.getAll();
dispatch(loadWalletSuccess(wallets));
} catch (error) {
dispatch(AlertsActions.showAlert({type: "danger", message: error}));
}
};
}
export function insertWallet(wallet: Wallet) {
return async (dispatch: Dispatch<any>) => {
try {
await walletService.insert(wallet);
await loadWallets()(dispatch);
} catch (error) {
dispatch(AlertsActions.showAlert({type: "danger", message: error}));
}
};
}
export function updateWallet(wallet: Wallet) {
return async (dispatch: Dispatch<any>) => {
try {
await walletService.update(wallet);
await loadWallets()(dispatch);
} catch (error) {
dispatch(AlertsActions.showAlert({type: "danger", message: error}));
}
};
}
export function deleteWallet(wallet: Wallet) {
return async (dispatch: Dispatch<any>) => {
try {
await walletService.delete(wallet);
await loadWallets()(dispatch);
} catch (error) {
dispatch(AlertsActions.showAlert({type: "danger", message: error}));
}
};
}
| import { Dispatch } from "redux";
import { Actions } from "../constants/actions";
import { Wallet, walletService } from "walletApi";
import { createAction } from "redux-actions";
import { AlertsActions } from "./alerts";
export const loadWalletSuccess = createAction<Wallet[]>(Actions.loadWallets);
export function loadWallets() {
return async (dispatch: Dispatch<any>) => {
try {
const wallets = await walletService.getAll();
dispatch(loadWalletSuccess(wallets));
} catch (error) {
dispatch(AlertsActions.showAlert({type: "danger", message: error.message}));
}
};
}
export function insertWallet(wallet: Wallet) {
return async (dispatch: Dispatch<any>) => {
try {
await walletService.insert(wallet);
await loadWallets()(dispatch);
} catch (error) {
dispatch(AlertsActions.showAlert({type: "danger", message: error.message}));
}
};
}
export function updateWallet(wallet: Wallet) {
return async (dispatch: Dispatch<any>) => {
try {
await walletService.update(wallet);
await loadWallets()(dispatch);
} catch (error) {
dispatch(AlertsActions.showAlert({type: "danger", message: error}));
}
};
}
export function deleteWallet(wallet: Wallet) {
return async (dispatch: Dispatch<any>) => {
try {
await walletService.delete(wallet);
await loadWallets()(dispatch);
} catch (error) {
dispatch(AlertsActions.showAlert({type: "danger", message: error}));
}
};
}
| Fix error message in failed wallet api call. | Fix error message in failed wallet api call.
| TypeScript | mit | faddiv/budget-keeper,faddiv/budget-keeper,faddiv/budget-keeper,faddiv/budget-keeper | ---
+++
@@ -12,7 +12,7 @@
const wallets = await walletService.getAll();
dispatch(loadWalletSuccess(wallets));
} catch (error) {
- dispatch(AlertsActions.showAlert({type: "danger", message: error}));
+ dispatch(AlertsActions.showAlert({type: "danger", message: error.message}));
}
};
}
@@ -23,7 +23,7 @@
await walletService.insert(wallet);
await loadWallets()(dispatch);
} catch (error) {
- dispatch(AlertsActions.showAlert({type: "danger", message: error}));
+ dispatch(AlertsActions.showAlert({type: "danger", message: error.message}));
}
};
} |
7851a3c0ada3a7034ca9988bcc2ef734b068d3ef | frontend/projects/admin/e2e/src/login/admin-login.e2e-spec.ts | frontend/projects/admin/e2e/src/login/admin-login.e2e-spec.ts | import { AdminLoginPage } from './admin-login.po';
describe('admin login page', () => {
const page = new AdminLoginPage();
let usernameInput;
let passwordInput;
beforeEach(async () => {
await page.navigateTo();
expect(await page.getTitleContent()).toBe('Admin Login');
usernameInput = page.getUsernameInput();
passwordInput = page.getPasswordInput();
});
describe('with empty username and password', () => {
it('should not allow logins', async () => {
expect(await page.getLoginBtn().isEnabled()).toBeFalsy();
});
});
describe('with invalid credentials', () => {
it('should not login the admin user', async () => {
await usernameInput.sendKeys(page.getUsername());
await passwordInput.sendKeys('invalid password!');
await page.attemptLoginAdmin();
expect(await page.getInvalidCredentialsAlert().isPresent()).toBeTruthy();
});
});
describe('with valid credentials', () => {
it('should login and logout the admin user', async () => {
await usernameInput.sendKeys(page.getUsername());
await passwordInput.sendKeys(page.getPassword());
await page.attemptLoginAdmin();
expect(await page.getCurrentUrl()).toBe('/');
await page.logoutAdmin();
expect(await page.getLoggedOutAlert().isPresent()).toBeTruthy();
});
});
});
| import { AdminLoginPage } from './admin-login.po';
describe('admin login page', () => {
const page = new AdminLoginPage();
let usernameInput;
let passwordInput;
beforeEach(async () => {
await page.navigateTo();
expect(await page.getTitleContent()).toBe('Admin Login');
usernameInput = page.getUsernameInput();
passwordInput = page.getPasswordInput();
});
describe('with empty username and password', () => {
it('should not allow logins', async () => {
expect(await page.getLoginBtn().isEnabled()).toBeFalsy();
});
});
describe('with invalid credentials', () => {
it('should not login the admin user', async () => {
await usernameInput.sendKeys(page.getUsername());
await passwordInput.sendKeys('invalid password!');
await page.attemptLoginAdmin();
expect(await page.getInvalidCredentialsAlert().isPresent()).toBeTruthy();
});
});
describe('with valid credentials', () => {
it('should login and logout the admin user', async () => {
await usernameInput.sendKeys(page.getUsername());
await passwordInput.sendKeys(page.getPassword());
await page.attemptLoginAdmin();
expect(await page.getCurrentUrl()).toBe('/');
// ensure login page is not accessible when already logged in
await page.navigateTo();
expect(await page.getCurrentUrl()).toBe('/');
await page.logoutAdmin();
expect(await page.getLoggedOutAlert().isPresent()).toBeTruthy();
});
});
});
| Add e2e login page scenario | Add e2e login page scenario
Ensures that the admin login page is not able to be accessed when the admin is already logged in.
| TypeScript | mit | drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild | ---
+++
@@ -44,6 +44,10 @@
await page.attemptLoginAdmin();
expect(await page.getCurrentUrl()).toBe('/');
+ // ensure login page is not accessible when already logged in
+ await page.navigateTo();
+ expect(await page.getCurrentUrl()).toBe('/');
+
await page.logoutAdmin();
expect(await page.getLoggedOutAlert().isPresent()).toBeTruthy();
}); |
3074d5ee04f6b3b9d2112164e649a121d3a42c88 | demo-shell-ng2/app/components/login/login.component.ts | demo-shell-ng2/app/components/login/login.component.ts | import {Component} from 'angular2/core';
import {Router, ROUTER_DIRECTIVES} from 'angular2/router';
import {FORM_DIRECTIVES, ControlGroup, FormBuilder, Validators} from 'angular2/common';
import {Authentication} from '../../services/authentication';
declare let componentHandler;
@Component({
selector: 'login-component',
moduleId: 'app/components/login/login',
directives: [ROUTER_DIRECTIVES, FORM_DIRECTIVES],
templateUrl: 'login.component.html',
styleUrls: ['login.component.css'],
})
export class LoginComponent {
form:ControlGroup;
error:boolean = false;
isErrorStyle(field:ControlGroup) {
componentHandler.upgradeAllRegistered();
if (field.valid) {
return false;
} else {
return true;
}
}
constructor(fb:FormBuilder, public auth:Authentication, public router:Router) {
this.form = fb.group({
username: ['', Validators.compose([Validators.required, Validators.minLength(4)])],
password: ['', Validators.required]
});
}
onSubmit(value:any, event) {
if (event) {
event.preventDefault();
}
this.auth.login('POST', value.username, value.password)
.subscribe(
(token:any) => this.router.navigate(['Home']),
() => {
this.error = true;
}
);
}
}
| import {Component} from 'angular2/core';
import {Router, ROUTER_DIRECTIVES} from 'angular2/router';
import {FORM_DIRECTIVES, ControlGroup, FormBuilder, Validators} from 'angular2/common';
import {Authentication} from '../../services/authentication';
declare let componentHandler;
@Component({
selector: 'login-component',
moduleId: 'app/components/login/login',
directives: [ROUTER_DIRECTIVES, FORM_DIRECTIVES],
templateUrl: 'login.component.html',
styleUrls: ['login.component.css'],
})
export class LoginComponent {
form:ControlGroup;
error:boolean = false;
isErrorStyle(field:ControlGroup) {
componentHandler.upgradeAllRegistered();
if (field.valid) {
return false;
} else {
return true;
}
}
constructor(fb:FormBuilder, public auth:Authentication, public router:Router) {
this.form = fb.group({
username: ['', Validators.compose([Validators.required, Validators.minLength(4)])],
password: ['', Validators.required]
});
}
onSubmit(value:any, event) {
if (event) {
event.preventDefault();
}
this.auth.login('POST', value.username, value.password)
.subscribe(
(token:any) => this.router.navigate(['Files']),
() => {
this.error = true;
}
);
}
}
| Fix redirect from Login dialog | Fix redirect from Login dialog
| TypeScript | apache-2.0 | Alfresco/alfresco-ng2-components,Alfresco/alfresco-ng2-components,Alfresco/alfresco-ng2-components,Alfresco/alfresco-ng2-components | ---
+++
@@ -37,7 +37,7 @@
}
this.auth.login('POST', value.username, value.password)
.subscribe(
- (token:any) => this.router.navigate(['Home']),
+ (token:any) => this.router.navigate(['Files']),
() => {
this.error = true;
} |
3a1f81d73bc7a720b4f03083c8cb0c1d2beb8e6e | src/mollie.ts | src/mollie.ts | import createHttpClient from './create-http-client';
import createMollieApi from './create-mollie-api';
// Expose models
import * as ChargebackModel from './models/chargeback';
import * as CustomerModel from './models/customer';
import * as MandateModel from './models/mandate';
import * as MethodModel from './models/method';
import * as PaymentModel from './models/payment';
import * as RefundModel from './models/refund';
import * as SubscriptionModel from './models/subscription';
/**
* Create Mollie client.
* @since 2.0.0
*/
export default function mollie(options: any = {}) {
if (!options.apiKey) {
throw new TypeError('Missing parameter "apiKey".');
}
const httpClient = createHttpClient(options);
this.Models = {
Chargeback: ChargebackModel,
Customer: CustomerModel,
Mandate: MandateModel,
Method: MethodModel,
Payment: PaymentModel,
Refund: RefundModel,
Subscription: SubscriptionModel,
};
return createMollieApi({ httpClient });
}
| import createHttpClient from './create-http-client';
import createMollieApi from './create-mollie-api';
// Expose models
import * as ChargebackModel from './models/chargeback';
import * as CustomerModel from './models/customer';
import * as MandateModel from './models/mandate';
import * as MethodModel from './models/method';
import * as PaymentModel from './models/payment';
import * as RefundModel from './models/refund';
import * as SubscriptionModel from './models/subscription';
/**
* Create Mollie client.
* @since 2.0.0
*/
export default function mollie(options: any = {}) {
if (!options.apiKey) {
throw new TypeError('Missing parameter "apiKey".');
}
const httpClient = createHttpClient(options);
return Object.assign({}, createMollieApi({ httpClient }), {
models: {
Chargeback: ChargebackModel,
Customer: CustomerModel,
Mandate: MandateModel,
Method: MethodModel,
Payment: PaymentModel,
Refund: RefundModel,
Subscription: SubscriptionModel,
},
});
}
| Change how models are exposed | Change how models are exposed
| TypeScript | bsd-3-clause | mollie/mollie-api-node,mollie/mollie-api-node,mollie/mollie-api-node | ---
+++
@@ -1,6 +1,5 @@
import createHttpClient from './create-http-client';
import createMollieApi from './create-mollie-api';
-
// Expose models
import * as ChargebackModel from './models/chargeback';
import * as CustomerModel from './models/customer';
@@ -21,15 +20,15 @@
const httpClient = createHttpClient(options);
- this.Models = {
- Chargeback: ChargebackModel,
- Customer: CustomerModel,
- Mandate: MandateModel,
- Method: MethodModel,
- Payment: PaymentModel,
- Refund: RefundModel,
- Subscription: SubscriptionModel,
- };
-
- return createMollieApi({ httpClient });
+ return Object.assign({}, createMollieApi({ httpClient }), {
+ models: {
+ Chargeback: ChargebackModel,
+ Customer: CustomerModel,
+ Mandate: MandateModel,
+ Method: MethodModel,
+ Payment: PaymentModel,
+ Refund: RefundModel,
+ Subscription: SubscriptionModel,
+ },
+ });
} |
21fdbfc10cd1028cbaac23a0bfed23969f52813f | src/eds-ui/src/main/frontend/app/dsa/purposeAdd.dialog.ts | src/eds-ui/src/main/frontend/app/dsa/purposeAdd.dialog.ts | import {Component, Input} from "@angular/core";
import {Dsa} from "./models/Dsa";
import {DsaService} from "./dsa.service";
import {LoggerService} from "eds-common-js";
import {NgbModal, NgbActiveModal} from "@ng-bootstrap/ng-bootstrap";
import {DsaPurpose} from "./models/DsaPurpose";
@Component({
selector: 'ngbd-modal-content',
template: require('./purposeAdd.html')
})
export class PurposeAddDialog {
public static open(modalService: NgbModal, purposes : DsaPurpose[]) {
const modalRef = modalService.open(PurposeAddDialog, { backdrop : "static"});
modalRef.componentInstance.resultData = jQuery.extend(true, [], purposes);
return modalRef;
}
@Input() resultData : DsaPurpose[];
title : string = '';
detail : string = '';
newPurpose : DsaPurpose = new DsaPurpose();
constructor(public activeModal: NgbActiveModal,
private log:LoggerService) {}
Add() {
this.newPurpose.title = this.title;
this.newPurpose.detail = this.detail;
this.resultData.push(this.newPurpose);
this.activeModal.close(this.resultData);
}
AddAnother() {
this.newPurpose.title = this.title;
this.newPurpose.detail = this.detail;
this.resultData.push(this.newPurpose);
this.title = '';
this.detail = '';
}
cancel() {
this.activeModal.dismiss('cancel');
}
}
| import {Component, Input} from "@angular/core";
import {Dsa} from "./models/Dsa";
import {DsaService} from "./dsa.service";
import {LoggerService} from "eds-common-js";
import {NgbModal, NgbActiveModal} from "@ng-bootstrap/ng-bootstrap";
import {DsaPurpose} from "./models/DsaPurpose";
@Component({
selector: 'ngbd-modal-content',
template: require('./purposeAdd.html')
})
export class PurposeAddDialog {
public static open(modalService: NgbModal, purposes : DsaPurpose[]) {
const modalRef = modalService.open(PurposeAddDialog, { backdrop : "static"});
modalRef.componentInstance.resultData = jQuery.extend(true, [], purposes);
return modalRef;
}
@Input() resultData : DsaPurpose[];
title : string = '';
detail : string = '';
constructor(public activeModal: NgbActiveModal,
private log:LoggerService) {}
Add() {
var newPurpose : DsaPurpose = new DsaPurpose();
newPurpose.title = this.title;
newPurpose.detail = this.detail;
this.resultData.push(newPurpose);
this.activeModal.close(this.resultData);
}
AddAnother() {
var newPurpose : DsaPurpose = new DsaPurpose();
newPurpose.title = this.title;
newPurpose.detail = this.detail;
this.resultData.push(newPurpose);
this.title = '';
this.detail = '';
}
cancel() {
this.activeModal.dismiss('cancel');
}
}
| Fix scope issue when adding multiple purposes | Fix scope issue when adding multiple purposes
| TypeScript | apache-2.0 | endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS | ---
+++
@@ -20,23 +20,24 @@
@Input() resultData : DsaPurpose[];
title : string = '';
detail : string = '';
- newPurpose : DsaPurpose = new DsaPurpose();
constructor(public activeModal: NgbActiveModal,
private log:LoggerService) {}
Add() {
- this.newPurpose.title = this.title;
- this.newPurpose.detail = this.detail;
- this.resultData.push(this.newPurpose);
+ var newPurpose : DsaPurpose = new DsaPurpose();
+ newPurpose.title = this.title;
+ newPurpose.detail = this.detail;
+ this.resultData.push(newPurpose);
this.activeModal.close(this.resultData);
}
AddAnother() {
- this.newPurpose.title = this.title;
- this.newPurpose.detail = this.detail;
- this.resultData.push(this.newPurpose);
+ var newPurpose : DsaPurpose = new DsaPurpose();
+ newPurpose.title = this.title;
+ newPurpose.detail = this.detail;
+ this.resultData.push(newPurpose);
this.title = '';
this.detail = '';
} |
18658caefdb8bb45fd8fc329c5a6e15ab3798b49 | app/src/renderer/components/paper/paper-icon-button.tsx | app/src/renderer/components/paper/paper-icon-button.tsx | // Copyright (c) 2016 Vadim Macagon
// MIT License, see LICENSE file for full terms.
import * as React from 'react';
import { PolymerComponent } from './polymer';
/**
* React component that wraps a Polymer paper-icon-button custom element.
*/
export class PaperIconButtonComponent
extends PolymerComponent<
PolymerElements.PaperIconButton, PaperIconButtonComponent.IProps, {}> {
protected get eventBindings() {
return [
{ event: 'tap', listener: 'onDidTap' }
];
}
protected renderElement(props: PaperIconButtonComponent.IProps) {
return (
<paper-icon-button {...props}></paper-icon-button>
);
}
}
namespace PaperIconButtonComponent {
export interface IProps extends PolymerComponent.IProps {
icon?: string;
/** Callback to invoke after the user taps on the button. */
onDidTap?: (e: polymer.TapEvent) => void;
}
}
| // Copyright (c) 2016 Vadim Macagon
// MIT License, see LICENSE file for full terms.
import * as React from 'react';
import { PolymerComponent } from './polymer';
import { omitOwnProps } from '../../../common/utils';
/**
* React component that wraps a Polymer paper-icon-button custom element.
*/
export class PaperIconButtonComponent
extends PolymerComponent<
PolymerElements.PaperIconButton, PaperIconButtonComponent.IProps, {}> {
protected get cssVars() {
const styles = this.props.styles;
const vars: any = {};
if (styles) {
if (styles.enabled) {
vars['--paper-icon-button'] = styles.enabled;
}
if (styles.disabled) {
vars['--paper-icon-button-disabled'] = styles.disabled;
}
if (styles.hover) {
vars['--paper-input-button-hover'] = styles.hover;
}
}
return vars;
}
protected get eventBindings() {
return [
{ event: 'tap', listener: 'onDidTap' }
];
}
protected renderElement(props: PaperIconButtonComponent.IProps) {
const elementProps = omitOwnProps(props, ['styles']);
return (
<paper-icon-button {...elementProps}></paper-icon-button>
);
}
}
namespace PaperIconButtonComponent {
export interface IProps extends PolymerComponent.IProps {
icon?: string;
styles?: {
/** CSS mixin to apply to the paper-icon-button. */
enabled?: React.CSSProperties;
/** CSS mixin to apply to the paper-icon-button when it's disabled. */
disabled?: React.CSSProperties;
/** CSS mixin to apply to the paper-icon-button on hover. */
hover?: React.CSSProperties;
};
/** Callback to invoke after the user taps on the button. */
onDidTap?: (e: polymer.TapEvent) => void;
}
}
| Make it easier to style PaperIconButtonComponent with CSS mixins | Make it easier to style PaperIconButtonComponent with CSS mixins
| TypeScript | mit | debugworkbench/hydragon,debugworkbench/hydragon,debugworkbench/hydragon | ---
+++
@@ -3,6 +3,7 @@
import * as React from 'react';
import { PolymerComponent } from './polymer';
+import { omitOwnProps } from '../../../common/utils';
/**
* React component that wraps a Polymer paper-icon-button custom element.
@@ -11,6 +12,24 @@
extends PolymerComponent<
PolymerElements.PaperIconButton, PaperIconButtonComponent.IProps, {}> {
+ protected get cssVars() {
+ const styles = this.props.styles;
+ const vars: any = {};
+
+ if (styles) {
+ if (styles.enabled) {
+ vars['--paper-icon-button'] = styles.enabled;
+ }
+ if (styles.disabled) {
+ vars['--paper-icon-button-disabled'] = styles.disabled;
+ }
+ if (styles.hover) {
+ vars['--paper-input-button-hover'] = styles.hover;
+ }
+ }
+ return vars;
+ }
+
protected get eventBindings() {
return [
{ event: 'tap', listener: 'onDidTap' }
@@ -18,8 +37,9 @@
}
protected renderElement(props: PaperIconButtonComponent.IProps) {
+ const elementProps = omitOwnProps(props, ['styles']);
return (
- <paper-icon-button {...props}></paper-icon-button>
+ <paper-icon-button {...elementProps}></paper-icon-button>
);
}
}
@@ -27,6 +47,14 @@
namespace PaperIconButtonComponent {
export interface IProps extends PolymerComponent.IProps {
icon?: string;
+ styles?: {
+ /** CSS mixin to apply to the paper-icon-button. */
+ enabled?: React.CSSProperties;
+ /** CSS mixin to apply to the paper-icon-button when it's disabled. */
+ disabled?: React.CSSProperties;
+ /** CSS mixin to apply to the paper-icon-button on hover. */
+ hover?: React.CSSProperties;
+ };
/** Callback to invoke after the user taps on the button. */
onDidTap?: (e: polymer.TapEvent) => void;
} |
dd1dfef513b70ab3156cb9b66856800efbc34252 | src/app/bestiary/bestiary-entry.model.ts | src/app/bestiary/bestiary-entry.model.ts | import { Die } from '../shared/die.model';
import { Data } from "../shared/data.interface";
export class BestiaryEntry implements Data<BestiaryEntry> {
constructor(
public ID:number|undefined = undefined,
public name:string="",
public description:string="",
public health:Die=new Die(),
public initiative:Die=new Die(1, 20),
public nameGeneratorID:number|undefined=undefined
) {}
fromJSON(raw:{
ID:number,
name:string,
description:string,
health:{
quantity:number,
sides:number,
modifier:number
},
initiative:undefined|{
quantity:number,
sides:number,
modifier:number
}
nameGeneratorID:number|undefined
}):BestiaryEntry {
if(!raw.health) {
// Backwards compatibility in case the initiative wasn't defined.
raw.health = { quantity: 1, sides: 20, modifier: 0};
}
return new BestiaryEntry(
raw.ID,
raw.name,
raw.description,
new Die(
raw.health.quantity,
raw.health.sides,
raw.health.modifier ),
new Die(
raw.health.quantity,
raw.health.sides,
raw.health.modifier ),
raw.nameGeneratorID);
}
}
| import { Die } from '../shared/die.model';
import { Data } from "../shared/data.interface";
export class BestiaryEntry implements Data<BestiaryEntry> {
constructor(
public ID:number|undefined = undefined,
public name:string="",
public description:string="",
public health:Die=new Die(),
public initiative:Die=new Die(1, 20),
public nameGeneratorID:number|undefined=undefined
) {}
fromJSON(raw:{
ID:number,
name:string,
description:string,
health:{
quantity:number,
sides:number,
modifier:number
},
initiative:undefined|{
quantity:number,
sides:number,
modifier:number
}
nameGeneratorID:number|undefined
}):BestiaryEntry {
if(!raw.initiative) {
// Backwards compatibility in case the initiative wasn't defined.
raw.initiative = { quantity: 1, sides: 20, modifier: 0};
}
return new BestiaryEntry(
raw.ID,
raw.name,
raw.description,
new Die(
raw.health.quantity,
raw.health.sides,
raw.health.modifier ),
new Die(
raw.initiative.quantity,
raw.initiative.sides,
raw.initiative.modifier ),
raw.nameGeneratorID);
}
}
| Fix bug where health was loaded as initiative. | Fix bug where health was loaded as initiative.
| TypeScript | mit | madigan/ncounter-ng2,madigan/ncounter-ng2,madigan/ncounter-ng2 | ---
+++
@@ -27,9 +27,9 @@
}
nameGeneratorID:number|undefined
}):BestiaryEntry {
- if(!raw.health) {
+ if(!raw.initiative) {
// Backwards compatibility in case the initiative wasn't defined.
- raw.health = { quantity: 1, sides: 20, modifier: 0};
+ raw.initiative = { quantity: 1, sides: 20, modifier: 0};
}
return new BestiaryEntry(
raw.ID,
@@ -40,9 +40,9 @@
raw.health.sides,
raw.health.modifier ),
new Die(
- raw.health.quantity,
- raw.health.sides,
- raw.health.modifier ),
+ raw.initiative.quantity,
+ raw.initiative.sides,
+ raw.initiative.modifier ),
raw.nameGeneratorID);
}
} |
9c8c5705c9d71df44881d71cda3a41b351f2e3f7 | src/app/public/ts/permalink.component.ts | src/app/public/ts/permalink.component.ts | import { ActivatedRoute } from '@angular/router'
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Socket } from '../../../services/socketio.service';
import { Title } from '@angular/platform-browser';
import { TranslateService } from '@ngx-translate/core';
import { User } from '../../../services/user.service';
@Component({
templateUrl: '../html/permalink.component.html'
})
export class PermalinkComponent implements OnInit, OnDestroy {
private currentMsg: any;
constructor(private titleService: Title, public translate: TranslateService,
private socket: Socket, public user: User,
private route: ActivatedRoute) {
}
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
this.socket.emit('msgInfo', id);
this.socket.on('msgInfo', (msgInfo:any) => {
this.currentMsg = msgInfo;
});
}
ngOnDestroy() {
this.socket.removeListener('msgInfo');
}
getCurrentMsg() {
return this.currentMsg;
}
}
| import { ActivatedRoute } from '@angular/router'
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Socket } from '../../../services/socketio.service';
import { Title } from '@angular/platform-browser';
import { TranslateService } from '@ngx-translate/core';
import { User } from '../../../services/user.service';
@Component({
templateUrl: '../html/permalink.component.html'
})
export class PermalinkComponent implements OnInit, OnDestroy {
private currentMsg: any;
constructor(private titleService: Title, public translate: TranslateService,
private socket: Socket, public user: User,
private route: ActivatedRoute) {
this.currentMsg = {};
}
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
this.socket.emit('msgInfo', id);
this.socket.on('msgInfo', (msgInfo:any) => {
this.currentMsg = msgInfo;
});
}
ngOnDestroy() {
this.socket.removeListener('msgInfo');
}
getCurrentMsg() {
return this.currentMsg;
}
}
| Define current msg as empty by default | Define current msg as empty by default | TypeScript | agpl-3.0 | V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War | ---
+++
@@ -16,6 +16,7 @@
constructor(private titleService: Title, public translate: TranslateService,
private socket: Socket, public user: User,
private route: ActivatedRoute) {
+ this.currentMsg = {};
}
ngOnInit() { |
60f57c203f65c9b25799ffaa21327042d5de2061 | web_client/app/models/mittens-chat/notification-signup.tsx | web_client/app/models/mittens-chat/notification-signup.tsx | import * as React from 'react';
import { Exchange } from "infrastructure/chat";
import { MittensChat } from "./mittens-chat";
import { Signup } from "components/signup/signup";
MittensChat.createGoal("notification-signup").exchanges = [
new Exchange(
[
"If you'd like me to remind you about upcoming elections, let me know your email address (I'll keep it secret and safe!)"
],
{
component: <Signup />
},
(state, signedup) => {
if (signedup) {
MittensChat.changeState({
goalName: "signed-up",
exchange: 0
});
} else {
MittensChat.changeState({
goalName: "declined-signup",
exchange: 0
});
}
})
];
| import * as React from 'react';
import { Exchange } from "infrastructure/chat";
import { MittensChat } from "./mittens-chat";
import { Signup } from "components/signup/signup";
MittensChat.createGoal("notification-signup").exchanges = [
new Exchange(
[
"If you'd like to stay in touch, let me know your email address (I'll keep it secret and safe!)"
],
{
component: <Signup />
},
(state, signedup) => {
if (signedup) {
MittensChat.changeState({
goalName: "signed-up",
exchange: 0
});
} else {
MittensChat.changeState({
goalName: "declined-signup",
exchange: 0
});
}
})
];
| Remove commitment to send email reminders | Remove commitment to send email reminders
| TypeScript | mit | citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement | ---
+++
@@ -6,7 +6,7 @@
MittensChat.createGoal("notification-signup").exchanges = [
new Exchange(
[
- "If you'd like me to remind you about upcoming elections, let me know your email address (I'll keep it secret and safe!)"
+ "If you'd like to stay in touch, let me know your email address (I'll keep it secret and safe!)"
],
{
component: <Signup /> |
7d70e0b4062d2d2ca0423fe80ea1bf3cdd8da4e1 | packages/components/containers/general/ShortcutsSection.tsx | packages/components/containers/general/ShortcutsSection.tsx | import React, { useState, useEffect } from 'react';
import { c } from 'ttag';
import { Row, Label, Field, SmallButton } from '../../components';
import { useMailSettings } from '../../hooks';
import ShortcutsToggle from './ShortcutsToggle';
interface Props {
onOpenShortcutsModal: () => void;
}
const ShortcutsSection = ({ onOpenShortcutsModal }: Props) => {
const [{ Hotkeys } = { Hotkeys: 0 }] = useMailSettings();
const [hotkeys, setHotkeys] = useState(Hotkeys);
// Handle updates from the Event Manager.
useEffect(() => {
setHotkeys(Hotkeys);
}, [Hotkeys]);
const handleChange = (newValue: number) => setHotkeys(newValue);
return (
<Row>
<Label htmlFor="hotkeysToggle">{c('Title').t`Keyboard shortcuts`}</Label>
<Field>
<div>
<ShortcutsToggle className="mr1" id="hotkeysToggle" hotkeys={hotkeys} onChange={handleChange} />
</div>
<div className="mt1">
<SmallButton onClick={onOpenShortcutsModal}>{c('Action').t`View keyboard shortcuts`}</SmallButton>
</div>
</Field>
</Row>
);
};
export default ShortcutsSection;
| import React, { useState, useEffect } from 'react';
import { c } from 'ttag';
import { Row, Label, Field, SmallButton } from '../../components';
import { useMailSettings } from '../../hooks';
import ShortcutsToggle from './ShortcutsToggle';
interface Props {
onOpenShortcutsModal: () => void;
}
const ShortcutsSection = ({ onOpenShortcutsModal }: Props) => {
const [{ Hotkeys } = { Hotkeys: 0 }] = useMailSettings();
const [hotkeys, setHotkeys] = useState(Hotkeys);
// Handle updates from the Event Manager.
useEffect(() => {
setHotkeys(Hotkeys);
}, [Hotkeys]);
const handleChange = (newValue: number) => setHotkeys(newValue);
return (
<Row>
<Label htmlFor="hotkeysToggle">{c('Title').t`Keyboard shortcuts`}</Label>
<Field>
<div>
<ShortcutsToggle className="mr1" id="hotkeysToggle" hotkeys={hotkeys} onChange={handleChange} />
</div>
<div className="mt1">
<SmallButton onClick={onOpenShortcutsModal}>{c('Action').t`Display keyboard shortcuts`}</SmallButton>
</div>
</Field>
</Row>
);
};
export default ShortcutsSection;
| Use the same message to open the shortcut modal | Use the same message to open the shortcut modal
INside ShortcutsSection.tsx and SupportDropdown.tsx
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -29,7 +29,7 @@
<ShortcutsToggle className="mr1" id="hotkeysToggle" hotkeys={hotkeys} onChange={handleChange} />
</div>
<div className="mt1">
- <SmallButton onClick={onOpenShortcutsModal}>{c('Action').t`View keyboard shortcuts`}</SmallButton>
+ <SmallButton onClick={onOpenShortcutsModal}>{c('Action').t`Display keyboard shortcuts`}</SmallButton>
</div>
</Field>
</Row> |
ce524feee0be9dd2b312e5efae5f0509e065075b | src/app/app.routes.ts | src/app/app.routes.ts | import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home';
import { AboutComponent } from './about';
import { NoContentComponent } from './no-content';
import { DataResolver } from './app.resolver';
import { StressComponent } from "./stress/stress.component";
export const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'stress', component: StressComponent },
{
path: 'detail', loadChildren: () => System.import('./+detail')
.then((comp: any) => comp.default),
},
{ path: '**', component: NoContentComponent },
];
| import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home';
import { AboutComponent } from './about';
import { NoContentComponent } from './no-content';
import { DataResolver } from './app.resolver';
import { StressComponent } from "./stress/stress.component";
export const ROUTES: Routes = [
{ path: '', component: StressComponent },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'stress', component: StressComponent },
{
path: 'detail', loadChildren: () => System.import('./+detail')
.then((comp: any) => comp.default),
},
{ path: '**', component: NoContentComponent },
];
| Change default route to stress | Change default route to stress
| TypeScript | mit | jacobjojan/angular2-webpack-starter,HipsterZipster/angular2-webpack-starter,jacobjojan/angular2-webpack-starter,HipsterZipster/angular2-webpack-starter,jacobjojan/angular2-webpack-starter,HipsterZipster/angular2-webpack-starter | ---
+++
@@ -8,7 +8,7 @@
export const ROUTES: Routes = [
- { path: '', component: HomeComponent },
+ { path: '', component: StressComponent },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'stress', component: StressComponent }, |
d966e1d712fb365122b6036dd7af3a444355e5ab | src/menu/bookmarks/components/TreeBar/Item/styles.ts | src/menu/bookmarks/components/TreeBar/Item/styles.ts | import styled from 'styled-components';
import opacity from '../../../../../shared/defaults/opacity';
import typography from '../../../../../shared/mixins/typography';
import images from '../../../../../shared/mixins/images';
const homeIcon = require('../../../../../shared/icons/home.svg');
export interface RootProps {
hovered: boolean;
}
export const Root = styled.div`
height: 32px;
margin-left: 4px;
padding-left: 4px;
padding-right: 4px;
display: flex;
align-items: center;
cursor: pointer;
border-radius: 4px;
transition: 0.2s background-color;
&:first-child {
margin-left: 0px;
}
&:hover {
background-color: rgba(0, 0, 0, 0.06);
}
`;
export const Title = styled.div`
padding-left: 2px;
padding-right: 2px;
font-size: 14px;
color: rgba(0, 0, 0, ${opacity.light.primaryText});
${typography.robotoMedium()};
`;
export const HomeIcon = styled.div`
width: 20px;
height: 20px;
background-image: url(${homeIcon});
transition: 0.2s opacity;
opacity: ${opacity.light.inactiveIcon};
${images.center('100%', 'auto')};
`;
| import styled from 'styled-components';
import opacity from '../../../../../shared/defaults/opacity';
import typography from '../../../../../shared/mixins/typography';
import images from '../../../../../shared/mixins/images';
const homeIcon = require('../../../../../shared/icons/home.svg');
export interface RootProps {
hovered: boolean;
}
export const Root = styled.div`
height: 32px;
margin-left: 4px;
padding-left: 4px;
padding-right: 4px;
display: flex;
align-items: center;
cursor: pointer;
border-radius: 4px;
transition: 0.2s background-color;
&:first-child {
margin-left: 0px;
}
&:hover {
background-color: rgba(0, 0, 0, 0.06);
}
`;
export const Title = styled.div`
padding-left: 2px;
padding-right: 2px;
font-size: 14px;
color: rgba(0, 0, 0, ${opacity.light.secondaryText});
${typography.robotoMedium()};
`;
export const HomeIcon = styled.div`
width: 20px;
height: 20px;
background-image: url(${homeIcon});
transition: 0.2s opacity;
opacity: ${opacity.light.inactiveIcon};
${images.center('100%', 'auto')};
`;
| Change TreeBar items text opacity to secondary | Change TreeBar items text opacity to secondary
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -34,7 +34,7 @@
padding-left: 2px;
padding-right: 2px;
font-size: 14px;
- color: rgba(0, 0, 0, ${opacity.light.primaryText});
+ color: rgba(0, 0, 0, ${opacity.light.secondaryText});
${typography.robotoMedium()};
`; |
31a91116674231815624542b99d95cbe7a64ed32 | src/file/table/table-column.ts | src/file/table/table-column.ts | import { TableCell, VMergeType } from "./table-cell";
export class TableColumn {
constructor(private readonly cells: TableCell[]) {}
public getCell(index: number): TableCell {
const cell = this.cells[index];
if (!cell) {
throw Error("Index out of bounds when trying to get cell on column");
}
return cell;
}
public mergeCells(startIndex: number, endIndex: number): TableCell {
this.cells[startIndex].addVerticalMerge(VMergeType.RESTART);
this.cells[endIndex].addVerticalMerge(VMergeType.CONTINUE);
return this.cells[startIndex];
}
}
| import { TableCell, VMergeType } from "./table-cell";
export class TableColumn {
constructor(private readonly cells: TableCell[]) {}
public getCell(index: number): TableCell {
const cell = this.cells[index];
if (!cell) {
throw Error("Index out of bounds when trying to get cell on column");
}
return cell;
}
public mergeCells(startIndex: number, endIndex: number): TableCell {
this.cells[startIndex].addVerticalMerge(VMergeType.RESTART);
for (let i = startIndex; i <= endIndex; i++) {
this.cells[i].addVerticalMerge(VMergeType.CONTINUE);
}
return this.cells[startIndex];
}
}
| Fix merging of 3+ cells vertically | Fix merging of 3+ cells vertically
| TypeScript | mit | dolanmiu/docx,dolanmiu/docx,dolanmiu/docx | ---
+++
@@ -15,7 +15,10 @@
public mergeCells(startIndex: number, endIndex: number): TableCell {
this.cells[startIndex].addVerticalMerge(VMergeType.RESTART);
- this.cells[endIndex].addVerticalMerge(VMergeType.CONTINUE);
+
+ for (let i = startIndex; i <= endIndex; i++) {
+ this.cells[i].addVerticalMerge(VMergeType.CONTINUE);
+ }
return this.cells[startIndex];
} |
0692edd2381159aa004995cfd973f4d6995170f8 | knockout.rx/knockout.rx.d.ts | knockout.rx/knockout.rx.d.ts | // Type definitions for knockout.rx 1.0
// Project: https://github.com/Igorbek/knockout.rx
// Definitions by: Igor Oleinikov <https://github.com/Igorbek>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../knockout/knockout.d.ts"/>
interface KnockoutSubscribableFunctions<T> {
toObservable(event?: string): Rx.Observable<T>;
toObservable<TEvent>(event: string): Rx.Observable<TEvent>;
}
interface KnockoutObservableFunctions<T> {
toObservableWithReplyLatest(): Rx.Observable<T>;
toSubject(): Rx.ISubject<T>;
}
interface KnockoutComputedFunctions<T> {
toObservableWithReplyLatest(): Rx.Observable<T>;
}
declare module Rx {
interface Observable<T> {
toKoSubscribable(): KnockoutSubscribable<T>;
toKoObservable(initialValue?: T): KnockoutObservable<T>;
}
interface Subject<T> {
toKoObservable(initialValue?: T): KnockoutObservable<T>;
}
}
| // Type definitions for knockout.rx 1.0
// Project: https://github.com/Igorbek/knockout.rx
// Definitions by: Igor Oleinikov <https://github.com/Igorbek>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../knockout/knockout.d.ts"/>
/// <reference path="../rx.js/rx.d.ts"/>
interface KnockoutSubscribableFunctions<T> {
toObservable(event?: string): Rx.Observable<T>;
toObservable<TEvent>(event: string): Rx.Observable<TEvent>;
}
interface KnockoutObservableFunctions<T> {
toObservableWithReplyLatest(): Rx.Observable<T>;
toSubject(): Rx.ISubject<T>;
}
interface KnockoutComputedFunctions<T> {
toObservableWithReplyLatest(): Rx.Observable<T>;
}
declare module Rx {
interface Observable<T> {
toKoSubscribable(): KnockoutSubscribable<T>;
toKoObservable(initialValue?: T): KnockoutObservable<T>;
}
interface Subject<T> {
toKoObservable(initialValue?: T): KnockoutObservable<T>;
}
}
| Revert "Remove useless reference to RxJS" | Revert "Remove useless reference to RxJS"
This reverts commit dc4d81a6bda11013ce1e1752a53a8cf00606adfd.
| TypeScript | mit | davidsidlinger/DefinitelyTyped,bluong/DefinitelyTyped,progre/DefinitelyTyped,arusakov/DefinitelyTyped,jimthedev/DefinitelyTyped,onecentlin/DefinitelyTyped,jasonswearingen/DefinitelyTyped,lseguin42/DefinitelyTyped,rcchen/DefinitelyTyped,bkristensen/DefinitelyTyped,dydek/DefinitelyTyped,olivierlemasle/DefinitelyTyped,ashwinr/DefinitelyTyped,Litee/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,forumone/DefinitelyTyped,Pro/DefinitelyTyped,amanmahajan7/DefinitelyTyped,drillbits/DefinitelyTyped,ciriarte/DefinitelyTyped,mrk21/DefinitelyTyped,richardTowers/DefinitelyTyped,mszczepaniak/DefinitelyTyped,danfma/DefinitelyTyped,musicist288/DefinitelyTyped,OpenMaths/DefinitelyTyped,amanmahajan7/DefinitelyTyped,RX14/DefinitelyTyped,shovon/DefinitelyTyped,reppners/DefinitelyTyped,goaty92/DefinitelyTyped,AgentME/DefinitelyTyped,use-strict/DefinitelyTyped,jpevarnek/DefinitelyTyped,tinganho/DefinitelyTyped,alexdresko/DefinitelyTyped,arma-gast/DefinitelyTyped,chbrown/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,sledorze/DefinitelyTyped,one-pieces/DefinitelyTyped,Mek7/DefinitelyTyped,sandersky/DefinitelyTyped,takenet/DefinitelyTyped,zuzusik/DefinitelyTyped,vpineda1996/DefinitelyTyped,miguelmq/DefinitelyTyped,Ptival/DefinitelyTyped,kanreisa/DefinitelyTyped,nfriend/DefinitelyTyped,herrmanno/DefinitelyTyped,dariajung/DefinitelyTyped,johan-gorter/DefinitelyTyped,jraymakers/DefinitelyTyped,magny/DefinitelyTyped,igorraush/DefinitelyTyped,mcrawshaw/DefinitelyTyped,giggio/DefinitelyTyped,Zorgatone/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,hellopao/DefinitelyTyped,superduper/DefinitelyTyped,egeland/DefinitelyTyped,Litee/DefinitelyTyped,DeadAlready/DefinitelyTyped,brentonhouse/DefinitelyTyped,martinduparc/DefinitelyTyped,furny/DefinitelyTyped,Dashlane/DefinitelyTyped,tgfjt/DefinitelyTyped,gildorwang/DefinitelyTyped,bennett000/DefinitelyTyped,paulmorphy/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,cesarmarinhorj/DefinitelyTyped,georgemarshall/DefinitelyTyped,duncanmak/DefinitelyTyped,TildaLabs/DefinitelyTyped,hellopao/DefinitelyTyped,use-strict/DefinitelyTyped,mjjames/DefinitelyTyped,laball/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,davidpricedev/DefinitelyTyped,reppners/DefinitelyTyped,psnider/DefinitelyTyped,abmohan/DefinitelyTyped,EnableSoftware/DefinitelyTyped,MarlonFan/DefinitelyTyped,stacktracejs/DefinitelyTyped,jtlan/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,AgentME/DefinitelyTyped,mweststrate/DefinitelyTyped,jeremyhayes/DefinitelyTyped,bdoss/DefinitelyTyped,Bunkerbewohner/DefinitelyTyped,minodisk/DefinitelyTyped,evansolomon/DefinitelyTyped,zuzusik/DefinitelyTyped,takenet/DefinitelyTyped,sclausen/DefinitelyTyped,trystanclarke/DefinitelyTyped,rfranco/DefinitelyTyped,axelcostaspena/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,aciccarello/DefinitelyTyped,whoeverest/DefinitelyTyped,vote539/DefinitelyTyped,biomassives/DefinitelyTyped,theyelllowdart/DefinitelyTyped,behzad888/DefinitelyTyped,pkhayundi/DefinitelyTyped,rushi216/DefinitelyTyped,gorcz/DefinitelyTyped,frogcjn/DefinitelyTyped,chrismbarr/DefinitelyTyped,benliddicott/DefinitelyTyped,stephenjelfs/DefinitelyTyped,gdi2290/DefinitelyTyped,AGBrown/DefinitelyTyped-ABContrib,egeland/DefinitelyTyped,dragouf/DefinitelyTyped,jesseschalken/DefinitelyTyped,jsaelhof/DefinitelyTyped,QuatroCode/DefinitelyTyped,gedaiu/DefinitelyTyped,Garciat/DefinitelyTyped,Minishlink/DefinitelyTyped,duongphuhiep/DefinitelyTyped,ecramer89/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,hafenr/DefinitelyTyped,philippsimon/DefinitelyTyped,benishouga/DefinitelyTyped,QuatroCode/DefinitelyTyped,alvarorahul/DefinitelyTyped,tigerxy/DefinitelyTyped,pocesar/DefinitelyTyped,yuit/DefinitelyTyped,newclear/DefinitelyTyped,tjoskar/DefinitelyTyped,syuilo/DefinitelyTyped,cherrydev/DefinitelyTyped,jbrantly/DefinitelyTyped,bardt/DefinitelyTyped,Pro/DefinitelyTyped,spearhead-ea/DefinitelyTyped,nainslie/DefinitelyTyped,innerverse/DefinitelyTyped,PascalSenn/DefinitelyTyped,dmoonfire/DefinitelyTyped,Pipe-shen/DefinitelyTyped,jimthedev/DefinitelyTyped,jraymakers/DefinitelyTyped,blink1073/DefinitelyTyped,alvarorahul/DefinitelyTyped,arma-gast/DefinitelyTyped,hatz48/DefinitelyTyped,tan9/DefinitelyTyped,masonkmeyer/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,mcliment/DefinitelyTyped,danfma/DefinitelyTyped,flyfishMT/DefinitelyTyped,EnableSoftware/DefinitelyTyped,OfficeDev/DefinitelyTyped,teves-castro/DefinitelyTyped,adammartin1981/DefinitelyTyped,teves-castro/DefinitelyTyped,OpenMaths/DefinitelyTyped,nitintutlani/DefinitelyTyped,hiraash/DefinitelyTyped,Dominator008/DefinitelyTyped,subjectix/DefinitelyTyped,michalczukm/DefinitelyTyped,bdoss/DefinitelyTyped,laco0416/DefinitelyTyped,emanuelhp/DefinitelyTyped,amir-arad/DefinitelyTyped,corps/DefinitelyTyped,chocolatechipui/DefinitelyTyped,mshmelev/DefinitelyTyped,alextkachman/DefinitelyTyped,donnut/DefinitelyTyped,stylelab-io/DefinitelyTyped,syuilo/DefinitelyTyped,deeleman/DefinitelyTyped,mattblang/DefinitelyTyped,aroder/DefinitelyTyped,jacqt/DefinitelyTyped,brainded/DefinitelyTyped,robert-voica/DefinitelyTyped,emanuelhp/DefinitelyTyped,nainslie/DefinitelyTyped,psnider/DefinitelyTyped,aindlq/DefinitelyTyped,quantumman/DefinitelyTyped,WritingPanda/DefinitelyTyped,pwelter34/DefinitelyTyped,philippsimon/DefinitelyTyped,Almouro/DefinitelyTyped,leoromanovsky/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,olemp/DefinitelyTyped,greglockwood/DefinitelyTyped,smrq/DefinitelyTyped,UzEE/DefinitelyTyped,vincentw56/DefinitelyTyped,newclear/DefinitelyTyped,sixinli/DefinitelyTyped,Zenorbi/DefinitelyTyped,scriby/DefinitelyTyped,vagarenko/DefinitelyTyped,paxibay/DefinitelyTyped,pafflique/DefinitelyTyped,maglar0/DefinitelyTyped,jeffbcross/DefinitelyTyped,shiwano/DefinitelyTyped,pocke/DefinitelyTyped,benishouga/DefinitelyTyped,HPFOD/DefinitelyTyped,dpsthree/DefinitelyTyped,vasek17/DefinitelyTyped,Ptival/DefinitelyTyped,panuhorsmalahti/DefinitelyTyped,dmoonfire/DefinitelyTyped,Deathspike/DefinitelyTyped,HPFOD/DefinitelyTyped,nodeframe/DefinitelyTyped,martinduparc/DefinitelyTyped,georgemarshall/DefinitelyTyped,rcchen/DefinitelyTyped,donnut/DefinitelyTyped,bennett000/DefinitelyTyped,dwango-js/DefinitelyTyped,mhegazy/DefinitelyTyped,gregoryagu/DefinitelyTyped,muenchdo/DefinitelyTyped,teddyward/DefinitelyTyped,elisee/DefinitelyTyped,magny/DefinitelyTyped,rschmukler/DefinitelyTyped,arcticwaters/DefinitelyTyped,mattanja/DefinitelyTyped,NCARalph/DefinitelyTyped,arueckle/DefinitelyTyped,glenndierckx/DefinitelyTyped,trystanclarke/DefinitelyTyped,esperco/DefinitelyTyped,progre/DefinitelyTyped,vote539/DefinitelyTyped,fredgalvao/DefinitelyTyped,modifyink/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,rockclimber90/DefinitelyTyped,isman-usoh/DefinitelyTyped,M-Zuber/DefinitelyTyped,abner/DefinitelyTyped,ayanoin/DefinitelyTyped,Lorisu/DefinitelyTyped,tan9/DefinitelyTyped,shiwano/DefinitelyTyped,borisyankov/DefinitelyTyped,pwelter34/DefinitelyTyped,georgemarshall/DefinitelyTyped,tscho/DefinitelyTyped,IAPark/DefinitelyTyped,opichals/DefinitelyTyped,chrootsu/DefinitelyTyped,hatz48/DefinitelyTyped,schmuli/DefinitelyTyped,gcastre/DefinitelyTyped,nmalaguti/DefinitelyTyped,TheBay0r/DefinitelyTyped,bencoveney/DefinitelyTyped,basp/DefinitelyTyped,syntax42/DefinitelyTyped,xswordsx/DefinitelyTyped,nseckinoral/DefinitelyTyped,kmeurer/DefinitelyTyped,zalamtech/DefinitelyTyped,hx0day/DefinitelyTyped,rschmukler/DefinitelyTyped,timramone/DefinitelyTyped,philippstucki/DefinitelyTyped,adamcarr/DefinitelyTyped,maxlang/DefinitelyTyped,arcticwaters/DefinitelyTyped,smrq/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,kuon/DefinitelyTyped,Nemo157/DefinitelyTyped,florentpoujol/DefinitelyTyped,DeluxZ/DefinitelyTyped,omidkrad/DefinitelyTyped,mwain/DefinitelyTyped,darkl/DefinitelyTyped,behzad888/DefinitelyTyped,mattblang/DefinitelyTyped,nabeix/DefinitelyTyped,xStrom/DefinitelyTyped,dflor003/DefinitelyTyped,samdark/DefinitelyTyped,ryan10132/DefinitelyTyped,jimthedev/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,esperco/DefinitelyTyped,lekaha/DefinitelyTyped,lightswitch05/DefinitelyTyped,mareek/DefinitelyTyped,kabogo/DefinitelyTyped,alainsahli/DefinitelyTyped,optical/DefinitelyTyped,damianog/DefinitelyTyped,GregOnNet/DefinitelyTyped,uestcNaldo/DefinitelyTyped,Syati/DefinitelyTyped,fishgoh0nk/DefinitelyTyped,Fraegle/DefinitelyTyped,erosb/DefinitelyTyped,Chris380/DefinitelyTyped,abbasmhd/DefinitelyTyped,Zorgatone/DefinitelyTyped,samwgoldman/DefinitelyTyped,shahata/DefinitelyTyped,chrilith/DefinitelyTyped,davidpricedev/DefinitelyTyped,chrootsu/DefinitelyTyped,panuhorsmalahti/DefinitelyTyped,xStrom/DefinitelyTyped,jsaelhof/DefinitelyTyped,greglo/DefinitelyTyped,subash-a/DefinitelyTyped,haskellcamargo/DefinitelyTyped,JaminFarr/DefinitelyTyped,wilfrem/DefinitelyTyped,psnider/DefinitelyTyped,nitintutlani/DefinitelyTyped,tomtarrot/DefinitelyTyped,Seltzer/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,rerezz/DefinitelyTyped,manekovskiy/DefinitelyTyped,abbasmhd/DefinitelyTyped,schmuli/DefinitelyTyped,olemp/DefinitelyTyped,rolandzwaga/DefinitelyTyped,jiaz/DefinitelyTyped,sclausen/DefinitelyTyped,zuzusik/DefinitelyTyped,nelsonmorais/DefinitelyTyped,ashwinr/DefinitelyTyped,flyfishMT/DefinitelyTyped,dumbmatter/DefinitelyTyped,algorithme/DefinitelyTyped,robl499/DefinitelyTyped,grahammendick/DefinitelyTyped,damianog/DefinitelyTyped,scsouthw/DefinitelyTyped,scriby/DefinitelyTyped,philippstucki/DefinitelyTyped,icereed/DefinitelyTyped,hesselink/DefinitelyTyped,dreampulse/DefinitelyTyped,RX14/DefinitelyTyped,aciccarello/DefinitelyTyped,ajtowf/DefinitelyTyped,fearthecowboy/DefinitelyTyped,minodisk/DefinitelyTyped,paulmorphy/DefinitelyTyped,lukehoban/DefinitelyTyped,PopSugar/DefinitelyTyped,arusakov/DefinitelyTyped,BrandonCKrueger/DefinitelyTyped,Carreau/DefinitelyTyped,glenndierckx/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,gandjustas/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,jasonswearingen/DefinitelyTyped,florentpoujol/DefinitelyTyped,modifyink/DefinitelyTyped,aciccarello/DefinitelyTyped,tarruda/DefinitelyTyped,shlomiassaf/DefinitelyTyped,bobslaede/DefinitelyTyped,gyohk/DefinitelyTyped,eugenpodaru/DefinitelyTyped,mhegazy/DefinitelyTyped,pocesar/DefinitelyTyped,georgemarshall/DefinitelyTyped,timjk/DefinitelyTyped,miguelmq/DefinitelyTyped,NelsonLamprecht/DefinitelyTyped,mattanja/DefinitelyTyped,raijinsetsu/DefinitelyTyped,tdmckinn/DefinitelyTyped,hellopao/DefinitelyTyped,musically-ut/DefinitelyTyped,GodsBreath/DefinitelyTyped,chrismbarr/DefinitelyTyped,borisyankov/DefinitelyTyped,benishouga/DefinitelyTyped,mrozhin/DefinitelyTyped,iCoreSolutions/DefinitelyTyped,drinchev/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,gcastre/DefinitelyTyped,elisee/DefinitelyTyped,pocesar/DefinitelyTyped,jaysoo/DefinitelyTyped,MidnightDesign/DefinitelyTyped,zuohaocheng/DefinitelyTyped,lbesson/DefinitelyTyped,Penryn/DefinitelyTyped,frogcjn/DefinitelyTyped,wilfrem/DefinitelyTyped,bjfletcher/DefinitelyTyped,johan-gorter/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,arusakov/DefinitelyTyped,Dominator008/DefinitelyTyped,jccarvalhosa/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,markogresak/DefinitelyTyped,KonaTeam/DefinitelyTyped,stanislavHamara/DefinitelyTyped,bruennijs/DefinitelyTyped,tgfjt/DefinitelyTyped,nakakura/DefinitelyTyped,Trapulo/DefinitelyTyped,munxar/DefinitelyTyped,mendix/DefinitelyTyped,DenEwout/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,LordJZ/DefinitelyTyped,vagarenko/DefinitelyTyped,zhiyiting/DefinitelyTyped,SebastianCoetzee/DefinitelyTyped,Zzzen/DefinitelyTyped,DustinWehr/DefinitelyTyped,ErykB2000/DefinitelyTyped,stacktracejs/DefinitelyTyped,mareek/DefinitelyTyped,robertbaker/DefinitelyTyped,nycdotnet/DefinitelyTyped,bpowers/DefinitelyTyped,Gmulti/DefinitelyTyped,gandjustas/DefinitelyTyped,ahmedalsudani/DefinitelyTyped,nmalaguti/DefinitelyTyped,micurs/DefinitelyTyped,Kuniwak/DefinitelyTyped,Dashlane/DefinitelyTyped,AgentME/DefinitelyTyped,YousefED/DefinitelyTyped,kalloc/DefinitelyTyped,TanakaYutaro/DefinitelyTyped,acepoblete/DefinitelyTyped,awerlang/DefinitelyTyped,angelobelchior8/DefinitelyTyped,Karabur/DefinitelyTyped,onecentlin/DefinitelyTyped,bobslaede/DefinitelyTyped,aqua89/DefinitelyTyped,billccn/DefinitelyTyped,mshmelev/DefinitelyTyped,mjjames/DefinitelyTyped,optical/DefinitelyTyped,scatcher/DefinitelyTyped,nycdotnet/DefinitelyTyped,greglo/DefinitelyTyped,hypno2000/typings,ducin/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,Jwsonic/DefinitelyTyped,fredgalvao/DefinitelyTyped,nojaf/DefinitelyTyped,the41/DefinitelyTyped,Shiak1/DefinitelyTyped,tboyce/DefinitelyTyped,stephenjelfs/DefinitelyTyped,fnipo/DefinitelyTyped,wcomartin/DefinitelyTyped,yuit/DefinitelyTyped,digitalpixies/DefinitelyTyped,applesaucers/lodash-invokeMap,eekboom/DefinitelyTyped,felipe3dfx/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,Bobjoy/DefinitelyTyped,Zzzen/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,aldo-roman/DefinitelyTyped,schmuli/DefinitelyTyped,HereSinceres/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,Saneyan/DefinitelyTyped,ajtowf/DefinitelyTyped,nakakura/DefinitelyTyped,zensh/DefinitelyTyped,dsebastien/DefinitelyTyped,raijinsetsu/DefinitelyTyped,behzad88/DefinitelyTyped,Ridermansb/DefinitelyTyped,martinduparc/DefinitelyTyped,brettle/DefinitelyTyped,daptiv/DefinitelyTyped,bilou84/DefinitelyTyped,subash-a/DefinitelyTyped,hor-crux/DefinitelyTyped,nobuoka/DefinitelyTyped,Karabur/DefinitelyTyped,igorsechyn/DefinitelyTyped,UzEE/DefinitelyTyped,RedSeal-co/DefinitelyTyped,Riron/DefinitelyTyped,wkrueger/DefinitelyTyped,MugeSo/DefinitelyTyped,CSharpFan/DefinitelyTyped,wbuchwalter/DefinitelyTyped,alextkachman/DefinitelyTyped,abner/DefinitelyTyped,takfjt/DefinitelyTyped,evandrewry/DefinitelyTyped,drinchev/DefinitelyTyped,gyohk/DefinitelyTyped,applesaucers/lodash-invokeMap,cvrajeesh/DefinitelyTyped,xica/DefinitelyTyped,sledorze/DefinitelyTyped,unknownloner/DefinitelyTyped,mcrawshaw/DefinitelyTyped,tomtheisen/DefinitelyTyped,lucyhe/DefinitelyTyped,isman-usoh/DefinitelyTyped,Penryn/DefinitelyTyped,ml-workshare/DefinitelyTyped,rolandzwaga/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,mvarblow/DefinitelyTyped,chadoliver/DefinitelyTyped,vsavkin/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,shlomiassaf/DefinitelyTyped,Syati/DefinitelyTyped,dydek/DefinitelyTyped,lbguilherme/DefinitelyTyped,moonpyk/DefinitelyTyped,Seikho/DefinitelyTyped,YousefED/DefinitelyTyped,MugeSo/DefinitelyTyped,musakarakas/DefinitelyTyped,almstrand/DefinitelyTyped,alexdresko/DefinitelyTyped,nobuoka/DefinitelyTyped | ---
+++
@@ -4,6 +4,7 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../knockout/knockout.d.ts"/>
+/// <reference path="../rx.js/rx.d.ts"/>
interface KnockoutSubscribableFunctions<T> {
toObservable(event?: string): Rx.Observable<T>; |
f57dc9cee65483eac287ea1747893fff3aabec95 | src/frontend/redux/store.ts | src/frontend/redux/store.ts | import * as Redux from 'redux'
import {rootReducer, rootReducerMock} from './reducers'
declare global {
interface Window {
__REDUX_DEVTOOLS_EXTENSION__: Function
}
}
const configureStore = (): Redux.Store<any> => {
const devtools = window.__REDUX_DEVTOOLS_EXTENSION__
const _module = module as any
if (_module.hot) {
const store = Redux.createStore(rootReducerMock, devtools && devtools())
_module.hot.accept('./reducers', () => store.replaceReducer(require('./reducers')))
return store
}
const store = Redux.createStore(rootReducer, devtools && devtools())
return store
}
const store = configureStore()
export default store
| import * as Redux from 'redux'
import {rootReducer} from './reducers'
// TODO: put back rootReducerMock
// import {rootReducer, rootReducerMock} from './reducers'
declare global {
interface Window {
__REDUX_DEVTOOLS_EXTENSION__: Function
}
}
const configureStore = (): Redux.Store<any> => {
const devtools = window.__REDUX_DEVTOOLS_EXTENSION__
const _module = module as any
if (_module.hot) {
const store = Redux.createStore(rootReducer, devtools && devtools())
_module.hot.accept('./reducers', () => store.replaceReducer(require('./reducers')))
return store
}
const store = Redux.createStore(rootReducer, devtools && devtools())
return store
}
const store = configureStore()
export default store
| Comment out rootReducerMock for now | Comment out rootReducerMock for now
| TypeScript | mit | devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity | ---
+++
@@ -1,5 +1,7 @@
import * as Redux from 'redux'
-import {rootReducer, rootReducerMock} from './reducers'
+import {rootReducer} from './reducers'
+// TODO: put back rootReducerMock
+// import {rootReducer, rootReducerMock} from './reducers'
declare global {
interface Window {
@@ -12,7 +14,7 @@
const _module = module as any
if (_module.hot) {
- const store = Redux.createStore(rootReducerMock, devtools && devtools())
+ const store = Redux.createStore(rootReducer, devtools && devtools())
_module.hot.accept('./reducers', () => store.replaceReducer(require('./reducers')))
return store
} |
0a1373b6ec1b008ab22f7deb4f56884039f3cd23 | test/index.ts | test/index.ts | import * as path from 'path';
import * as Mocha from 'mocha';
import * as glob from 'glob';
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd',
});
mocha.useColors(true);
const testsRoot = path.resolve(__dirname, '..');
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
e(err);
}
});
});
}
| import * as path from 'path';
import * as Mocha from 'mocha';
import * as glob from 'glob';
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd',
color: true
});
const testsRoot = path.resolve(__dirname, '..');
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
e(err);
}
});
});
}
| Use new property to tell Mocha to use colors | Use new property to tell Mocha to use colors
| TypeScript | mit | DAXaholic/vscode-edifact | ---
+++
@@ -6,8 +6,8 @@
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd',
+ color: true
});
- mocha.useColors(true);
const testsRoot = path.resolve(__dirname, '..');
|
ae422d6ffe5c83c0f87b7a15defd068c62b97940 | src/dev.pakl.ttvst/renderer/Pages/SettingsPage.ts | src/dev.pakl.ttvst/renderer/Pages/SettingsPage.ts | import Page from '../UI/Page';
import _ttvst from '../TTVST';
import * as riot from 'riot';
import SettingsMenu from '../../../../dist/dev.pakl.ttvst/renderer/UI/Settings/SettingsMenu';
import SettingsConfig from '../UI/Settings/SettingsConfiguration';
declare var TTVST: _ttvst;
class SettingsPage extends Page {
settings: riot.RiotComponent = null;
constructor() {
super('Settings');
}
get icon(): any {
return 'Settings';
}
content(): HTMLElement {
let settCmpnt = riot.component<null, null>(SettingsMenu);
this.settings = settCmpnt(document.createElement('SettingsMenu'));
this.settings.setSettings(SettingsConfig);
return this.settings.root;
}
}
export = SettingsPage; | import Page from '../UI/Page';
import _ttvst from '../TTVST';
import * as riot from 'riot';
import SettingsMenu from '../../../../dist/dev.pakl.ttvst/renderer/UI/Settings/SettingsMenu';
import SettingsConfig from '../UI/Settings/SettingsConfiguration';
import { ISettingsSetProps } from '../UI/Settings/SettingsConfiguration';
declare var TTVST: _ttvst;
class SettingsPage extends Page {
settingsCmpnt: riot.RiotComponent = null;
settings: Array<ISettingsSetProps> = [];
constructor() {
super('Settings');
this.settings = this.settings.concat(SettingsConfig);
}
get icon(): any {
return 'Settings';
}
content(): HTMLElement {
let settCmpnt = riot.component<null, null>(SettingsMenu);
this.settingsCmpnt = settCmpnt(document.createElement('SettingsMenu'));
this.settingsCmpnt.setSettings(this.settings);
return this.settingsCmpnt.root;
}
addSettingsSet(settings: ISettingsSetProps) {
this.settings.push(settings);
this.settingsCmpnt.setSettings(this.settings);
}
update() {
this.settingsCmpnt.update();
}
}
export = SettingsPage; | Allow for settings to be added | Allow for settings to be added
| TypeScript | mit | PakL/TTVStreamerTool,PakL/TTVStreamerTool,PakL/TTVStreamerTool | ---
+++
@@ -5,15 +5,19 @@
import SettingsMenu from '../../../../dist/dev.pakl.ttvst/renderer/UI/Settings/SettingsMenu';
import SettingsConfig from '../UI/Settings/SettingsConfiguration';
+import { ISettingsSetProps } from '../UI/Settings/SettingsConfiguration';
declare var TTVST: _ttvst;
class SettingsPage extends Page {
- settings: riot.RiotComponent = null;
+ settingsCmpnt: riot.RiotComponent = null;
+ settings: Array<ISettingsSetProps> = [];
constructor() {
super('Settings');
+
+ this.settings = this.settings.concat(SettingsConfig);
}
get icon(): any {
@@ -22,11 +26,20 @@
content(): HTMLElement {
let settCmpnt = riot.component<null, null>(SettingsMenu);
- this.settings = settCmpnt(document.createElement('SettingsMenu'));
+ this.settingsCmpnt = settCmpnt(document.createElement('SettingsMenu'));
- this.settings.setSettings(SettingsConfig);
+ this.settingsCmpnt.setSettings(this.settings);
- return this.settings.root;
+ return this.settingsCmpnt.root;
+ }
+
+ addSettingsSet(settings: ISettingsSetProps) {
+ this.settings.push(settings);
+ this.settingsCmpnt.setSettings(this.settings);
+ }
+
+ update() {
+ this.settingsCmpnt.update();
}
} |
da5c634880b1f077ac6b6b55a3a7e08324e2ac18 | src/elements/types/object.ts | src/elements/types/object.ts | import {Container} from '../../collections';
import {emit_object} from '../../helpers/emit-object';
import {ObjectMember} from '../members/object';
import {Type} from '../type';
// tslint:disable-next-line no-empty-interface
export interface IObjectTypeRequiredParameters {}
export interface IObjectTypeOptionalParameters {
children: ObjectMember[];
}
export class ObjectType extends Type<IObjectTypeRequiredParameters, IObjectTypeOptionalParameters> {
public get default_parameters(): IObjectTypeOptionalParameters {
return {
children: [],
};
}
public _emit(_container: Container): string {
const {children} = this.parameters;
return emit_object(children, this);
}
}
| import {Container} from '../../collections';
import {emit_object} from '../../helpers/emit-object';
import {ObjectMember} from '../members/object';
import {Type} from '../type';
export interface IObjectTypeRequiredParameters {
children: ObjectMember[];
}
// tslint:disable-next-line no-empty-interface
export interface IObjectTypeOptionalParameters {}
export class ObjectType extends Type<IObjectTypeRequiredParameters, IObjectTypeOptionalParameters> {
public get default_parameters(): IObjectTypeOptionalParameters {
return {};
}
public _emit(_container: Container): string {
const {children} = this.parameters;
return emit_object(children, this);
}
}
| Update ObjectType children should be required parameter | Update ObjectType
children should be required parameter
| TypeScript | mit | ikatyang/dts-element,ikatyang/dts-element | ---
+++
@@ -3,19 +3,17 @@
import {ObjectMember} from '../members/object';
import {Type} from '../type';
-// tslint:disable-next-line no-empty-interface
-export interface IObjectTypeRequiredParameters {}
-
-export interface IObjectTypeOptionalParameters {
+export interface IObjectTypeRequiredParameters {
children: ObjectMember[];
}
+
+// tslint:disable-next-line no-empty-interface
+export interface IObjectTypeOptionalParameters {}
export class ObjectType extends Type<IObjectTypeRequiredParameters, IObjectTypeOptionalParameters> {
public get default_parameters(): IObjectTypeOptionalParameters {
- return {
- children: [],
- };
+ return {};
}
public _emit(_container: Container): string { |
399fe0fb1da41976e7e5120d52752ce5a81d8207 | src/Documents/Queries/HashCalculator.ts | src/Documents/Queries/HashCalculator.ts | import * as md5 from "md5";
import { TypeUtil } from "../../Utility/TypeUtil";
import { TypesAwareObjectMapper } from "../../Mapping/ObjectMapper";
export class HashCalculator {
private _buffers: Buffer[] = [];
public getHash(): string {
return md5(Buffer.concat(this._buffers));
}
//TBD 4.1 public void Write(HighlightedField[] highlightedFields)
public write(o: any, mapper?: TypesAwareObjectMapper) {
if (TypeUtil.isNullOrUndefined(o)) {
this._buffers.push(Buffer.from("null"));
return;
}
if (typeof o === "number") {
this._buffers.push(Buffer.from([o]));
} else if (typeof o === "string") {
this._buffers.push(Buffer.from(o));
} else if (typeof o === "boolean") {
this._buffers.push(Buffer.from(o ? [1] : [2]));
} else if (Array.isArray(o)) {
for (const item of o) {
this.write(item, mapper);
}
} else if (typeof o === "object") {
for (const key of Object.keys(o)) {
this.write(key, mapper);
this.write(o[key], mapper);
}
} else {
this.write(mapper.toObjectLiteral(o), mapper);
}
}
}
| import * as md5 from "md5";
import { TypeUtil } from "../../Utility/TypeUtil";
import { TypesAwareObjectMapper } from "../../Mapping/ObjectMapper";
const typeSignatures = {
bigint: Buffer.from([1]),
boolean: Buffer.from([2]),
function: Buffer.from([3]),
number: Buffer.from([4]),
object: Buffer.from([5]),
string: Buffer.from([6]),
symbol: Buffer.from([7]),
undefined: Buffer.from([8]),
};
export class HashCalculator {
private _buffers: Buffer[] = [];
public getHash(): string {
return md5(Buffer.concat(this._buffers));
}
//TBD 4.1 public void Write(HighlightedField[] highlightedFields)
public write(o: any, mapper?: TypesAwareObjectMapper) {
if (TypeUtil.isNullOrUndefined(o)) {
this._buffers.push(Buffer.from("null"));
return;
}
// Push a byte that identifies the type, to differentiate strings, numbers, and bools
this._buffers.push(typeSignatures[typeof o] || typeSignatures.undefined);
if (typeof o === "number") {
this._buffers.push(Buffer.from([o]));
} else if (typeof o === "string") {
this._buffers.push(Buffer.from(o));
} else if (typeof o === "boolean") {
this._buffers.push(Buffer.from(o ? [1] : [2]));
} else if (Array.isArray(o)) {
for (const item of o) {
this.write(item, mapper);
}
} else if (typeof o === "object") {
for (const key of Object.keys(o)) {
this.write(key, mapper);
this.write(o[key], mapper);
}
} else {
this.write(mapper.toObjectLiteral(o), mapper);
}
}
}
| Add type signatures to query hashes | Add type signatures to query hashes
| TypeScript | mit | ravendb/ravendb-nodejs-client,ravendb/ravendb-nodejs-client | ---
+++
@@ -1,6 +1,17 @@
import * as md5 from "md5";
import { TypeUtil } from "../../Utility/TypeUtil";
import { TypesAwareObjectMapper } from "../../Mapping/ObjectMapper";
+
+const typeSignatures = {
+ bigint: Buffer.from([1]),
+ boolean: Buffer.from([2]),
+ function: Buffer.from([3]),
+ number: Buffer.from([4]),
+ object: Buffer.from([5]),
+ string: Buffer.from([6]),
+ symbol: Buffer.from([7]),
+ undefined: Buffer.from([8]),
+};
export class HashCalculator {
@@ -17,6 +28,9 @@
this._buffers.push(Buffer.from("null"));
return;
}
+
+ // Push a byte that identifies the type, to differentiate strings, numbers, and bools
+ this._buffers.push(typeSignatures[typeof o] || typeSignatures.undefined);
if (typeof o === "number") {
this._buffers.push(Buffer.from([o])); |
df1f5f3bbace7f54ef7f1172656d582d73523b29 | tests/intern-saucelabs.ts | tests/intern-saucelabs.ts | export * from './intern';
export const environments = [
{ browserName: 'internet explorer', version: [ '10.0', '11.0' ], platform: 'Windows 7' },
/* Having issues with Edge with Intern and SauceLabs */
// { browserName: 'MicrosoftEdge', platform: 'Windows 10' },
{ browserName: 'firefox', platform: 'Windows 10' },
{ browserName: 'chrome', platform: 'Windows 10' },
/* Having issues with Intern 3.1 and Safari on SauceLabs */
// { browserName: 'safari', version: '8.0', platform: 'OS X 10.10' },
// { browserName: 'safari', version: '9.0', platform: 'OS X 10.11' },
{ browserName: 'android', deviceName: 'Google Nexus 7 HD Emulator' },
{ browserName: 'iphone', version: '7.1' }
/* saucelabs has stability issues with iphone 8.4, 9.1 and 9.2 */
];
/* SauceLabs supports more max concurrency */
export const maxConcurrency = 4;
export const tunnel = 'SauceLabsTunnel';
| export * from './intern';
export const environments = [
{ browserName: 'internet explorer', version: [ '10.0', '11.0' ], platform: 'Windows 7' },
/* Having issues with Edge with Intern and SauceLabs */
// { browserName: 'MicrosoftEdge', platform: 'Windows 10' },
// { browserName: 'firefox', platform: 'Windows 10' },
{ browserName: 'chrome', platform: 'Windows 10' },
/* Having issues with Intern 3.1 and Safari on SauceLabs */
// { browserName: 'safari', version: '8.0', platform: 'OS X 10.10' },
// { browserName: 'safari', version: '9.0', platform: 'OS X 10.11' },
{ browserName: 'android', deviceName: 'Google Nexus 7 HD Emulator' },
{ browserName: 'iphone', version: '7.1' }
/* saucelabs has stability issues with iphone 8.4, 9.1 and 9.2 */
];
/* SauceLabs supports more max concurrency */
export const maxConcurrency = 4;
export const tunnel = 'SauceLabsTunnel';
| Remove firefox from SauceLab tests | Remove firefox from SauceLab tests
| TypeScript | bsd-3-clause | edhager/widget-core,edhager/widget-core,edhager/widget-core,edhager/widget-core | ---
+++
@@ -4,7 +4,7 @@
{ browserName: 'internet explorer', version: [ '10.0', '11.0' ], platform: 'Windows 7' },
/* Having issues with Edge with Intern and SauceLabs */
// { browserName: 'MicrosoftEdge', platform: 'Windows 10' },
- { browserName: 'firefox', platform: 'Windows 10' },
+ // { browserName: 'firefox', platform: 'Windows 10' },
{ browserName: 'chrome', platform: 'Windows 10' },
/* Having issues with Intern 3.1 and Safari on SauceLabs */
// { browserName: 'safari', version: '8.0', platform: 'OS X 10.10' }, |
f5084045f216c79702ad7124ae72a7144d014881 | public/app/features/dashboard/components/SaveModals/index.ts | public/app/features/dashboard/components/SaveModals/index.ts | export { SaveDashboardAsModalCtrl } from './SaveDashboardAsModalCtrl';
export { SaveDashboardModalCtrl } from './SaveDashboardModalCtrl';
| export { SaveDashboardAsModalCtrl } from './SaveDashboardAsModalCtrl';
export { SaveDashboardModalCtrl } from './SaveDashboardModalCtrl';
export { SaveProvisionedDashboardModalCtrl } from './SaveProvisionedDashboardModalCtrl';
| Fix save provisioned dashboard modal | Fix save provisioned dashboard modal
| TypeScript | agpl-3.0 | grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana | ---
+++
@@ -1,2 +1,3 @@
export { SaveDashboardAsModalCtrl } from './SaveDashboardAsModalCtrl';
export { SaveDashboardModalCtrl } from './SaveDashboardModalCtrl';
+export { SaveProvisionedDashboardModalCtrl } from './SaveProvisionedDashboardModalCtrl'; |
7de2659a424ca472388bc7169fb80b802a69c0c6 | src/config.ts | src/config.ts | import * as localForage from 'localforage';
import * as immutableTransform from 'redux-persist-transform-immutable';
import {
PERSISTED_STATE_WHITELIST,
IMMUTABLE_PERSISTED_STATE_WHITELIST
} from './constants/settings';
export const config = {
reduxPersistSettings: {
whitelist: PERSISTED_STATE_WHITELIST,
storage: localForage,
transforms: [
immutableTransform({
whitelist: IMMUTABLE_PERSISTED_STATE_WHITELIST
})
]
},
reduxPersistErrorCallback: (err?: Error) =>
err
? console.warn(
`There was an issue retrieving your Mturk Engine settings. Error Log: ` +
err
)
: undefined,
// tslint:disable:no-any
// tslint:disable:no-string-literal
devtools: window['__REDUX_DEVTOOLS_EXTENSION__']
? window['__REDUX_DEVTOOLS_EXTENSION__']()
: () => ({})
};
| import * as localForage from 'localforage';
import * as immutableTransform from 'redux-persist-transform-immutable';
import {
PERSISTED_STATE_WHITELIST,
IMMUTABLE_PERSISTED_STATE_WHITELIST
} from './constants/settings';
import { compose } from 'redux';
export const config = {
reduxPersistSettings: {
whitelist: PERSISTED_STATE_WHITELIST,
storage: localForage,
transforms: [
immutableTransform({
whitelist: IMMUTABLE_PERSISTED_STATE_WHITELIST
})
]
},
reduxPersistErrorCallback: (err?: Error) =>
err
? console.warn(
`There was an issue retrieving your Mturk Engine settings. Error Log: ` +
err
)
: undefined,
// tslint:disable:no-string-literal
devtools: window['__REDUX_DEVTOOLS_EXTENSION__']
? window['__REDUX_DEVTOOLS_EXTENSION__']()
: compose
};
| Fix crash when redux devtools extension is not installed. | Fix crash when redux devtools extension is not installed.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -4,6 +4,7 @@
PERSISTED_STATE_WHITELIST,
IMMUTABLE_PERSISTED_STATE_WHITELIST
} from './constants/settings';
+import { compose } from 'redux';
export const config = {
reduxPersistSettings: {
@@ -22,9 +23,8 @@
err
)
: undefined,
- // tslint:disable:no-any
// tslint:disable:no-string-literal
devtools: window['__REDUX_DEVTOOLS_EXTENSION__']
? window['__REDUX_DEVTOOLS_EXTENSION__']()
- : () => ({})
+ : compose
}; |
a01b302530451b9cece38806e68b304a27c8f1b3 | src/index.tsx | src/index.tsx | import * as React from 'react';
import {
applyMiddleware,
createStore,
combineReducers,
compose,
} from 'redux';
import * as ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import * as ReactGA from 'react-ga';
import * as injectTapEventPlugin from 'react-tap-event-plugin';
// Initialize google analytics
ReactGA.initialize('UA-101530055-1');
injectTapEventPlugin();
import App from './App';
import PlaygroundReducer from './Playground/reducer';
import './index.css';
const reducer = combineReducers({
playground: PlaygroundReducer,
});
// tslint:disable-next-line:no-string-literal
const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
// tslint:disable-next-line:no-any
reducer,
composeEnhancers(
applyMiddleware(
thunkMiddleware
)
),
);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root') as HTMLElement,
() => {
ReactGA.pageview(window.location.hash);
}
);
| import * as React from 'react';
import {
applyMiddleware,
createStore,
combineReducers,
compose,
} from 'redux';
import * as ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import * as ReactGA from 'react-ga';
import * as injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import App from './App';
import PlaygroundReducer from './Playground/reducer';
import './index.css';
const reducer = combineReducers({
playground: PlaygroundReducer,
});
// tslint:disable-next-line:no-string-literal
const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
// tslint:disable-next-line:no-any
reducer,
composeEnhancers(
applyMiddleware(
thunkMiddleware
)
),
);
// Initialize google analytics
ReactGA.initialize('UA-101530055-1');
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root') as HTMLElement,
() => {
ReactGA.pageview(window.location.pathname);
}
);
| Fix call to GA pageview | Fix call to GA pageview
| TypeScript | mit | fsahmad/tsuml-demo,fsahmad/tsuml-demo,fsahmad/tsuml-demo | ---
+++
@@ -10,9 +10,6 @@
import thunkMiddleware from 'redux-thunk';
import * as ReactGA from 'react-ga';
import * as injectTapEventPlugin from 'react-tap-event-plugin';
-
-// Initialize google analytics
-ReactGA.initialize('UA-101530055-1');
injectTapEventPlugin();
@@ -37,12 +34,15 @@
),
);
+// Initialize google analytics
+ReactGA.initialize('UA-101530055-1');
+
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root') as HTMLElement,
() => {
- ReactGA.pageview(window.location.hash);
+ ReactGA.pageview(window.location.pathname);
}
); |
f5952435dd00a9906995b7426b2664f8c3da3729 | src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular-ui/src/lib/features-module/language-switch/language-switch.component.ts | src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular-ui/src/lib/features-module/language-switch/language-switch.component.ts | import { Component } from '@angular/core';
import { Language, LanguageService } from '@picturepark/sdk-v1-angular';
@Component({
selector: 'pp-language-switch',
templateUrl: './language-switch.component.html',
styleUrls: ['./language-switch.component.scss'],
})
export class LanguageSwitchComponent {
get languages(): Language[] {
return this.languageService.languages;
}
get selectedLanguageCode(): string {
return this.languageService.currentLanguage.ietf;
}
constructor(private languageService: LanguageService) {}
public changeLanguage(languageCode: string) {
this.languageService.changeCurrentLanguage(languageCode);
window.location.reload();
}
}
| import { Component } from '@angular/core';
import { Language, LanguageService } from '@picturepark/sdk-v1-angular';
import { TranslatePipe } from '../../shared-module/pipes/translate.pipe';
@Component({
selector: 'pp-language-switch',
templateUrl: './language-switch.component.html',
styleUrls: ['./language-switch.component.scss'],
})
export class LanguageSwitchComponent {
languages: Language[];
get selectedLanguageCode(): string {
return this.languageService.currentLanguage.ietf;
}
constructor(private languageService: LanguageService, translatePipe: TranslatePipe) {
this.languages = this.languageService.languages.sort((a, b) =>
translatePipe.transform(a.name) < translatePipe.transform(b.name) ? -1 : 1
);
}
public changeLanguage(languageCode: string) {
this.languageService.changeCurrentLanguage(languageCode);
window.location.reload();
}
}
| Fix sort language switch items alphabethical. | PP9-11554: Fix sort language switch items alphabethical.
| TypeScript | mit | Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript | ---
+++
@@ -1,5 +1,6 @@
import { Component } from '@angular/core';
import { Language, LanguageService } from '@picturepark/sdk-v1-angular';
+import { TranslatePipe } from '../../shared-module/pipes/translate.pipe';
@Component({
selector: 'pp-language-switch',
@@ -7,14 +8,17 @@
styleUrls: ['./language-switch.component.scss'],
})
export class LanguageSwitchComponent {
- get languages(): Language[] {
- return this.languageService.languages;
- }
+ languages: Language[];
+
get selectedLanguageCode(): string {
return this.languageService.currentLanguage.ietf;
}
- constructor(private languageService: LanguageService) {}
+ constructor(private languageService: LanguageService, translatePipe: TranslatePipe) {
+ this.languages = this.languageService.languages.sort((a, b) =>
+ translatePipe.transform(a.name) < translatePipe.transform(b.name) ? -1 : 1
+ );
+ }
public changeLanguage(languageCode: string) {
this.languageService.changeCurrentLanguage(languageCode); |
e9b20c800a3e2162bd96f323b073efb5606bb56e | app/scripts/modules/core/src/application/modal/PlatformHealthOverride.tsx | app/scripts/modules/core/src/application/modal/PlatformHealthOverride.tsx | import * as React from 'react';
import { isEqual } from 'lodash';
import { IServerGroupCommand } from 'core/serverGroup';
import { HelpField } from 'core/help/HelpField';
export interface IPlatformHealthOverrideProps {
command: IServerGroupCommand;
onChange: (healthProviderNames: string[]) => void;
platformHealthType: string;
showHelpDetails?: boolean;
}
export class PlatformHealthOverride extends React.Component<IPlatformHealthOverrideProps> {
private clicked = (event: React.ChangeEvent<HTMLInputElement>) => {
const interestingHealthProviderNames = event.target.checked ? [this.props.platformHealthType] : null;
this.props.onChange(interestingHealthProviderNames);
};
public render() {
return (
<div className="checkbox">
<label>
<input
type="checkbox"
checked={isEqual(this.props.command.interestingHealthProviderNames, [this.props.platformHealthType])}
onChange={this.clicked}
/>
Consider only {this.props.platformHealthType} health
</label>
<HelpField id="application.platformHealthOnly" expand={this.props.showHelpDetails} />
</div>
);
}
}
| import * as React from 'react';
import { isEqual } from 'lodash';
import { IServerGroupCommand } from 'core/serverGroup';
import { HelpField } from 'core/help/HelpField';
export interface IPlatformHealthOverrideProps {
command: IServerGroupCommand;
onChange: (healthProviderNames: string[]) => void;
platformHealthType: string;
showHelpDetails?: boolean;
}
export class PlatformHealthOverride extends React.Component<IPlatformHealthOverrideProps> {
private clicked = (event: React.ChangeEvent<HTMLInputElement>) => {
const interestingHealthProviderNames = event.target.checked ? [this.props.platformHealthType] : null;
this.props.onChange(interestingHealthProviderNames);
};
public render() {
return (
<div className="checkbox">
<label>
<input
type="checkbox"
checked={isEqual(this.props.command.interestingHealthProviderNames, [this.props.platformHealthType])}
onChange={this.clicked}
/>
Consider only {this.props.platformHealthType} health
</label>{' '}
<HelpField id="application.platformHealthOnly" expand={this.props.showHelpDetails} />
</div>
);
}
}
| Fix whitespace in platform health override | fix(core/deploy): Fix whitespace in platform health override
| TypeScript | apache-2.0 | spinnaker/deck,sgarlick987/deck,icfantv/deck,ajordens/deck,spinnaker/deck,duftler/deck,spinnaker/deck,icfantv/deck,icfantv/deck,duftler/deck,duftler/deck,ajordens/deck,ajordens/deck,sgarlick987/deck,sgarlick987/deck,spinnaker/deck,duftler/deck,icfantv/deck,ajordens/deck,sgarlick987/deck | ---
+++
@@ -27,7 +27,7 @@
onChange={this.clicked}
/>
Consider only {this.props.platformHealthType} health
- </label>
+ </label>{' '}
<HelpField id="application.platformHealthOnly" expand={this.props.showHelpDetails} />
</div>
); |
5ce9656a940207a8157c8cd2e6f9b72324777936 | src/Diploms.WebUI/ClientApp/app/auth/auth.module.ts | src/Diploms.WebUI/ClientApp/app/auth/auth.module.ts | import { NgModule, ModuleWithProviders } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './interceptors/token.interceptor';
import { JwtHelper } from './helpers/jwt.helper';
import { TokenService } from './services/token.service';
import { AuthService } from './services/auth.service';
import { RefreshInterceptor } from './interceptors/refresh.interceptor';
@NgModule({
imports: [],
declarations: [],
exports: [],
providers: [
JwtHelper,
AuthService,
TokenService,
{
provide: HTTP_INTERCEPTORS,
useClass: RefreshInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},
],
})
export class AuthModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: AuthModule,
providers: [TokenService]
};
}
} | import { NgModule, ModuleWithProviders } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './interceptors/token.interceptor';
import { JwtHelper } from './helpers/jwt.helper';
import { TokenService } from './services/token.service';
import { AuthService } from './services/auth.service';
import { RefreshInterceptor } from './interceptors/refresh.interceptor';
import { AuthInfoService } from './services/auth-info.service';
import { AuthGuard } from './guards/auth.guard';
@NgModule({
imports: [],
declarations: [],
exports: [],
providers: [
JwtHelper,
AuthService,
AuthInfoService,
TokenService,
{
provide: HTTP_INTERCEPTORS,
useClass: RefreshInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},
AuthGuard
],
})
export class AuthModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: AuthModule,
providers: [TokenService]
};
}
} | Add AuthInfo and AuthGuard into the AuthModule | Add AuthInfo and AuthGuard into the AuthModule
| TypeScript | mit | denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs | ---
+++
@@ -5,6 +5,8 @@
import { TokenService } from './services/token.service';
import { AuthService } from './services/auth.service';
import { RefreshInterceptor } from './interceptors/refresh.interceptor';
+import { AuthInfoService } from './services/auth-info.service';
+import { AuthGuard } from './guards/auth.guard';
@NgModule({
@@ -14,6 +16,7 @@
providers: [
JwtHelper,
AuthService,
+ AuthInfoService,
TokenService,
{
provide: HTTP_INTERCEPTORS,
@@ -25,6 +28,7 @@
useClass: TokenInterceptor,
multi: true
},
+ AuthGuard
],
})
export class AuthModule { |
4c602ce5e28f27c1e8a2a46bf9b948359d71992b | packages/@sanity/base/src/client/index.ts | packages/@sanity/base/src/client/index.ts | import config from 'config:sanity'
import configureClient from 'part:@sanity/base/configure-client?'
import sanityClient from '@sanity/client'
const deprecationMessage = `[deprecation] The Sanity client is now exposed in CommonJS format.
For instance, change:
\`const client = require('part:@sanity/base/client').default\`
To the following:
\`const client = require('part:@sanity/base/client')\`
`
const fallbackConfig = {projectId: 'UNSPECIFIED', dataset: 'UNSPECIFIED'}
const apiConfig = {...fallbackConfig, ...config.api, withCredentials: true, useCdn: false}
const client = sanityClient(apiConfig)
const configuredClient = configureClient ? configureClient(sanityClient(apiConfig)) : client
// Warn when people use `.default`
Object.defineProperty(configuredClient, 'default', {
get() {
// eslint-disable-next-line no-console
console.warn(deprecationMessage)
return configuredClient
}
})
// Expose as CJS to allow Node scripts to consume it without `.default`
// eslint-disable-next-line @typescript-eslint/no-var-requires
module.exports = configuredClient
| import config from 'config:sanity'
import configureClient from 'part:@sanity/base/configure-client?'
import sanityClient, {SanityClient} from '@sanity/client'
const deprecationMessage = `[deprecation] The Sanity client is now exposed in CommonJS format.
For instance, change:
\`const client = require('part:@sanity/base/client').default\`
To the following:
\`const client = require('part:@sanity/base/client')\`
`
const fallbackConfig = {projectId: 'UNSPECIFIED', dataset: 'UNSPECIFIED'}
const apiConfig = {...fallbackConfig, ...config.api, withCredentials: true, useCdn: false}
const client = sanityClient(apiConfig)
const configuredClient = experimental(
configureClient ? configureClient(sanityClient(apiConfig)) : client
)
function experimental(original: SanityClient): SanityClient {
let useExperimental = false
try {
useExperimental = Boolean(window.localStorage.vx)
} catch (err) {
// nah
}
if (!useExperimental) {
return original
}
;[original.clientConfig as any, original.observable.clientConfig as any].forEach(cfg => {
cfg.url = cfg.url.replace(/\/v1$/, '/vX')
cfg.cdnUrl = cfg.cdnUrl.replace(/\/v1$/, '/vX')
})
return original
}
// Warn when people use `.default`
Object.defineProperty(configuredClient, 'default', {
get() {
// eslint-disable-next-line no-console
console.warn(deprecationMessage)
return configuredClient
}
})
// Expose as CJS to allow Node scripts to consume it without `.default`
// eslint-disable-next-line @typescript-eslint/no-var-requires
module.exports = configuredClient
| Add ability to use experimental API version (localStorage flag) | [base] Add ability to use experimental API version (localStorage flag)
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -1,6 +1,6 @@
import config from 'config:sanity'
import configureClient from 'part:@sanity/base/configure-client?'
-import sanityClient from '@sanity/client'
+import sanityClient, {SanityClient} from '@sanity/client'
const deprecationMessage = `[deprecation] The Sanity client is now exposed in CommonJS format.
@@ -15,7 +15,29 @@
const apiConfig = {...fallbackConfig, ...config.api, withCredentials: true, useCdn: false}
const client = sanityClient(apiConfig)
-const configuredClient = configureClient ? configureClient(sanityClient(apiConfig)) : client
+const configuredClient = experimental(
+ configureClient ? configureClient(sanityClient(apiConfig)) : client
+)
+
+function experimental(original: SanityClient): SanityClient {
+ let useExperimental = false
+ try {
+ useExperimental = Boolean(window.localStorage.vx)
+ } catch (err) {
+ // nah
+ }
+
+ if (!useExperimental) {
+ return original
+ }
+
+ ;[original.clientConfig as any, original.observable.clientConfig as any].forEach(cfg => {
+ cfg.url = cfg.url.replace(/\/v1$/, '/vX')
+ cfg.cdnUrl = cfg.cdnUrl.replace(/\/v1$/, '/vX')
+ })
+
+ return original
+}
// Warn when people use `.default`
Object.defineProperty(configuredClient, 'default', { |
3ce1b2c9856242c369d4a988f3d0d59159ff95ba | src/lib/ng-bootstrap-form-validation.module.ts | src/lib/ng-bootstrap-form-validation.module.ts | import { CommonModule } from "@angular/common";
import { NgModule, ModuleWithProviders } from "@angular/core";
import { FormValidationDirective } from "./Directives/form-validation.directive";
import { FormGroupComponent } from "./Components/form-group-component/form-group-component";
import { ErrorMessageService } from "./Services/error-message.service";
import { ErrorMessage } from "./Models/ErrorMessage";
import { CUSTOM_ERROR_MESSAGES } from "./Tokens/tokens";
@NgModule({
declarations: [FormValidationDirective, FormGroupComponent],
imports: [CommonModule],
providers: [ErrorMessageService],
exports: [FormValidationDirective, FormGroupComponent]
})
export class NgBootstrapFormValidationModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: NgBootstrapFormValidationModule,
providers: [
ErrorMessageService,
{
provide: CUSTOM_ERROR_MESSAGES,
useValue: [],
multi: true
}
]
};
}
}
| import { CommonModule } from "@angular/common";
import { NgModule, ModuleWithProviders } from "@angular/core";
import { FormValidationDirective } from "./Directives/form-validation.directive";
import { FormGroupComponent } from "./Components/form-group-component/form-group-component";
import { ErrorMessageService } from "./Services/error-message.service";
import { ErrorMessage } from "./Models/ErrorMessage";
import { CUSTOM_ERROR_MESSAGES } from "./Tokens/tokens";
@NgModule({
declarations: [FormValidationDirective, FormGroupComponent],
imports: [CommonModule],
providers: [ErrorMessageService],
exports: [FormValidationDirective, FormGroupComponent]
})
export class NgBootstrapFormValidationModule {
static forRoot(
customErrorMessages: ErrorMessage[] = []
): ModuleWithProviders {
return {
ngModule: NgBootstrapFormValidationModule,
providers: [
ErrorMessageService,
{
provide: CUSTOM_ERROR_MESSAGES,
useValue: customErrorMessages,
multi: true
}
]
};
}
}
| Use message from forRoot as muli-provider base | Use message from forRoot as muli-provider base
| TypeScript | mit | third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation | ---
+++
@@ -13,14 +13,16 @@
exports: [FormValidationDirective, FormGroupComponent]
})
export class NgBootstrapFormValidationModule {
- static forRoot(): ModuleWithProviders {
+ static forRoot(
+ customErrorMessages: ErrorMessage[] = []
+ ): ModuleWithProviders {
return {
ngModule: NgBootstrapFormValidationModule,
providers: [
ErrorMessageService,
{
provide: CUSTOM_ERROR_MESSAGES,
- useValue: [],
+ useValue: customErrorMessages,
multi: true
}
] |
4785f0158789d8fee2d5a2b06e2d81b46748cd70 | packages/schematics/angular/application/other-files/app.component.spec.ts | packages/schematics/angular/application/other-files/app.component.spec.ts | import { TestBed, async } from '@angular/core/testing';<% if (routing) { %>
import { RouterTestingModule } from '@angular/router/testing';<% } %>
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({<% if (routing) { %>
imports: [
RouterTestingModule
],<% } %>
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title '<%= name %>'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('<%= name %>');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to <%= prefix %>!');
}));
});
| import { TestBed, async } from '@angular/core/testing';<% if (routing) { %>
import { RouterTestingModule } from '@angular/router/testing';<% } %>
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({<% if (routing) { %>
imports: [
RouterTestingModule
],<% } %>
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title '<%= name %>'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('<%= name %>');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to <%= name %>!');
}));
});
| Fix broken unit test on new app | fix(@schematics/angular): Fix broken unit test on new app
| TypeScript | mit | hansl/devkit,hansl/devkit,hansl/devkit,hansl/devkit | ---
+++
@@ -26,6 +26,6 @@
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
- expect(compiled.querySelector('h1').textContent).toContain('Welcome to <%= prefix %>!');
+ expect(compiled.querySelector('h1').textContent).toContain('Welcome to <%= name %>!');
}));
}); |
c4c9bf70c429fd5a22537691f841cfc5867db0b9 | tests/cases/fourslash/completionListOfUnion.ts | tests/cases/fourslash/completionListOfUnion.ts | /// <reference path='fourslash.ts' />
// @strictNullChecks: true
// Non-objects should be skipped, so `| number | null` should have no effect on completions.
////const x: { a: number, b: number } | { a: string, c: string } | { b: boolean } | number | null = { /*x*/ };
////interface I { a: number; }
////function f(...args: Array<I | I[]>) {}
////f({ /*f*/ });
goTo.marker("x");
verify.completionListCount(3);
verify.completionListContains("a", "(property) a: string | number");
verify.completionListContains("b", "(property) b: number | boolean");
verify.completionListContains("c", "(property) c: string");
goTo.marker("f");
verify.completionListContains("a", "(property) a: number");
// Also contains array members
| /// <reference path='fourslash.ts' />
// @strictNullChecks: true
// Primitives should be skipped, so `| number | null | undefined` should have no effect on completions.
////const x: { a: number, b: number } | { a: string, c: string } | { b: boolean } | number | null | undefined = { /*x*/ };
////interface I { a: number; }
////function f(...args: Array<I | I[]>) {}
////f({ /*f*/ });
goTo.marker("x");
verify.completionListCount(3);
verify.completionListContains("a", "(property) a: string | number");
verify.completionListContains("b", "(property) b: number | boolean");
verify.completionListContains("c", "(property) c: string");
goTo.marker("f");
verify.completionListContains("a", "(property) a: number");
// Also contains array members
| Add `| undefined` to test | Add `| undefined` to test
| TypeScript | apache-2.0 | minestarks/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,basarat/TypeScript,Microsoft/TypeScript,RyanCavanaugh/TypeScript,donaldpipowitch/TypeScript,mihailik/TypeScript,kitsonk/TypeScript,Eyas/TypeScript,nojvek/TypeScript,TukekeSoft/TypeScript,kpreisser/TypeScript,mihailik/TypeScript,chuckjaz/TypeScript,RyanCavanaugh/TypeScript,SaschaNaz/TypeScript,synaptek/TypeScript,kitsonk/TypeScript,chuckjaz/TypeScript,RyanCavanaugh/TypeScript,donaldpipowitch/TypeScript,basarat/TypeScript,donaldpipowitch/TypeScript,SaschaNaz/TypeScript,chuckjaz/TypeScript,kitsonk/TypeScript,kpreisser/TypeScript,Eyas/TypeScript,mihailik/TypeScript,Microsoft/TypeScript,synaptek/TypeScript,kpreisser/TypeScript,donaldpipowitch/TypeScript,weswigham/TypeScript,microsoft/TypeScript,alexeagle/TypeScript,mihailik/TypeScript,TukekeSoft/TypeScript,basarat/TypeScript,chuckjaz/TypeScript,SaschaNaz/TypeScript,microsoft/TypeScript,microsoft/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,synaptek/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,minestarks/TypeScript,basarat/TypeScript,Eyas/TypeScript,TukekeSoft/TypeScript,Microsoft/TypeScript,Eyas/TypeScript,synaptek/TypeScript,minestarks/TypeScript,weswigham/TypeScript,weswigham/TypeScript | ---
+++
@@ -2,8 +2,8 @@
// @strictNullChecks: true
-// Non-objects should be skipped, so `| number | null` should have no effect on completions.
-////const x: { a: number, b: number } | { a: string, c: string } | { b: boolean } | number | null = { /*x*/ };
+// Primitives should be skipped, so `| number | null | undefined` should have no effect on completions.
+////const x: { a: number, b: number } | { a: string, c: string } | { b: boolean } | number | null | undefined = { /*x*/ };
////interface I { a: number; }
////function f(...args: Array<I | I[]>) {} |
9070d68b069d930d9166efeb56cd53d0cfa539fb | src/index.ts | src/index.ts | import * as C from './combinators';
import * as T from './types/index';
import * as S from './seq';
import { Arbitrary } from './arbitrary';
import hold from './integrations/index';
import { property, TestResult, forAll, ForAll } from './property';
const namespace = Object.assign({}, C, T, {
seq: S,
forAll: forAll,
property: property,
hold: hold
});
export default namespace; | import * as C from './combinators';
import * as T from './types/index';
import * as S from './seq';
import { Arbitrary } from './arbitrary';
import hold from './integrations/index';
import { property, TestResult, forAll, ForAll } from './property';
const namespace = Object.assign({}, C, T, {
seq: S,
forAll: forAll,
property: property,
hold: hold,
register: function register(name: string, module: Object) {
if (namespace.hasOwnProperty(name)) {
throw new Error(`${name} is registered.`);
}
namespace[name] = module;
return true;
}
});
export default namespace; | Add ke.register to add a new type/library in ke namespace. | Add ke.register to add a new type/library in ke namespace.
Example:
```
$ ke.register('chance', ke.number.choose(0, 1).set('name', 'Chance'))
```
| TypeScript | mit | hychen/ke-e,hychen/ke-e | ---
+++
@@ -9,7 +9,14 @@
seq: S,
forAll: forAll,
property: property,
- hold: hold
+ hold: hold,
+ register: function register(name: string, module: Object) {
+ if (namespace.hasOwnProperty(name)) {
+ throw new Error(`${name} is registered.`);
+ }
+ namespace[name] = module;
+ return true;
+ }
});
export default namespace; |
72d3f7de35b2639e7b1a1f0ceba97347850b3677 | DeadBaseSample/src/DeadBaseSample/TypeScriptSource/deadbase.ts | DeadBaseSample/src/DeadBaseSample/TypeScriptSource/deadbase.ts | import { bootstrap, Component } from 'angular2/angular2';
@Component({
selector: 'deadbase-app',
template: '<h1>{{title}}</h1><h2>{{venue}} Details!</h2>'
})
class DeadBaseAppComponent {
public title = "Deadbase - Grateful Dead Concert Archive";
public venue = "Filmore West";
}
bootstrap(DeadBaseAppComponent);
| import { bootstrap, Component } from 'angular2/angular2';
class ConcertSet {
date: Date;
venue: string;
set: number;
}
@Component({
selector: 'deadbase-app',
template: '<h1>{{title}}</h1><h2>{{concert.date}} -- {{concert.venue}} Details!</h2>'
})
class DeadBaseAppComponent {
public title = "Deadbase - Grateful Dead Concert Archive";
public concert: ConcertSet = {
date: new Date(1971, 7, 2),
venue: "Filmore West",
set: 2
}
}
bootstrap(DeadBaseAppComponent);
| Create class for a concert set | Create class for a concert set
| TypeScript | mit | BillWagner/TypeScriptAngular2,BillWagner/TypeScriptAngular2,BillWagner/TypeScriptAngular2,BillWagner/TypeScriptAngular2 | ---
+++
@@ -1,12 +1,23 @@
import { bootstrap, Component } from 'angular2/angular2';
+
+class ConcertSet {
+ date: Date;
+ venue: string;
+ set: number;
+}
+
@Component({
selector: 'deadbase-app',
- template: '<h1>{{title}}</h1><h2>{{venue}} Details!</h2>'
+ template: '<h1>{{title}}</h1><h2>{{concert.date}} -- {{concert.venue}} Details!</h2>'
})
class DeadBaseAppComponent {
public title = "Deadbase - Grateful Dead Concert Archive";
- public venue = "Filmore West";
+ public concert: ConcertSet = {
+ date: new Date(1971, 7, 2),
+ venue: "Filmore West",
+ set: 2
+ }
}
bootstrap(DeadBaseAppComponent); |
092a5164043632802dfa56ec51b7c6658794fe5f | test/reducers/slides/actions/moveSlideDown-spec.ts | test/reducers/slides/actions/moveSlideDown-spec.ts | import { expect } from 'chai';
import { MOVE_SLIDE_DOWN } from '../../../../app/constants/slides.constants';
export default function(initialState: any, reducer: any, slide: any) {
const dummySlide1 = {
plugins: ['plugin1'],
state: {
backgroundColor: { r: 255, g: 255, b: 255, a: 100 },
transition: {
right: 'rotate-push-left-move-from-right',
left: 'rotate-push-right-move-from-left',
}
}
};
describe('MOVE_SLIDE_DOWN', () => {
it('should not move the slide when current selected slide is 0', () => {
expect(
reducer(initialState, {
type: MOVE_SLIDE_DOWN,
slideNumber: 0
})
).to.deep.equal(initialState);
});
it('should swap slide 1 and slide 0 when slide 1 is active', () => {
const _initialState = [slide, dummySlide1];
expect(
reducer(_initialState, {
type: MOVE_SLIDE_DOWN,
slideNumber: 1
})
).to.deep.equal([dummySlide1, slide]);
});
});
}
| import { expect } from 'chai';
import { MOVE_SLIDE_DOWN } from '../../../../app/constants/slides.constants';
export default function(initialState: any, reducer: any, slide: any) {
const dummySlide1 = {
plugins: ['plugin1'],
state: {
backgroundColor: { r: 255, g: 255, b: 255, a: 100 },
transition: {
right: 'rotate-push-left-move-from-right',
left: 'rotate-push-right-move-from-left',
}
}
};
describe('MOVE_SLIDE_DOWN', () => {
const _initialState = [slide, dummySlide1];
it('should not move the slide when the first slide is selected', () => {
expect(
reducer(_initialState, {
type: MOVE_SLIDE_DOWN,
slideNumber: 0
})
).to.deep.equal(_initialState);
});
it('should swap slide 1 and slide 0 when slide 1 is active', () => {
expect(
reducer(_initialState, {
type: MOVE_SLIDE_DOWN,
slideNumber: 1
})
).to.deep.equal([dummySlide1, slide]);
});
});
}
| Update description of test case | refactor: Update description of test case
| TypeScript | mit | Team-CHAD/DevDecks,Team-CHAD/DevDecks,chengsieuly/devdecks,chengsieuly/devdecks,chengsieuly/devdecks,Team-CHAD/DevDecks,DevDecks/devdecks,DevDecks/devdecks,DevDecks/devdecks | ---
+++
@@ -14,17 +14,17 @@
};
describe('MOVE_SLIDE_DOWN', () => {
- it('should not move the slide when current selected slide is 0', () => {
+ const _initialState = [slide, dummySlide1];
+ it('should not move the slide when the first slide is selected', () => {
expect(
- reducer(initialState, {
+ reducer(_initialState, {
type: MOVE_SLIDE_DOWN,
slideNumber: 0
})
- ).to.deep.equal(initialState);
+ ).to.deep.equal(_initialState);
});
it('should swap slide 1 and slide 0 when slide 1 is active', () => {
- const _initialState = [slide, dummySlide1];
expect(
reducer(_initialState, {
type: MOVE_SLIDE_DOWN, |
5fef998275aa6330b812a1e741bee0111981f2a5 | tests/__tests__/ts-coverage-async.spec.ts | tests/__tests__/ts-coverage-async.spec.ts | import runJest from '../__helpers__/runJest';
import * as fs from 'fs';
import * as path from 'path';
describe('hello_world', () => {
const snapshot =
`---------------|----------|----------|----------|----------|----------------|
File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
---------------|----------|----------|----------|----------|----------------|
simple-async${path.sep} | 90.91 | 50 | 80 | 88.89 | |
Hello.ts | 90.91 | 50 | 80 | 88.89 | 20 |
---------------|----------|----------|----------|----------|----------------|
All files | 90.91 | 50 | 80 | 88.89 | |
---------------|----------|----------|----------|----------|----------------|
`;
it('should run successfully', () => {
runJest('../simple-async', ['--no-cache', '--coverage']);
const coveragePath = path.resolve('./tests/simple-async/coverage/remapped/coverage.txt');
expect(fs.statSync(coveragePath).isFile()).toBeTruthy();
expect(fs.readFileSync(coveragePath, 'utf-8')).toEqual(snapshot);
});
}); | import runJest from '../__helpers__/runJest';
import * as fs from 'fs';
import * as path from 'path';
describe('hello_world', () => {
const snapshot =
`------------------|----------|----------|----------|----------|----------------|
File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
------------------|----------|----------|----------|----------|----------------|
simple-async/ | 71.43 | 33.33 | 66.67 | 66.67 | |
Hello.ts | 90.91 | 50 | 80 | 88.89 | 20 |
NullCoverage.js | 0 | 0 | 0 | 0 | 2,3,5 |
------------------|----------|----------|----------|----------|----------------|
All files | 71.43 | 33.33 | 66.67 | 66.67 | |
------------------|----------|----------|----------|----------|----------------|
`;
it('should run successfully', () => {
runJest('../simple-async', ['--no-cache', '--coverage']);
const coveragePath = path.resolve('./tests/simple-async/coverage/remapped/coverage.txt');
expect(fs.statSync(coveragePath).isFile()).toBeTruthy();
expect(fs.readFileSync(coveragePath, 'utf-8')).toEqual(snapshot);
});
});
| Include JS file in coverage for `simple-async` test | Include JS file in coverage for `simple-async` test
| TypeScript | mit | kulshekhar/ts-jest,kulshekhar/ts-jest | ---
+++
@@ -4,14 +4,15 @@
describe('hello_world', () => {
const snapshot =
-`---------------|----------|----------|----------|----------|----------------|
-File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
----------------|----------|----------|----------|----------|----------------|
- simple-async${path.sep} | 90.91 | 50 | 80 | 88.89 | |
- Hello.ts | 90.91 | 50 | 80 | 88.89 | 20 |
----------------|----------|----------|----------|----------|----------------|
-All files | 90.91 | 50 | 80 | 88.89 | |
----------------|----------|----------|----------|----------|----------------|
+ `------------------|----------|----------|----------|----------|----------------|
+File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
+------------------|----------|----------|----------|----------|----------------|
+ simple-async/ | 71.43 | 33.33 | 66.67 | 66.67 | |
+ Hello.ts | 90.91 | 50 | 80 | 88.89 | 20 |
+ NullCoverage.js | 0 | 0 | 0 | 0 | 2,3,5 |
+------------------|----------|----------|----------|----------|----------------|
+All files | 71.43 | 33.33 | 66.67 | 66.67 | |
+------------------|----------|----------|----------|----------|----------------|
`;
it('should run successfully', () => { |
4ab1fc513569ec42869061828be1140fda570073 | app/components/signIn/signIn.ts | app/components/signIn/signIn.ts | import {Component} from 'angular2/core';
import {Router, ROUTER_DIRECTIVES} from 'angular2/router';
import { References } from '../../services/references';
@Component({
selector: 'home',
templateUrl: './components/signIn/signIn.html',
styleUrls: ['./components/signIn/signIn.css'],
directives: [ROUTER_DIRECTIVES]
})
export class SignInCmp {
private ref: Firebase;
public constructor(private router: Router, private references:References) {
this.ref = this.references.getGlobalRef();
if (this.ref.getAuth()) {
this.router.navigate(['/Dashboard']);
}
}
onOAuth(provider) {
this.ref.authWithOAuthPopup(provider, (error) => {
if (error) {
console.log(error);
} else {
this.references.getUserRef().set({info: this.ref.getAuth()}, (err) => {
this.router.navigate(['/Dashboard']);
});
}
});
}
}
| import {Component} from 'angular2/core';
import {Router, ROUTER_DIRECTIVES} from 'angular2/router';
import { References } from '../../services/references';
@Component({
selector: 'home',
templateUrl: './components/signIn/signIn.html',
styleUrls: ['./components/signIn/signIn.css'],
directives: [ROUTER_DIRECTIVES]
})
export class SignInCmp {
private ref: Firebase;
public constructor(private router: Router, private references:References) {
this.ref = this.references.getGlobalRef();
if (this.ref.getAuth()) {
this.router.navigate(['/Dashboard']);
}
}
onOAuth(provider) {
this.ref.authWithOAuthPopup(provider, (error) => {
if (error) {
console.log(error);
} else {
this.references.getUserRef().update({info: this.ref.getAuth()}, (err) => {
this.router.navigate(['/Dashboard']);
});
}
});
}
}
| Change set to update for user profile. | Change set to update for user profile.
| TypeScript | mit | misoukrane/did-or-wish,misoukrane/did-or-wish,misoukrane/did-or-wish | ---
+++
@@ -23,7 +23,7 @@
if (error) {
console.log(error);
} else {
- this.references.getUserRef().set({info: this.ref.getAuth()}, (err) => {
+ this.references.getUserRef().update({info: this.ref.getAuth()}, (err) => {
this.router.navigate(['/Dashboard']);
});
} |
2f740f4bc97e187e5415466435d7ed54494f027b | citrus-admin-client/src/js/components/design/test.action.component.ts | citrus-admin-client/src/js/components/design/test.action.component.ts | import {Component, Input, Output, EventEmitter} from 'angular2/core';
import {TestAction} from "../../model/tests";
@Component({
selector: "test-action",
template: `<div class="test-action" (click)="select()" (mouseenter)="focused = true" (mouseleave)="focused = false">
<i class="fa icon-{{action.type}}"></i>
<span>{{action.type}}</span>
<div [hidden]="!focused" class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{action.type}}</h3>
</div>
<div class="panel-body">
<p *ngFor="#property of action.properties">{{property.id}}={{property.value}}</p>
</div>
</div>
</div>`
})
export class TestActionComponent {
@Input() action: TestAction;
@Output() selected = new EventEmitter(true);
focused = false;
constructor() {}
select() {
this.selected.emit(this.action);
}
} | import {Component, Input, Output, EventEmitter} from 'angular2/core';
import {NgSwitch} from "angular2/common";
import {TestAction} from "../../model/tests";
@Component({
selector: "test-action",
template: `<div class="test-action" (click)="select()" (mouseenter)="focused = true" (mouseleave)="focused = false">
<i class="fa icon-{{action.type}}"></i>
<span>{{action.type}}</span>
<div [hidden]="!focused" class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{action.type}}</h3>
</div>
<div class="panel-body">
<div [ngSwitch]="action.type">
<template [ngSwitchWhen]="'send'">
<span>{{getProperty("endpoint")}}</span>
</template>
<template [ngSwitchWhen]="'receive'">
<span>{{getProperty("endpoint")}}</span>
</template>
<template [ngSwitchWhen]="'sleep'">
<span>{{getProperty("time")}}</span>
</template>
<template [ngSwitchWhen]="'echo'">
<span>{{getProperty("message")}}</span>
</template>
<template ngSwitchDefault>
<p *ngFor="#property of action.properties">{{property.id}}={{property.value}}</p>
</template>
</div>
</div>
</div>
</div>`,
directives: [NgSwitch]
})
export class TestActionComponent {
@Input() action: TestAction;
@Output() selected = new EventEmitter(true);
focused = false;
constructor() {}
select() {
this.selected.emit(this.action);
}
getProperty(name: string) {
var property = this.action.properties.find(p => p.id === name);
return property.value;
}
} | Use action specific detail preview | Use action specific detail preview
| TypeScript | apache-2.0 | christophd/citrus-admin,christophd/citrus-admin,christophd/citrus-admin,christophd/citrus-admin | ---
+++
@@ -1,4 +1,5 @@
import {Component, Input, Output, EventEmitter} from 'angular2/core';
+import {NgSwitch} from "angular2/common";
import {TestAction} from "../../model/tests";
@Component({
@@ -11,10 +12,27 @@
<h3 class="panel-title">{{action.type}}</h3>
</div>
<div class="panel-body">
- <p *ngFor="#property of action.properties">{{property.id}}={{property.value}}</p>
+ <div [ngSwitch]="action.type">
+ <template [ngSwitchWhen]="'send'">
+ <span>{{getProperty("endpoint")}}</span>
+ </template>
+ <template [ngSwitchWhen]="'receive'">
+ <span>{{getProperty("endpoint")}}</span>
+ </template>
+ <template [ngSwitchWhen]="'sleep'">
+ <span>{{getProperty("time")}}</span>
+ </template>
+ <template [ngSwitchWhen]="'echo'">
+ <span>{{getProperty("message")}}</span>
+ </template>
+ <template ngSwitchDefault>
+ <p *ngFor="#property of action.properties">{{property.id}}={{property.value}}</p>
+ </template>
+ </div>
</div>
</div>
- </div>`
+ </div>`,
+ directives: [NgSwitch]
})
export class TestActionComponent {
@@ -30,4 +48,9 @@
this.selected.emit(this.action);
}
+ getProperty(name: string) {
+ var property = this.action.properties.find(p => p.id === name);
+ return property.value;
+ }
+
} |
60d8868306f3a1479cc16f00f52c1e8db714c465 | app/javascript/retrospring/features/answerbox/subscribe.ts | app/javascript/retrospring/features/answerbox/subscribe.ts | import Rails from '@rails/ujs';
import I18n from '../../../legacy/i18n';
import { showNotification, showErrorNotification } from 'utilities/notifications';
export function answerboxSubscribeHandler(event: Event): void {
const button = event.target as HTMLButtonElement;
const id = button.dataset.aId;
let torpedo = 0;
let targetUrl;
event.preventDefault();
if (button.dataset.torpedo === 'yes') {
torpedo = 1;
}
if (torpedo) {
targetUrl = '/ajax/subscribe';
} else {
targetUrl = '/ajax/unsubscribe';
}
Rails.ajax({
url: targetUrl,
type: 'POST',
data: new URLSearchParams({
answer: id
}).toString(),
success: (data) => {
if (data.success) {
button.dataset.torpedo = ["yes", "no"][torpedo];
button.children[0].nextSibling.textContent = torpedo ? I18n.translate('views.actions.unsubscribe') : I18n.translate('views.actions.subscribe');
showNotification(I18n.translate(`frontend.subscription.${torpedo ? 'subscribe' : 'unsubscribe'}`));
} else {
showErrorNotification(I18n.translate(`frontend.subscription.fail.${torpedo ? 'subscribe' : 'unsubscribe'}`));
}
},
error: (data, status, xhr) => {
console.log(data, status, xhr);
showErrorNotification(I18n.translate('frontend.error.message'));
}
});
} | import Rails from '@rails/ujs';
import I18n from '../../../legacy/i18n';
import { showNotification, showErrorNotification } from 'utilities/notifications';
export function answerboxSubscribeHandler(event: Event): void {
const button = event.target as HTMLButtonElement;
const id = button.dataset.aId;
let torpedo = 0;
let targetUrl;
event.preventDefault();
if (button.dataset.torpedo === 'yes') {
torpedo = 1;
}
if (torpedo) {
targetUrl = '/ajax/subscribe';
} else {
targetUrl = '/ajax/unsubscribe';
}
Rails.ajax({
url: targetUrl,
type: 'POST',
data: new URLSearchParams({
answer: id
}).toString(),
success: (data) => {
if (data.success) {
button.dataset.torpedo = ["yes", "no"][torpedo];
button.children[0].nextSibling.textContent = ' ' + (torpedo ? I18n.translate('views.actions.unsubscribe') : I18n.translate('views.actions.subscribe'));
showNotification(I18n.translate(`frontend.subscription.${torpedo ? 'subscribe' : 'unsubscribe'}`));
} else {
showErrorNotification(I18n.translate(`frontend.subscription.fail.${torpedo ? 'subscribe' : 'unsubscribe'}`));
}
},
error: (data, status, xhr) => {
console.log(data, status, xhr);
showErrorNotification(I18n.translate('frontend.error.message'));
}
});
} | Apply review suggestion from @raccube | Apply review suggestion from @raccube
Co-authored-by: Karina Kwiatek <a279f78642aaf231facf94ac593d2ad2fd791699@users.noreply.github.com> | TypeScript | agpl-3.0 | Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring | ---
+++
@@ -29,7 +29,7 @@
success: (data) => {
if (data.success) {
button.dataset.torpedo = ["yes", "no"][torpedo];
- button.children[0].nextSibling.textContent = torpedo ? I18n.translate('views.actions.unsubscribe') : I18n.translate('views.actions.subscribe');
+ button.children[0].nextSibling.textContent = ' ' + (torpedo ? I18n.translate('views.actions.unsubscribe') : I18n.translate('views.actions.subscribe'));
showNotification(I18n.translate(`frontend.subscription.${torpedo ? 'subscribe' : 'unsubscribe'}`));
} else {
showErrorNotification(I18n.translate(`frontend.subscription.fail.${torpedo ? 'subscribe' : 'unsubscribe'}`)); |
feeba12976632355f6a8300e6bbf873f7b98be56 | packages/lit-dev-server/src/middleware/tutorials-middleware.ts | packages/lit-dev-server/src/middleware/tutorials-middleware.ts | /**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import type Koa from 'koa';
/**
* Koa Middleware to serve '/tutorials/view.html' from '/tutorials/*'.
*/
export const tutorialsMiddleware = (): Koa.Middleware => async (ctx, next) => {
const path = ctx.request.path;
/*
* We want to intercept /tutorials/* but not /tutorials/ itself or the place
* where we are currently rendering the markdown to html so not
* /tutorials/content/*
*/
if (
path.startsWith('/tutorials/') &&
!path.startsWith('/tutorials/content/') &&
path !== '/tutorials/'
) {
ctx.path = '/tutorials/view/index.html';
}
await next();
};
| /**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import type Koa from 'koa';
/**
* Koa Middleware to serve '/tutorials/view.html' from '/tutorials/*'.
*/
export const tutorialsMiddleware = (): Koa.Middleware => async (ctx, next) => {
const path = ctx.request.path;
// We want to intercept /tutorials/* but not /tutorials/ itself or the place
// where we are currently rendering the markdown to html so not
// /tutorials/content/*
if (
path.startsWith('/tutorials/') &&
!path.startsWith('/tutorials/content/') &&
path !== '/tutorials/'
) {
ctx.path = '/tutorials/view/index.html';
}
await next();
};
| Change comment format for tutorial middleware | Change comment format for tutorial middleware
| TypeScript | bsd-3-clause | lit/lit.dev,lit/lit.dev,lit/lit.dev | ---
+++
@@ -12,11 +12,9 @@
export const tutorialsMiddleware = (): Koa.Middleware => async (ctx, next) => {
const path = ctx.request.path;
- /*
- * We want to intercept /tutorials/* but not /tutorials/ itself or the place
- * where we are currently rendering the markdown to html so not
- * /tutorials/content/*
- */
+ // We want to intercept /tutorials/* but not /tutorials/ itself or the place
+ // where we are currently rendering the markdown to html so not
+ // /tutorials/content/*
if (
path.startsWith('/tutorials/') &&
!path.startsWith('/tutorials/content/') && |
f708ded77ee8933f424d95216d6cdea379032365 | src/vs/base/worker/workerMain.ts | src/vs/base/worker/workerMain.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
(function () {
'use strict';
let MonacoEnvironment = (<any>self).MonacoEnvironment;
let monacoBaseUrl = MonacoEnvironment && MonacoEnvironment.baseUrl ? MonacoEnvironment.baseUrl : '../../../';
importScripts(monacoBaseUrl + 'vs/loader.js');
require.config({
baseUrl: monacoBaseUrl,
catchError: true
});
let loadCode = function(moduleId) {
require([moduleId], function(ws) {
let messageHandler = ws.create((msg:any) => {
(<any>self).postMessage(msg);
}, null);
self.onmessage = (e) => messageHandler.onmessage(e.data);
while(beforeReadyMessages.length > 0) {
self.onmessage(beforeReadyMessages.shift());
}
});
};
let isFirstMessage = true;
let beforeReadyMessages:MessageEvent[] = [];
self.onmessage = (message) => {
if (!isFirstMessage) {
beforeReadyMessages.push(message);
return;
}
isFirstMessage = false;
loadCode(message.data);
};
})();
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
(function () {
'use strict';
let MonacoEnvironment = (<any>self).MonacoEnvironment;
let monacoBaseUrl = MonacoEnvironment && MonacoEnvironment.baseUrl ? MonacoEnvironment.baseUrl : '../../../';
importScripts(monacoBaseUrl + 'vs/loader.js');
require.config({
baseUrl: monacoBaseUrl,
catchError: true
});
let loadCode = function(moduleId) {
require([moduleId], function(ws) {
setTimeout(function() {
let messageHandler = ws.create((msg:any) => {
(<any>self).postMessage(msg);
}, null);
self.onmessage = (e) => messageHandler.onmessage(e.data);
while(beforeReadyMessages.length > 0) {
self.onmessage(beforeReadyMessages.shift());
}
}, 0);
});
};
let isFirstMessage = true;
let beforeReadyMessages:MessageEvent[] = [];
self.onmessage = (message) => {
if (!isFirstMessage) {
beforeReadyMessages.push(message);
return;
}
isFirstMessage = false;
loadCode(message.data);
};
})();
| Allow define queue to be consumed by loader before reacting to incoming worker messages | Allow define queue to be consumed by loader before reacting to incoming worker messages
| TypeScript | mit | rishii7/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,stringham/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,the-ress/vscode,hungys/vscode,hashhar/vscode,microlv/vscode,veeramarni/vscode,hashhar/vscode,cleidigh/vscode,DustinCampbell/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,charlespierce/vscode,hungys/vscode,rishii7/vscode,the-ress/vscode,hungys/vscode,hoovercj/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,zyml/vscode,joaomoreno/vscode,charlespierce/vscode,Microsoft/vscode,eamodio/vscode,rishii7/vscode,hashhar/vscode,0xmohit/vscode,cra0zy/VSCode,Microsoft/vscode,cleidigh/vscode,matthewshirley/vscode,hoovercj/vscode,mjbvz/vscode,microsoft/vscode,hashhar/vscode,Microsoft/vscode,Zalastax/vscode,hoovercj/vscode,eamodio/vscode,stringham/vscode,rishii7/vscode,hoovercj/vscode,matthewshirley/vscode,jchadwick/vscode,cleidigh/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,cleidigh/vscode,stringham/vscode,landonepps/vscode,radshit/vscode,jchadwick/vscode,hashhar/vscode,eamodio/vscode,jchadwick/vscode,gagangupt16/vscode,charlespierce/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,zyml/vscode,hashhar/vscode,joaomoreno/vscode,cleidigh/vscode,Zalastax/vscode,radshit/vscode,zyml/vscode,zyml/vscode,microlv/vscode,hungys/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,matthewshirley/vscode,Microsoft/vscode,radshit/vscode,charlespierce/vscode,the-ress/vscode,radshit/vscode,gagangupt16/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,veeramarni/vscode,charlespierce/vscode,Zalastax/vscode,radshit/vscode,stringham/vscode,gagangupt16/vscode,DustinCampbell/vscode,hoovercj/vscode,matthewshirley/vscode,radshit/vscode,mjbvz/vscode,rishii7/vscode,veeramarni/vscode,KattMingMing/vscode,rishii7/vscode,rishii7/vscode,eamodio/vscode,zyml/vscode,eamodio/vscode,veeramarni/vscode,the-ress/vscode,jchadwick/vscode,hashhar/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,0xmohit/vscode,microsoft/vscode,stringham/vscode,microlv/vscode,charlespierce/vscode,hungys/vscode,matthewshirley/vscode,gagangupt16/vscode,eamodio/vscode,0xmohit/vscode,mjbvz/vscode,rishii7/vscode,zyml/vscode,KattMingMing/vscode,hashhar/vscode,joaomoreno/vscode,jchadwick/vscode,DustinCampbell/vscode,jchadwick/vscode,charlespierce/vscode,hoovercj/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,KattMingMing/vscode,stringham/vscode,landonepps/vscode,zyml/vscode,veeramarni/vscode,DustinCampbell/vscode,mjbvz/vscode,KattMingMing/vscode,hungys/vscode,veeramarni/vscode,microsoft/vscode,DustinCampbell/vscode,DustinCampbell/vscode,landonepps/vscode,joaomoreno/vscode,DustinCampbell/vscode,jchadwick/vscode,DustinCampbell/vscode,rishii7/vscode,eamodio/vscode,gagangupt16/vscode,DustinCampbell/vscode,0xmohit/vscode,microsoft/vscode,charlespierce/vscode,hoovercj/vscode,rishii7/vscode,microlv/vscode,gagangupt16/vscode,KattMingMing/vscode,the-ress/vscode,zyml/vscode,microlv/vscode,jchadwick/vscode,landonepps/vscode,hungys/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,hoovercj/vscode,microsoft/vscode,stringham/vscode,KattMingMing/vscode,Microsoft/vscode,Zalastax/vscode,0xmohit/vscode,DustinCampbell/vscode,charlespierce/vscode,microsoft/vscode,DustinCampbell/vscode,cleidigh/vscode,0xmohit/vscode,stringham/vscode,Zalastax/vscode,microlv/vscode,Zalastax/vscode,KattMingMing/vscode,microsoft/vscode,landonepps/vscode,zyml/vscode,veeramarni/vscode,hungys/vscode,mjbvz/vscode,veeramarni/vscode,joaomoreno/vscode,joaomoreno/vscode,hungys/vscode,stringham/vscode,landonepps/vscode,hungys/vscode,veeramarni/vscode,zyml/vscode,veeramarni/vscode,the-ress/vscode,radshit/vscode,jchadwick/vscode,joaomoreno/vscode,microlv/vscode,matthewshirley/vscode,eamodio/vscode,landonepps/vscode,joaomoreno/vscode,jchadwick/vscode,mjbvz/vscode,the-ress/vscode,Zalastax/vscode,hoovercj/vscode,hashhar/vscode,stringham/vscode,cleidigh/vscode,charlespierce/vscode,cleidigh/vscode,microsoft/vscode,hoovercj/vscode,hoovercj/vscode,landonepps/vscode,hashhar/vscode,mjbvz/vscode,matthewshirley/vscode,jchadwick/vscode,Microsoft/vscode,rishii7/vscode,rishii7/vscode,0xmohit/vscode,zyml/vscode,mjbvz/vscode,hoovercj/vscode,zyml/vscode,zyml/vscode,zyml/vscode,gagangupt16/vscode,KattMingMing/vscode,microsoft/vscode,matthewshirley/vscode,jchadwick/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Zalastax/vscode,the-ress/vscode,matthewshirley/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,gagangupt16/vscode,radshit/vscode,gagangupt16/vscode,veeramarni/vscode,eamodio/vscode,Microsoft/vscode,Zalastax/vscode,hoovercj/vscode,0xmohit/vscode,gagangupt16/vscode,0xmohit/vscode,0xmohit/vscode,matthewshirley/vscode,microlv/vscode,veeramarni/vscode,veeramarni/vscode,KattMingMing/vscode,KattMingMing/vscode,zyml/vscode,matthewshirley/vscode,rishii7/vscode,radshit/vscode,matthewshirley/vscode,matthewshirley/vscode,matthewshirley/vscode,0xmohit/vscode,Microsoft/vscode,hoovercj/vscode,rishii7/vscode,hashhar/vscode,Microsoft/vscode,matthewshirley/vscode,eamodio/vscode,cleidigh/vscode,rishii7/vscode,radshit/vscode,gagangupt16/vscode,Microsoft/vscode,hungys/vscode,landonepps/vscode,joaomoreno/vscode,cleidigh/vscode,the-ress/vscode,charlespierce/vscode,mjbvz/vscode,hungys/vscode,matthewshirley/vscode,landonepps/vscode,landonepps/vscode,0xmohit/vscode,zyml/vscode,KattMingMing/vscode,veeramarni/vscode,microsoft/vscode,stringham/vscode,radshit/vscode,KattMingMing/vscode,Zalastax/vscode,stringham/vscode,Zalastax/vscode,microlv/vscode,landonepps/vscode,microlv/vscode,stringham/vscode,DustinCampbell/vscode,hashhar/vscode,hungys/vscode,mjbvz/vscode,DustinCampbell/vscode,veeramarni/vscode,microsoft/vscode,mjbvz/vscode,KattMingMing/vscode,0xmohit/vscode,radshit/vscode,eamodio/vscode,gagangupt16/vscode,charlespierce/vscode,radshit/vscode,joaomoreno/vscode,Microsoft/vscode,gagangupt16/vscode,gagangupt16/vscode,Zalastax/vscode,microlv/vscode,Zalastax/vscode,Microsoft/vscode,the-ress/vscode,cleidigh/vscode,Zalastax/vscode,joaomoreno/vscode,stringham/vscode,joaomoreno/vscode,KattMingMing/vscode,microlv/vscode,KattMingMing/vscode,hoovercj/vscode,hashhar/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,Zalastax/vscode,charlespierce/vscode,radshit/vscode,mjbvz/vscode,eamodio/vscode,charlespierce/vscode,microsoft/vscode,Microsoft/vscode,the-ress/vscode,veeramarni/vscode,Microsoft/vscode,DustinCampbell/vscode,rishii7/vscode,0xmohit/vscode,hoovercj/vscode,gagangupt16/vscode,the-ress/vscode,KattMingMing/vscode,radshit/vscode,joaomoreno/vscode,hashhar/vscode,Krzysztof-Cieslak/vscode,hungys/vscode,hungys/vscode,cleidigh/vscode,charlespierce/vscode,cleidigh/vscode,cleidigh/vscode,Microsoft/vscode,the-ress/vscode,eamodio/vscode,jchadwick/vscode,radshit/vscode,Krzysztof-Cieslak/vscode,Zalastax/vscode,matthewshirley/vscode,mjbvz/vscode,jchadwick/vscode,microlv/vscode,rishii7/vscode,the-ress/vscode,rkeithhill/VSCode,microsoft/vscode,hashhar/vscode,cleidigh/vscode,hungys/vscode,DustinCampbell/vscode,the-ress/vscode,charlespierce/vscode,landonepps/vscode,the-ress/vscode,microlv/vscode,stringham/vscode,landonepps/vscode,cleidigh/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,KattMingMing/vscode,microsoft/vscode,jchadwick/vscode,radshit/vscode,stringham/vscode,joaomoreno/vscode,microlv/vscode,Zalastax/vscode,eamodio/vscode,cleidigh/vscode,landonepps/vscode,Microsoft/vscode,mjbvz/vscode,gagangupt16/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,gagangupt16/vscode,hashhar/vscode,Microsoft/vscode,hoovercj/vscode,jchadwick/vscode,zyml/vscode,hungys/vscode,jchadwick/vscode,veeramarni/vscode,landonepps/vscode,joaomoreno/vscode,charlespierce/vscode,stringham/vscode,hashhar/vscode | ---
+++
@@ -18,14 +18,16 @@
let loadCode = function(moduleId) {
require([moduleId], function(ws) {
- let messageHandler = ws.create((msg:any) => {
- (<any>self).postMessage(msg);
- }, null);
+ setTimeout(function() {
+ let messageHandler = ws.create((msg:any) => {
+ (<any>self).postMessage(msg);
+ }, null);
- self.onmessage = (e) => messageHandler.onmessage(e.data);
- while(beforeReadyMessages.length > 0) {
- self.onmessage(beforeReadyMessages.shift());
- }
+ self.onmessage = (e) => messageHandler.onmessage(e.data);
+ while(beforeReadyMessages.length > 0) {
+ self.onmessage(beforeReadyMessages.shift());
+ }
+ }, 0);
});
};
|
fe830a3d4823493faff3d967fb989fee8b18204d | src/component/sidenav/sidenav.component.spec.ts | src/component/sidenav/sidenav.component.spec.ts | /*
* @license
* Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
*
* Use of this source code is governed by an Apache-2.0 license that can be
* found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { DejaSidenavModule } from './index';
import { DejaSidenavComponent } from './sidenav.component';
describe('DejaSidenavComponent', () => {
let comp: DejaSidenavComponent;
let fixture: ComponentFixture<DejaSidenavComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
DejaSidenavModule
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
fixture = TestBed.createComponent(DejaSidenavComponent);
comp = fixture.componentInstance; // Component test instance
}));
it('should create the component', async(() => {
comp.ngOnInit();
expect(comp).toBeTruthy();
}));
});
| /*
* @license
* Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
*
* Use of this source code is governed by an Apache-2.0 license that can be
* found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { DejaSidenavModule } from './index';
import { DejaSidenavComponent } from './sidenav.component';
describe('DejaSidenavComponent', () => {
let comp: DejaSidenavComponent;
let fixture: ComponentFixture<DejaSidenavComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
DejaSidenavModule.forRoot(),
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
fixture = TestBed.createComponent(DejaSidenavComponent);
comp = fixture.componentInstance; // Component test instance
}));
it('should create the component', async(() => {
comp.ngOnInit();
expect(comp).toBeTruthy();
}));
});
| Add forRoot for test module injection | fix(DejaSidenav): Add forRoot for test module injection
| TypeScript | apache-2.0 | DSI-HUG/dejajs-components,DSI-HUG/dejajs-components,DSI-HUG/dejajs-components,DSI-HUG/dejajs-components | ---
+++
@@ -21,7 +21,7 @@
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
- DejaSidenavModule
+ DejaSidenavModule.forRoot(),
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents(); |
5b750b99297670aea575b24719a1181f3aa40ea9 | front_end/src/app/setup/setup.component.ts | front_end/src/app/setup/setup.component.ts | import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { SetupService } from './setup.service';
import { RootService } from '../shared/services';
@Component({
selector: 'setup',
templateUrl: 'setup.component.html',
styleUrls: ['setup.component.scss'],
providers: [ SetupService ]
})
export class SetupComponent implements OnInit {
machineId: string;
isError: boolean;
constructor(private setupService: SetupService,
private route: ActivatedRoute,
private rootService: RootService) {}
reset() {
document.cookie.split(';').forEach(function(c) {
document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
});
this.machineId = undefined;
}
ngOnInit() {
this.isError = this.route.snapshot.params['error'];
let machineGuid;
this.route.params.forEach((params: Params) => {
machineGuid = params['machine'];
});
machineGuid = machineGuid || this.setupService.getMachineIdConfigCookie();
if ( machineGuid ) {
this.machineId = machineGuid;
this.setupService.setMachineIdConfigCookie(this.machineId);
}
}
}
| import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { SetupService } from './setup.service';
import { RootService } from '../shared/services';
@Component({
selector: 'setup',
templateUrl: 'setup.component.html',
styleUrls: ['setup.component.scss'],
providers: [ SetupService ]
})
export class SetupComponent implements OnInit {
machineId: string;
isError: boolean;
constructor(private setupService: SetupService,
private route: ActivatedRoute,
private rootService: RootService) {}
reset() {
document.cookie.split(';').forEach(function(c) {
document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
});
this.machineId = undefined;
}
ngOnInit() {
let machineGuid;
this.route.params.forEach((params: Params) => {
this.isError = params['error'];
machineGuid = params['machine'];
});
machineGuid = machineGuid || this.setupService.getMachineIdConfigCookie();
if ( machineGuid ) {
this.machineId = machineGuid;
this.setupService.setMachineIdConfigCookie(this.machineId);
}
}
}
| Fix how we are getting params. | Fix how we are getting params.
| TypeScript | bsd-2-clause | crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin | ---
+++
@@ -25,11 +25,12 @@
}
ngOnInit() {
- this.isError = this.route.snapshot.params['error'];
let machineGuid;
this.route.params.forEach((params: Params) => {
- machineGuid = params['machine'];
- });
+ this.isError = params['error'];
+ machineGuid = params['machine'];
+ });
+
machineGuid = machineGuid || this.setupService.getMachineIdConfigCookie();
if ( machineGuid ) {
this.machineId = machineGuid; |
12ccfab25a885a6c69685bb48dc783ecc358c86b | demo/router-components/echo.tsx | demo/router-components/echo.tsx | import app, { Component } from '../../index-jsx';
var model = 'world';
const Hello = ({name}) => <div>Hello: {name}</div>;
const view = (val) => {
return <div>
<Hello name={val}/>
<input value={val} oninput={function() { app.run('render', this.value)}}/>
</div>
};
const update = {
'#echo': (model, pushState) => pushState || model,
'render': (_, val) => {
history.pushState(null, null, '#echo/' + val);
return val;
}
}
export default (element) => app.start(element, model, view, update);
| import app from '../../index-jsx';
var model = 'world';
const Hello = ({name}) => <div>Hello: {name}</div>;
const view = (val) => {
return <div>
<Hello name={val}/>
<input value={val} oninput={function() { app.run('render', this.value)}}/>
</div>
};
const update = {
'#echo': (model, pushState) => pushState || model,
'render': (_, val) => {
history.pushState(null, null, '#echo/' + val);
return val;
}
}
export default (element) => app.start(element, model, view, update);
| Fix demo to use app.start instead of new Component | Fix demo to use app.start instead of new Component
| TypeScript | mit | yysun/apprun,yysun/apprun,yysun/apprun | ---
+++
@@ -1,4 +1,4 @@
-import app, { Component } from '../../index-jsx';
+import app from '../../index-jsx';
var model = 'world';
|
c64cf403bb255f3e3a72f341dae629ea41c5b812 | app/components/footer.tsx | app/components/footer.tsx | import dynamic from "next/dynamic";
import ExternalLink from "./externalLink";
const ShareButtons = dynamic(() => import("./shareButtons"));
export default function Footer() {
return (
<>
<style jsx={true}>{`
.footer_row {
display: flex;
flex-direction: row;
align-items: stretch;
color: #ffffff;
font-size: 10pt;
background-color: #df696e;
}
.footer_item {
display: flex;
flex-direction: row;
flex-grow: 1;
padding: 8px;
align-items: center;
filter: grayscale(50%);
}
.footer_item > a {
color: #ffffff;
}
.footer_right {
flex-direction: row-reverse;
}
.share_text {
margin-right: 10px;
}
.tenor_logo {
height: 12px;
}
`}</style>
<div className="footer_row">
<div className="footer_item">
<div className="share_text">Share the ❤️</div>
<ShareButtons />
</div>
<div className="footer_item footer_right">
<ExternalLink href="https://tenor.com/">
Powered by{" "}
<img className="tenor_logo" src="/tenor.svg" alt="Logo for Tenor" />
</ExternalLink>
</div>
</div>
</>
);
}
| import dynamic from "next/dynamic";
import ExternalLink from "./externalLink";
import ShareButtons from "./shareButtons";
export default function Footer() {
return (
<>
<style jsx={true}>{`
.footer_row {
display: flex;
flex-direction: row;
align-items: stretch;
color: #ffffff;
font-size: 10pt;
background-color: #df696e;
}
.footer_item {
display: flex;
flex-direction: row;
flex-grow: 1;
padding: 8px;
align-items: center;
filter: grayscale(50%);
}
.footer_item > a {
color: #ffffff;
}
.footer_right {
flex-direction: row-reverse;
}
.share_text {
margin-right: 10px;
}
.tenor_logo {
height: 12px;
}
`}</style>
<div className="footer_row">
<div className="footer_item">
<div className="share_text">Share the ❤️</div>
<ShareButtons />
</div>
<div className="footer_item footer_right">
<ExternalLink href="https://tenor.com/">
Powered by{" "}
<img className="tenor_logo" src="/tenor.svg" alt="Logo for Tenor" />
</ExternalLink>
</div>
</div>
</>
);
}
| Remove delay load share buttons | Remove delay load share buttons
Big issues were coming up with this - I may need to remove the library completely
| TypeScript | apache-2.0 | thenickreynolds/popcorngif,thenickreynolds/popcorngif | ---
+++
@@ -1,7 +1,6 @@
import dynamic from "next/dynamic";
import ExternalLink from "./externalLink";
-
-const ShareButtons = dynamic(() => import("./shareButtons"));
+import ShareButtons from "./shareButtons";
export default function Footer() {
return ( |
13a223f761c4afa81fc8eaab2461221dc251a0ce | packages/formdata-event/ts_src/wrappers/wrap_constructor.ts | packages/formdata-event/ts_src/wrappers/wrap_constructor.ts | /**
* @license
* Copyright (c) 2020 The Polymer Project Authors. All rights reserved. This
* code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be
* found at http://polymer.github.io/AUTHORS.txt The complete set of
* contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code
* distributed by Google as part of the polymer project is also subject to an
* additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
export const wrapConstructor = (Wrapper: any, Constructor: any, prototype: any) => {
for (const prop of Object.keys(Constructor)) {
// `Event.prototype` is not writable or configurable in Safari 9. We
// overwrite it immediately after, so we might as well not copy it.
if (prop === 'prototype') {
continue;
}
Object.defineProperty(Wrapper, prop,
Object.getOwnPropertyDescriptor(Constructor, prop) as PropertyDescriptor);
}
Wrapper.prototype = prototype;
// `Event.prototype.constructor` is not writable in Safari 9, so we have to
// define it with `defineProperty`.
Object.defineProperty(Wrapper.prototype, 'constructor', {
writable: true,
configurable: true,
enumerable: false,
value: Wrapper,
});
};
| /**
* @license
* Copyright (c) 2020 The Polymer Project Authors. All rights reserved. This
* code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be
* found at http://polymer.github.io/AUTHORS.txt The complete set of
* contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code
* distributed by Google as part of the polymer project is also subject to an
* additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
interface Constructor<T> extends Function {
new (...args: Array<any>): T;
}
export function wrapConstructor<T extends Object, C extends Constructor<T>>(
Wrapper: C,
Constructor: C,
prototype: C['prototype'],
) {
for (const prop of Object.keys(Constructor)) {
// `Event.prototype` is not writable or configurable in Safari 9. We
// overwrite it immediately after, so we might as well not copy it.
if (prop === 'prototype') {
continue;
}
Object.defineProperty(Wrapper, prop,
Object.getOwnPropertyDescriptor(Constructor, prop) as PropertyDescriptor);
}
Wrapper.prototype = prototype;
// `Event.prototype.constructor` is not writable in Safari 9, so we have to
// define it with `defineProperty`.
Object.defineProperty(Wrapper.prototype, 'constructor', {
writable: true,
configurable: true,
enumerable: false,
value: Wrapper,
});
};
| Use more specific types in `wrapConstructor` parameters. | Use more specific types in `wrapConstructor` parameters.
| TypeScript | bsd-3-clause | webcomponents/polyfills,webcomponents/polyfills,webcomponents/polyfills | ---
+++
@@ -9,7 +9,15 @@
* additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
-export const wrapConstructor = (Wrapper: any, Constructor: any, prototype: any) => {
+interface Constructor<T> extends Function {
+ new (...args: Array<any>): T;
+}
+
+export function wrapConstructor<T extends Object, C extends Constructor<T>>(
+ Wrapper: C,
+ Constructor: C,
+ prototype: C['prototype'],
+) {
for (const prop of Object.keys(Constructor)) {
// `Event.prototype` is not writable or configurable in Safari 9. We
// overwrite it immediately after, so we might as well not copy it. |
97c23ff2ce61196f97191a4a72f315f726f4d218 | app/services/instagram.ts | app/services/instagram.ts | import {XHR} from '../libs/xhr';
export class InstagramClient {
endpoint: string;
protocol: string;
token: string;
xhr: XHR;
constructor() {
this.protocol = 'https://'
this.endpoint = 'api.instagram.com'
this.token = '31003280.5c1de8f.3e76027eeefe429ba5cc90f0e64ccda0' //For debugging only
this.xhr = new XHR();
}
getMedias(tag){
let url = '/tags/' + tag + '/media/recent';
return this.xhr.get(this.protocol + this.endpoint + url).then(console.log.bind(console))
}
} | import {XHR} from '../libs/xhr';
let ENDPOINT = 'api.instagram.com'
let API_VERSION = 'v1'
let ACCESS_TOKEN = '31003280.5c1de8f.3e76027eeefe429ba5cc90f0e64ccda0'
let CLIENT_ID = '5c1de8fe2653445489b480a72803a44c'
export class InstagramClient {
endpoint: string;
protocol: string;
token: string;
xhr: XHR;
constructor() {
this.protocol = 'https://'
this.xhr = new XHR();
this.endpoint = [this.protocol, ENDPOINT, API_VERSION].join('/')
}
getMedias(tag){
let url = '/tags/' + tag + '/media/recent';
return this.xhr.get(this.protocol + this.endpoint + url).then(console.log.bind(console))
}
} | Move variable token outside class declaration | Move variable token outside class declaration
| TypeScript | mit | yadomi/lastagram,yadomi/lastagram,yadomi/lastagram | ---
+++
@@ -1,4 +1,10 @@
import {XHR} from '../libs/xhr';
+
+let ENDPOINT = 'api.instagram.com'
+let API_VERSION = 'v1'
+
+let ACCESS_TOKEN = '31003280.5c1de8f.3e76027eeefe429ba5cc90f0e64ccda0'
+let CLIENT_ID = '5c1de8fe2653445489b480a72803a44c'
export class InstagramClient {
@@ -10,10 +16,8 @@
constructor() {
this.protocol = 'https://'
- this.endpoint = 'api.instagram.com'
- this.token = '31003280.5c1de8f.3e76027eeefe429ba5cc90f0e64ccda0' //For debugging only
-
this.xhr = new XHR();
+ this.endpoint = [this.protocol, ENDPOINT, API_VERSION].join('/')
}
getMedias(tag){ |
6abfb5073d1dea53c55e1e2d0d2f37a5665f0fa6 | resources/assets/lib/home-links.ts | resources/assets/lib/home-links.ts | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import { route } from 'laroute';
export default function homeLinks(active: string) {
return [
{
active: active === 'home@index',
title: osu.trans('home.user.title'),
url: route('home'),
},
{
active: active === 'friends@index',
title: osu.trans('friends.title_compact'),
url: route('friends.index'),
},
{
active: active === 'follows@index',
title: osu.trans('follows.index.title_compact'),
url: route('follows.index', { subtype: 'comment' }),
},
{
active: active === 'account@edit',
title: osu.trans('accounts.edit.title_compact'),
url: route('account.edit'),
},
];
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import { route } from 'laroute';
export default function homeLinks(active: string) {
return [
{
active: active === 'home@index',
title: osu.trans('home.user.title'),
url: route('home'),
},
{
active: active === 'friends@index',
title: osu.trans('friends.title_compact'),
url: route('friends.index'),
},
{
active: active === 'follows@index',
title: osu.trans('follows.index.title_compact'),
url: route('follows.index', { subtype: 'forum_topic' }),
},
{
active: active === 'account@edit',
title: osu.trans('accounts.edit.title_compact'),
url: route('account.edit'),
},
];
}
| Use subtype that actually exists | Use subtype that actually exists
| TypeScript | agpl-3.0 | notbakaneko/osu-web,notbakaneko/osu-web,ppy/osu-web,nanaya/osu-web,nanaya/osu-web,ppy/osu-web,nanaya/osu-web,omkelderman/osu-web,nanaya/osu-web,omkelderman/osu-web,LiquidPL/osu-web,ppy/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,ppy/osu-web,LiquidPL/osu-web,nanaya/osu-web,ppy/osu-web,omkelderman/osu-web,LiquidPL/osu-web,omkelderman/osu-web,notbakaneko/osu-web | ---
+++
@@ -18,7 +18,7 @@
{
active: active === 'follows@index',
title: osu.trans('follows.index.title_compact'),
- url: route('follows.index', { subtype: 'comment' }),
+ url: route('follows.index', { subtype: 'forum_topic' }),
},
{
active: active === 'account@edit', |
b6eca5a50677143a650a8d538a9bffd7c22e3cb4 | app/static/components/application/application.ts | app/static/components/application/application.ts | import {Component} from "@angular/core";
@Component({
selector: 'application-component',
templateUrl: '/static/components/application/application.html',
styles: [
`#navbar_botom {margin-bottom: 0; border-radius: 0;}`,
`#buffer {height: 70px}`
]
})
export class ApplicationComponent {
}
| import {Component} from "@angular/core";
@Component({
selector: 'application-component',
templateUrl: '/static/components/application/application.html',
styles: [
`#navbar_botom {margin-bottom: 0; border-radius: 0; position: fixed; bottom: 0; left: 0; right: 0;}`,
`#buffer {height: 70px}`
]
})
export class ApplicationComponent {
}
| Make navbar footer really stick to bottom | Make navbar footer really stick to bottom
| TypeScript | mit | pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise | ---
+++
@@ -3,7 +3,7 @@
selector: 'application-component',
templateUrl: '/static/components/application/application.html',
styles: [
- `#navbar_botom {margin-bottom: 0; border-radius: 0;}`,
+ `#navbar_botom {margin-bottom: 0; border-radius: 0; position: fixed; bottom: 0; left: 0; right: 0;}`,
`#buffer {height: 70px}`
]
}) |
414b0e94dbf38aaa7fd56943f610281e87052752 | src/main/ts/ephox/bridge/components/dialog/SelectBox.ts | src/main/ts/ephox/bridge/components/dialog/SelectBox.ts | import { ValueSchema, FieldSchema, FieldProcessorAdt } from '@ephox/boulder';
import { Result } from '@ephox/katamari';
import { FormComponentApi, FormComponent, formComponentFields } from './FormComponent';
export interface ExternalSelectBoxItem {
text: string;
value: string;
}
export interface SelectBoxApi extends FormComponentApi {
type: 'selectbox';
items: ExternalSelectBoxItem[];
size?: number;
}
export interface InternalSelectBoxItem extends ExternalSelectBoxItem {
text: string;
value: string;
}
export interface SelectBox extends FormComponent {
type: 'selectbox';
items: InternalSelectBoxItem[];
size: number;
}
export const selectBoxFields: FieldProcessorAdt[] = formComponentFields.concat([
FieldSchema.strictArrayOfObj('items', [
FieldSchema.strictString('text'),
FieldSchema.strictString('value')
]),
FieldSchema.defaultedNumber('size', 1)
]);
export const selectBoxSchema = ValueSchema.objOf(selectBoxFields);
export const selectBoxDataProcessor = ValueSchema.string;
export const createSelectBox = (spec: SelectBoxApi): Result<SelectBox, ValueSchema.SchemaError<any>> => {
return ValueSchema.asRaw<SelectBox>('selectbox', selectBoxSchema, spec);
};
| import { ValueSchema, FieldSchema, FieldProcessorAdt } from '@ephox/boulder';
import { Result } from '@ephox/katamari';
import { FormComponentApi, FormComponent, formComponentFields } from './FormComponent';
export interface ExternalSelectBoxItem {
text: string;
value: string;
}
export interface SelectBoxApi extends FormComponentApi {
type: 'selectbox';
items: ExternalSelectBoxItem[];
size?: number;
}
interface InternalSelectBoxItem extends ExternalSelectBoxItem {
text: string;
value: string;
}
export interface SelectBox extends FormComponent {
type: 'selectbox';
items: InternalSelectBoxItem[];
size: number;
}
export const selectBoxFields: FieldProcessorAdt[] = formComponentFields.concat([
FieldSchema.strictArrayOfObj('items', [
FieldSchema.strictString('text'),
FieldSchema.strictString('value')
]),
FieldSchema.defaultedNumber('size', 1)
]);
export const selectBoxSchema = ValueSchema.objOf(selectBoxFields);
export const selectBoxDataProcessor = ValueSchema.string;
export const createSelectBox = (spec: SelectBoxApi): Result<SelectBox, ValueSchema.SchemaError<any>> => {
return ValueSchema.asRaw<SelectBox>('selectbox', selectBoxSchema, spec);
};
| Stop exporting the internal select box interface | Stop exporting the internal select box interface
| TypeScript | lgpl-2.1 | FernCreek/tinymce,FernCreek/tinymce,TeamupCom/tinymce,FernCreek/tinymce,tinymce/tinymce,tinymce/tinymce,tinymce/tinymce,TeamupCom/tinymce | ---
+++
@@ -13,7 +13,7 @@
size?: number;
}
-export interface InternalSelectBoxItem extends ExternalSelectBoxItem {
+interface InternalSelectBoxItem extends ExternalSelectBoxItem {
text: string;
value: string;
} |
6d60229e820c5069fa1477b91e12d1d7dea0a395 | static/main-hall/components/adventure-list.component.ts | static/main-hall/components/adventure-list.component.ts | import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {Player} from '../models/player';
import {AdventureService} from '../services/adventure.service';
import {StatusComponent} from "../components/status.component";
import {PlayerService} from "../services/player.service";
@Component({
template: `
<h4>Go on an adventure</h4>
<p class="adventure"
*ngFor="let adv of _adventureService.adventures"><a href="/adventure/{{adv.slug}}">{{adv.name}}</a></p>
<button class="btn"><a (click)="gotoDetail()">Go back to Main Hall</a></button>
`,
directives: [StatusComponent]
})
export class AdventureListComponent implements OnInit {
constructor(private _router: Router,
private _route: ActivatedRoute,
private _adventureService: AdventureService,
private _playerService: PlayerService) {
}
ngOnInit() {
this._adventureService.getList();
let id = Number(this._route.snapshot.params['id']);
this._playerService.getPlayer(id);
}
gotoDetail() {
this._router.navigate(['/player', this._playerService.player.id]);
}
}
| import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {Player} from '../models/player';
import {AdventureService} from '../services/adventure.service';
import {StatusComponent} from "../components/status.component";
import {PlayerService} from "../services/player.service";
import {Adventure} from "../models/adventure";
@Component({
template: `
<h4>Go on an adventure</h4>
<p class="adventure"
*ngFor="let adv of _adventureService.adventures"><a (click)="gotoAdventure(adv)">{{adv.name}}</a></p>
<button class="btn"><a (click)="gotoDetail()">Go back to Main Hall</a></button>
`,
directives: [StatusComponent]
})
export class AdventureListComponent implements OnInit {
constructor(private _router: Router,
private _route: ActivatedRoute,
private _adventureService: AdventureService,
private _playerService: PlayerService) {
}
ngOnInit() {
this._adventureService.getList();
let id = Number(this._route.snapshot.params['id']);
this._playerService.getPlayer(id);
}
gotoAdventure(adv: Adventure) {
this._playerService.update().subscribe(
data => {
window.location.href = '/adventure/' + adv.slug;
}
);
}
gotoDetail() {
this._router.navigate(['/player', this._playerService.player.id]);
}
}
| Save player when leaving to go on an adventure | Save player when leaving to go on an adventure
| TypeScript | mit | kdechant/eamon,kdechant/eamon,kdechant/eamon,kdechant/eamon | ---
+++
@@ -5,12 +5,13 @@
import {AdventureService} from '../services/adventure.service';
import {StatusComponent} from "../components/status.component";
import {PlayerService} from "../services/player.service";
+import {Adventure} from "../models/adventure";
@Component({
template: `
<h4>Go on an adventure</h4>
<p class="adventure"
- *ngFor="let adv of _adventureService.adventures"><a href="/adventure/{{adv.slug}}">{{adv.name}}</a></p>
+ *ngFor="let adv of _adventureService.adventures"><a (click)="gotoAdventure(adv)">{{adv.name}}</a></p>
<button class="btn"><a (click)="gotoDetail()">Go back to Main Hall</a></button>
`,
directives: [StatusComponent]
@@ -31,6 +32,14 @@
}
+ gotoAdventure(adv: Adventure) {
+ this._playerService.update().subscribe(
+ data => {
+ window.location.href = '/adventure/' + adv.slug;
+ }
+ );
+ }
+
gotoDetail() {
this._router.navigate(['/player', this._playerService.player.id]);
} |
7bec5d37ec99e7cf0b7fb9014be1c05ebf58c040 | test/runTest.ts | test/runTest.ts | import * as path from "path";
import { runTests } from "vscode-test";
async function main() {
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = path.resolve(__dirname, "../../");
// The path to the extension test script
// Passed to --extensionTestsPath
const extensionTestsPath = path.resolve(__dirname, "./index");
// Download VS Code, unzip it and run the integration test
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
launchArgs: [
"example/example.code-workspace",
"--disable-extensions",
],
});
} catch (err) {
console.error("Failed to run tests");
process.exit(1);
}
}
main();
| import {resolve} from "path";
import { downloadAndUnzipVSCode, runTests } from "vscode-test";
async function main() {
try {
const extensionDevelopmentPath = resolve(__dirname, "..", "..");
const extensionTestsPath = resolve(__dirname, "index");
const vscodeExecutablePath = await downloadAndUnzipVSCode("insiders");
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
launchArgs: [
"example/example.code-workspace",
"--disable-extensions",
],
vscodeExecutablePath,
});
} catch (err) {
console.error("Failed to run tests");
process.exit(1);
}
}
main();
| Use insiders build for test suite | Use insiders build for test suite
| 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,25 +1,23 @@
-import * as path from "path";
+import {resolve} from "path";
-import { runTests } from "vscode-test";
+import { downloadAndUnzipVSCode, runTests } from "vscode-test";
async function main() {
try {
- // The folder containing the Extension Manifest package.json
- // Passed to `--extensionDevelopmentPath`
- const extensionDevelopmentPath = path.resolve(__dirname, "../../");
+ const extensionDevelopmentPath = resolve(__dirname, "..", "..");
- // The path to the extension test script
- // Passed to --extensionTestsPath
- const extensionTestsPath = path.resolve(__dirname, "./index");
+ const extensionTestsPath = resolve(__dirname, "index");
- // Download VS Code, unzip it and run the integration test
+ const vscodeExecutablePath = await downloadAndUnzipVSCode("insiders");
+
await runTests({
- extensionDevelopmentPath,
- extensionTestsPath,
- launchArgs: [
- "example/example.code-workspace",
- "--disable-extensions",
- ],
+ extensionDevelopmentPath,
+ extensionTestsPath,
+ launchArgs: [
+ "example/example.code-workspace",
+ "--disable-extensions",
+ ],
+ vscodeExecutablePath,
});
} catch (err) {
console.error("Failed to run tests"); |
ef09d62d60b3924e1493ea1c8b8fbaa26793750d | addon/components/o-s-s/tag.ts | addon/components/o-s-s/tag.ts | import Component from '@glimmer/component';
export type SkinType = 'primary' | 'success' | 'warning' | 'danger' | 'secondary';
type SkinDefType = {
[key in SkinType]: string;
};
const BASE_CLASS = 'upf-tag';
export const SkinDefinition: SkinDefType = {
primary: 'regular',
success: 'success',
warning: 'alert',
danger: 'critical',
secondary: 'neutral'
};
interface OSSTagArgs {
label?: string;
skin?: string;
icon?: string;
hasEllipsis?: boolean;
}
export default class OSSTag extends Component<OSSTagArgs> {
constructor(owner: unknown, args: OSSTagArgs) {
super(owner, args);
if (!args.icon && !args.label) {
throw new Error('[component][OSS::Tag] You must pass either a @label or an @icon argument.');
}
}
get skin(): string {
if (!this.args.skin) {
return SkinDefinition.primary;
}
return SkinDefinition[this.args.skin as SkinType] ?? SkinDefinition.primary;
}
get hasEllipsis(): boolean {
if (!this.args.hasEllipsis) {
return false;
}
return this.args.hasEllipsis;
}
get computedClass() {
let classes = [BASE_CLASS];
if (this.skin) {
classes.push(`upf-tag--${this.skin}`);
}
return classes.join(' ');
}
}
| import Component from '@glimmer/component';
export type SkinType = 'primary' | 'success' | 'warning' | 'danger' | 'secondary';
type SkinDefType = {
[key in SkinType]: string;
};
const BASE_CLASS = 'upf-tag';
export const SkinDefinition: SkinDefType = {
primary: 'regular',
success: 'success',
warning: 'alert',
danger: 'critical',
secondary: 'neutral'
};
interface OSSTagArgs {
label?: string;
skin?: string;
icon?: string;
hasEllipsis?: boolean;
}
export default class OSSTag extends Component<OSSTagArgs> {
constructor(owner: unknown, args: OSSTagArgs) {
super(owner, args);
if (!args.icon && !args.label) {
throw new Error('[component][OSS::Tag] You must pass either a @label or an @icon argument.');
}
}
get skin(): string {
if (!this.args.skin) {
return SkinDefinition.primary;
}
return SkinDefinition[this.args.skin as SkinType] ?? SkinDefinition.primary;
}
get hasEllipsis(): boolean {
if (!this.args.hasEllipsis) {
return false;
}
return this.args.hasEllipsis;
}
get computedClass(): string {
let classes = [BASE_CLASS];
if (this.skin) {
classes.push(`upf-tag--${this.skin}`);
}
return classes.join(' ');
}
}
| Update because of PR Review | Update because of PR Review
| TypeScript | mit | upfluence/oss-components,upfluence/oss-components,upfluence/oss-components,upfluence/oss-components | ---
+++
@@ -46,7 +46,7 @@
return this.args.hasEllipsis;
}
- get computedClass() {
+ get computedClass(): string {
let classes = [BASE_CLASS];
if (this.skin) { |
5cf0d4aee06ca1c1e5e38a9b1d1c69dcc22a166d | demo/demo_config.ts | demo/demo_config.ts | // The address of your Looker instance. Required.
export const lookerHost = 'self-signed.looker.com:9999'
// A dashboard that the user can see. Set to 0 to disable dashboard demo.
export const dashboardId = 1
// A Look that the user can see. Set to 0 to disable look demo.
export const lookId = 1
// An Explore that the user can see. Set to '' to disable explore demo.
export const exploreId = 'thelook::products'
// An Extension that the user can see. Set to '' to disable extension demo.
// export const extensionId = 'extension::my-great-extension'
export const extensionId = ''
| // The address of your Looker instance. Required.
export const lookerHost = 'self-signed.looker.com:9999'
// A dashboard that the user can see. Set to 0 to disable dashboard demo.
export const dashboardId = 1
// A Look that the user can see. Set to 0 to disable look demo.
export const lookId = 1
// An Explore that the user can see. Set to '' to disable explore demo.
export const exploreId = 'thelook::orders'
// An Extension that the user can see. Set to '' to disable extension demo.
// export const extensionId = 'extension::my-great-extension'
export const extensionId = ''
| Use demo explore with users.state. | Use demo explore with users.state.
| TypeScript | mit | looker-open-source/embed-sdk,looker-open-source/embed-sdk,looker-open-source/embed-sdk,looker-open-source/embed-sdk | ---
+++
@@ -6,7 +6,7 @@
// A Look that the user can see. Set to 0 to disable look demo.
export const lookId = 1
// An Explore that the user can see. Set to '' to disable explore demo.
-export const exploreId = 'thelook::products'
+export const exploreId = 'thelook::orders'
// An Extension that the user can see. Set to '' to disable extension demo.
// export const extensionId = 'extension::my-great-extension'
export const extensionId = '' |
905f0d85bf0506f592a4de418cc7a230c3668832 | src/events/registry.ts | src/events/registry.ts | import { translate } from '@waldur/i18n';
import { EventGroup } from './types';
export class EventRegistry {
private groups = [];
private formatters = {};
registerGroup(group: EventGroup) {
this.groups.push(group);
for (const type of group.events) {
const defaultFormatter = (event) => {
let context = event;
if (group.context) {
context = { ...context, ...group.context(event) };
}
return translate(type.title, context);
};
this.formatters[type.key] = type.formatter || defaultFormatter;
}
}
formatEvent(event) {
const formatter = this.formatters[event.event_type];
if (formatter) {
return formatter(event.context);
} else {
return event.message;
}
}
getGroups() {
return this.groups;
}
}
const registry = new EventRegistry();
export default registry;
| import { translate } from '@waldur/i18n';
import { EventGroup } from './types';
export class EventRegistry {
private groups = [];
private formatters = {};
registerGroup(group: EventGroup) {
this.groups.push(group);
for (const type of group.events) {
const defaultFormatter = (event) => {
let context = event;
if (group.context) {
context = { ...context, ...group.context(event) };
}
return translate(type.title, context);
};
this.formatters[type.key] = type.formatter || defaultFormatter;
}
}
formatEvent(event) {
const formatter = this.formatters[event.event_type];
if (formatter) {
return formatter(event.context) || event.message;
} else {
return event.message;
}
}
getGroups() {
return this.groups;
}
}
const registry = new EventRegistry();
export default registry;
| Fix event log rendering for offering permission event | Fix event log rendering for offering permission event [WAL-3764]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -23,7 +23,7 @@
formatEvent(event) {
const formatter = this.formatters[event.event_type];
if (formatter) {
- return formatter(event.context);
+ return formatter(event.context) || event.message;
} else {
return event.message;
} |
6924ab35f330f9dc7a4518af8be70ae65e3ff37c | src/storage/CachedStorage.ts | src/storage/CachedStorage.ts | import bind from "bind-decorator";
import { Subscribable } from "event/Event";
import { SyncEvent } from "event/SyncEvent";
import { Storage } from "storage/Storage";
export class CachedStorage<T> implements Storage<T> {
private readonly _onChange = new SyncEvent<T | null>();
private readonly init: Promise<void>;
private cache: Readonly<T | null> = null;
public constructor(
private readonly delegate: Storage<T>
) {
// Listen for changes in storage and update internal cache
delegate.onChange.subscribe(this.onStorageChange);
// Sync internal cache with storage
this.init = delegate.load()
.then((data: T | null) => {
this.cache = data;
});
}
public get onChange(): Subscribable<T | null> {
return this._onChange;
}
public async save(data: T | null): Promise<void> {
await this.init;
this.cache = data;
return this.delegate.save(data);
}
public async load(): Promise<T | null> {
await this.init;
return this.cache;
}
public clear(): Promise<void> {
return this.delegate.clear();
}
public dispose(): void {
this._onChange.dispose();
this.delegate.dispose();
}
@bind
private onStorageChange(data: T | null): void {
this.cache = data;
this._onChange.dispatch(this.cache);
}
}
| import bind from "bind-decorator";
import { Subscribable } from "event/Event";
import { SyncEvent } from "event/SyncEvent";
import { Storage } from "storage/Storage";
export class CachedStorage<T> implements Storage<T> {
private readonly _onChange = new SyncEvent<T | null>();
private cache: Readonly<T | null> = null;
private initialized = false;
public constructor(
private readonly delegate: Storage<T>
) {
// Listen for changes in storage and update internal cache
delegate.onChange.subscribe(this.onStorageChange);
}
public get onChange(): Subscribable<T | null> {
return this._onChange;
}
public async save(data: T | null): Promise<void> {
this.cache = data;
return this.delegate.save(data);
}
public async load(): Promise<T | null> {
if (!this.initialized) {
this.initialized = true;
this.cache = await this.delegate.load();
}
return this.cache;
}
public async clear(): Promise<void> {
await this.delegate.clear();
}
public dispose(): void {
this._onChange.dispose();
this.delegate.dispose();
}
@bind
private onStorageChange(data: T | null): void {
this.cache = data;
this.initialized = true;
this._onChange.dispatch(this.cache);
}
}
| Initialize cache on first load rather than instantiation | Initialize cache on first load rather than instantiation
| TypeScript | mit | easyfuckingpeasy/chrome-reddit-comment-highlights,easyfuckingpeasy/chrome-reddit-comment-highlights | ---
+++
@@ -5,20 +5,14 @@
export class CachedStorage<T> implements Storage<T> {
private readonly _onChange = new SyncEvent<T | null>();
- private readonly init: Promise<void>;
private cache: Readonly<T | null> = null;
+ private initialized = false;
public constructor(
private readonly delegate: Storage<T>
) {
// Listen for changes in storage and update internal cache
delegate.onChange.subscribe(this.onStorageChange);
-
- // Sync internal cache with storage
- this.init = delegate.load()
- .then((data: T | null) => {
- this.cache = data;
- });
}
public get onChange(): Subscribable<T | null> {
@@ -26,21 +20,22 @@
}
public async save(data: T | null): Promise<void> {
- await this.init;
-
this.cache = data;
return this.delegate.save(data);
}
public async load(): Promise<T | null> {
- await this.init;
+ if (!this.initialized) {
+ this.initialized = true;
+ this.cache = await this.delegate.load();
+ }
return this.cache;
}
- public clear(): Promise<void> {
- return this.delegate.clear();
+ public async clear(): Promise<void> {
+ await this.delegate.clear();
}
public dispose(): void {
@@ -51,6 +46,7 @@
@bind
private onStorageChange(data: T | null): void {
this.cache = data;
+ this.initialized = true;
this._onChange.dispatch(this.cache);
} |
1faf756a1d926576e1276ef437545a9df609561b | client/app/accounts/components/register/register.component.ts | client/app/accounts/components/register/register.component.ts | import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Account } from '../../models';
import { AccountService } from '../../services';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent {
public account = new Account();
public passwordConfirmation2: string;
public errorMessage: string;
constructor(private service: AccountService, private router: Router) {
}
register() {
this.service
.register(this.account.email, this.account.password)
.then(() => this.router.navigate(['/']))
.catch(() => this.errorMessage = `We're sorry, but an unexpected error occurred.`)
;
}
}
| import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Account } from '../../models';
import { AccountService } from '../../services';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent {
public account = new Account();
public passwordConfirmation2: string;
public errorMessage: string;
constructor(private service: AccountService, private router: Router) {
}
register() {
this.service
.register(this.account.email, this.account.password)
.then(() => this.router.navigate(['/']))
.catch(error => this.errorMessage = getErrorMessage(error.status))
;
function getErrorMessage(status) {
switch (status) {
case 409:
return 'This account already exists.';
default:
return `We're sorry, but an unexpected error occurred.`;
}
}
}
}
| Add specific error message for conflict | Add specific error message for conflict
| TypeScript | mit | fvilers/angular2-training,fvilers/angular2-training,fvilers/angular2-training | ---
+++
@@ -21,7 +21,16 @@
this.service
.register(this.account.email, this.account.password)
.then(() => this.router.navigate(['/']))
- .catch(() => this.errorMessage = `We're sorry, but an unexpected error occurred.`)
+ .catch(error => this.errorMessage = getErrorMessage(error.status))
;
+
+ function getErrorMessage(status) {
+ switch (status) {
+ case 409:
+ return 'This account already exists.';
+ default:
+ return `We're sorry, but an unexpected error occurred.`;
+ }
+ }
}
} |
685782b4aba3b80e1f36ca5b918ea00c57a6da48 | lib/resources/tasks/process-less.ts | lib/resources/tasks/process-less.ts | import * as gulp from 'gulp';
import * as changedInPlace from 'gulp-changed-in-place';
import * as sourcemaps from 'gulp-sourcemaps';
import * as less from 'gulp-less';
import * as project from '../aurelia.json';
import {build} from 'aurelia-cli';
export default function processCSS() {
return gulp.src(project.cssProcessor.source)
.pipe(changedInPlace({firstPass:true}))
.pipe(sourcemaps.init())
.pipe(less())
.pipe(build.bundle());
};
| import * as gulp from 'gulp';
import * as changedInPlace from 'gulp-changed-in-place';
import * as sourcemaps from 'gulp-sourcemaps';
import * as less from 'gulp-less';
import * as plumber from 'gulp-plumber';
import * as notify from 'gulp-notify';
import * as project from '../aurelia.json';
import {build} from 'aurelia-cli';
export default function processCSS() {
return gulp.src(project.cssProcessor.source)
.pipe(changedInPlace({firstPass:true}))
.pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }))
.pipe(sourcemaps.init())
.pipe(less())
.pipe(build.bundle());
};
| Stop breaking the stream when a less file doesn't compile by introducing plumber here as well. Also add better error logging through notify. | Stop breaking the stream when a less file doesn't compile by introducing plumber here as well. Also add better error logging through notify.
| TypeScript | mit | ghidello/cli,zewa666/cli,zewa666/cli,aurelia/cli,DrSammyD/cli,ghidello/cli,ghidello/cli,zewa666/cli,aurelia/cli,DrSammyD/cli,zewa666/cli,DrSammyD/cli | ---
+++
@@ -2,12 +2,15 @@
import * as changedInPlace from 'gulp-changed-in-place';
import * as sourcemaps from 'gulp-sourcemaps';
import * as less from 'gulp-less';
+import * as plumber from 'gulp-plumber';
+import * as notify from 'gulp-notify';
import * as project from '../aurelia.json';
import {build} from 'aurelia-cli';
export default function processCSS() {
return gulp.src(project.cssProcessor.source)
.pipe(changedInPlace({firstPass:true}))
+ .pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }))
.pipe(sourcemaps.init())
.pipe(less())
.pipe(build.bundle()); |
8d2ac8dbda1384b16f469e6e4ddb85ee5ad0ea64 | src/app/core/datastore/model/datastore-errors.ts | src/app/core/datastore/model/datastore-errors.ts | /**
* @author Daniel de Oliveira
*/
export class DatastoreErrors {
public static INVALID_DOCUMENT: string = 'idai-components-2/datastore/invaliddocument';
public static GENERIC_ERROR: string = 'idai-components-2/datastore/genericerror';
public static DOCUMENT_RESOURCE_ID_EXISTS: string = 'idai-components-2/datastore/documentresourceidexists';
public static DOCUMENT_NO_RESOURCE_ID: string = 'idai-components-2/datastore/documentnoresourceid';
public static DOCUMENT_NOT_FOUND: string = 'idai-components-2/datastore/documentnotfound';
public static SAVE_CONFLICT: string = 'idai-components-2/datastore/saveconflict';
public static REMOVE_REVISIONS_ERROR: string = 'idai-components-2/datastore/removerevisionserror';
}
| /**
* @author Daniel de Oliveira
*/
export class DatastoreErrors {
public static INVALID_DOCUMENT: string = 'datastore/invaliddocument';
public static GENERIC_ERROR: string = 'datastore/genericerror';
public static DOCUMENT_RESOURCE_ID_EXISTS: string = 'datastore/documentresourceidexists';
public static DOCUMENT_NO_RESOURCE_ID: string = 'datastore/documentnoresourceid';
public static DOCUMENT_NOT_FOUND: string = 'datastore/documentnotfound';
public static SAVE_CONFLICT: string = 'datastore/saveconflict';
public static REMOVE_REVISIONS_ERROR: string = 'datastore/removerevisionserror';
}
| Remove 'idai-components-2' from string values of DatastoreErrors | Remove 'idai-components-2' from string values of DatastoreErrors
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -3,11 +3,11 @@
*/
export class DatastoreErrors {
- public static INVALID_DOCUMENT: string = 'idai-components-2/datastore/invaliddocument';
- public static GENERIC_ERROR: string = 'idai-components-2/datastore/genericerror';
- public static DOCUMENT_RESOURCE_ID_EXISTS: string = 'idai-components-2/datastore/documentresourceidexists';
- public static DOCUMENT_NO_RESOURCE_ID: string = 'idai-components-2/datastore/documentnoresourceid';
- public static DOCUMENT_NOT_FOUND: string = 'idai-components-2/datastore/documentnotfound';
- public static SAVE_CONFLICT: string = 'idai-components-2/datastore/saveconflict';
- public static REMOVE_REVISIONS_ERROR: string = 'idai-components-2/datastore/removerevisionserror';
+ public static INVALID_DOCUMENT: string = 'datastore/invaliddocument';
+ public static GENERIC_ERROR: string = 'datastore/genericerror';
+ public static DOCUMENT_RESOURCE_ID_EXISTS: string = 'datastore/documentresourceidexists';
+ public static DOCUMENT_NO_RESOURCE_ID: string = 'datastore/documentnoresourceid';
+ public static DOCUMENT_NOT_FOUND: string = 'datastore/documentnotfound';
+ public static SAVE_CONFLICT: string = 'datastore/saveconflict';
+ public static REMOVE_REVISIONS_ERROR: string = 'datastore/removerevisionserror';
} |
4c21d84c6cf6e2c898ba0e5f916b043dc1c1deb5 | src/image-sizes.ts | src/image-sizes.ts | export {}; // To get around: Cannot redeclare block-scoped variable 'mockLogger'.ts(2451)
/**
* Calculate the sizes to be used for resizing the image based on the current size
* @param {number} width - the width of the original image
* @return {ImageSize[]} - an array of up to 4 elements representing the size
* in each group
*/
function calcSizes(width: number): ImageSize[] {
if (width < 1) {
throw new Error(`Unexpected width less than 1: ${width}`);
}
const brackets = [{
bracket: 100,
name: 'thumb',
}, {
bracket: 500,
name: 'sm',
}, {
bracket: 1000,
name: 'md',
}, {
bracket: 1500,
name: 'lg',
}, {
bracket: 2000,
name: 'xl',
}];
return brackets.reduce(
(acc: ImageSize[], { bracket, name }, index) => {
let w;
if (width > bracket) {
w = bracket;
} else if (index > 0 && width > brackets[index - 1].bracket && width <= bracket) {
w = width;
} else if (index === 0 && width <= bracket) {
w = width;
}
if (w) {
acc.push({ width: w, name });
}
return acc;
}, [],
);
}
module.exports = calcSizes;
| export {}; // To get around: Cannot redeclare block-scoped variable 'mockLogger'.ts(2451)
/**
* Calculate the sizes to be used for resizing the image based on the current size
* @param width - the width of the original image
* @return - an array of up to 4 elements representing the size
* in each group
*/
const calcSizes = (width: number): ImageSize[] => {
if (width < 1) {
throw new Error(`Unexpected width less than 1: ${width}`);
}
const brackets = [{
bracket: 100,
name: 'thumb',
}, {
bracket: 500,
name: 'sm',
}, {
bracket: 1000,
name: 'md',
}, {
bracket: 1500,
name: 'lg',
}, {
bracket: 2000,
name: 'xl',
}];
return brackets.reduce(
(acc: ImageSize[], { bracket, name }, index) => {
let w;
if (width > bracket) {
w = bracket;
} else if (index > 0 && width > brackets[index - 1].bracket && width <= bracket) {
w = width;
} else if (index === 0 && width <= bracket) {
w = width;
}
if (w) {
acc.push({ width: w, name });
}
return acc;
}, [],
);
};
module.exports = calcSizes;
| Change calcSizes from function to arrow function | Change calcSizes from function to arrow function
| TypeScript | mit | guyellis/plant-image-lambda,guyellis/plant-image-lambda | ---
+++
@@ -2,11 +2,11 @@
/**
* Calculate the sizes to be used for resizing the image based on the current size
- * @param {number} width - the width of the original image
- * @return {ImageSize[]} - an array of up to 4 elements representing the size
+ * @param width - the width of the original image
+ * @return - an array of up to 4 elements representing the size
* in each group
*/
-function calcSizes(width: number): ImageSize[] {
+const calcSizes = (width: number): ImageSize[] => {
if (width < 1) {
throw new Error(`Unexpected width less than 1: ${width}`);
}
@@ -44,6 +44,6 @@
return acc;
}, [],
);
-}
+};
module.exports = calcSizes; |
a6104f9bdc6c076f6643e688e617913354013384 | src/client/web/components/PathwayDisplay/PrerequisiteBox/WorkExperienceBox.tsx | src/client/web/components/PathwayDisplay/PrerequisiteBox/WorkExperienceBox.tsx | import * as React from 'react'
import CombinationBox from '../CombinationBox'
import { WorkExperiencePrereq } from '../../../../../definitions/Prerequisites/WorkExperiencePrereq'
import inflect from '../../../../utils/inflect'
import { text } from '../../../../utils/text'
import { units } from '../../../../../data/common/units'
import { LangId } from '../../../../../definitions/auxiliary/MultiLang'
const WorkExperienceBox = (props: { prereq: WorkExperiencePrereq, lang: LangId }) => {
const prereq = props.prereq
const texts = {
workExperiences: text({
en: 'Work experience:',
zh_hans: '工作经验:',
}),
withinLast: text({
en: 'With in the last',
zh_hans: '过去',
}),
}
return (
<div>
{texts.workExperiences}
<div style={{marginBottom: '0.5em'}}>
{
prereq.withinLast &&
`${texts.withinLast}
${prereq.withinLast.value}
${inflect(text(units[prereq.withinLast.unit].name), {number: prereq.withinLast.value})}, `
}
{
prereq.duration
? `you have worked ${prereq.duration[1].value} ${inflect(
text(prereq.duration[1].unit),
{number: prereq.duration[1].value})} in:`
: ''
}
</div>
<CombinationBox combo={prereq.jobNature as any} level={1} lang={props.lang}/>
</div>
)
}
export default WorkExperienceBox
| import * as React from 'react'
import CombinationBox from '../CombinationBox'
import { WorkExperiencePrereq } from '../../../../../definitions/Prerequisites/WorkExperiencePrereq'
import inflect from '../../../../utils/inflect'
import { text } from '../../../../utils/text'
import { units } from '../../../../../data/common/units'
import { LangId } from '../../../../../definitions/auxiliary/MultiLang'
const WorkExperienceBox = (props: { prereq: WorkExperiencePrereq, lang: LangId }) => {
const prereq = props.prereq
const texts = {
withinLast: text({
en: 'With in the last',
zh_hans: '过去',
}),
}
return (
<div>
<div style={{marginBottom: '0.5em'}}>
{
prereq.withinLast &&
`${texts.withinLast}
${prereq.withinLast.value}
${inflect(text(units[prereq.withinLast.unit].name), {number: prereq.withinLast.value})}, `
}
{
prereq.duration
? `you have worked ${prereq.duration[1].value} ${inflect(
text(prereq.duration[1].unit),
{number: prereq.duration[1].value})} in:`
: ''
}
</div>
<CombinationBox combo={prereq.jobNature as any} level={1} lang={props.lang}/>
</div>
)
}
export default WorkExperienceBox
| Remove title that usually overlap with combination title | Remove title that usually overlap with combination title
Signed-off-by: Andy Shu <d9a5ae79e0620530e640970c782273ccd89702f2@gmail.com>
| TypeScript | agpl-3.0 | wikimigrate/wikimigrate,wikimigrate/wikimigrate,wikimigrate/wikimigrate,wikimigrate/wikimigrate | ---
+++
@@ -10,10 +10,6 @@
const WorkExperienceBox = (props: { prereq: WorkExperiencePrereq, lang: LangId }) => {
const prereq = props.prereq
const texts = {
- workExperiences: text({
- en: 'Work experience:',
- zh_hans: '工作经验:',
- }),
withinLast: text({
en: 'With in the last',
zh_hans: '过去',
@@ -21,7 +17,6 @@
}
return (
<div>
- {texts.workExperiences}
<div style={{marginBottom: '0.5em'}}>
{
prereq.withinLast && |
ed6f9b2cb78eb18aab07807056a4d9841f1e4c3f | app/src/lib/open-shell.ts | app/src/lib/open-shell.ts | import { spawn } from 'child_process'
import { fatalError } from './fatal-error'
/** Opens a shell setting the working directory to fullpath. If a shell is not specified, OS defaults are used. */
export function openShell(fullPath: string, shell?: string) {
let commandName: string = ''
let commandArgs: ReadonlyArray<string>
if ( __DARWIN__) {
commandName = 'open'
commandArgs = [ '-a', shell || 'Terminal', fullPath ]
}
else if (__WIN32__) {
commandName = 'START'
commandArgs = [ shell || 'cmd', '/D', `"${fullPath}"` , 'title', 'GitHub Desktop' ]
}
else {
return fatalError('Unsupported OS')
}
return spawn(commandName, commandArgs.map(x => x), { 'shell' : true })
}
| import { spawn } from 'child_process'
import { fatalError } from './fatal-error'
/** Opens a shell setting the working directory to fullpath. If a shell is not specified, OS defaults are used. */
export function openShell(fullPath: string, shell?: string) {
let commandName: string = ''
let commandArgs: ReadonlyArray<string>
if ( __DARWIN__) {
commandName = 'open'
commandArgs = [ '-a', shell || 'Terminal', fullPath ]
}
else if (__WIN32__) {
commandName = 'START'
commandArgs = [ shell || 'cmd', '/D', `"${fullPath}"` , 'title', 'GitHub Desktop' ]
}
else {
return fatalError('Unsupported OS')
}
return spawn(commandName, Array.from(commandArgs), { 'shell' : true })
}
| Use correct function to convert to an array | Use correct function to convert to an array
| TypeScript | mit | hjobrien/desktop,shiftkey/desktop,kactus-io/kactus,gengjiawen/desktop,kactus-io/kactus,shiftkey/desktop,hjobrien/desktop,BugTesterTest/desktops,hjobrien/desktop,say25/desktop,artivilla/desktop,hjobrien/desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,BugTesterTest/desktops,shiftkey/desktop,BugTesterTest/desktops,BugTesterTest/desktops,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,gengjiawen/desktop,artivilla/desktop,kactus-io/kactus,gengjiawen/desktop,kactus-io/kactus,desktop/desktop,gengjiawen/desktop,j-f1/forked-desktop,j-f1/forked-desktop,artivilla/desktop,say25/desktop,desktop/desktop,say25/desktop | ---
+++
@@ -18,5 +18,5 @@
return fatalError('Unsupported OS')
}
- return spawn(commandName, commandArgs.map(x => x), { 'shell' : true })
+ return spawn(commandName, Array.from(commandArgs), { 'shell' : true })
} |
4416d199e21a5207361e3311072c2dbefa9a3ed0 | packages/@sanity/form-builder/src/sanity/uploads/utils.ts | packages/@sanity/form-builder/src/sanity/uploads/utils.ts | import {UploadEvent} from './typedefs'
import {UPLOAD_STATUS_KEY} from './constants'
import {set, unset} from '../../utils/patches'
const UNSET_UPLOAD_PATCH = unset([UPLOAD_STATUS_KEY])
export function createUploadEvent(patches = []): UploadEvent {
return {
type: 'uploadEvent',
patches
}
}
export const CLEANUP_EVENT = createUploadEvent([UNSET_UPLOAD_PATCH])
export function createInitialUploadEvent(file: File) {
return createUploadEvent([
set(
{
progress: 2,
initiated: new Date().toISOString(),
file: {name: file.name, type: file.type}
},
[UPLOAD_STATUS_KEY]
)
])
}
| import {UploadEvent} from './typedefs'
import {UPLOAD_STATUS_KEY} from './constants'
import {set, unset, setIfMissing} from '../../utils/patches'
const UNSET_UPLOAD_PATCH = unset([UPLOAD_STATUS_KEY])
export function createUploadEvent(patches = []): UploadEvent {
return {
type: 'uploadEvent',
patches
}
}
export const CLEANUP_EVENT = createUploadEvent([UNSET_UPLOAD_PATCH])
export function createInitialUploadEvent(file: File) {
const value = {
progress: 2,
initiated: new Date().toISOString(),
file: {name: file.name, type: file.type}
}
return createUploadEvent([
setIfMissing({[UPLOAD_STATUS_KEY]: value}, []),
set(value, [UPLOAD_STATUS_KEY])
])
}
| Add setIfMissing patch to createInitialUploadEvent | [form-builder] Add setIfMissing patch to createInitialUploadEvent
If you have a nested object inside the PTE which you upload images to, there will be an error because the _upload key is not set yet.
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -1,6 +1,6 @@
import {UploadEvent} from './typedefs'
import {UPLOAD_STATUS_KEY} from './constants'
-import {set, unset} from '../../utils/patches'
+import {set, unset, setIfMissing} from '../../utils/patches'
const UNSET_UPLOAD_PATCH = unset([UPLOAD_STATUS_KEY])
@@ -14,14 +14,13 @@
export const CLEANUP_EVENT = createUploadEvent([UNSET_UPLOAD_PATCH])
export function createInitialUploadEvent(file: File) {
+ const value = {
+ progress: 2,
+ initiated: new Date().toISOString(),
+ file: {name: file.name, type: file.type}
+ }
return createUploadEvent([
- set(
- {
- progress: 2,
- initiated: new Date().toISOString(),
- file: {name: file.name, type: file.type}
- },
- [UPLOAD_STATUS_KEY]
- )
+ setIfMissing({[UPLOAD_STATUS_KEY]: value}, []),
+ set(value, [UPLOAD_STATUS_KEY])
])
} |
53932ea12ea5e85a65c8e2db51cd7283a88947af | index.d.ts | index.d.ts | interface stringToObjConfig {
trim: Boolean;
delimiters: {
values: { [key: string]: any },
blackhole: string | Boolean,
};
}
declare module 'string-to-obj' {
class stringToObj {
constructor(config: stringToObjConfig);
}
namespace stringToObj {
function parse(input: string): { [key: string]: string[] };
const source: stringToObjConfig;
}
export = stringToObj;
}
| interface stringToObjConfig {
trim?: Boolean;
delimiters?: {
values?: { [key: string]: any },
blackhole?: string | Boolean,
};
}
declare module 'string-to-obj' {
class stringToObj {
constructor(config?: stringToObjConfig);
}
namespace stringToObj {
function parse(input: string): { [key: string]: string[] };
const source: stringToObjConfig;
}
export = stringToObj;
}
| Configure args to be optional in TypeScript | :wrench: Configure args to be optional in TypeScript
| TypeScript | mit | richmondwang/string-to-obj | ---
+++
@@ -1,15 +1,15 @@
interface stringToObjConfig {
- trim: Boolean;
- delimiters: {
- values: { [key: string]: any },
- blackhole: string | Boolean,
+ trim?: Boolean;
+ delimiters?: {
+ values?: { [key: string]: any },
+ blackhole?: string | Boolean,
};
}
declare module 'string-to-obj' {
class stringToObj {
- constructor(config: stringToObjConfig);
+ constructor(config?: stringToObjConfig);
}
namespace stringToObj { |
09fed824ad739f013cf7d0c3ab08a0f2dd889b9d | src/js/View/Components/AppAlerts/Index.tsx | src/js/View/Components/AppAlerts/Index.tsx | import * as React from 'react';
import { connect } from 'react-redux';
import AppAlert from './AppAlert';
interface IAppAlertsProps
{
appAlerts?: IAppAlert[];
};
class AppAlerts extends React.Component<IAppAlertsProps, any>
{
render()
{
return (
<div className="app-alert-container">
{this.props.appAlerts
.map(a => <AppAlert key={a.index}
appAlert={a} />)}
</div>
);
}
};
export default connect(
(state: IState, props: IAppAlertsProps) => ({
appAlerts : state.appAlerts.alerts
})
)(AppAlerts as any); // @todo: Fix this. It's complaining. :( | import * as React from 'react';
import { connect } from 'react-redux';
import AppAlert from './AppAlert';
interface IAppAlertsProps
{
appAlerts?: IAppAlert[];
};
class AppAlerts extends React.Component<IAppAlertsProps, any>
{
render()
{
return (
<div className="app-alert-container">
{this.props.appAlerts
.map(a => <AppAlert key={a.index}
appAlert={a} />)}
</div>
);
}
};
export default connect<{}, {}, IAppAlertsProps>(
(state: IState, props: IAppAlertsProps) => ({
appAlerts : state.appAlerts.alerts
})
)(AppAlerts); | Fix @todo: AppAlerts connect wrapping | Fix @todo: AppAlerts connect wrapping
| TypeScript | mit | harksys/HawkEye,harksys/HawkEye,harksys/HawkEye | ---
+++
@@ -22,8 +22,8 @@
}
};
-export default connect(
+export default connect<{}, {}, IAppAlertsProps>(
(state: IState, props: IAppAlertsProps) => ({
appAlerts : state.appAlerts.alerts
})
-)(AppAlerts as any); // @todo: Fix this. It's complaining. :(
+)(AppAlerts); |
45aa575cfb01e8e056797073b29c80de035b5561 | APM-Start/src/app/products/product-edit/product-edit-info.component.ts | APM-Start/src/app/products/product-edit/product-edit-info.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';
import { Product } from '../product';
@Component({
templateUrl: './product-edit-info.component.html'
})
export class ProductEditInfoComponent implements OnInit {
@ViewChild(NgForm, {static: false}) productForm: NgForm;
errorMessage: string;
product = { id: 1, productName: 'test', productCode: 'test' };
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
}
}
| import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';
import { Product } from '../product';
@Component({
templateUrl: './product-edit-info.component.html'
})
export class ProductEditInfoComponent implements OnInit {
@ViewChild(NgForm, {static: false}) productForm: NgForm;
errorMessage: string;
product = { id: 1, productName: 'test', productCode: 'test', description: 'test' };
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
}
}
| Add description property to temporary data | Add description property to temporary data
| TypeScript | mit | DeborahK/Angular-Routing,DeborahK/Angular-Routing,DeborahK/Angular-Routing | ---
+++
@@ -11,7 +11,7 @@
@ViewChild(NgForm, {static: false}) productForm: NgForm;
errorMessage: string;
- product = { id: 1, productName: 'test', productCode: 'test' };
+ product = { id: 1, productName: 'test', productCode: 'test', description: 'test' };
constructor(private route: ActivatedRoute) { }
|
0e2cf4bbec21fa03cada14d4efe87f00c5e680f4 | lib/components/src/blocks/ArgsTable/SectionRow.stories.tsx | lib/components/src/blocks/ArgsTable/SectionRow.stories.tsx | import React from 'react';
import { SectionRow } from './SectionRow';
import { TableWrapper } from './ArgsTable';
import { ResetWrapper } from '../../typography/DocumentFormatting';
export default {
component: SectionRow,
title: 'Docs/SectionRow',
decorators: [
(getStory) => (
<ResetWrapper>
<TableWrapper>
<tbody>{getStory()}</tbody>
</TableWrapper>
</ResetWrapper>
),
],
};
const Story = (args) => <SectionRow {...args} />;
export const Section = Story.bind({});
Section.args = { level: 'section', label: 'Props' };
export const Subsection = Story.bind({});
Subsection.args = { level: 'subsection', label: 'HTMLElement' };
export const Collapsed = Story.bind({});
Collapsed.args = { ...Section.args, initialExpanded: false };
export const Nested = () => (
<SectionRow {...Section.args}>
<SectionRow {...Subsection.args}>
<tr>
<td>Some content</td>
</tr>
</SectionRow>
</SectionRow>
);
| import React from 'react';
import { SectionRow } from './SectionRow';
import { TableWrapper } from './ArgsTable';
import { ResetWrapper } from '../../typography/DocumentFormatting';
export default {
component: SectionRow,
title: 'Docs/SectionRow',
decorators: [
(getStory) => (
<ResetWrapper>
<TableWrapper>
<tbody>{getStory()}</tbody>
</TableWrapper>
</ResetWrapper>
),
],
};
const Story = (args) => <SectionRow {...args} />;
export const Section = Story.bind({});
Section.args = { level: 'section', label: 'Props' };
export const Subsection = Story.bind({});
Subsection.args = { level: 'subsection', label: 'HTMLElement' };
export const Collapsed = Story.bind({});
Collapsed.args = { ...Section.args, initialExpanded: false };
export const Nested = () => (
<SectionRow {...Section.args}>
<SectionRow {...Subsection.args}>
<tr>
<td colSpan={2}>Some content</td>
</tr>
</SectionRow>
</SectionRow>
);
| Fix bug in SectionRow story | Fix bug in SectionRow story
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook | ---
+++
@@ -32,7 +32,7 @@
<SectionRow {...Section.args}>
<SectionRow {...Subsection.args}>
<tr>
- <td>Some content</td>
+ <td colSpan={2}>Some content</td>
</tr>
</SectionRow>
</SectionRow> |
0a12b27bd19ef1342f3df9aa87d91a0e32b1e15a | src/components/Queue/QueueTable.tsx | src/components/Queue/QueueTable.tsx | import * as React from 'react';
import { SearchMap } from '../../types';
import { Card, ResourceList, FormLayout, Button } from '@shopify/polaris';
import EmptyQueue from './EmptyQueue';
import QueueItem from './QueueItem';
export interface Props {
readonly queue: SearchMap;
}
export interface Handlers {
readonly onRefresh: () => void;
}
const QueueTable = ({ queue, onRefresh }: Props & Handlers) => {
return queue.isEmpty() ? (
<EmptyQueue onRefresh={onRefresh} />
) : (
<Card>
<Card.Section>
<FormLayout>
<Button>Refresh queue.</Button>
</FormLayout>
</Card.Section>
<ResourceList
items={queue.toArray()}
renderItem={hit => <QueueItem hit={hit} />}
/>
</Card>
);
};
export default QueueTable;
| import * as React from 'react';
import { SearchMap } from '../../types';
import { Card, ResourceList, Stack, Button } from '@shopify/polaris';
import EmptyQueue from './EmptyQueue';
import QueueItem from './QueueItem';
export interface Props {
readonly queue: SearchMap;
}
export interface Handlers {
readonly onRefresh: () => void;
}
const QueueTable = ({ queue, onRefresh }: Props & Handlers) => {
return queue.isEmpty() ? (
<EmptyQueue onRefresh={onRefresh} />
) : (
<Stack vertical>
<Card sectioned>
<Button>Refresh queue.</Button>
</Card>
<Card>
<ResourceList
items={queue.toArray()}
renderItem={hit => <QueueItem hit={hit} />}
/>
</Card>
</Stack>
);
};
export default QueueTable;
| Refresh queue button is now a child of a Card. | Refresh queue button is now a child of a Card.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -1,6 +1,6 @@
import * as React from 'react';
import { SearchMap } from '../../types';
-import { Card, ResourceList, FormLayout, Button } from '@shopify/polaris';
+import { Card, ResourceList, Stack, Button } from '@shopify/polaris';
import EmptyQueue from './EmptyQueue';
import QueueItem from './QueueItem';
@@ -16,17 +16,17 @@
return queue.isEmpty() ? (
<EmptyQueue onRefresh={onRefresh} />
) : (
- <Card>
- <Card.Section>
- <FormLayout>
- <Button>Refresh queue.</Button>
- </FormLayout>
- </Card.Section>
- <ResourceList
- items={queue.toArray()}
- renderItem={hit => <QueueItem hit={hit} />}
- />
- </Card>
+ <Stack vertical>
+ <Card sectioned>
+ <Button>Refresh queue.</Button>
+ </Card>
+ <Card>
+ <ResourceList
+ items={queue.toArray()}
+ renderItem={hit => <QueueItem hit={hit} />}
+ />
+ </Card>
+ </Stack>
);
};
|
60c167097f724c8e84e7afa923ef6673ec3cb36b | showcase/app/app.component.ts | showcase/app/app.component.ts | import {Component, ViewEncapsulation} from '@angular/core';
import {MenuItem} from 'primeng/primeng';
import {SiteBrowserState} from "../../core/util/site-browser.state";
import {SettingsService} from "../services/settings.services";
var prismjs = require('../assets/js/prism');
@Component({
selector: 'my-app',
template: require('./app.component.html'),
styles: [
require('./app.component.css'),
require('../assets/css/prism.css'),
require('../../node_modules/primeng/resources/primeng.min.css'),
require('../../node_modules/primeng/resources/themes/omega/theme.css'),
],
encapsulation: ViewEncapsulation.None,
})
export class AppComponent {
private items: MenuItem[];
constructor(private updateService: SiteBrowserState, private settingsService: SettingsService) {}
ngOnInit() {
// For showcase purposes, we initialize a host by default
this.updateService.changeSite('demo.dotcms.com');
this.items = [
{
label: 'Breadcrumb',
routerLink: ['breadcrumb']
},
{
label: 'Site Datatable',
routerLink: ['site-datatable']
},
{
label: 'Site Selector',
routerLink: ['site-selector']
},
{
label: 'Site Treetable',
routerLink: ['site-treetable']
},
{
label: 'Treeable Detail',
routerLink: ['treable-detail']
},
];
}
} | import {Component, ViewEncapsulation} from '@angular/core';
import {MenuItem} from 'primeng/primeng';
import {SiteBrowserState} from "../../core/util/site-browser.state";
import {SettingsService} from "../services/settings.services";
var prismjs = require('../assets/js/prism');
@Component({
selector: 'my-app',
template: require('./app.component.html'),
styles: [
require('./app.component.css'),
require('../assets/css/prism.css'),
require('../../node_modules/primeng/resources/primeng.min.css'),
require('../../node_modules/primeng/resources/themes/omega/theme.css'),
],
encapsulation: ViewEncapsulation.None,
})
export class AppComponent {
private items: MenuItem[];
constructor(private updateService: SiteBrowserState, private settingsService: SettingsService) {}
ngOnInit() {
// For showcase purposes, we initialize a host by default
this.updateService.changeSite('demo.dotcms.com');
this.items = [
{
label: 'Breadcrumb',
routerLink: ['breadcrumb']
},
{
label: 'Site Datatable',
routerLink: ['site-datatable']
},
{
label: 'Site Selector',
routerLink: ['site-selector']
},
{
label: 'Site Treetable',
routerLink: ['site-treetable']
},
{
label: 'Treeable Detail',
routerLink: ['treable-detail']
},
{
label: 'Services Documentation',
url: './docs'
},
];
}
} | Add services doc link, public deploy npm script | Add services doc link, public deploy npm script
| TypeScript | agpl-3.0 | dotCMS/dotJS,dotCMS/dotJS,dotCMS/dotJS | ---
+++
@@ -46,6 +46,10 @@
label: 'Treeable Detail',
routerLink: ['treable-detail']
},
+ {
+ label: 'Services Documentation',
+ url: './docs'
+ },
];
}
} |
3a8f23c0dc197494eca12d7a3b5cf706e73ea8ff | client/app/accounts/components/login/login.component.ts | client/app/accounts/components/login/login.component.ts | import { Component } from '@angular/core';
import { Account } from '../../models';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent {
public account = new Account();
}
| import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Account } from '../../models';
import { AccountService } from '../../services';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent {
public account = new Account();
public errorMessage: string;
constructor(private service: AccountService, private router: Router) {
}
login() {
this.service
.createToken(this.account.email, this.account.password)
.then(token => {
localStorage.setItem('jwt', token);
this.router.navigate(['/']);
})
.catch(error => this.errorMessage = getErrorMessage(error.status))
;
function getErrorMessage(status) {
switch (status) {
case 403:
return 'This email or password is incorrect.';
default:
return `We're sorry, but an unexpected error occurred.`;
}
}
}
}
| Add login method and store jwt | Add login method and store jwt
| TypeScript | mit | fvilers/angular2-training,fvilers/angular2-training,fvilers/angular2-training | ---
+++
@@ -1,6 +1,8 @@
import { Component } from '@angular/core';
+import { Router } from '@angular/router';
import { Account } from '../../models';
+import { AccountService } from '../../services';
@Component({
selector: 'app-login',
@@ -9,4 +11,28 @@
})
export class LoginComponent {
public account = new Account();
+ public errorMessage: string;
+
+ constructor(private service: AccountService, private router: Router) {
+ }
+
+ login() {
+ this.service
+ .createToken(this.account.email, this.account.password)
+ .then(token => {
+ localStorage.setItem('jwt', token);
+ this.router.navigate(['/']);
+ })
+ .catch(error => this.errorMessage = getErrorMessage(error.status))
+ ;
+
+ function getErrorMessage(status) {
+ switch (status) {
+ case 403:
+ return 'This email or password is incorrect.';
+ default:
+ return `We're sorry, but an unexpected error occurred.`;
+ }
+ }
+ }
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.