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
22651f5d3a8c823215e611c8cc6c3bbc68476ce8
src/Input/NumericInput.tsx
src/Input/NumericInput.tsx
import * as React from "react"; import {FormGroupContext, FormGroupContextTypes} from "../FormGroup/FormGroupContext"; import {InputContext, InputContextTypes} from "./InputContext"; import {BaseInput} from "./BaseInput"; export class NumericInput extends BaseInput<HTMLInputElement> { public render() { const childProps = { ...this.childProps, ...{ onInput: this.handleInputChange, onChange: () => undefined, type: "number" } }; return <input {...childProps} />; } protected handleInputChange = async (event: any) => { this.props.onChange && this.props.onChange(event); if (!event.defaultPrevented) { const cleanValue = parseInt(event.currentTarget.value, 10) || ""; event.currentTarget.value = ""; event.currentTarget.value = cleanValue; await this.context.onChange(cleanValue); } }; }
import * as React from "react"; import {FormGroupContext, FormGroupContextTypes} from "../FormGroup/FormGroupContext"; import {InputContext, InputContextTypes} from "./InputContext"; import {BaseInput} from "./BaseInput"; export class NumericInput extends BaseInput<HTMLInputElement> { protected cleanValue: number | string = ""; public render() { const childProps = { ...this.childProps, ...{ onInput: this.handleInputChange, onChange: () => undefined, type: "number" } }; return <input {...childProps} />; } protected handleInputChange = async (event: any) => { this.props.onChange && this.props.onChange(event); if (!event.defaultPrevented) { const parsedValue = parseInt(event.currentTarget.value, 10); this.cleanValue = event.currentTarget.value ? parsedValue : (this.cleanValue.toString().length > 1 ? this.cleanValue : ""); event.currentTarget.value = ""; event.currentTarget.value = this.cleanValue; await this.context.onChange(this.cleanValue); } }; }
Fix cleaned value on non digit input
Fix cleaned value on non digit input
TypeScript
mit
Horat1us/react-context-form,Horat1us/react-context-form
--- +++ @@ -4,6 +4,8 @@ import {BaseInput} from "./BaseInput"; export class NumericInput extends BaseInput<HTMLInputElement> { + + protected cleanValue: number | string = ""; public render() { const childProps = { @@ -22,11 +24,16 @@ this.props.onChange && this.props.onChange(event); if (!event.defaultPrevented) { - const cleanValue = parseInt(event.currentTarget.value, 10) || ""; + const parsedValue = parseInt(event.currentTarget.value, 10); + + this.cleanValue = event.currentTarget.value + ? parsedValue + : (this.cleanValue.toString().length > 1 ? this.cleanValue : ""); + event.currentTarget.value = ""; - event.currentTarget.value = cleanValue; + event.currentTarget.value = this.cleanValue; - await this.context.onChange(cleanValue); + await this.context.onChange(this.cleanValue); } }; }
1a80c21b3532daec1ec82cf260f4e388afd262ea
src/graphql/GraphQLUser.ts
src/graphql/GraphQLUser.ts
import { GraphQLObjectType, GraphQLInputObjectType, GraphQLEnumType, GraphQLString, } from 'graphql' import { MemberType } from './../models' const MutableUserFields = { firstName: { type: GraphQLString }, lastName: { type: GraphQLString }, phone: { type: GraphQLString }, picture: { type: GraphQLString }, allergies: { type: GraphQLString }, master: { type: GraphQLString }, } export const GraphQLUser = new GraphQLObjectType({ name : 'User', fields : { email: { type: GraphQLString }, ...MutableUserFields, }, }) // This type represents the fields that a user can change about themselves export const GraphQLUserInput = new GraphQLInputObjectType({ name : 'UserInput', fields : MutableUserFields, }) export const GraphQLMemberType = new GraphQLEnumType({ name : 'MemberType', values: { 'studs_member': { value: MemberType.StudsMember }, 'company_member': { value: MemberType.CompanyMember }, }, })
import { GraphQLObjectType, GraphQLInputObjectType, GraphQLEnumType, GraphQLString, } from 'graphql' import { MemberType } from './../models' const MutableUserFields = { firstName: { type: GraphQLString }, lastName: { type: GraphQLString }, phone: { type: GraphQLString }, picture: { type: GraphQLString }, allergies: { type: GraphQLString }, master: { type: GraphQLString }, } export const GraphQLMemberType = new GraphQLEnumType({ name : 'MemberType', values: { 'studs_member': { value: MemberType.StudsMember }, 'company_member': { value: MemberType.CompanyMember }, }, }) export const GraphQLUser = new GraphQLObjectType({ name : 'User', fields : { email: { type: GraphQLString }, memberType: { type: GraphQLMemberType }, ...MutableUserFields, }, }) // This type represents the fields that a user can change about themselves export const GraphQLUserInput = new GraphQLInputObjectType({ name : 'UserInput', fields : MutableUserFields, })
Add member_type to graphql user
Add member_type to graphql user
TypeScript
mit
studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord
--- +++ @@ -14,10 +14,20 @@ allergies: { type: GraphQLString }, master: { type: GraphQLString }, } + +export const GraphQLMemberType = new GraphQLEnumType({ + name : 'MemberType', + values: { + 'studs_member': { value: MemberType.StudsMember }, + 'company_member': { value: MemberType.CompanyMember }, + }, +}) + export const GraphQLUser = new GraphQLObjectType({ name : 'User', fields : { email: { type: GraphQLString }, + memberType: { type: GraphQLMemberType }, ...MutableUserFields, }, }) @@ -27,11 +37,3 @@ name : 'UserInput', fields : MutableUserFields, }) - -export const GraphQLMemberType = new GraphQLEnumType({ - name : 'MemberType', - values: { - 'studs_member': { value: MemberType.StudsMember }, - 'company_member': { value: MemberType.CompanyMember }, - }, -})
caa6d0f063d82688144e3f50db0682ec0524aaca
src/utils/function-name.ts
src/utils/function-name.ts
/// Extract the name of a function (the `name' property does not appear to be set /// in some cases). A variant of this appeared in older Augury code and it appears /// to cover the cases where name is not available as a property. export const functionName = (fn: Function): string => { const extract = (value: string) => value.match(/^function ([^\(]*)\(/); let name: string = (<any>fn).name; if (name == null || name.length === 0) { const match = extract(fn.toString()); if (match != null && match.length > 1) { return match[1]; } return null; } return name; };
/// Extract the name of a function (the `name' property does not appear to be set /// in some cases). A variant of this appeared in older Augury code and it appears /// to cover the cases where name is not available as a property. export const functionName = (fn: Function): string => { const extract = (value: string) => value.match(/^function ([^\(]*)\(/); let name: string = (<any>fn).name; if (name == null || name.length === 0) { const match = extract(fn.toString()); if (match != null && match.length > 1) { return match[1]; } return fn.toString(); } return name; };
Fix issue with types without names
Fix issue with types without names
TypeScript
mit
rangle/batarangle,rangle/augury,rangle/batarangle,rangle/augury,rangle/augury,rangle/batarangle,rangle/augury,rangle/batarangle
--- +++ @@ -10,7 +10,7 @@ if (match != null && match.length > 1) { return match[1]; } - return null; + return fn.toString(); } return name; };
04499b910153a72ff96e1aeaece9b4738e3a65c2
src/test/Apha/EventStore/EventClassMap.spec.ts
src/test/Apha/EventStore/EventClassMap.spec.ts
import {expect} from "chai"; import {EventClassMap} from "../../../main/Apha/EventStore/EventClassMap"; import {Event, EventType} from "../../../main/Apha/Message/Event"; import {UnknownEventException} from "../../../main/Apha/EventStore/UnknownEventException"; describe("EventClassMap", () => { describe("getTypeByClassName", () => { it("retrieves type by event class name", () => { const events = new Set<EventType>(); events.add(EventClassMapEvent); const classMap = new EventClassMap(events); const classType = classMap.getTypeByClassName("EventClassMapEvent"); expect(classType).to.equal(EventClassMapEvent); }); it("throws exception if class cannot be found", () => { const classMap = new EventClassMap(); expect(() => { classMap.getTypeByClassName("foo"); }).to.throw(UnknownEventException); }); }); }); class EventClassMapEvent extends Event {}
import {expect} from "chai"; import {EventClassMap} from "../../../main/Apha/EventStore/EventClassMap"; import {Event, EventType} from "../../../main/Apha/Message/Event"; import {UnknownEventException} from "../../../main/Apha/EventStore/UnknownEventException"; describe("EventClassMap", () => { describe("getTypeByClassName", () => { it("should retrieve type by event class name", () => { const events = new Set<EventType>(); events.add(EventClassMapEvent); const classMap = new EventClassMap(events); const classType = classMap.getTypeByClassName("EventClassMapEvent"); expect(classType).to.equal(EventClassMapEvent); }); it("should throw exception if class cannot be found", () => { const classMap = new EventClassMap(); expect(() => { classMap.getTypeByClassName("foo"); }).to.throw(UnknownEventException); }); }); describe("register", () => { it("should register an event in the map", () => { const classMap = new EventClassMap(); classMap.register(EventClassMapEvent); expect(classMap.getTypeByClassName("EventClassMapEvent")).to.equal(EventClassMapEvent); }); }); describe("unregister", () => { it("should unregister an event from the map", () => { const classMap = new EventClassMap(); classMap.register(EventClassMapEvent); classMap.unregister(EventClassMapEvent); expect(() => { classMap.getTypeByClassName("EventClassMapEvent"); }).to.throw(UnknownEventException); }); it("should be idempotent", () => { const classMap = new EventClassMap(); expect(() => { classMap.unregister(EventClassMapEvent); }).to.not.throw(); }); }); }); class EventClassMapEvent extends Event {}
Add test for register/unregister in event class map.
Add test for register/unregister in event class map.
TypeScript
mit
martyn82/aphajs
--- +++ @@ -6,7 +6,7 @@ describe("EventClassMap", () => { describe("getTypeByClassName", () => { - it("retrieves type by event class name", () => { + it("should retrieve type by event class name", () => { const events = new Set<EventType>(); events.add(EventClassMapEvent); @@ -16,7 +16,7 @@ expect(classType).to.equal(EventClassMapEvent); }); - it("throws exception if class cannot be found", () => { + it("should throw exception if class cannot be found", () => { const classMap = new EventClassMap(); expect(() => { @@ -24,6 +24,35 @@ }).to.throw(UnknownEventException); }); }); + + describe("register", () => { + it("should register an event in the map", () => { + const classMap = new EventClassMap(); + classMap.register(EventClassMapEvent); + + expect(classMap.getTypeByClassName("EventClassMapEvent")).to.equal(EventClassMapEvent); + }); + }); + + describe("unregister", () => { + it("should unregister an event from the map", () => { + const classMap = new EventClassMap(); + classMap.register(EventClassMapEvent); + classMap.unregister(EventClassMapEvent); + + expect(() => { + classMap.getTypeByClassName("EventClassMapEvent"); + }).to.throw(UnknownEventException); + }); + + it("should be idempotent", () => { + const classMap = new EventClassMap(); + + expect(() => { + classMap.unregister(EventClassMapEvent); + }).to.not.throw(); + }); + }); }); class EventClassMapEvent extends Event {}
38bf1680a242ea8d50176791354a58326db54adc
src/utils/units.ts
src/utils/units.ts
/* Copyright 2020 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Simple utils for formatting style values */ // converts a pixel value to rem. export function toRem(pixelValue: number): string { return pixelValue / 15 + "rem"; } export function toPx(pixelValue: number): string { return pixelValue + "px"; }
/* Copyright 2020 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Simple utils for formatting style values */ // converts a pixel value to rem. export function toRem(pixelValue: number): string { return pixelValue / 10 + "rem"; } export function toPx(pixelValue: number): string { return pixelValue + "px"; }
Update read receipt remainder for internal font size change
Update read receipt remainder for internal font size change In https://github.com/matrix-org/matrix-react-sdk/pull/4725, we changed the internal font size from 15 to 10, but the `toRem` function (currently only used for read receipts remainders curiously) was not updated. This updates the function, which restores the remainders. Fixes https://github.com/vector-im/riot-web/issues/14127
TypeScript
apache-2.0
matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk
--- +++ @@ -19,7 +19,7 @@ // converts a pixel value to rem. export function toRem(pixelValue: number): string { - return pixelValue / 15 + "rem"; + return pixelValue / 10 + "rem"; } export function toPx(pixelValue: number): string {
0d26f7ef6b16f4cbe24801b0e3927c62e6e43492
lib/cli/src/generators/PREACT/index.ts
lib/cli/src/generators/PREACT/index.ts
import { baseGenerator, Generator } from '../baseGenerator'; const generator: Generator = async (packageManager, npmOptions, options) => { baseGenerator(packageManager, npmOptions, options, 'preact'); }; export default generator;
import { baseGenerator, Generator } from '../baseGenerator'; const generator: Generator = async (packageManager, npmOptions, options) => { baseGenerator(packageManager, npmOptions, options, 'preact', { extraPackages: ['core-js'], }); }; export default generator;
Add core-js to the generator for preact
Add core-js to the generator for preact
TypeScript
mit
kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook
--- +++ @@ -1,7 +1,9 @@ import { baseGenerator, Generator } from '../baseGenerator'; const generator: Generator = async (packageManager, npmOptions, options) => { - baseGenerator(packageManager, npmOptions, options, 'preact'); + baseGenerator(packageManager, npmOptions, options, 'preact', { + extraPackages: ['core-js'], + }); }; export default generator;
442da7dd13b365f9017b59ca285e9f0230d61d05
src/config.ts
src/config.ts
import Middleware from "./types/Middleware"; import Setup from "./types/Setup"; import Results from "./types/Results"; import { EventEmitter } from "events"; import notEmpty from "./utils/notEmpty"; /** * Returns a function that executes middlewares * * Eeach middleware setup function and each optionally returned results function * * @param middlewares Middlewares to run * @returns {() => void} Function that executes middlewares */ const config = (...middlewares: Array<Middleware>) => () => { const setup: Setup = { events: new EventEmitter(), testFilePaths: [], assertionErrorsTypes: [], globals: {}, tests: [], args: {} }; const results: Results = []; middlewares .map(middlewareSetup => middlewareSetup(setup)) .filter(notEmpty) .forEach(middlewareResults => middlewareResults(results)); }; export default config;
import Middleware from "./types/Middleware"; import Setup from "./types/Setup"; import Results from "./types/Results"; import { EventEmitter } from "events"; import notEmpty from "./utils/notEmpty"; /** * Returns a function that executes middlewares * * Eeach middleware setup function and each optionally returned results function * * @param middlewares Middlewares to run * @returns {() => void} Function that executes middlewares */ const config = (...middlewares: Array<Middleware>) => () => { const setup: Setup = { events: new EventEmitter(), testFilePaths: [], assertionErrorsTypes: [], globals: {}, tests: [], args: {} }; const results: Results = []; const resultExecutors = middlewares .map(middlewareSetup => middlewareSetup(setup)) .filter(notEmpty); setup.events.emit("setup", setup); resultExecutors.forEach(middlewareResults => middlewareResults(results)); }; export default config;
Fix setup event not being emitted
Fix setup event not being emitted
TypeScript
mit
testingrequired/tf,testingrequired/tf
--- +++ @@ -23,10 +23,13 @@ }; const results: Results = []; - middlewares + const resultExecutors = middlewares .map(middlewareSetup => middlewareSetup(setup)) - .filter(notEmpty) - .forEach(middlewareResults => middlewareResults(results)); + .filter(notEmpty); + + setup.events.emit("setup", setup); + + resultExecutors.forEach(middlewareResults => middlewareResults(results)); }; export default config;
4bfec9c80f2d6b7f4546df0d68b756e555a606c9
extensions/typescript-language-features/src/utils/languageDescription.ts
extensions/typescript-language-features/src/utils/languageDescription.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as languageModeIds from './languageModeIds'; export const enum DiagnosticLanguage { JavaScript, TypeScript } export const allDiagnosticLangauges = [DiagnosticLanguage.JavaScript, DiagnosticLanguage.TypeScript]; export interface LanguageDescription { readonly id: string; readonly diagnosticOwner: string; readonly diagnosticSource: string; readonly diagnosticLanguage: DiagnosticLanguage; readonly modeIds: string[]; readonly configFilePattern?: RegExp; readonly isExternal?: boolean; } export const standardLanguageDescriptions: LanguageDescription[] = [ { id: 'typescript', diagnosticOwner: 'typescript', diagnosticSource: 'ts', diagnosticLanguage: DiagnosticLanguage.TypeScript, modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact], configFilePattern: /tsconfig(\..*)?\.json/gi }, { id: 'javascript', diagnosticOwner: 'typescript', diagnosticSource: 'ts', diagnosticLanguage: DiagnosticLanguage.JavaScript, modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact], configFilePattern: /jsconfig(\..*)?\.json/gi } ];
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as languageModeIds from './languageModeIds'; export const enum DiagnosticLanguage { JavaScript, TypeScript } export const allDiagnosticLangauges = [DiagnosticLanguage.JavaScript, DiagnosticLanguage.TypeScript]; export interface LanguageDescription { readonly id: string; readonly diagnosticOwner: string; readonly diagnosticSource: string; readonly diagnosticLanguage: DiagnosticLanguage; readonly modeIds: string[]; readonly configFilePattern?: RegExp; readonly isExternal?: boolean; } export const standardLanguageDescriptions: LanguageDescription[] = [ { id: 'typescript', diagnosticOwner: 'typescript', diagnosticSource: 'ts', diagnosticLanguage: DiagnosticLanguage.TypeScript, modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact], configFilePattern: /^tsconfig(\..*)?\.json$/gi }, { id: 'javascript', diagnosticOwner: 'typescript', diagnosticSource: 'ts', diagnosticLanguage: DiagnosticLanguage.JavaScript, modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact], configFilePattern: /^jsconfig(\..*)?\.json$/gi } ];
Make sure we match whole file name for config file
Make sure we match whole file name for config file
TypeScript
mit
eamodio/vscode,eamodio/vscode,mjbvz/vscode,joaomoreno/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,hoovercj/vscode,eamodio/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,Microsoft/vscode,microsoft/vscode,the-ress/vscode,the-ress/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,eamodio/vscode,hoovercj/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,the-ress/vscode,microsoft/vscode,the-ress/vscode,Microsoft/vscode,hoovercj/vscode,microsoft/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,mjbvz/vscode,mjbvz/vscode,Microsoft/vscode,hoovercj/vscode,hoovercj/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,mjbvz/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,hoovercj/vscode,mjbvz/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,hoovercj/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,mjbvz/vscode,the-ress/vscode,Microsoft/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,Microsoft/vscode,the-ress/vscode,Microsoft/vscode,joaomoreno/vscode,joaomoreno/vscode,eamodio/vscode,hoovercj/vscode,eamodio/vscode,mjbvz/vscode,joaomoreno/vscode,mjbvz/vscode,mjbvz/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,the-ress/vscode,mjbvz/vscode,the-ress/vscode,joaomoreno/vscode,mjbvz/vscode,joaomoreno/vscode,hoovercj/vscode,Microsoft/vscode,eamodio/vscode,the-ress/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,hoovercj/vscode,joaomoreno/vscode,Microsoft/vscode,the-ress/vscode,joaomoreno/vscode,joaomoreno/vscode,eamodio/vscode,mjbvz/vscode,microsoft/vscode,joaomoreno/vscode,mjbvz/vscode,hoovercj/vscode,eamodio/vscode,hoovercj/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,Microsoft/vscode,hoovercj/vscode,eamodio/vscode,eamodio/vscode,the-ress/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,joaomoreno/vscode,the-ress/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,joaomoreno/vscode,microsoft/vscode
--- +++ @@ -28,13 +28,13 @@ diagnosticSource: 'ts', diagnosticLanguage: DiagnosticLanguage.TypeScript, modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact], - configFilePattern: /tsconfig(\..*)?\.json/gi + configFilePattern: /^tsconfig(\..*)?\.json$/gi }, { id: 'javascript', diagnosticOwner: 'typescript', diagnosticSource: 'ts', diagnosticLanguage: DiagnosticLanguage.JavaScript, modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact], - configFilePattern: /jsconfig(\..*)?\.json/gi + configFilePattern: /^jsconfig(\..*)?\.json$/gi } ];
66ec22eedeac820177f49e897bf6ddd417eebd0a
src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular-ui/src/lib/features-module/list-browser/list-browser.module.ts
src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular-ui/src/lib/features-module/list-browser/list-browser.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; // MODULES import { SharedModule } from '../../shared-module/shared-module.module'; // COMPONENTS import { ListBrowserComponent } from './list-browser.component'; import { BrowserToolbarModule } from '../browser-toolbar/browser-toolbar.module'; @NgModule({ declarations: [ListBrowserComponent], imports: [CommonModule, SharedModule, BrowserToolbarModule], exports: [ListBrowserComponent], }) export class ListBrowserModule {}
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; // MODULES import { SharedModule } from '../../shared-module/shared-module.module'; // COMPONENTS import { ListBrowserComponent } from './list-browser.component'; import { BrowserToolbarModule } from '../browser-toolbar/browser-toolbar.module'; import { MAT_TOOLTIP_DEFAULT_OPTIONS } from '@angular/material/tooltip'; @NgModule({ declarations: [ListBrowserComponent], imports: [CommonModule, SharedModule, BrowserToolbarModule], exports: [ListBrowserComponent], providers: [ { provide: MAT_TOOLTIP_DEFAULT_OPTIONS, useValue: { showDelay: 250, hideDelay: 0, touchGestures: 'off' } } ] }) export class ListBrowserModule {}
Fix scrolling on list browser hover tooltips
Fix scrolling on list browser hover tooltips
TypeScript
mit
Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript
--- +++ @@ -7,10 +7,14 @@ // COMPONENTS import { ListBrowserComponent } from './list-browser.component'; import { BrowserToolbarModule } from '../browser-toolbar/browser-toolbar.module'; +import { MAT_TOOLTIP_DEFAULT_OPTIONS } from '@angular/material/tooltip'; @NgModule({ declarations: [ListBrowserComponent], imports: [CommonModule, SharedModule, BrowserToolbarModule], exports: [ListBrowserComponent], + providers: [ + { provide: MAT_TOOLTIP_DEFAULT_OPTIONS, useValue: { showDelay: 250, hideDelay: 0, touchGestures: 'off' } } + ] }) export class ListBrowserModule {}
8b44df04fc7b7245e337780c7d48fbb71e78e69a
lib/QiitaWidget.ts
lib/QiitaWidget.ts
import {QiitaItems} from "./QiitaItems"; import {QiitaPresenter} from "./QiitaPresenter"; import {QiitaWidgetParam} from "./interface"; export default class QiitaWidget { private conf: QiitaWidgetParam; private presenter: QiitaPresenter; private items: QiitaItems; static defaultConf: QiitaWidgetParam = { useTransition: true }; constructor(container: HTMLElement, conf: QiitaWidgetParam) { this.conf = Object.assign({}, QiitaWidget.defaultConf, conf); this.items = new QiitaItems(this.conf); this.presenter = new QiitaPresenter(container, this.items, this.conf); } async init():Promise<void> { await this.items.fetch(); this.presenter.render(); } }
import {QiitaItems} from "./QiitaItems"; import {QiitaPresenter} from "./QiitaPresenter"; import {QiitaWidgetParam} from "./interface"; export default class QiitaWidget { private conf: QiitaWidgetParam; private presenter: QiitaPresenter; private items: QiitaItems; static defaultConf: QiitaWidgetParam = { }; constructor(container: HTMLElement, conf: QiitaWidgetParam) { this.conf = Object.assign({}, QiitaWidget.defaultConf, conf); this.items = new QiitaItems(this.conf); this.presenter = new QiitaPresenter(container, this.items, this.conf); } async init():Promise<void> { await this.items.fetch(); this.presenter.render(); } }
Remove a duplicated default setting
Remove a duplicated default setting
TypeScript
mit
hokkey/qiita-widget-js,hokkey/qiita-widget-js,hokkey/qiita-widget-js
--- +++ @@ -9,7 +9,6 @@ private items: QiitaItems; static defaultConf: QiitaWidgetParam = { - useTransition: true };
072e1744332d7c60d529a281a101b82c1fc416d2
src/lib/jest_process.ts
src/lib/jest_process.ts
'use strict'; import {ChildProcess, spawn} from 'child_process'; import {ProjectWorkspace} from './project_workspace'; /** * Spawns and returns a Jest process with specific args * * @param {string[]} args * @returns {ChildProcess} */ export function jestChildProcessWithArgs(workspace: ProjectWorkspace, args: string[]) : ChildProcess { // A command could look like `npm run test`, which we cannot use as a command // as they can only be the first command, so take out the command, and add // any other bits into the args const runtimeExecutable = workspace.pathToJest; const [command, ...initialArgs] = runtimeExecutable.split(" "); const runtimeArgs = [...initialArgs, ...args]; // If a path to configuration file was defined, push it to runtimeArgs const configPath = workspace.pathToConfig; if (configPath !== "") { args.push("--config"); args.push(configPath); } // To use our own commands in create-react, we need to tell the command that we're in a CI // environment, or it will always append --watch const env = process.env; env["CI"] = true; return spawn(command, runtimeArgs, {cwd: workspace.rootPath, env: env}); }
'use strict'; import {ChildProcess, spawn} from 'child_process'; import {ProjectWorkspace} from './project_workspace'; /** * Spawns and returns a Jest process with specific args * * @param {string[]} args * @returns {ChildProcess} */ export function jestChildProcessWithArgs(workspace: ProjectWorkspace, args: string[]) : ChildProcess { // A command could look like `npm run test`, which we cannot use as a command // as they can only be the first command, so take out the command, and add // any other bits into the args const runtimeExecutable = workspace.pathToJest; const [command, ...initialArgs] = runtimeExecutable.split(" "); const runtimeArgs = [...initialArgs, ...args]; // If a path to configuration file was defined, push it to runtimeArgs const configPath = workspace.pathToConfig; if (configPath !== "") { runtimeArgs.push("--config"); runtimeArgs.push(configPath); } // To use our own commands in create-react, we need to tell the command that we're in a CI // environment, or it will always append --watch const env = process.env; env["CI"] = true; return spawn(command, runtimeArgs, {cwd: workspace.rootPath, env: env}); }
Fix the args array where config should be added
Fix the args array where config should be added
TypeScript
mit
orta/vscode-jest,bookman25/vscode-jest,orta/vscode-jest,bookman25/vscode-jest,bookman25/vscode-jest,orta/vscode-jest
--- +++ @@ -21,8 +21,8 @@ // If a path to configuration file was defined, push it to runtimeArgs const configPath = workspace.pathToConfig; if (configPath !== "") { - args.push("--config"); - args.push(configPath); + runtimeArgs.push("--config"); + runtimeArgs.push(configPath); } // To use our own commands in create-react, we need to tell the command that we're in a CI
f50862e3b043b30b323454529cb6ca9b495d7aa5
capstone-project/src/main/angular-webapp/src/app/app.module.ts
capstone-project/src/main/angular-webapp/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { GoogleMapsModule } from '@angular/google-maps'; import { MatCardModule } from '@angular/material/card' import { AppRoutingModule } from './app-routing.module'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { SocialLoginModule, SocialAuthServiceConfig } from 'angularx-social-login'; import { GoogleLoginProvider } from 'angularx-social-login'; import { InfoWindowComponent } from './info-window/info-window.component'; import { AppComponent } from './app.component'; import { MapComponent } from './map/map.component'; import { AuthenticationComponent } from './authentication/authentication.component'; @NgModule({ declarations: [ AppComponent, MapComponent, AuthenticationComponent, InfoWindowComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, GoogleMapsModule, BrowserAnimationsModule, SocialLoginModule, MatCardModule ], providers: [{ provide: 'SocialAuthServiceConfig', useValue: { autoLogin: false, providers: [ { id: GoogleLoginProvider.PROVIDER_ID, provider: new GoogleLoginProvider( 'client-id' ), } ], } as SocialAuthServiceConfig, } ], bootstrap: [AppComponent] }) export class AppModule { }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { GoogleMapsModule } from '@angular/google-maps'; import { MatCardModule } from '@angular/material/card' import { AppRoutingModule } from './app-routing.module'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { SocialLoginModule, SocialAuthServiceConfig } from 'angularx-social-login'; import { GoogleLoginProvider } from 'angularx-social-login'; import { InfoWindowComponent } from './info-window/info-window.component'; import { AppComponent } from './app.component'; import { MapComponent } from './map/map.component'; import { AuthenticationComponent } from './authentication/authentication.component'; import { environment } from 'src/environments/environment'; @NgModule({ declarations: [ AppComponent, MapComponent, AuthenticationComponent, InfoWindowComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, GoogleMapsModule, BrowserAnimationsModule, SocialLoginModule, MatCardModule ], providers: [{ provide: 'SocialAuthServiceConfig', useValue: { autoLogin: false, providers: [ { id: GoogleLoginProvider.PROVIDER_ID, provider: new GoogleLoginProvider( environment["CLIENT_ID"] ), } ], } as SocialAuthServiceConfig, } ], bootstrap: [AppComponent] }) export class AppModule { }
Add client id as environment veriable
Add client id as environment veriable
TypeScript
apache-2.0
googleinterns/step263-2020,googleinterns/step263-2020,googleinterns/step263-2020,googleinterns/step263-2020
--- +++ @@ -11,6 +11,7 @@ import { AppComponent } from './app.component'; import { MapComponent } from './map/map.component'; import { AuthenticationComponent } from './authentication/authentication.component'; +import { environment } from 'src/environments/environment'; @NgModule({ @@ -37,7 +38,7 @@ { id: GoogleLoginProvider.PROVIDER_ID, provider: new GoogleLoginProvider( - 'client-id' + environment["CLIENT_ID"] ), } ],
bfdb047521856ea93a79e7b392f84132255c90a9
transpilation/deploy.ts
transpilation/deploy.ts
import fs = require("fs"); import { exec } from "shelljs"; function cmd(command: string): string { const result: any = exec(command); return result.stdout.trim().replace("\r\n", "\n"); } const currentBranch = cmd("git rev-parse --abbrev-ref HEAD"); if (currentBranch !== "master") { throw new Error("This script should only be run on master. You're on " + currentBranch); } const changes = cmd("git status --porcelain"); if (changes) { throw new Error("This script shouldn't be run when you've got working copy changes."); } cmd("git branch -f gh-pages"); cmd("git checkout gh-pages"); const toDeploy = [ "index.html", "dist/slime.js", ".gitignore", "transpile/deploy.ts", "dist/transpile/deploy.js" ]; const gitignore = ["*"].concat(toDeploy.map(f => "!" + f)).join("\r\n"); fs.writeFileSync(".gitignore", gitignore, "utf8"); cmd("git ls-files").split("\n").filter(f => toDeploy.indexOf(f) > -1).forEach(f => cmd(`git rm -rf '${f}' --dry-run`)); // cmd("git rm -rf * --dry-run"); toDeploy.forEach(f => cmd(`git add ${f}`)); console.log(cmd("git status"));
import fs = require("fs"); import { exec } from "shelljs"; function cmd(command: string): string { const result: any = exec(command); return result.stdout.trim().replace("\r\n", "\n"); } const currentBranch = cmd("git rev-parse --abbrev-ref HEAD"); if (currentBranch !== "master") { throw new Error("This script should only be run on master. You're on " + currentBranch); } const changes = cmd("git status --porcelain"); if (changes) { throw new Error("This script shouldn't be run when you've got working copy changes."); } cmd("git branch -f gh-pages"); cmd("git checkout gh-pages"); const toDeploy = [ "index.html", "dist/slime.js", ".gitignore", "transpile/deploy.ts", "dist/transpile/deploy.js" ]; const gitignore = ["*"].concat(toDeploy.map(f => "!" + f)).join("\r\n"); fs.writeFileSync(".gitignore", gitignore, "utf8"); const trackedFiles = cmd("git ls-files").split("\n"); const toRemove = trackedFiles.filter(f => toDeploy.indexOf(f) > -1) toRemove.forEach(f => cmd(`git rm -rf ${f} --dry-run`)); // cmd("git rm -rf * --dry-run"); toDeploy.forEach(f => cmd(`git add ${f}`)); console.log(cmd("git status"));
Save tracked files in a variable.
Save tracked files in a variable.
TypeScript
mit
mmkal/slimejs,mmkal/slimejs,mmkal/slimejs,mmkal/slimejs
--- +++ @@ -24,7 +24,10 @@ fs.writeFileSync(".gitignore", gitignore, "utf8"); -cmd("git ls-files").split("\n").filter(f => toDeploy.indexOf(f) > -1).forEach(f => cmd(`git rm -rf '${f}' --dry-run`)); +const trackedFiles = cmd("git ls-files").split("\n"); +const toRemove = trackedFiles.filter(f => toDeploy.indexOf(f) > -1) + +toRemove.forEach(f => cmd(`git rm -rf ${f} --dry-run`)); // cmd("git rm -rf * --dry-run");
bae1a1d3a3a2053753f47d5faea1bda78dbd10ab
source/services/number/number.service.ts
source/services/number/number.service.ts
import { Provider, OpaqueToken } from 'angular2/core'; enum Sign { positive = 1, negative = -1, } export interface INumberUtility { preciseRound(num: number, decimals: number): number; integerDivide(dividend: number, divisor: number): number; roundToStep(num: number, step: number): number; } export class NumberUtility implements INumberUtility { preciseRound(num: number, decimals: number): number { var sign: Sign = num >= 0 ? Sign.positive : Sign.negative; return (Math.round((num * Math.pow(10, decimals)) + (<number>sign * 0.001)) / Math.pow(10, decimals)); } integerDivide(dividend: number, divisor: number): number { return Math.floor(dividend / divisor); } roundToStep(num: number, step: number): number { if (!step) { return num; } var remainder: number = num % step; if (remainder >= step / 2) { return num + (step - remainder); } else { return num - remainder; } } } export const numberUtilityToken: OpaqueToken = new OpaqueToken('number utility service'); export const NUMBER_UTILITY_PROVIDER: Provider = new Provider(numberServiceToken, { useClass: NumberUtility });
import { Provider, OpaqueToken } from 'angular2/core'; enum Sign { positive = 1, negative = -1, } export interface INumberUtility { preciseRound(num: number, decimals: number): number; integerDivide(dividend: number, divisor: number): number; roundToStep(num: number, step: number): number; } export class NumberUtility implements INumberUtility { preciseRound(num: number, decimals: number): number { var sign: Sign = num >= 0 ? Sign.positive : Sign.negative; return (Math.round((num * Math.pow(10, decimals)) + (<number>sign * 0.001)) / Math.pow(10, decimals)); } integerDivide(dividend: number, divisor: number): number { return Math.floor(dividend / divisor); } roundToStep(num: number, step: number): number { if (!step) { return num; } var remainder: number = num % step; if (remainder >= step / 2) { return num + (step - remainder); } else { return num - remainder; } } } export const numberUtility: INumberUtility = new NumberUtility(); export const numberUtilityToken: OpaqueToken = new OpaqueToken('number utility service'); export const NUMBER_UTILITY_PROVIDER: Provider = new Provider(numberUtilityToken, { useClass: NumberUtility });
Fix small typo and export a static version of the number utility.
Fix small typo and export a static version of the number utility.
TypeScript
mit
RenovoSolutions/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities
--- +++ @@ -36,8 +36,10 @@ } } +export const numberUtility: INumberUtility = new NumberUtility(); + export const numberUtilityToken: OpaqueToken = new OpaqueToken('number utility service'); -export const NUMBER_UTILITY_PROVIDER: Provider = new Provider(numberServiceToken, { +export const NUMBER_UTILITY_PROVIDER: Provider = new Provider(numberUtilityToken, { useClass: NumberUtility });
7b1580e928d5e1425de52f6f4511adfc0c00582d
src/chord-regex.ts
src/chord-regex.ts
const chordNames = `[A-G][#|b]?` const qualities = `min|m|dim|aug|sus[249]?` const degrees = `(#|b|M|maj)?(2|3|4|5|6|7|9|11|13)` const extensions = `[\\(]?[add|sub]?${degrees}[\\)]?` const slashChordPattern = `\\/${chordNames}` const chordRegexString = `(${chordNames})(${qualities})?(${extensions})*(${slashChordPattern})?` export const chordRegex = RegExp(`\\[(${chordRegexString})\\]`)
const chordNames = `[A-G][#|b]?` const qualities = `min|m|dim|aug|sus[249]?` const degrees = `(#|b|M|maj)?(2|3|4|5|6|7|9|11|13)` const extensions = `[\\(]?(add|sub)?${degrees}[\\)]?` const slashChordPattern = `\\/${chordNames}` const chordRegexString = `(${chordNames})(${qualities})?(${extensions})*(${slashChordPattern})?` export const chordRegex = RegExp(`\\[(${chordRegexString})\\]`)
Fix regex bug with add/sub extensions
Fix regex bug with add/sub extensions
TypeScript
mit
gldraphael/chordsheet
--- +++ @@ -2,7 +2,7 @@ const qualities = `min|m|dim|aug|sus[249]?` const degrees = `(#|b|M|maj)?(2|3|4|5|6|7|9|11|13)` -const extensions = `[\\(]?[add|sub]?${degrees}[\\)]?` +const extensions = `[\\(]?(add|sub)?${degrees}[\\)]?` const slashChordPattern = `\\/${chordNames}` const chordRegexString = `(${chordNames})(${qualities})?(${extensions})*(${slashChordPattern})?`
6a5e3ada5f3e8d21624d8600a2e643d4cc575c91
src/app/dashboard/dashboard.component.spec.ts
src/app/dashboard/dashboard.component.spec.ts
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { DashboardComponent } from './dashboard.component'; describe('DashboardComponent', () => { let component: DashboardComponent; let fixture: ComponentFixture<DashboardComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ DashboardComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DashboardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { DashboardComponent } from './dashboard.component'; import { CarComponent } from "../car/car.component"; describe('DashboardComponent', () => { let component: DashboardComponent; let fixture: ComponentFixture<DashboardComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ DashboardComponent, CarComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DashboardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
Fix unit test by adding the CarComponent to the declaration.
Fix unit test by adding the CarComponent to the declaration.
TypeScript
apache-2.0
emielkwakkel/angular-course,emielkwakkel/angular-2-course,emielkwakkel/angular-2-course,emielkwakkel/angular-course,emielkwakkel/angular-course,emielkwakkel/angular-2-course
--- +++ @@ -4,6 +4,7 @@ import { DebugElement } from '@angular/core'; import { DashboardComponent } from './dashboard.component'; +import { CarComponent } from "../car/car.component"; describe('DashboardComponent', () => { let component: DashboardComponent; @@ -11,7 +12,7 @@ beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ DashboardComponent ] + declarations: [ DashboardComponent, CarComponent ] }) .compileComponents(); }));
e0704ef05932c185feebc29199b99f776ef14e1f
src/app/cardsView/services/base-card.service.ts
src/app/cardsView/services/base-card.service.ts
/** * Created by wiekonek on 13.12.16. */ import {Http, RequestOptions, URLSearchParams} from "@angular/http"; import {Observable} from "rxjs"; import {AppAuthenticationService} from "../../app-authentication.service"; import {PaginateResponse} from "./paginate-response"; import {Card} from "../../card/card"; export abstract class BaseCardService { constructor(protected http: Http, protected pluginAuth: AppAuthenticationService) {} protected _get<T extends Card>(path: string, params?: URLSearchParams): Observable<PaginateResponse<T>> { let req = new RequestOptions({search: params == null ? new URLSearchParams : params}); req.search.appendAll(this.pluginAuth.RequestOptionsWithPluginAuthentication.search); return this.http .get(path, req) .map(res => res.json()); } protected _put<T>(path: string): Observable<T> { return this.http.put(path, "") .map(res => res.json()); } protected _getPage<T extends Card>(path: string, page: number, size: number): Observable<PaginateResponse<T>> { return this._get(path, this.paginationParams(page, size)); } private paginationParams(page: number, size: number): URLSearchParams { let params = new URLSearchParams(); params.append('page', page.toString()); params.append('size', size.toString()); return params; } }
/** * Created by wiekonek on 13.12.16. */ import {Http, RequestOptions, URLSearchParams} from "@angular/http"; import {Observable} from "rxjs"; import {AppAuthenticationService} from "../../app-authentication.service"; import {PaginateResponse} from "./paginate-response"; import {Card} from "../../card/card"; export abstract class BaseCardService { constructor(protected http: Http, protected pluginAuth: AppAuthenticationService) {} protected _get<T extends Card>(path: string, params?: URLSearchParams): Observable<PaginateResponse<T>> { let req = new RequestOptions({search: params == null ? new URLSearchParams : params}); req.search.appendAll(this.pluginAuth.RequestOptionsWithPluginAuthentication.search); return this.http .get(path, req) .map(res => res.json()); } protected _put<T>(path: string): Observable<T> { return this.http.put(path, "", this.pluginAuth.RequestOptionsWithPluginAuthentication) .map(res => res.json()); } protected _getPage<T extends Card>(path: string, page: number, size: number): Observable<PaginateResponse<T>> { return this._get(path, this.paginationParams(page, size)); } private paginationParams(page: number, size: number): URLSearchParams { let params = new URLSearchParams(); params.append('page', page.toString()); params.append('size', size.toString()); return params; } }
Fix missing jwt token in put request
Fix missing jwt token in put request
TypeScript
mit
JiraGoggles/jiragoggles-frontend,JiraGoggles/jiragoggles-frontend,JiraGoggles/jiragoggles-frontend,JiraGoggles/jiragoggles-frontend
--- +++ @@ -21,7 +21,7 @@ } protected _put<T>(path: string): Observable<T> { - return this.http.put(path, "") + return this.http.put(path, "", this.pluginAuth.RequestOptionsWithPluginAuthentication) .map(res => res.json()); }
150f1ebfe33e0c8d4ccd9c6f4ab80ce872cb4464
src/app/core/bot-storage/bot-storage.service.ts
src/app/core/bot-storage/bot-storage.service.ts
import { Injectable } from '@angular/core' import { Http } from '@angular/http' import { environment } from '../../../environments/environment' @Injectable() export class BotStorageService { public currentBot: {url: string, key: string} = {url: null, key: null} constructor(private http: Http) {} reachable (): Promise<void> { return this.http.get(`http://${environment.botStorageAPI}/ping`).toPromise() .then((response) => { if (typeof response.text() !== 'string' || response.text() !== 'pong') { let msg = 'Wrong bot storage response on /ping' log.error(msg) throw new Error(msg) } }) } getDocuments (): Promise<void> { return this.http.get(`http://${environment.botStorageAPI}/docs`).toPromise() .then((response) => { log.debug('DOCS: ', response.json()) return response.json() }) } updateCurrent (key) { this.currentBot.url = this.getURL() this.currentBot.key = key } getURL () { return environment.botStorage } }
import { Injectable } from '@angular/core' import { Http } from '@angular/http' import { environment } from '../../../environments/environment' @Injectable() export class BotStorageService { public currentBot: {url: string, key: string} = {url: '', key: ''} constructor(private http: Http) {} reachable (): Promise<void> { return this.http.get(`http://${environment.botStorageAPI}/ping`).toPromise() .then((response) => { if (typeof response.text() !== 'string' || response.text() !== 'pong') { let msg = 'Wrong bot storage response on /ping' log.error(msg) throw new Error(msg) } }) } getDocuments (): Promise<void> { return this.http.get(`http://${environment.botStorageAPI}/docs`).toPromise() .then((response) => { log.debug('DOCS: ', response.json()) return response.json() }) } updateCurrent (key) { this.currentBot.url = this.getURL() this.currentBot.key = key } getURL () { return environment.botStorage } }
Fix default values of currentBot
fix(botStorage): Fix default values of currentBot
TypeScript
agpl-3.0
oster/mute,oster/mute,coast-team/mute,coast-team/mute,coast-team/mute,coast-team/mute,oster/mute
--- +++ @@ -6,7 +6,7 @@ @Injectable() export class BotStorageService { - public currentBot: {url: string, key: string} = {url: null, key: null} + public currentBot: {url: string, key: string} = {url: '', key: ''} constructor(private http: Http) {}
9c2bee5ee4415dba9f0f89a9b5cf396c54abfb27
src/stack/stack.ts
src/stack/stack.ts
import { StackNode } from '.'; export class Stack<T> { public top: StackNode<T>; public size: number = 0; public push(data: T): void { this.top = new StackNode(data, this.top); ++this.size; } public pop(): T { if (!this.top) { throw new Error('Empty stack'); } const data = this.top.data; this.top = this.top.next; --this.size; return data; } public peek(): T { if (!this.top) { throw new Error('Empty stack'); } return this.top.data; } public isEmpty(): boolean { return this.size === 0; } }
import { StackNode } from '.'; export class Stack<T> { public top: StackNode<T>; public size: number = 0; public push(data: T): void { this.top = new StackNode(data, this.top); ++this.size; } public pop(): T { if (this.isEmpty()) { throw new Error('Empty stack'); } const data = this.top.data; this.top = this.top.next; --this.size; return data; } public peek(): T { if (this.isEmpty()) { throw new Error('Empty stack'); } return this.top.data; } public isEmpty(): boolean { return this.size === 0; } }
Use isEmpty method for error checking
Use isEmpty method for error checking
TypeScript
mit
worsnupd/ts-data-structures
--- +++ @@ -10,7 +10,7 @@ } public pop(): T { - if (!this.top) { + if (this.isEmpty()) { throw new Error('Empty stack'); } @@ -23,7 +23,7 @@ } public peek(): T { - if (!this.top) { + if (this.isEmpty()) { throw new Error('Empty stack'); }
ff45079872fe6473b0618443f7e06250506b8aae
bot/app.ts
bot/app.ts
import * as restify from 'restify'; import * as builder from 'botbuilder'; import * as os from 'os'; const connector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); const server = restify.createServer(); server.post('/api/messages', connector.listen()); server.get('/healthz', (request, response) => { response.send(200); }) server.listen(3978, () => console.log(`${server.name} listening to ${server.url}`)); var bot = new builder.UniversalBot(connector, (session: builder.Session) => { session.send(`Kubernetes is awesome! I am ${os.hostname}. You said: ${session.message.text}`) }); var recognizer = new builder.LuisRecognizer(process.env.LUIS_URI); bot.recognizer(recognizer); bot.dialog('GetPods', function (session) { session.endDialog('You are trying to get pods'); }).triggerAction({ matches: 'GetPods' }); bot.dialog('GetDeployments', function (session) { session.endDialog('You are trying to get deployments'); }).triggerAction({ matches: 'GetDeployments' });
import * as restify from 'restify'; import * as builder from 'botbuilder'; import * as os from 'os'; const connector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); const server = restify.createServer(); server.post('/api/messages', connector.listen()); server.get('/healthz', (request, response) => { response.send(200); }) server.listen(3978, () => console.log(`${server.name} listening to ${server.url}`)); var bot = new builder.UniversalBot(connector, (session: builder.Session) => { session.send(`Kubernetes is awesome! I am ${os.hostname}. You said: ${session.message.text}`) }); var recognizer = new builder.LuisRecognizer(process.env.LUIS_URI); bot.recognizer(recognizer); bot.dialog('GetContainers', function (session) { session.say('You are trying to get containers'); session.endDialog(); }).triggerAction({ matches: 'GetContainers' }); bot.dialog('GetDeployments', function (session) { session.endDialog('You are trying to get deployments'); }).triggerAction({ matches: 'GetDeployments' });
Change ambiguous calls to Cortana
Change ambiguous calls to Cortana Signed-off-by: radu-matei <5658ddc86f190a3ca12b15ca39a24e2d214bc7d0@gmail.com>
TypeScript
mit
radu-matei/kube-bot,radu-matei/kube-bot
--- +++ @@ -22,10 +22,11 @@ var recognizer = new builder.LuisRecognizer(process.env.LUIS_URI); bot.recognizer(recognizer); -bot.dialog('GetPods', function (session) { - session.endDialog('You are trying to get pods'); +bot.dialog('GetContainers', function (session) { + session.say('You are trying to get containers'); + session.endDialog(); }).triggerAction({ - matches: 'GetPods' + matches: 'GetContainers' }); bot.dialog('GetDeployments', function (session) {
147fbcc2523f8ef5f606db2ce12eaab8bc943cb7
src/app/auth/services/auth.guard.ts
src/app/auth/services/auth.guard.ts
import { Injectable } from '@angular/core' import { CanActivate } from '@angular/router' import { Store } from '@ngrx/store' import { Observable } from 'rxjs/Observable' import { of } from 'rxjs/observable/of' import { map, take, tap } from 'rxjs/operators' import * as AuthActions from '../store/auth.actions' import * as fromAuth from '../store/auth.reducer' @Injectable() export class AuthGuard implements CanActivate { constructor(private store: Store<fromAuth.State>) {} canActivate(): Observable<boolean> { return this.store.select(fromAuth.getIsLoggedIn).pipe( map(isLoggedIn => { if (!isLoggedIn) { this.store.dispatch(new AuthActions.LoginRedirect()) return false } return true }), take(1) ) } }
import { Injectable } from '@angular/core' import { CanActivate } from '@angular/router' import { JwtHelperService } from '@auth0/angular-jwt' import { Store } from '@ngrx/store' import { Observable } from 'rxjs/Observable' import { of } from 'rxjs/observable/of' import { map, take, tap } from 'rxjs/operators' import * as AuthActions from '../store/auth.actions' import * as fromAuth from '../store/auth.reducer' @Injectable() export class AuthGuard implements CanActivate { constructor( private store: Store<fromAuth.State>, public jwtHelper: JwtHelperService ) {} canActivate(): Observable<boolean> { return this.store.select(fromAuth.getIsLoggedIn).pipe( map(isLoggedIn => { if (this.jwtHelper.isTokenExpired()) { this.store.dispatch(new AuthActions.LoginRedirect()) return false } if (!isLoggedIn) { this.store.dispatch(new AuthActions.RehydrateAuth()) } return true }), take(1) ) } }
Check token expiration and rehydrate auth store
Check token expiration and rehydrate auth store
TypeScript
apache-2.0
RADAR-CNS/RADAR-Dashboard,RADAR-CNS/RADAR-Dashboard,RADAR-CNS/RADAR-Dashboard,RADAR-CNS/RADAR-Dashboard
--- +++ @@ -1,5 +1,6 @@ import { Injectable } from '@angular/core' import { CanActivate } from '@angular/router' +import { JwtHelperService } from '@auth0/angular-jwt' import { Store } from '@ngrx/store' import { Observable } from 'rxjs/Observable' import { of } from 'rxjs/observable/of' @@ -10,14 +11,21 @@ @Injectable() export class AuthGuard implements CanActivate { - constructor(private store: Store<fromAuth.State>) {} + constructor( + private store: Store<fromAuth.State>, + public jwtHelper: JwtHelperService + ) {} canActivate(): Observable<boolean> { return this.store.select(fromAuth.getIsLoggedIn).pipe( map(isLoggedIn => { - if (!isLoggedIn) { + if (this.jwtHelper.isTokenExpired()) { this.store.dispatch(new AuthActions.LoginRedirect()) return false + } + + if (!isLoggedIn) { + this.store.dispatch(new AuthActions.RehydrateAuth()) } return true
76dff867caf497ca1463373abf5844d38b2e8406
ui/src/Project.tsx
ui/src/Project.tsx
import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router-dom'; import { search } from './search'; import DocumentTeaser from './DocumentTeaser'; import { Container } from 'react-bootstrap'; export default () => { const { id } = useParams(); const [documents, setDocuments] = useState([]); useEffect(() => { const query = { q: `project:${id}`, skipTypes: ['Project', 'Image', 'Photo', 'Drawing'] }; search(query).then(setDocuments); }, [id]); return ( <Container> { documents.map(document => <DocumentTeaser document={ document } key={ document.resource.id } />) } </Container> ); };
import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router-dom'; import { search } from './search'; import DocumentTeaser from './DocumentTeaser'; import { Container, Row, Col } from 'react-bootstrap'; import DocumentDetails from './DocumentDetails'; export default () => { const { id } = useParams(); const [documents, setDocuments] = useState([]); const [projectDocument, setProjectDocument] = useState(null); useEffect(() => { const query = { q: `project:${id}`, skipTypes: ['Project', 'Image', 'Photo', 'Drawing'] }; search(query).then(setDocuments); getProjectDocument(id).then(setProjectDocument); }, [id]); return ( <Container fluid> <Row> <Col sm={ 4 }> { renderProjectDocument(projectDocument) } </Col> <Col> { renderResultList(documents) } </Col> </Row> </Container> ); }; const renderProjectDocument = (projectDocument: any) => projectDocument ? <DocumentDetails document={ projectDocument } /> : ''; const renderResultList = (documents: any) => documents.map(document => <DocumentTeaser document={ document } key={ document.resource.id } />); const getProjectDocument = async (id: string): Promise<any> => { const response = await fetch(`/documents/${id}`); return await response.json(); };
Add project details to project component
Add project details to project component
TypeScript
apache-2.0
dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web
--- +++ @@ -2,22 +2,44 @@ import { useParams } from 'react-router-dom'; import { search } from './search'; import DocumentTeaser from './DocumentTeaser'; -import { Container } from 'react-bootstrap'; +import { Container, Row, Col } from 'react-bootstrap'; +import DocumentDetails from './DocumentDetails'; export default () => { const { id } = useParams(); const [documents, setDocuments] = useState([]); + const [projectDocument, setProjectDocument] = useState(null); useEffect(() => { const query = { q: `project:${id}`, skipTypes: ['Project', 'Image', 'Photo', 'Drawing'] }; search(query).then(setDocuments); + getProjectDocument(id).then(setProjectDocument); }, [id]); return ( - <Container> - { documents.map(document => <DocumentTeaser document={ document } key={ document.resource.id } />) } + <Container fluid> + <Row> + <Col sm={ 4 }> + { renderProjectDocument(projectDocument) } + </Col> + <Col> + { renderResultList(documents) } + </Col> + </Row> </Container> ); }; + +const renderProjectDocument = (projectDocument: any) => + projectDocument ? <DocumentDetails document={ projectDocument } /> : ''; + +const renderResultList = (documents: any) => + documents.map(document => <DocumentTeaser document={ document } key={ document.resource.id } />); + +const getProjectDocument = async (id: string): Promise<any> => { + + const response = await fetch(`/documents/${id}`); + return await response.json(); +};
491f099cfe63b26bed0d3126eeaaa4f98c1ee8d2
src/middlewares/index.ts
src/middlewares/index.ts
import { Middleware } from '../index' import { Logger } from '../utils/logger' import { argsParser } from './argsParser' import { commandCaller } from './commandCaller' import { commandFinder } from './commandFinder' import { errorsHandler } from './errorsHandler' import { helper } from './helper' import { rawArgsParser } from './rawArgsParser' import { validator } from './validator' export function useMiddlewares(middlewares: Middleware[] = []) { const logger = new Logger() const argv = process.argv return [ errorsHandler(logger), argsParser(argv), commandFinder, helper(logger), validator, rawArgsParser(argv), ...middlewares, commandCaller ] }
import { Middleware } from '../index' import { Logger } from '../utils/logger' import { argsParser } from './argsParser' import { commandCaller } from './commandCaller' import { commandFinder } from './commandFinder' import { errorsHandler } from './errorsHandler' import { helper } from './helper' import { rawArgsParser } from './rawArgsParser' import { validator } from './validator' export function useMiddlewares( middlewares: Middleware[] = [], logger = new Logger() ) { const argv = process.argv return [ errorsHandler(logger), argsParser(argv), commandFinder, helper(logger), validator, rawArgsParser(argv), ...middlewares, commandCaller ] }
Make useMiddlewares accept logger as an argument
Make useMiddlewares accept logger as an argument
TypeScript
mit
pawelgalazka/microcli,pawelgalazka/microcli
--- +++ @@ -8,8 +8,10 @@ import { rawArgsParser } from './rawArgsParser' import { validator } from './validator' -export function useMiddlewares(middlewares: Middleware[] = []) { - const logger = new Logger() +export function useMiddlewares( + middlewares: Middleware[] = [], + logger = new Logger() +) { const argv = process.argv return [ errorsHandler(logger),
fdab34aa2d3c9163d7a766242ceddd511797a76a
src/pages/login/login.ts
src/pages/login/login.ts
import { Component } from '@angular/core'; import { Validators, FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'page-login', templateUrl: 'login.html' }) export class LoginPage { loginForm: FormGroup; constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, public loadingCtrl: LoadingController) { this.loginForm = this.formBuilder.group({ url: ['', Validators.required], user: ['', Validators.required], password: ['', Validators.required], }); } login() { console.log(this.loginForm.value) } }
import { Component } from '@angular/core'; import { Validators, FormBuilder, FormGroup } from '@angular/forms'; import { NavController, NavParams } from 'ionic-angular'; import { LoadingController } from 'ionic-angular'; @Component({ selector: 'page-login', templateUrl: 'login.html' }) export class LoginPage { loginForm: FormGroup; constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, public loadingCtrl: LoadingController) { this.loginForm = this.formBuilder.group({ url: ['', Validators.required], user: ['', Validators.required], password: ['', Validators.required], }); } login() { let loader = this.loadingCtrl.create({ content: "Connecting to IMS Server", duration: 3000 }); loader.present(); } }
Add loading icon, To lateron wait until user is logged in and maybe content of next page has been loaded.
Add loading icon, To lateron wait until user is logged in and maybe content of next page has been loaded.
TypeScript
mit
IMSmobile/app,IMSmobile/app,IMSmobile/app,IMSmobile/app
--- +++ @@ -1,5 +1,8 @@ import { Component } from '@angular/core'; import { Validators, FormBuilder, FormGroup } from '@angular/forms'; +import { NavController, NavParams } from 'ionic-angular'; +import { LoadingController } from 'ionic-angular'; + @@ -20,7 +23,11 @@ } login() { - console.log(this.loginForm.value) + let loader = this.loadingCtrl.create({ + content: "Connecting to IMS Server", + duration: 3000 + }); + loader.present(); } }
6b9a77545668070b927be5505f678ce45cbc072a
AzureFunctions.Client/app/pipes/sidebar.pipe.ts
AzureFunctions.Client/app/pipes/sidebar.pipe.ts
import {Injectable, Pipe, PipeTransform} from '@angular/core'; import {FunctionInfo} from '../models/function-info'; @Pipe({ name: 'sidebarFilter', pure: false }) @Injectable() export class SideBarFilterPipe implements PipeTransform { transform(items: FunctionInfo[], args: string[]): any { if (args && args.length > 0 && args[0] && args[0].length > 0) { return items.filter(item => !item.clientOnly && item.name.toLocaleLowerCase().indexOf(args[0].toLocaleLowerCase()) !== -1); } else { return items; } } }
import {Injectable, Pipe, PipeTransform} from '@angular/core'; import {FunctionInfo} from '../models/function-info'; @Pipe({ name: 'sidebarFilter', pure: false }) @Injectable() export class SideBarFilterPipe implements PipeTransform { transform(items: FunctionInfo[], args: string[] | string): any { var query = typeof args === 'string' ? args : args[0]; if (args && args.length > 0 && args[0] && args[0].length > 0) { return items.filter(item => !item.clientOnly && item.name.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) !== -1); } else { return items; } } }
Fix search filter on the sidebar
Fix search filter on the sidebar
TypeScript
apache-2.0
agruning/azure-functions-ux,chunye/azure-functions-ux,projectkudu/AzureFunctions,agruning/azure-functions-ux,agruning/azure-functions-ux,projectkudu/WebJobsPortal,projectkudu/AzureFunctions,chunye/azure-functions-ux,projectkudu/WebJobsPortal,chunye/azure-functions-ux,projectkudu/WebJobsPortal,chunye/azure-functions-ux,projectkudu/WebJobsPortal,projectkudu/AzureFunctions,agruning/azure-functions-ux,chunye/azure-functions-ux,projectkudu/AzureFunctions,agruning/azure-functions-ux
--- +++ @@ -7,9 +7,10 @@ }) @Injectable() export class SideBarFilterPipe implements PipeTransform { - transform(items: FunctionInfo[], args: string[]): any { + transform(items: FunctionInfo[], args: string[] | string): any { + var query = typeof args === 'string' ? args : args[0]; if (args && args.length > 0 && args[0] && args[0].length > 0) { - return items.filter(item => !item.clientOnly && item.name.toLocaleLowerCase().indexOf(args[0].toLocaleLowerCase()) !== -1); + return items.filter(item => !item.clientOnly && item.name.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) !== -1); } else { return items; }
0ffabea9998a369d2d7c816b1c2abe2f7e6315ea
src/themefactory.ts
src/themefactory.ts
/* * Copyright (C) 2016 Chi Vinh Le and contributors. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ import { default as defaultJSS } from "jss"; export type ThemeCallback<TThemeVars, TTheme> = (theme?: TThemeVars) => TTheme; export type ThemeFactory<TThemeVars, TTheme> = (theme: TThemeVars, jss?: JSS.JSS) => TTheme; let index = 0; export function createThemeFactory<TThemeVars, TTheme>( callback: ThemeCallback<TThemeVars, TTheme>, options: JSS.StyleSheetOptions = {} ): ThemeFactory<TThemeVars, TTheme> { if (options.index === undefined) { index++; options.index = index; } return (vars: TThemeVars, jss: JSS.JSS = defaultJSS) => { const theme: any = callback(vars); const sheet = jss.createStyleSheet(theme.classes, options); sheet.attach(); theme.classes = sheet.classes; return theme; }; }
/* * Copyright (C) 2016 Chi Vinh Le and contributors. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ import { default as defaultJSS } from "jss"; export type ThemeCallback<TThemeVars, TTheme> = (theme?: TThemeVars) => TTheme; export type ThemeFactory<TThemeVars, TTheme> = (vars: TThemeVars, jss?: JSS.JSS) => TTheme; let index = 0; export function createThemeFactory<TThemeVars, TTheme>( callback: ThemeCallback<TThemeVars, TTheme>, options: JSS.StyleSheetOptions = {} ): ThemeFactory<TThemeVars, TTheme> { if (options.index === undefined) { index++; options.index = index; } return (vars: TThemeVars, jss: JSS.JSS = defaultJSS) => { const theme: any = callback(vars); const sheet = jss.createStyleSheet(theme.classes, options); sheet.attach(); theme.classes = sheet.classes; return theme; }; }
Correct parameter names of ThemeFactory
Correct parameter names of ThemeFactory
TypeScript
mit
wikiwi/react-jss-theme,wikiwi/react-jss-theme,wikiwi/react-jss-theme
--- +++ @@ -7,7 +7,7 @@ import { default as defaultJSS } from "jss"; export type ThemeCallback<TThemeVars, TTheme> = (theme?: TThemeVars) => TTheme; -export type ThemeFactory<TThemeVars, TTheme> = (theme: TThemeVars, jss?: JSS.JSS) => TTheme; +export type ThemeFactory<TThemeVars, TTheme> = (vars: TThemeVars, jss?: JSS.JSS) => TTheme; let index = 0;
e1e79c6857d57b3e6b5016c1038558775669b4fd
src/sdk/apis/business/appointment/book-a-business-for-me-request/otws-book-a-business-for-me-request-request.ts
src/sdk/apis/business/appointment/book-a-business-for-me-request/otws-book-a-business-for-me-request-request.ts
import {OTWSBookItForMeRequestRequest} from "../book-it-for-me-request/otws-book-it-for-me-request-request"; export class OTWSBookABusinessForMeRequestRequest extends OTWSBookItForMeRequestRequest implements OTWSAPIRequest { private _businessID: number; private _placesID: string; private _placesURL: string; private _getBusinessID() { return this._businessID; } private _getPlacesID() { return this._placesID; } private _getPlacesURL() { return this._placesURL; } setPlacesURL(placesURL: string) { this._placesURL = placesURL; } setPlacesID(placesID: string) { this._placesID = placesID; } setBusinessID(businessID: number) { this._businessID = businessID; } getData(): any { let data = super.getData(); data.business_id = this._getBusinessID(); data.google_data = []; data.google_data["url"] = this._getPlacesURL(); data.google_data["id"] = this._getPlacesID(); return data; } }
import {OTWSBookItForMeRequestRequest} from "../book-it-for-me-request/otws-book-it-for-me-request-request"; export class OTWSBookABusinessForMeRequestRequest extends OTWSBookItForMeRequestRequest implements OTWSAPIRequest { private _businessID: number; private _placesID: string; private _placesURL: string; private _getBusinessID() { return this._businessID; } private _getPlacesID() { return this._placesID; } private _getPlacesURL() { return this._placesURL; } setPlacesURL(placesURL: string) { this._placesURL = placesURL; } setPlacesID(placesID: string) { this._placesID = placesID; } setBusinessID(businessID: number) { this._businessID = businessID; } getData(): any { let data = super.getData(); data.business_id = this._getBusinessID(); data.google_data = { url : this._getPlacesURL(), id: this._getPlacesID() }; return data; } }
Fix (Book a business for me request): Create book a business for me request
Fix (Book a business for me request): Create book a business for me request
TypeScript
mit
TimeRocket/TimeRocketTypeScriptBookerSDK,TimeRocket/TimeRocketTypeScriptBookerSDK
--- +++ @@ -33,9 +33,10 @@ getData(): any { let data = super.getData(); data.business_id = this._getBusinessID(); - data.google_data = []; - data.google_data["url"] = this._getPlacesURL(); - data.google_data["id"] = this._getPlacesID(); + data.google_data = { + url : this._getPlacesURL(), + id: this._getPlacesID() + }; return data; } }
e5a8592786d503c84d7439fc1aeb8cbec9e0713c
tests/cases/fourslash/completionListInFunctionExpression.ts
tests/cases/fourslash/completionListInFunctionExpression.ts
/// <reference path="fourslash.ts"/> ////interface Number { //// toString(radix?: number): string; //// toFixed(fractionDigits?: number): string; //// toExponential(fractionDigits?: number): string; //// toPrecision(precision: number): string; ////} //// ////() => { //// var foo = 0; //// /*requestCompletion*/ //// foo./*memberCompletion*/toString; ////}/*editDeclaration*/ goTo.marker("requestCompletion"); verify.memberListContains("foo"); goTo.marker("memberCompletion"); verify.memberListContains("toExponential"); // Now change the decl by adding a semicolon goTo.marker("editDeclaration"); edit.insert(";"); // foo should still be there goTo.marker("requestCompletion"); verify.memberListContains("foo"); goTo.marker("memberCompletion"); verify.memberListContains("toExponential");
/// <reference path="fourslash.ts"/> ////() => { //// var foo = 0; //// /*requestCompletion*/ //// foo./*memberCompletion*/toString; ////}/*editDeclaration*/ goTo.marker("requestCompletion"); verify.memberListContains("foo"); goTo.marker("memberCompletion"); verify.memberListContains("toExponential"); // Now change the decl by adding a semicolon goTo.marker("editDeclaration"); edit.insert(";"); // foo should still be there goTo.marker("requestCompletion"); verify.memberListContains("foo"); goTo.marker("memberCompletion"); verify.memberListContains("toExponential");
Remove extraneous Number decls now that lib.d.ts is always present
Remove extraneous Number decls now that lib.d.ts is always present
TypeScript
apache-2.0
mbebenita/shumway.ts,hippich/typescript,hippich/typescript,fdecampredon/jsx-typescript-old-version,mbrowne/typescript-dci,hippich/typescript,mbrowne/typescript-dci,popravich/typescript,mbrowne/typescript-dci,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,mbrowne/typescript-dci,popravich/typescript,popravich/typescript
--- +++ @@ -1,12 +1,5 @@ /// <reference path="fourslash.ts"/> -////interface Number { -//// toString(radix?: number): string; -//// toFixed(fractionDigits?: number): string; -//// toExponential(fractionDigits?: number): string; -//// toPrecision(precision: number): string; -////} -//// ////() => { //// var foo = 0; //// /*requestCompletion*/
8091da5335d1ae16471db3b21bd1294681c13349
src/app/presentation/mode-overview/mode-overview.component.ts
src/app/presentation/mode-overview/mode-overview.component.ts
import { Component } from '@angular/core'; import { Mode } from '../mode.enum'; import { PresentationComponent } from '../presentation/presentation.component'; @Component({ selector: 'slides-mode-overview', templateUrl: './mode-overview.component.html', styleUrls: ['./mode-overview.css'] }) export class ModeOverviewComponent { private previousMode: Mode; modeEnum = Mode; onOverview = false; constructor(private presentation: PresentationComponent) { } get buttonLabel(): string { switch (this.presentation.mode) { case Mode.overview: return 'Back'; default: return 'Overview'; } } /* Returns true if in presentation is in overview mode */ get shouldShowPrintButton(): boolean { return this.presentation.mode === Mode.overview; } print() { window.print(); } toggle(mode: Mode) { this.onOverview = !this.onOverview; if (this.presentation.mode !== mode) { this.previousMode = this.presentation.mode; this.presentation.mode = mode; } else { // Go to last mode before this mode this.presentation.mode = this.previousMode; } } }
import { Component } from '@angular/core'; import { Mode } from '../mode.enum'; import { PresentationComponent } from '../presentation/presentation.component'; @Component({ selector: 'slides-mode-overview', templateUrl: './mode-overview.component.html', styleUrls: ['./mode-overview.css'] }) export class ModeOverviewComponent { private previousMode: Mode; modeEnum = Mode; onOverview = false; constructor(private presentation: PresentationComponent) { } get buttonLabel(): string { switch (this.presentation.mode) { case Mode.overview: return 'Back'; default: return 'Overview'; } } /* Returns true if in presentation is in overview mode */ get shouldShowPrintButton(): boolean { return this.presentation.mode === Mode.overview; } static print() { // TODO(synnz) this bug will be fixed with 2.8.2 ts release // window.print(); console.log("Check it out https://github.com/Microsoft/TypeScript/issues/22917") } toggle(mode: Mode) { this.onOverview = !this.onOverview; if (this.presentation.mode !== mode) { this.previousMode = this.presentation.mode; this.presentation.mode = mode; } else { // Go to last mode before this mode this.presentation.mode = this.previousMode; } } }
Comment window.print() for ts < 2.8.2
Comment window.print() for ts < 2.8.2
TypeScript
apache-2.0
nycJSorg/angular-presentation,nycJSorg/angular-presentation,nycJSorg/angular-presentation
--- +++ @@ -30,8 +30,10 @@ return this.presentation.mode === Mode.overview; } - print() { - window.print(); + static print() { + // TODO(synnz) this bug will be fixed with 2.8.2 ts release + // window.print(); + console.log("Check it out https://github.com/Microsoft/TypeScript/issues/22917") } toggle(mode: Mode) {
9afcabefa3605bc8051dfca36696cafa54a3b02f
src/helpers/file.ts
src/helpers/file.ts
import * as fs from 'fs'; import * as path from 'path'; /** * Recursively creates the directory structure if not exists * @param fullPath the path to create in Linux format */ export function createRecursive(fullPath: string) { const sep = path.sep; const initDir = path.isAbsolute(fullPath) ? sep : ''; const baseDir = '.'; if (!fs.existsSync(fullPath)) { fullPath.split(sep).reduce((total, current) => { const newVal = path.join(baseDir, total, current); if (!fs.existsSync(newVal)) { fs.mkdirSync(newVal); } return newVal; }, initDir); } }
import * as fs from 'fs'; import * as path from 'path'; /** * Recursively creates the directory structure if not exists * @param fullPath the path to create in Linux format */ export function createRecursive(fullPath: string) { const sep = path.sep; const initDir = path.isAbsolute(fullPath) ? sep : ''; const baseDir = sep === '\\' ? '.' : ''; if (!fs.existsSync(fullPath)) { fullPath.split(sep).reduce((total, current) => { const newVal = path.join(baseDir, total, current); if (!fs.existsSync(newVal)) { fs.mkdirSync(newVal); } return newVal; }, initDir); } }
Make sure basedir does not affect linux
Make sure basedir does not affect linux
TypeScript
mit
arijoon/vendaire-discord-bot,arijoon/vendaire-discord-bot
--- +++ @@ -8,7 +8,7 @@ export function createRecursive(fullPath: string) { const sep = path.sep; const initDir = path.isAbsolute(fullPath) ? sep : ''; - const baseDir = '.'; + const baseDir = sep === '\\' ? '.' : ''; if (!fs.existsSync(fullPath)) { fullPath.split(sep).reduce((total, current) => { const newVal = path.join(baseDir, total, current);
be9a099658f08419fb45f2ca70b895c66ab2250d
explorer/urlMigrations/ExplorerUrlMigrationUtils.ts
explorer/urlMigrations/ExplorerUrlMigrationUtils.ts
import { QueryParams } from "../../clientUtils/urls/UrlUtils" import { Url } from "../../clientUtils/urls/Url" import { EXPLORERS_ROUTE_FOLDER } from "../ExplorerConstants" export const decodeURIComponentOrUndefined = (value: string | undefined) => value !== undefined ? decodeURIComponent(value.replace(/\+/g, "%20")) : undefined export type QueryParamTransformMap = Record< string, { newName: string transformValue: (value: string | undefined) => string | undefined } > export const transformQueryParams = ( queryParams: Readonly<QueryParams>, transformMap: QueryParamTransformMap ) => { const newQueryParams = { ...queryParams } for (const oldParamName in transformMap) { if (!(oldParamName in newQueryParams)) continue const { newName, transformValue } = transformMap[oldParamName] newQueryParams[newName] = transformValue(queryParams[oldParamName]) delete newQueryParams[oldParamName] } return newQueryParams } export const getExplorerSlugFromUrl = (url: Url): string | undefined => { if (!url.pathname) return undefined const match = url.pathname.match( new RegExp(`^\/+${EXPLORERS_ROUTE_FOLDER}\/+([^\/]+)`) ) if (match && match[1]) return match[1] return undefined }
import { QueryParams } from "../../clientUtils/urls/UrlUtils" import { Url } from "../../clientUtils/urls/Url" import { EXPLORERS_ROUTE_FOLDER } from "../ExplorerConstants" import { omit } from "../../clientUtils/Util" export const decodeURIComponentOrUndefined = (value: string | undefined) => value !== undefined ? decodeURIComponent(value.replace(/\+/g, "%20")) : undefined export type QueryParamTransformMap = Record< string, { newName?: string transformValue: (value: string | undefined) => string | undefined } > export const transformQueryParams = ( oldQueryParams: Readonly<QueryParams>, transformMap: QueryParamTransformMap ) => { const newQueryParams = omit( oldQueryParams, ...Object.keys(transformMap) ) as QueryParams for (const oldParamName in transformMap) { if (!(oldParamName in oldQueryParams)) continue const { newName, transformValue } = transformMap[oldParamName] newQueryParams[newName ?? oldParamName] = transformValue( oldQueryParams[oldParamName] ) } return newQueryParams } export const getExplorerSlugFromUrl = (url: Url): string | undefined => { if (!url.pathname) return undefined const match = url.pathname.match( new RegExp(`^\/+${EXPLORERS_ROUTE_FOLDER}\/+([^\/]+)`) ) if (match && match[1]) return match[1] return undefined }
Support value-only renames in transformQueryParams
Support value-only renames in transformQueryParams
TypeScript
mit
OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher
--- +++ @@ -1,6 +1,7 @@ import { QueryParams } from "../../clientUtils/urls/UrlUtils" import { Url } from "../../clientUtils/urls/Url" import { EXPLORERS_ROUTE_FOLDER } from "../ExplorerConstants" +import { omit } from "../../clientUtils/Util" export const decodeURIComponentOrUndefined = (value: string | undefined) => value !== undefined @@ -10,21 +11,25 @@ export type QueryParamTransformMap = Record< string, { - newName: string + newName?: string transformValue: (value: string | undefined) => string | undefined } > export const transformQueryParams = ( - queryParams: Readonly<QueryParams>, + oldQueryParams: Readonly<QueryParams>, transformMap: QueryParamTransformMap ) => { - const newQueryParams = { ...queryParams } + const newQueryParams = omit( + oldQueryParams, + ...Object.keys(transformMap) + ) as QueryParams for (const oldParamName in transformMap) { - if (!(oldParamName in newQueryParams)) continue + if (!(oldParamName in oldQueryParams)) continue const { newName, transformValue } = transformMap[oldParamName] - newQueryParams[newName] = transformValue(queryParams[oldParamName]) - delete newQueryParams[oldParamName] + newQueryParams[newName ?? oldParamName] = transformValue( + oldQueryParams[oldParamName] + ) } return newQueryParams }
a9b09bbacb4cadee3ecc18602822d3c04d59ded9
src/app/shared/mrs.service.ts
src/app/shared/mrs.service.ts
import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs'; import { StorageService } from './storage.service'; import { userDataModel } from './models'; @Injectable() export class MRSService { defaultModel: userDataModel = { comics: [] }; userData: Subject<any> = new Subject<any>(null); constructor(private _storageService: StorageService) { this._storageService.currentStorage .subscribe(this.userData); this._storageService.getStorage(); } AddComic() { } RemoveComic() { } }
import { Injectable } from '@angular/core'; import { Subject, BehaviorSubject } from 'rxjs'; import { StorageService } from './storage.service'; import { userDataModel } from './models'; @Injectable() export class MRSService { defaultModel: userDataModel = { comics: [] }; userData: Subject<any> = new BehaviorSubject<any>(null); constructor(private _storageService: StorageService) { this._storageService.currentStorage .subscribe(this.userData); this._storageService.getStorage(); } AddComic() { } RemoveComic() { } }
Use BehaviorSubject for UserData to allow subscribers to get last/current value
Use BehaviorSubject for UserData to allow subscribers to get last/current value
TypeScript
mit
SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend
--- +++ @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { Observable, Subject } from 'rxjs'; +import { Subject, BehaviorSubject } from 'rxjs'; import { StorageService } from './storage.service'; import { userDataModel } from './models'; @@ -9,7 +9,7 @@ defaultModel: userDataModel = { comics: [] }; - userData: Subject<any> = new Subject<any>(null); + userData: Subject<any> = new BehaviorSubject<any>(null); constructor(private _storageService: StorageService) { this._storageService.currentStorage
7911d8a673919aead9e9933a277772bf2bfd2fc5
src/actions/databaseFilterSettings.ts
src/actions/databaseFilterSettings.ts
import { updateValue } from './updateValue'; import { UPDATE_DB_SEARCH_TERM } from '../constants'; export interface UpdateDatabaseSearchTerm { readonly type: UPDATE_DB_SEARCH_TERM; readonly data: string; } export const changeSearchTerm = updateValue<string>(UPDATE_DB_SEARCH_TERM);
import { updateValue } from './updateValue'; import { UPDATE_DB_SEARCH_TERM, UPDATE_DB_STATUS_FILTERS } from '../constants'; import { StatusFilterType } from 'types'; import { Set } from 'immutable'; export interface UpdateDatabaseSearchTerm { readonly type: UPDATE_DB_SEARCH_TERM; readonly data: string; } export interface UpdateDatabaseStatusFilters { readonly type: UPDATE_DB_STATUS_FILTERS; readonly data: Set<StatusFilterType>; } export type DatabaseFilterAction = | UpdateDatabaseSearchTerm | UpdateDatabaseStatusFilters; export const changeSearchTerm = updateValue<string>(UPDATE_DB_SEARCH_TERM); export const changeFilters = ( data: Set<StatusFilterType> ): UpdateDatabaseStatusFilters => ({ type: UPDATE_DB_STATUS_FILTERS, data });
Add action creators for UPDATE_DB_STATUS_FILTERS action types.
Add action creators for UPDATE_DB_STATUS_FILTERS action types.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -1,9 +1,27 @@ import { updateValue } from './updateValue'; -import { UPDATE_DB_SEARCH_TERM } from '../constants'; +import { UPDATE_DB_SEARCH_TERM, UPDATE_DB_STATUS_FILTERS } from '../constants'; +import { StatusFilterType } from 'types'; +import { Set } from 'immutable'; export interface UpdateDatabaseSearchTerm { readonly type: UPDATE_DB_SEARCH_TERM; readonly data: string; } +export interface UpdateDatabaseStatusFilters { + readonly type: UPDATE_DB_STATUS_FILTERS; + readonly data: Set<StatusFilterType>; +} + +export type DatabaseFilterAction = + | UpdateDatabaseSearchTerm + | UpdateDatabaseStatusFilters; + export const changeSearchTerm = updateValue<string>(UPDATE_DB_SEARCH_TERM); + +export const changeFilters = ( + data: Set<StatusFilterType> +): UpdateDatabaseStatusFilters => ({ + type: UPDATE_DB_STATUS_FILTERS, + data +});
9bfd146cd646f137017b2fcaf43d196a25ff196f
core/modules/cart/helpers/productChecksum.ts
core/modules/cart/helpers/productChecksum.ts
import CartItem from '@vue-storefront/core/modules/cart/types/CartItem' import { sha3_224 } from 'js-sha3' const getDataToHash = (product: CartItem): any => { if (!product.product_option) { return null } const { extension_attributes } = product.product_option if (extension_attributes.bundle_options) { const { bundle_options } = extension_attributes return Array.isArray(bundle_options) ? bundle_options : Object.values(bundle_options) } if (extension_attributes.custom_options) { const { custom_options } = extension_attributes return Array.isArray(custom_options) ? custom_options : Object.values(custom_options) } return product.product_option } const productChecksum = (product: CartItem): string => sha3_224(JSON.stringify(getDataToHash(product))) export default productChecksum
import CartItem from '@vue-storefront/core/modules/cart/types/CartItem' import { sha3_224 } from 'js-sha3' const replaceNumberToString = obj => { Object.keys(obj).forEach(key => { if (typeof obj[key] === 'object') { return replaceNumberToString(obj[key]); } obj[key] = String(obj[key]); }); return obj; } const getDataToHash = (product: CartItem): any => { if (!product.product_option) { return null } const { extension_attributes } = product.product_option const { bundle_options } = extension_attributes const { custom_options } = extension_attributes if (extension_attributes.bundle_options && ((Array.isArray(bundle_options) && bundle_options.length > 0) || (typeof bundle_options === 'object' && bundle_options !== null && Object.values(bundle_options).length > 0))) { return Array.isArray(bundle_options) ? bundle_options : Object.values(replaceNumberToString(bundle_options)) } if (extension_attributes.custom_options && ((Array.isArray(custom_options) && custom_options.length > 0) || (typeof custom_options === 'object' && custom_options !== null && Object.values(custom_options).length > 0))) { return Array.isArray(custom_options) ? custom_options : Object.values(replaceNumberToString(custom_options)) } return product.product_option } const productChecksum = (product: CartItem): string => sha3_224(JSON.stringify(getDataToHash(product))) export default productChecksum
Fix checksum by covert numbers to strings
Fix checksum by covert numbers to strings
TypeScript
mit
DivanteLtd/vue-storefront,pkarw/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront
--- +++ @@ -1,5 +1,15 @@ import CartItem from '@vue-storefront/core/modules/cart/types/CartItem' import { sha3_224 } from 'js-sha3' + +const replaceNumberToString = obj => { + Object.keys(obj).forEach(key => { + if (typeof obj[key] === 'object') { + return replaceNumberToString(obj[key]); + } + obj[key] = String(obj[key]); + }); + return obj; +} const getDataToHash = (product: CartItem): any => { if (!product.product_option) { @@ -7,15 +17,14 @@ } const { extension_attributes } = product.product_option + const { bundle_options } = extension_attributes + const { custom_options } = extension_attributes - if (extension_attributes.bundle_options) { - const { bundle_options } = extension_attributes - return Array.isArray(bundle_options) ? bundle_options : Object.values(bundle_options) + if (extension_attributes.bundle_options && ((Array.isArray(bundle_options) && bundle_options.length > 0) || (typeof bundle_options === 'object' && bundle_options !== null && Object.values(bundle_options).length > 0))) { + return Array.isArray(bundle_options) ? bundle_options : Object.values(replaceNumberToString(bundle_options)) } - - if (extension_attributes.custom_options) { - const { custom_options } = extension_attributes - return Array.isArray(custom_options) ? custom_options : Object.values(custom_options) + if (extension_attributes.custom_options && ((Array.isArray(custom_options) && custom_options.length > 0) || (typeof custom_options === 'object' && custom_options !== null && Object.values(custom_options).length > 0))) { + return Array.isArray(custom_options) ? custom_options : Object.values(replaceNumberToString(custom_options)) } return product.product_option
8369a9e45a9c3f454d07334b416d3ec8caf47cca
app/test/app-test.tsx
app/test/app-test.tsx
import * as chai from 'chai' const expect = chai.expect import * as React from 'react' import * as ReactDOM from 'react-dom' import * as TestUtils from 'react-addons-test-utils' import App from '../src/ui/app' import { Dispatcher, AppStore, GitHubUserStore, CloningRepositoriesStore, EmojiStore } from '../src/lib/dispatcher' import InMemoryDispatcher from './in-memory-dispatcher' import TestGitHubUserDatabase from './test-github-user-database' (global as {}).__WIN32__ = true (global as any).__DARWIN__ = true describe('App', () => { let appStore: AppStore | null = null let dispatcher: Dispatcher | null = null beforeEach(async () => { const db = new TestGitHubUserDatabase() await db.reset() appStore = new AppStore(new GitHubUserStore(db), new CloningRepositoriesStore(), new EmojiStore()) dispatcher = new InMemoryDispatcher(appStore) }) it('renders', () => { const app = TestUtils.renderIntoDocument( <App dispatcher={dispatcher!} appStore={appStore!}/> ) as React.Component<any, any> const node = ReactDOM.findDOMNode(app) expect(node).not.to.equal(null) }) })
import * as chai from 'chai' const expect = chai.expect import * as React from 'react' import * as ReactDOM from 'react-dom' import * as TestUtils from 'react-addons-test-utils' import App from '../src/ui/app' import { Dispatcher, AppStore, GitHubUserStore, CloningRepositoriesStore, EmojiStore } from '../src/lib/dispatcher' import InMemoryDispatcher from './in-memory-dispatcher' import TestGitHubUserDatabase from './test-github-user-database' // These constants are defined by Webpack at build time, but since tests aren't // built with Webpack we need to make sure these exist at runtime. const g: any = global g['__WIN32__'] = process.platform === 'win32' g['__DARWIN__'] = process.platform === 'darwin' describe('App', () => { let appStore: AppStore | null = null let dispatcher: Dispatcher | null = null beforeEach(async () => { const db = new TestGitHubUserDatabase() await db.reset() appStore = new AppStore(new GitHubUserStore(db), new CloningRepositoriesStore(), new EmojiStore()) dispatcher = new InMemoryDispatcher(appStore) }) it('renders', () => { const app = TestUtils.renderIntoDocument( <App dispatcher={dispatcher!} appStore={appStore!}/> ) as React.Component<any, any> const node = ReactDOM.findDOMNode(app) expect(node).not.to.equal(null) }) })
Define the constants at runtime for tests.
Define the constants at runtime for tests.
TypeScript
mit
desktop/desktop,kactus-io/kactus,BugTesterTest/desktops,shiftkey/desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,BugTesterTest/desktops,artivilla/desktop,artivilla/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,gengjiawen/desktop,hjobrien/desktop,j-f1/forked-desktop,desktop/desktop,gengjiawen/desktop,shiftkey/desktop,say25/desktop,hjobrien/desktop,kactus-io/kactus,artivilla/desktop,gengjiawen/desktop,kactus-io/kactus,gengjiawen/desktop,hjobrien/desktop,BugTesterTest/desktops,say25/desktop,kactus-io/kactus,BugTesterTest/desktops,say25/desktop,hjobrien/desktop,shiftkey/desktop,j-f1/forked-desktop,j-f1/forked-desktop
--- +++ @@ -10,8 +10,11 @@ import InMemoryDispatcher from './in-memory-dispatcher' import TestGitHubUserDatabase from './test-github-user-database' -(global as {}).__WIN32__ = true -(global as any).__DARWIN__ = true +// These constants are defined by Webpack at build time, but since tests aren't +// built with Webpack we need to make sure these exist at runtime. +const g: any = global +g['__WIN32__'] = process.platform === 'win32' +g['__DARWIN__'] = process.platform === 'darwin' describe('App', () => { let appStore: AppStore | null = null
d3c736e9bc547b02220a8639c0411c72886049bf
src/app/map/home/home.component.spec.ts
src/app/map/home/home.component.spec.ts
/* tslint:disable:no-unused-variable */ /*! * Home Component Test * * Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> * Licensed under MIT */ import { Renderer } from '@angular/core'; import { TestBed, async, inject } from '@angular/core/testing'; import { Http, HttpModule} from '@angular/http'; import { Router } from '@angular/router'; import { CookieService } from 'angular2-cookie/core'; import { TranslateModule, TranslateLoader, TranslateStaticLoader, TranslateService } from 'ng2-translate'; import { WindowService } from '../window.service'; import { AppLoggerService } from '../../app-logger.service'; import { MockRouter } from '../../mocks/router'; import { HomeComponent } from './home.component'; describe('Component: Home', () => { let mockRouter: MockRouter; beforeEach(() => { mockRouter = new MockRouter(); TestBed.configureTestingModule({ imports: [ HttpModule, TranslateModule.forRoot({ provide: TranslateLoader, useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'), deps: [Http] }), ], providers: [ CookieService, TranslateService, AppLoggerService, Renderer, WindowService, HomeComponent, { provide: Router, useValue: mockRouter }, ] }); }); it('should create an instance', inject([HomeComponent], (component: HomeComponent) => { expect(component).toBeTruthy(); })); });
/* tslint:disable:no-unused-variable */ /*! * Home Component Test * * Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> * Licensed under MIT */ import { Renderer } from '@angular/core'; import { TestBed, async, inject } from '@angular/core/testing'; import { Http, HttpModule} from '@angular/http'; import { Router } from '@angular/router'; import { CookieService } from 'angular2-cookie/core'; import { TranslateModule, TranslateLoader, TranslateService } from 'ng2-translate'; import { TranslationFactoryLoader } from '../../app-translation-factory.service'; import { WindowService } from '../window.service'; import { AppLoggerService } from '../../app-logger.service'; import { MockRouter } from '../../mocks/router'; import { HomeComponent } from './home.component'; describe('Component: Home', () => { let mockRouter: MockRouter; beforeEach(() => { mockRouter = new MockRouter(); TestBed.configureTestingModule({ imports: [ HttpModule, TranslateModule.forRoot({ provide: TranslateLoader, useFactory: TranslationFactoryLoader, deps: [Http] }), ], providers: [ CookieService, TranslateService, AppLoggerService, Renderer, WindowService, HomeComponent, { provide: Router, useValue: mockRouter }, ] }); }); it('should create an instance', inject([HomeComponent], (component: HomeComponent) => { expect(component).toBeTruthy(); })); });
Replace factory function with exported function
Replace factory function with exported function
TypeScript
mit
ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2
--- +++ @@ -12,7 +12,8 @@ import { Http, HttpModule} from '@angular/http'; import { Router } from '@angular/router'; import { CookieService } from 'angular2-cookie/core'; -import { TranslateModule, TranslateLoader, TranslateStaticLoader, TranslateService } from 'ng2-translate'; +import { TranslateModule, TranslateLoader, TranslateService } from 'ng2-translate'; +import { TranslationFactoryLoader } from '../../app-translation-factory.service'; import { WindowService } from '../window.service'; import { AppLoggerService } from '../../app-logger.service'; import { MockRouter } from '../../mocks/router'; @@ -29,7 +30,7 @@ HttpModule, TranslateModule.forRoot({ provide: TranslateLoader, - useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'), + useFactory: TranslationFactoryLoader, deps: [Http] }), ],
1a70bc95899a061a12c5ef76d81bd19a9b58c3bf
packages/multipartfiles/src/components/MultipartFileFilter.ts
packages/multipartfiles/src/components/MultipartFileFilter.ts
import {Filter, IFilter} from "@tsed/common"; /** * @private * @filter */ @Filter() export class MultipartFileFilter implements IFilter { transform(expression: string, request: any, response: any) { return request["files"][0]; } }
import {Filter, IFilter} from "@tsed/common"; /** * @private * @filter */ @Filter() export class MultipartFileFilter implements IFilter { transform(expression: string, request: any, response: any) { return request["files"] && request["files"][0]; } }
Fix request.files issue when file isn't required
fix(multipartfile): Fix request.files issue when file isn't required Closes: #462
TypeScript
mit
Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators
--- +++ @@ -7,6 +7,6 @@ @Filter() export class MultipartFileFilter implements IFilter { transform(expression: string, request: any, response: any) { - return request["files"][0]; + return request["files"] && request["files"][0]; } }
2f45f3125136f245dcab9be961d906b288ade8bb
src/eager-provider.token.ts
src/eager-provider.token.ts
import { OpaqueToken } from '@angular/core'; export const EAGER_PROVIDER = new OpaqueToken('EAGER_PROVIDER');
import { InjectionToken } from '@angular/core'; export const EAGER_PROVIDER = new InjectionToken<any>('EAGER_PROVIDER');
Use `InjectionToken` instead of `OpaqueToken` to support Angular 5
Use `InjectionToken` instead of `OpaqueToken` to support Angular 5
TypeScript
mit
dscheerens/angular-eager-provider-loader,dscheerens/angular-eager-provider-loader
--- +++ @@ -1,3 +1,3 @@ -import { OpaqueToken } from '@angular/core'; +import { InjectionToken } from '@angular/core'; -export const EAGER_PROVIDER = new OpaqueToken('EAGER_PROVIDER'); +export const EAGER_PROVIDER = new InjectionToken<any>('EAGER_PROVIDER');
9ca4594b147a126d4393dd8b99d1e698af423a81
packages/core/types/client.d.ts
packages/core/types/client.d.ts
import Breadcrumb from "./breadcrumb"; import * as common from "./common"; import Report from "./report"; import Session from "./session"; declare class Client { public app: object; public device: object; public context: string | void; public config: common.IConfig; public user: object; public metaData: object; public BugsnagReport: typeof Report; public BugsnagBreadcrumb: typeof Breadcrumb; public BugsnagSession: typeof Session; public use(plugin: common.IPlugin): Client; public getPlugin(name: string): any; public setOptions(opts: common.IConfig): Client; public configure(schema?: common.IConfigSchema): Client; public delivery(delivery: common.IDelivery): Client; public logger(logger: common.ILogger): Client; public sessionDelegate(sessionDelegate: common.ISessionDelegate): Client; public notify(error: common.NotifiableError, opts?: common.INotifyOpts): boolean; public leaveBreadcrumb(name: string, metaData?: any, type?: string, timestamp?: string): Client; public startSession(): Client; } export default Client;
import Breadcrumb from "./breadcrumb"; import * as common from "./common"; import Report from "./report"; import Session from "./session"; declare class Client { public app: object; public device: object; public context: string | void; public config: common.IConfig; public user: object; public metaData: object; public BugsnagReport: typeof Report; public BugsnagBreadcrumb: typeof Breadcrumb; public BugsnagSession: typeof Session; public use(plugin: common.IPlugin, ...args: any[]): Client; public getPlugin(name: string): any; public setOptions(opts: common.IConfig): Client; public configure(schema?: common.IConfigSchema): Client; public delivery(delivery: common.IDelivery): Client; public logger(logger: common.ILogger): Client; public sessionDelegate(sessionDelegate: common.ISessionDelegate): Client; public notify(error: common.NotifiableError, opts?: common.INotifyOpts): boolean; public leaveBreadcrumb(name: string, metaData?: any, type?: string, timestamp?: string): Client; public startSession(): Client; } export default Client;
Correct type signature of client.use()
fix(core): Correct type signature of client.use()
TypeScript
mit
bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js
--- +++ @@ -15,7 +15,7 @@ public BugsnagBreadcrumb: typeof Breadcrumb; public BugsnagSession: typeof Session; - public use(plugin: common.IPlugin): Client; + public use(plugin: common.IPlugin, ...args: any[]): Client; public getPlugin(name: string): any; public setOptions(opts: common.IConfig): Client; public configure(schema?: common.IConfigSchema): Client;
c99a9750a896eff0666ddaaf5e596c3808dff57d
src/app/components/inline-assessment/comment-assessment.component.ts
src/app/components/inline-assessment/comment-assessment.component.ts
import {Component, Input} from "@angular/core"; @Component({ selector: 'comment-assessment', template: ` <div class="panel" [hidden]="!hasVoted"> <div class="panel-body"> <h5>¿Porqué está {{tipo}}</h5> {{texto}} <input type="text" placeholder="máximo 250 caracteres ..."> </div> </div> ` }) export class CommentAssessment { @Input() tipo: string; @Input() hasVoted: boolean; @Input() texto: string; }
import {Component, Input} from "@angular/core"; @Component({ selector: 'comment-assessment', template: ` <div class="panel" [hidden]="!hasVoted"> <div class="panel-body"> <h4>¿Porqué está {{tipo}}</h4> {{texto}} <textarea placeholder="máximo 250 caracteres ..." maxlength="250" style="width: 100%"></textarea> <button class="btn btn-success btn-block">Aceptar</button> </div> </div> ` }) export class CommentAssessment { @Input() tipo: string; @Input() hasVoted: boolean; @Input() texto: string; }
Improve some styles on inline assessment
Improve some styles on inline assessment
TypeScript
agpl-3.0
llopv/jetpad-ic,P2Pvalue/jetpad,P2Pvalue/jetpad,P2Pvalue/jetpad,llopv/jetpad-ic,llopv/jetpad-ic
--- +++ @@ -5,9 +5,10 @@ template: ` <div class="panel" [hidden]="!hasVoted"> <div class="panel-body"> - <h5>¿Porqué está {{tipo}}</h5> + <h4>¿Porqué está {{tipo}}</h4> {{texto}} - <input type="text" placeholder="máximo 250 caracteres ..."> + <textarea placeholder="máximo 250 caracteres ..." maxlength="250" style="width: 100%"></textarea> + <button class="btn btn-success btn-block">Aceptar</button> </div> </div> `
69bf3bf740c1cb4e6b7ef38378b53802128bf356
src/actions/FallingAction.ts
src/actions/FallingAction.ts
import { Action } from "./Action"; import { ActionType } from "./ActionType"; import { StrayKittyState } from "../StrayKittyState"; import { StandingAction } from "./StandingAction"; export class FallingAction implements Action { do(kitty: StrayKittyState, dt: number) { if (kitty.y < window.innerHeight - 32) { kitty.yVector += dt / 250; } else { if (Math.abs(kitty.yVector) < dt / 100) { kitty.y = window.innerHeight - 32; kitty.action = new StandingAction(); } kitty.yVector *= -0.5; } } readonly type = ActionType.Falling; readonly frames = [2, 3]; }
import { Action } from "./Action"; import { ActionType } from "./ActionType"; import { StrayKittyState } from "../StrayKittyState"; import { StandingAction } from "./StandingAction"; export class FallingAction implements Action { do(kitty: StrayKittyState, dt: number) { if (kitty.y < window.innerHeight - 32) { kitty.yVector += dt / 250; } else { if (Math.abs(kitty.yVector) < dt / 100) { kitty.y = window.innerHeight - 32; kitty.yVector = 0; kitty.action = new StandingAction(); } kitty.yVector *= -0.5; } } readonly type = ActionType.Falling; readonly frames = [2, 3]; }
Set y vector to 0 when done falling
Set y vector to 0 when done falling
TypeScript
mit
xianbaum/StrayKitty,xianbaum/StrayKitty,xianbaum/StrayKitty
--- +++ @@ -10,6 +10,7 @@ } else { if (Math.abs(kitty.yVector) < dt / 100) { kitty.y = window.innerHeight - 32; + kitty.yVector = 0; kitty.action = new StandingAction(); } kitty.yVector *= -0.5;
b290ab519c17ee63e1bf537b0a4e25fa3edd86c0
packages/@sanity/base/src/change-indicators/helpers/scrollIntoView.ts
packages/@sanity/base/src/change-indicators/helpers/scrollIntoView.ts
import isScrollContainer from './isScrollContainer' const SCROLL_INTO_VIEW_TOP_PADDING = -15 const scrollIntoView = field => { const element = field.element let parentElementWithScroll = element.parentElement while (!isScrollContainer(parentElementWithScroll)) { parentElementWithScroll = parentElementWithScroll.parentElement } parentElementWithScroll.scroll({ top: parentElementWithScroll.scrollTop + field.rect.top - field.rect.bounds.top + SCROLL_INTO_VIEW_TOP_PADDING, left: 0, behavior: 'smooth' }) } export default scrollIntoView
import isScrollContainer from './isScrollContainer' const SCROLL_INTO_VIEW_TOP_PADDING = -15 const scrollIntoView = field => { const element = field.element /* * Start at current element and check the parent for a scroll * bar until a scrollable element has been found. */ let parentElementWithScroll = element while (!isScrollContainer(parentElementWithScroll)) { parentElementWithScroll = parentElementWithScroll.parentElement /* * If the parent element is null it means we are at the root * element, which has no parent. Since no scroll bar has * been found so far it does not make sense to scroll. */ if (!parentElementWithScroll) { return } } parentElementWithScroll.scroll({ top: parentElementWithScroll.scrollTop + field.rect.top - field.rect.bounds.top + SCROLL_INTO_VIEW_TOP_PADDING, left: 0, behavior: 'smooth' }) } export default scrollIntoView
Fix unable to scroll on connector click bug
[base] Fix unable to scroll on connector click bug The logic would try and find the nearest element with a scrollbar and keep checking until the root element gives null as parent. Stop before that happens.
TypeScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
--- +++ @@ -5,10 +5,23 @@ const scrollIntoView = field => { const element = field.element - let parentElementWithScroll = element.parentElement + /* + * Start at current element and check the parent for a scroll + * bar until a scrollable element has been found. + */ + let parentElementWithScroll = element while (!isScrollContainer(parentElementWithScroll)) { parentElementWithScroll = parentElementWithScroll.parentElement + + /* + * If the parent element is null it means we are at the root + * element, which has no parent. Since no scroll bar has + * been found so far it does not make sense to scroll. + */ + if (!parentElementWithScroll) { + return + } } parentElementWithScroll.scroll({
a023b90521def7227a577cd80f73d48b1d587a95
NavigationReactNative/src/BarButtonIOS.tsx
NavigationReactNative/src/BarButtonIOS.tsx
import React from 'react'; import { requireNativeComponent, Platform } from 'react-native'; declare var NVBarButton: any; var BarButtonIOS = props => <NVBarButton key={props.systemItem} {...props} />; export default Platform.OS === 'ios' ? requireNativeComponent('NVBarButton', BarButtonIOS as any) : () => null;
import React from 'react'; import { requireNativeComponent, Platform } from 'react-native'; declare var NVBarButton: any; var BarButtonIOS = props => <NVBarButton {...props} key={props.systemItem} />; export default Platform.OS === 'ios' ? requireNativeComponent('NVBarButton', BarButtonIOS as any) : () => null;
Revert "Switched so custom key takes precedence"
Revert "Switched so custom key takes precedence" This reverts commit 94571767ffd556a38063ce61adc27ee0013c68e4.
TypeScript
apache-2.0
grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation
--- +++ @@ -2,6 +2,6 @@ import { requireNativeComponent, Platform } from 'react-native'; declare var NVBarButton: any; -var BarButtonIOS = props => <NVBarButton key={props.systemItem} {...props} />; +var BarButtonIOS = props => <NVBarButton {...props} key={props.systemItem} />; export default Platform.OS === 'ios' ? requireNativeComponent('NVBarButton', BarButtonIOS as any) : () => null;
c14a8f1ed8d86379bf6b978e604de618250f8698
Signum.React/Scripts/Lines/FormControlReadonly.tsx
Signum.React/Scripts/Lines/FormControlReadonly.tsx
import * as React from 'react' import { StyleContext, TypeContext } from '../Lines'; import { classes, addClass } from '../Globals'; import "./Lines.css" export interface FormControlReadonlyProps extends React.Props<FormControlReadonly> { ctx: StyleContext; htmlAttributes?: React.HTMLAttributes<any>; className?: string } export class FormControlReadonly extends React.Component<FormControlReadonlyProps> { render() { const ctx = this.props.ctx; var attrs = this.props.htmlAttributes; var formControlClasses = ctx.readonlyAsPlainText ? ctx.formControlPlainTextClass : classes(ctx.formControlClass, "readonly"); return ( <div {...attrs} className={classes(formControlClasses, attrs && attrs.className, this.props.className)}> {this.props.children || "\u00A0" /*To get min height*/} </div> ); } }
import * as React from 'react' import { StyleContext, TypeContext } from '../Lines'; import { classes, addClass } from '../Globals'; import "./Lines.css" import { navigatorIsReadOnly } from '../../../../Extensions/Signum.React.Extensions/Authorization/AuthClient'; export interface FormControlReadonlyProps extends React.Props<FormControlReadonly> { ctx: StyleContext; htmlAttributes?: React.HTMLAttributes<any>; className?: string } export class FormControlReadonly extends React.Component<FormControlReadonlyProps> { render() { const ctx = this.props.ctx; var attrs = this.props.htmlAttributes; if (ctx.readonlyAsPlainText) { return ( <p {...attrs} className={classes(ctx.formControlPlainTextClass, attrs && attrs.className, this.props.className)}> {this.props.children} </p> ); } else { return ( <input type="text" style={{ pointerEvents: "none" }} readOnly {...attrs} className={classes(ctx.formControlClass, attrs && attrs.className, this.props.className)} value={React.Children.toArray(this.props.children)[0] as string || ""} /> ); } } }
Revert to last Version and set ccs styleoption for deactivate pointer events.
Revert to last Version and set ccs styleoption for deactivate pointer events.
TypeScript
mit
AlejandroCano/framework,signumsoftware/framework,signumsoftware/framework,avifatal/framework,avifatal/framework,AlejandroCano/framework
--- +++ @@ -3,6 +3,7 @@ import { classes, addClass } from '../Globals'; import "./Lines.css" +import { navigatorIsReadOnly } from '../../../../Extensions/Signum.React.Extensions/Authorization/AuthClient'; export interface FormControlReadonlyProps extends React.Props<FormControlReadonly> { ctx: StyleContext; @@ -16,14 +17,19 @@ const ctx = this.props.ctx; var attrs = this.props.htmlAttributes; + + if (ctx.readonlyAsPlainText) { + return ( + <p {...attrs} className={classes(ctx.formControlPlainTextClass, attrs && attrs.className, this.props.className)}> + {this.props.children} + </p> + ); - - var formControlClasses = ctx.readonlyAsPlainText ? ctx.formControlPlainTextClass : classes(ctx.formControlClass, "readonly"); - - return ( - <div {...attrs} className={classes(formControlClasses, attrs && attrs.className, this.props.className)}> - {this.props.children || "\u00A0" /*To get min height*/} - </div> - ); + } else { + return ( + <input type="text" style={{ pointerEvents: "none" }} readOnly {...attrs} className={classes(ctx.formControlClass, attrs && attrs.className, this.props.className)} + value={React.Children.toArray(this.props.children)[0] as string || ""} /> + ); + } } }
c0d05b130cb4427c9d215b1380a68a152f2e8913
server/src/parser/test-cases-table-parser.ts
server/src/parser/test-cases-table-parser.ts
import * as _ from "lodash"; import { DataTable, DataRow } from "./table-models"; import { TestCasesTable, TestCase, Step, CallExpression } from "./models"; import { parseIdentifier, parseValueExpression, } from "./primitive-parsers"; export function parseTestCasesTable(dataTable: DataTable): TestCasesTable { const testCasesTable = new TestCasesTable(dataTable.location); let currentTestCase: TestCase; dataTable.rows.forEach(row => { if (row.isEmpty()) { return; } if (startsTestCase(row)) { const identifier = parseIdentifier(row.first()); currentTestCase = new TestCase(identifier, row.location.start); testCasesTable.addTestCase(currentTestCase); } else if (currentTestCase) { const step = parseStep(row); currentTestCase.addStep(step); } }); return testCasesTable; } function startsTestCase(row: DataRow) { return !row.first().isEmpty(); } function parseStep(row: DataRow) { // TODO: Variable parsing. Now assumes all are call expressions const identifier = parseIdentifier(row.getCellByIdx(1)); const valueExpressions = row.getCellsByRange(2).map(parseValueExpression); return new Step( new CallExpression(identifier, valueExpressions, row.location), row.location ); }
import * as _ from "lodash"; import { DataTable, DataRow } from "./table-models"; import { TestCasesTable, TestCase, Step, CallExpression } from "./models"; import { parseIdentifier, parseValueExpression, } from "./primitive-parsers"; import { isVariable, parseTypeAndName, parseVariableDeclaration } from "./variable-parsers"; export function parseTestCasesTable(dataTable: DataTable): TestCasesTable { const testCasesTable = new TestCasesTable(dataTable.location); let currentTestCase: TestCase; dataTable.rows.forEach(row => { if (row.isEmpty()) { return; } if (startsTestCase(row)) { const identifier = parseIdentifier(row.first()); currentTestCase = new TestCase(identifier, row.location.start); testCasesTable.addTestCase(currentTestCase); } else if (currentTestCase) { const step = parseStep(row); currentTestCase.addStep(step); } }); return testCasesTable; } function startsTestCase(row: DataRow) { return !row.first().isEmpty(); } function parseStep(row: DataRow) { const firstDataCell = row.getCellByIdx(1); const valueExpressions = row.getCellsByRange(2).map(parseValueExpression); let stepContent; if (isVariable(firstDataCell)) { const typeAndName = parseTypeAndName(firstDataCell); stepContent = parseVariableDeclaration(typeAndName, valueExpressions, row.location); } else { const identifier = parseIdentifier(row.getCellByIdx(1)); stepContent = new CallExpression(identifier, valueExpressions, row.location); } return new Step(stepContent, row.location); }
Implement variable declaration parsing as part of step
Implement variable declaration parsing as part of step
TypeScript
mit
tomi/vscode-rf-language-server,tomi/vscode-rf-language-server
--- +++ @@ -16,6 +16,12 @@ parseIdentifier, parseValueExpression, } from "./primitive-parsers"; + +import { + isVariable, + parseTypeAndName, + parseVariableDeclaration +} from "./variable-parsers"; export function parseTestCasesTable(dataTable: DataTable): TestCasesTable { const testCasesTable = new TestCasesTable(dataTable.location); @@ -45,12 +51,20 @@ } function parseStep(row: DataRow) { - // TODO: Variable parsing. Now assumes all are call expressions - const identifier = parseIdentifier(row.getCellByIdx(1)); + const firstDataCell = row.getCellByIdx(1); const valueExpressions = row.getCellsByRange(2).map(parseValueExpression); - return new Step( - new CallExpression(identifier, valueExpressions, row.location), - row.location - ); + let stepContent; + + if (isVariable(firstDataCell)) { + const typeAndName = parseTypeAndName(firstDataCell); + stepContent = + parseVariableDeclaration(typeAndName, valueExpressions, row.location); + } else { + const identifier = parseIdentifier(row.getCellByIdx(1)); + + stepContent = new CallExpression(identifier, valueExpressions, row.location); + } + + return new Step(stepContent, row.location); }
57effc26d3616c5c2562d92f4713786b1e3dc760
app/preact/src/client/preview/render.tsx
app/preact/src/client/preview/render.tsx
import * as preact from 'preact'; import { document } from 'global'; import dedent from 'ts-dedent'; import { RenderContext, StoryFnPreactReturnType } from './types'; const rootElement = document ? document.getElementById('root') : null; let renderedStory: Element; function preactRender(element: StoryFnPreactReturnType | null): void { if (preact.Fragment) { preact.render(element, rootElement); } else { renderedStory = (preact.render(element, rootElement, renderedStory) as unknown) as Element; } } export default function renderMain({ storyFn, kind, name, showMain, showError }: RenderContext) { const element = storyFn(); if (!element) { showError({ title: `Expecting a Preact element from the story: "${name}" of "${kind}".`, description: dedent` Did you forget to return the Preact element from the story? Use "() => (<MyComp/>)" or "() => { return <MyComp/>; }" when defining the story. `, }); return; } preactRender(null); showMain(); preactRender(element); }
import * as preact from 'preact'; import { document } from 'global'; import dedent from 'ts-dedent'; import { RenderContext, StoryFnPreactReturnType } from './types'; const rootElement = document ? document.getElementById('root') : null; let renderedStory: Element; function preactRender(element: StoryFnPreactReturnType | null): void { if ((preact as any).Fragment) { // Preact 10 only: preact.render(element, rootElement); } else if (element) { renderedStory = (preact.render(element, rootElement) as unknown) as Element; } else { preact.render(element, rootElement, renderedStory); } } export default function renderMain({ storyFn, kind, name, showMain, showError }: RenderContext) { const element = storyFn(); if (!element) { showError({ title: `Expecting a Preact element from the story: "${name}" of "${kind}".`, description: dedent` Did you forget to return the Preact element from the story? Use "() => (<MyComp/>)" or "() => { return <MyComp/>; }" when defining the story. `, }); return; } preactRender(null); showMain(); preactRender(element); }
Fix Preact 8 issue when changing between diferent stories
Preact: Fix Preact 8 issue when changing between diferent stories
TypeScript
mit
storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook
--- +++ @@ -8,10 +8,13 @@ let renderedStory: Element; function preactRender(element: StoryFnPreactReturnType | null): void { - if (preact.Fragment) { + if ((preact as any).Fragment) { + // Preact 10 only: preact.render(element, rootElement); + } else if (element) { + renderedStory = (preact.render(element, rootElement) as unknown) as Element; } else { - renderedStory = (preact.render(element, rootElement, renderedStory) as unknown) as Element; + preact.render(element, rootElement, renderedStory); } }
102f7bc8a2d82ace575e1eeb5a37809fc5ea95bd
src/engine/actions/sendImbMessage.ts
src/engine/actions/sendImbMessage.ts
import {WorldState} from '../../models/WorldState'; import {IAction, ActionHelper} from '../../models/Action'; import {Utils} from '../../helpers/Utils'; import {RuleEngine, IRuleEngineService} from '../../engine/RuleEngine'; export interface ISendImbMessageData extends IAction { topic: string; publisher: string; // TODO to?: string; } export function run(service: IRuleEngineService, data: ISendImbMessageData) { if (!data || !data.hasOwnProperty('topic') || !data.hasOwnProperty('publisher')) return null; let publisher = service.router.publishers[data['publisher']]; if (!publisher) return null; let topic = data['topic']; let action: ISendImbMessageData = Utils.deepClone(data); delete action.topic; delete action.publisher; return function (worldState: WorldState, activatedFeatures: GeoJSON.Feature<GeoJSON.GeometryObject>[]) { if (!activatedFeatures) return; activatedFeatures.forEach(f => { if (action.property === '$location') { action.property = JSON.stringify(f.geometry); } publisher.publish(topic, JSON.stringify(action)); }); }; }
import {WorldState} from '../../models/WorldState'; import {IAction, ActionHelper} from '../../models/Action'; import {Utils} from '../../helpers/Utils'; import {RuleEngine, IRuleEngineService} from '../../engine/RuleEngine'; export interface ISendImbMessageData extends IAction { topic: string; publisher: string; // TODO to?: string; } export function run(service: IRuleEngineService, data: ISendImbMessageData) { if (!data || !data.hasOwnProperty('topic') || !data.hasOwnProperty('publisher')) return null; let publisher = service.router.publishers[data['publisher']]; if (!publisher) return null; let topic = data['topic']; let action: ISendImbMessageData = Utils.deepClone(data); delete action.topic; delete action.publisher; return function (worldState: WorldState) { let feature = worldState.updatedFeature; if (!feature) return; if (action.property === '$location') { action.property = JSON.stringify(feature.geometry); } service.logger.info(`Publishing feature ${feature.id}`); publisher.publish(topic, JSON.stringify(action)); }; }
Send IMB message: show info.
Send IMB message: show info.
TypeScript
mit
TNOCS/csWeb-rules,TNOCS/csWeb-rules
--- +++ @@ -17,13 +17,13 @@ let action: ISendImbMessageData = Utils.deepClone(data); delete action.topic; delete action.publisher; - return function (worldState: WorldState, activatedFeatures: GeoJSON.Feature<GeoJSON.GeometryObject>[]) { - if (!activatedFeatures) return; - activatedFeatures.forEach(f => { - if (action.property === '$location') { - action.property = JSON.stringify(f.geometry); - } - publisher.publish(topic, JSON.stringify(action)); - }); + return function (worldState: WorldState) { + let feature = worldState.updatedFeature; + if (!feature) return; + if (action.property === '$location') { + action.property = JSON.stringify(feature.geometry); + } + service.logger.info(`Publishing feature ${feature.id}`); + publisher.publish(topic, JSON.stringify(action)); }; }
83178a6e8891a4903bed06179262d9296075f4ea
bids-validator/src/validators/bids.ts
bids-validator/src/validators/bids.ts
import { Issue } from '../types/issues.ts' import { FileTree } from '../files/filetree.ts' import { walkFileTree } from '../schema/walk.ts' import { loadSchema } from '../setup/loadSchema.ts' import { applyRules } from '../schema/applyRules.ts' import { isTopLevel, isAtRoot, checkDatatypes, checkLabelFormat, } from './filenames.ts' /** * Full BIDS schema validation entrypoint */ export async function validate(fileTree: FileTree): Promise<> { const issues = [] const schema = await loadSchema() for await (const context of walkFileTree(fileTree)) { if (!isTopLevel(schema, context) && !isAtRoot(context)) { checkDatatypes(schema, context) checkLabelFormat(schema, context) } applyRules(schema, context) } }
import { Issue } from '../types/issues.ts' import { FileTree } from '../files/filetree.ts' import { walkFileTree } from '../schema/walk.ts' import { loadSchema } from '../setup/loadSchema.ts' import { applyRules } from '../schema/applyRules.ts' import { isTopLevel, isAtRoot, checkDatatypes, checkLabelFormat, } from './filenames.ts' /** * Full BIDS schema validation entrypoint */ export async function validate(fileTree: FileTree): Promise<void> { const issues = [] const schema = await loadSchema() for await (const context of walkFileTree(fileTree)) { if (!isTopLevel(schema, context) && !isAtRoot(context)) { checkDatatypes(schema, context) checkLabelFormat(schema, context) } applyRules(schema, context) } }
Fix missing generic on validate return type
Fix missing generic on validate return type
TypeScript
mit
nellh/bids-validator,nellh/bids-validator,nellh/bids-validator
--- +++ @@ -13,7 +13,7 @@ /** * Full BIDS schema validation entrypoint */ -export async function validate(fileTree: FileTree): Promise<> { +export async function validate(fileTree: FileTree): Promise<void> { const issues = [] const schema = await loadSchema() for await (const context of walkFileTree(fileTree)) {
d85ec9c9db4a4c4ac9951c8bced086a986f20d84
react-redux-todos/src/main.tsx
react-redux-todos/src/main.tsx
// tslint:disable-next-line no-unused-variable import * as React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore, Store } from 'redux' import { App } from './components/App' import { rootReducer } from './reducers/rootReducer' import { RootStore } from './model/RootStore' const initialState = new RootStore({ todos: [], visibilityFilter: 'SHOW_ALL' }) const store: Store<RootStore> = createStore<RootStore>(rootReducer, initialState) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
// tslint:disable-next-line no-unused-variable import * as React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore, Store } from 'redux' import { hashHistory, Route, Router } from 'react-router' import { App } from './components/App' import { rootReducer } from './reducers/rootReducer' import { RootStore } from './model/RootStore' const store: Store<RootStore> = createStore<RootStore>(rootReducer) render( <Provider store={store}> <Router history={hashHistory}> <Route component={App}> <Route path="/"/> <Route path="/active"/> <Route path="/completed"/> </Route> </Router> </Provider>, document.getElementById('root') )
Remove initial state and add router
Remove initial state and add router
TypeScript
unlicense
janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations
--- +++ @@ -3,21 +3,23 @@ import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore, Store } from 'redux' +import { hashHistory, Route, Router } from 'react-router' import { App } from './components/App' import { rootReducer } from './reducers/rootReducer' import { RootStore } from './model/RootStore' -const initialState = new RootStore({ - todos: [], - visibilityFilter: 'SHOW_ALL' -}) - -const store: Store<RootStore> = createStore<RootStore>(rootReducer, initialState) +const store: Store<RootStore> = createStore<RootStore>(rootReducer) render( <Provider store={store}> - <App /> + <Router history={hashHistory}> + <Route component={App}> + <Route path="/"/> + <Route path="/active"/> + <Route path="/completed"/> + </Route> + </Router> </Provider>, document.getElementById('root') )
7c3b9587ef17bef39086d932f484587d15860dde
client/components/login/login.component.ts
client/components/login/login.component.ts
import { Component, AfterViewInit } from '@angular/core'; import { LoginService } from './login.service'; @Component({ selector: 'login', templateUrl: 'client/components/login/login.component.html', styleUrls: ['client/components/login/login.styles.css'], providers: [LoginService] }) /** * Login component is to display login screen and relevent method * to act as authentication interface */ export class LoginComponent implements AfterViewInit{ constructor(private loginService: LoginService) { } ngAfterViewInit() { $.material.init() } /** * Actions to take when submitting a form */ onSubmit(form) { let email:string = form.value.inputEmail; let pwd:string = form.value.inputPassword; this.login(email, pwd); } /** * Call login back-end route */ login(username, password) { this.loginService.Login(username, password) .then( () => console.log('login clicked')); } }
import { Component, AfterViewInit } from '@angular/core'; import { LoginService } from './login.service'; @Component({ selector: 'login', templateUrl: 'client/components/login/login.component.html', styleUrls: ['client/customCss/login-style.css'], providers: [LoginService] }) /** * Login component is to display login screen and relevent method * to act as authentication interface */ export class LoginComponent implements AfterViewInit{ constructor(private loginService: LoginService) { } ngAfterViewInit() { $.material.init() } /** * Actions to take when submitting a form */ onSubmit(form) { let email:string = form.value.inputEmail; let pwd:string = form.value.inputPassword; this.login(email, pwd); } /** * Call login back-end route */ login(username, password) { this.loginService.Login(username, password) .then( () => console.log('login clicked')); } }
Add css from shared custom css
Add css from shared custom css
TypeScript
mit
shavindraSN/examen,shavindraSN/examen,shavindraSN/examen
--- +++ @@ -4,7 +4,7 @@ @Component({ selector: 'login', templateUrl: 'client/components/login/login.component.html', - styleUrls: ['client/components/login/login.styles.css'], + styleUrls: ['client/customCss/login-style.css'], providers: [LoginService] }) /**
f7e70ed9ae092acca81e1606278f885fa632c377
app/test/__mocks__/electron.ts
app/test/__mocks__/electron.ts
export const shell = { moveItemToTrash: jest.fn(), } export const remote = { app: { on: jest.fn(), }, getCurrentWebContents: jest.fn().mockImplementation(() => ({ on: jest.fn().mockImplementation(() => true), })), getCurrentWindow: jest.fn().mockImplementation(() => ({ isFullScreen: jest.fn().mockImplementation(() => true), webContents: { zoomFactor: jest.fn().mockImplementation(_ => null), }, })), autoUpdater: { on: jest.fn(), }, nativeTheme: { addListener: jest.fn(), removeAllListeners: jest.fn(), shouldUseDarkColors: jest.fn().mockImplementation(() => true), }, } export const ipcRenderer = { on: jest.fn(), send: jest.fn(), }
export const shell = { moveItemToTrash: jest.fn(), } export const remote = { app: { on: jest.fn(), }, getCurrentWebContents: jest.fn().mockImplementation(() => ({ on: jest.fn().mockImplementation(() => true), })), getCurrentWindow: jest.fn().mockImplementation(() => ({ isFullScreen: jest.fn().mockImplementation(() => true), webContents: { zoomFactor: jest.fn().mockImplementation(_ => null), }, })), autoUpdater: { on: jest.fn(), }, nativeTheme: { addListener: jest.fn(), removeAllListeners: jest.fn(), shouldUseDarkColors: jest.fn().mockImplementation(() => true), }, } export const ipcRenderer = { on: jest.fn(), send: jest.fn(), invoke: jest.fn(), }
Add invoke to ipcRenderer mock
Add invoke to ipcRenderer mock
TypeScript
mit
desktop/desktop,desktop/desktop,j-f1/forked-desktop,desktop/desktop,j-f1/forked-desktop,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop
--- +++ @@ -28,4 +28,5 @@ export const ipcRenderer = { on: jest.fn(), send: jest.fn(), + invoke: jest.fn(), }
ac2c6a0f6744ccc78b95ca86db6dc463af9fc9c5
tests/unit/templating/all.ts
tests/unit/templating/all.ts
import html = require('./html'); html; import parser = require('./html/peg/html'); parser;
/// <amd-dependency path="intern/dojo/has!host-browser?./html" /> import parser = require('./html/peg/html'); parser;
Fix test suite failures in Node.js
Fix test suite failures in Node.js
TypeScript
bsd-3-clause
QuinntyneBrown/mayhem,QuinntyneBrown/mayhem,jessevdk/mayhem,SitePen/mayhem,SitePen/mayhem,SitePen/mayhem,QuinntyneBrown/mayhem,QuinntyneBrown/mayhem,jkieboom/mayhem,jessevdk/mayhem,jkieboom/mayhem,jessevdk/mayhem,SitePen/mayhem,jessevdk/mayhem,jkieboom/mayhem,jkieboom/mayhem
--- +++ @@ -1,2 +1,2 @@ -import html = require('./html'); html; +/// <amd-dependency path="intern/dojo/has!host-browser?./html" /> import parser = require('./html/peg/html'); parser;
855d872d5160ef3388d69fc1ba41305218f0aca0
generators/app/templates/src/index.ts
generators/app/templates/src/index.ts
export * from './<%- ngModuleFilename.replace('.ts', '') %>'; // all components that will be codegen'd need to be exported for AOT to work export * from './helloWorld.component';
export * from './<%- ngModuleFilename.replace('.ts', '') %>';
Remove hack now angular bug is fixed
Remove hack now angular bug is fixed
TypeScript
mit
mattlewis92/generator-angular-library,mattlewis92/generator-angular-library,mattlewis92/generator-angular-library
--- +++ @@ -1,4 +1 @@ export * from './<%- ngModuleFilename.replace('.ts', '') %>'; - -// all components that will be codegen'd need to be exported for AOT to work -export * from './helloWorld.component';
d8801c4aac0cebc9992a00063717af502a3b6a0a
02-Calling-an-API/src/app/auth/interceptor.service.ts
02-Calling-an-API/src/app/auth/interceptor.service.ts
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { AuthService } from './auth.service'; import { Observable, throwError } from 'rxjs'; import { filter, mergeMap, catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class InterceptorService implements HttpInterceptor { constructor(private auth: AuthService) { } intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { return this.auth.getTokenSilently$().pipe( mergeMap(token => { const tokenReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next.handle(tokenReq); }), catchError(err => throwError(err)) ); } }
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { AuthService } from './auth.service'; import { Observable, throwError } from 'rxjs'; import { mergeMap, catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class InterceptorService implements HttpInterceptor { constructor(private auth: AuthService) { } intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { return this.auth.getTokenSilently$().pipe( mergeMap(token => { const tokenReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next.handle(tokenReq); }), catchError(err => throwError(err)) ); } }
Clean up interceptor (unused import)
Clean up interceptor (unused import)
TypeScript
mit
auth0-samples/auth0-angular-samples,auth0-samples/auth0-angular-samples,auth0-samples/auth0-angular-samples,auth0-samples/auth0-angular-samples
--- +++ @@ -7,7 +7,7 @@ } from '@angular/common/http'; import { AuthService } from './auth.service'; import { Observable, throwError } from 'rxjs'; -import { filter, mergeMap, catchError } from 'rxjs/operators'; +import { mergeMap, catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root'
bece36886c36c99e6704b58dac39ee8cabbc2d8d
packages/skatejs/src/define.ts
packages/skatejs/src/define.ts
import { CustomElementConstructor } from './types'; import { name } from './name.js'; export function define(Ctor: CustomElementConstructor): CustomElementConstructor { customElements.define(Ctor.is || name(), Ctor); return Ctor; }
import { CustomElementConstructor } from './types'; import { name } from './name.js'; export function define( ctor: CustomElementConstructor ): CustomElementConstructor { if (!ctor.is) { ctor.is = name(); } customElements.define(ctor.is, ctor); return ctor; }
Define is class property on constructor if it's not present.
Define is class property on constructor if it's not present.
TypeScript
mit
skatejs/skatejs,skatejs/skatejs,skatejs/skatejs
--- +++ @@ -1,7 +1,12 @@ import { CustomElementConstructor } from './types'; import { name } from './name.js'; -export function define(Ctor: CustomElementConstructor): CustomElementConstructor { - customElements.define(Ctor.is || name(), Ctor); - return Ctor; +export function define( + ctor: CustomElementConstructor +): CustomElementConstructor { + if (!ctor.is) { + ctor.is = name(); + } + customElements.define(ctor.is, ctor); + return ctor; }
dcc1eaec8bf4006b4d7305af1fa603f87c8bdc9e
AzureFunctions.Client/app/components/binding-designer.component.ts
AzureFunctions.Client/app/components/binding-designer.component.ts
import {Component, OnInit, EventEmitter} from 'angular2/core'; import {FunctionBinding} from '../models/function-config'; import {Binding, BindingOption} from '../models/designer-schema'; @Component({ selector: 'binding-designer', templateUrl: 'templates/binding-designer.html', inputs: ['currentBinding', 'bindings', ], outputs: ['changedBinding'] }) export class BindingDesignerComponent implements OnInit { public changedBinding: EventEmitter<FunctionBinding>; public currentBinding: FunctionBinding; public bindings: Binding[]; public selectedBindingType: string; public bindingOptionsMeta: Binding; constructor() { this.changedBinding = new EventEmitter<FunctionBinding>(); } ngOnInit() { if (this.currentBinding) { this.selectedBindingType = this.currentBinding.type; this.bindingOptionsMeta = this.bindings.find(e => e.name === this.selectedBindingType); if (this.bindingOptionsMeta) { for(var e in this.currentBinding) { if (e === 'type') continue; var option = this.bindingOptionsMeta.options.find(o => o.name === e); if (option) { option.value = this.currentBinding[e]; } else { this.bindingOptionsMeta.options.push({ name: e, value: this.currentBinding[e], type: 'string' }) } } } } } }
import {Component, OnInit, EventEmitter} from 'angular2/core'; import {FunctionBinding} from '../models/function-config'; import {Binding, BindingOption} from '../models/designer-schema'; @Component({ selector: 'binding-designer', templateUrl: 'templates/binding-designer.html', inputs: ['currentBinding', 'bindings'], outputs: ['changedBinding'] }) export class BindingDesignerComponent implements OnInit { public changedBinding: EventEmitter<FunctionBinding>; public currentBinding: FunctionBinding; public bindings: Binding[]; public selectedBindingType: string; public bindingOptionsMeta: Binding; constructor() { this.changedBinding = new EventEmitter<FunctionBinding>(); } ngOnInit() { if (this.currentBinding) { this.selectedBindingType = this.currentBinding.type; this.bindingOptionsMeta = this.bindings.find(e => e.name === this.selectedBindingType); if (this.bindingOptionsMeta) { for(var e in this.currentBinding) { if (e === 'type') continue; var option = this.bindingOptionsMeta.options.find(o => o.name === e); if (option) { option.value = this.currentBinding[e]; } else { this.bindingOptionsMeta.options.push({ name: e, value: this.currentBinding[e], type: 'string' }) } } } } } }
Fix typo of an extra comma
Fix typo of an extra comma
TypeScript
apache-2.0
agruning/azure-functions-ux,agruning/azure-functions-ux,projectkudu/WebJobsPortal,projectkudu/AzureFunctions,projectkudu/WebJobsPortal,projectkudu/AzureFunctions,chunye/azure-functions-ux,projectkudu/AzureFunctions,agruning/azure-functions-ux,chunye/azure-functions-ux,agruning/azure-functions-ux,agruning/azure-functions-ux,chunye/azure-functions-ux,chunye/azure-functions-ux,projectkudu/AzureFunctions,projectkudu/WebJobsPortal,projectkudu/WebJobsPortal,chunye/azure-functions-ux
--- +++ @@ -6,7 +6,7 @@ @Component({ selector: 'binding-designer', templateUrl: 'templates/binding-designer.html', - inputs: ['currentBinding', 'bindings', ], + inputs: ['currentBinding', 'bindings'], outputs: ['changedBinding'] }) export class BindingDesignerComponent implements OnInit {
77a6a0ecb1c89c5e9be1cb244caf59cc572f120f
src/panels/panel-view.styles.ts
src/panels/panel-view.styles.ts
import {css} from '@microsoft/fast-element'; import {display} from '@microsoft/fast-foundation'; import { designUnit, typeRampBaseFontSize, typeRampBaseLineHeight, } from '../design-tokens'; export const PanelViewStyles = css` ${display('flex')} :host { color: #ffffff; background-color: transparent; border: solid 1px transparent; box-sizing: border-box; font-size: ${typeRampBaseFontSize}; line-height: ${typeRampBaseLineHeight}; padding: 10px calc((6 + (${designUnit}) * 1px); } `;
import {css} from '@microsoft/fast-element'; import {display} from '@microsoft/fast-foundation'; import { designUnit, typeRampBaseFontSize, typeRampBaseLineHeight, } from '../design-tokens'; export const PanelViewStyles = css` ${display('flex')} :host { color: #ffffff; background-color: transparent; border: solid 1px transparent; box-sizing: border-box; font-size: ${typeRampBaseFontSize}; line-height: ${typeRampBaseLineHeight}; padding: 10px calc((${designUnit} + 2) * 1px); } `;
Fix broken padding in panel view..again
Fix broken padding in panel view..again
TypeScript
mit
microsoft/vscode-webview-ui-toolkit,microsoft/vscode-webview-ui-toolkit,microsoft/vscode-webview-ui-toolkit
--- +++ @@ -14,6 +14,6 @@ box-sizing: border-box; font-size: ${typeRampBaseFontSize}; line-height: ${typeRampBaseLineHeight}; - padding: 10px calc((6 + (${designUnit}) * 1px); + padding: 10px calc((${designUnit} + 2) * 1px); } `;
7b9b13e4a68bbe9b4f0e6707d976f0c318c28f0e
src/client/datascience/history-react/transforms.ts
src/client/datascience/history-react/transforms.ts
/* tslint:disable */ 'use strict'; // THis code is from @nteract/transforms-full except without the Vega transforms // https://github.com/nteract/nteract/blob/master/packages/transforms-full/src/index.js // Vega transforms mess up our npm pkg install because they rely on the npm canvas module that needs // to be built on each system. import PlotlyTransform, { PlotlyNullTransform } from "@nteract/transform-plotly"; import GeoJSONTransform from "@nteract/transform-geojson"; import ModelDebug from "@nteract/transform-model-debug"; import DataResourceTransform from "@nteract/transform-dataresource"; // import { VegaLite1, VegaLite2, Vega2, Vega3 } from "@nteract/transform-vega"; import { standardTransforms, standardDisplayOrder, registerTransform, richestMimetype } from "@nteract/transforms"; const additionalTransforms = [ DataResourceTransform, ModelDebug, PlotlyNullTransform, PlotlyTransform, GeoJSONTransform, ]; const { transforms, displayOrder } = additionalTransforms.reduce( registerTransform, { transforms: standardTransforms, displayOrder: standardDisplayOrder } ); export { displayOrder, transforms, richestMimetype, registerTransform };
/* tslint:disable */ 'use strict'; // This code is from @nteract/transforms-full except without the Vega transforms: // https://github.com/nteract/nteract/blob/v0.12.2/packages/transforms-full/src/index.js . // Vega transforms mess up our npm pkg install because they rely on the npm canvas module that needs // to be built on each system. import PlotlyTransform, { PlotlyNullTransform } from "@nteract/transform-plotly"; import GeoJSONTransform from "@nteract/transform-geojson"; import ModelDebug from "@nteract/transform-model-debug"; import DataResourceTransform from "@nteract/transform-dataresource"; // import { VegaLite1, VegaLite2, Vega2, Vega3 } from "@nteract/transform-vega"; import { standardTransforms, standardDisplayOrder, registerTransform, richestMimetype } from "@nteract/transforms"; const additionalTransforms = [ DataResourceTransform, ModelDebug, PlotlyNullTransform, PlotlyTransform, GeoJSONTransform, ]; const { transforms, displayOrder } = additionalTransforms.reduce( registerTransform, { transforms: standardTransforms, displayOrder: standardDisplayOrder } ); export { displayOrder, transforms, richestMimetype, registerTransform };
Clarify the exact version of a file that is pulled from nteract
Clarify the exact version of a file that is pulled from nteract
TypeScript
mit
DonJayamanne/pythonVSCode,DonJayamanne/pythonVSCode,DonJayamanne/pythonVSCode,DonJayamanne/pythonVSCode,DonJayamanne/pythonVSCode
--- +++ @@ -1,8 +1,8 @@ /* tslint:disable */ 'use strict'; -// THis code is from @nteract/transforms-full except without the Vega transforms -// https://github.com/nteract/nteract/blob/master/packages/transforms-full/src/index.js +// This code is from @nteract/transforms-full except without the Vega transforms: +// https://github.com/nteract/nteract/blob/v0.12.2/packages/transforms-full/src/index.js . // Vega transforms mess up our npm pkg install because they rely on the npm canvas module that needs // to be built on each system.
efdb1523309cf8af90be38b5faf7a62359366734
src/frontend/views/components/pane.tsx
src/frontend/views/components/pane.tsx
import * as React from 'react' import {Component, Children} from 'react' import * as PropTypes from 'prop-types' import * as classnames from 'classnames' interface PaneProps { resizable?: boolean, allowFocus?: boolean, className?: string, } export default class Pane extends Component<PaneProps, any> { public static propTypes = { children: PropTypes.element, resizable: PropTypes.bool, allowFocus: PropTypes.bool, } public static defaultProps = { allowFocus: false, resizable: true, draggable: false, } public render() { const { className, allowFocus, resizable, children, ...props } = this.props return ( <div className={classnames('_workspace-pane', className, { '_workspace-pane--allow-focus': allowFocus, })} tabIndex={allowFocus ? -1 : void 0} {...props} > {(() => resizable ? <div className='_workspace-pane-handle' /> : null)()} {Children.map(children, child => child)} </div> ) } }
import * as React from 'react' import {Component, Children} from 'react' import * as PropTypes from 'prop-types' import * as classnames from 'classnames' interface PaneProps extends React.HTMLAttributes<HTMLDivElement> { resizable?: boolean, allowFocus?: boolean, className?: string, } export default class Pane extends Component<PaneProps, any> { public static propTypes = { children: PropTypes.element, resizable: PropTypes.bool, allowFocus: PropTypes.bool, } public static defaultProps = { allowFocus: false, resizable: true, draggable: false, } public render() { const { className, allowFocus, resizable, children, ...props } = this.props return ( <div className={classnames('_workspace-pane', className, { '_workspace-pane--allow-focus': allowFocus, })} tabIndex={allowFocus ? -1 : void 0} {...props} > {(() => resizable ? <div className='_workspace-pane-handle' /> : null)()} {Children.map(children, child => child)} </div> ) } }
Improve typing for Pane component
Improve typing for Pane component
TypeScript
mit
Ragg-/Delir,Ragg-/Delir,Ragg-/Delir,Ragg-/Delir
--- +++ @@ -3,7 +3,7 @@ import * as PropTypes from 'prop-types' import * as classnames from 'classnames' -interface PaneProps { +interface PaneProps extends React.HTMLAttributes<HTMLDivElement> { resizable?: boolean, allowFocus?: boolean, className?: string,
a5f366f357bcc424852f2c6ee209720cc70bdc5a
src/fetcher.ts
src/fetcher.ts
import * as vscode from 'vscode'; import ParseEngineRegistry from './parse-engines/parse-engine-registry'; class Fetcher { static async findAllParseableDocuments(): Promise<vscode.Uri[]> { const languages = ParseEngineRegistry.supportedLanguagesIds.join(','); return await vscode.workspace.findFiles(`**/*.{${languages}}`, ''); } } export default Fetcher;
import * as vscode from 'vscode'; import ParseEngineRegistry from './parse-engines/parse-engine-registry'; class Fetcher { static async findAllParseableDocuments(): Promise<vscode.Uri[]> { const languages = ParseEngineRegistry.supportedLanguagesIds.join(','); return await vscode.workspace.findFiles(`**/*.{${languages}}`, '**/node_modules'); } } export default Fetcher;
Exclude npm_modules when fetching files to index
Exclude npm_modules when fetching files to index
TypeScript
mit
zignd/HTML-CSS-Class-Completion
--- +++ @@ -5,7 +5,7 @@ static async findAllParseableDocuments(): Promise<vscode.Uri[]> { const languages = ParseEngineRegistry.supportedLanguagesIds.join(','); - return await vscode.workspace.findFiles(`**/*.{${languages}}`, ''); + return await vscode.workspace.findFiles(`**/*.{${languages}}`, '**/node_modules'); } }
ae7d43714048ea44aac82c8f0e6839e859d15ea8
app/core/datastore/core/sync-state.ts
app/core/datastore/core/sync-state.ts
import {Observable} from "rxjs"; export interface SyncState { url: string; cancel(): void; onError: Observable<any>; onChange: Observable<any>; }
import {Observable} from 'rxjs'; export interface SyncState { url: string; cancel(): void; onError: Observable<any>; onChange: Observable<any>; }
Adjust to code style rules
Adjust to code style rules
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -1,13 +1,9 @@ -import {Observable} from "rxjs"; +import {Observable} from 'rxjs'; export interface SyncState { url: string; - cancel(): void; - onError: Observable<any>; - onChange: Observable<any>; - }
3002e1ffcde95835b0267a95b1913ebc9aabe348
test/routes.test.ts
test/routes.test.ts
import { Application } from 'express'; import { createServer } from '../src/server'; import * as request from 'supertest'; describe('routes', () => { let app: Application; before('create app', function() { app = createServer(); }); describe('GET /api', () => { it('should redirect to the docs on GitHub', () => request(app) .get('/api') .expect(301) .expect('Location', /github\.com/) ); }); });
import { Application } from 'express'; import { createServer } from '../src/server'; import * as request from 'supertest'; describe('routes', () => { let app: Application; before('create app', function() { app = createServer(); }); describe('GET /api', () => { it('should redirect to the docs on GitHub', () => request(app) .get('/api') .expect(302) .expect('Location', /github\.com/) ); }); });
Fix status code for redirect
Fix status code for redirect
TypeScript
mit
thatJavaNerd/novaXfer,thatJavaNerd/novaXfer,thatJavaNerd/novaXfer
--- +++ @@ -13,7 +13,7 @@ it('should redirect to the docs on GitHub', () => request(app) .get('/api') - .expect(301) + .expect(302) .expect('Location', /github\.com/) ); });
8e05337812835ce390e4480eb2079e8bdbc0202c
src/LondonTravel.Site/assets/scripts/ts/Swagger.ts
src/LondonTravel.Site/assets/scripts/ts/Swagger.ts
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. declare var SwaggerUIBundle: any; declare var SwaggerUIStandalonePreset: any; function HideTopbarPlugin(): any { return { components: { Topbar: (): any => { return null; } } }; } window.onload = () => { let url: string = $("link[rel='swagger']").attr("href"); const ui: any = SwaggerUIBundle({ url: url, dom_id: "#swagger-ui", deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl, HideTopbarPlugin ], layout: "StandaloneLayout", booleanValues: ["false", "true"], defaultModelRendering: "schema", displayRequestDuration: true, jsonEditor: true, showRequestHeaders: true, supportedSubmitMethods: ["get"], validatorUrl: null, responseInterceptor: (response: any): any => { // Delete overly-verbose headers from the UI delete response.headers["content-security-policy"]; delete response.headers["content-security-policy-report-only"]; delete response.headers["public-key-pins-report-only"]; } }); (window as any).ui = ui; };
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. declare var SwaggerUIBundle: any; declare var SwaggerUIStandalonePreset: any; function HideTopbarPlugin(): any { return { components: { Topbar: (): any => { return null; } } }; } window.onload = () => { if ("SwaggerUIBundle" in window) { const url: string = $("link[rel='swagger']").attr("href"); const ui: any = SwaggerUIBundle({ url: url, dom_id: "#swagger-ui", deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl, HideTopbarPlugin ], layout: "StandaloneLayout", booleanValues: ["false", "true"], defaultModelRendering: "schema", displayRequestDuration: true, jsonEditor: true, showRequestHeaders: true, supportedSubmitMethods: ["get"], validatorUrl: null, responseInterceptor: (response: any): any => { // Delete overly-verbose headers from the UI delete response.headers["content-security-policy"]; delete response.headers["content-security-policy-report-only"]; delete response.headers["public-key-pins-report-only"]; } }); (window as any).ui = ui; } };
Fix occasional JS error in puppeteer tests
Fix occasional JS error in puppeteer tests Fix occasional JS error in puppeteer tests by checking that SwaggerUIBundle exists in the window before using it onload.
TypeScript
apache-2.0
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
--- +++ @@ -15,36 +15,36 @@ } window.onload = () => { + if ("SwaggerUIBundle" in window) { + const url: string = $("link[rel='swagger']").attr("href"); + const ui: any = SwaggerUIBundle({ + url: url, + dom_id: "#swagger-ui", + deepLinking: true, + presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIStandalonePreset + ], + plugins: [ + SwaggerUIBundle.plugins.DownloadUrl, + HideTopbarPlugin + ], + layout: "StandaloneLayout", + booleanValues: ["false", "true"], + defaultModelRendering: "schema", + displayRequestDuration: true, + jsonEditor: true, + showRequestHeaders: true, + supportedSubmitMethods: ["get"], + validatorUrl: null, + responseInterceptor: (response: any): any => { + // Delete overly-verbose headers from the UI + delete response.headers["content-security-policy"]; + delete response.headers["content-security-policy-report-only"]; + delete response.headers["public-key-pins-report-only"]; + } + }); - let url: string = $("link[rel='swagger']").attr("href"); - - const ui: any = SwaggerUIBundle({ - url: url, - dom_id: "#swagger-ui", - deepLinking: true, - presets: [ - SwaggerUIBundle.presets.apis, - SwaggerUIStandalonePreset - ], - plugins: [ - SwaggerUIBundle.plugins.DownloadUrl, - HideTopbarPlugin - ], - layout: "StandaloneLayout", - booleanValues: ["false", "true"], - defaultModelRendering: "schema", - displayRequestDuration: true, - jsonEditor: true, - showRequestHeaders: true, - supportedSubmitMethods: ["get"], - validatorUrl: null, - responseInterceptor: (response: any): any => { - // Delete overly-verbose headers from the UI - delete response.headers["content-security-policy"]; - delete response.headers["content-security-policy-report-only"]; - delete response.headers["public-key-pins-report-only"]; - } - }); - - (window as any).ui = ui; + (window as any).ui = ui; + } };
0b0965f0eb2844a9b1f82c6f06798c18ef85ac5c
src/displays/display_helper.ts
src/displays/display_helper.ts
const padImpl = require('pad') /** * */ expor t const clamp = (val: number, min: number, max: number): number => Math.min(max, Math.max(min, val)) /** * */ export const pad = (val: string, count: number): string => padImpl(count, '' + val, '\u00A0') /** * */ export const number = (val: string, padding: number) => '`\u200B' + pad(val, padding + 2) + '`' /** * */ export const unit = (unit: string, val: number, padding: number): string => number(val + unit, padding) /** * */ export const percent = (val: number, padding: number): string => unit('%', +(val).toFixed(2), padding) /** * */ export const decimalPercent = (val: number, padding: number): string => percent(val * 100, padding) /** * */ export const deg = (val: number, padding: number): string => unit('\u00B0', +(val).toFixed(2), padding) /** * */ export const func = (name: string, ...keys: Array<string>): string => `**${name}(**${keys.join(', ')}**)**`
const padImpl = require('pad') /** * */ export const clamp = (val: number, min: number, max: number): number => Math.min(max, Math.max(min, val)) /** * */ export const pad = (val: string, count: number): string => padImpl(count, '' + val, '\u00A0') /** * */ export const number = (val: string, padding: number) => '`\u200B' + pad(val, padding + 2) + '`' /** * */ export const unit = (unit: string, val: number, padding: number): string => number(val + unit, padding) /** * */ export const percent = (val: number, padding: number): string => unit('%', +(val).toFixed(2), padding) /** * */ export const decimalPercent = (val: number, padding: number): string => percent(val * 100, padding) /** * */ export const deg = (val: number, padding: number): string => unit('\u00B0', +(val).toFixed(2), padding) /** * */ export const func = (name: string, ...keys: Array<string>): string => `**${name}(**${keys.join(', ')}**)**`
Revert intentional break for testing travis
Revert intentional break for testing travis
TypeScript
mit
mattbierner/vscode-color-info,mattbierner/vscode-color-info
--- +++ @@ -3,7 +3,7 @@ /** * */ -expor t const clamp = (val: number, min: number, max: number): number => +export const clamp = (val: number, min: number, max: number): number => Math.min(max, Math.max(min, val)) /**
ba61cacd022a3a672f33623715470bb4381d9de1
jupyter-widgets-htmlmanager/test/src/output_test.ts
jupyter-widgets-htmlmanager/test/src/output_test.ts
import * as chai from 'chai'; import { HTMLManager } from '../../lib/'; import { OutputModel, OutputView } from '../../lib/output'; describe('output', () => { let model; let view; let manager; beforeEach(async function() { const widgetTag = document.createElement('div'); widgetTag.className = 'widget-subarea'; document.body.appendChild(widgetTag); manager = new HTMLManager() const modelId = 'u-u-i-d'; model = await manager.new_model({ model_name: 'OutputModel', model_id: modelId, model_module: '@jupyter-widgets/controls', state: { outputs: [ { "output_type": "stream", "name": "stdout", "text": "hi\n" } ], } }); view = await manager.display_model( undefined, model, { el: widgetTag } ); }) it('show the view', () => { console.error(view); }); })
import * as chai from 'chai'; import { HTMLManager } from '../../lib/'; import { OutputModel, OutputView } from '../../lib/output'; import * as widgets from '@jupyter-widgets/controls' describe('output', () => { let model; let view; let manager; beforeEach(async function() { const widgetTag = document.createElement('div'); widgetTag.className = 'widget-subarea'; document.body.appendChild(widgetTag); manager = new HTMLManager() const modelId = 'u-u-i-d'; const modelCreate: widgets.ModelOptions = { model_name: 'OutputModel', model_id: modelId, model_module: '@jupyter-widgets/controls', model_module_version: '*' } const modelState = { outputs: [ { "output_type": "stream", "name": "stdout", "text": "hi\n" } ], } model = await manager.new_model(modelCreate, modelState); view = await manager.display_model( undefined, model, { el: widgetTag } ); }) it('show the view', () => { console.error(view); }); })
Split out state in test
Split out state in test
TypeScript
bsd-3-clause
ipython/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets
--- +++ @@ -3,6 +3,8 @@ import { HTMLManager } from '../../lib/'; import { OutputModel, OutputView } from '../../lib/output'; + +import * as widgets from '@jupyter-widgets/controls' describe('output', () => { @@ -16,20 +18,22 @@ document.body.appendChild(widgetTag); manager = new HTMLManager() const modelId = 'u-u-i-d'; - model = await manager.new_model({ + const modelCreate: widgets.ModelOptions = { model_name: 'OutputModel', model_id: modelId, model_module: '@jupyter-widgets/controls', - state: { - outputs: [ - { - "output_type": "stream", - "name": "stdout", - "text": "hi\n" - } - ], - } - }); + model_module_version: '*' + } + const modelState = { + outputs: [ + { + "output_type": "stream", + "name": "stdout", + "text": "hi\n" + } + ], + } + model = await manager.new_model(modelCreate, modelState); view = await manager.display_model( undefined, model, { el: widgetTag } );
ea03f8f85f48493fb6658bcde1536851e1823ab3
src/controller/message/download-image-controller.ts
src/controller/message/download-image-controller.ts
/// <reference path="../../../definitions/chrome/chrome.d.ts" /> /// <reference path="../../model/config/config.ts" /> /// <reference path="../controller.ts" /> module Prisc { export class MessageDownloadImageController extends Controller { constructor() { super(); } execute(params: Object) { var dirName = Config.get('download-dir-name'), filename = params['filename']; chrome.downloads.download({ url: params['imageURI'], filename: [dirName, filename].join('/') },(downloadId: number) => { if (! Config.get('show-file-on-download')) return; // FIXME: なんやこれ。なんでコールバックなのに待たなあかんねん  // FIXME: なんのためのコールバックですかwww // FIXME: 125 < limitTime < 250 or depending on file size?? var delay = 250; setTimeout(() => { chrome.downloads.show(downloadId); }, delay); }); } } }
/// <reference path="../../../definitions/chrome/chrome.d.ts" /> /// <reference path="../../model/config/config.ts" /> /// <reference path="../controller.ts" /> module Prisc { export interface IDownloadParams { filename: string; imageURI: string; } export class MessageDownloadImageController extends Controller { constructor() { super(); } execute(params: IDownloadParams) { var dirName = Config.get('download-dir-name'), filename = params.filename; chrome.downloads.download({ url: params.imageURI, filename: [dirName, filename].join('/') },(downloadId: number) => { if (! Config.get('show-file-on-download')) return; // FIXME: なんやこれ。なんでコールバックなのに待たなあかんねん  // FIXME: なんのためのコールバックですかwww // FIXME: 125 < limitTime < 250 or depending on file size?? var delay = 250; setTimeout(() => { chrome.downloads.show(downloadId); }, delay); }); } } }
Add parameter interface for download
Add parameter interface for download
TypeScript
mit
otiai10/prisc,otiai10/prisc,otiai10/prisc
--- +++ @@ -3,15 +3,19 @@ /// <reference path="../controller.ts" /> module Prisc { + export interface IDownloadParams { + filename: string; + imageURI: string; + } export class MessageDownloadImageController extends Controller { constructor() { super(); } - execute(params: Object) { + execute(params: IDownloadParams) { var dirName = Config.get('download-dir-name'), - filename = params['filename']; + filename = params.filename; chrome.downloads.download({ - url: params['imageURI'], + url: params.imageURI, filename: [dirName, filename].join('/') },(downloadId: number) => { if (! Config.get('show-file-on-download')) return;
4c2c4efa519b831e9d8bffd730001d91f3636e88
TheCollection.Web/ClientApp/views/tea/Dashboard.tsx
TheCollection.Web/ClientApp/views/tea/Dashboard.tsx
import { Chart } from '../../components/charts/Chart'; import * as React from 'react'; import * as c3 from 'c3'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { IApplicationState } from '../../store'; import * as DashboardReducer from '../../reducers/tea/dashboard'; type DashboardProps = DashboardReducer.IDashboardState // ... state we've requested from the Redux store & typeof DashboardReducer.actionCreators; // ... plus action creators we've requested class Dashboard extends React.Component<DashboardProps, {}> { constructor(props: DashboardProps) { super(); } componentDidMount() { this.props.requestBagTypeCount(); } renderBagTypeChart() { if (this.props.bagtypecount === undefined) { return undefined; } let data = this.props.bagtypecount.map(btc => { return [btc.value.name, btc.count] as string | number[]; }); return <Chart columns={data} chartType='pie' />; } render() { return <div>{this.renderBagTypeChart()}</div>; } } export default connect( (state: IApplicationState) => state.teadashboard, DashboardReducer.actionCreators, )(Dashboard);
import * as React from 'react'; import * as c3 from 'c3'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { IApplicationState } from '../../store'; import * as DashboardReducer from '../../reducers/tea/dashboard'; import { Chart } from '../../components/charts/Chart'; type DashboardProps = DashboardReducer.IDashboardState // ... state we've requested from the Redux store & typeof DashboardReducer.actionCreators; // ... plus action creators we've requested class Dashboard extends React.Component<DashboardProps, {}> { constructor(props: DashboardProps) { super(); } componentDidMount() { this.props.requestBagTypeCount(); } renderBagTypeChart() { if (this.props.bagtypecount === undefined) { return undefined; } let data = this.props.bagtypecount.map(btc => { if (btc.value === undefined || btc.value === null) { return ['None', btc.count] as string | number[]; } return [btc.value.name, btc.count] as string | number[]; }); return <Chart columns={data} chartType='pie' />; } render() { return <div>{this.renderBagTypeChart()}</div>; } } export default connect( (state: IApplicationState) => state.teadashboard, DashboardReducer.actionCreators, )(Dashboard);
Fix null reference on value for chart
Fix null reference on value for chart
TypeScript
apache-2.0
projecteon/thecollection,projecteon/thecollection,projecteon/thecollection,projecteon/thecollection
--- +++ @@ -1,10 +1,10 @@ -import { Chart } from '../../components/charts/Chart'; import * as React from 'react'; import * as c3 from 'c3'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { IApplicationState } from '../../store'; import * as DashboardReducer from '../../reducers/tea/dashboard'; +import { Chart } from '../../components/charts/Chart'; type DashboardProps = DashboardReducer.IDashboardState // ... state we've requested from the Redux store @@ -25,6 +25,10 @@ } let data = this.props.bagtypecount.map(btc => { + if (btc.value === undefined || btc.value === null) { + return ['None', btc.count] as string | number[]; + } + return [btc.value.name, btc.count] as string | number[]; });
08489801b7ea280295c799d67a4a967a0c4a415f
app/src/ui/notification/new-commits-banner.tsx
app/src/ui/notification/new-commits-banner.tsx
import * as React from 'react' import { ButtonGroup } from '../lib/button-group' import { Button } from '../lib/button' import { Ref } from '../lib/ref' import { Octicon, OcticonSymbol } from '../octicons' import { Branch } from '../../models/branch' interface INewCommitsBannerProps { /** * The number of commits behind `branch` */ readonly commitsBehind: number /** * The base branch that is ahead */ readonly branch: Branch readonly onCompareClicked: () => void readonly onMergeClicked: () => void } /** * Banner used to notify user that there branch is _commitsBehind_ * commits behind `branch` */ export class NewCommitsBanner extends React.Component< INewCommitsBannerProps, {} > { public render() { return ( <div className="notification-banner diverge-banner"> <div className="notification-banner-content"> <p> Your branch is <strong>{this.props.commitsBehind} commits</strong>{' '} behind <Ref>{this.props.branch.name}</Ref> </p> <a className="close" aria-label="Dismiss banner"> <Octicon symbol={OcticonSymbol.x} /> </a> </div> <ButtonGroup> <Button type="submit" onClick={this.props.onCompareClicked}> Compare </Button> <Button onClick={this.props.onMergeClicked}>Merge...</Button> </ButtonGroup> </div> ) } }
import * as React from 'react' import { ButtonGroup } from '../lib/button-group' import { Button } from '../lib/button' import { Ref } from '../lib/ref' import { Octicon, OcticonSymbol } from '../octicons' import { Branch } from '../../models/branch' interface INewCommitsBannerProps { /** * The number of commits behind `branch` */ readonly commitsBehind: number /** * The target branch that will accept commits * from the current branch */ readonly baseBranch: Branch readonly onCompareClicked: () => void readonly onMergeClicked: () => void } /** * Banner used to notify user that there branch is _commitsBehind_ * commits behind `branch` */ export class NewCommitsBanner extends React.Component< INewCommitsBannerProps, {} > { public render() { return ( <div className="notification-banner diverge-banner"> <div className="notification-banner-content"> <p> Your branch is <strong>{this.props.commitsBehind} commits</strong>{' '} behind <Ref>{this.props.baseBranch.name}</Ref> </p> <a className="close" aria-label="Dismiss banner"> <Octicon symbol={OcticonSymbol.x} /> </a> </div> <ButtonGroup> <Button type="submit" onClick={this.props.onCompareClicked}> Compare </Button> <Button onClick={this.props.onMergeClicked}>Merge...</Button> </ButtonGroup> </div> ) } }
Use more specific name and update doc
Use more specific name and update doc
TypeScript
mit
desktop/desktop,kactus-io/kactus,artivilla/desktop,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop,j-f1/forked-desktop,artivilla/desktop,say25/desktop,desktop/desktop,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,shiftkey/desktop,artivilla/desktop,say25/desktop,say25/desktop,shiftkey/desktop,say25/desktop
--- +++ @@ -12,9 +12,10 @@ readonly commitsBehind: number /** - * The base branch that is ahead + * The target branch that will accept commits + * from the current branch */ - readonly branch: Branch + readonly baseBranch: Branch readonly onCompareClicked: () => void readonly onMergeClicked: () => void } @@ -33,7 +34,7 @@ <div className="notification-banner-content"> <p> Your branch is <strong>{this.props.commitsBehind} commits</strong>{' '} - behind <Ref>{this.props.branch.name}</Ref> + behind <Ref>{this.props.baseBranch.name}</Ref> </p> <a className="close" aria-label="Dismiss banner">
d8d77bc9ebb59bdb1d692a9fb2b41f9b804b1db0
__mocks__/fs.ts
__mocks__/fs.ts
import * as path from 'path'; type Dictionary<T> = {[key: string]: T}; type FileContentDict = Dictionary<string>; type DirectoryListing = Dictionary<string[]>; const fs: any = jest.genMockFromModule('fs'); let mockFiles: DirectoryListing = {}; let allMockFiles: FileContentDict = {}; function __setMockFiles(newMockFiles: FileContentDict) { mockFiles = Object.create(null); for (const file in newMockFiles) { allMockFiles[file] = newMockFiles[file]; const dir = path.dirname(file); if (!mockFiles[dir]) { mockFiles[dir] = []; } mockFiles[dir].push(path.basename(file)); } } function readdirSync(directoryPath: string): string[] { if (mockFiles[directoryPath]) { return mockFiles[directoryPath]; } return []; } function readFileSync(filePath: string): string { if (allMockFiles[filePath]) { return allMockFiles[filePath]; } return ''; } function existsSync(filePath: string): boolean { return (typeof allMockFiles[filePath] !== 'undefined'); } fs.__setMockFiles = __setMockFiles; fs.readFileSync = readFileSync; fs.readdirSync = readdirSync; fs.existsSync = existsSync; module.exports = fs;
import * as path from 'path'; type Dictionary<T> = { [key: string]: T }; type FileContentDict = Dictionary<string>; type DirectoryListing = Dictionary<string[]>; const fs: any = jest.genMockFromModule('fs'); const originalFs = require.requireActual('fs'); let mockFiles: DirectoryListing = {}; let allMockFiles: FileContentDict = {}; function __setMockFiles(newMockFiles: FileContentDict) { mockFiles = Object.create(null); for (const file in newMockFiles) { allMockFiles[file] = newMockFiles[file]; const dir = path.dirname(file); if (!mockFiles[dir]) { mockFiles[dir] = []; } mockFiles[dir].push(path.basename(file)); } } function readdirSync(directoryPath: string): string[] { if (mockFiles[directoryPath]) { return mockFiles[directoryPath]; } return []; } function readFileSync(...args: any[]): string { const filePath = args[0] as string; if (allMockFiles[filePath]) { return allMockFiles[filePath]; } return originalFs.readFileSync(...args); } function existsSync(filePath: string): boolean { return typeof allMockFiles[filePath] !== 'undefined'; } module.exports = { ...fs, readFileSync, readdirSync, existsSync, __setMockFiles, };
Make readFileSync mock fallback to original
:bug: Make readFileSync mock fallback to original
TypeScript
mit
dkundel/node-env-run
--- +++ @@ -1,10 +1,11 @@ import * as path from 'path'; -type Dictionary<T> = {[key: string]: T}; +type Dictionary<T> = { [key: string]: T }; type FileContentDict = Dictionary<string>; type DirectoryListing = Dictionary<string[]>; const fs: any = jest.genMockFromModule('fs'); +const originalFs = require.requireActual('fs'); let mockFiles: DirectoryListing = {}; let allMockFiles: FileContentDict = {}; @@ -28,20 +29,22 @@ return []; } -function readFileSync(filePath: string): string { +function readFileSync(...args: any[]): string { + const filePath = args[0] as string; if (allMockFiles[filePath]) { return allMockFiles[filePath]; } - return ''; + return originalFs.readFileSync(...args); } function existsSync(filePath: string): boolean { - return (typeof allMockFiles[filePath] !== 'undefined'); + return typeof allMockFiles[filePath] !== 'undefined'; } -fs.__setMockFiles = __setMockFiles; -fs.readFileSync = readFileSync; -fs.readdirSync = readdirSync; -fs.existsSync = existsSync; - -module.exports = fs; +module.exports = { + ...fs, + readFileSync, + readdirSync, + existsSync, + __setMockFiles, +};
5687c45abb924cfa88888c545de2e8b94bfccaa2
src/components/Hello.tsx
src/components/Hello.tsx
import * as React from 'react'; export interface IProps { name: string; enthusiasmLevel?: number; } function Hello({ name, enthusiasmLevel = 1 }: IProps) { if (enthusiasmLevel <= 0) { throw new Error('You could be a little more enthusiastic. :D'); } return ( <div className="hello"> <div className="greeting"> Hello.. {name + getExclamationMarks(enthusiasmLevel)} </div> </div> ); } export default Hello; // helpers function getExclamationMarks(numChars: number) { return Array(numChars + 1).join('!'); }
import * as React from 'react'; export interface IProps { name: string; enthusiasmLevel?: number; } function Hello({ name, enthusiasmLevel = 1 }: IProps) { return ( <div className="hello"> <div className="greeting"> Hello.. {name + getExclamationMarks(enthusiasmLevel)} </div> </div> ); } export default Hello; // helpers function getExclamationMarks(numChars: number) { return Array(numChars + 1).join('!'); }
Remove some comments, Make adjustments to the bit logic rendering and offsets, Remove sample code that keeps throwing errors
Remove some comments, Make adjustments to the bit logic rendering and offsets, Remove sample code that keeps throwing errors
TypeScript
apache-2.0
ettiennegous/online-eitris,ettiennegous/online-eitris
--- +++ @@ -6,9 +6,6 @@ } function Hello({ name, enthusiasmLevel = 1 }: IProps) { - if (enthusiasmLevel <= 0) { - throw new Error('You could be a little more enthusiastic. :D'); - } return ( <div className="hello">
bac7ad87f1697d8406cfa0504e4231e01ee232e1
server/services/database/population-queries.ts
server/services/database/population-queries.ts
const accountTableQuery: string = 'CREATE TABLE IF NOT EXISTS Account(' + 'id INTEGER PRIMARY KEY,' + 'name TEXT NOT NULL UNIQUE);'; const categoryTableQuery: string = 'CREATE TABLE IF NOT EXISTS Category(' + 'id INTEGER PRIMARY KEY,' + 'name TEXT NOT NULL UNIQUE);'; const subcategoryTableQuery: string = 'CREATE TABLE IF NOT EXISTS Subcategory(' + 'id INTEGER PRIMARY KEY,' + 'name TEXT NOT NULL UNIQUE,' + 'refCategory INTEGER NOT NULL,' + 'FOREIGN KEY(refCategory) REFERENCES Category(id));'; export const populationQueries: string[] = [ accountTableQuery, categoryTableQuery, subcategoryTableQuery ]; const accountDataset: string[] = [ 'INSERT INTO Account VALUES (1, \'test-account1\');', 'INSERT INTO Account VALUES (2, \'test-account2\');', 'INSERT INTO Account VALUES (3, \'test-account3\');' ]; const categoryDataset: string[] = [ 'INSERT INTO Category VALUES(1, \'test-cat1\');', 'INSERT INTO Category VALUES(2, \'test-cat2\');', 'INSERT INTO Category VALUES(3, \'test-cat3\');', 'INSERT INTO Subcategory VALUES(1, \'test-subcat-1.1\', 1);', 'INSERT INTO Subcategory VALUES(2, \'test-subcat-1.2\', 1);', 'INSERT INTO Subcategory VALUES(3, \'test-subcat-2.1\', 2);' ]; export const datasetQueries: string[] = accountDataset.concat(categoryDataset);
const accountTableQuery: string = 'CREATE TABLE IF NOT EXISTS Account(' + 'id INTEGER PRIMARY KEY,' + 'name TEXT NOT NULL UNIQUE);'; const categoryTableQuery: string = 'CREATE TABLE IF NOT EXISTS Category(' + 'id INTEGER PRIMARY KEY,' + 'name TEXT NOT NULL UNIQUE);'; const subcategoryTableQuery: string = 'CREATE TABLE IF NOT EXISTS Subcategory(' + 'id INTEGER PRIMARY KEY,' + 'name TEXT NOT NULL,' + 'refCategory INTEGER NOT NULL,' + 'UNIQUE (name, refCategory),' + 'FOREIGN KEY(refCategory) REFERENCES Category(id));'; export const populationQueries: string[] = [ accountTableQuery, categoryTableQuery, subcategoryTableQuery ]; const accountDataset: string[] = [ 'INSERT INTO Account VALUES (1, \'test-account1\');', 'INSERT INTO Account VALUES (2, \'test-account2\');', 'INSERT INTO Account VALUES (3, \'test-account3\');' ]; const categoryDataset: string[] = [ 'INSERT INTO Category VALUES(1, \'test-cat1\');', 'INSERT INTO Category VALUES(2, \'test-cat2\');', 'INSERT INTO Category VALUES(3, \'test-cat3\');', 'INSERT INTO Subcategory VALUES(1, \'test-subcat-1.1\', 1);', 'INSERT INTO Subcategory VALUES(2, \'test-subcat-1.2\', 1);', 'INSERT INTO Subcategory VALUES(3, \'test-subcat-2.1\', 2);' ]; export const datasetQueries: string[] = accountDataset.concat(categoryDataset);
Fix unique constraint in Subcategory
Fix unique constraint in Subcategory
TypeScript
mit
DavidLevayer/countable,DavidLevayer/countable,DavidLevayer/countable
--- +++ @@ -11,8 +11,9 @@ const subcategoryTableQuery: string = 'CREATE TABLE IF NOT EXISTS Subcategory(' + 'id INTEGER PRIMARY KEY,' + - 'name TEXT NOT NULL UNIQUE,' + + 'name TEXT NOT NULL,' + 'refCategory INTEGER NOT NULL,' + + 'UNIQUE (name, refCategory),' + 'FOREIGN KEY(refCategory) REFERENCES Category(id));'; export const populationQueries: string[] = [
4f2ca1733ae9097f623d151dd0788679e14afd82
sql-template-strings/sql-template-strings.d.ts
sql-template-strings/sql-template-strings.d.ts
declare class SQLStatement { private strings: string[] /** The SQL Statement for node-postgres */ text: string /** The SQL Statement for mysql */ sql: string /** The values to be inserted for the placeholders */ values: any[] /** The name for postgres prepared statements, if set */ name: string /** Appends a string or another statement */ append(statement: SQLStatement|string|number): this /** Sets the name property of this statement for prepared statements in postgres */ setName(name: string): this } /** Template string tag */ export default function SQL(strings: string[], values: any[]): SQLStatement
import {QueryConfig} from "pg"; declare class SQLStatement implements QueryConfig { private strings: string[] /** The constructor used by the tag */ constructor(strings: string[], values: any[]); /** The SQL Statement for node-postgres */ text: string; /** The SQL Statement for mysql */ sql: string; /** The values to be inserted for the placeholders */ values: any[]; /** The name for postgres prepared statements, if set */ name: string; /** Appends a string or another statement */ append(statement: SQLStatement | string | number): this; /** Sets the name property of this statement for prepared statements in postgres */ setName(name: string): this; } /** Template string tag */ export default function SQL(strings: string[], values: any[]): SQLStatement;
Make sql-template-strings types compatibly with PG
Make sql-template-strings types compatibly with PG
TypeScript
mit
detroit-labs/typed-things
--- +++ @@ -1,26 +1,29 @@ +import {QueryConfig} from "pg"; -declare class SQLStatement { +declare class SQLStatement implements QueryConfig { + private strings: string[] - private strings: string[] + /** The constructor used by the tag */ + constructor(strings: string[], values: any[]); - /** The SQL Statement for node-postgres */ - text: string + /** The SQL Statement for node-postgres */ + text: string; - /** The SQL Statement for mysql */ - sql: string + /** The SQL Statement for mysql */ + sql: string; - /** The values to be inserted for the placeholders */ - values: any[] + /** The values to be inserted for the placeholders */ + values: any[]; - /** The name for postgres prepared statements, if set */ - name: string + /** The name for postgres prepared statements, if set */ + name: string; - /** Appends a string or another statement */ - append(statement: SQLStatement|string|number): this + /** Appends a string or another statement */ + append(statement: SQLStatement | string | number): this; - /** Sets the name property of this statement for prepared statements in postgres */ - setName(name: string): this + /** Sets the name property of this statement for prepared statements in postgres */ + setName(name: string): this; } /** Template string tag */ -export default function SQL(strings: string[], values: any[]): SQLStatement +export default function SQL(strings: string[], values: any[]): SQLStatement;
98270445b082c1cb038fb290f44ec32f4c0bddfe
src/app/model/loadstate.ts
src/app/model/loadstate.ts
export enum State { Loading = "Loading...", Ready = "Ready", EmptyFile = "File is empty", Fail = "Loading failed", TooLarge = "File is too large", } export class LoadState { public state: State; private _message: string; private buttonText; constructor(state: State, message?: string, buttonText?: string) { this.state = state; this._message = message; this.buttonText = buttonText; } get message() { return this._message ? this._message : this.state; } isReady(): boolean { return this.state === State.Ready; } }
export enum State { Loading = "Loading...", Ready = "Ready", EmptyFile = "File is empty", Fail = "Loading failed", TooLarge = "File is too large", } export class LoadState { public state: State; private _message: string; public buttonText; constructor(state: State, message?: string, buttonText?: string) { this.state = state; this._message = message; this.buttonText = buttonText; } get message() { return this._message ? this._message : this.state; } isReady(): boolean { return this.state === State.Ready; } }
Make a field public for aot
Make a field public for aot
TypeScript
mit
chipster/chipster-web,chipster/chipster-web,chipster/chipster-web
--- +++ @@ -9,7 +9,7 @@ export class LoadState { public state: State; private _message: string; - private buttonText; + public buttonText; constructor(state: State, message?: string, buttonText?: string) { this.state = state;
49c239a50caf43d7e19864cbefc6a267d825ea8a
app/events/event-thumbnail.component.ts
app/events/event-thumbnail.component.ts
import { Component, Input } from '@angular/core'; @Component({ moduleId: module.id, selector: 'event-thumbnail', templateUrl: 'event-thumbnail.component.html', styleUrls: ['event-thumbnail.component.css'] }) export class EventThumbnailComponent { @Input() event: any; getStartTimeStyle() { if (this.event && this.event.time === '8:00 am') { return { 'color': '#003300', 'font-weight': 'bold' } } if (this.event && this.event.time === '10:00 am') { return { 'color': 'red', 'font-weight': 'bold' } } return {}; } }
import { Component, Input } from '@angular/core'; @Component({ moduleId: module.id, selector: 'event-thumbnail', templateUrl: 'event-thumbnail.component.html', styleUrls: ['event-thumbnail.component.css'] }) export class EventThumbnailComponent { @Input() event: any; getStartTimeStyle():any { if (this.event && this.event.time === '8:00 am') { return { 'color': '#003300', 'font-weight': 'bold' } } if (this.event && this.event.time === '10:00 am') { return { 'color': 'red', 'font-weight': 'bold' } } return {}; } }
Fix bug: No best common type exists among return expressions
Fix bug: No best common type exists among return expressions
TypeScript
mit
robertoachar/ng2-fundamentals,robertoachar/ng2-fundamentals,robertoachar/ng2-fundamentals
--- +++ @@ -9,7 +9,7 @@ export class EventThumbnailComponent { @Input() event: any; - getStartTimeStyle() { + getStartTimeStyle():any { if (this.event && this.event.time === '8:00 am') { return { 'color': '#003300', 'font-weight': 'bold' } }
c15f7a69a0779399398ea776f10511f955a2e392
polygerrit-ui/app/services/flags/flags.ts
polygerrit-ui/app/services/flags/flags.ts
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {Finalizable} from '../registry'; export interface FlagsService extends Finalizable { isEnabled(experimentId: string): boolean; enabledExperiments: string[]; } /** * Experiment ids used in Gerrit. */ export enum KnownExperimentId { NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui', CHECKS_DEVELOPER = 'UiFeature__checks_developer', BULK_ACTIONS = 'UiFeature__bulk_actions_dashboard', DIFF_RENDERING_LIT = 'UiFeature__diff_rendering_lit', PUSH_NOTIFICATIONS = 'UiFeature__push_notifications', RELATED_CHANGES_SUBMITTABILITY = 'UiFeature__related_changes_submittability', MENTION_USERS = 'UIFeature_mention_users', }
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import {Finalizable} from '../registry'; export interface FlagsService extends Finalizable { isEnabled(experimentId: string): boolean; enabledExperiments: string[]; } /** * Experiment ids used in Gerrit. */ export enum KnownExperimentId { NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui', CHECKS_DEVELOPER = 'UiFeature__checks_developer', BULK_ACTIONS = 'UiFeature__bulk_actions_dashboard', DIFF_RENDERING_LIT = 'UiFeature__diff_rendering_lit', PUSH_NOTIFICATIONS = 'UiFeature__push_notifications', RELATED_CHANGES_SUBMITTABILITY = 'UiFeature__related_changes_submittability', MENTION_USERS = 'UiFeature__mention_users', }
Fix typo in experiment name
Fix typo in experiment name Release-Notes: skip Google-bug-id: b/236921879 Change-Id: Ib76a9022339996fbe5193a7c42924eeb29450aa9
TypeScript
apache-2.0
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
--- +++ @@ -20,5 +20,5 @@ DIFF_RENDERING_LIT = 'UiFeature__diff_rendering_lit', PUSH_NOTIFICATIONS = 'UiFeature__push_notifications', RELATED_CHANGES_SUBMITTABILITY = 'UiFeature__related_changes_submittability', - MENTION_USERS = 'UIFeature_mention_users', + MENTION_USERS = 'UiFeature__mention_users', }
73aae94c7f97ec019d56e96afb3afaa2ac15a9f9
client/app/accounts/services/current-account.service.ts
client/app/accounts/services/current-account.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class CurrentAccountService { set(token: string) { localStorage.setItem('jwt', token); } }
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; @Injectable() export class CurrentAccountService { private account = new Subject<string>(); set(token: string) { localStorage.setItem('jwt', token); this.account.next(token); } get(): Observable<string> { return this.account .asObservable() .startWith(localStorage.getItem('jwt')) ; } clear() { this.set(null); } }
Add get and clear methods
Add get and clear methods
TypeScript
mit
fvilers/angular2-training,fvilers/angular2-training,fvilers/angular2-training
--- +++ @@ -1,8 +1,24 @@ import { Injectable } from '@angular/core'; +import { Observable } from 'rxjs/Observable'; +import { Subject } from 'rxjs/Subject'; @Injectable() export class CurrentAccountService { + private account = new Subject<string>(); + set(token: string) { localStorage.setItem('jwt', token); + this.account.next(token); + } + + get(): Observable<string> { + return this.account + .asObservable() + .startWith(localStorage.getItem('jwt')) + ; + } + + clear() { + this.set(null); } }
a54e09991f51e720f350f766583a23e2d6e9302d
src/index.ts
src/index.ts
#!/usr/bin/env node
#!/usr/bin/env node import * as program from "commander"; program .arguments('message') .action(message => { console.log('Results: ', message); }) .parse(process.argv);
Make simple command line interface
Make simple command line interface
TypeScript
mit
martinhartt/messagelint,martinhartt/messagelint,martinhartt/messagelint
--- +++ @@ -1 +1,9 @@ #!/usr/bin/env node +import * as program from "commander"; + +program + .arguments('message') + .action(message => { + console.log('Results: ', message); + }) + .parse(process.argv);
8b23cec9b5bdc94ed7e02412b42080b7a0f884df
app/core/map.ts
app/core/map.ts
// Enum for the kind of map export type MapType = City | Square; interface City { kind: "city"; } interface Square { kind: "square"; } // Map class export class Map { constructor( private id?: number, private title?: string, private height: number, private width: number, private mapType: MapType, private owner?: number, private graphics?: string = "", private hash?: string, private dateCreation?: string, ) {} }
// Enum for the kind of map export type MapType = City | Square; interface City { kind: "city"; } interface Square { kind: "square"; } // Map class export class Map { constructor( private id: number, private height: number, private width: number, private mapType: MapType, private title?: string, private owner?: number, private graphics?: string, private hash?: string, private dateCreation?: string, ) {} }
Fix optional id for Map
Fix optional id for Map
TypeScript
mit
ABAPlan/abaplan-core,ABAPlan/abaplan-core,ABAPlan/abaplan-core
--- +++ @@ -6,13 +6,13 @@ // Map class export class Map { constructor( - private id?: number, - private title?: string, + private id: number, private height: number, private width: number, private mapType: MapType, + private title?: string, private owner?: number, - private graphics?: string = "", + private graphics?: string, private hash?: string, private dateCreation?: string, ) {}
bab9e0d57e0ba48bdedfe3315d1d7e3f30c55a0b
src/app/shared/footer/footer.component.ts
src/app/shared/footer/footer.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router' @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.sass'] }) export class FooterComponent { constructor(private router: Router) { } relativePos() { if (this.router.url === '/snippet/view') return true; else return false; } }
import { Component } from '@angular/core'; import { Router } from '@angular/router' @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.sass'] }) export class FooterComponent { constructor(private router: Router) { } relativePos() { if (this.router.url === '/snippet/view' || this.router.url === '/sign-up') return true; else return false; } }
Add another link to relativePos
Add another link to relativePos
TypeScript
apache-2.0
SamuelM333/snippet-sniper-frontend,SamuelM333/snippet-sniper-frontend,SamuelM333/snippet-sniper-frontend
--- +++ @@ -7,14 +7,14 @@ styleUrls: ['./footer.component.sass'] }) export class FooterComponent { - + constructor(private router: Router) { } - + relativePos() { - if (this.router.url === '/snippet/view') + if (this.router.url === '/snippet/view' || this.router.url === '/sign-up') return true; else return false; } - + }
13822e6ff92208c35a84ab9ddf1335319cd10a85
src/app/app/app-providers/map-source-providers/open-layers-IDAHO2-source-provider.ts
src/app/app/app-providers/map-source-providers/open-layers-IDAHO2-source-provider.ts
import { Injectable } from '@angular/core'; import { OpenLayerIDAHOSourceProvider } from './open-layers-IDAHO-source-provider'; export const OpenLayerIDAHO2SourceProviderSourceType = 'IDAHO2'; @Injectable() export class OpenLayerIDAHO2SourceProvider extends OpenLayerIDAHOSourceProvider { public sourceType = OpenLayerIDAHO2SourceProviderSourceType; }
import { Injectable } from '@angular/core'; import { OpenLayerIDAHOSourceProvider } from './open-layers-IDAHO-source-provider'; export const OpenLayerIDAHO2SourceProviderSourceType = 'IDAHO2'; // TODO: Remove "OpenLayerIDAHO2SourceProvider" when new valid source provider is added @Injectable() export class OpenLayerIDAHO2SourceProvider extends OpenLayerIDAHOSourceProvider { public sourceType = OpenLayerIDAHO2SourceProviderSourceType; }
Add TODO to remove this file
Add TODO to remove this file
TypeScript
mit
AnSyn/ansyn,AnSyn/ansyn,AnSyn/ansyn,AnSyn/ansyn
--- +++ @@ -2,7 +2,7 @@ import { OpenLayerIDAHOSourceProvider } from './open-layers-IDAHO-source-provider'; export const OpenLayerIDAHO2SourceProviderSourceType = 'IDAHO2'; - +// TODO: Remove "OpenLayerIDAHO2SourceProvider" when new valid source provider is added @Injectable() export class OpenLayerIDAHO2SourceProvider extends OpenLayerIDAHOSourceProvider { public sourceType = OpenLayerIDAHO2SourceProviderSourceType;
e4436a6e8c96b7cb5b6c8b34aa19dca6c21f2036
types/jest-each/index.d.ts
types/jest-each/index.d.ts
// Type definitions for jest-each 0.3 // Project: https://github.com/mattphillips/jest-each // Definitions by: Michael Utz <https://github.com/theutz> // Definitions: <https://github.com/DefinitelyTyped/DefinitelyTyped> // TypeScript Version: 2.1 export = JestEach; declare function JestEach(parameters: any[][]): JestEach.ReturnType; declare namespace JestEach { type SyncCallback = (...args: string[]) => void; type AsyncCallback = () => void; type TestCallback = SyncCallback | AsyncCallback; type TestFn = (name: string, fn: TestCallback) => void; type DescribeFn = (name: string, fn: SyncCallback) => void; interface TestObj { (name: string, fn: TestCallback): void; only: TestFn; skip: TestFn; } interface DescribeObj { (name: string, fn: DescribeFn): void; only: DescribeFn; skip: DescribeFn; } interface ReturnType { test: TestObj; it: TestObj; fit: TestFn; xit: TestFn; xtest: TestFn; describe: DescribeObj; fdescribe: DescribeFn; xdescribe: DescribeFn; } }
// Type definitions for jest-each 0.3 // Project: https://github.com/mattphillips/jest-each // Definitions by: Michael Utz <https://github.com/theutz> // Definitions: <https://github.com/DefinitelyTyped/DefinitelyTyped> // TypeScript Version: 2.1 export = JestEach; declare function JestEach(parameters: any[][]): JestEach.ReturnType; declare namespace JestEach { type SyncCallback = (...args: any[]) => void; type AsyncCallback = () => void; type TestCallback = SyncCallback | AsyncCallback; type TestFn = (name: string, fn: TestCallback) => void; type DescribeFn = (name: string, fn: SyncCallback) => void; interface TestObj { (name: string, fn: TestCallback): void; only: TestFn; skip: TestFn; } interface DescribeObj { (name: string, fn: DescribeFn): void; only: DescribeFn; skip: DescribeFn; } interface ReturnType { test: TestObj; it: TestObj; fit: TestFn; xit: TestFn; xtest: TestFn; describe: DescribeObj; fdescribe: DescribeFn; xdescribe: DescribeFn; } }
Fix test argument type for jest-each
Fix test argument type for jest-each
TypeScript
mit
magny/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,markogresak/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped
--- +++ @@ -9,7 +9,7 @@ declare function JestEach(parameters: any[][]): JestEach.ReturnType; declare namespace JestEach { - type SyncCallback = (...args: string[]) => void; + type SyncCallback = (...args: any[]) => void; type AsyncCallback = () => void; type TestCallback = SyncCallback | AsyncCallback;
3e3606ef0ada52d6d332354041007772afba6964
src/generic/network-options.ts
src/generic/network-options.ts
import social = require('../interfaces/social'); export var NETWORK_OPTIONS :{[name:string]:social.NetworkOptions} = { 'Google': { // Old GTalk XMPP provider, being deprecated. displayName: 'Google Hangouts', isFirebase: false, enableMonitoring: true, areAllContactsUproxy: false, supportsReconnect: true, supportsInvites: false, isExperimental: true }, 'Facebook': { // Old "v1" Facebook Firebase provider, being deprecated. isFirebase: true, enableMonitoring: true, areAllContactsUproxy: true, supportsReconnect: true, supportsInvites: false }, 'Facebook-Firebase-V2': { displayName: 'Facebook', isFirebase: true, enableMonitoring: true, areAllContactsUproxy: true, supportsReconnect: true, supportsInvites: true }, 'GMail': { isFirebase: true, enableMonitoring: true, areAllContactsUproxy: true, supportsReconnect: true, supportsInvites: true }, 'WeChat': { isFirebase: false, enableMonitoring: false, areAllContactsUproxy: false, supportsReconnect: false, supportsInvites: false, isExperimental: true } };
import social = require('../interfaces/social'); export var NETWORK_OPTIONS :{[name:string]:social.NetworkOptions} = { 'Google': { // Old GTalk XMPP provider, being deprecated. displayName: 'Google Hangouts', isFirebase: false, enableMonitoring: true, areAllContactsUproxy: false, supportsReconnect: true, supportsInvites: false, isExperimental: true }, 'Facebook': { // Old "v1" Facebook Firebase provider, being deprecated. isFirebase: true, enableMonitoring: true, areAllContactsUproxy: true, supportsReconnect: true, supportsInvites: false }, 'Facebook-Firebase-V2': { displayName: 'Facebook', isFirebase: true, enableMonitoring: true, areAllContactsUproxy: true, supportsReconnect: true, supportsInvites: true }, 'GMail': { isFirebase: true, enableMonitoring: true, areAllContactsUproxy: true, supportsReconnect: true, supportsInvites: true }, 'WeChat': { isFirebase: false, enableMonitoring: false, areAllContactsUproxy: false, supportsReconnect: false, supportsInvites: false, isExperimental: true }, 'GitHub': { isFirebase: false, enableMonitoring: false, areAllContactsUproxy: true, supportsReconnect: false, supportsInvites: true, isExperimental: true } };
Add GitHub to network options
Add GitHub to network options
TypeScript
apache-2.0
uProxy/uproxy,uProxy/uproxy,jpevarnek/uproxy,jpevarnek/uproxy,jpevarnek/uproxy,jpevarnek/uproxy,uProxy/uproxy,jpevarnek/uproxy,uProxy/uproxy,uProxy/uproxy
--- +++ @@ -39,5 +39,13 @@ supportsReconnect: false, supportsInvites: false, isExperimental: true + }, + 'GitHub': { + isFirebase: false, + enableMonitoring: false, + areAllContactsUproxy: true, + supportsReconnect: false, + supportsInvites: true, + isExperimental: true } };
3bb95e90f54b9a34145e6d2df7caf9ba806ec025
src/renderer/App.tsx
src/renderer/App.tsx
import React from 'react'; import { hot } from 'react-hot-loader'; import { MemoryRouter, Route, Redirect, Switch } from 'react-router-dom'; import { Provider } from 'react-redux'; import { ThemeProvider } from './styles/styled-components'; import { theme } from './styles/theme'; import configureStore from './store/configure'; const store = configureStore({}); import Editor from './screens/Editor'; import Welcome from './screens/Welcome'; import FileHandlerContainer from './containers/FileHandler'; import 'normalize.css'; import 'react-virtualized/styles.css'; import './styles/global.css'; const { subtitleReady, videoReady } = store.getState().welcome; const StartRoute = () => { if (subtitleReady && videoReady) { return <Redirect to="/editor" />; } return <Redirect to="/welcome" />; }; const App = () => ( <Provider store={store}> <ThemeProvider theme={theme}> <MemoryRouter> <> <Switch> <Route exact path="/" component={StartRoute} /> <Route path="/editor" component={Editor} /> <Route path="/welcome" component={Welcome} /> </Switch> <FileHandlerContainer /> </> </MemoryRouter> </ThemeProvider> </Provider> ); export default hot(module)(App);
import React from 'react'; import { hot } from 'react-hot-loader'; import { MemoryRouter, Route, Redirect, Switch } from 'react-router-dom'; import { Provider } from 'react-redux'; import { ThemeProvider } from './styles/styled-components'; import { theme } from './styles/theme'; import configureStore from './store/configure'; const store = configureStore({}); import Editor from './screens/Editor'; import Welcome from './screens/Welcome'; import FileHandlerContainer from './containers/FileHandler'; import 'normalize.css'; import 'react-virtualized/styles.css'; import GlobalStyle from './styles/global'; const { subtitleReady, videoReady } = store.getState().welcome; const StartRoute = () => { if (subtitleReady && videoReady) { return <Redirect to="/editor" />; } return <Redirect to="/welcome" />; }; const App = () => ( <Provider store={store}> <ThemeProvider theme={theme}> <MemoryRouter> <> <Switch> <Route exact path="/" component={StartRoute} /> <Route path="/editor" component={Editor} /> <Route path="/welcome" component={Welcome} /> </Switch> <FileHandlerContainer /> <GlobalStyle /> </> </MemoryRouter> </ThemeProvider> </Provider> ); export default hot(module)(App);
Use styled-components v4 global style
Use styled-components v4 global style
TypeScript
mit
Heeryong-Kang/jamak,Heeryong-Kang/jamak,drakang4/jamak,drakang4/jamak,drakang4/jamak
--- +++ @@ -14,7 +14,7 @@ import 'normalize.css'; import 'react-virtualized/styles.css'; -import './styles/global.css'; +import GlobalStyle from './styles/global'; const { subtitleReady, videoReady } = store.getState().welcome; @@ -37,6 +37,7 @@ <Route path="/welcome" component={Welcome} /> </Switch> <FileHandlerContainer /> + <GlobalStyle /> </> </MemoryRouter> </ThemeProvider>
705e948a1e8abe1e69fb34ff52785c7f8bd629f9
configloader.ts
configloader.ts
import RoutingServer from './routingserver'; export interface ConfigServer { listenPort: number; routingServers: RoutingServer[]; } export interface ConfigOptions { fakeVersion: boolean; fakeVersionNum: number; blockInvis: boolean; } export interface Config { servers: ConfigServer[]; options: ConfigOptions; } export const ConfigSettings: Config = require('./config.js').ConfigSettings;
import RoutingServer from './routingserver'; export interface ConfigServer { listenPort: number; routingServers: RoutingServer[]; } export interface ConfigOptions { fakeVersion: boolean; fakeVersionNum: number; blockInvis: boolean; } export interface Config { servers: ConfigServer[]; options: ConfigOptions; } export const ConfigSettings: Config = require(`../config.js`).ConfigSettings;
Use config.js from project main
Use config.js from project main
TypeScript
mit
popstarfreas/Dimensions,popstarfreas/Dimensions,popstarfreas/Dimensions
--- +++ @@ -17,4 +17,4 @@ } -export const ConfigSettings: Config = require('./config.js').ConfigSettings; +export const ConfigSettings: Config = require(`../config.js`).ConfigSettings;
0535d1cde172f579e1326d1dedfda37284a22f0e
packages/@orbit/core/src/main.ts
packages/@orbit/core/src/main.ts
import { assert } from './assert'; import { deprecate } from './deprecate'; import { uuid } from '@orbit/utils'; declare const self: any; declare const global: any; export interface OrbitGlobal { globals: any; assert: (description: string, test: boolean) => void | never; deprecate: (message: string, test?: boolean | (() => boolean)) => void; uuid: () => string; debug: boolean; } // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. // // Source: https://github.com/jashkenas/underscore/blob/master/underscore.js#L11-L17 // Underscore.js 1.8.3 // http://underscorejs.org // (c) 2009-2017 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. const globals = (typeof self == 'object' && self.self === self && self) || (typeof global == 'object' && global) || {}; export const Orbit: OrbitGlobal = { globals, assert, debug: true, deprecate, uuid };
import { assert } from './assert'; import { deprecate } from './deprecate'; import { uuid as customRandomUUID } from '@orbit/utils'; declare const self: any; declare const global: any; export interface OrbitGlobal { globals: any; assert: (description: string, test: boolean) => void | never; deprecate: (message: string, test?: boolean | (() => boolean)) => void; uuid: () => string; debug: boolean; } // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. // // Source: https://github.com/jashkenas/underscore/blob/master/underscore.js#L11-L17 // Underscore.js 1.8.3 // http://underscorejs.org // (c) 2009-2017 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. const globals = (typeof self == 'object' && self.self === self && self) || (typeof global == 'object' && global) || {}; const uuid = globals.crypto?.randomUUID !== undefined ? () => globals.crypto.randomUUID() : customRandomUUID; export const Orbit: OrbitGlobal = { globals, assert, debug: true, deprecate, uuid };
Use crypto.randomUUID by default for Orbit.uuid
Use crypto.randomUUID by default for Orbit.uuid A browser's built-in Crypto interface should provide the fastest and most secure UUID v4 implementation. Only default to the custom `uuid` function from `@orbit/utils` if `crypto.randomUUID` is not available.
TypeScript
mit
orbitjs/orbit.js,orbitjs/orbit.js
--- +++ @@ -1,6 +1,6 @@ import { assert } from './assert'; import { deprecate } from './deprecate'; -import { uuid } from '@orbit/utils'; +import { uuid as customRandomUUID } from '@orbit/utils'; declare const self: any; declare const global: any; @@ -27,6 +27,11 @@ (typeof global == 'object' && global) || {}; +const uuid = + globals.crypto?.randomUUID !== undefined + ? () => globals.crypto.randomUUID() + : customRandomUUID; + export const Orbit: OrbitGlobal = { globals, assert,
e087422b47a9e1836366df4b6701d3154943d9b0
src/support/path-utils.ts
src/support/path-utils.ts
/** * @license * Copyright (c) 2019 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 */ import {relative} from 'path'; export const ensureLeadingDot = (path: string): string => (path.startsWith('../') || path.startsWith('./')) ? path : './' + path; export const forwardSlashesOnlyPlease = (path: string): string => path.replace(/\\/g, '/'); export const getBasePath = (href: string): string => href.replace(/[^\/]+$/, ''); export const noLeadingSlash = (href: string): string => href.replace(/^\//, ''); export const relativePath = (from: string, to: string): string => { from = forwardSlashesOnlyPlease(from); to = forwardSlashesOnlyPlease(to); if (!from.endsWith('/')) { from = from.replace(/[^/]*$/, ''); } return ensureLeadingDot(relative(from, to)); };
/** * @license * Copyright (c) 2019 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 */ import {relative} from 'path'; export const ensureLeadingDot = (path: string): string => (path.startsWith('../') || path.startsWith('./')) ? path : './' + path; export const forwardSlashesOnlyPlease = (path: string): string => path.replace(/\\/g, '/'); export const getBasePath = (href: string): string => href.replace(/[^\/]+$/, ''); export const noLeadingSlash = (href: string): string => href.replace(/^\//, ''); export const relativePath = (from: string, to: string): string => { from = getBasePath(forwardSlashesOnlyPlease(from)); to = forwardSlashesOnlyPlease(to); return ensureLeadingDot(relative(from, to)); };
Use the getBasePath function instead of duplicate regexp.
Use the getBasePath function instead of duplicate regexp.
TypeScript
bsd-3-clause
Polymer/koa-node-resolve
--- +++ @@ -25,10 +25,7 @@ export const noLeadingSlash = (href: string): string => href.replace(/^\//, ''); export const relativePath = (from: string, to: string): string => { - from = forwardSlashesOnlyPlease(from); + from = getBasePath(forwardSlashesOnlyPlease(from)); to = forwardSlashesOnlyPlease(to); - if (!from.endsWith('/')) { - from = from.replace(/[^/]*$/, ''); - } return ensureLeadingDot(relative(from, to)); };
10699f14ad50ad04ea6aed9a959153a8acb989fd
app/touchpad/voice.service.ts
app/touchpad/voice.service.ts
import { Injectable } from '@angular/core'; import artyomjs = require('artyom.js'); @Injectable() export class VoiceService { private voiceProvider: IVoiceProvider = new ArtyomProvider(); constructor() { } public say(text: string) { console.log("Saying: ", text); this.voiceProvider.say(text); } public sayGeocodeResult(result : /*google.maps.GeocoderResult*/any) { const address = result.address_components[0].long_name + ' '+ result.address_components[1].long_name; this.voiceProvider.say(address); } } interface IVoiceProvider { say(text: string): void; } class ArtyomProvider implements IVoiceProvider { readonly artyom = artyomjs.ArtyomBuilder.getInstance(); constructor() { this.artyom.initialize({ lang: "fr-FR", // GreatBritain english continuous: false, // Listen forever soundex: true,// Use the soundex algorithm to increase accuracy debug: true, // Show messages in the console listen: false // Start to listen commands ! }); } public say(text: string): void { this.artyom.say(text); } }
import { Injectable } from '@angular/core'; import artyomjs = require('artyom.js'); @Injectable() export class VoiceService { private voiceProvider: IVoiceProvider = new ArtyomProvider(); constructor() { } public say(text: string) { console.log("Saying: ", text); this.voiceProvider.say(text); } public sayGeocodeResult(result : /*google.maps.GeocoderResult*/any) { const address = result.address_components[0].long_name + ' '+ result.address_components[1].long_name; this.say(address); } } interface IVoiceProvider { say(text: string): void; } class ArtyomProvider implements IVoiceProvider { readonly artyom = artyomjs.ArtyomBuilder.getInstance(); constructor() { this.artyom.initialize({ lang: "fr-FR", // GreatBritain english continuous: false, // Listen forever soundex: true,// Use the soundex algorithm to increase accuracy debug: true, // Show messages in the console listen: false // Start to listen commands ! }); } public say(text: string): void { this.artyom.say(text); } }
Use inner method insteand of provider in sayGeocodeResult
Use inner method insteand of provider in sayGeocodeResult
TypeScript
mit
ABAPlan/abaplan-core,ABAPlan/abaplan-core,ABAPlan/abaplan-core
--- +++ @@ -17,7 +17,7 @@ public sayGeocodeResult(result : /*google.maps.GeocoderResult*/any) { const address = result.address_components[0].long_name + ' '+ result.address_components[1].long_name; - this.voiceProvider.say(address); + this.say(address); } }
b3afad9b86b264e6ee0f21ea5619bb6da4ed8e5e
src/components/login_header.tsx
src/components/login_header.tsx
import * as React from "react" import styled from "styled-components" import Icon from "./icons" const Header = styled.header` margin: 20px; font-size: 26px; line-height: 1.3; text-align: center; ` export default class LoginHeader extends React.Component<any, null> { render() { return ( <div> <Header> <Icon name={"logotype"} color={"black"} /> </Header> </div> ) } }
import * as React from "react" import styled from "styled-components" import Icon from "./icon" const Header = styled.header` margin: 20px; font-size: 26px; line-height: 1.3; text-align: center; ` export default class LoginHeader extends React.Component<any, null> { render() { return ( <div> <Header> <Icon name={"logotype"} color={"black"} /> </Header> </div> ) } }
Fix the storybook for LoginHeader
Fix the storybook for LoginHeader
TypeScript
mit
xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction,craigspaeth/reaction,artsy/reaction-force,artsy/reaction,craigspaeth/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction,craigspaeth/reaction,artsy/reaction-force
--- +++ @@ -1,6 +1,6 @@ import * as React from "react" import styled from "styled-components" -import Icon from "./icons" +import Icon from "./icon" const Header = styled.header` margin: 20px;
99db9bdfb159f93688e57722eb3876f12fa96367
tests/__tests__/import.spec.ts
tests/__tests__/import.spec.ts
import { } from 'jest'; import { } from 'node'; import runJest from '../__helpers__/runJest'; describe('import with relative and absolute paths', () => { it('should run successfully', () => { const result = runJest('../imports-test', ['--no-cache']); const stderr = result.stderr.toString(); const output = result.output.toString(); expect(result.status).toBe(1); expect(output).toContain('4 failed, 4 total'); expect(stderr).toContain('at new Hello (src\\classes\\Hello.ts:11:11)'); expect(stderr).toContain('at Object.<anonymous> (__tests__\\classes\\Hello.test.ts:9:19)'); expect(stderr).toContain('at Object.<anonymous> (__tests__\\classes\\Hello-relative.test.ts:9:19)'); expect(stderr).toContain('at Object.simpleFunction (src\\absolute-import.ts:4:17)'); expect(stderr).toContain('at Object.<anonymous> (__tests__\\absolute-import.test.ts:8:9)'); expect(stderr).toContain('at Object.simpleFunction (src\\relative-import.ts:4:17)'); expect(stderr).toContain('at Object.<anonymous> (__tests__\\relative-import.test.ts:8:9)'); }); });
import { } from 'jest'; import { } from 'node'; import * as path from 'path'; import runJest from '../__helpers__/runJest'; describe('import with relative and absolute paths', () => { it('should run successfully', () => { const result = runJest('../imports-test', ['--no-cache']); const stderr = result.stderr.toString(); const output = result.output.toString(); expect(result.status).toBe(1); expect(output).toContain('4 failed, 4 total'); expect(stderr).toContain('at new Hello (src' + path.sep + 'classes' + path.sep + 'Hello.ts:11:11)'); expect(stderr).toContain('at Object.<anonymous> (__tests__' + path.sep + 'classes' + path.sep + 'Hello.test.ts:9:19)'); expect(stderr).toContain('at Object.<anonymous> (__tests__' + path.sep + 'classes' + path.sep + 'Hello-relative.test.ts:9:19)'); expect(stderr).toContain('at Object.simpleFunction (src' + path.sep + 'absolute-import.ts:4:17)'); expect(stderr).toContain('at Object.<anonymous> (__tests__' + path.sep + 'absolute-import.test.ts:8:9)'); expect(stderr).toContain('at Object.simpleFunction (src' + path.sep + 'relative-import.ts:4:17)'); expect(stderr).toContain('at Object.<anonymous> (__tests__' + path.sep + 'relative-import.test.ts:8:9)'); }); });
Fix for wrong path separator for *nix
Fix for wrong path separator for *nix
TypeScript
mit
kulshekhar/ts-jest,kulshekhar/ts-jest
--- +++ @@ -1,5 +1,6 @@ import { } from 'jest'; import { } from 'node'; +import * as path from 'path'; import runJest from '../__helpers__/runJest'; describe('import with relative and absolute paths', () => { @@ -14,16 +15,16 @@ expect(result.status).toBe(1); expect(output).toContain('4 failed, 4 total'); - expect(stderr).toContain('at new Hello (src\\classes\\Hello.ts:11:11)'); + expect(stderr).toContain('at new Hello (src' + path.sep + 'classes' + path.sep + 'Hello.ts:11:11)'); - expect(stderr).toContain('at Object.<anonymous> (__tests__\\classes\\Hello.test.ts:9:19)'); - expect(stderr).toContain('at Object.<anonymous> (__tests__\\classes\\Hello-relative.test.ts:9:19)'); + expect(stderr).toContain('at Object.<anonymous> (__tests__' + path.sep + 'classes' + path.sep + 'Hello.test.ts:9:19)'); + expect(stderr).toContain('at Object.<anonymous> (__tests__' + path.sep + 'classes' + path.sep + 'Hello-relative.test.ts:9:19)'); - expect(stderr).toContain('at Object.simpleFunction (src\\absolute-import.ts:4:17)'); - expect(stderr).toContain('at Object.<anonymous> (__tests__\\absolute-import.test.ts:8:9)'); + expect(stderr).toContain('at Object.simpleFunction (src' + path.sep + 'absolute-import.ts:4:17)'); + expect(stderr).toContain('at Object.<anonymous> (__tests__' + path.sep + 'absolute-import.test.ts:8:9)'); - expect(stderr).toContain('at Object.simpleFunction (src\\relative-import.ts:4:17)'); - expect(stderr).toContain('at Object.<anonymous> (__tests__\\relative-import.test.ts:8:9)'); + expect(stderr).toContain('at Object.simpleFunction (src' + path.sep + 'relative-import.ts:4:17)'); + expect(stderr).toContain('at Object.<anonymous> (__tests__' + path.sep + 'relative-import.test.ts:8:9)'); }); });
301cacc736cc933f26e08f7abb4051796cb2ae1f
src/app/home/home.component.ts
src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { MdDialog } from '@angular/material'; import { CreateChallengeDialog, SelectTrainingPathDialog } from './../dialogs'; import { UserService } from './../core/services/user.service'; @Component({ templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { event: string; constructor(private router: Router, public dialog: MdDialog, public userSrv: UserService) { } ngOnInit() { this.event = this.userSrv.getUserContext().event; } startIndividual() { this.router.navigate(['/individual']); } startTraining() { this.dialog.open(SelectTrainingPathDialog); } startChallenge() { this.dialog.open(CreateChallengeDialog); } }
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { MdDialog } from '@angular/material'; import { CreateChallengeDialog, SelectTrainingPathDialog } from './../dialogs'; import { UserService } from './../core/services/user.service'; @Component({ templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { event: string; constructor(private router: Router, public dialog: MdDialog, public userSrv: UserService) { } ngOnInit() { this.event = (this.userSrv.getUserContext()) ? this.userSrv.getUserContext().event : ''; } startIndividual() { this.router.navigate(['/individual']); } startTraining() { this.dialog.open(SelectTrainingPathDialog); } startChallenge() { this.dialog.open(CreateChallengeDialog); } }
Hide training option in event mode
Hide training option in event mode
TypeScript
mit
semagarcia/javascript-kata-player,semagarcia/javascript-kata-player,semagarcia/javascript-kata-player
--- +++ @@ -14,7 +14,7 @@ constructor(private router: Router, public dialog: MdDialog, public userSrv: UserService) { } ngOnInit() { - this.event = this.userSrv.getUserContext().event; + this.event = (this.userSrv.getUserContext()) ? this.userSrv.getUserContext().event : ''; } startIndividual() {
0a97097d862af24a9c2c834391fea70234a54082
src/selectors/available-hours.ts
src/selectors/available-hours.ts
import {createSelector} from 'reselect' import uniqWith from 'lodash-es/uniqWith' import * as moment from 'moment' import {availableTimeSelector} from './available-time' import {IDropdownOptions, IRootState} from '../types' export const availableHoursSelector = createSelector( availableTimeSelector, (state: IRootState) => state.footage.tmpDate, (times: number[], tmpDate: string | null): IDropdownOptions[] => { if (!tmpDate) { return [] } const day = moment(tmpDate) const matchedTimes = times .map(time => moment(time)) // Change all object to moment object .filter(time => time.isSame(day, 'day')) // Filter: Only same date can keep here const uniqTimes: typeof matchedTimes = uniqWith(matchedTimes, (a: moment.Moment, b: moment.Moment) => a.isSame(b, 'hour') ) return uniqTimes.map(time => ({ label: time.format('HH'), value: time.format('HH') })) } )
import {createSelector} from 'reselect' import uniqWith from 'lodash-es/uniqWith' import * as moment from 'moment' import {availableTimeSelector} from './available-time' import {IDropdownOptions} from '../types' import {tmpDateSelector} from './tmp-date' export const availableHoursSelector = createSelector( availableTimeSelector, tmpDateSelector, (times: number[], tmpDate: moment.Moment): IDropdownOptions[] => { const matchedTimes = times .map(time => moment(time)) // Change all object to moment object .filter(time => time.isSame(tmpDate, 'day')) // Filter: Only same date can keep here const uniqTimes: typeof matchedTimes = uniqWith(matchedTimes, (a: moment.Moment, b: moment.Moment) => a.isSame(b, 'hour') ) return uniqTimes.map(time => ({ label: time.format('HH'), value: time.format('HH') })) } )
Fix no hour available on first render
Fix no hour available on first render
TypeScript
mit
jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend
--- +++ @@ -2,19 +2,16 @@ import uniqWith from 'lodash-es/uniqWith' import * as moment from 'moment' import {availableTimeSelector} from './available-time' -import {IDropdownOptions, IRootState} from '../types' +import {IDropdownOptions} from '../types' +import {tmpDateSelector} from './tmp-date' export const availableHoursSelector = createSelector( availableTimeSelector, - (state: IRootState) => state.footage.tmpDate, - (times: number[], tmpDate: string | null): IDropdownOptions[] => { - if (!tmpDate) { - return [] - } - const day = moment(tmpDate) + tmpDateSelector, + (times: number[], tmpDate: moment.Moment): IDropdownOptions[] => { const matchedTimes = times .map(time => moment(time)) // Change all object to moment object - .filter(time => time.isSame(day, 'day')) // Filter: Only same date can keep here + .filter(time => time.isSame(tmpDate, 'day')) // Filter: Only same date can keep here const uniqTimes: typeof matchedTimes = uniqWith(matchedTimes, (a: moment.Moment, b: moment.Moment) => a.isSame(b, 'hour') )
c5d98f9f95bfd779bbc936655583dbab613c6991
src/app/loadout/armor-upgrade-utils.ts
src/app/loadout/armor-upgrade-utils.ts
import { AssumeArmorMasterwork, LockArmorEnergyType } from '@destinyitemmanager/dim-api-types'; import { DimItem } from 'app/inventory/item-types'; import { ArmorEnergyRules } from 'app/loadout-builder/types'; /** Gets the max energy allowed from the passed in UpgradeSpendTier */ export function calculateAssumedItemEnergy( item: DimItem, { assumeArmorMasterwork, minItemEnergy }: ArmorEnergyRules ) { const itemEnergy = item.energy?.energyCapacity || minItemEnergy; const assumedEnergy = assumeArmorMasterwork === AssumeArmorMasterwork.All || (assumeArmorMasterwork === AssumeArmorMasterwork.Legendary && !item.isExotic) ? 10 : minItemEnergy; return Math.max(itemEnergy, assumedEnergy); } export function isArmorEnergyLocked( item: DimItem, { lockArmorEnergyType, loadouts }: ArmorEnergyRules ) { switch (lockArmorEnergyType) { case LockArmorEnergyType.None: { return false; } case LockArmorEnergyType.Masterworked: { const { loadoutsByItem, optimizingLoadoutId } = loadouts!; return loadoutsByItem[item.id]?.some( (l) => l.loadoutItem.equip && l.loadout.id !== optimizingLoadoutId ); } case LockArmorEnergyType.All: { return true; } } }
import { AssumeArmorMasterwork, LockArmorEnergyType } from '@destinyitemmanager/dim-api-types'; import { DimItem } from 'app/inventory/item-types'; import { ArmorEnergyRules } from 'app/loadout-builder/types'; /** Gets the max energy allowed from the passed in UpgradeSpendTier */ export function calculateAssumedItemEnergy( item: DimItem, { assumeArmorMasterwork, minItemEnergy }: ArmorEnergyRules ) { const itemEnergy = item.energy?.energyCapacity || minItemEnergy; const assumedEnergy = assumeArmorMasterwork === AssumeArmorMasterwork.All || (assumeArmorMasterwork === AssumeArmorMasterwork.Legendary && !item.isExotic) ? 10 : minItemEnergy; return Math.max(itemEnergy, assumedEnergy); } export function isArmorEnergyLocked( item: DimItem, { lockArmorEnergyType, loadouts }: ArmorEnergyRules ) { switch (lockArmorEnergyType) { default: case LockArmorEnergyType.None: { return false; } case LockArmorEnergyType.Masterworked: { const { loadoutsByItem, optimizingLoadoutId } = loadouts!; return loadoutsByItem[item.id]?.some( (l) => l.loadoutItem.equip && l.loadout.id !== optimizingLoadoutId ); } case LockArmorEnergyType.All: { return true; } } }
Add default case to isArmorEnergyLocked
Add default case to isArmorEnergyLocked
TypeScript
mit
DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM
--- +++ @@ -21,6 +21,7 @@ { lockArmorEnergyType, loadouts }: ArmorEnergyRules ) { switch (lockArmorEnergyType) { + default: case LockArmorEnergyType.None: { return false; }
124810bd7686d4561c8fa1543fa296ca885eebf2
src/app/modules/AutomatedPOS/index.tsx
src/app/modules/AutomatedPOS/index.tsx
import * as React from 'react' import { AutomatedPOS as Component } from '~/components/AutomatedPOS' const txt = ( 'The book theorized that sufficiently intense competition for suburban houses in ' + 'good school districts meant that people had to throw away lots of other values – ' + 'time at home with their children, financial security – to optimize for ' + 'house-buying-ability or else be consigned to the ghetto.' ) export const AutomatedPOS = () => ( <div> <br /> <Component text='This is a sentence' /> <br /> <Component text={txt} /> </div> )
import * as React from 'react' import { AutomatedPOS as Component } from '~/components/AutomatedPOS' const txt1 = ( 'The book theorized that sufficiently intense competition for suburban houses in ' + 'good school districts meant that people had to throw away lots of other values – ' + 'time at home with their children, financial security – to optimize for ' + 'house-buying-ability or else be consigned to the ghetto.' ) const txt2 = ( 'Reading, like any human activity, has a history. Modern reading is a silent and solitary ' + 'activity. Ancient reading was usually oral, either aloud, in groups, or individually, in ' + 'a muffled voice. The text format in which thought has been presented to readers has ' + 'undergone many changes in order to reach the form that the modern Western reader now ' + 'views as immutable and nearly universal. This book explains how a change in writing—the ' + 'introduction of word separation—led to the development of silent reading during the period ' + 'from late antiquity to the fifteenth century.' ) export const AutomatedPOS = () => ( <div> <br /> <Component text='This is a sentence' /> <br /> <Component text={txt1} /> <br /> <Component text={txt2} /> </div> )
Add AutomatedPOS "History of Reading" example
Add AutomatedPOS "History of Reading" example
TypeScript
mit
devonzuegel/aldine,devonzuegel/aldine,devonzuegel/aldine,devonzuegel/aldine
--- +++ @@ -1,17 +1,28 @@ import * as React from 'react' import { AutomatedPOS as Component } from '~/components/AutomatedPOS' -const txt = ( +const txt1 = ( 'The book theorized that sufficiently intense competition for suburban houses in ' + 'good school districts meant that people had to throw away lots of other values – ' + 'time at home with their children, financial security – to optimize for ' + 'house-buying-ability or else be consigned to the ghetto.' +) +const txt2 = ( + 'Reading, like any human activity, has a history. Modern reading is a silent and solitary ' + + 'activity. Ancient reading was usually oral, either aloud, in groups, or individually, in ' + + 'a muffled voice. The text format in which thought has been presented to readers has ' + + 'undergone many changes in order to reach the form that the modern Western reader now ' + + 'views as immutable and nearly universal. This book explains how a change in writing—the ' + + 'introduction of word separation—led to the development of silent reading during the period ' + + 'from late antiquity to the fifteenth century.' ) export const AutomatedPOS = () => ( <div> <br /> <Component text='This is a sentence' /> <br /> - <Component text={txt} /> + <Component text={txt1} /> + <br /> + <Component text={txt2} /> </div> )
ed55b8bff43d9765bd0d4d92df66bda0f53be155
src/main/webapp/app/admin/elasticsearch-reindex/elasticsearch-reindex-modal.component.ts
src/main/webapp/app/admin/elasticsearch-reindex/elasticsearch-reindex-modal.component.ts
import { Component } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ElasticsearchReindexService } from './elasticsearch-reindex.service'; @Component({ selector: 'jhi-elasticsearch-reindex-modal', templateUrl: './elasticsearch-reindex-modal.component.html' }) export class ElasticsearchReindexModalComponent { constructor( private elasticsearchReindexService: ElasticsearchReindexService, public activeModal: NgbActiveModal) { } reindex() { this.elasticsearchReindexService.reindex().subscribe(); this.activeModal.dismiss(true); } }
import { Component } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { AlertService } from 'ng-jhipster'; import { ElasticsearchReindexService } from './elasticsearch-reindex.service'; @Component({ selector: 'jhi-elasticsearch-reindex-modal', templateUrl: './elasticsearch-reindex-modal.component.html' }) export class ElasticsearchReindexModalComponent { constructor( private elasticsearchReindexService: ElasticsearchReindexService, public activeModal: NgbActiveModal, private alertService: AlertService ) { } reindex() { this.elasticsearchReindexService.reindex().subscribe(); this.activeModal.dismiss(true); this.alertService.info('elasticsearch.reindex.accepted', null, null); } }
Add alert when launching elasticsearch reindex
Add alert when launching elasticsearch reindex
TypeScript
apache-2.0
pascalgrimaud/qualitoast,pascalgrimaud/qualitoast,pascalgrimaud/qualitoast,pascalgrimaud/qualitoast,pascalgrimaud/qualitoast
--- +++ @@ -1,5 +1,6 @@ import { Component } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { AlertService } from 'ng-jhipster'; import { ElasticsearchReindexService } from './elasticsearch-reindex.service'; @@ -11,10 +12,13 @@ constructor( private elasticsearchReindexService: ElasticsearchReindexService, - public activeModal: NgbActiveModal) { } + public activeModal: NgbActiveModal, + private alertService: AlertService + ) { } reindex() { this.elasticsearchReindexService.reindex().subscribe(); this.activeModal.dismiss(true); + this.alertService.info('elasticsearch.reindex.accepted', null, null); } }
af911f7e4abf8777c85453d6f5680bba9ed53213
types/react-inlinesvg/index.d.ts
types/react-inlinesvg/index.d.ts
// Type definitions for react-inlinesvg 0.8.3 // Project: https://github.com/gilbarbara/react-inlinesvg#readme // Definitions by: MyCrypto <https://github.com/MyCryptoHQ>, Nick <https://github.com/nickmccurdy> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { ComponentType, ReactNode } from 'react'; export interface RequestError extends Error { isHttpError: boolean; status: number; } export interface InlineSVGError extends Error { name: 'InlineSVGError'; isSupportedBrowser: boolean; isConfigurationError: boolean; isUnsupportedBrowserError: boolean; message: string; } export interface Props { baseURL?: string; cacheGetRequests?: boolean; children?: ReactNode; className?: string; preloader?: ReactNode; src: URL | string; style?: object; uniqueHash?: string; uniquifyIDs?: boolean; onError?(error: RequestError | InlineSVGError): void; onLoad?(src: URL | string, isCached: boolean): void; supportTest?(): void; wrapper?(): ReactNode; } declare const InlineSVG: ComponentType<Props>; export default InlineSVG;
// Type definitions for react-inlinesvg 0.8.3 // Project: https://github.com/gilbarbara/react-inlinesvg#readme // Definitions by: MyCrypto <https://github.com/MyCryptoHQ>, Nick <https://github.com/nickmccurdy> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { ComponentType, ReactNode } from 'react'; export interface RequestError extends Error { isHttpError: boolean; status: number; } export interface InlineSVGError extends Error { name: 'InlineSVGError'; isSupportedBrowser: boolean; isConfigurationError: boolean; isUnsupportedBrowserError: boolean; message: string; } export interface Props { baseURL?: string; cacheGetRequests?: boolean; children?: ReactNode; className?: string; preloader?: ReactNode; src: URL | string; style?: object; uniqueHash?: string; uniquifyIDs?: boolean; onError?(error: RequestError | InlineSVGError): void; onLoad?(src: URL | string, isCached: boolean): void; supportTest?(): void; wrapper?(): ReactNode; } declare const InlineSVG: ComponentType<Props>; export default InlineSVG;
Use React's minimum TypeScript version
Use React's minimum TypeScript version
TypeScript
mit
borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped
--- +++ @@ -2,6 +2,7 @@ // Project: https://github.com/gilbarbara/react-inlinesvg#readme // Definitions by: MyCrypto <https://github.com/MyCryptoHQ>, Nick <https://github.com/nickmccurdy> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 import { ComponentType, ReactNode } from 'react';
51f3679642a5ec3803a284ed68f612ffa49d17c6
packages/puppeteer/src/index.ts
packages/puppeteer/src/index.ts
import { Webdriver } from 'mugshot'; import { Page } from 'puppeteer'; /** * Webdriver adapter over [Puppeteer](https://github.com/puppeteer/puppeteer) * to be used with [[WebdriverScreenshotter]]. * * @see https://github.com/puppeteer/puppeteer/blob/v2.0.0/docs/api.md */ export default class PuppeteerAdapter implements Webdriver { constructor(private readonly page: Page) {} getElementRect = async (selector: string) => { const elements = await this.page.$$(selector); if (!elements.length) { return null; } const rects = await Promise.all( elements.map(async (element) => { const rect = await element.boundingBox(); if (!rect) { return { x: 0, y: 0, width: 0, height: 0 }; } return rect; }) ); return rects.length === 1 ? rects[0] : rects; }; setViewportSize = (width: number, height: number) => this.page.setViewport({ width, height, }); takeScreenshot = () => this.page.screenshot(); execute = <R, A extends any[]>(func: (...args: A) => R, ...args: A) => this.page.evaluate( // @ts-expect-error the puppeteer type expects at least 1 argument func, ...args ); }
import { Webdriver } from 'mugshot'; import { Page } from 'puppeteer'; /** * Webdriver adapter over [Puppeteer](https://github.com/puppeteer/puppeteer) * to be used with [[WebdriverScreenshotter]]. * * @see https://github.com/puppeteer/puppeteer/blob/v2.0.0/docs/api.md */ export default class PuppeteerAdapter implements Webdriver { constructor(private readonly page: Page) {} getElementRect = async (selector: string) => { const elements = await this.page.$$(selector); if (!elements.length) { return null; } const rects = await Promise.all( elements.map(async (element) => { const rect = await element.boundingBox(); if (!rect) { return { x: 0, y: 0, width: 0, height: 0 }; } return rect; }) ); return rects.length === 1 ? rects[0] : rects; }; setViewportSize = (width: number, height: number) => this.page.setViewport({ width, height, }); takeScreenshot = async () => // The puppeteer type returns Buffer | string depending on the encoding, // but does not discriminate on it. It can also return void if the screenshot // fails. (await (this.page.screenshot() as Promise<Buffer>)).toString('base64'); execute = <R, A extends any[]>(func: (...args: A) => R, ...args: A) => this.page.evaluate( // @ts-expect-error the puppeteer type expects at least 1 argument func, ...args ); }
Use type assertion for screenshot promise
refactor: Use type assertion for screenshot promise
TypeScript
mit
uberVU/mugshot,uberVU/mugshot
--- +++ @@ -38,7 +38,11 @@ height, }); - takeScreenshot = () => this.page.screenshot(); + takeScreenshot = async () => + // The puppeteer type returns Buffer | string depending on the encoding, + // but does not discriminate on it. It can also return void if the screenshot + // fails. + (await (this.page.screenshot() as Promise<Buffer>)).toString('base64'); execute = <R, A extends any[]>(func: (...args: A) => R, ...args: A) => this.page.evaluate(
d80d1fdbb3b2321dada90609313e61997ebc243f
src/app/_shared/animations.ts
src/app/_shared/animations.ts
import { transition, trigger, style, state, animate } from '@angular/animations'; export const slideIn = trigger('slideIn', [ state('*', style({ opacity: 1, transform: 'scaleY(1)' })), state('void', style({ opacity: 0, transform: 'scaleY(0)' })), transition('* => void', animate('250ms ease-out')), transition('void => *', animate('250ms ease-in')) ]); export const fade = trigger('fade', [ state('*', style({ opacity: 1, })), state('void', style({ opacity: 0, })), transition('* => void', animate('250ms ease-out')), transition('void => *', animate('250ms ease-in')) ]);
import { transition, trigger, style, state, animate, group } from '@angular/animations'; export const slideIn = trigger('slideIn', [ state('*', style({ opacity: 1, transform: 'scaleY(1)' })), state('void', style({ opacity: 0, transform: 'scaleY(0.6)' })), transition('* => void', animate('250ms ease-out')), transition('void => *', animate('250ms ease-in')) ]); export const fade = trigger('fade', [ state('*', style({ opacity: 1, })), state('void', style({ opacity: 0, })), transition('* => void', animate('250ms ease-out')), transition('void => *', animate('250ms ease-in')) ]);
Set slidein animation back to .6 height
Set slidein animation back to .6 height
TypeScript
mit
bluecaret/carettab,bluecaret/carettab,bluecaret/carettab
--- +++ @@ -1,4 +1,4 @@ -import { transition, trigger, style, state, animate } from '@angular/animations'; +import { transition, trigger, style, state, animate, group } from '@angular/animations'; export const slideIn = trigger('slideIn', [ state('*', style({ @@ -7,7 +7,7 @@ })), state('void', style({ opacity: 0, - transform: 'scaleY(0)' + transform: 'scaleY(0.6)' })), transition('* => void', animate('250ms ease-out')), transition('void => *', animate('250ms ease-in'))
dc8cd68cfa37b201ea850076bcad162f530ba885
src/app/leaflet-geocoder/leaflet-geocoder.component.ts
src/app/leaflet-geocoder/leaflet-geocoder.component.ts
/*! * Leaflet Geocoder Component * * Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> * Licensed under MIT */ import { Component, OnInit, ViewChild } from '@angular/core'; import { Map, Control } from 'leaflet'; import { LeafletMapService } from '../leaflet-map.service'; import 'leaflet-control-geocoder2'; @Component({ selector: 'app-leaflet-geocoder', templateUrl: './leaflet-geocoder.component.html', styleUrls: ['./leaflet-geocoder.component.sass'] }) export class LeafletGeocoderComponent implements OnInit { public control: Control; @ViewChild('controlwrapper') controlWrapper; constructor(private _mapService: LeafletMapService) { } ngOnInit() { // prevent 'Control' is not a propery of L let controlObj = (L as any).Control; this.control = controlObj .geocoder({ collapsed: false, placeholder: 'Find a place...', geocoder: new controlObj.Geocoder.Nominatim({ geocodingQueryParams: { countrycodes: 'ph' } }) }) ; this._mapService .getMap() .then((map: Map) => { // add to the wrapper this.controlWrapper.nativeElement.appendChild(this.control.onAdd(map)); }) ; } }
/*! * Leaflet Geocoder Component * * Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> * Licensed under MIT */ import { Component, OnInit, OnChanges, ViewChild, Input } from '@angular/core'; import { Map, Control } from 'leaflet'; import { LeafletMapService } from '../leaflet-map.service'; import 'leaflet-control-geocoder2'; @Component({ selector: 'app-leaflet-geocoder', templateUrl: './leaflet-geocoder.component.html', styleUrls: ['./leaflet-geocoder.component.sass'] }) export class LeafletGeocoderComponent implements OnInit, OnChanges { public control: Control; @Input() placeholder: string = 'Find a place...'; @ViewChild('controlwrapper') controlWrapper; constructor(private _mapService: LeafletMapService) { } ngOnInit() { // prevent 'Control' is not a propery of L let controlObj = (L as any).Control; this.control = controlObj .geocoder({ collapsed: false, placeholder: this.placeholder, geocoder: new controlObj.Geocoder.Nominatim({ geocodingQueryParams: { countrycodes: 'ph' } }) }) ; this._mapService .getMap() .then((map: Map) => { // add to the wrapper this.controlWrapper.nativeElement.appendChild(this.control.onAdd(map)); }) ; } ngOnChanges(changes) { // detect the change on the placeholder input if (typeof this.control !== 'undefined') { (this.control as any)._input.placeholder = changes.placeholder.currentValue; } } }
Make geocode input placeholder dynamic
Make geocode input placeholder dynamic
TypeScript
mit
ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2
--- +++ @@ -5,7 +5,7 @@ * Licensed under MIT */ -import { Component, OnInit, ViewChild } from '@angular/core'; +import { Component, OnInit, OnChanges, ViewChild, Input } from '@angular/core'; import { Map, Control } from 'leaflet'; import { LeafletMapService } from '../leaflet-map.service'; import 'leaflet-control-geocoder2'; @@ -15,9 +15,10 @@ templateUrl: './leaflet-geocoder.component.html', styleUrls: ['./leaflet-geocoder.component.sass'] }) -export class LeafletGeocoderComponent implements OnInit { +export class LeafletGeocoderComponent implements OnInit, OnChanges { public control: Control; + @Input() placeholder: string = 'Find a place...'; @ViewChild('controlwrapper') controlWrapper; constructor(private _mapService: LeafletMapService) { } @@ -29,7 +30,7 @@ this.control = controlObj .geocoder({ collapsed: false, - placeholder: 'Find a place...', + placeholder: this.placeholder, geocoder: new controlObj.Geocoder.Nominatim({ geocodingQueryParams: { countrycodes: 'ph' @@ -47,6 +48,13 @@ ; } + ngOnChanges(changes) { + // detect the change on the placeholder input + if (typeof this.control !== 'undefined') { + (this.control as any)._input.placeholder = changes.placeholder.currentValue; + } + } + }
a8c86a32e051d62ea10fbc39b2f50342d3bead7c
packages/schematics/angular/utility/latest-versions.ts
packages/schematics/angular/utility/latest-versions.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export const latestVersions = { // These versions should be kept up to date with latest Angular peer dependencies. Angular: '~8.0.0-beta.12', RxJs: '~6.5.1', ZoneJs: '~0.9.0', TypeScript: '~3.4.3', TsLib: '^1.9.0', // The versions below must be manually updated when making a new devkit release. DevkitBuildAngular: '~0.800.0-beta.13', DevkitBuildNgPackagr: '~0.800.0-beta.13', };
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export const latestVersions = { // These versions should be kept up to date with latest Angular peer dependencies. Angular: '~8.0.0-beta.12', RxJs: '~6.4.0', ZoneJs: '~0.9.0', TypeScript: '~3.4.3', TsLib: '^1.9.0', // The versions below must be manually updated when making a new devkit release. DevkitBuildAngular: '~0.800.0-beta.13', DevkitBuildNgPackagr: '~0.800.0-beta.13', };
Revert "feat(@schematics/angular): update scaffolding rxjs version to 6.5.1"
Revert "feat(@schematics/angular): update scaffolding rxjs version to 6.5.1" This reverts commit 636ff36b3a1789be392698f254d91a80d854f6ea.
TypeScript
mit
DevIntent/angular-cli,geofffilippi/angular-cli,geofffilippi/angular-cli,Brocco/angular-cli,angular/angular-cli,geofffilippi/angular-cli,clydin/angular-cli,DevIntent/angular-cli,angular/angular-cli,Brocco/angular-cli,clydin/angular-cli,filipesilva/angular-cli,clydin/angular-cli,angular/angular-cli,geofffilippi/angular-cli,ocombe/angular-cli,clydin/angular-cli,DevIntent/angular-cli,catull/angular-cli,angular/angular-cli,beeman/angular-cli,ocombe/angular-cli,hansl/angular-cli,hansl/angular-cli,hansl/angular-cli,filipesilva/angular-cli,ocombe/angular-cli,DevIntent/angular-cli,beeman/angular-cli,ocombe/angular-cli,catull/angular-cli,hansl/angular-cli,DevIntent/angular-cli,beeman/angular-cli,manekinekko/angular-cli,catull/angular-cli,Brocco/angular-cli,Brocco/angular-cli,catull/angular-cli,ocombe/angular-cli,beeman/angular-cli,Brocco/angular-cli,filipesilva/angular-cli,manekinekko/angular-cli,manekinekko/angular-cli,filipesilva/angular-cli
--- +++ @@ -9,7 +9,7 @@ export const latestVersions = { // These versions should be kept up to date with latest Angular peer dependencies. Angular: '~8.0.0-beta.12', - RxJs: '~6.5.1', + RxJs: '~6.4.0', ZoneJs: '~0.9.0', TypeScript: '~3.4.3', TsLib: '^1.9.0',
584854ea6f36a2eecdd2d6d65fb9a5b9cb3a943f
test/data/User.spec.ts
test/data/User.spec.ts
import {UserSchema, IUserModel} from "../../src/server/data/User"; import {GameSchema, IGameModel} from "../../src/server/data/GameModel"; import mongoose from "mongoose"; import assert from "assert"; const connectionString = "mongodb://localhost/test" const User = mongoose.model("User", UserSchema) as IUserModel; const GameModel = mongoose.model("GameModel", GameSchema) as IGameModel; describe("User", () => { beforeEach(async () => { await mongoose.connect(connectionString); await mongoose.connection.db.dropDatabase() }); afterEach(async () => { await mongoose.disconnect() }) describe("findOrCreate", () => { it("should create user", async () => { await User.findOrCreate("M4T4L4"); const users = await User.find().exec(); assert.equal(1, users.length, "users"); }); }); describe("addGame", () => { it("should add game for logged in user", async () => { const facebookId = "M4T4L4" let user = await User.findOrCreate(facebookId); const doc = await GameModel.findOrCreate("P3L1") await User.addGame(user._id, doc.title); user = await User.findOne({facebookId}).exec(); assert.equal(user.games.length, 1, "added game"); assert.equal(user.games[0], "P3L1", "game title"); }); }); });
import {UserSchema, IUserModel} from "../../src/server/data/User"; import {GameSchema, IGameModel} from "../../src/server/data/GameModel"; import mongoose from "mongoose"; import assert from "assert"; const connectionString = "mongodb://localhost:27017/test" const User = mongoose.model("User", UserSchema) as IUserModel; const GameModel = mongoose.model("GameModel", GameSchema) as IGameModel; describe("User", () => { beforeEach(async () => { await mongoose.connect(connectionString, {useNewUrlParser: true}); await mongoose.connection.db.dropDatabase() }); afterEach(async () => { await mongoose.disconnect() }) describe("findOrCreate", () => { it("should create user", async () => { await User.findOrCreate("M4T4L4"); const users = await User.find().exec(); assert.equal(1, users.length, "users"); }); }); describe("addGame", () => { it("should add game for logged in user", async () => { const facebookId = "M4T4L4" let user = await User.findOrCreate(facebookId); const doc = await GameModel.findOrCreate("P3L1") await User.addGame(user._id, doc.title); user = await User.findOne({facebookId}).exec(); assert.equal(user.games.length, 1, "added game"); assert.equal(user.games[0], "P3L1", "game title"); }); }); });
Fix url parser warning during tests
Fix url parser warning during tests
TypeScript
mit
Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki
--- +++ @@ -3,13 +3,13 @@ import mongoose from "mongoose"; import assert from "assert"; -const connectionString = "mongodb://localhost/test" +const connectionString = "mongodb://localhost:27017/test" const User = mongoose.model("User", UserSchema) as IUserModel; const GameModel = mongoose.model("GameModel", GameSchema) as IGameModel; describe("User", () => { beforeEach(async () => { - await mongoose.connect(connectionString); + await mongoose.connect(connectionString, {useNewUrlParser: true}); await mongoose.connection.db.dropDatabase() });