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
eb692c5b37b80be8dc9bad510aa019e9e459706f
applications/calendar/src/app/containers/calendar/confirmationModals/DuplicateAttendeesModal.tsx
applications/calendar/src/app/containers/calendar/confirmationModals/DuplicateAttendeesModal.tsx
import React from 'react'; import { c } from 'ttag'; import { Alert, FormModal } from 'react-components'; import { noop } from 'proton-shared/lib/helpers/function'; interface Props { onClose: () => void; duplicateAttendees: string[][]; } const DuplicateAttendeesModal = ({ onClose, duplicateAttendees, ...rest }: Props) => { return ( <FormModal submit={c('Action').t`OK`} close={null} title={c('Title').t`You have invited participants with equivalent emails`} onSubmit={onClose} onClose={noop} hasClose={false} small {...rest} > <p>{c('Info').t`Please remove the duplicates and try again.`}</p> {duplicateAttendees.map((group) => ( <Alert type="warning" key={group.join('')}> {group.map((email) => ( <p className="text-ellipsis" key={email} title={email}> {email} </p> ))} </Alert> ))} </FormModal> ); }; export default DuplicateAttendeesModal;
import React from 'react'; import { c } from 'ttag'; import { Alert, FormModal } from 'react-components'; import { noop } from 'proton-shared/lib/helpers/function'; interface Props { onClose: () => void; duplicateAttendees: string[][]; } const DuplicateAttendeesModal = ({ onClose, duplicateAttendees, ...rest }: Props) => { return ( <FormModal submit={c('Action').t`OK`} close={null} title={c('Title').t`You have invited participants with equivalent emails`} onSubmit={onClose} onClose={noop} hasClose={false} noTitleEllipsis small {...rest} > <p>{c('Info').t`Please remove the duplicates and try again.`}</p> {duplicateAttendees.map((group) => ( <Alert type="warning" key={group.join('')}> {group.map((email) => ( <p className="text-ellipsis" key={email} title={email}> {email} </p> ))} </Alert> ))} </FormModal> ); }; export default DuplicateAttendeesModal;
Remove title ellipsis on duplicate attendees modal
Remove title ellipsis on duplicate attendees modal CALWEB-2487
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -17,6 +17,7 @@ onSubmit={onClose} onClose={noop} hasClose={false} + noTitleEllipsis small {...rest} >
165978bf842b6f017a42a3409ef9281b1743c537
examples/examples.test.ts
examples/examples.test.ts
import {assert} from 'chai'; import * as vl from '../src/vl'; import {zSchema} from '../test/util'; const inspect = require('util').inspect; const fs = require('fs'); const path = require('path'); const validator = new zSchema({ noEmptyArrays: true, noEmptyStrings: true }); const vlSchema = require('../vega-lite-schema.json'); const vgSchema = require('../node_modules/vega/vega-schema.json'); function validateAgainstSchemas(vlspec) { const isVlValid = validator.validate(vlspec, vlSchema); if (!isVlValid) { const errors = validator.getLastErrors(); console.log(inspect(errors, { depth: 10, colors: true })); } assert(isVlValid); const vegaSpec = vl.compile(vlspec); const isVgValid = validator.validate(vegaSpec, vgSchema); if (!isVgValid) { const errors = validator.getLastErrors(); console.log(inspect(errors, { depth: 10, colors: true })); } assert(isVgValid); } describe('Examples', function() { const examples = fs.readdirSync('examples/specs'); examples.forEach(function(example) { if (path.extname(example) !== '.json') { return; } it('should be valid and produce valid vega for: ' + example, function() { const data = JSON.parse(fs.readFileSync('examples/specs/' + example)); validateAgainstSchemas(data); }); }); });
import {assert} from 'chai'; import * as vl from '../src/vl'; import {zSchema} from '../test/util'; const inspect = require('util').inspect; const fs = require('fs'); const path = require('path'); const validator = new zSchema({ noEmptyArrays: true, noEmptyStrings: true }); const vlSchema = require('../vega-lite-schema.json'); const vgSchema = require('../node_modules/vega/vega-schema.json'); function validateAgainstSchemas(vlspec) { const isVlValid = validator.validate(vlspec, vlSchema); if (!isVlValid) { const errors = validator.getLastErrors(); console.log(inspect(errors, { depth: 10, colors: true })); } assert(isVlValid); const vegaSpec = vl.compile(vlspec).spec; const isVgValid = validator.validate(vegaSpec, vgSchema); if (!isVgValid) { const errors = validator.getLastErrors(); console.log(inspect(errors, { depth: 10, colors: true })); } assert(isVgValid); } describe('Examples', function() { const examples = fs.readdirSync('examples/specs'); examples.forEach(function(example) { if (path.extname(example) !== '.json') { return; } it('should be valid and produce valid vega for: ' + example, function() { const data = JSON.parse(fs.readFileSync('examples/specs/' + example)); validateAgainstSchemas(data); }); }); });
Validate generated vega spec against vega schema
Validate generated vega spec against vega schema Fixes https://github.com/vega/vega-lite/issues/1156
TypeScript
bsd-3-clause
uwdata/vega-lite,uwdata/vega-lite,vega/vega-lite,uwdata/vega-lite,uwdata/vega-lite,vega/vega-lite,vega/vega-lite,uwdata/vega-lite,vega/vega-lite,vega/vega-lite
--- +++ @@ -22,7 +22,7 @@ } assert(isVlValid); - const vegaSpec = vl.compile(vlspec); + const vegaSpec = vl.compile(vlspec).spec; const isVgValid = validator.validate(vegaSpec, vgSchema); if (!isVgValid) {
70995bb7eac31e2fe1864448c56bbb9969a5bc20
src/components/Checkbox/Checkbox.tsx
src/components/Checkbox/Checkbox.tsx
import { Fragment } from 'react' import styled from 'styled-components' import type { Nodes } from '../../types' const List = styled.ul` list-style-type: none; ` const StyledCheckbox = styled.input` margin-right: 0.5rem; cursor: pointer; ` interface Props { id: string nodes: Nodes onToggle: (id: string) => void } export const Checkbox = ({ id, nodes, onToggle }: Props) => { const node = nodes[id] const { text, childIds, checked } = node return ( <Fragment key={id}> {text && ( <li> <label> <StyledCheckbox type='checkbox' checked={checked} onChange={() => onToggle(id)} /> {text} </label> </li> )} {childIds.length ? ( <li> <List> {childIds.map((childId) => ( <Checkbox key={childId} id={childId} nodes={nodes} onToggle={onToggle} /> ))} </List> </li> ) : null} </Fragment> ) }
import { Fragment } from 'react' import styled from 'styled-components' import type { Nodes } from '../../types' const List = styled.ul` list-style-type: none; ` const StyledCheckbox = styled.input` margin-right: 0.5rem; cursor: pointer; ` interface Props { id: string nodes: Nodes onToggle: (id: string) => void } export const Checkbox = ({ id, nodes, onToggle }: Props) => { const node = nodes[id] const { text, childIds, checked } = node return ( <Fragment key={id}> {text && ( <li> <label> <StyledCheckbox type='checkbox' checked={checked} onChange={() => onToggle(id)} /> {text} </label> </li> )} {childIds.length > 0 && ( <li> <List> {childIds.map((childId) => ( <Checkbox key={childId} id={childId} nodes={nodes} onToggle={onToggle} /> ))} </List> </li> )} </Fragment> ) }
Use logical && in place of ternary condition
Use logical && in place of ternary condition
TypeScript
mit
joelgeorgev/react-checkbox-tree,joelgeorgev/react-checkbox-tree
--- +++ @@ -36,7 +36,7 @@ </label> </li> )} - {childIds.length ? ( + {childIds.length > 0 && ( <li> <List> {childIds.map((childId) => ( @@ -49,7 +49,7 @@ ))} </List> </li> - ) : null} + )} </Fragment> ) }
4c1254a880633a6ea153a0ee7d5d5c8a8b7c9048
common/Toolbox.ts
common/Toolbox.ts
import { escapeRegExp } from "lodash"; export interface KeyValueSet<T> { [key: string]: T; } export function toModifierString(number: number): string { if (number >= 0) { return `+${number}`; } return number.toString(); } export function probablyUniqueString(): string { //string contains only easily relayable characters for forward //compatability with speech-based data transfer ;-) let chars = "1234567890abcdefghijkmnpqrstuvxyz"; let probablyUniqueString = ""; for (let i = 0; i < 8; i++) { let index = Math.floor(Math.random() * chars.length); probablyUniqueString += chars[index]; } return probablyUniqueString; } export function concatenatedStringRegex(strings: string[]) { const allStrings = strings .map(s => escapeRegExp(s)) .sort((a, b) => b.localeCompare(a)); if (allStrings.length === 0) { return new RegExp("a^"); } return new RegExp(`\\b(${allStrings.join("|")})\\b`, "gim"); } export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
import { escapeRegExp } from "lodash"; export interface KeyValueSet<T> { [key: string]: T; } export function toModifierString(number: number): string { if (number >= 0) { return `+${number}`; } return number.toString(); } export function probablyUniqueString(): string { //string contains only easily relayable characters for forward //compatability with speech-based data transfer ;-) let chars = "1234567890abcdefghijkmnpqrstuvxyz"; let probablyUniqueString = ""; for (let i = 0; i < 8; i++) { let index = Math.floor(Math.random() * chars.length); probablyUniqueString += chars[index]; } return probablyUniqueString; } export function concatenatedStringRegex(strings: string[]) { const allStrings = strings .map(s => escapeRegExp(s)) .sort((a, b) => b.localeCompare(a)); if (allStrings.length === 0) { return new RegExp("a^"); } return new RegExp(`\\b(${allStrings.join("|")})\\b`, "gim"); } export function ParseJSONOrDefault<T>(json, defaultValue: T) { try { return JSON.parse(json); } catch { return defaultValue; } } export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
Add safe JSON parsing method
Add safe JSON parsing method
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -34,4 +34,12 @@ return new RegExp(`\\b(${allStrings.join("|")})\\b`, "gim"); } +export function ParseJSONOrDefault<T>(json, defaultValue: T) { + try { + return JSON.parse(json); + } catch { + return defaultValue; + } +} + export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
ab08e8b4dd81b5e3b046e29f67101870a5f6a57c
src/app/home/top-page/top-page.component.spec.ts
src/app/home/top-page/top-page.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { TopPageComponent } from './top-page.component'; describe('TopPageComponent', () => { let component: TopPageComponent; let fixture: ComponentFixture<TopPageComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ TopPageComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TopPageComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { ImageService } from '../../gallery/image.service'; import { MockImageService } from '../../gallery/mocks/mock-image.service'; import { GalleryFormatPipe } from '../../gallery/gallery-format.pipe'; import { ThumbnailComponent } from '../../gallery/thumbnail/thumbnail.component'; import { ImageContainerComponent } from '../../gallery/image-container/image-container.component'; import { TopPageComponent } from './top-page.component'; describe('TopPageComponent', () => { const mockImageService = new MockImageService(); let component: TopPageComponent; let fixture: ComponentFixture<TopPageComponent>; let compiled: HTMLElement; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ GalleryFormatPipe, ThumbnailComponent, ImageContainerComponent, TopPageComponent ], providers: [ { provide: ImageService, useValue: mockImageService } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TopPageComponent); component = fixture.componentInstance; compiled = fixture.debugElement.nativeElement; fixture.detectChanges(); }); it('should create and load images', () => { expect(component).toBeTruthy(); const thumbnails = compiled.querySelectorAll('jblog-thumbnail'); expect(thumbnails.length).toBe(1); }); });
Fix top page component test
Fix top page component test
TypeScript
apache-2.0
jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog
--- +++ @@ -1,14 +1,33 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { RouterTestingModule } from '@angular/router/testing'; + +import { ImageService } from '../../gallery/image.service'; +import { MockImageService } from '../../gallery/mocks/mock-image.service'; +import { GalleryFormatPipe } from '../../gallery/gallery-format.pipe'; +import { ThumbnailComponent } from '../../gallery/thumbnail/thumbnail.component'; +import { ImageContainerComponent } from '../../gallery/image-container/image-container.component'; import { TopPageComponent } from './top-page.component'; describe('TopPageComponent', () => { + const mockImageService = new MockImageService(); + let component: TopPageComponent; let fixture: ComponentFixture<TopPageComponent>; + let compiled: HTMLElement; beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ TopPageComponent ] + imports: [ RouterTestingModule ], + declarations: [ + GalleryFormatPipe, + ThumbnailComponent, + ImageContainerComponent, + TopPageComponent + ], + providers: [ + { provide: ImageService, useValue: mockImageService } + ] }) .compileComponents(); })); @@ -16,10 +35,13 @@ beforeEach(() => { fixture = TestBed.createComponent(TopPageComponent); component = fixture.componentInstance; + compiled = fixture.debugElement.nativeElement; fixture.detectChanges(); }); - it('should create', () => { + it('should create and load images', () => { expect(component).toBeTruthy(); + const thumbnails = compiled.querySelectorAll('jblog-thumbnail'); + expect(thumbnails.length).toBe(1); }); });
ddc79b8b549290423420bb7e46d2a315b34d1b4c
src/dom/assignProperties.ts
src/dom/assignProperties.ts
import {DeepPartial} from '../extra/DeepPartial' /** * Assign properties to an object of type `HTMLElement` or `SVGElement`. */ export function assignProperties<E extends Element, P extends DeepPartial<E>>(elem: E, props: P): void { doAssignProperties(elem, props) } function doAssignProperties<E extends Element, P extends DeepPartial<E>>(elem: E, props: P): void { for (const p in props) { if (props.hasOwnProperty(p)) { if (isObject(props[p])) { // Go deeper, for properties such as `style`. assignNestedProperties((elem as any)[p], props[p] as {[key: string]: any}) } else { if (p.indexOf('-') > -1) { // Deal with custom and special attributes, such as `data-*` and `aria-*` attributes. elem.setAttribute(p, props[p] as any) } else { // Treat the rest as standard properties. (elem as any)[p] = props[p] } } } } } function assignNestedProperties(target: {[key: string]: any}, props: {[key: string]: any}) { for (const p in props) { if (props.hasOwnProperty(p)) { if (isObject(props[p])) { // Some SVG properties are even more nested. assignNestedProperties(target[p], props[p]) } else { target[p] = props[p] } } } } function isObject(o: any): boolean { return o instanceof Object && (o as Object).constructor === Object }
import {DeepPartial} from '../extra/DeepPartial' /** * Assign properties to an object of type `HTMLElement` or `SVGElement`. */ export function assignProperties<E extends Element, P extends DeepPartial<E>>(elem: E, props: P): void { for (const p in props) { if (props.hasOwnProperty(p)) { if (isObject(props[p])) { // Go deeper, for properties such as `style`. assignNestedProperties((elem as any)[p], props[p] as {[key: string]: any}) } else { if (p.indexOf('-') > -1) { // Deal with custom and special attributes, such as `data-*` and `aria-*` attributes. elem.setAttribute(p, props[p] as any) } else { // Treat the rest as standard properties. (elem as any)[p] = props[p] } } } } } function assignNestedProperties(target: {[key: string]: any}, props: {[key: string]: any}) { for (const p in props) { if (props.hasOwnProperty(p)) { if (isObject(props[p])) { // Some SVG properties are even more nested. assignNestedProperties(target[p], props[p]) } else { target[p] = props[p] } } } } function isObject(o: any): boolean { return o instanceof Object && (o as Object).constructor === Object }
Remove private function not needed anymore.
Remove private function not needed anymore.
TypeScript
agpl-3.0
inad9300/Soil,inad9300/Soil
--- +++ @@ -4,10 +4,6 @@ * Assign properties to an object of type `HTMLElement` or `SVGElement`. */ export function assignProperties<E extends Element, P extends DeepPartial<E>>(elem: E, props: P): void { - doAssignProperties(elem, props) -} - -function doAssignProperties<E extends Element, P extends DeepPartial<E>>(elem: E, props: P): void { for (const p in props) { if (props.hasOwnProperty(p)) { if (isObject(props[p])) {
4406da75773d6adffd1f2249ccebf677c48e5b58
src/impl/네이버뉴스.ts
src/impl/네이버뉴스.ts
import { clearStyles } from '../util'; import { Article } from '..'; export const cleanup = () => { document.querySelectorAll('#tooltipLayer_english, .u_cbox_layer_wrap').forEach((v) => { v.remove(); }); } export function parse(): Article { return { title: $('#articleTitle').text(), content: (() => { const content = document.querySelector('#articleBodyContents')!; const iframes = content.querySelectorAll('.vod_area iframe[_src]'); if (iframes.length > 0) { iframes.forEach((v) => { v.setAttribute('src', v.getAttribute('_src')!); }); } return clearStyles(content).innerHTML; })(), timestamp: { created: (() => { let created = $('.article_info .sponsor .t11').eq(0).text(); return new Date(created.replace(' ', 'T') + '+09:00'); // ISO 8601 })(), lastModified: (() => { let modified = $('.article_info .sponsor .t11').eq(1).text(); if(modified === '') { return undefined; } return new Date(modified.replace(' ', 'T') + '+09:00'); // ISO 8601 })(), }, }; }
import { clearStyles } from '../util'; import { Article } from '..'; export const cleanup = () => { document.querySelectorAll('#tooltipLayer_english, .u_cbox_layer_wrap').forEach((v) => { v.remove(); }); } export function parse(): Article { const parseTime = (timeInfo: Nullable<string>) => { if (timeInfo) { const iso8601 = timeInfo.replace(/(\d{4}).(\d{2}).(\d{2}). (오전|오후) (\d{1,2}):(\d{2})/, function(_, year, month, day, ampm, hour, minuate) { hour |= 0; if (ampm === "오후") hour += 12; if (hour === 24) hour = 0; hour = hour < 10 ? "0" + hour : hour; return `${year}-${month}-${day}T${hour}:${minuate}+09:00`; }) return new Date(iso8601); } return undefined; } return { title: $('#articleTitle').text(), content: (() => { const content = document.querySelector('#articleBodyContents')!; const iframes = content.querySelectorAll('.vod_area iframe[_src]'); if (iframes.length > 0) { iframes.forEach((v) => { v.setAttribute('src', v.getAttribute('_src')!); }); } return clearStyles(content).innerHTML; })(), timestamp: { created: (() => { let created = $('.article_info .sponsor .t11').eq(0).text(); return parseTime(created); })(), lastModified: (() => { let modified = $('.article_info .sponsor .t11').eq(1).text(); return parseTime(modified); })(), }, }; }
Fix parsing error on naver news date
Fix parsing error on naver news date
TypeScript
mit
disjukr/jews,disjukr/just-news,disjukr/just-news,disjukr/jews,disjukr/just-news
--- +++ @@ -8,6 +8,19 @@ } export function parse(): Article { + const parseTime = (timeInfo: Nullable<string>) => { + if (timeInfo) { + const iso8601 = timeInfo.replace(/(\d{4}).(\d{2}).(\d{2}). (오전|오후) (\d{1,2}):(\d{2})/, function(_, year, month, day, ampm, hour, minuate) { + hour |= 0; + if (ampm === "오후") hour += 12; + if (hour === 24) hour = 0; + hour = hour < 10 ? "0" + hour : hour; + return `${year}-${month}-${day}T${hour}:${minuate}+09:00`; + }) + return new Date(iso8601); + } + return undefined; + } return { title: $('#articleTitle').text(), content: (() => { @@ -23,14 +36,11 @@ timestamp: { created: (() => { let created = $('.article_info .sponsor .t11').eq(0).text(); - return new Date(created.replace(' ', 'T') + '+09:00'); // ISO 8601 + return parseTime(created); })(), lastModified: (() => { let modified = $('.article_info .sponsor .t11').eq(1).text(); - if(modified === '') { - return undefined; - } - return new Date(modified.replace(' ', 'T') + '+09:00'); // ISO 8601 + return parseTime(modified); })(), }, };
d56522b88d9204f090ccffc94f2773b34faab712
src/lib/stitching/vortex/schema.ts
src/lib/stitching/vortex/schema.ts
import { createVortexLink } from "./link" import { makeRemoteExecutableSchema, transformSchema, RenameTypes, RenameRootFields, FilterRootFields, } from "graphql-tools" import { readFileSync } from "fs" export const executableVortexSchema = ({ removeRootFields = true, }: { removeRootFields?: boolean } = {}) => { const vortexLink = createVortexLink() const vortexTypeDefs = readFileSync("src/data/vortex.graphql", "utf8") // Setup the default Schema const schema = makeRemoteExecutableSchema({ schema: vortexTypeDefs, link: vortexLink, }) const removeRootFieldList = [ "pricingContext", "partnerStat", "userStat", "BigInt", ] const filterTransform = new FilterRootFields( (_operation, name) => !removeRootFieldList.includes(name) ) const transforms = [ ...(removeRootFields ? [filterTransform] : []), new RenameTypes((name) => { if ( name.includes("PriceInsight") || name.includes("PageCursor") || ["BigInt", "ISO8601DateTime"].includes(name) ) { return name } else { return `Analytics${name}` } }), new RenameRootFields((_operation, name) => { if (["priceInsights", "marketPriceInsights"].includes(name)) { return name } else { return `analytics${name.charAt(0).toUpperCase() + name.slice(1)}` } }), ] return transformSchema(schema, transforms) }
import { createVortexLink } from "./link" import { makeRemoteExecutableSchema, transformSchema, RenameTypes, RenameRootFields, FilterRootFields, } from "graphql-tools" import { readFileSync } from "fs" export const executableVortexSchema = ({ removeRootFields = true, }: { removeRootFields?: boolean } = {}) => { const vortexLink = createVortexLink() const vortexTypeDefs = readFileSync("src/data/vortex.graphql", "utf8") // Setup the default Schema const schema = makeRemoteExecutableSchema({ schema: vortexTypeDefs, link: vortexLink, }) const rootFieldsToFilter = [ "pricingContext", "partnerStat", "userStat", "BigInt", ] const filterTransform = new FilterRootFields( (_operation, name) => !rootFieldsToFilter.includes(name) ) const transforms = [ ...(removeRootFields ? [filterTransform] : []), new RenameTypes((name) => { if ( name.includes("PriceInsight") || name.includes("PageCursor") || ["BigInt", "ISO8601DateTime"].includes(name) ) { return name } else { return `Analytics${name}` } }), new RenameRootFields((_operation, name) => { if (["priceInsights", "marketPriceInsights"].includes(name)) { return name } else { return `analytics${name.charAt(0).toUpperCase() + name.slice(1)}` } }), ] return transformSchema(schema, transforms) }
Use better name for list of fields to filter
Use better name for list of fields to filter
TypeScript
mit
artsy/metaphysics,artsy/metaphysics,artsy/metaphysics
--- +++ @@ -20,7 +20,7 @@ link: vortexLink, }) - const removeRootFieldList = [ + const rootFieldsToFilter = [ "pricingContext", "partnerStat", "userStat", @@ -28,7 +28,7 @@ ] const filterTransform = new FilterRootFields( - (_operation, name) => !removeRootFieldList.includes(name) + (_operation, name) => !rootFieldsToFilter.includes(name) ) const transforms = [
b9f54a8cee2de1dea672a1267bbee824c70c3f93
src/public_api.ts
src/public_api.ts
/* * Public API Surface of papaparse */ export * from './lib/papa'; export * from './lib/papa-parse.module';
/* * Public API Surface of papaparse */ export * from './lib/papa';
Remove module from Public api
fix: Remove module from Public api
TypeScript
mit
Alberthaff/ngx-papaparse,Alberthaff/ngx-papaparse
--- +++ @@ -3,4 +3,3 @@ */ export * from './lib/papa'; -export * from './lib/papa-parse.module';
77bb6f36e9651c846f6b0c6148f40b96e2f7598f
src/vmware/VMwareForm.tsx
src/vmware/VMwareForm.tsx
import * as React from 'react'; import { required } from '@waldur/core/validators'; import { FormContainer, StringField, NumberField, SecretField } from '@waldur/form-react'; export const VMwareForm = ({ translate, container }) => ( <FormContainer {...container}> <StringField name="backend_url" label={translate('Hostname')} required={true} validate={required} /> <StringField name="username" label={translate('Username')} required={true} validate={required} /> <SecretField name="password" label={translate('Password')} required={true} validate={required} /> <StringField name="default_cluster_id" label={translate('Default cluster ID')} required={true} validate={required} /> <NumberField name="max_cpu" label={translate('Maximum vCPU for each VM')} /> <NumberField name="max_ram" label={translate('Maximum RAM for each VM')} unit="GB" format={v => v ? v / 1024 : ''} normalize={v => Number(v) * 1024} /> <NumberField name="max_disk" label={translate('Maximum capacity for each disk')} unit="GB" format={v => v ? v / 1024 : ''} normalize={v => Number(v) * 1024} /> </FormContainer> );
import * as React from 'react'; import { required } from '@waldur/core/validators'; import { FormContainer, StringField, NumberField, SecretField } from '@waldur/form-react'; export const VMwareForm = ({ translate, container }) => ( <FormContainer {...container}> <StringField name="backend_url" label={translate('Hostname')} required={true} validate={required} /> <StringField name="username" label={translate('Username')} required={true} validate={required} /> <SecretField name="password" label={translate('Password')} required={true} validate={required} /> <StringField name="default_cluster_label" label={translate('Default cluster label')} required={true} validate={required} /> <NumberField name="max_cpu" label={translate('Maximum vCPU for each VM')} /> <NumberField name="max_ram" label={translate('Maximum RAM for each VM')} unit="GB" format={v => v ? v / 1024 : ''} normalize={v => Number(v) * 1024} /> <NumberField name="max_disk" label={translate('Maximum capacity for each disk')} unit="GB" format={v => v ? v / 1024 : ''} normalize={v => Number(v) * 1024} /> </FormContainer> );
Allow setting cluster label instead of ID when creating a VMware offering
Allow setting cluster label instead of ID when creating a VMware offering [WAL-2536]
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -24,8 +24,8 @@ validate={required} /> <StringField - name="default_cluster_id" - label={translate('Default cluster ID')} + name="default_cluster_label" + label={translate('Default cluster label')} required={true} validate={required} />
68779294a2de0d31bfc6fd3b6d2b66b751e9a286
src/Debug/babylon.debugLayer.ts
src/Debug/babylon.debugLayer.ts
module BABYLON { // declare INSPECTOR namespace for compilation issue declare var INSPECTOR : any; export class DebugLayer { private _scene: Scene; public static InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js'; // The inspector instance private _inspector : any; constructor(scene: Scene) { this._scene = scene; } /** Creates the inspector window. */ private _createInspector(popup?:boolean) { if (!this._inspector) { this._inspector = new INSPECTOR.Inspector(this._scene, popup); } // else nothing to do,; instance is already existing } public isVisible(): boolean { return false; } public hide() { if (this._inspector) { this._inspector.dispose(); this._inspector = null; } } public show(popup?:boolean) { if (typeof INSPECTOR == 'undefined') { // Load inspector and add it to the DOM Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup)); } else { // Otherwise creates the inspector this._createInspector(popup); } } } }
module BABYLON { // declare INSPECTOR namespace for compilation issue declare var INSPECTOR : any; export class DebugLayer { private _scene: Scene; public static InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js'; // The inspector instance private _inspector : any; constructor(scene: Scene) { this._scene = scene; } /** Creates the inspector window. */ private _createInspector(popup?:boolean) { if (!this._inspector) { this._inspector = new INSPECTOR.Inspector(this._scene, popup); } // else nothing to do,; instance is already existing } public isVisible(): boolean { if (!this._inspector) { return false; } return true; } public hide() { if (this._inspector) { this._inspector.dispose(); this._inspector = null; } } public show(popup?:boolean) { if (typeof INSPECTOR == 'undefined') { // Load inspector and add it to the DOM Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup)); } else { // Otherwise creates the inspector this._createInspector(popup); } } } }
Fix isVisible method of debuglayer
Fix isVisible method of debuglayer
TypeScript
apache-2.0
Hersir88/Babylon.js,sebavan/Babylon.js,sebavan/Babylon.js,Hersir88/Babylon.js,RaananW/Babylon.js,NicolasBuecher/Babylon.js,abow/Babylon.js,abow/Babylon.js,BabylonJS/Babylon.js,abow/Babylon.js,Kesshi/Babylon.js,Temechon/Babylon.js,BabylonJS/Babylon.js,jbousquie/Babylon.js,Kesshi/Babylon.js,Hersir88/Babylon.js,Temechon/Babylon.js,Temechon/Babylon.js,NicolasBuecher/Babylon.js,BabylonJS/Babylon.js,Kesshi/Babylon.js,jbousquie/Babylon.js,RaananW/Babylon.js,sebavan/Babylon.js,jbousquie/Babylon.js,NicolasBuecher/Babylon.js,RaananW/Babylon.js
--- +++ @@ -21,7 +21,10 @@ } public isVisible(): boolean { - return false; + if (!this._inspector) { + return false; + } + return true; } public hide() {
d0ed2be8fc8caaad107e6768cc352f8f15eb10f1
src/app/nav/storage/storage.component.ts
src/app/nav/storage/storage.component.ts
import { Component, Input, OnInit } from '@angular/core' import { AbstractStorageService } from 'core/AbstractStorageService' @Component({ selector: 'mute-storage', templateUrl: './storage.component.html', styleUrls: ['./storage.component.scss'] }) export class StorageComponent implements OnInit { private available: boolean private tooltipMsg: string @Input() storageService: AbstractStorageService constructor () {} ngOnInit () { this.storageService.isReachable() .then((isReachable: boolean) => { this.available = isReachable }) .catch(() => { this.available = false }) .then(() => { if (this.available) { this.tooltipMsg = `Is available on: ${this.storageService}` } else { this.tooltipMsg = `${this.storageService} is not available` } }) } isAvailable (): boolean { return this.available } }
import { Component, Input, OnInit } from '@angular/core' import { AbstractStorageService } from 'core/AbstractStorageService' @Component({ selector: 'mute-storage', templateUrl: './storage.component.html', styleUrls: ['./storage.component.scss'] }) export class StorageComponent implements OnInit { private isAvailable: boolean private tooltipMsg: string @Input() storageService: AbstractStorageService constructor () {} ngOnInit () { this.storageService.isReachable() .then((isReachable: boolean) => { this.isAvailable = isReachable }) .catch(() => { this.isAvailable = false }) .then(() => { if (this.isAvailable) { this.tooltipMsg = `Is available on: ${this.storageService}` } else { this.tooltipMsg = `${this.storageService} is not available` } }) } }
Rename property from 'available' to 'isAvailable'
fix(storage): Rename property from 'available' to 'isAvailable'
TypeScript
agpl-3.0
oster/mute,coast-team/mute,oster/mute,coast-team/mute,oster/mute,coast-team/mute,coast-team/mute
--- +++ @@ -9,7 +9,7 @@ }) export class StorageComponent implements OnInit { - private available: boolean + private isAvailable: boolean private tooltipMsg: string @Input() storageService: AbstractStorageService @@ -18,21 +18,17 @@ ngOnInit () { this.storageService.isReachable() .then((isReachable: boolean) => { - this.available = isReachable + this.isAvailable = isReachable }) .catch(() => { - this.available = false + this.isAvailable = false }) .then(() => { - if (this.available) { + if (this.isAvailable) { this.tooltipMsg = `Is available on: ${this.storageService}` } else { this.tooltipMsg = `${this.storageService} is not available` } }) } - - isAvailable (): boolean { - return this.available - } }
fbb6d692b7075e4dcea5dbae1ff6dd20cc4ccb37
lib/ts/unicorn.ts
lib/ts/unicorn.ts
var prepareHello = (name:string) => { return 'Hello, ' + name; } console.log(prepareHello('Unicorns')); class fixOnScroll { constructor(element){ this.element = element; window.addEventListener('scroll', this.handleScroll.bind(this)) } getElement(){ switch (typeof this.element){ case 'function': return this.element(); case 'string': return document.querySelector(this.element); default: return this.element; } } handleScroll(e){ var element = this.getElement(); element.classList.remove('fixed'); var rekt = element.getBoundingClientRect(); if(rekt.top < 0) element.classList.add('fixed'); } }
var prepareHello = (name:string) => { return 'Hello, ' + name; } console.log(prepareHello('Unicorns')); class UnicornPlugin { getElement(providedElement){ var element = providedElement || this.element; switch (typeof element){ case 'function': return element(); case 'string': return document.querySelector(element); default: return element; } } } class fixOnScroll extends UnicornPlugin { constructor(element){ this.element = element; window.addEventListener('scroll', this.handleScroll.bind(this)) } pulldown(){ window.removeEventListener('scroll', this.handleScroll.bind(this)) }, handleScroll(e){ var element = this.getElement(); element.classList.remove('fixed'); var rekt = element.getBoundingClientRect(); if(rekt.top < 0) element.classList.add('fixed'); } }
Make a UnicornPlugin master class
Make a UnicornPlugin master class
TypeScript
mit
SevereOverfl0w/Unicorn-UI-Kit,SevereOverfl0w/Unicorn-UI-Kit
--- +++ @@ -4,21 +4,28 @@ console.log(prepareHello('Unicorns')); -class fixOnScroll { +class UnicornPlugin { + getElement(providedElement){ + var element = providedElement || this.element; + switch (typeof element){ + case 'function': + return element(); + case 'string': + return document.querySelector(element); + default: + return element; + } + } +} + +class fixOnScroll extends UnicornPlugin { constructor(element){ this.element = element; window.addEventListener('scroll', this.handleScroll.bind(this)) } - getElement(){ - switch (typeof this.element){ - case 'function': - return this.element(); - case 'string': - return document.querySelector(this.element); - default: - return this.element; - } - } + pulldown(){ + window.removeEventListener('scroll', this.handleScroll.bind(this)) + }, handleScroll(e){ var element = this.getElement(); element.classList.remove('fixed');
e5a1935a2b42aa983f7a216e99c70543485564e6
src/app/core/voice.service.ts
src/app/core/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.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'); import ArtyomCommand = Artyom.ArtyomCommand; import * as _ from "lodash"; @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); } public addCommand(indexes: string[], description: string, action: (i: number, wildcard?: string) => void ): void { const isSmart = _.some(indexes, str => _.includes(str, "*")); const command: ArtyomCommand = <ArtyomCommand> { indexes: indexes, action: action, description: description, smart: isSmart}; this.artyom.addCommands(command); } }
Add new public addCommand functions
Add new public addCommand functions
TypeScript
mit
ABAPlan/abaplan-core,ABAPlan/abaplan-core,ABAPlan/abaplan-core
--- +++ @@ -1,6 +1,7 @@ import { Injectable } from '@angular/core'; import artyomjs = require('artyom.js'); - +import ArtyomCommand = Artyom.ArtyomCommand; +import * as _ from "lodash"; @Injectable() export class VoiceService { @@ -43,4 +44,10 @@ public say(text: string): void { this.artyom.say(text); } + + public addCommand(indexes: string[], description: string, action: (i: number, wildcard?: string) => void ): void { + const isSmart = _.some(indexes, str => _.includes(str, "*")); + const command: ArtyomCommand = <ArtyomCommand> { indexes: indexes, action: action, description: description, smart: isSmart}; + this.artyom.addCommands(command); + } }
6220ca8eb640114e225f49638a19a92ef60737e8
cli.ts
cli.ts
import * as sourceMapSupport from "source-map-support"; sourceMapSupport.install(); import * as commander from "commander"; import * as fs from "fs-extra"; import * as lib from "./lib"; import * as path from "path"; function printUsage(): void { console.log("Usage: eta <subcommand> [options]"); } export default async function main(): Promise<boolean> { const args: string[] = process.argv.splice(2); if (args.length === 0) { printUsage(); return false; } if (args[0] === "-v" || args[0] === "-version") { console.log("Project Eta CLI: v" + (await fs.readJSON(lib.CLI_DIR + "/package.json")).version); return true; } let actionPath: string = undefined; let i: number; for (i = args.length; i > 0; i--) { actionPath = lib.DIST_DIR + "/lib/actions/" + args.slice(0, i).join("/") + ".js"; if (await fs.pathExists(actionPath)) break; else actionPath = undefined; } if (!actionPath) { printUsage(); return false; } const action: (args: string[]) => Promise<boolean> = require(actionPath).default; if (!action) throw new Error(`Internal error: invalid action defined for "${action}"`); return await action(args.splice(i + 1)); }
import * as sourceMapSupport from "source-map-support"; sourceMapSupport.install(); import * as commander from "commander"; import * as fs from "fs-extra"; import * as lib from "./lib"; import * as path from "path"; function printUsage(): void { console.log("Usage: eta <subcommand> [options]"); } export default async function main(): Promise<boolean> { const args: string[] = process.argv.splice(2); if (args.length === 0) { printUsage(); return false; } if (args[0] === "-v" || args[0] === "-version") { console.log("Project Eta CLI: v" + (await fs.readJSON(lib.CLI_DIR + "/package.json")).version); return true; } let actionPath: string = undefined; let i: number; for (i = args.length; i > 0; i--) { actionPath = lib.DIST_DIR + "/lib/actions/" + args.slice(0, i).join("/") + ".js"; if (await fs.pathExists(actionPath)) break; else actionPath = undefined; } if (!actionPath) { printUsage(); return false; } const action: (args: string[]) => Promise<boolean> = require(actionPath).default; if (!action) throw new Error(`Internal error: invalid action defined for "${action}"`); return await action(args.splice(i)); }
Fix a bug in argument handling
Fix a bug in argument handling
TypeScript
mit
crossroads-education/eta-cli,crossroads-education/eta-cli
--- +++ @@ -32,5 +32,5 @@ } const action: (args: string[]) => Promise<boolean> = require(actionPath).default; if (!action) throw new Error(`Internal error: invalid action defined for "${action}"`); - return await action(args.splice(i + 1)); + return await action(args.splice(i)); }
62a437e8fecf82503b3f7943eed76a0dc1aceb63
webpack/connectivity/reducer_support.ts
webpack/connectivity/reducer_support.ts
import { ConnectionStatus } from "./interfaces"; import * as m from "moment"; import { isString, max } from "lodash"; export function maxDate(l: m.Moment, r: m.Moment): string { const dates = [l, r].map(y => y.toDate()); return (max(dates) || dates[0]).toJSON(); } export function getStatus(cs: ConnectionStatus | undefined): "up" | "down" { return (cs && cs.state) || "down"; } /** USE CASE: We have numerous, possibly duplicate sources of information * that represent `last_saw_mq`. One came from the API and another (possibly) * came from the MQ directly to the browser. This function determines which of * the two is most relevant. It is a heuristic process that gives up when * unable to make a determination. */ export function computeBestTime(cs: ConnectionStatus | undefined, lastSawMq: string | undefined, now = m()): ConnectionStatus | undefined { // Only use the `last_saw_mq` time if it is more recent than the local // timestamp. // don't bother guessing if info is unavailable return isString(lastSawMq) ? { at: maxDate(now, m(lastSawMq)), state: getStatus(cs) } : cs; }
import { ConnectionStatus } from "./interfaces"; import * as m from "moment"; import { isString, max } from "lodash"; export function maxDate(l: m.Moment, r: m.Moment): string { const dates = [l, r].map(y => y.toDate()); return (max(dates) || dates[0]).toJSON(); } export function getStatus(cs: ConnectionStatus | undefined): "up" | "down" { return (cs && cs.state) || "down"; } /** USE CASE: We have numerous, possibly duplicate sources of information * that represent `last_saw_mq`. One came from the API and another (possibly) * came from the MQ directly to the browser. This function determines which of * the two is most relevant. It is a heuristic process that gives up when * unable to make a determination. */ export function computeBestTime(cs: ConnectionStatus | undefined, lastSawMq: string | undefined): ConnectionStatus | undefined { // Only use the `last_saw_mq` time if it is more recent than the local // timestamp. // don't bother guessing if info is unavailable return isString(lastSawMq) ? { at: maxDate(m(cs && cs.at ? cs.at : lastSawMq), m(lastSawMq)), state: getStatus(cs) } : cs; }
Fix logical error in `computeBestTime`
[STABLE] Fix logical error in `computeBestTime`
TypeScript
mit
FarmBot/farmbot-web-app,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/farmbot-web-app,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app
--- +++ @@ -17,12 +17,11 @@ * the two is most relevant. It is a heuristic process that gives up when * unable to make a determination. */ export function computeBestTime(cs: ConnectionStatus | undefined, - lastSawMq: string | undefined, - now = m()): ConnectionStatus | undefined { + lastSawMq: string | undefined): ConnectionStatus | undefined { // Only use the `last_saw_mq` time if it is more recent than the local // timestamp. // don't bother guessing if info is unavailable return isString(lastSawMq) ? - { at: maxDate(now, m(lastSawMq)), state: getStatus(cs) } : cs; + { at: maxDate(m(cs && cs.at ? cs.at : lastSawMq), m(lastSawMq)), state: getStatus(cs) } : cs; }
75b4c030af608ae0538c832d37339ba5ee59224b
src/Apps/Search/Components/SearchResultsSkeleton/index.tsx
src/Apps/Search/Components/SearchResultsSkeleton/index.tsx
import { Box, Col, Flex, Grid, Row } from "@artsy/palette" import { AppContainer } from "Apps/Components/AppContainer" import { HorizontalPadding } from "Apps/Components/HorizontalPadding" import React from "react" import { FilterSidebar } from "./FilterSidebar" import { GridItem } from "./GridItem" import { Header } from "./Header" export const SearchResultsSkeleton: React.FC<any> = props => { return ( <AppContainer> <HorizontalPadding> <Box> <Header /> <Flex> <FilterSidebar /> <Box width={["100%", "75%"]}> <Grid fluid> <Row> <Col sm={4} pr={1}> <GridItem height={200} /> <GridItem height={400} /> <GridItem height={240} /> </Col> <Col sm={4} pr={1}> <GridItem height={300} /> <GridItem height={200} /> <GridItem height={320} /> </Col> <Col sm={4}> <GridItem height={240} /> <GridItem height={400} /> </Col> </Row> </Grid> </Box> </Flex> </Box> </HorizontalPadding> </AppContainer> ) }
import { Box, Col, Flex, Grid, Row } from "@artsy/palette" import { AppContainer } from "Apps/Components/AppContainer" import React from "react" import { FilterSidebar } from "./FilterSidebar" import { GridItem } from "./GridItem" import { Header } from "./Header" export const SearchResultsSkeleton: React.FC<any> = props => { return ( <AppContainer> <Box pl={20}> <Header /> <Flex> <FilterSidebar /> <Box width={["100%", "75%"]}> <Grid fluid> <Row> <Col xs="6" sm="6" md="6" lg="4"> <GridItem height={200} /> <GridItem height={400} /> <GridItem height={240} /> </Col> <Col xs="6" sm="6" md="6" lg="4"> <GridItem height={300} /> <GridItem height={200} /> <GridItem height={320} /> </Col> <Col xs="6" sm="6" md="6" lg="4"> <GridItem height={240} /> <GridItem height={400} /> </Col> </Row> </Grid> </Box> </Flex> </Box> </AppContainer> ) }
Update responsive grid styling for search results skeleton
Update responsive grid styling for search results skeleton This commit updates styling for various responsive breakpoints.
TypeScript
mit
artsy/reaction,xtina-starr/reaction,artsy/reaction,artsy/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction-force,xtina-starr/reaction
--- +++ @@ -1,6 +1,5 @@ import { Box, Col, Flex, Grid, Row } from "@artsy/palette" import { AppContainer } from "Apps/Components/AppContainer" -import { HorizontalPadding } from "Apps/Components/HorizontalPadding" import React from "react" import { FilterSidebar } from "./FilterSidebar" import { GridItem } from "./GridItem" @@ -9,34 +8,32 @@ export const SearchResultsSkeleton: React.FC<any> = props => { return ( <AppContainer> - <HorizontalPadding> - <Box> - <Header /> - <Flex> - <FilterSidebar /> - <Box width={["100%", "75%"]}> - <Grid fluid> - <Row> - <Col sm={4} pr={1}> - <GridItem height={200} /> - <GridItem height={400} /> - <GridItem height={240} /> - </Col> - <Col sm={4} pr={1}> - <GridItem height={300} /> - <GridItem height={200} /> - <GridItem height={320} /> - </Col> - <Col sm={4}> - <GridItem height={240} /> - <GridItem height={400} /> - </Col> - </Row> - </Grid> - </Box> - </Flex> - </Box> - </HorizontalPadding> + <Box pl={20}> + <Header /> + <Flex> + <FilterSidebar /> + <Box width={["100%", "75%"]}> + <Grid fluid> + <Row> + <Col xs="6" sm="6" md="6" lg="4"> + <GridItem height={200} /> + <GridItem height={400} /> + <GridItem height={240} /> + </Col> + <Col xs="6" sm="6" md="6" lg="4"> + <GridItem height={300} /> + <GridItem height={200} /> + <GridItem height={320} /> + </Col> + <Col xs="6" sm="6" md="6" lg="4"> + <GridItem height={240} /> + <GridItem height={400} /> + </Col> + </Row> + </Grid> + </Box> + </Flex> + </Box> </AppContainer> ) }
395d8701914b03e330d226335bbbd374792ed7be
tasks/listings.ts
tasks/listings.ts
///<reference path="../typings/main.d.ts" /> import fs = require('fs'); function listings(grunt: IGrunt) { grunt.registerMultiTask('listings', 'Generates listings.json', function() { var done: (status?: boolean) => void = this.async(), cwd = process.cwd(), options = this.options(); grunt.util.spawn({ cmd: 'node', args: [`${cwd}/node_modules/coffee-script/bin/coffee`, `${cwd}/node_modules/browserfs/tools/XHRIndexer.coffee`], opts: {cwd: options.cwd} }, function(error: Error, result: grunt.util.ISpawnResult, code: number) { if (code !== 0 || error) { grunt.fail.fatal("Error generating listings.json: " + result.stderr + error); } fs.writeFileSync(options.output, result.stdout); done(); }); }); } export = listings;
///<reference path="../typings/main.d.ts" /> import fs = require('fs'); function listings(grunt: IGrunt) { grunt.registerMultiTask('listings', 'Generates listings.json', function() { var done: (status?: boolean) => void = this.async(), cwd = process.cwd(), options = this.options(); // Make sure that `programs` folder exists. grunt.util.spawn({ cmd: 'mkdir', args: ['-p', options.cwd] }, function(error: Error, result: grunt.util.ISpawnResult, code: number) { if (code !== 0 || error) { grunt.fail.fatal("Error creating needed directory for listings.json: " + result.stderr + error); } grunt.util.spawn({ cmd: 'node', args: [`${cwd}/node_modules/coffee-script/bin/coffee`, `${cwd}/node_modules/browserfs/tools/XHRIndexer.coffee`], opts: {cwd: options.cwd} }, function(error: Error, result: grunt.util.ISpawnResult, code: number) { if (code !== 0 || error) { grunt.fail.fatal("Error generating listings.json: " + result.stderr + error); } fs.writeFileSync(options.output, result.stdout); done(); }); }); }); } export = listings;
Create `programs` folder if it doesn't exist
Create `programs` folder if it doesn't exist
TypeScript
mit
jvilk/doppio-demo,jvilk/doppio-demo,jvilk/doppio-demo,jvilk/doppio-demo
--- +++ @@ -6,16 +6,27 @@ var done: (status?: boolean) => void = this.async(), cwd = process.cwd(), options = this.options(); + + // Make sure that `programs` folder exists. grunt.util.spawn({ - cmd: 'node', - args: [`${cwd}/node_modules/coffee-script/bin/coffee`, `${cwd}/node_modules/browserfs/tools/XHRIndexer.coffee`], - opts: {cwd: options.cwd} + cmd: 'mkdir', + args: ['-p', options.cwd] }, function(error: Error, result: grunt.util.ISpawnResult, code: number) { if (code !== 0 || error) { - grunt.fail.fatal("Error generating listings.json: " + result.stderr + error); + grunt.fail.fatal("Error creating needed directory for listings.json: " + result.stderr + error); } - fs.writeFileSync(options.output, result.stdout); - done(); + + grunt.util.spawn({ + cmd: 'node', + args: [`${cwd}/node_modules/coffee-script/bin/coffee`, `${cwd}/node_modules/browserfs/tools/XHRIndexer.coffee`], + opts: {cwd: options.cwd} + }, function(error: Error, result: grunt.util.ISpawnResult, code: number) { + if (code !== 0 || error) { + grunt.fail.fatal("Error generating listings.json: " + result.stderr + error); + } + fs.writeFileSync(options.output, result.stdout); + done(); + }); }); }); }
e690a506d9267fc4798bb1dbc90bab36e85f161f
app/src/ui/autocompletion/emoji-autocompletion-provider.tsx
app/src/ui/autocompletion/emoji-autocompletion-provider.tsx
import * as React from 'react' import { IAutocompletionProvider } from './index' /** Autocompletion provider for emoji. */ export default class EmojiAutocompletionProvider implements IAutocompletionProvider<string> { private emoji: Map<string, string> public constructor(emoji: Map<string, string>) { this.emoji = emoji } public getRegExp(): RegExp { return /(\\A|\\n| )(:)([a-z0-9\\+\\-][a-z0-9_]*)?/g } public getAutocompletionItems(text: string) { return Array.from(this.emoji.keys()).filter(e => e.startsWith(`:${text}`)) } public renderItem(emoji: string) { return ( <div key={emoji}> <img className='emoji' src={this.emoji.get(emoji)}/> {emoji} </div> ) } }
import * as React from 'react' import { IAutocompletionProvider } from './index' /** Autocompletion provider for emoji. */ export default class EmojiAutocompletionProvider implements IAutocompletionProvider<string> { private emoji: Map<string, string> public constructor(emoji: Map<string, string>) { this.emoji = emoji } public getRegExp(): RegExp { return /(^|\n| )(:)([a-z0-9\\+\\-][a-z0-9_]*)?/g } public getAutocompletionItems(text: string) { return Array.from(this.emoji.keys()).filter(e => e.startsWith(`:${text}`)) } public renderItem(emoji: string) { return ( <div key={emoji}> <img className='emoji' src={this.emoji.get(emoji)}/> {emoji} </div> ) } }
Stop double escaping and match the start of the line
Stop double escaping and match the start of the line
TypeScript
mit
hjobrien/desktop,BugTesterTest/desktops,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,hjobrien/desktop,kactus-io/kactus,hjobrien/desktop,artivilla/desktop,kactus-io/kactus,desktop/desktop,hjobrien/desktop,artivilla/desktop,desktop/desktop,artivilla/desktop,say25/desktop,BugTesterTest/desktops,j-f1/forked-desktop,gengjiawen/desktop,say25/desktop,artivilla/desktop,gengjiawen/desktop,shiftkey/desktop,j-f1/forked-desktop,BugTesterTest/desktops,shiftkey/desktop,gengjiawen/desktop,desktop/desktop,gengjiawen/desktop,kactus-io/kactus,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,say25/desktop,BugTesterTest/desktops,desktop/desktop
--- +++ @@ -10,7 +10,7 @@ } public getRegExp(): RegExp { - return /(\\A|\\n| )(:)([a-z0-9\\+\\-][a-z0-9_]*)?/g + return /(^|\n| )(:)([a-z0-9\\+\\-][a-z0-9_]*)?/g } public getAutocompletionItems(text: string) {
b80dd72ea9cf5f81102825abb7e250e52ec842ce
client/components/Avatar.tsx
client/components/Avatar.tsx
import React, { SyntheticEvent } from 'react'; const avatarFallback = '/avatar/0.jpg'; const failTimes = new Map(); /** * 处理头像加载失败的情况, 展示默认头像 * @param e 事件 */ function handleError(e: SyntheticEvent) { const times = failTimes.get(e.target) || 0; if (times >= 2) { return; } (e.target as HTMLImageElement).src = avatarFallback; failTimes.set(e.target, times + 1); } interface AvatarProps { /** 头像链接 */ src: string; /** 展示大小 */ size?: number; /** 额外类名 */ className?: string; /** 点击事件 */ onClick?: () => void; onMouseEnter?: () => void; onMouseLeave?: () => void; } const noop = () => {}; function Avatar(props: AvatarProps) { const { src, size = 60, className = '', onClick = noop, onMouseEnter = noop, onMouseLeave = noop, } = props; return ( <img className={className} style={{ width: size, height: size, borderRadius: size / 2 }} src={/(blob|data):/.test(src) ? src : `${src}?imageView2/3/w/${size * 2}/h/${size * 2}`} alt="头像图" onClick={onClick} onError={handleError} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} /> ); } export default Avatar;
import React, { SyntheticEvent } from 'react'; const avatarFallback = '/avatar/0.jpg'; const failTimes = new Map(); /** * 处理头像加载失败的情况, 展示默认头像 * @param e 事件 */ function handleError(e: SyntheticEvent) { const times = failTimes.get(e.target) || 0; if (times >= 2) { return; } (e.target as HTMLImageElement).src = avatarFallback; failTimes.set(e.target, times + 1); } interface AvatarProps { /** 头像链接 */ src: string; /** 展示大小 */ size?: number; /** 额外类名 */ className?: string; /** 点击事件 */ onClick?: () => void; onMouseEnter?: () => void; onMouseLeave?: () => void; } const noop = () => {}; function Avatar(props: AvatarProps) { const { src, size = 60, className = '', onClick = noop, onMouseEnter = noop, onMouseLeave = noop, } = props; return ( <img className={className} style={{ width: size, height: size, borderRadius: size / 2 }} src={/(blob|data):/.test(src) ? src : `${src}?imageView2/3/w/${size * 2}/h/${size * 2}`} alt="" onClick={onClick} onError={handleError} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} /> ); } export default Avatar;
Change avatar image alt to emtry string
feat: Change avatar image alt to emtry string
TypeScript
mit
yinxin630/fiora,yinxin630/fiora,yinxin630/fiora
--- +++ @@ -45,7 +45,7 @@ className={className} style={{ width: size, height: size, borderRadius: size / 2 }} src={/(blob|data):/.test(src) ? src : `${src}?imageView2/3/w/${size * 2}/h/${size * 2}`} - alt="头像图" + alt="" onClick={onClick} onError={handleError} onMouseEnter={onMouseEnter}
5af13d48e2e6265356fb305bdb5b44d02e0583ed
ui/src/Navbar.tsx
ui/src/Navbar.tsx
import React, { CSSProperties, useContext } from 'react'; import { Navbar, Nav } from 'react-bootstrap'; import { useLocation } from 'react-router-dom'; import { JwtContext } from './App'; export default () => { const location = useLocation(); const jwtContext = useContext(JwtContext); return ( <Navbar variant="dark" style={ navbarStyle }> <Navbar.Brand href="/">iDAI.<strong>field</strong></Navbar.Brand> <Nav activeKey={ location.pathname }> <Nav.Link href="/">Projekte</Nav.Link> <Nav.Link href="/download">Download</Nav.Link> <Nav.Link href="/manual">Handbuch</Nav.Link> </Nav> <Navbar.Text>{ jwtContext.user }</Navbar.Text> </Navbar> ); }; const navbarStyle: CSSProperties = { backgroundImage: 'linear-gradient(to right, rgba(106,164,184,0.95) 0%, #557ebb 100%)' };
import React, { CSSProperties, useContext } from 'react'; import { Navbar, Nav } from 'react-bootstrap'; import { useLocation, Link } from 'react-router-dom'; import { JwtContext } from './App'; export default () => { const location = useLocation(); const jwtContext = useContext(JwtContext); return ( <Navbar variant="dark" style={ navbarStyle }> <Navbar.Brand href="/">iDAI.<strong>field</strong></Navbar.Brand> <Nav activeKey={ location.pathname }> <Nav.Link> <Link to="/">Projekte</Link> </Nav.Link> <Nav.Link> <Link to="/download">Download</Link> </Nav.Link> <Nav.Link> <Link to="/manual">Handbuch</Link> </Nav.Link> </Nav> <Navbar.Text>{ jwtContext.user }</Navbar.Text> </Navbar> ); }; const navbarStyle: CSSProperties = { backgroundImage: 'linear-gradient(to right, rgba(106,164,184,0.95) 0%, #557ebb 100%)' };
Use Link component in navbar
Use Link component in navbar
TypeScript
apache-2.0
dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web
--- +++ @@ -1,6 +1,6 @@ import React, { CSSProperties, useContext } from 'react'; import { Navbar, Nav } from 'react-bootstrap'; -import { useLocation } from 'react-router-dom'; +import { useLocation, Link } from 'react-router-dom'; import { JwtContext } from './App'; export default () => { @@ -12,9 +12,15 @@ <Navbar variant="dark" style={ navbarStyle }> <Navbar.Brand href="/">iDAI.<strong>field</strong></Navbar.Brand> <Nav activeKey={ location.pathname }> - <Nav.Link href="/">Projekte</Nav.Link> - <Nav.Link href="/download">Download</Nav.Link> - <Nav.Link href="/manual">Handbuch</Nav.Link> + <Nav.Link> + <Link to="/">Projekte</Link> + </Nav.Link> + <Nav.Link> + <Link to="/download">Download</Link> + </Nav.Link> + <Nav.Link> + <Link to="/manual">Handbuch</Link> + </Nav.Link> </Nav> <Navbar.Text>{ jwtContext.user }</Navbar.Text> </Navbar>
d918d81e102bdd563e78df3d4e0060ebc44c69f1
client/src/app/rp/services/banner-message.service.ts
client/src/app/rp/services/banner-message.service.ts
import { Injectable } from '@angular/core'; import { of } from 'rxjs'; @Injectable() export class BannerMessageService { public message$ = of( 'This is the beta version of RPNow. Please report problems to <a href="mailto:rpnow.net@gmail.com">rpnow.net@gmail.com</a>!' ); }
import { Injectable } from '@angular/core'; import { of } from 'rxjs'; @Injectable() export class BannerMessageService { public message$ = of( 'By using RPNow, you agree to its <a target="_blank" href="/terms">terms of use.</a>' ); }
Change "beta" warning message to "terms of use" message
Change "beta" warning message to "terms of use" message
TypeScript
mit
shamblesides/rpnow,shamblesides/rpnow
--- +++ @@ -5,7 +5,7 @@ export class BannerMessageService { public message$ = of( - 'This is the beta version of RPNow. Please report problems to <a href="mailto:rpnow.net@gmail.com">rpnow.net@gmail.com</a>!' + 'By using RPNow, you agree to its <a target="_blank" href="/terms">terms of use.</a>' ); }
e15ee82c3c108dbe061a0ed531186846498117b2
src/helpers.ts
src/helpers.ts
import * as vscode from 'vscode'; export function isTerraformDocument(document: vscode.TextDocument): boolean { return document.languageId === "terraform"; }
import * as vscode from 'vscode'; import { readFile } from 'fs'; export function isTerraformDocument(document: vscode.TextDocument): boolean { return document.languageId === "terraform"; } export function read(path: string): Promise<string> { return new Promise<string>((resolve, reject) => { readFile(path, (err, data) => { if (err) { reject(err); } else { resolve(data.toString('utf8')); } }); }); }
Add simple async readFile helper
Add simple async readFile helper
TypeScript
mpl-2.0
mauve/vscode-terraform,hashicorp/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform
--- +++ @@ -1,5 +1,18 @@ import * as vscode from 'vscode'; +import { readFile } from 'fs'; export function isTerraformDocument(document: vscode.TextDocument): boolean { return document.languageId === "terraform"; } + +export function read(path: string): Promise<string> { + return new Promise<string>((resolve, reject) => { + readFile(path, (err, data) => { + if (err) { + reject(err); + } else { + resolve(data.toString('utf8')); + } + }); + }); +}
f21b95cd74b4f16c0e0434569e1b4d850e2bc5bd
ng2-bootstrap.ts
ng2-bootstrap.ts
export * from './components/accordion'; export * from './components/alert'; export * from './components/buttons'; export * from './components/carousel'; export * from './components/collapse'; export * from './components/datepicker'; export * from './components/dropdown'; export * from './components/pagination'; export * from './components/progressbar'; export * from './components/rating'; export * from './components/tabs'; export * from './components/timepicker'; export * from './components/tooltip'; export * from './components/typeahead'; export * from './components/position' export * from './components/common' export * from './components/ng2-bootstrap-config';
import {Accordion, AccordionPanel} from './components/accordion'; import {Alert} from './components/alert'; import {ButtonCheckbox, ButtonRadio} from './components/buttons'; import {Carousel, Slide} from './components/carousel'; import {Collapse} from './components/collapse'; import {DatePicker} from './components/datepicker'; import {Dropdown} from './components/dropdown'; import {Pagination, Pager} from './components/pagination'; import {Progressbar, Progress} from './components/progressbar'; import {Rating} from './components/rating'; import {Tabset, Tab, TabHeading} from './components/tabs'; import {Timepicker} from './components/timepicker'; import {Tooltip} from './components/tooltip'; import {Typeahead} from './components/typeahead'; export * from './components/accordion'; export * from './components/alert'; export * from './components/buttons'; export * from './components/carousel'; export * from './components/collapse'; export * from './components/datepicker'; export * from './components/dropdown'; export * from './components/pagination'; export * from './components/progressbar'; export * from './components/rating'; export * from './components/tabs'; export * from './components/timepicker'; export * from './components/tooltip'; export * from './components/typeahead'; export * from './components/position' export * from './components/common' export * from './components/ng2-bootstrap-config'; export default { directives: [Dropdown, Progress, Tab, TabHeading], components: [ Accordion, AccordionPanel, ButtonCheckbox, ButtonRadio, Carousel, Slide, Collapse, DatePicker, Pagination, Pager, Rating, Tabset, Timepicker, Tooltip, Typeahead ] }
Make it compatible with angular-cli
chore(): Make it compatible with angular-cli
TypeScript
mit
imribarr-compit/ng2-bootstrap,felixkubli/ng2-bootstrap,buchslava/angular2-bootstrap,IlyaSurmay/ngx-bootstrap-versioning,lanocturne/ng2-bootstrap,macroorganizm/ng2-bootstrap,buchslava/angular2-bootstrap,valor-software/ng2-bootstrap,vvpanchenko/ng2-bootstrap,BojanKogoj/ng2-bootstrap,valor-software/ngx-bootstrap,Betrozov/ng2-bootstrap,JohanSmolders/ng2-bootstrap,vvpanchenko/ng2-bootstrap,vvpanchenko/ng2-bootstrap,Betrozov/ng2-bootstrap,buchslava/angular2-bootstrap,valor-software/ngx-bootstrap,sublime392/ng2-bootstrap,imribarr-compit/ng2-bootstrap,sublime392/ng2-bootstrap,valor-software/ngx-bootstrap,BojanKogoj/ng2-bootstrap,lanocturne/ng2-bootstrap,lanocturne/ng2-bootstrap,imribarr-compit/ng2-bootstrap,olivierceulemans/ng2-bootstrap,BojanKogoj/ng2-bootstrap,macroorganizm/ng2-bootstrap,felixkubli/ng2-bootstrap,olivierceulemans/ng2-bootstrap,Betrozov/ng2-bootstrap,felixkubli/ng2-bootstrap,IlyaSurmay/ngx-bootstrap-versioning,erodriguezh/ngx-bootstrap,JohanSmolders/ng2-bootstrap,valor-software/ng2-bootstrap,valor-software/ngx-bootstrap,Le0Michine/ng2-bootstrap,Le0Michine/ng2-bootstrap,sublime392/ng2-bootstrap,JohanSmolders/ng2-bootstrap,olivierceulemans/ng2-bootstrap,macroorganizm/ng2-bootstrap
--- +++ @@ -1,3 +1,18 @@ +import {Accordion, AccordionPanel} from './components/accordion'; +import {Alert} from './components/alert'; +import {ButtonCheckbox, ButtonRadio} from './components/buttons'; +import {Carousel, Slide} from './components/carousel'; +import {Collapse} from './components/collapse'; +import {DatePicker} from './components/datepicker'; +import {Dropdown} from './components/dropdown'; +import {Pagination, Pager} from './components/pagination'; +import {Progressbar, Progress} from './components/progressbar'; +import {Rating} from './components/rating'; +import {Tabset, Tab, TabHeading} from './components/tabs'; +import {Timepicker} from './components/timepicker'; +import {Tooltip} from './components/tooltip'; +import {Typeahead} from './components/typeahead'; + export * from './components/accordion'; export * from './components/alert'; export * from './components/buttons'; @@ -16,3 +31,24 @@ export * from './components/position' export * from './components/common' export * from './components/ng2-bootstrap-config'; + +export default { + directives: [Dropdown, Progress, Tab, TabHeading], + components: [ + Accordion, + AccordionPanel, + ButtonCheckbox, + ButtonRadio, + Carousel, + Slide, + Collapse, + DatePicker, + Pagination, + Pager, + Rating, + Tabset, + Timepicker, + Tooltip, + Typeahead + ] +}
9c1879f85bb288ecbf139d38df62648a04441d3c
src/rxjs-redux.ts
src/rxjs-redux.ts
import {Observable} from "rxjs/Observable"; import "rxjs/add/observable/merge"; import "rxjs/add/operator/scan"; import "rxjs/add/operator/publishReplay"; // THIS FILE CONTAINS THE BOILERPLATE CODE YOU NEED TO COPY export interface Reducer<S> { (state: S): S; } export function createState<S>(reducers: Observable<Reducer<S>>, initialState: S): Observable<S> { return reducers .scan( (state: S, reducer: Reducer<S>) => reducer(state), initialState) // these two lines make our observable emit the last state upon subscription .publishReplay(1) .refCount(); } export function createReducer<S>(...observables: Observable<Reducer<S>>[]): Observable<Reducer<S>> { return Observable.merge.apply(Observable, observables); }
import {Observable} from "rxjs/Observable"; import "rxjs/add/observable/merge"; import "rxjs/add/operator/scan"; import "rxjs/add/operator/publishReplay"; // THIS FILE CONTAINS THE BOILERPLATE CODE YOU NEED TO COPY export type Reducer<S> = (state: S) => S; export function createState<S>(reducers: Observable<Reducer<S>>, initialState: S): Observable<S> { return reducers .scan( (state: S, reducer: Reducer<S>) => reducer(state), initialState) // these two lines make our observable emit the last state upon subscription .publishReplay(1) .refCount(); } export function createReducer<S>(...observables: Observable<Reducer<S>>[]): Observable<Reducer<S>> { return Observable.merge.apply(Observable, observables); }
Replace Reducer interface with a type alias to avoid having to import the interface in some cases
Replace Reducer interface with a type alias to avoid having to import the interface in some cases
TypeScript
mit
Dynalon/redux-pattern-with-rx,Dynalon/redux-pattern-with-rx
--- +++ @@ -5,9 +5,7 @@ // THIS FILE CONTAINS THE BOILERPLATE CODE YOU NEED TO COPY -export interface Reducer<S> { - (state: S): S; -} +export type Reducer<S> = (state: S) => S; export function createState<S>(reducers: Observable<Reducer<S>>, initialState: S): Observable<S> { return reducers
e6be73fc9dabf873078f0ca9b44ef71d6ac8b091
src/skinview3d.ts
src/skinview3d.ts
export { SkinObject, CapeObject, PlayerObject } from "./model"; export { SkinViewer } from "./viewer"; export { OrbitControls, createOrbitControls } from "./orbit_controls"; export { invokeAnimation, CompositeAnimation, WalkingAnimation, RunningAnimation, RotatingAnimation } from "./animation"; export { isSlimSkin } from "./utils";
Add back in the main entry point content
Add back in the main entry point content
TypeScript
mit
to2mbn/skinview3d
--- +++ @@ -0,0 +1,26 @@ +export { + SkinObject, + CapeObject, + PlayerObject +} from "./model"; + +export { + SkinViewer +} from "./viewer"; + +export { + OrbitControls, + createOrbitControls +} from "./orbit_controls"; + +export { + invokeAnimation, + CompositeAnimation, + WalkingAnimation, + RunningAnimation, + RotatingAnimation +} from "./animation"; + +export { + isSlimSkin +} from "./utils";
9e869babbcb737303b7966cea4447741a01783b0
src/code/data/migrations/26_remove_minigraphs_visibility.ts
src/code/data/migrations/26_remove_minigraphs_visibility.ts
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const _ = require("lodash"); import { MigrationMixin } from "./migration-mixin"; const migration = { version: "1.25.0", description: "Removes minigraphs settings", date: "2018-11-23", doUpdate(data) { if (data.settings == null) { data.settings = {}; } delete data.settings.showMinigraphs; } }; export const migration_26 = _.mixin(migration, MigrationMixin);
const _ = require("lodash"); import { MigrationMixin } from "./migration-mixin"; const migration = { version: "1.25.0", description: "Removes minigraphs settings", date: "2018-11-23", doUpdate(data) { if (data.settings == null) { data.settings = {}; } delete data.settings.showMinigraphs; } }; export const migration_26 = _.mixin(migration, MigrationMixin);
Remove autogenerated header from the last migration
Remove autogenerated header from the last migration [#162022659]
TypeScript
mit
concord-consortium/building-models,concord-consortium/building-models,concord-consortium/building-models,concord-consortium/building-models,concord-consortium/building-models
--- +++ @@ -1,10 +1,3 @@ -/* - * decaffeinate suggestions: - * DS102: Remove unnecessary code created because of implicit returns - * DS207: Consider shorter variations of null checks - * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md - */ - const _ = require("lodash"); import { MigrationMixin } from "./migration-mixin";
0ab1c71cb66930d396b8e2dcbec4117ddba03611
src/components/MediaTypeSwitch/MediaTypesSwitch.tsx
src/components/MediaTypeSwitch/MediaTypesSwitch.tsx
import { observer } from 'mobx-react'; import * as React from 'react'; import { MediaContentModel, SchemaModel, MediaTypeModel } from '../../services/models'; import { DropdownProps } from '../../common-elements/dropdown'; export interface MediaTypeChildProps { schema: SchemaModel; mime?: string; } export interface MediaTypesSwitchProps { content?: MediaContentModel; renderDropdown: (props: DropdownProps) => JSX.Element; children: (activeMime: MediaTypeModel) => JSX.Element; } @observer export class MediaTypesSwitch extends React.Component<MediaTypesSwitchProps> { switchMedia = ({ value }) => { this.props.content && this.props.content.activate(parseInt(value)); }; render() { const { content } = this.props; if (!content || !content.mediaTypes) return null; const activeMimeIdx = content.activeMimeIdx; let options = content.mediaTypes.map((mime, idx) => { return { label: mime.name, value: idx.toString(), }; }); return ( <div> {this.props.renderDropdown({ value: options[activeMimeIdx], options, onChange: this.switchMedia, })} {this.props.children(content.active)} </div> ); } }
import { observer } from 'mobx-react'; import * as React from 'react'; import { MediaContentModel, SchemaModel, MediaTypeModel } from '../../services/models'; import { DropdownProps } from '../../common-elements/dropdown'; export interface MediaTypeChildProps { schema: SchemaModel; mime?: string; } export interface MediaTypesSwitchProps { content?: MediaContentModel; renderDropdown: (props: DropdownProps) => JSX.Element; children: (activeMime: MediaTypeModel) => JSX.Element; } @observer export class MediaTypesSwitch extends React.Component<MediaTypesSwitchProps> { switchMedia = ({ value }) => { this.props.content && this.props.content.activate(parseInt(value)); }; render() { const { content } = this.props; if (!content || !content.mediaTypes || !content.mediaTypes.length) return null; const activeMimeIdx = content.activeMimeIdx; let options = content.mediaTypes.map((mime, idx) => { return { label: mime.name, value: idx.toString(), }; }); return ( <div> {this.props.renderDropdown({ value: options[activeMimeIdx], options, onChange: this.switchMedia, })} {this.props.children(content.active)} </div> ); } }
Fix crash when content is empty map
Fix crash when content is empty map
TypeScript
mit
Rebilly/ReDoc,Rebilly/ReDoc,Rebilly/ReDoc,Rebilly/ReDoc
--- +++ @@ -23,7 +23,7 @@ render() { const { content } = this.props; - if (!content || !content.mediaTypes) return null; + if (!content || !content.mediaTypes || !content.mediaTypes.length) return null; const activeMimeIdx = content.activeMimeIdx; let options = content.mediaTypes.map((mime, idx) => {
92e9cba8e3a0a9520267c8688c6a0f1b51404e7c
src/css.ts
src/css.ts
import { isBrowser } from './browser' /** * Injects a string of CSS styles to a style node in <head> */ export function injectCSS(css: string): void { if (isBrowser) { const style = document.createElement('style') style.type = 'text/css' style.textContent = css style.setAttribute('data-tippy-stylesheet', '') const head = document.head const { firstChild } = head if (firstChild) { head.insertBefore(style, firstChild) } else { head.appendChild(style) } } }
import { isBrowser } from './browser' /** * Injects a string of CSS styles to a style node in <head> */ export function injectCSS(css: string): void { if (isBrowser) { const style = document.createElement('style') style.type = 'text/css' style.textContent = css style.setAttribute('data-__NAMESPACE_PREFIX__-stylesheet', '') const head = document.head const { firstChild } = head if (firstChild) { head.insertBefore(style, firstChild) } else { head.appendChild(style) } } }
Use namespace prefix for style tag
Use namespace prefix for style tag
TypeScript
mit
atomiks/tippyjs,atomiks/tippyjs,atomiks/tippyjs,atomiks/tippyjs
--- +++ @@ -8,7 +8,7 @@ const style = document.createElement('style') style.type = 'text/css' style.textContent = css - style.setAttribute('data-tippy-stylesheet', '') + style.setAttribute('data-__NAMESPACE_PREFIX__-stylesheet', '') const head = document.head const { firstChild } = head if (firstChild) {
3d0140fdfa40c77c6a760355a915480e73e692de
src/noExpressionStatementRule.ts
src/noExpressionStatementRule.ts
import * as ts from "typescript"; import * as Lint from "tslint/lib/lint"; export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "Using expressions to cause side-effects not allowed."; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { const noExpressionStatementWalker = new NoExpressionStatementWalker(sourceFile, this.getOptions()); return this.applyWithWalker(noExpressionStatementWalker); } } class NoExpressionStatementWalker extends Lint.RuleWalker { public visitNode(node: ts.Node) { if (node && node.kind === ts.SyntaxKind.ExpressionStatement) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); } super.visitNode(node); } }
import * as ts from "typescript"; import * as Lint from "tslint/lib/lint"; export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "Using expressions to cause side-effects not allowed."; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { const noExpressionStatementWalker = new NoExpressionStatementWalker(sourceFile, this.getOptions()); return this.applyWithWalker(noExpressionStatementWalker); } } class NoExpressionStatementWalker extends Lint.RuleWalker { public visitNode(node: ts.Node): void { if (node && node.kind === ts.SyntaxKind.ExpressionStatement) { const children = node.getChildren(); if (children.every((n: ts.Node) => n.kind !== ts.SyntaxKind.YieldExpression)) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); } } super.visitNode(node); } }
Fix for no expression statement rule
Fix for no expression statement rule
TypeScript
mit
jonaskello/tslint-immutable
--- +++ @@ -12,9 +12,12 @@ class NoExpressionStatementWalker extends Lint.RuleWalker { - public visitNode(node: ts.Node) { + public visitNode(node: ts.Node): void { if (node && node.kind === ts.SyntaxKind.ExpressionStatement) { - this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); + const children = node.getChildren(); + if (children.every((n: ts.Node) => n.kind !== ts.SyntaxKind.YieldExpression)) { + this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); + } } super.visitNode(node); }
a8ce879f105a7bafd05bc71e1fe345d95425405e
pages/_app.tsx
pages/_app.tsx
import type { AppProps } from "next/app"; import Router from "next/router"; import NProgress from "nprogress"; import "nprogress/nprogress.css"; import "../styles/index.scss"; NProgress.configure({ showSpinner: false }); Router.events.on("routeChangeStart", () => NProgress.start()); Router.events.on("routeChangeComplete", () => NProgress.done()); Router.events.on("routeChangeError", () => NProgress.done()); export default function GolazonApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} />; }
import type { AppProps } from "next/app"; import Router from "next/router"; import NProgress from "nprogress"; import "nprogress/nprogress.css"; import "../styles/index.scss"; NProgress.configure({ showSpinner: false, minimum: 0 }); Router.events.on("routeChangeStart", () => NProgress.start()); Router.events.on("routeChangeComplete", () => NProgress.done()); Router.events.on("routeChangeError", () => NProgress.done()); export default function GolazonApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} />; }
Set nprogress minimum at 0
Set nprogress minimum at 0
TypeScript
isc
sobstel/golazon,sobstel/golazon,sobstel/golazon
--- +++ @@ -5,7 +5,7 @@ import "nprogress/nprogress.css"; import "../styles/index.scss"; -NProgress.configure({ showSpinner: false }); +NProgress.configure({ showSpinner: false, minimum: 0 }); Router.events.on("routeChangeStart", () => NProgress.start()); Router.events.on("routeChangeComplete", () => NProgress.done()); Router.events.on("routeChangeError", () => NProgress.done());
d3d40c75e569f582ccfd8f4aa70f294786337743
packages/schematics/src/scam/index.ts
packages/schematics/src/scam/index.ts
import { chain, externalSchematic, Rule } from '@angular-devkit/schematics'; import { Schema as NgComponentOptions } from '@schematics/angular/component/schema'; export interface ScamOptions extends NgComponentOptions { separateModule: boolean; } export function scam(options: ScamOptions): Rule { const ruleList = [ externalSchematic('@schematics/angular', 'module', options), externalSchematic('@schematics/angular', 'component', { ...options, export: true, module: options.name }) ]; return chain(ruleList); }
import { chain, externalSchematic, Rule } from '@angular-devkit/schematics'; import { Schema as NgComponentOptions } from '@schematics/angular/component/schema'; export interface ScamOptions extends NgComponentOptions { separateModule: boolean; } export function scam(options: ScamOptions): Rule { let ruleList = [ externalSchematic('@schematics/angular', 'module', options), externalSchematic('@schematics/angular', 'component', { ...options, export: true, module: options.name }) ]; if (!options.separateModule) { ruleList = [ ...ruleList ]; } return chain(ruleList); }
Merge module and component as default behavior.
@wishtack/schematics:scam: Merge module and component as default behavior.
TypeScript
mit
wishtack/ng-steroids,wishtack/wishtack-steroids,wishtack/wishtack-steroids,wishtack/ng-steroids,wishtack/wishtack-steroids
--- +++ @@ -7,7 +7,7 @@ export function scam(options: ScamOptions): Rule { - const ruleList = [ + let ruleList = [ externalSchematic('@schematics/angular', 'module', options), externalSchematic('@schematics/angular', 'component', { ...options, @@ -16,6 +16,12 @@ }) ]; + if (!options.separateModule) { + ruleList = [ + ...ruleList + ]; + } + return chain(ruleList); }
8f31bcb0f63b781d038f63af54316983d40675cd
src/bakeCharts.ts
src/bakeCharts.ts
import {ChartBaker} from './ChartBaker' import * as parseArgs from 'minimist' import * as os from 'os' import * as path from 'path' const argv = parseArgs(process.argv.slice(2)) async function main(email: string, name: string, slug: string) { const baker = new ChartBaker({ canonicalRoot: 'https://ourworldindata.org', pathRoot: '/grapher', repoDir: path.join(__dirname, `../../public`) }) try { await baker.bakeAll() if (email && name && slug) await baker.deploy(email, name, `Updating ${slug}`) else await baker.deploy("Automated update") } catch (err) { console.error(err) } finally { baker.end() } } main(argv._[0], argv._[1], argv._[2])
import {ChartBaker} from './ChartBaker' import * as parseArgs from 'minimist' import * as os from 'os' import * as path from 'path' const argv = parseArgs(process.argv.slice(2)) async function main(email: string, name: string, slug: string) { const baker = new ChartBaker({ canonicalRoot: 'https://ourworldindata.org', pathRoot: '/grapher', repoDir: path.join(__dirname, `../../public`), regenConfig: argv.regenConfig }) try { await baker.bakeAll() if (email && name && slug) await baker.deploy(email, name, `Updating ${slug}`) else await baker.deploy("Automated update") } catch (err) { console.error(err) } finally { baker.end() } } main(argv._[0], argv._[1], argv._[2])
Allow force regen from command line
Allow force regen from command line
TypeScript
mit
aaldaber/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,aaldaber/owid-grapher,OurWorldInData/our-world-in-data-grapher,aaldaber/owid-grapher,OurWorldInData/our-world-in-data-grapher,aaldaber/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,aaldaber/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher
--- +++ @@ -8,7 +8,8 @@ const baker = new ChartBaker({ canonicalRoot: 'https://ourworldindata.org', pathRoot: '/grapher', - repoDir: path.join(__dirname, `../../public`) + repoDir: path.join(__dirname, `../../public`), + regenConfig: argv.regenConfig }) try {
b338ed1ed273f6d109f5515d6f87ad7aa90b8a7c
packages/@sanity/desk-tool/src/diffs/annotationTooltip/annotationTooltip.tsx
packages/@sanity/desk-tool/src/diffs/annotationTooltip/annotationTooltip.tsx
import React from 'react' import {useUser, LOADING_USER} from '@sanity/react-hooks' import {Tooltip} from 'react-tippy' import {UserAvatar} from '@sanity/components/presence' import {Annotation, AnnotationChanged} from '../../panes/documentPane/history/types' import styles from './annotationTooltip.css' interface AnnotationTooltipProps { annotation: Annotation children: React.ReactNode } export function AnnotationTooltip(props: AnnotationTooltipProps) { if (props.annotation.type === 'unchanged') { return <>{props.children}</> } return ( <Tooltip arrow html={<AnnotationTooltipContent annotation={props.annotation} />} position="top" theme="light" > {props.children} </Tooltip> ) } function AnnotationTooltipContent(props: {annotation: AnnotationChanged}) { return ( <div className={styles.root}> <UserItem userId={props.annotation.author} /> </div> ) } function UserItem(props: {userId: string}) { const user = useUser(props.userId) return ( <div className={styles.userItem}> {user && user !== LOADING_USER ? ( <> <UserAvatar user={user} /> {user.displayName} </> ) : ( 'Loading…' )} </div> ) }
import React from 'react' import {useUser} from '@sanity/react-hooks' import {Tooltip} from 'react-tippy' import {UserAvatar} from '@sanity/components/presence' import {Annotation, AnnotationChanged} from '../../panes/documentPane/history/types' import styles from './annotationTooltip.css' interface AnnotationTooltipProps { annotation: Annotation children: React.ReactNode } export function AnnotationTooltip(props: AnnotationTooltipProps) { if (props.annotation.type === 'unchanged') { return <>{props.children}</> } return ( <Tooltip arrow html={<AnnotationTooltipContent annotation={props.annotation} />} position="top" theme="light" > {props.children} </Tooltip> ) } function AnnotationTooltipContent(props: {annotation: AnnotationChanged}) { return ( <div className={styles.root}> <UserItem userId={props.annotation.author} /> </div> ) } function UserItem(props: {userId: string}) { const {isLoading, error, value: user} = useUser(props.userId) // @todo handle? if (error) { return null } return ( <div className={styles.userItem}> {isLoading && 'Loading…'} {user && ( <> <UserAvatar user={user} /> {user.displayName} </> )} </div> ) }
Use new useUser API for annotation tooltips
[desk-tool] Use new useUser API for annotation tooltips
TypeScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
--- +++ @@ -1,5 +1,5 @@ import React from 'react' -import {useUser, LOADING_USER} from '@sanity/react-hooks' +import {useUser} from '@sanity/react-hooks' import {Tooltip} from 'react-tippy' import {UserAvatar} from '@sanity/components/presence' import {Annotation, AnnotationChanged} from '../../panes/documentPane/history/types' @@ -37,15 +37,20 @@ } function UserItem(props: {userId: string}) { - const user = useUser(props.userId) + const {isLoading, error, value: user} = useUser(props.userId) + + // @todo handle? + if (error) { + return null + } + return ( <div className={styles.userItem}> - {user && user !== LOADING_USER ? ( + {isLoading && 'Loading…'} + {user && ( <> <UserAvatar user={user} /> {user.displayName} </> - ) : ( - 'Loading…' )} </div> )
36016d34220f6a7e24dc2465d24e4858ae88d03c
index.ts
index.ts
import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core"; import { AirOptions } from "./lib/options"; import { AirCalendar } from "./lib/calendar"; import { LANGUAGES, AirLanguage } from "./lib/languages"; @Component({ selector: 'air-datepicker', templateUrl: './template.html', styleUrls: ['./style.css'] }) export class AirDatepicker implements OnInit { @Input() airOptions: AirOptions; @Input() airDate: Date; @Output() airChange = new EventEmitter<Date>(); airLanguage: AirLanguage; airCalendar: AirCalendar; ngOnInit () { if (!this.airOptions) { this.airOptions = new AirOptions; } this.airLanguage = LANGUAGES.get(this.airOptions.language); this.airCalendar = new AirCalendar(this.airDate); } setDate (index?: number) { if (this.airCalendar.airDays[index]) { this.airCalendar.selectDate(index); } this.airDate.setTime(Date.parse(`${this.airCalendar.year}/${this.airCalendar.month + 1}/${this.airCalendar.date} ${this.airCalendar.hour}:${this.airCalendar.minute}`)); this.airChange.emit(this.airDate); } }
import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core"; import { AirOptions } from "./lib/options"; import { AirCalendar } from "./lib/calendar"; import { LANGUAGES, AirLanguage } from "./lib/languages"; @Component({ selector: 'air-datepicker', templateUrl: './template.html', styleUrls: ['./style.css'] }) export class AirDatepicker implements OnInit { @Input() airOptions: AirOptions; @Input() airDate: Date; @Output() airChange = new EventEmitter<Date>(); airLanguage: AirLanguage; airCalendar: AirCalendar; ngOnInit () { this.airOptions = Object.assign(new AirOptions, this.airOptions || {}); this.airLanguage = LANGUAGES.get(this.airOptions.language); this.airCalendar = new AirCalendar(this.airDate); } setDate (index?: number) { if (this.airCalendar.airDays[index]) { this.airCalendar.selectDate(index); } this.airDate.setTime(Date.parse(`${this.airCalendar.year}/${this.airCalendar.month + 1}/${this.airCalendar.date} ${this.airCalendar.hour}:${this.airCalendar.minute}`)); this.airChange.emit(this.airDate); } }
Make sure default options are used when partial options are supplied
Make sure default options are used when partial options are supplied Closes #6
TypeScript
mit
kesarion/angular2-air-datepicker,kesarion/angular2-air-datepicker,kesarion/angular2-air-datepicker
--- +++ @@ -19,9 +19,7 @@ airCalendar: AirCalendar; ngOnInit () { - if (!this.airOptions) { - this.airOptions = new AirOptions; - } + this.airOptions = Object.assign(new AirOptions, this.airOptions || {}); this.airLanguage = LANGUAGES.get(this.airOptions.language); this.airCalendar = new AirCalendar(this.airDate); }
360b22e9dad9b3d44d31c761a05a865fcd4e70e4
cypress/integration/navigation.spec.ts
cypress/integration/navigation.spec.ts
import { visitExample } from '../helper'; describe('Navigation', () => { beforeEach(() => { visitExample('official-storybook'); }); it('should search navigation item', () => { cy.get('#storybook-explorer-searchfield') .click() .type('persisting the action logger'); cy.get('.sidebar-container a') .should('contain', 'Persisting the action logger') .and('not.contain', 'a11y'); }); it('should display no results after searching a non-existing navigation item', () => { cy.get('#storybook-explorer-searchfield') .click() .type('zzzzzzzzzz'); cy.get('.sidebar-container').should('contain', 'This filter resulted in 0 results'); }); }); describe('Routing', () => { it('should navigate to story addons-a11y-basebutton--default', () => { visitExample('official-storybook'); cy.get('#exploreraddons-a11y-basebutton--label').click(); cy.url().should('include', 'path=/story/addons-a11y-basebutton--label'); }); it('should directly visit a certain story and render correctly', () => { visitExample('official-storybook', '?path=/story/addons-a11y-basebutton--label'); cy.preview().should('contain.text', 'Testing the a11y addon'); }); });
/* eslint-disable jest/expect-expect */ import { visitExample } from '../helper'; describe('Navigation', () => { before(() => { visitExample('official-storybook'); }); it('should search navigation item', () => { cy.get('#storybook-explorer-searchfield') .click() .clear() .type('persisting the action logger'); cy.get('.sidebar-container a') .should('contain', 'Persisting the action logger') .and('not.contain', 'a11y'); }); it('should display no results after searching a non-existing navigation item', () => { cy.get('#storybook-explorer-searchfield') .click() .clear() .type('zzzzzzzzzz'); cy.get('.sidebar-container').should('contain', 'This filter resulted in 0 results'); }); }); describe('Routing', () => { before(() => { visitExample('official-storybook'); }); it('should navigate to story addons-a11y-basebutton--default', () => { cy.get('#addons-a11y-basebutton--label').click(); cy.url().should('include', 'path=/story/addons-a11y-basebutton--label'); }); it('should directly visit a certain story and render correctly', () => { visitExample('official-storybook', '?path=/story/addons-a11y-basebutton--label'); cy.preview().should('contain.text', 'Testing the a11y addon'); }); });
IMPROVE the navigation e2e cypress test
IMPROVE the navigation e2e cypress test
TypeScript
mit
storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook
--- +++ @@ -1,13 +1,15 @@ +/* eslint-disable jest/expect-expect */ import { visitExample } from '../helper'; describe('Navigation', () => { - beforeEach(() => { + before(() => { visitExample('official-storybook'); }); it('should search navigation item', () => { cy.get('#storybook-explorer-searchfield') .click() + .clear() .type('persisting the action logger'); cy.get('.sidebar-container a') @@ -18,6 +20,7 @@ it('should display no results after searching a non-existing navigation item', () => { cy.get('#storybook-explorer-searchfield') .click() + .clear() .type('zzzzzzzzzz'); cy.get('.sidebar-container').should('contain', 'This filter resulted in 0 results'); @@ -25,9 +28,12 @@ }); describe('Routing', () => { + before(() => { + visitExample('official-storybook'); + }); + it('should navigate to story addons-a11y-basebutton--default', () => { - visitExample('official-storybook'); - cy.get('#exploreraddons-a11y-basebutton--label').click(); + cy.get('#addons-a11y-basebutton--label').click(); cy.url().should('include', 'path=/story/addons-a11y-basebutton--label'); });
f1ebe811731f6bd3c4789ac09f120793633e73ad
src/actions/blockHitGroup.ts
src/actions/blockHitGroup.ts
import { BLOCK_HIT, UNBLOCK_HIT, UNBLOCK_MULTIPLE_HITS } from '../constants'; import { BlockedHit } from '../types'; import { Set } from 'immutable'; export interface BlockHit { readonly type: BLOCK_HIT; readonly data: BlockedHit; } export interface UnblockHit { readonly type: UNBLOCK_HIT; readonly groupId: string; } export interface UnblockMultipleHits { readonly type: UNBLOCK_MULTIPLE_HITS; readonly groupIds: Set<string>; } export type BlockHitAction = BlockHit | UnblockHit | UnblockMultipleHits; export const blockHitGroup = (data: BlockedHit): BlockHit => ({ type: BLOCK_HIT, data }); export const unblockHitGroup = (groupId: string): UnblockHit => ({ type: UNBLOCK_HIT, groupId });
import { BLOCK_HIT, UNBLOCK_HIT, UNBLOCK_MULTIPLE_HITS } from '../constants'; import { BlockedHit, GroupId } from '../types'; import { Set } from 'immutable'; export interface BlockHit { readonly type: BLOCK_HIT; readonly data: BlockedHit; } export interface UnblockHit { readonly type: UNBLOCK_HIT; readonly groupId: string; } export interface UnblockMultipleHits { readonly type: UNBLOCK_MULTIPLE_HITS; readonly groupIds: Set<GroupId>; } export type BlockHitAction = BlockHit | UnblockHit | UnblockMultipleHits; export const blockHitGroup = (data: BlockedHit): BlockHit => ({ type: BLOCK_HIT, data }); export const unblockHitGroup = (groupId: string): UnblockHit => ({ type: UNBLOCK_HIT, groupId });
Use more expressive type name for UnblockMultipleHits.
Use more expressive type name for UnblockMultipleHits.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -1,5 +1,5 @@ import { BLOCK_HIT, UNBLOCK_HIT, UNBLOCK_MULTIPLE_HITS } from '../constants'; -import { BlockedHit } from '../types'; +import { BlockedHit, GroupId } from '../types'; import { Set } from 'immutable'; export interface BlockHit { @@ -14,7 +14,7 @@ export interface UnblockMultipleHits { readonly type: UNBLOCK_MULTIPLE_HITS; - readonly groupIds: Set<string>; + readonly groupIds: Set<GroupId>; } export type BlockHitAction = BlockHit | UnblockHit | UnblockMultipleHits;
84bb977f278e88b6250ff429d54ff0dfbd6bb640
src/gui/storage.ts
src/gui/storage.ts
class WebStorage { private storageObj: Storage; public constructor(storageObj: Storage) { this.storageObj = storageObj; } public get(key: string): string { if (!this.isCompatible()) { return; } return this.storageObj.getItem(key); } public getObj(key: string): any { if (!this.isCompatible()) { return; } try { return JSON.parse(this.get(key)); } catch (e) { console.log(e.message); } } public set(key: string, value: string): void { if (!this.isCompatible()) { return; } this.storageObj.setItem(key, value); } public setObj(key: string, value: Object): void { if (!this.isCompatible()) { return; } try { this.set(key, JSON.stringify(value)); } catch (e) { console.log(e.message); } } private isCompatible(): boolean { if (typeof(Storage) !== 'undefined') { return true; } else { console.log('Your browser does not support Web Storage.'); return false; } } }
class WebStorage { private storageObj: Storage; public constructor(storageObj: Storage) { this.storageObj = storageObj; } public get(key: string): string { if (!this.isCompatible()) { return; } return this.storageObj.getItem(key); } public getObj(key: string): any { if (!this.isCompatible()) { return; } try { return JSON.parse(this.get(key)); } catch (e) { console.log('Invalid JSON: ' + e.message); } } public set(key: string, value: string): void { if (!this.isCompatible()) { return; } this.storageObj.setItem(key, value); } public setObj(key: string, value: Object): void { if (!this.isCompatible()) { return; } try { this.set(key, JSON.stringify(value)); } catch (e) { console.log('Invalid JSON: ' + e.message); } } private isCompatible(): boolean { if (typeof(Storage) !== 'undefined') { return true; } else { console.log('Your browser does not support Web Storage.'); return false; } } }
Add more descriptive error messages on JSON exceptions
Add more descriptive error messages on JSON exceptions
TypeScript
mit
CAAL/CAAL,CAAL/CAAL,CAAL/CAAL,CAAL/CAAL
--- +++ @@ -17,7 +17,7 @@ try { return JSON.parse(this.get(key)); } catch (e) { - console.log(e.message); + console.log('Invalid JSON: ' + e.message); } } @@ -33,7 +33,7 @@ try { this.set(key, JSON.stringify(value)); } catch (e) { - console.log(e.message); + console.log('Invalid JSON: ' + e.message); } }
6e6cb3bb651740ff87df93d1190110c169cfdd59
src/geometries/ConeGeometry.d.ts
src/geometries/ConeGeometry.d.ts
import { CylinderGeometry } from './CylinderGeometry'; export class ConeGeometry extends CylinderGeometry { /** * @param [radius=1] — Radius of the cone base. * @param [height=1] — Height of the cone. * @param [radiusSegments=8] — Number of segmented faces around the circumference of the cone. * @param [heightSegments=1] — Number of rows of faces along the height of the cone. * @param [openEnded=false] — A Boolean indicating whether the base of the cone is open or capped. * @param [thetaStart=0] * @param [thetaLength=Math.PI * 2] */ constructor( radius?: number, height?: number, radialSegment?: number, heightSegment?: number, openEnded?: boolean, thetaStart?: number, thetaLength?: number ); /** * @default 'ConeGeometry' */ type: string; }
import { CylinderGeometry } from './CylinderGeometry'; export class ConeGeometry extends CylinderGeometry { /** * @param [radius=1] — Radius of the cone base. * @param [height=1] — Height of the cone. * @param [radialSegments=8] — Number of segmented faces around the circumference of the cone. * @param [heightSegments=1] — Number of rows of faces along the height of the cone. * @param [openEnded=false] — A Boolean indicating whether the base of the cone is open or capped. * @param [thetaStart=0] * @param [thetaLength=Math.PI * 2] */ constructor( radius?: number, height?: number, radialSegments?: number, heightSegments?: number, openEnded?: boolean, thetaStart?: number, thetaLength?: number ); /** * @default 'ConeGeometry' */ type: string; }
Fix typo in ConeGeometry (again)
Fix typo in ConeGeometry (again)
TypeScript
mit
fyoudine/three.js,Liuer/three.js,fyoudine/three.js,gero3/three.js,WestLangley/three.js,06wj/three.js,looeee/three.js,kaisalmen/three.js,mrdoob/three.js,greggman/three.js,aardgoose/three.js,WestLangley/three.js,mrdoob/three.js,gero3/three.js,donmccurdy/three.js,jpweeks/three.js,kaisalmen/three.js,makc/three.js.fork,Liuer/three.js,06wj/three.js,makc/three.js.fork,donmccurdy/three.js,jpweeks/three.js,greggman/three.js,aardgoose/three.js,looeee/three.js
--- +++ @@ -5,7 +5,7 @@ /** * @param [radius=1] — Radius of the cone base. * @param [height=1] — Height of the cone. - * @param [radiusSegments=8] — Number of segmented faces around the circumference of the cone. + * @param [radialSegments=8] — Number of segmented faces around the circumference of the cone. * @param [heightSegments=1] — Number of rows of faces along the height of the cone. * @param [openEnded=false] — A Boolean indicating whether the base of the cone is open or capped. * @param [thetaStart=0] @@ -14,8 +14,8 @@ constructor( radius?: number, height?: number, - radialSegment?: number, - heightSegment?: number, + radialSegments?: number, + heightSegments?: number, openEnded?: boolean, thetaStart?: number, thetaLength?: number
65798c7539eb90c19804cd0cbc8bb86fb2022430
packages/components/hooks/useOnline.ts
packages/components/hooks/useOnline.ts
import { useEffect, useState } from 'react'; const getOnlineStatus = () => { return typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean' ? navigator.onLine : true; }; const useOnline = () => { const [onlineStatus, setOnlineStatus] = useState(getOnlineStatus()); useEffect(() => { const goOnline = () => setOnlineStatus(true); const goOffline = () => setOnlineStatus(false); window.addEventListener('online', goOnline); window.addEventListener('offline', goOffline); return () => { window.removeEventListener('online', goOnline); window.removeEventListener('offline', goOffline); }; }, []); return onlineStatus; }; export default useOnline;
import { useEffect, useState } from 'react'; const getOnlineStatus = () => { return typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean' ? navigator.onLine : true; }; const useOnline = () => { const [onlineStatus, setOnlineStatus] = useState(getOnlineStatus()); useEffect(() => { const goOnline = () => setOnlineStatus(true); const goOffline = () => setOnlineStatus(false); setOnlineStatus(getOnlineStatus()); window.addEventListener('online', goOnline); window.addEventListener('offline', goOffline); return () => { window.removeEventListener('online', goOnline); window.removeEventListener('offline', goOffline); }; }, []); return onlineStatus; }; export default useOnline;
Read online status in effect
Read online status in effect If the online status would have changed between render and effect, it'd use a stale value. Re-read it to make sure it's up-to-date.
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -10,6 +10,8 @@ useEffect(() => { const goOnline = () => setOnlineStatus(true); const goOffline = () => setOnlineStatus(false); + + setOnlineStatus(getOnlineStatus()); window.addEventListener('online', goOnline); window.addEventListener('offline', goOffline);
c4ddc9f53862b2104a1bb19fd555d5f674035d02
test/isaac-generator.test.ts
test/isaac-generator.test.ts
/// <reference path="../typings/tape/tape.d.ts"/> import * as test from 'tape'; import { IsaacGenerator } from '../src/isaac-generator'; test("getValue calls _randomise if count is 0", (t) => { let generator = new IsaacGenerator(); generator["_count"] = 0; let _randomiseCalled = false; generator["_randomise"] = () => { _randomiseCalled = true; } generator.getValue(); t.true(_randomiseCalled, "_randomise called"); t.end(); }); test("getValue calls _randomise if count is -1", (t) => { let generator = new IsaacGenerator(); generator["_count"] = -1; let _randomiseCalled = false; generator["_randomise"] = () => { _randomiseCalled = true; } generator.getValue(); t.true(_randomiseCalled, "_randomise called"); t.end(); }); test("getValue does not call _randomise if count is 1", (t) => { let generator = new IsaacGenerator(); generator["_count"] = 1; let _randomiseCalled = false; generator["_randomise"] = () => { _randomiseCalled = true; } generator.getValue(); t.false(_randomiseCalled, "_randomise not called"); t.end(); });
/// <reference path="../typings/tape/tape.d.ts"/> import * as test from 'tape'; import { IsaacGenerator } from '../src/isaac-generator'; test("getValue calls _randomise if count is 0", (t) => { t.plan(1); let generator = new IsaacGenerator(); generator["_randomise"] = () => { t.pass("_randomise called"); } generator["_count"] = 0; generator.getValue(); }); test("getValue calls _randomise if count is -1", (t) => { t.plan(1); let generator = new IsaacGenerator(); generator["_randomise"] = () => { t.pass("_randomise called"); } generator["_count"] = -1; generator.getValue(); }); test("getValue does not call _randomise if count is 1", (t) => { let generator = new IsaacGenerator(); let _randomiseCalled = false; generator["_randomise"] = () => { _randomiseCalled = true; } generator["_count"] = 1; generator.getValue(); t.false(_randomiseCalled, "_randomise not called"); t.end(); });
Use plan/pass rather than booleans where possible
Use plan/pass rather than booleans where possible
TypeScript
mit
Jameskmonger/isaac-crypto
--- +++ @@ -4,44 +4,37 @@ import { IsaacGenerator } from '../src/isaac-generator'; test("getValue calls _randomise if count is 0", (t) => { + t.plan(1); let generator = new IsaacGenerator(); + + generator["_randomise"] = () => { + t.pass("_randomise called"); + } + generator["_count"] = 0; + generator.getValue(); +}); +test("getValue calls _randomise if count is -1", (t) => { + t.plan(1); + let generator = new IsaacGenerator(); + + generator["_randomise"] = () => { + t.pass("_randomise called"); + } + + generator["_count"] = -1; + generator.getValue(); +}); + +test("getValue does not call _randomise if count is 1", (t) => { + let generator = new IsaacGenerator(); let _randomiseCalled = false; generator["_randomise"] = () => { _randomiseCalled = true; } - generator.getValue(); - - t.true(_randomiseCalled, "_randomise called"); - t.end(); -}); - -test("getValue calls _randomise if count is -1", (t) => { - let generator = new IsaacGenerator(); - generator["_count"] = -1; - - let _randomiseCalled = false; - generator["_randomise"] = () => { - _randomiseCalled = true; - } - - generator.getValue(); - - t.true(_randomiseCalled, "_randomise called"); - t.end(); -}); - -test("getValue does not call _randomise if count is 1", (t) => { - let generator = new IsaacGenerator(); generator["_count"] = 1; - - let _randomiseCalled = false; - generator["_randomise"] = () => { - _randomiseCalled = true; - } - generator.getValue(); t.false(_randomiseCalled, "_randomise not called");
92397aa1cc6469b9ef977f0754aaa2a254e7f6e3
src/environment.ts
src/environment.ts
// Angular 2 import {enableDebugTools} from "@angular/platform-browser"; import {enableProdMode, ApplicationRef} from "@angular/core"; // Angular debug tools in the dev console // https://github.com/angular/angular/blob/86405345b781a9dc2438c0fbe3e9409245647019/TOOLS_JS.md let _decorateModuleRef = function identity<T>(value: T): T { return value; }; if ("production" === ENV) { // Since the debug tools are disabled by default in v4, we don't have to explicitly disable them as we had to before. enableProdMode(); } else { _decorateModuleRef = (modRef: any) => { const appRef = modRef.injector.get(ApplicationRef); const cmpRef = appRef.components[0]; let _ng = (<any>window).ng; enableDebugTools(cmpRef); (<any>window).ng.probe = _ng.probe; (<any>window).ng.coreTokens = _ng.coreTokens; return modRef; }; } export const decorateModuleRef = _decorateModuleRef;
// Angular 2 import {enableDebugTools} from "@angular/platform-browser"; import {enableProdMode} from "@angular/core"; // Angular debug tools in the dev console // https://github.com/angular/angular/blob/86405345b781a9dc2438c0fbe3e9409245647019/TOOLS_JS.md let _decorateModuleRef = function identity<T>(value: T): T { return value; }; if ("production" === ENV) { // Since the debug tools are disabled by default in v4, we don't have to explicitly disable them as we had to before. enableProdMode(); } else { _decorateModuleRef = (modRef: any) => { /* Note: In earlier versions, it was required to pick a reference to the `window.ng` token for properly adding the debug tools without getting them overwritten by angular. const appRef = modRef.injector.get(ApplicationRef); const cmpRef = appRef.components[0]; let _ng = (<any>window).ng; enableDebugTools(cmpRef); (<any>window).ng.probe = _ng.probe; (<any>window).ng.coreTokens = _ng.coreTokens; This was tracked in https://github.com/angular/angular/issues/12002. Since the corresponding pull request https://github.com/angular/angular/pull/12003 is merged, this workaround is no longer required. */ enableDebugTools(modRef); return modRef; }; } export const decorateModuleRef = _decorateModuleRef;
Remove no longer required workaround for enabling the angular debug tools
(cleanup): Remove no longer required workaround for enabling the angular debug tools
TypeScript
mit
DorianGrey/ng2-webpack-template,DorianGrey/ng2-webpack-template,DorianGrey/ng-webpack-template,DorianGrey/ng-webpack-template,DorianGrey/ng-webpack-template,DorianGrey/ng2-webpack-template
--- +++ @@ -1,6 +1,6 @@ // Angular 2 import {enableDebugTools} from "@angular/platform-browser"; -import {enableProdMode, ApplicationRef} from "@angular/core"; +import {enableProdMode} from "@angular/core"; // Angular debug tools in the dev console // https://github.com/angular/angular/blob/86405345b781a9dc2438c0fbe3e9409245647019/TOOLS_JS.md @@ -15,13 +15,25 @@ } else { _decorateModuleRef = (modRef: any) => { - const appRef = modRef.injector.get(ApplicationRef); - const cmpRef = appRef.components[0]; + /* + Note: In earlier versions, it was required to pick a reference to the + `window.ng` token for properly adding the debug tools without getting them overwritten + by angular. - let _ng = (<any>window).ng; - enableDebugTools(cmpRef); - (<any>window).ng.probe = _ng.probe; - (<any>window).ng.coreTokens = _ng.coreTokens; + const appRef = modRef.injector.get(ApplicationRef); + const cmpRef = appRef.components[0]; + + let _ng = (<any>window).ng; + enableDebugTools(cmpRef); + (<any>window).ng.probe = _ng.probe; + (<any>window).ng.coreTokens = _ng.coreTokens; + + This was tracked in https://github.com/angular/angular/issues/12002. + Since the corresponding pull request https://github.com/angular/angular/pull/12003 is merged, + this workaround is no longer required. + */ + enableDebugTools(modRef); + return modRef; }; }
fda898e14a4914579851c5988ee2f6ba53d1f630
saleor/static/dashboard-next/storybook/stories/products/ProductCreatePage.tsx
saleor/static/dashboard-next/storybook/stories/products/ProductCreatePage.tsx
import { storiesOf } from "@storybook/react"; import * as React from "react"; import ProductCreatePage from "../../../products/components/ProductCreatePage"; import { product as productFixture } from "../../../products/fixtures"; import { productTypes } from "../../../productTypes/fixtures"; import Decorator from "../../Decorator"; const product = productFixture(""); storiesOf("Views / Products / Create product", module) .addDecorator(Decorator) .add("default", () => ( <ProductCreatePage currency="USD" disabled={false} errors={[]} header="Add product" collections={product.collections} fetchCategories={() => undefined} fetchCollections={() => undefined} productTypes={productTypes} categories={[product.category]} onAttributesEdit={undefined} onBack={() => undefined} onSubmit={() => undefined} saveButtonBarState="default" /> )) .add("When loading", () => ( <ProductCreatePage currency="USD" disabled={true} errors={[]} header="Add product" collections={product.collections} fetchCategories={() => undefined} fetchCollections={() => undefined} productTypes={productTypes} categories={[product.category]} onAttributesEdit={undefined} onBack={() => undefined} onSubmit={() => undefined} saveButtonBarState="default" /> ));
import { storiesOf } from "@storybook/react"; import * as React from "react"; import ProductCreatePage, { FormData } from "../../../products/components/ProductCreatePage"; import { formError } from "../../misc"; import { product as productFixture } from "../../../products/fixtures"; import { productTypes } from "../../../productTypes/fixtures"; import Decorator from "../../Decorator"; const product = productFixture(""); storiesOf("Views / Products / Create product", module) .addDecorator(Decorator) .add("default", () => ( <ProductCreatePage currency="USD" disabled={false} errors={[]} header="Add product" collections={product.collections} fetchCategories={() => undefined} fetchCollections={() => undefined} productTypes={productTypes} categories={[product.category]} onAttributesEdit={undefined} onBack={() => undefined} onSubmit={() => undefined} saveButtonBarState="default" /> )) .add("When loading", () => ( <ProductCreatePage currency="USD" disabled={true} errors={[]} header="Add product" collections={product.collections} fetchCategories={() => undefined} fetchCollections={() => undefined} productTypes={productTypes} categories={[product.category]} onAttributesEdit={undefined} onBack={() => undefined} onSubmit={() => undefined} saveButtonBarState="default" /> )) .add("form errors", () => ( <ProductCreatePage currency="USD" disabled={false} errors={(["name", "productType", "category", "sku"] as Array< keyof FormData >).map(field => formError(field))} header="Add product" collections={product.collections} fetchCategories={() => undefined} fetchCollections={() => undefined} productTypes={productTypes} categories={[product.category]} onAttributesEdit={undefined} onBack={() => undefined} onSubmit={() => undefined} saveButtonBarState="default" /> ));
Add new product error view to storybook
Add new product error view to storybook
TypeScript
bsd-3-clause
UITools/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor
--- +++ @@ -1,7 +1,12 @@ import { storiesOf } from "@storybook/react"; import * as React from "react"; -import ProductCreatePage from "../../../products/components/ProductCreatePage"; +import ProductCreatePage, { + FormData +} from "../../../products/components/ProductCreatePage"; + +import { formError } from "../../misc"; + import { product as productFixture } from "../../../products/fixtures"; import { productTypes } from "../../../productTypes/fixtures"; import Decorator from "../../Decorator"; @@ -43,4 +48,23 @@ onSubmit={() => undefined} saveButtonBarState="default" /> + )) + .add("form errors", () => ( + <ProductCreatePage + currency="USD" + disabled={false} + errors={(["name", "productType", "category", "sku"] as Array< + keyof FormData + >).map(field => formError(field))} + header="Add product" + collections={product.collections} + fetchCategories={() => undefined} + fetchCollections={() => undefined} + productTypes={productTypes} + categories={[product.category]} + onAttributesEdit={undefined} + onBack={() => undefined} + onSubmit={() => undefined} + saveButtonBarState="default" + /> ));
4d2c0e41616111b6b13f8688bd7b15d0867b0bdd
src/misc/dependencyInfo.ts
src/misc/dependencyInfo.ts
import Logger from './logger'; import { execSync } from 'child_process'; export default class { private logger: Logger; constructor() { this.logger = new Logger('Deps'); } public showAll(): void { this.show('MongoDB', 'mongo --version', x => x.match(/^MongoDB shell version:? (.*)\r?\n/)); this.show('Redis', 'redis-server --version', x => x.match(/v=([0-9\.]*)/)); this.show('ImageMagick', 'magick -version', x => x.match(/^Version: ImageMagick (.+?)\r?\n/)); } public show(serviceName: string, command: string, transform: (x: string) => RegExpMatchArray): void { try { // ステータス0以外のときにexecSyncはstderrをコンソール上に出力してしまうので // プロセスからのstderrをすべて無視するように stdio オプションをセット const x = execSync(command, { stdio: ['pipe', 'pipe', 'ignore'] }); const ver = transform(x.toString()); if (ver != null) { this.logger.succ(`${serviceName} ${ver[1]} found`); } else { this.logger.warn(`${serviceName} not found`); this.logger.warn(`Regexp used for version check of ${serviceName} is probably messed up`); } } catch (e) { this.logger.warn(`${serviceName} not found`); } } }
import Logger from './logger'; import { execSync } from 'child_process'; export default class { private logger: Logger; constructor() { this.logger = new Logger('Deps'); } public showAll(): void { this.show('MongoDB', 'mongo --version', x => x.match(/^MongoDB shell version:? (.*)\r?\n/)); this.show('Redis', 'redis-server --version', x => x.match(/v=([0-9\.]*)/)); this.show('ImageMagick', 'magick -version', x => x.match(/^Version: ImageMagick ([^ ]*)/)); } public show(serviceName: string, command: string, transform: (x: string) => RegExpMatchArray): void { try { // ステータス0以外のときにexecSyncはstderrをコンソール上に出力してしまうので // プロセスからのstderrをすべて無視するように stdio オプションをセット const x = execSync(command, { stdio: ['pipe', 'pipe', 'ignore'] }); const ver = transform(x.toString()); if (ver != null) { this.logger.succ(`${serviceName} ${ver[1]} found`); } else { this.logger.warn(`${serviceName} not found`); this.logger.warn(`Regexp used for version check of ${serviceName} is probably messed up`); } } catch (e) { this.logger.warn(`${serviceName} not found`); } } }
Update dependency checking for ImageMagick
Update dependency checking for ImageMagick
TypeScript
mit
syuilo/Misskey,Tosuke/misskey,Tosuke/misskey,ha-dai/Misskey,Tosuke/misskey,Tosuke/misskey,syuilo/Misskey,ha-dai/Misskey,Tosuke/misskey
--- +++ @@ -11,7 +11,7 @@ public showAll(): void { this.show('MongoDB', 'mongo --version', x => x.match(/^MongoDB shell version:? (.*)\r?\n/)); this.show('Redis', 'redis-server --version', x => x.match(/v=([0-9\.]*)/)); - this.show('ImageMagick', 'magick -version', x => x.match(/^Version: ImageMagick (.+?)\r?\n/)); + this.show('ImageMagick', 'magick -version', x => x.match(/^Version: ImageMagick ([^ ]*)/)); } public show(serviceName: string, command: string, transform: (x: string) => RegExpMatchArray): void {
4d689b06112bd5b6113dca8272c87a5ddefcc09b
src/game.ts
src/game.ts
import { Grid, Move } from './definitions'; export function makeMove(grid: Grid, move: Move, forX: (grid: Grid) => boolean): Grid { const newValue = forX(grid); return grid.map((value, index) => index == move ? newValue : value); } function hasXWon(grid: Grid): boolean { return false; } function hasOWon(grid: Grid): boolean { return false; } function isDraw(grid: Grid): boolean { return false; } export function hasGameEnded(grid: Grid): boolean { return hasXWon(grid) || hasOWon(grid) || isDraw(grid); }
import { Grid, Move } from './definitions'; import { getRows, getColumns, getDiagonals } from './utils'; export function makeMove(grid: Grid, move: Move, forX: (grid: Grid) => boolean): Grid { const newValue = forX(grid); return grid.map((value, index) => index == move ? newValue : value); } function hasXWon(grid: Grid): boolean { return getRows(grid).some(row => row.every(cell => cell === true)) || getColumns(grid).some(column => column.every(cell => cell === true)) || getDiagonals(grid).some(diagonal => diagonal.every(cell => cell === true)); } function hasOWon(grid: Grid): boolean { return getRows(grid).some(row => row.every(cell => cell === false)) || getColumns(grid).some(column => column.every(cell => cell === false)) || getDiagonals(grid).some(diagonal => diagonal.every(cell => cell === false)); } function isDraw(grid: Grid): boolean { return grid.filter(cell => cell != undefined).length === grid.length; } export function hasGameEnded(grid: Grid): boolean { return hasXWon(grid) || hasOWon(grid) || isDraw(grid); }
Implement hasXWon, hasOWon, and isDraw methods
Implement hasXWon, hasOWon, and isDraw methods
TypeScript
mit
artfuldev/tictactoe-ai,artfuldev/tictactoe-ai
--- +++ @@ -1,4 +1,5 @@ import { Grid, Move } from './definitions'; +import { getRows, getColumns, getDiagonals } from './utils'; export function makeMove(grid: Grid, move: Move, forX: (grid: Grid) => boolean): Grid { const newValue = forX(grid); @@ -6,15 +7,19 @@ } function hasXWon(grid: Grid): boolean { - return false; + return getRows(grid).some(row => row.every(cell => cell === true)) + || getColumns(grid).some(column => column.every(cell => cell === true)) + || getDiagonals(grid).some(diagonal => diagonal.every(cell => cell === true)); } function hasOWon(grid: Grid): boolean { - return false; + return getRows(grid).some(row => row.every(cell => cell === false)) + || getColumns(grid).some(column => column.every(cell => cell === false)) + || getDiagonals(grid).some(diagonal => diagonal.every(cell => cell === false)); } function isDraw(grid: Grid): boolean { - return false; + return grid.filter(cell => cell != undefined).length === grid.length; } export function hasGameEnded(grid: Grid): boolean {
e746218ba8915ee395e178e7e30dcbbdda4dfc50
types/react-router/test/WithRouter.tsx
types/react-router/test/WithRouter.tsx
import * as React from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; interface TOwnProps extends RouteComponentProps { username: string; } const ComponentFunction = (props: TOwnProps) => ( <h2>Welcome {props.username}</h2> ); class ComponentClass extends React.Component<TOwnProps> { render() { return <h2>Welcome {this.props.username}</h2>; } } const WithRouterComponentFunction = withRouter(ComponentFunction); const WithRouterComponentClass = withRouter(ComponentClass); const WithRouterTestFunction = () => ( <WithRouterComponentFunction username="John" /> ); const WithRouterTestClass = () => <WithRouterComponentClass username="John" />;
import * as React from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; interface TOwnProps extends RouteComponentProps { username: string; } const ComponentFunction = (props: TOwnProps) => ( <h2>Welcome {props.username}</h2> ); class ComponentClass extends React.Component<TOwnProps> { render() { return <h2>Welcome {this.props.username}</h2>; } } const WithRouterComponentFunction = withRouter(ComponentFunction); const WithRouterComponentClass = withRouter(ComponentClass); const WithRouterTestFunction = () => ( <WithRouterComponentFunction username="John" /> ); const WithRouterTestClass = () => <WithRouterComponentClass username="John" />; // union props { interface Book { kind: 'book'; author: string; } interface Magazine { kind: 'magazine'; issue: number; } type SomethingToRead = (Book | Magazine) & RouteComponentProps; const Readable: React.SFC<SomethingToRead> = props => { if (props.kind === 'magazine') { return <div>magazine #{props.issue}</div>; } return <div>magazine #{props.author}</div>; }; const RoutedReadable = withRouter(Readable); <RoutedReadable kind="book" author="Hejlsberg" />; <RoutedReadable kind="magazine" author="Hejlsberg" />; // $ExpectError }
Add failing test for union props
[react-router] Add failing test for union props
TypeScript
mit
georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,mcliment/DefinitelyTyped
--- +++ @@ -22,3 +22,31 @@ <WithRouterComponentFunction username="John" /> ); const WithRouterTestClass = () => <WithRouterComponentClass username="John" />; + +// union props +{ + interface Book { + kind: 'book'; + author: string; + } + + interface Magazine { + kind: 'magazine'; + issue: number; + } + + type SomethingToRead = (Book | Magazine) & RouteComponentProps; + + const Readable: React.SFC<SomethingToRead> = props => { + if (props.kind === 'magazine') { + return <div>magazine #{props.issue}</div>; + } + + return <div>magazine #{props.author}</div>; + }; + + const RoutedReadable = withRouter(Readable); + + <RoutedReadable kind="book" author="Hejlsberg" />; + <RoutedReadable kind="magazine" author="Hejlsberg" />; // $ExpectError +}
8d76b14790b6f15e50b50031eac4ed1ccdddd049
src/main/components/App/App.tsx
src/main/components/App/App.tsx
import React from "react" import { bindKeyboardShortcut } from "main/services/KeyboardShortcut.ts" import RootStore from "stores/RootStore.ts" import { theme } from "common/theme/muiTheme" import { ThemeProvider } from "@material-ui/styles" import { applyThemeToCSS } from "common/theme/applyThemeToCSS" import { defaultTheme } from "common/theme/Theme" import { ThemeContext } from "main/hooks/useTheme" import { StoreContext } from "main/hooks/useStores" import RootView from "../RootView/RootView" import "./App.css" const rootStore = new RootStore() applyThemeToCSS(defaultTheme) bindKeyboardShortcut(rootStore) export default function App() { return ( <StoreContext.Provider value={{ rootStore: new RootStore() }}> <ThemeContext.Provider value={defaultTheme}> <ThemeProvider theme={theme}> <RootView /> </ThemeProvider> </ThemeContext.Provider> </StoreContext.Provider> ) }
import React from "react" import { bindKeyboardShortcut } from "main/services/KeyboardShortcut.ts" import RootStore from "stores/RootStore.ts" import { theme } from "common/theme/muiTheme" import { ThemeProvider } from "@material-ui/styles" import { applyThemeToCSS } from "common/theme/applyThemeToCSS" import { defaultTheme } from "common/theme/Theme" import { ThemeContext } from "main/hooks/useTheme" import { StoreContext } from "main/hooks/useStores" import RootView from "../RootView/RootView" import "./App.css" import { StylesProvider } from "@material-ui/core" const rootStore = new RootStore() applyThemeToCSS(defaultTheme) bindKeyboardShortcut(rootStore) export default function App() { return ( <StoreContext.Provider value={{ rootStore: new RootStore() }}> <ThemeContext.Provider value={defaultTheme}> <ThemeProvider theme={theme}> <StylesProvider injectFirst> <RootView /> </StylesProvider> </ThemeProvider> </ThemeContext.Provider> </StoreContext.Provider> ) }
Support using styled-component with Material-UI
Support using styled-component with Material-UI
TypeScript
mit
ryohey/signal,ryohey/signal,ryohey/signal
--- +++ @@ -13,6 +13,7 @@ import RootView from "../RootView/RootView" import "./App.css" +import { StylesProvider } from "@material-ui/core" const rootStore = new RootStore() @@ -25,7 +26,9 @@ <StoreContext.Provider value={{ rootStore: new RootStore() }}> <ThemeContext.Provider value={defaultTheme}> <ThemeProvider theme={theme}> - <RootView /> + <StylesProvider injectFirst> + <RootView /> + </StylesProvider> </ThemeProvider> </ThemeContext.Provider> </StoreContext.Provider>
e0dc82ab6565e06417cf4aad5a59a8fb80b70c2b
js/appconfig.ts
js/appconfig.ts
class GameHandHistory { /** * Show game history with cards. */ public showPictureHistory = true; /** * Show game history as text. */ public showTextHistory = true; } class GameActionBlock { /** * Wherether action panel is present on the application */ public hasSecondaryPanel = true; } class AppConfig { public auth = { automaticLogin: true, automaticTableSelection: true, }; public game = { handHistory: new GameHandHistory(), actionBlock: new GameActionBlock(), seatMode: document.body.classList.contains("poker-feature-single-seat"), tablePreviewMode: document.body.classList.contains("poker-feature-table-preview"), autoFoldAsFoldOnRaise: true, useSignalR: false, noTableMoneyLimit: true, showTournamentTables: true, }; public tournament = { enabled: false, openTableAutomatically: true, }; public joinTable = { allowUsePersonalAccount: false, allowTickets: true, }; } export const appConfig = new AppConfig();
class GameHandHistory { /** * Show game history with cards. */ public showPictureHistory = true; /** * Show game history as text. */ public showTextHistory = true; } class GameActionBlock { /** * Wherether action panel is present on the application */ public hasSecondaryPanel = true; } class AppConfig { public auth = { automaticLogin: true, automaticTableSelection: true, }; public game = { handHistory: new GameHandHistory(), actionBlock: new GameActionBlock(), seatMode: document.body.classList.contains("poker-feature-single-seat"), tablePreviewMode: document.body.classList.contains("poker-feature-table-preview"), autoFoldAsFoldOnRaise: true, useSignalR: false, noTableMoneyLimit: true, showTournamentTables: true, isRoundNotificationEnabled: true, }; public tournament = { enabled: false, openTableAutomatically: true, }; public joinTable = { allowUsePersonalAccount: false, allowTickets: true, }; } export const appConfig = new AppConfig();
Add setings variable for enabling/disabling round notification
Add setings variable for enabling/disabling round notification
TypeScript
apache-2.0
online-poker/poker-html-client,online-poker/poker-html-client,online-poker/poker-html-client
--- +++ @@ -31,6 +31,7 @@ useSignalR: false, noTableMoneyLimit: true, showTournamentTables: true, + isRoundNotificationEnabled: true, }; public tournament = { enabled: false,
92a04a3e2731adfbfb742f4da72105ab67ccf8b6
src/app/menu/menu.component.ts
src/app/menu/menu.component.ts
import { Component, OnInit, AnimationTransitionEvent } from '@angular/core'; import { routerTransition } from '../app.routes.animations'; import { GameStateService } from "../services/game-state.service"; import { SoundService } from "../services/sound.service"; @Component({ selector: 'app-menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.less'], host: { '[@routerTransition]': '', '(@routerTransition.start)': 'routerAnimationStarted($event)', '(@routerTransition.done)': 'routerAnimationDone($event)', '[style.display]': "'block'" }, animations: [ routerTransition() ] }) export class MenuComponent implements OnInit { private gameState; constructor(private gameStateService: GameStateService, private soundService: SoundService) { this.gameState = gameStateService.getGameState(); } ngOnInit() { } routerAnimationStarted($event: AnimationTransitionEvent) { if ($event.toState === 'void') { this.soundService.playTransitionSound(); this.gameState.isRouteLeaveAnimationInProgress = true; } } routerAnimationDone($event: AnimationTransitionEvent) { if ($event.toState == 'void') { this.gameState.isRouteLeaveAnimationInProgress = false; } } playHoverSound() { this.soundService.playHoverSound(); } }
import { Component, OnInit, AnimationTransitionEvent } from '@angular/core'; import { routerTransition } from '../app.routes.animations'; import { GameStateService } from "../services/game-state.service"; import { SoundService } from "../services/sound.service"; @Component({ selector: 'app-menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.less'], host: { '[@routerTransition]': '', '(@routerTransition.start)': 'routerAnimationStarted($event)', '(@routerTransition.done)': 'routerAnimationDone($event)', '[style.display]': "'block'" }, animations: [ routerTransition() ] }) export class MenuComponent implements OnInit { private gameState; constructor(private gameStateService: GameStateService, private soundService: SoundService) { this.gameState = gameStateService.getGameState(); } ngOnInit() { } routerAnimationStarted($event: AnimationTransitionEvent) { console.log(`menu: [routerAnimationStarted] $event.toState=${$event.toState}`); if ($event.toState === 'void') { this.soundService.playTransitionSound(); this.gameState.isRouteLeaveAnimationInProgress = true; } } routerAnimationDone($event: AnimationTransitionEvent) { console.log(`menu: [routerAnimationDone] $event.toState=${$event.toState}`); if ($event.toState == 'void') { this.gameState.isRouteLeaveAnimationInProgress = false; } } playHoverSound() { this.soundService.playHoverSound(); } }
Add some console.log statements for home router animation started/done (take 3)
Add some console.log statements for home router animation started/done (take 3)
TypeScript
mit
nmarsden/make-em-green,nmarsden/make-em-green,nmarsden/make-em-green
--- +++ @@ -29,6 +29,8 @@ } routerAnimationStarted($event: AnimationTransitionEvent) { + console.log(`menu: [routerAnimationStarted] $event.toState=${$event.toState}`); + if ($event.toState === 'void') { this.soundService.playTransitionSound(); this.gameState.isRouteLeaveAnimationInProgress = true; @@ -36,6 +38,8 @@ } routerAnimationDone($event: AnimationTransitionEvent) { + console.log(`menu: [routerAnimationDone] $event.toState=${$event.toState}`); + if ($event.toState == 'void') { this.gameState.isRouteLeaveAnimationInProgress = false; }
094c82b75a7c2ac0e56c6a340ddee51cbe1039b0
console/src/app/common/BasicTab/BasicTab.ts
console/src/app/common/BasicTab/BasicTab.ts
export class BasicTab { public isActive: boolean = false private name: String; private link: String; private id: String; // MARK: - Getters & Setters public getId(): String { return this.id; } public getLink(): String { return this.link; } public onTabSelected() { this.isActive = !this.isActive; } constructor(name: String = "", link: String = "") { this.name = name; this.link = link; this.isActive = false; this.id = this.getUniqueIdentifier(); } // MARK: - Public public isEqual(comparingTab): boolean { return (this.id == comparingTab.getId()); } // MARK: - Private private getUniqueIdentifier(): string { const currentDateTime = Date.now(); const hexNumericSystemBase = 16; return currentDateTime.toString(hexNumericSystemBase) + this.name; } }
export class BasicTab { public isActive: boolean = false private name: String; private link: String; private id: String; // MARK: - Getters & Setters public getId(): String { return this.id; } public getLink(): String { return this.link; } public onTabSelected() { this.isActive = !this.isActive; } constructor(name: String = "", link: String = "") { this.name = name; this.link = link; this.isActive = false; this.id = this.getUniqueIdentifier(); } // MARK: - Public public isEqual(comparingTab): boolean { return (this.id == comparingTab.getId()); } // MARK: - Private private getUniqueIdentifier(): string { const currentDateTime = new Date().getMilliseconds(); const hexNumericSystemBase = 16; return currentDateTime.toString(hexNumericSystemBase) + this.name; } }
Change logic of generating ID for tab.
Change logic of generating ID for tab.
TypeScript
mit
emc-mongoose/console,emc-mongoose/console,emc-mongoose/console
--- +++ @@ -36,7 +36,7 @@ // MARK: - Private private getUniqueIdentifier(): string { - const currentDateTime = Date.now(); + const currentDateTime = new Date().getMilliseconds(); const hexNumericSystemBase = 16; return currentDateTime.toString(hexNumericSystemBase) + this.name; }
d1ac4df089ec54513c28dd9f4b9ae45ef6706384
src/utils.ts
src/utils.ts
/* * Copyright (C) 2016 wikiwi.io * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ import {Rule } from "jss"; import createHash = require("murmurhash-js/murmurhash3_gc"); export function generateClassName(str: string, rule: Rule): string { if (rule.name) { if (rule.options.sheet) { const sheet = rule.options.sheet; if (sheet.options.meta) { const sheetMeta = rule.options.sheet.options.meta; return `${sheetMeta}-${rule.name}`; } } return `${rule.name}-${createHash(str)}`; } return `${createHash(str)}`; }
/* * Copyright (C) 2016 wikiwi.io * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ import {Rule } from "jss"; import createHash = require("murmurhash-js/murmurhash3_gc"); export function generateClassName(str: string, rule: Rule): string { if (rule.name) { const dashedRuleName = rule.name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); if (rule.options.sheet) { const sheet = rule.options.sheet; if (sheet.options.meta) { const sheetMeta = rule.options.sheet.options.meta; return `${sheetMeta}-${dashedRuleName}`; } } return `${dashedRuleName}-${createHash(str)}`; } return `${createHash(str)}`; }
Change camel case to dash
Change camel case to dash
TypeScript
mit
wikiwi/react-jss-theme,wikiwi/react-jss-theme,wikiwi/react-jss-theme
--- +++ @@ -10,14 +10,15 @@ export function generateClassName(str: string, rule: Rule): string { if (rule.name) { + const dashedRuleName = rule.name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); if (rule.options.sheet) { const sheet = rule.options.sheet; if (sheet.options.meta) { const sheetMeta = rule.options.sheet.options.meta; - return `${sheetMeta}-${rule.name}`; + return `${sheetMeta}-${dashedRuleName}`; } } - return `${rule.name}-${createHash(str)}`; + return `${dashedRuleName}-${createHash(str)}`; } return `${createHash(str)}`; }
1bca022b184abab90430ad092e1436c300eeb0e8
src/app/views/sessions/session/leftpanel/adddatasetmodal/adddatasetmodal.content.ts
src/app/views/sessions/session/leftpanel/adddatasetmodal/adddatasetmodal.content.ts
import Dataset from "../../../../../model/session/dataset"; import {Component, Input, ChangeDetectorRef, ViewChild, AfterViewInit} from '@angular/core'; import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap'; import {UploadService} from "../../../../../shared/services/upload.service"; @Component({ selector: 'ch-add-dataset-modal-content', templateUrl: './adddatasetmodal.content.html' }) export class AddDatasetModalContent implements AfterViewInit { @Input() sessionId: string; @ViewChild('browseFilesButton') browseFilesButton; @ViewChild('browseDirButton') browseDirButton; flow; constructor( public activeModal: NgbActiveModal, private uploadService: UploadService, private changeDetectorRef: ChangeDetectorRef) { } ngOnInit() { this.flow = this.uploadService.getFlow( this.fileAdded.bind(this), this.fileSuccess.bind(this)); } fileAdded(file: any) { this.uploadService.scheduleViewUpdate(this.changeDetectorRef, this.flow); this.uploadService.startUpload(this.sessionId, file); } fileSuccess(file: any) { // remove from the list file.cancel(); } ngAfterViewInit() { this.flow.assignBrowse(this.browseFilesButton); this.flow.assignBrowse(this.browseDirButton, true); } }
import Dataset from "../../../../../model/session/dataset"; import { Component, Input, ChangeDetectorRef, ViewChild, AfterViewInit, OnInit } from "@angular/core"; import { NgbActiveModal } from "@ng-bootstrap/ng-bootstrap"; import { UploadService } from "../../../../../shared/services/upload.service"; @Component({ selector: "ch-add-dataset-modal-content", templateUrl: "./adddatasetmodal.content.html" }) export class AddDatasetModalContent implements AfterViewInit, OnInit { @Input() sessionId: string; @ViewChild("browseFilesButton") browseFilesButton; @ViewChild("browseDirButton") browseDirButton; flow; constructor( public activeModal: NgbActiveModal, private uploadService: UploadService, private changeDetectorRef: ChangeDetectorRef ) {} ngOnInit() { this.flow = this.uploadService.getFlow( this.fileAdded.bind(this), this.fileSuccess.bind(this) ); } fileAdded(file: any) { this.uploadService.scheduleViewUpdate(this.changeDetectorRef, this.flow); this.uploadService.startUpload(this.sessionId, file); } fileSuccess(file: any) { // remove from the list file.cancel(); } ngAfterViewInit() { this.flow.assignBrowse(this.browseFilesButton); this.flow.assignBrowse(this.browseDirButton, true); } }
Reformat and fix linting errors
Reformat and fix linting errors
TypeScript
mit
chipster/chipster-web,chipster/chipster-web,chipster/chipster-web
--- +++ @@ -1,30 +1,38 @@ import Dataset from "../../../../../model/session/dataset"; -import {Component, Input, ChangeDetectorRef, ViewChild, AfterViewInit} from '@angular/core'; -import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap'; -import {UploadService} from "../../../../../shared/services/upload.service"; +import { + Component, + Input, + ChangeDetectorRef, + ViewChild, + AfterViewInit, + OnInit +} from "@angular/core"; +import { NgbActiveModal } from "@ng-bootstrap/ng-bootstrap"; +import { UploadService } from "../../../../../shared/services/upload.service"; @Component({ - selector: 'ch-add-dataset-modal-content', - templateUrl: './adddatasetmodal.content.html' + selector: "ch-add-dataset-modal-content", + templateUrl: "./adddatasetmodal.content.html" }) -export class AddDatasetModalContent implements AfterViewInit { - +export class AddDatasetModalContent implements AfterViewInit, OnInit { @Input() sessionId: string; - @ViewChild('browseFilesButton') browseFilesButton; - @ViewChild('browseDirButton') browseDirButton; + @ViewChild("browseFilesButton") browseFilesButton; + @ViewChild("browseDirButton") browseDirButton; flow; constructor( public activeModal: NgbActiveModal, private uploadService: UploadService, - private changeDetectorRef: ChangeDetectorRef) { - } + private changeDetectorRef: ChangeDetectorRef + ) {} ngOnInit() { this.flow = this.uploadService.getFlow( - this.fileAdded.bind(this), this.fileSuccess.bind(this)); + this.fileAdded.bind(this), + this.fileSuccess.bind(this) + ); } fileAdded(file: any) {
4e49ee6d87f3b922ea7ba7456f87ac235fed180d
frontend/applications/auth/src/modules/login/Authenticated.tsx
frontend/applications/auth/src/modules/login/Authenticated.tsx
import React from 'react'; import { Redirect } from 'react-router'; export const Authenticated = ({ location }) => location.referrer !== location.url ? ( <Redirect to={{ pathname: location.referrer }} /> ) : ( <div>You have been successfully logged in</div> );
import React from 'react'; import { Redirect } from 'react-router'; //TODO: Redirect back to correct path export const Authenticated = ({ location }) => location.referrer !== location.url ? ( <Redirect to={{ pathname: location.referrer }} /> ) : ( <div>You have been successfully logged in</div> );
Add todo for fixing auth
Add todo for fixing auth
TypeScript
mit
CodeForCharlotte/cmpd-holiday-gift-backend,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/cmpd-holiday-gift-backend,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/cmpd-holiday-gift-backend
--- +++ @@ -1,6 +1,7 @@ import React from 'react'; import { Redirect } from 'react-router'; +//TODO: Redirect back to correct path export const Authenticated = ({ location }) => location.referrer !== location.url ? ( <Redirect
8c45898245072158e6ff0e70244fdf75739f46ab
packages/lesswrong/server/startupSanityChecks.ts
packages/lesswrong/server/startupSanityChecks.ts
import { onStartup } from '../lib/executionEnvironment'; import process from 'process'; import { DatabaseMetadata } from '../lib/collections/databaseMetadata/collection'; import { PublicInstanceSetting } from '../lib/instanceSettings'; // Database ID string that this config file should match with const expectedDatabaseIdSetting = new PublicInstanceSetting<string | null>('expectedDatabaseId', null, "warning") onStartup(() => { const expectedDatabaseId = expectedDatabaseIdSetting.get(); const databaseIdObject = DatabaseMetadata.findOne({ name: "databaseId" }); // If either the database or the settings config file contains an ID, then // both must contain IDs and they must match. if (expectedDatabaseId || databaseIdObject) { if (expectedDatabaseId !== databaseIdObject?.value) { console.error("Database ID in config file and in database don't match."); // eslint-disable-line no-console console.error(` Database ID: ${databaseIdObject?.value}`); // eslint-disable-line no-console console.error(` Expected database ID: ${expectedDatabaseId}`); // eslint-disable-line no-console console.error("If you are connecting to a production DB, you must use a matching config file. If you are *not* connecting to a production DB, you should not use a production config file."); // eslint-disable-line no-console process.exit(1); } } });
import { onStartup } from '../lib/executionEnvironment'; import process from 'process'; import { DatabaseMetadata } from '../lib/collections/databaseMetadata/collection'; import { PublicInstanceSetting } from '../lib/instanceSettings'; // Database ID string that this config file should match with const expectedDatabaseIdSetting = new PublicInstanceSetting<string | null>('expectedDatabaseId', null, "warning") onStartup(() => { const expectedDatabaseId = expectedDatabaseIdSetting.get(); const databaseIdObject = DatabaseMetadata.findOne({ name: "databaseId" }); const databaseId = databaseIdObject?.value || null; // If either the database or the settings config file contains an ID, then // both must contain IDs and they must match. if (expectedDatabaseId || databaseId) { if (expectedDatabaseId !== databaseId) { console.error("Database ID in config file and in database don't match."); // eslint-disable-line no-console console.error(` Database ID: ${databaseId}`); // eslint-disable-line no-console console.error(` Expected database ID: ${expectedDatabaseId}`); // eslint-disable-line no-console console.error("If you are connecting to a production DB, you must use a matching config file. If you are *not* connecting to a production DB, you should not use a production config file."); // eslint-disable-line no-console process.exit(1); } } });
Fix an undefined-vs-null issue that prevented starting without a database
Fix an undefined-vs-null issue that prevented starting without a database
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -9,13 +9,14 @@ onStartup(() => { const expectedDatabaseId = expectedDatabaseIdSetting.get(); const databaseIdObject = DatabaseMetadata.findOne({ name: "databaseId" }); + const databaseId = databaseIdObject?.value || null; // If either the database or the settings config file contains an ID, then // both must contain IDs and they must match. - if (expectedDatabaseId || databaseIdObject) { - if (expectedDatabaseId !== databaseIdObject?.value) { + if (expectedDatabaseId || databaseId) { + if (expectedDatabaseId !== databaseId) { console.error("Database ID in config file and in database don't match."); // eslint-disable-line no-console - console.error(` Database ID: ${databaseIdObject?.value}`); // eslint-disable-line no-console + console.error(` Database ID: ${databaseId}`); // eslint-disable-line no-console console.error(` Expected database ID: ${expectedDatabaseId}`); // eslint-disable-line no-console console.error("If you are connecting to a production DB, you must use a matching config file. If you are *not* connecting to a production DB, you should not use a production config file."); // eslint-disable-line no-console process.exit(1);
8e10cf1308dce3c6d8187bd9e702a62ac96d3d90
functions/amazon.ts
functions/amazon.ts
import * as apac from "apac"; import * as functions from "firebase-functions"; const amazonClient = new apac.OperationHelper({ assocId: functions.config().aws.tag, awsId: functions.config().aws.id, awsSecret: functions.config().aws.secret, endPoint: "webservices.amazon.co.jp", }); export async function books(): Promise<any[]> { const { result: { ItemSearchResponse: { Items: { Item } } } } = await amazonClient.execute("ItemSearch", { BrowseNode: "466298", ResponseGroup: "Images,ItemAttributes", SearchIndex: "Books", }); return Item.map(({ ASIN, DetailPageURL, SmallImage, ItemAttributes: { Author, Publisher, Title } }) => ({ asin: ASIN, author: Author, imageUri: SmallImage.URL, pageUri: DetailPageURL, publisher: Publisher, title: Title, })); }
import * as apac from "apac"; import * as functions from "firebase-functions"; const amazonClient = new apac.OperationHelper({ assocId: functions.config().aws.tag, awsId: functions.config().aws.id, awsSecret: functions.config().aws.secret, endPoint: "webservices.amazon.co.jp", }); export async function books(): Promise<any[]> { const { result: { ItemSearchErrorResponse, ItemSearchResponse } } = await amazonClient.execute("ItemSearch", { BrowseNode: "466298", ResponseGroup: "Images,ItemAttributes", SearchIndex: "Books", }); if (ItemSearchErrorResponse) { throw new Error(ItemSearchErrorResponse.Error.Message); } return ItemSearchResponse.Items.Item.map(({ ASIN, DetailPageURL, SmallImage, ItemAttributes: { Author, Publisher, Title } }) => ({ asin: ASIN, author: Author, imageUri: SmallImage.URL, pageUri: DetailPageURL, publisher: Publisher, title: Title, })); }
Throw error from books function
Throw error from books function
TypeScript
mit
raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d
--- +++ @@ -9,14 +9,18 @@ }); export async function books(): Promise<any[]> { - const { result: { ItemSearchResponse: { Items: { Item } } } } + const { result: { ItemSearchErrorResponse, ItemSearchResponse } } = await amazonClient.execute("ItemSearch", { BrowseNode: "466298", ResponseGroup: "Images,ItemAttributes", SearchIndex: "Books", }); - return Item.map(({ + if (ItemSearchErrorResponse) { + throw new Error(ItemSearchErrorResponse.Error.Message); + } + + return ItemSearchResponse.Items.Item.map(({ ASIN, DetailPageURL, SmallImage,
9c7fd609d041a75c578e180c2fd46251f8b81dc4
packages/core/src/classes/http-request.ts
packages/core/src/classes/http-request.ts
export class HttpRequest { params: { [key: string]: any } = {}; body: any = undefined; query: { [key: string]: any } = {}; constructor(private expressRequest?) { if (expressRequest) { this.query = expressRequest.query; this.params = expressRequest.params; this.body = expressRequest.body; } } getHeader(field: string): string { if (this.expressRequest) { return this.expressRequest.getHeader(field); } return field; } }
import { HttpMethod } from '../interfaces'; export class HttpRequest { params: { [key: string]: any } = {}; body: any = undefined; query: { [key: string]: any } = {}; method: HttpMethod = 'GET'; path: string = ''; constructor(private expressRequest?) { if (expressRequest) { this.query = expressRequest.query; this.params = expressRequest.params; this.body = expressRequest.body; this.method = expressRequest.method; this.path = expressRequest.path; } } getHeader(field: string): string { if (this.expressRequest) { return this.expressRequest.getHeader(field); } return field; } }
Add path and method to HttpRequest.
Add path and method to HttpRequest.
TypeScript
mit
FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal
--- +++ @@ -1,13 +1,19 @@ +import { HttpMethod } from '../interfaces'; + export class HttpRequest { params: { [key: string]: any } = {}; body: any = undefined; query: { [key: string]: any } = {}; + method: HttpMethod = 'GET'; + path: string = ''; constructor(private expressRequest?) { if (expressRequest) { this.query = expressRequest.query; this.params = expressRequest.params; this.body = expressRequest.body; + this.method = expressRequest.method; + this.path = expressRequest.path; } }
f5a47bf4008068c34cb825af5777059adba48191
app/services/alert.service.ts
app/services/alert.service.ts
import * as config from '../common/config'; import {Injectable, EventEmitter} from '@angular/core'; import {Subject} from 'rxjs/Subject'; import {UUID} from 'angular2-uuid'; @Injectable() export class AlertService { private alertEmitSource = new Subject(); alertEmit$ = this.alertEmitSource.asObservable(); alertTypes = { success: 'Success!', warning: 'Warning!', danger : 'Error!', info : 'Info:' }; addAlert(type:string, title:string, content:string, expiresIn:number = -1) { // Default alert type to 'info' if(typeof this.alertTypes[type] !== 'string') { type = 'info'; } let alert:Alert = { id: UUID.UUID(), expiresIn, type, title, content }; this.alertEmitSource.next(alert); } } export interface Alert { id:string; expiresIn?:number; type:string; title:string; content:string; }
import * as config from '../common/config'; import {Injectable, EventEmitter} from '@angular/core'; import {contains} from '../common/utils'; import {Subject} from 'rxjs/Subject'; import {UUID} from 'angular2-uuid'; @Injectable() export class AlertService { private alertEmitSource = new Subject(); alertEmit$ = this.alertEmitSource.asObservable(); alertTypes = [ 'info', 'success', 'warning', 'danger' ]; addAlert(type:string, title:string, content:string, expiresIn:number = -1) { // Default alert type to 'info' if(!contains(this.alertTypes, type)) { type = 'info'; } let alert:Alert = { id: UUID.UUID(), expiresIn, type, title, content }; this.alertEmitSource.next(alert); } } export interface Alert { id:string; expiresIn?:number; type:string; title:string; content:string; }
Change alertTypes to an array since we don't use the automatic titles anymore
Change alertTypes to an array since we don't use the automatic titles anymore
TypeScript
mit
MyMICDS/MyMICDS-v2-Angular,MyMICDS/MyMICDS-v2-Angular,MyMICDS/MyMICDS-v2-Angular,michaelgira23/MyMICDS-v2-Angular,michaelgira23/MyMICDS-v2-Angular,michaelgira23/MyMICDS-v2-Angular
--- +++ @@ -1,6 +1,7 @@ import * as config from '../common/config'; import {Injectable, EventEmitter} from '@angular/core'; +import {contains} from '../common/utils'; import {Subject} from 'rxjs/Subject'; import {UUID} from 'angular2-uuid'; @@ -10,16 +11,16 @@ private alertEmitSource = new Subject(); alertEmit$ = this.alertEmitSource.asObservable(); - alertTypes = { - success: 'Success!', - warning: 'Warning!', - danger : 'Error!', - info : 'Info:' - }; + alertTypes = [ + 'info', + 'success', + 'warning', + 'danger' + ]; addAlert(type:string, title:string, content:string, expiresIn:number = -1) { // Default alert type to 'info' - if(typeof this.alertTypes[type] !== 'string') { + if(!contains(this.alertTypes, type)) { type = 'info'; }
6b44626b784ab4446945216f6781c80642ed17fa
tools/tasks/seed/karma.run.with_coverage.ts
tools/tasks/seed/karma.run.with_coverage.ts
import * as karma from 'karma'; import { join } from 'path'; import Config from '../../config'; let repeatableStartKarma = (done: any, config: any = {}) => { return new (<any>karma).Server(Object.assign({ configFile: join(process.cwd(), 'karma.conf.js'), singleRun: true }, config), (exitCode: any) => { // Karma run is finished but do not exit the process for failure. Rather just mark this task as done. done(); }).start(); }; export = (done: any) => { return repeatableStartKarma(done, { preprocessors: { 'dist/**/!(*spec).js': ['coverage'] }, reporters: ['mocha', 'coverage', 'karma-remap-istanbul'], coverageReporter: { dir: 'coverage_js/', reporters: [ { type: 'json', subdir: '.', file: 'coverage-final.json' }, { type: 'html', subdir: '.' } ] }, remapIstanbulReporter: { reports: { html: Config.COVERAGE_DIR } }, singleRun: true }); };
import * as karma from 'karma'; import { join } from 'path'; import Config from '../../config'; let repeatableStartKarma = (done: any, config: any = {}) => { return new (<any>karma).Server(Object.assign({ configFile: join(process.cwd(), 'karma.conf.js'), singleRun: true }, config), (exitCode: any) => { // Karma run is finished but do not exit the process for failure. Rather just mark this task as done. done(); }).start(); }; export = (done: any) => { return repeatableStartKarma(done, { preprocessors: { 'dist/**/!(*spec|index|*.module).js': ['coverage'] }, reporters: ['mocha', 'coverage', 'karma-remap-istanbul'], coverageReporter: { dir: 'coverage_js/', reporters: [ { type: 'json', subdir: '.', file: 'coverage-final.json' }, { type: 'html', subdir: '.' } ] }, remapIstanbulReporter: { reports: { html: Config.COVERAGE_DIR } }, singleRun: true }); };
Exclude index.ts and *.module.ts from coverage
chore: Exclude index.ts and *.module.ts from coverage These files are scaffolding files that are skewing the test coverage. They are tested through the use of the moldule's components so they are always covered.
TypeScript
mit
pratheekhegde/a2-redux,idready/Philosophers,fart-one/monitor-ngx,tiagomapmarques/angular-examples_books,alexmanning23/uafl-web,sanastasiadis/angular-seed-openlayers,pocmanu/angular2-seed-advanced,oblong-antelope/oblong-web,natarajanmca11/angular2-seed,arun-awnics/mesomeds-ng2,ppanthony/angular-seed-tutorial,Sn3b/angular-seed-advanced,jelgar1/fpl-api,jigarpt/angular-seed-semi,shaggyshelar/Linkup,davewragg/agot-spa,CNSKnight/angular2-seed-advanced,zertyz/edificando-o-controle-interno,Karasuni/angular-seed,ysyun/angular-seed-stub-api-environment,trutoo/startatalk-native,wenzelj/nativescript-angular,tobiaseisenschenk/data-cube,mgechev/angular-seed,talentspear/a2-redux,larsnolden/MLB,dmitriyse/angular2-seed,vyakymenko/angular-seed-express,nickaranz/robinhood-ui,adobley/angular2-tdd-workshop,jigarpt/angular-seed-semi,fr-esco/angular-seed,zertyz/observatorio-SUAS-formularios,adobley/angular2-tdd-workshop,trutoo/startatalk-native,radiorabe/raar-ui,oblong-antelope/oblong-web,felipecamargo/ACSC-SBPL-M,pratheekhegde/a2-redux,christophersanson/js-demo-fe,JohnnyQQQQ/angular-seed-material2,AnnaCasper/finance-tool,zertyz/angular-seed-advanced-spikes,MgCoders/angular-seed,shaggyshelar/Linkup,guilhebl/offer-web,llwt/angular-seed-advanced,ysyun/angular-seed-stub-api-environment,tobiaseisenschenk/data-cube,mgechev/angular2-seed,hookom/climbontheway,JohnnyQQQQ/md-dashboard,JohnnyQQQQ/angular-seed-material2,NathanWalker/angular-seed-advanced,pieczkus/whyblogfront,shaggyshelar/Linkup,talentspear/a2-redux,ilvestoomas/angular-seed-advanced,rtang03/fabric-seed,NathanWalker/angular2-seed-advanced,natarajanmca11/angular2-seed,guilhebl/offer-web,talentspear/a2-redux,hookom/climbontheway,Nightapes/angular2-seed,zertyz/observatorio-SUAS,nickaranz/robinhood-ui,ilvestoomas/angular-seed-advanced,prabhatsharma/bwa2,OlivierVoyer/angular-seed-advanced,OlivierVoyer/angular-seed-advanced,ManasviA/Dashboard,Shyiy/angular-seed,alexmanning23/uafl-web,GeoscienceAustralia/gnss-site-manager,jelgar1/fpl-api,zertyz/observatorio-SUAS-formularios,prabhatsharma/bwa2,idready/Philosophers,ppanthony/angular-seed-tutorial,OlivierVoyer/angular-seed-advanced,pieczkus/whyblogfront,ysyun/angular-seed-stub-api-environment,idready/Bloody-Prophety-NG2,Sn3b/angular-seed-advanced,AWNICS/mesomeds-ng2,idready/Philosophers,deanQj/angular2-seed-bric,MgCoders/angular-seed,tiagomapmarques/angular-examples_books,zertyz/angular-seed-advanced-spikes,ManasviA/Dashboard,Shyiy/angular-seed,nickaranz/robinhood-ui,hookom/climbontheway,zertyz/edificando-o-controle-interno,lhoezee/faithreg1,pratheekhegde/a2-redux,sanastasiadis/angular-seed-openlayers,millea1/tips1,Karasuni/angular-seed,alexmanning23/uafl-web,dmitriyse/angular2-seed,maniche04/ngIntranet,MgCoders/angular-seed,zertyz/observatorio-SUAS,llwt/angular-seed-advanced,GeoscienceAustralia/gnss-site-manager,rawnics/mesomeds-ng2,sanastasiadis/angular-seed-openlayers,davewragg/agot-spa,lhoezee/faithreg1,radiorabe/raar-ui,NathanWalker/angular2-seed-advanced,zertyz/observatorio-SUAS,llwt/angular-seed-advanced,hookom/climbontheway,ronikurnia1/ClientApp,Shyiy/angular-seed,fr-esco/angular-seed,pocmanu/angular2-seed-advanced,MgCoders/angular-seed,larsnolden/MLB,vyakymenko/angular-seed-express,lhoezee/faithreg1,miltador/unichat,ppanthony/angular-seed-tutorial,Jimmysh/angular2-seed-advanced,adobley/angular2-tdd-workshop,tctc91/angular2-wordpress-portfolio,nie-ine/raeber-website,wenzelj/nativescript-angular,origamyllc/Mangular,Nightapes/angular2-seed,zertyz/angular-seed-advanced-spikes,tctc91/angular2-wordpress-portfolio,Nightapes/angular2-seed,rtang03/fabric-seed,watonyweng/angular-seed,fr-esco/angular-seed,pieczkus/whyblogfront,chnoumis/angular2-seed-advanced,fart-one/monitor-ngx,vyakymenko/angular-seed-express,trutoo/startatalk-native,origamyllc/Mangular,deanQj/angular2-seed-bric,idready/Bloody-Prophety-NG2,ilvestoomas/angular-seed-advanced,millea1/tips1,JohnnyQQQQ/md-dashboard,christophersanson/js-demo-fe,m-abs/angular2-seed-advanced,mgechev/angular2-seed,davewragg/agot-spa,oblong-antelope/oblong-web,m-abs/angular2-seed-advanced,rawnics/mesomeds-ng2,GeoscienceAustralia/gnss-site-manager,jigarpt/angular-seed-semi,chnoumis/angular2-seed-advanced,miltador/unichat,zertyz/observatorio-SUAS,Karasuni/angular-seed,mgechev/angular2-seed,maniche04/ngIntranet,mgechev/angular-seed,watonyweng/angular-seed,deanQj/angular2-seed-bric,tctc91/angular2-wordpress-portfolio,zertyz/observatorio-SUAS-formularios,AWNICS/mesomeds-ng2,felipecamargo/ACSC-SBPL-M,rtang03/fabric-seed,CNSKnight/angular2-seed-advanced,pocmanu/angular2-seed-advanced,fart-one/monitor-ngx,rtang03/fabric-seed,chnoumis/angular2-seed-advanced,AnnaCasper/finance-tool,natarajanmca11/angular2-seed,JohnnyQQQQ/md-dashboard,rtang03/fabric-seed,dmitriyse/angular2-seed,sylviefiat/bdmer3,christophersanson/js-demo-fe,AnnaCasper/finance-tool,arun-awnics/mesomeds-ng2,NathanWalker/angular-seed-advanced,wenzelj/nativescript-angular,maniche04/ngIntranet,miltador/unichat,ManasviA/Dashboard,idready/Bloody-Prophety-NG2,radiorabe/raar-ui,adobley/angular2-tdd-workshop,NathanWalker/angular-seed-advanced,CNSKnight/angular2-seed-advanced,tobiaseisenschenk/data-cube,Jimmysh/angular2-seed-advanced,NathanWalker/angular2-seed-advanced,arun-awnics/mesomeds-ng2,zertyz/edificando-o-controle-interno,Sn3b/angular-seed-advanced,jelgar1/fpl-api,rawnics/mesomeds-ng2,mgechev/angular-seed,nie-ine/raeber-website,ronikurnia1/ClientApp,nie-ine/raeber-website,guilhebl/offer-web,radiorabe/raar-ui,m-abs/angular2-seed-advanced,prabhatsharma/bwa2,origamyllc/Mangular,AWNICS/mesomeds-ng2,larsnolden/MLB,ManasviA/Dashboard,ysyun/angular-seed-stub-api-environment,felipecamargo/ACSC-SBPL-M,dmitriyse/angular2-seed,JohnnyQQQQ/angular-seed-material2,millea1/tips1,sylviefiat/bdmer3,ronikurnia1/ClientApp,tiagomapmarques/angular-examples_books,sylviefiat/bdmer3,nie-ine/raeber-website,Jimmysh/angular2-seed-advanced,OlivierVoyer/angular-seed-advanced
--- +++ @@ -16,7 +16,7 @@ export = (done: any) => { return repeatableStartKarma(done, { preprocessors: { - 'dist/**/!(*spec).js': ['coverage'] + 'dist/**/!(*spec|index|*.module).js': ['coverage'] }, reporters: ['mocha', 'coverage', 'karma-remap-istanbul'], coverageReporter: {
91342f4eac48bc241764124f4883dc888e0a5665
examples/MeteorCLI/all-in-one/imports/app/app.module.ts
examples/MeteorCLI/all-in-one/imports/app/app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { TodoAddModule } from './todo-add/todo-add.module'; import { TodoListComponent } from './todo-list/todo-list.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; @NgModule({ imports: [ // Transition between server and client BrowserModule.withServerTransition({ appId: 'angular-meteor-universal' }), FormsModule, RouterModule.forRoot([ { path: 'todoList', component: TodoListComponent, data: { title: 'Todo List' } }, { path: 'todoAdd', loadChildren: () => TodoAddModule, data: { title: 'Add Todo' } }, // Home Page { path: '', redirectTo: '/todoList', pathMatch: 'full' }, // 404 Page { path: '**', component: PageNotFoundComponent, data: { title: '404 Page Not Found' } } ]) ], declarations: [ AppComponent, TodoListComponent, PageNotFoundComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { TodoListComponent } from './todo-list/todo-list.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; @NgModule({ imports: [ // Transition between server and client BrowserModule.withServerTransition({ appId: 'angular-meteor-universal' }), FormsModule, RouterModule.forRoot([ { path: 'todoList', component: TodoListComponent, data: { title: 'Todo List' } }, { path: 'todoAdd', loadChildren: './todo-add/todo-add.module#TodoAddModule', data: { title: 'Add Todo' } }, // Home Page { path: '', redirectTo: '/todoList', pathMatch: 'full' }, // 404 Page { path: '**', component: PageNotFoundComponent, data: { title: '404 Page Not Found' } } ]) ], declarations: [ AppComponent, TodoListComponent, PageNotFoundComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
Use Meteor's dynamic loading syntax.
Use Meteor's dynamic loading syntax.
TypeScript
mit
Urigo/angular-meteor
--- +++ @@ -7,7 +7,7 @@ import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; -import { TodoAddModule } from './todo-add/todo-add.module'; + import { TodoListComponent } from './todo-list/todo-list.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; @@ -28,7 +28,7 @@ }, { path: 'todoAdd', - loadChildren: () => TodoAddModule, + loadChildren: './todo-add/todo-add.module#TodoAddModule', data: { title: 'Add Todo' }
af2043c5592546b626ff1e75154cc77fc9650cea
src/main.ts
src/main.ts
/* This is the main module, it exports the 'render' API. The compiled modules are bundled by Webpack into 'var' (script tag) and 'commonjs' (npm) formatted libraries. */ /* tslint:disable */ import {renderSource} from './render' import * as options from './options' import * as quotes from './quotes' /* tslint:enable */ /** * * This is the single public API which translates Rimu Markup to HTML. * * @param source * Input text containing Rimu Markup. * * @param opts * Markup translation options. * * @returns Returns HTML output text. * * Example: * * Rimu.render('Hello *Rimu*!', {safeMode: 1}) * */ export function render(source: string, opts: options.RenderOptions = {}): string { options.update(opts) return renderSource(source) } // Load-time initializations. quotes.initialize()
/* This is the main module, it exports the 'render' API. The compiled modules are bundled by Webpack into 'var' (script tag) and 'commonjs' (npm) formatted libraries. */ /* tslint:disable */ import {renderSource} from './render' import * as options from './options' import * as quotes from './quotes' /* tslint:enable */ /** * * This is the single public API which translates Rimu Markup to HTML. * * @param source * Input text containing Rimu Markup. * * @param opts * Markup translation options. * * @returns Returns HTML output text. * * Example: * * Rimu.render('Hello *Rimu*!', {safeMode: 1}) * */ export function render(source: string, opts: options.RenderOptions = {}): string { if (typeof source !== 'string') { throw new TypeError('render(): source argument is not a string') } if (opts !== undefined && typeof opts !== 'object') { throw new TypeError('render(): options argument is not an object') } options.update(opts) return renderSource(source) } // Load-time initializations. quotes.initialize()
Check render() API arguments at runtime.
feature: Check render() API arguments at runtime.
TypeScript
mit
srackham/rimu
--- +++ @@ -29,6 +29,12 @@ * */ export function render(source: string, opts: options.RenderOptions = {}): string { + if (typeof source !== 'string') { + throw new TypeError('render(): source argument is not a string') + } + if (opts !== undefined && typeof opts !== 'object') { + throw new TypeError('render(): options argument is not an object') + } options.update(opts) return renderSource(source) }
a4cef559aa13e3fbb3053c2683030105115c85ca
src/shadowbox/model/access_key.ts
src/shadowbox/model/access_key.ts
// Copyright 2018 The Outline Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. export type AccessKeyId = string; export interface ProxyParams { hostname: string; portNumber: number; encryptionMethod: string; password: string; } export interface AccessKey { // The unique identifier for this access key. id: AccessKeyId; // Admin-controlled, editable name for this access key. name: string; // Used in metrics reporting to decouple from the real id. Can change. metricsId: AccessKeyId; // Parameters to access the proxy proxyParams: ProxyParams; } export interface AccessKeyRepository { // Creates a new access key. Parameters are chosen automatically. createNewAccessKey(): Promise<AccessKey>; // Removes the access key given its id. Returns true if successful. removeAccessKey(id: AccessKeyId): boolean; // Lists all existing access keys listAccessKeys(): IterableIterator<AccessKey>; // Apply the specified update to the specified access key. // Returns true if successful. renameAccessKey(id: AccessKeyId, name: string): boolean; }
// Copyright 2018 The Outline Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. export type AccessKeyId = string; export interface ProxyParams { hostname: string; portNumber: number; encryptionMethod: string; password: string; } export interface AccessKey { // The unique identifier for this access key. id: AccessKeyId; // Admin-controlled, editable name for this access key. name: string; // Used in metrics reporting to decouple from the real id. Can change. metricsId: AccessKeyId; // Parameters to access the proxy proxyParams: ProxyParams; } export interface AccessKeyRepository { // Creates a new access key. Parameters are chosen automatically. createNewAccessKey(): Promise<AccessKey>; // Removes the access key given its id. Returns true if successful. removeAccessKey(id: AccessKeyId): boolean; // Lists all existing access keys listAccessKeys(): IterableIterator<AccessKey>; // Apply the specified update to the specified access key. // Returns true if successful. renameAccessKey(id: AccessKeyId, name: string): boolean; }
Add blank line after copyright
Add blank line after copyright
TypeScript
apache-2.0
Jigsaw-Code/outline-server,Jigsaw-Code/outline-server,Jigsaw-Code/outline-server,Jigsaw-Code/outline-server
--- +++ @@ -12,6 +12,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + export type AccessKeyId = string; export interface ProxyParams {
018af2378a70de0e0fec4c1430285bf48037e36f
ng2-timetable/app/main.ts
ng2-timetable/app/main.ts
import {bootstrap} from 'angular2/platform/browser' import {AppComponent} from './app.component' bootstrap(AppComponent);
///<reference path="../../node_modules/angular2/typings/browser.d.ts"/> import {bootstrap} from 'angular2/platform/browser' import {AppComponent} from './app.component' bootstrap(AppComponent);
Fix broken dependencies while compiling TS
Fix broken dependencies while compiling TS
TypeScript
mit
bluebirrrrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrd/nau-timetable,bluebirrd/nau-timetable,bluebirrd/nau-timetable,bluebirrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrrrd/nau-timetable
--- +++ @@ -1,3 +1,5 @@ +///<reference path="../../node_modules/angular2/typings/browser.d.ts"/> + import {bootstrap} from 'angular2/platform/browser' import {AppComponent} from './app.component'
52b94ad763575b3c67139ed5ed378e26ee104b94
src/client/app/+play/play.component.ts
src/client/app/+play/play.component.ts
import { Component } from '@angular/core'; /** * This class represents the lazy loaded PlayComponent. */ @Component({ moduleId: module.id, selector: 'sd-play', templateUrl: 'play.component.html', styleUrls: ['play.component.css'] }) export class PlayComponent { audioContext: AudioContext; currentOscillator: OscillatorNode; constructor() { this.audioContext = new AudioContext(); } startNote(frequency: number) { console.log("startNote()"); var oscillator = this.audioContext.createOscillator(); oscillator.type = 'sine'; oscillator.frequency.value = frequency; oscillator.connect(this.audioContext.destination); oscillator.start(0); this.currentOscillator = oscillator; } stopNote() { console.log("stopNote()"); this.currentOscillator.stop(0); } }
import { Component } from '@angular/core'; /** * This class represents the lazy loaded PlayComponent. */ @Component({ moduleId: module.id, selector: 'sd-play', templateUrl: 'play.component.html', styleUrls: ['play.component.css'] }) export class PlayComponent { audioContext: AudioContext; currentOscillator: OscillatorNode; constructor() { this.audioContext = new AudioContext(); } startNote(frequency: number) { console.log("startNote()"); var oscillator = this.audioContext.createOscillator(); oscillator.type = 'sine'; oscillator.frequency.value = frequency; oscillator.connect(this.audioContext.destination); oscillator.start(0); this.currentOscillator = oscillator; } stopNote() { console.log("stopNote()"); if (this.currentOscillator !== undefined) { this.currentOscillator.stop(0); } } }
Fix undefined error in PlayComponent.stopNote
Fix undefined error in PlayComponent.stopNote
TypeScript
mit
Ecafracs/flatthirteen,Ecafracs/flatthirteen,Ecafracs/flatthirteen
--- +++ @@ -28,6 +28,10 @@ stopNote() { console.log("stopNote()"); - this.currentOscillator.stop(0); + if (this.currentOscillator !== undefined) + { + this.currentOscillator.stop(0); + } + } }
84938c6001b7d7028498d4df9d01a254f37d5afa
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 { CookieService } from 'angular2-cookie/core'; import { TranslateModule, TranslateLoader, TranslateStaticLoader, TranslateService } from 'ng2-translate'; import { WindowService } from '../window.service'; import { HomeComponent } from './home.component'; describe('Component: Home', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpModule, TranslateModule.forRoot({ provide: TranslateLoader, useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'), deps: [Http] }), ], providers: [ CookieService, TranslateService, Renderer, HomeComponent, // using window object in Angular 2 is discouraged since // it isn’t only designed to run within your browser, but also on mobiles, // the server or web workers where objects like window may not be available. { provide: WindowService, useValue: window } ] }); }); 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 { CookieService } from 'angular2-cookie/core'; import { TranslateModule, TranslateLoader, TranslateStaticLoader, TranslateService } from 'ng2-translate'; import { WindowService } from '../window.service'; import { AppLoggerService } from '../../app-logger.service'; import { HomeComponent } from './home.component'; describe('Component: Home', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpModule, TranslateModule.forRoot({ provide: TranslateLoader, useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'), deps: [Http] }), ], providers: [ CookieService, TranslateService, AppLoggerService, Renderer, HomeComponent, // using window object in Angular 2 is discouraged since // it isn’t only designed to run within your browser, but also on mobiles, // the server or web workers where objects like window may not be available. { provide: WindowService, useValue: window } ] }); }); it('should create an instance', inject([HomeComponent], (component: HomeComponent) => { expect(component).toBeTruthy(); })); });
Fix test due to DI mismatch
Fix test due to DI mismatch
TypeScript
mit
ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps
--- +++ @@ -13,6 +13,7 @@ import { CookieService } from 'angular2-cookie/core'; import { TranslateModule, TranslateLoader, TranslateStaticLoader, TranslateService } from 'ng2-translate'; import { WindowService } from '../window.service'; +import { AppLoggerService } from '../../app-logger.service'; import { HomeComponent } from './home.component'; describe('Component: Home', () => { @@ -31,6 +32,7 @@ providers: [ CookieService, TranslateService, + AppLoggerService, Renderer, HomeComponent,
e8de26ff202e862da95d1c69dea5d0e7fafef761
src/website/pages/MainPage/MainPage.tsx
src/website/pages/MainPage/MainPage.tsx
import * as React from "react"; import { observer } from "mobx-react"; import style from "./style.scss"; import { WebsiteModel } from "../../WebsiteModel"; interface MainPageProps { websiteModel: WebsiteModel; } @observer class MainPage extends React.Component<MainPageProps> { render() { const websiteModel = this.props.websiteModel; return ( <div> <h1 className={style.header}>Hello World!</h1> <span>version: {websiteModel.version}</span> </div> ); } } export { MainPageProps, MainPage };
import * as React from "react"; import { observer } from "mobx-react"; import style from "./style.scss"; import { WebsiteModel } from "../../WebsiteModel"; interface MainPageProps { websiteModel: WebsiteModel; } const MainPage = observer(function(props: MainPageProps) { const websiteModel = props.websiteModel; return ( <div> <h1 className={style.header}>Hello World!</h1> <span>version: {websiteModel.version}</span> </div> ); }); export { MainPageProps, MainPage };
Convert class component to function component
Convert class component to function component
TypeScript
apache-2.0
gamliela/starter-react-mobx-css-modules,gamliela/starter-react-mobx-css-modules,gamliela/starter-react-mobx-css-modules
--- +++ @@ -7,17 +7,14 @@ websiteModel: WebsiteModel; } -@observer -class MainPage extends React.Component<MainPageProps> { - render() { - const websiteModel = this.props.websiteModel; - return ( - <div> - <h1 className={style.header}>Hello World!</h1> - <span>version: {websiteModel.version}</span> - </div> - ); - } -} +const MainPage = observer(function(props: MainPageProps) { + const websiteModel = props.websiteModel; + return ( + <div> + <h1 className={style.header}>Hello World!</h1> + <span>version: {websiteModel.version}</span> + </div> + ); +}); export { MainPageProps, MainPage };
bf1f789e17eba94aa2875954a53046750a5274dc
resources/assets/lib/utils/css.ts
resources/assets/lib/utils/css.ts
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import { forEach } from 'lodash'; export function classWithModifiers(className: string, modifiers?: string[] | Record<string, boolean>) { let ret = className; if (modifiers != null) { if (Array.isArray(modifiers)) { modifiers.forEach((modifier) => { if (modifier != null) { ret += ` ${className}--${modifier}`; } }); } else { forEach(modifiers, (isActive, modifier) => { if (isActive) { ret += ` ${className}--${modifier}`; } }); } } return ret; }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import { forEach } from 'lodash'; type Modifiers = (string | null | undefined)[] | Record<string, boolean | null | undefined>; export function classWithModifiers(className: string, modifiers?: Modifiers) { let ret = className; if (modifiers != null) { if (Array.isArray(modifiers)) { modifiers.forEach((modifier) => { if (modifier != null) { ret += ` ${className}--${modifier}`; } }); } else { forEach(modifiers, (isActive, modifier) => { if (isActive) { ret += ` ${className}--${modifier}`; } }); } } return ret; }
Revert "Apparently null is a-ok for array/record of things"
Revert "Apparently null is a-ok for array/record of things" This reverts commit d182845e558bef14edf1978498c5c964f6187060. It's a bug. Fixed somewhere between 3.7.2 and 3.9.5
TypeScript
agpl-3.0
nekodex/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,omkelderman/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,nanaya/osu-web,notbakaneko/osu-web,nanaya/osu-web,nekodex/osu-web,omkelderman/osu-web,nekodex/osu-web,ppy/osu-web,nekodex/osu-web,nanaya/osu-web,LiquidPL/osu-web,nanaya/osu-web,notbakaneko/osu-web,ppy/osu-web,nekodex/osu-web,ppy/osu-web,omkelderman/osu-web,nanaya/osu-web,LiquidPL/osu-web,ppy/osu-web,ppy/osu-web,omkelderman/osu-web,LiquidPL/osu-web
--- +++ @@ -3,7 +3,9 @@ import { forEach } from 'lodash'; -export function classWithModifiers(className: string, modifiers?: string[] | Record<string, boolean>) { +type Modifiers = (string | null | undefined)[] | Record<string, boolean | null | undefined>; + +export function classWithModifiers(className: string, modifiers?: Modifiers) { let ret = className; if (modifiers != null) {
39ebbf87e6c54dabb0df4383de86fe76d946fcab
desktop/core/src/desktop/js/apps/notebook2/apiUtils.ts
desktop/core/src/desktop/js/apps/notebook2/apiUtils.ts
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { simplePost } from 'api/apiUtilsV2'; import { FORMAT_SQL_API } from 'api/urls'; export const formatSql = async (options: { statements: string; silenceErrors?: boolean; }): Promise<string> => { try { const response = await simplePost< { formatted_statements: string; status: number; }, { statements: string } >(FORMAT_SQL_API, options, { silenceErrors: !!options.silenceErrors, ignoreSuccessErrors: true }); return (response && response.formatted_statements) || options.statements; } catch (err) { if (!options.silenceErrors) { throw err; } } return options.statements; };
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import axios from 'axios'; type FormatSqlApiResponse = { formatted_statements?: string; status: number; }; const FORMAT_SQL_API_URL = '/notebook/api/format'; export const formatSql = async (options: { statements: string; silenceErrors?: boolean; }): Promise<string> => { try { const params = new URLSearchParams(); params.append('statements', options.statements); const response = await axios.post<FormatSqlApiResponse>(FORMAT_SQL_API_URL, params); if (response.data.status !== -1 && response.data.formatted_statements) { return response.data.formatted_statements; } } catch (err) { if (!options.silenceErrors) { throw err; } } return options.statements; };
Switch to axios for the format SQL ajax request
[editor] Switch to axios for the format SQL ajax request
TypeScript
apache-2.0
kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,kawamon/hue
--- +++ @@ -14,25 +14,27 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { simplePost } from 'api/apiUtilsV2'; -import { FORMAT_SQL_API } from 'api/urls'; +import axios from 'axios'; + +type FormatSqlApiResponse = { + formatted_statements?: string; + status: number; +}; + +const FORMAT_SQL_API_URL = '/notebook/api/format'; export const formatSql = async (options: { statements: string; silenceErrors?: boolean; }): Promise<string> => { try { - const response = await simplePost< - { - formatted_statements: string; - status: number; - }, - { statements: string } - >(FORMAT_SQL_API, options, { - silenceErrors: !!options.silenceErrors, - ignoreSuccessErrors: true - }); - return (response && response.formatted_statements) || options.statements; + const params = new URLSearchParams(); + params.append('statements', options.statements); + const response = await axios.post<FormatSqlApiResponse>(FORMAT_SQL_API_URL, params); + + if (response.data.status !== -1 && response.data.formatted_statements) { + return response.data.formatted_statements; + } } catch (err) { if (!options.silenceErrors) { throw err;
496af05201408614fdecabde5905b24eaf0948a7
e2e/cypress/support/commands.ts
e2e/cypress/support/commands.ts
Cypress.Commands.add('login', (username = 'admin') => { window.localStorage.setItem('USER', JSON.stringify({ username })); });
Cypress.Commands.add('login', (username = 'admin') => { window.localStorage.setItem('USER', JSON.stringify({ username })); }); export {};
Fix issue with missing export
Fix issue with missing export
TypeScript
mit
sheldarr/Votenger,sheldarr/Votenger
--- +++ @@ -1,3 +1,5 @@ Cypress.Commands.add('login', (username = 'admin') => { window.localStorage.setItem('USER', JSON.stringify({ username })); }); + +export {};
bc979a3615e893fa6ea044da47b3fcb102687fb8
app/javascript/packs/application.ts
app/javascript/packs/application.ts
require('sweetalert/dist/sweetalert.css'); import start from 'retrospring/common'; import initAnswerbox from 'retrospring/features/answerbox/index'; import initInbox from 'retrospring/features/inbox/index'; import initUser from 'retrospring/features/user'; import initSettings from 'retrospring/features/settings/index'; import initLists from 'retrospring/features/lists'; import initQuestionbox from 'retrospring/features/questionbox'; import initQuestion from 'retrospring/features/question'; import initModeration from 'retrospring/features/moderation'; start(); document.addEventListener('turbolinks:load', initAnswerbox); document.addEventListener('DOMContentLoaded', initInbox); document.addEventListener('DOMContentLoaded', initUser); document.addEventListener('turbolinks:load', initSettings); document.addEventListener('DOMContentLoaded', initLists); document.addEventListener('DOMContentLoaded', initQuestionbox); document.addEventListener('DOMContentLoaded', initQuestion); document.addEventListener('DOMContentLoaded', initModeration);
require('sweetalert/dist/sweetalert.css'); import start from 'retrospring/common'; import initAnswerbox from 'retrospring/features/answerbox/index'; import initInbox from 'retrospring/features/inbox/index'; import initUser from 'retrospring/features/user'; import initSettings from 'retrospring/features/settings/index'; import initLists from 'retrospring/features/lists'; import initQuestionbox from 'retrospring/features/questionbox'; import initQuestion from 'retrospring/features/question'; import initModeration from 'retrospring/features/moderation'; start(); document.addEventListener('DOMContentLoaded', initAnswerbox); document.addEventListener('DOMContentLoaded', initInbox); document.addEventListener('DOMContentLoaded', initUser); document.addEventListener('turbolinks:load', initSettings); document.addEventListener('DOMContentLoaded', initLists); document.addEventListener('DOMContentLoaded', initQuestionbox); document.addEventListener('DOMContentLoaded', initQuestion); document.addEventListener('DOMContentLoaded', initModeration);
Use proper event for global event handlers in answerbox
Use proper event for global event handlers in answerbox
TypeScript
agpl-3.0
Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring
--- +++ @@ -11,7 +11,7 @@ import initModeration from 'retrospring/features/moderation'; start(); -document.addEventListener('turbolinks:load', initAnswerbox); +document.addEventListener('DOMContentLoaded', initAnswerbox); document.addEventListener('DOMContentLoaded', initInbox); document.addEventListener('DOMContentLoaded', initUser); document.addEventListener('turbolinks:load', initSettings);
408cf6185ab8f81197f2d404c10fb1afa5caa87c
src/models/request-promise.ts
src/models/request-promise.ts
import * as request from 'request'; function requestPromise(options: request.Options) { 'use strict'; return new Promise<string>((resolve, reject) => { request(options, (error, response, body) => { error ? reject(error) : resolve(body); }); }); } export default requestPromise;
import * as request from 'request'; function requestPromise(options: request.Options) { 'use strict'; return new Promise<string>((resolve, reject) => { request(options, (error, response, body) => { if (error) { reject(error); } else { resolve(body); } }); }); } export default requestPromise;
Use if statement instead of conditional operator
Use if statement instead of conditional operator
TypeScript
mit
AyaMorisawa/Disskey,AyaMorisawa/Disskey,AyaMorisawa/Disskey
--- +++ @@ -4,7 +4,11 @@ 'use strict'; return new Promise<string>((resolve, reject) => { request(options, (error, response, body) => { - error ? reject(error) : resolve(body); + if (error) { + reject(error); + } else { + resolve(body); + } }); }); }
784950cfdf5661b343341cefbe346357438e64b9
lib/msal-common/src/authority/AuthorityOptions.ts
lib/msal-common/src/authority/AuthorityOptions.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ProtocolMode } from "./ProtocolMode"; import { AzureRegionConfiguration } from "./AzureRegionConfiguration"; export type AuthorityOptions = { protocolMode: ProtocolMode; knownAuthorities: Array<string>; cloudDiscoveryMetadata: string; authorityMetadata: string; azureRegionConfiguration?: AzureRegionConfiguration; }; export enum AzureCloudInstance { // AzureCloudInstance is not specified. None, // Microsoft Azure public cloud AzurePublic = "https://login.microsoftonline.com", // Microsoft Chinese national cloud AzureChina = "https://login.chinacloudapi.cn", // Microsoft German national cloud ("Black Forest") AzureGermany = "https://login.microsoftonline.de", // US Government cloud AzureUsGovernment = "https://login.microsoftonline.us", }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ProtocolMode } from "./ProtocolMode"; import { AzureRegionConfiguration } from "./AzureRegionConfiguration"; export type AuthorityOptions = { protocolMode: ProtocolMode; knownAuthorities: Array<string>; cloudDiscoveryMetadata: string; authorityMetadata: string; azureRegionConfiguration?: AzureRegionConfiguration; }; export enum AzureCloudInstance { // AzureCloudInstance is not specified. None, // Microsoft Azure public cloud AzurePublic = "https://login.microsoftonline.com", // Microsoft PPE AzurePpe = "https://login.windows-ppe.net", // Microsoft Chinese national cloud AzureChina = "https://login.chinacloudapi.cn", // Microsoft German national cloud ("Black Forest") AzureGermany = "https://login.microsoftonline.de", // US Government cloud AzureUsGovernment = "https://login.microsoftonline.us", }
Add PPE to azure cloud instance enum
Add PPE to azure cloud instance enum
TypeScript
mit
AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js
--- +++ @@ -21,6 +21,9 @@ // Microsoft Azure public cloud AzurePublic = "https://login.microsoftonline.com", + // Microsoft PPE + AzurePpe = "https://login.windows-ppe.net", + // Microsoft Chinese national cloud AzureChina = "https://login.chinacloudapi.cn",
a524363a3eedd2e81e60bb0ad0f0c0380b076c1e
server/playerviewmanager.ts
server/playerviewmanager.ts
import { PlayerView } from "../common/PlayerView"; import { probablyUniqueString } from "../common/Toolbox"; export class PlayerViewManager { private playerViews: { [encounterId: string]: PlayerView } = {}; constructor() {} public Get(id: string) { return this.playerViews[id]; } public UpdateEncounter(id: string, newState: any) { this.playerViews[id].encounterState = newState; } public UpdateSettings(id: string, newSettings: any) { this.playerViews[id].settings = newSettings; } public InitializeNew() { const encounterId = probablyUniqueString(); this.playerViews[encounterId] = { encounterState: null, settings: null }; return encounterId; } public EnsureInitialized(id: string) { if (this.playerViews[id] === undefined) { this.playerViews[id] = { encounterState: null, settings: null }; } } public Destroy(id: string) { delete this.playerViews[id]; } }
import { PlayerViewState } from "../common/PlayerViewState"; import { probablyUniqueString } from "../common/Toolbox"; export class PlayerViewManager { private playerViews: { [encounterId: string]: PlayerViewState } = {}; constructor() {} public Get(id: string) { return this.playerViews[id]; } public UpdateEncounter(id: string, newState: any) { this.playerViews[id].encounterState = newState; } public UpdateSettings(id: string, newSettings: any) { this.playerViews[id].settings = newSettings; } public InitializeNew() { const encounterId = probablyUniqueString(); this.playerViews[encounterId] = { encounterState: null, settings: null }; return encounterId; } public EnsureInitialized(id: string) { if (this.playerViews[id] === undefined) { this.playerViews[id] = { encounterState: null, settings: null }; } } public Destroy(id: string) { delete this.playerViews[id]; } }
Fix missed file during rename
Fix missed file during rename
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -1,8 +1,8 @@ -import { PlayerView } from "../common/PlayerView"; +import { PlayerViewState } from "../common/PlayerViewState"; import { probablyUniqueString } from "../common/Toolbox"; export class PlayerViewManager { - private playerViews: { [encounterId: string]: PlayerView } = {}; + private playerViews: { [encounterId: string]: PlayerViewState } = {}; constructor() {}
fbfffcfc8b6b9431bc345a797dd846d5d2625fb9
src/Generation/Elements/ObjectNode.ts
src/Generation/Elements/ObjectNode.ts
import { IElement } from '../Element'; import { DomElementParent } from '../DomElementParent'; export default class ObjNode extends DomElementParent implements IElement { public data?: string; public form?: string; public height?: string; public name?: string; public type?: string; public usemap?: boolean; public width?: string; generate() : HTMLElement{ var element = document.createElement("object"); for(let child of this.Children) { element.appendChild(child.generate()); } return element; } }
import { IElement } from '../Element'; import { DomElementParent } from '../DomElementParent'; export default class ObjectNode extends DomElementParent implements IElement { public data?: string; public form?: string; public height?: string; public name?: string; public type?: string; public usemap?: boolean; public width?: string; generate() : HTMLElement{ var element = document.createElement("object"); for(let child of this.Children) { element.appendChild(child.generate()); } return element; } }
Change object node's name back
Change object node's name back
TypeScript
mit
Flatline4/Flatline4,Flatline4/Flatline4,Flatline4/Flatline4
--- +++ @@ -1,6 +1,6 @@ import { IElement } from '../Element'; import { DomElementParent } from '../DomElementParent'; -export default class ObjNode extends DomElementParent implements IElement { +export default class ObjectNode extends DomElementParent implements IElement { public data?: string; public form?: string; public height?: string;
c08c6f249c2136a9396866fe7b0d0f6d47c96077
src/components/ThemeProvider/types.ts
src/components/ThemeProvider/types.ts
import { MediaAliases, Media } from '../../media/types'; export type Breakpoints = { [key in Media]: number }; export type PartialBreakpoints = Partial<Breakpoints>; interface GridTheme { breakpoints?: PartialBreakpoints; row?: { padding?: number; }; col?: { padding?: number; }; container?: { padding?: number; maxWidth?: PartialBreakpoints; }; } export interface ThemeProps { gridTheme?: GridTheme; } export type DefaultContainerMaxWidth = { [K in MediaAliases]: number }; export interface StyledBootstrapGrid extends GridTheme { container: { padding?: number; maxWidth: PartialBreakpoints; }; getContainerPadding: any; getContainerMaxWidth: any; getRowPadding: any; getColPadding: any; } export interface Theme { styledBootstrapGrid: StyledBootstrapGrid; }
import { MediaAliases, Media } from '../../media/types'; export type Breakpoints = { [key in Media]: number }; export type PartialBreakpoints = Partial<Breakpoints>; interface GridTheme { breakpoints?: PartialBreakpoints; row?: { padding?: number; }; col?: { padding?: number; }; container?: { padding?: number; maxWidth?: PartialBreakpoints; }; } export interface ThemeProps { gridTheme?: GridTheme; children: React.ReactNode; } export type DefaultContainerMaxWidth = { [K in MediaAliases]: number }; export interface StyledBootstrapGrid extends GridTheme { container: { padding?: number; maxWidth: PartialBreakpoints; }; getContainerPadding: any; getContainerMaxWidth: any; getRowPadding: any; getColPadding: any; } export interface Theme { styledBootstrapGrid: StyledBootstrapGrid; }
Add children as prop to gridThemeProvider
Add children as prop to gridThemeProvider
TypeScript
mit
dragma/styled-bootstrap-grid,dragma/styled-bootstrap-grid,dragma/styled-bootstrap-grid,dragma/styled-bootstrap-grid
--- +++ @@ -19,6 +19,7 @@ export interface ThemeProps { gridTheme?: GridTheme; + children: React.ReactNode; } export type DefaultContainerMaxWidth = { [K in MediaAliases]: number };
e0ca413c54538f979ecd416eb9f38c5e9f303751
src/mol-model/structure/query/queries/atom-set.ts
src/mol-model/structure/query/queries/atom-set.ts
/** * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Koya Sakuma * Adapted from MolQL implemtation of atom-set.ts * * Copyright (c) 2017 MolQL contributors, licensed under MIT, See LICENSE file for more info. * * @author David Sehnal <david.sehnal@gmail.com> */ import { StructureQuery } from '../query'; import { StructureSelection } from '../selection'; import { getCurrentStructureProperties } from './filters'; import { QueryContext, QueryFn } from '../context'; export function atomCount(ctx: QueryContext) { return ctx.currentStructure.elementCount; } export function countQuery(query: StructureQuery) { return (ctx: QueryContext) => { const sel = query(ctx); const x: number = StructureSelection.structureCount(sel); return x; }; } export function propertySet(prop: QueryFn<any>) { return (ctx: QueryContext) => { const set = new Set(); const x = getCurrentStructureProperties(ctx, prop, set); return x; }; }
/** * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Koya Sakuma * Adapted from MolQL implemtation of atom-set.ts * * Copyright (c) 2017 MolQL contributors, licensed under MIT, See LICENSE file for more info. * * @author David Sehnal <david.sehnal@gmail.com> */ import { StructureQuery } from '../query'; import { StructureSelection } from '../selection'; import { getCurrentStructureProperties } from './filters'; import { QueryContext, QueryFn } from '../context'; export function atomCount(ctx: QueryContext) { return ctx.currentStructure.elementCount; } export function countQuery(query: StructureQuery) { return (ctx: QueryContext) => { const sel = query(ctx); return StructureSelection.structureCount(sel); }; } export function propertySet(prop: QueryFn<any>) { return (ctx: QueryContext) => { const set = new Set(); return getCurrentStructureProperties(ctx, prop, set); }; }
Remove needless substitutions to a temporary variable x
Remove needless substitutions to a temporary variable x
TypeScript
mit
molstar/molstar,molstar/molstar,molstar/molstar
--- +++ @@ -23,16 +23,14 @@ export function countQuery(query: StructureQuery) { return (ctx: QueryContext) => { const sel = query(ctx); - const x: number = StructureSelection.structureCount(sel); - return x; + return StructureSelection.structureCount(sel); }; } export function propertySet(prop: QueryFn<any>) { return (ctx: QueryContext) => { const set = new Set(); - const x = getCurrentStructureProperties(ctx, prop, set); - return x; + return getCurrentStructureProperties(ctx, prop, set); }; }
020cbbf358e54d55265d42086e7dbfe46f3d5123
src/lib/interface/IRoute.ts
src/lib/interface/IRoute.ts
type Dictionary<T> = { [key: string]: T }; /** * @description This should be the vue router type but it causes a lot of issues with mismatching versions so create * a separate interface for the route */ interface IRoute { path: string; name?: string; hash: string; query: Dictionary<string>; params: Dictionary<string>; fullPath: string; matched: Array<any>; redirectedFrom?: string; meta?: any; } export default IRoute;
/** * @description This should be the vue router type but it causes a lot of issues with mismatching versions so create * a separate interface for the route */ interface IRoute { path: string; name?: string; hash: string; query: { [key: string]: string }; params: { [key: string]: string }; fullPath: string; matched: Array<any>; redirectedFrom?: string; meta?: any; } export default IRoute;
Replace type dictionary with hardcoded type
Replace type dictionary with hardcoded type
TypeScript
mit
larsvanbraam/vue-transition-component,larsvanbraam/vue-transition-component,larsvanbraam/vue-transition-component
--- +++ @@ -1,5 +1,3 @@ -type Dictionary<T> = { [key: string]: T }; - /** * @description This should be the vue router type but it causes a lot of issues with mismatching versions so create * a separate interface for the route @@ -8,8 +6,8 @@ path: string; name?: string; hash: string; - query: Dictionary<string>; - params: Dictionary<string>; + query: { [key: string]: string }; + params: { [key: string]: string }; fullPath: string; matched: Array<any>; redirectedFrom?: string;
0a4d0e5ea2c633f8e248d0d84a54b167edf40058
app/src/renderer/components/paper/paper-button.tsx
app/src/renderer/components/paper/paper-button.tsx
// Copyright (c) 2016 Vadim Macagon // MIT License, see LICENSE file for full terms. import * as React from 'react'; import { PolymerComponent } from './polymer'; import { omitOwnProps } from '../../../common/utils'; /** * React component that wraps a Polymer paper-button custom element. */ export class PaperButtonComponent extends PolymerComponent<PolymerElements.PaperButton, PaperButtonComponent.IProps, {}> { protected get cssVars() { const styles = this.props.styles; const vars: any = {}; if (styles) { if (styles.backgroundColor) { vars['--paper-button-background-color'] = styles.backgroundColor; } if (styles.textColor) { vars['--paper-button-color'] = styles.textColor; } } return vars; } protected get eventBindings() { return [ { event: 'tap', listener: 'onDidTap' } ]; } protected renderElement(props: PaperButtonComponent.IProps) { const elementProps = omitOwnProps(props, ['styles']); return ( <paper-button {...elementProps}></paper-button> ); } } namespace PaperButtonComponent { export interface IProps extends PolymerComponent.IProps { /** Callback to invoke after the user taps on the button. */ onDidTap?: (e: polymer.TapEvent) => void; styles?: { backgroundColor?: string; textColor?: string; } } }
// Copyright (c) 2016 Vadim Macagon // MIT License, see LICENSE file for full terms. import * as React from 'react'; import { PolymerComponent } from './polymer'; import { omitOwnProps } from '../../../common/utils'; /** * React component that wraps a Polymer paper-button custom element. */ export class PaperButtonComponent extends PolymerComponent<PolymerElements.PaperButton, PaperButtonComponent.IProps, {}> { protected get cssVars() { const styles = this.props.styles; const vars: any = {}; if (styles) { vars['--paper-button'] = {}; if (styles.backgroundColor) { vars['--paper-button']['background-color'] = styles.backgroundColor; } if (styles.textColor) { vars['--paper-button']['color'] = styles.textColor; } } return vars; } protected get eventBindings() { return [ { event: 'tap', listener: 'onDidTap' } ]; } protected renderElement(props: PaperButtonComponent.IProps) { const elementProps = omitOwnProps(props, ['styles']); return ( <paper-button {...elementProps}></paper-button> ); } } namespace PaperButtonComponent { export interface IProps extends PolymerComponent.IProps { /** Callback to invoke after the user taps on the button. */ onDidTap?: (e: polymer.TapEvent) => void; styles?: { backgroundColor?: string; textColor?: string; } } }
Fix PaperButtonComponent style overrides not being applied
Fix PaperButtonComponent style overrides not being applied Not sure if it was the limitations of the CSS vars shim Polymer uses, or just a scope issue.
TypeScript
mit
debugworkbench/hydragon,debugworkbench/hydragon,debugworkbench/hydragon
--- +++ @@ -16,11 +16,12 @@ const vars: any = {}; if (styles) { + vars['--paper-button'] = {}; if (styles.backgroundColor) { - vars['--paper-button-background-color'] = styles.backgroundColor; + vars['--paper-button']['background-color'] = styles.backgroundColor; } if (styles.textColor) { - vars['--paper-button-color'] = styles.textColor; + vars['--paper-button']['color'] = styles.textColor; } } return vars;
ce5fe238ffa1fd7208bd7f2be05c5e217e0d142b
src/server/lib/TestTask.ts
src/server/lib/TestTask.ts
/** * Created by Home on 1/1/2016. */ import Log = require('../api/RTSLog') import RtsIo = require("../api/io"); export class TestTask { //Constructor for task public name:string; constructor(public name:string, public duration:number) { this.name = name; } execute() { var time0 = Date.now(); while (true) { var time1 = Date.now(); var elapsed = time1 - time0; if (elapsed >= this.duration) break; } var msg = this.name + " started at: " + time0 + " ran for: " + elapsed; console.log(msg); Log.log.info(msg); RtsIo.io.emit('Task data',msg); } }
/** * Created by Home on 1/1/2016. */ import Log = require('../api/RTSLog') import RtsIo = require("../api/io"); export class TestTask { //Constructor for task public name:string; constructor(public name:string, public duration:number) { this.name = name; } execute() { var time0 = Date.now(); while (true) { var time1 = Date.now(); var elapsed = time1 - time0; if (elapsed >= this.duration) break; } var json = JSON.stringify({Task:this.name, Started:time0, Ran:elapsed}, null, 4); console.log(json); Log.log.info(json); RtsIo.io.emit('Task data',json); } }
Send data in json format
Send data in json format
TypeScript
mit
rtsjs/rts,rtsjs/rts,rtsjs/rts
--- +++ @@ -20,9 +20,10 @@ if (elapsed >= this.duration) break; } - var msg = this.name + " started at: " + time0 + " ran for: " + elapsed; - console.log(msg); - Log.log.info(msg); - RtsIo.io.emit('Task data',msg); + + var json = JSON.stringify({Task:this.name, Started:time0, Ran:elapsed}, null, 4); + console.log(json); + Log.log.info(json); + RtsIo.io.emit('Task data',json); } }
cbb9209b9578ffbe23432bce6d16495b0cee50ef
src/utils/general-utils.ts
src/utils/general-utils.ts
import * as toBuffer from 'blob-to-buffer' import * as domtoimage from 'dom-to-image' import { remote, shell } from 'electron' import * as fs from 'fs' const container = document.getElementById('app-container') export function saveImage(fileName: string): Promise<string> { return domtoimage.toBlob(container).then((blob: Blob) => { toBuffer(blob, (__: any, buffer: Buffer) => { fs.writeFile(fileName, buffer) }) }) } export function openLinksInExternalBrowser(): void { const links = document.querySelectorAll('a[href]') Array.prototype.forEach.call(links, (link: Element) => { const url = link.getAttribute('href') if (url!.indexOf('http') === 0) { link.addEventListener('click', (e) => { e.preventDefault() shell.openExternal(url!) }) } }) } export function setFileMenuItemsEnable(enable: boolean): void { const menu = remote.Menu.getApplicationMenu() menu.items[1].submenu!.items[1].enabled = enable menu.items[1].submenu!.items[2].enabled = enable }
import * as toBuffer from 'blob-to-buffer' import * as domtoimage from 'dom-to-image' import { remote, shell } from 'electron' import * as fs from 'fs' const container = document.getElementById('app-container') export function saveImage(fileName: string): Promise<string> { return domtoimage.toBlob(container).then((blob: Blob) => { toBuffer(blob, (__: any, buffer: Buffer) => { fs.writeFile(fileName, buffer) }) }) } export function openLinksInExternalBrowser(): void { const links = document.querySelectorAll('a[href]') for (const link of links) { const url = link.getAttribute('href') if (url!.indexOf('http') === 0) { link.addEventListener('click', (e) => { e.preventDefault() shell.openExternal(url!) }) } } } export function setFileMenuItemsEnable(enable: boolean): void { const menu = remote.Menu.getApplicationMenu() menu.items[1].submenu!.items[1].enabled = enable menu.items[1].submenu!.items[2].enabled = enable }
Replace forEach.call with for each loop
Replace forEach.call with for each loop
TypeScript
mit
nrlquaker/nfov,nrlquaker/nfov
--- +++ @@ -15,7 +15,7 @@ export function openLinksInExternalBrowser(): void { const links = document.querySelectorAll('a[href]') - Array.prototype.forEach.call(links, (link: Element) => { + for (const link of links) { const url = link.getAttribute('href') if (url!.indexOf('http') === 0) { link.addEventListener('click', (e) => { @@ -23,7 +23,7 @@ shell.openExternal(url!) }) } - }) + } } export function setFileMenuItemsEnable(enable: boolean): void {
aef05e74b9e20ecceaa58bd019056e42991d27ae
client/app/accounts/services/account-guard.service.ts
client/app/accounts/services/account-guard.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router'; import { CurrentAccountService } from './current-account.service'; @Injectable() export class AccountGuardService implements CanActivate { constructor( private currentAccountService: CurrentAccountService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { const url: string = state.url; return this.checkLogin(url); } checkLogin(url: string): Observable<boolean> { return this.currentAccountService.get().map((account: string) => { if (! account) { // Store the attempted URL for redirecting after login this.currentAccountService.redirectUrl = url; this.router.navigate(['accounts', 'login']); return false; } return true; }); } }
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router'; import { CurrentAccountService } from './current-account.service'; @Injectable() export class AccountGuardService implements CanActivate { constructor( private currentAccountService: CurrentAccountService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { const url: string = state.url; return this.checkLogin(url); } checkLogin(url: string): Observable<boolean> { return this.currentAccountService.get().map((account: string) => { if (!account) { this.router.navigate(['accounts', 'login'], { queryParams: { redirectUrl: url } }); return false; } return true; }); } }
Use query params for the redirect url
Use query params for the redirect url
TypeScript
mit
fvilers/angular2-training,fvilers/angular2-training,fvilers/angular2-training
--- +++ @@ -22,11 +22,8 @@ checkLogin(url: string): Observable<boolean> { return this.currentAccountService.get().map((account: string) => { - if (! account) { - // Store the attempted URL for redirecting after login - this.currentAccountService.redirectUrl = url; - - this.router.navigate(['accounts', 'login']); + if (!account) { + this.router.navigate(['accounts', 'login'], { queryParams: { redirectUrl: url } }); return false; } return true;
0a21fb633dc2ca6416857d4e5cee7ae0aaa72a52
client-react/components/Routes.tsx
client-react/components/Routes.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { Route, Redirect, Switch } from 'react-router-dom'; import { Login, Register, ConfirmEmail } from './Auth'; import { Landing } from './Landing'; import { Header } from './Header'; import auth from '../services/authentication'; export default class Routes extends React.Component<any, any> { render() { return <div> <Route exact path='/' component={Login} /> <Route path='/register' component={Register} /> <Route path='/confirm' component={ConfirmEmail} /> <DefaultLayout path='/landing' component={Landing} /> </div> } } const DefaultLayout = ({ component: Component, ...rest }: { component: any, path: string }) => ( <Route {...rest} render={props => ( auth.isLoggedIn() ? ( <div> <Header></Header> <div className="container"> <Component {...props} /> </div> </div> ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> ) )} /> );
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { Route, Redirect, Switch } from 'react-router-dom'; import { Login, Register, ConfirmEmail } from './Auth'; import { Landing } from './Landing'; import { Header } from './Header'; import auth from '../services/authentication'; export default class Routes extends React.Component<any, any> { render() { return <div> <Route exact path='/' component={Login} /> <Route path='/register' component={Register} /> <Route path='/confirm' component={ConfirmEmail} /> <DefaultLayout path='/landing' component={Landing} /> </div> } } const DefaultLayout = ({ component: Component, ...rest }: { component: any, path: string }) => ( <Route {...rest} render={props => ( auth.isLoggedIn() ? ( <div> <Header></Header> <div className="container"> <Component {...props} /> </div> </div> ) : ( <Redirect to={{ pathname: '/', state: { from: props.location } }} /> ) )} /> );
Fix invalid /login route reference (should be /)
Fix invalid /login route reference (should be /)
TypeScript
mit
bradyholt/aspnet-core-react-template,bradyholt/aspnet-core-react-template,bradyholt/aspnet-core-react-template,bradyholt/aspnet-core-react-template,bradyholt/aspnet-core-react-template
--- +++ @@ -28,7 +28,7 @@ </div> ) : ( <Redirect to={{ - pathname: '/login', + pathname: '/', state: { from: props.location } }} /> )
3183e39527e1c9008a2d9abdfe4db7486894c4cf
app/src/ui/lib/theme-change-monitor.ts
app/src/ui/lib/theme-change-monitor.ts
import { remote } from 'electron' import { ApplicationTheme } from './application-theme' import { IDisposable, Disposable, Emitter } from 'event-kit' import { supportsDarkMode, isDarkModeEnabled } from './dark-theme' class ThemeChangeMonitor implements IDisposable { private readonly emitter = new Emitter() public constructor() { this.subscribe() } public dispose() { if (remote.nativeTheme) { remote.nativeTheme.removeAllListeners() } } private subscribe = () => { if (!supportsDarkMode() || !remote.nativeTheme) { return } remote.nativeTheme.addListener('updated', this.onThemeNotificationFromOS) } private onThemeNotificationFromOS = (event: string, userInfo: any) => { const darkModeEnabled = isDarkModeEnabled() const theme = darkModeEnabled ? ApplicationTheme.Dark : ApplicationTheme.Light this.emitThemeChanged(theme) } public onThemeChanged(fn: (theme: ApplicationTheme) => void): Disposable { return this.emitter.on('theme-changed', fn) } private emitThemeChanged(theme: ApplicationTheme) { this.emitter.emit('theme-changed', theme) } } // this becomes our singleton that we can subscribe to from anywhere export const themeChangeMonitor = new ThemeChangeMonitor() // this ensures we cleanup any existing subscription on exit remote.app.on('will-quit', () => { themeChangeMonitor.dispose() })
import { remote } from 'electron' import { ApplicationTheme } from './application-theme' import { IDisposable, Disposable, Emitter } from 'event-kit' import { supportsDarkMode, isDarkModeEnabled } from './dark-theme' class ThemeChangeMonitor implements IDisposable { private readonly emitter = new Emitter() public constructor() { this.subscribe() } public dispose() { remote.nativeTheme.removeAllListeners() } private subscribe = () => { if (!supportsDarkMode()) { return } remote.nativeTheme.addListener('updated', this.onThemeNotificationFromOS) } private onThemeNotificationFromOS = (event: string, userInfo: any) => { const darkModeEnabled = isDarkModeEnabled() const theme = darkModeEnabled ? ApplicationTheme.Dark : ApplicationTheme.Light this.emitThemeChanged(theme) } public onThemeChanged(fn: (theme: ApplicationTheme) => void): Disposable { return this.emitter.on('theme-changed', fn) } private emitThemeChanged(theme: ApplicationTheme) { this.emitter.emit('theme-changed', theme) } } // this becomes our singleton that we can subscribe to from anywhere export const themeChangeMonitor = new ThemeChangeMonitor() // this ensures we cleanup any existing subscription on exit remote.app.on('will-quit', () => { themeChangeMonitor.dispose() })
Revert "Fix nativeTheme errors in tests on Windows 10 1809+ and Server 2019+"
Revert "Fix nativeTheme errors in tests on Windows 10 1809+ and Server 2019+" This reverts commit b8a7c8c5c73439e20df6398d62709f72a5206e0d.
TypeScript
mit
shiftkey/desktop,shiftkey/desktop,say25/desktop,say25/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,artivilla/desktop,say25/desktop
--- +++ @@ -11,13 +11,11 @@ } public dispose() { - if (remote.nativeTheme) { - remote.nativeTheme.removeAllListeners() - } + remote.nativeTheme.removeAllListeners() } private subscribe = () => { - if (!supportsDarkMode() || !remote.nativeTheme) { + if (!supportsDarkMode()) { return }
1a44445f9e1e82eb976a0bca424e9230c0e06a97
src/api/hosts/index.ts
src/api/hosts/index.ts
import { Router } from 'express' import * as hosts from './get' import * as containers from './get-containers' const router = Router() router.get('/', hosts.getAll) router.get('/containers', containers.getAll) router.get('/:id', hosts.getOne) router.get('/containers/:id', containers.getOne) export default router
import { Router } from 'express' import * as hosts from './get' import * as containers from './get-containers' const router = Router() router.get('/', hosts.getAll) router.get('/containers', containers.getAll) router.get('/:id', hosts.getOne) router.get('/:id/containers', containers.getOne) export default router
Change host specific containers route
Change host specific containers route
TypeScript
mit
paypac/node-concierge,paypac/node-concierge,the-concierge/concierge,paypac/node-concierge,the-concierge/concierge,paypac/node-concierge,the-concierge/concierge
--- +++ @@ -8,6 +8,6 @@ router.get('/containers', containers.getAll) router.get('/:id', hosts.getOne) -router.get('/containers/:id', containers.getOne) +router.get('/:id/containers', containers.getOne) export default router
0cb83c5f629541838fdc5432fe6b3e5e48a06b77
src/scroll-listener.ts
src/scroll-listener.ts
import 'rxjs/add/observable/fromEvent'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/sampleTime'; import 'rxjs/add/operator/share'; import { Observable } from 'rxjs/Observable'; const scrollListeners = {}; // Only create one scroll listener per target and share the observable. // Typical, there will only be one observable export const getScrollListener = (scrollTarget): Observable<any> => { if (scrollTarget in scrollListeners) { return scrollListeners[scrollTarget]; } scrollListeners[scrollTarget] = Observable.fromEvent(scrollTarget, 'scroll') .sampleTime(100) .startWith('') .share(); return scrollListeners[scrollTarget]; };
import 'rxjs/add/observable/fromEvent'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/sampleTime'; import 'rxjs/add/operator/share'; import { Observable } from 'rxjs/Observable'; const scrollListeners = {}; // Only create one scroll listener per target and share the observable. // Typical, there will only be one observable export const getScrollListener = (scrollTarget): Observable<any> => { if (scrollTarget in scrollListeners) { return scrollListeners[scrollTarget]; } scrollListeners[scrollTarget] = Observable.fromEvent(scrollTarget, 'scroll') .sampleTime(100) .share() .startWith(''); return scrollListeners[scrollTarget]; };
Put a default value on all subscriptions
:bug: Put a default value on all subscriptions
TypeScript
mit
tjoskar/ng2-lazyload-image,tjoskar/ng-lazyload-image,tjoskar/ng-lazyload-image,tjoskar/ng2-lazyload-image,tjoskar/ng2-lazyload-image
--- +++ @@ -14,7 +14,7 @@ } scrollListeners[scrollTarget] = Observable.fromEvent(scrollTarget, 'scroll') .sampleTime(100) - .startWith('') - .share(); + .share() + .startWith(''); return scrollListeners[scrollTarget]; };
be2c7bb7ddf70132246cb04b6c338a1528fbf079
APM-Final/src/app/products/product-edit-info.component.ts
APM-Final/src/app/products/product-edit-info.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { NgForm } from '@angular/forms'; import { IProduct } from './product'; @Component({ templateUrl: './app/products/product-edit-info.component.html' }) export class ProductEditInfoComponent implements OnInit { @ViewChild(NgForm) productForm: NgForm; errorMessage: string; product: IProduct; constructor(private route: ActivatedRoute) { } ngOnInit(): void { this.route.parent.data.subscribe(data => { this.product = data['product']; if (this.productForm) { this.productForm.reset(); } }); } }
import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { NgForm } from '@angular/forms'; import { IProduct } from './product'; @Component({ templateUrl: './app/products/product-edit-info.component.html' }) export class ProductEditInfoComponent implements OnInit { @ViewChild(NgForm) productForm: NgForm; errorMessage: string; product: IProduct; constructor(private route: ActivatedRoute) { } ngOnInit(): void { this.route.parent.data.subscribe(data => { if (this.productForm) { this.productForm.reset(); } this.product = data['product']; }); } }
Reorder where the form is reset.
Reorder where the form is reset.
TypeScript
mit
DeborahK/Angular-Routing,DeborahK/Angular-Routing,DeborahK/Angular-Routing
--- +++ @@ -5,23 +5,23 @@ import { IProduct } from './product'; @Component({ - templateUrl: './app/products/product-edit-info.component.html' + templateUrl: './app/products/product-edit-info.component.html' }) export class ProductEditInfoComponent implements OnInit { - @ViewChild(NgForm) productForm: NgForm; + @ViewChild(NgForm) productForm: NgForm; - errorMessage: string; - product: IProduct; + errorMessage: string; + product: IProduct; - constructor(private route: ActivatedRoute) { } + constructor(private route: ActivatedRoute) { } - ngOnInit(): void { - this.route.parent.data.subscribe(data => { - this.product = data['product']; + ngOnInit(): void { + this.route.parent.data.subscribe(data => { + if (this.productForm) { + this.productForm.reset(); + } - if (this.productForm) { - this.productForm.reset(); - } - }); - } + this.product = data['product']; + }); + } }
e88192e981de0fa19e3be3eb2d440003a4a8d246
assets/src/images.ts
assets/src/images.ts
export function get(href: string): Promise<SVGSVGElement> { return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); request.open('GET', href); request.addEventListener('load', (event: ProgressEvent) => { const request = <XMLHttpRequest>event.currentTarget; const xml = request.responseXML; if (!xml || !xml.children[0]) { return reject('no xml data'); } return resolve(<SVGSVGElement>xml.children[0]); }); request.send(); }); } export async function svg2image( svg: SVGSVGElement, color: string ): Promise<Image> { svg.setAttribute('fill', color); const DOMURL = window.URL || window; const image = new Image(); const blob = new Blob([svg.outerHTML], {type: 'image/svg+xml'}); const url = DOMURL.createObjectURL(blob); image.src = url; const promise: Promise<Image> = new Promise((resolve, reject) => { window.setTimeout(reject, 100); image.onload = () => resolve(image); }); return promise; } export async function loadImage(id: string, color: string): Promise<Image> { const link = <HTMLLinkElement | null>document.getElementById(id); if (!link || !link.href) { return Promise.reject('no href on link'); } const svg: SVGSVGElement = await get(link.href); return svg2image(svg, color); }
export function get(href: string): Promise<SVGSVGElement> { return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); request.open('GET', href); request.addEventListener('load', (event: ProgressEvent) => { const request = <XMLHttpRequest>event.currentTarget; const xml = request.responseXML; if (!xml || !xml.children[0]) { return reject('no xml data'); } return resolve(<SVGSVGElement>xml.children[0]); }); request.send(); }); } export async function svg2image( svg: SVGSVGElement, color: string ): Promise<Image> { svg.setAttribute('fill', color); const DOMURL = window.URL || window; const image = new Image(); const blob = new Blob([svg.outerHTML], {type: 'image/svg+xml'}); const url = DOMURL.createObjectURL(blob); image.src = url; const promise: Promise<Image> = new Promise((resolve) => { image.onload = () => resolve(image); }); return promise; } export async function loadImage(id: string, color: string): Promise<Image> { const link = <HTMLLinkElement | null>document.getElementById(id); if (!link || !link.href) { return Promise.reject('no href on link'); } const svg: SVGSVGElement = await get(link.href); return svg2image(svg, color); }
Remove timeout on image loading.
Remove timeout on image loading.
TypeScript
agpl-3.0
Dkendal/battle_snake,Dkendal/battle_snake,Dkendal/battle_snake,Dkendal/battle_snake,Dkendal/battle_snake
--- +++ @@ -36,8 +36,7 @@ image.src = url; - const promise: Promise<Image> = new Promise((resolve, reject) => { - window.setTimeout(reject, 100); + const promise: Promise<Image> = new Promise((resolve) => { image.onload = () => resolve(image); });
65eb6747411bb48f314952c1f2b5a61c576d6435
client/LauncherViewModel.ts
client/LauncherViewModel.ts
import * as ko from "knockout"; import { env } from "./Environment"; import { Metrics } from "./Utility/Metrics"; import { Store } from "./Utility/Store"; export class LauncherViewModel { constructor() { const pageLoadData = { referrer: document.referrer, userAgent: navigator.userAgent }; Metrics.TrackEvent("LandingPageLoad", pageLoadData); const firstVisit = Store.Load(Store.User, "SkipIntro") === null; if (firstVisit && window.location.href != env.CanonicalURL + "/") { window.location.href = env.CanonicalURL; } } public GeneratedEncounterId = env.EncounterId; public JoinEncounterInput = ko.observable<string>(""); public StartEncounter = () => { let encounterId = this.JoinEncounterInput().split("/").pop(); window.location.href = `e/${encounterId || this.GeneratedEncounterId}`; } public JoinEncounter = () => { let encounterId = this.JoinEncounterInput().split("/").pop(); if (encounterId) { window.location.href = `p/${encounterId}`; } } public JoinEncounterButtonClass = () => { let encounterId = this.JoinEncounterInput().split("/").pop(); return encounterId ? "enabled" : "disabled"; } }
import * as ko from "knockout"; import { env } from "./Environment"; import { Metrics } from "./Utility/Metrics"; import { Store } from "./Utility/Store"; export class LauncherViewModel { constructor() { const pageLoadData = { referrer: document.referrer, userAgent: navigator.userAgent }; Metrics.TrackEvent("LandingPageLoad", pageLoadData); const notAtCanonicalUrl = env.CanonicalURL.length > 0 && window.location.href != env.CanonicalURL + "/"; if (notAtCanonicalUrl) { const isFirstVisit = Store.Load(Store.User, "SkipIntro") === null; if (isFirstVisit) { window.location.href = env.CanonicalURL; } else { this.transferLocalStorageToCanonicalUrl(); } } } public GeneratedEncounterId = env.EncounterId; public JoinEncounterInput = ko.observable<string>(""); public StartEncounter = () => { let encounterId = this.JoinEncounterInput().split("/").pop(); window.location.href = `e/${encounterId || this.GeneratedEncounterId}`; } public JoinEncounter = () => { let encounterId = this.JoinEncounterInput().split("/").pop(); if (encounterId) { window.location.href = `p/${encounterId}`; } } public JoinEncounterButtonClass = () => { let encounterId = this.JoinEncounterInput().split("/").pop(); return encounterId ? "enabled" : "disabled"; } private transferLocalStorageToCanonicalUrl() { } }
Add stub call to transferLocalStorageToCanonicalUrl()
Add stub call to transferLocalStorageToCanonicalUrl()
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -11,10 +11,16 @@ userAgent: navigator.userAgent }; Metrics.TrackEvent("LandingPageLoad", pageLoadData); - const firstVisit = Store.Load(Store.User, "SkipIntro") === null; - if (firstVisit && window.location.href != env.CanonicalURL + "/") { - window.location.href = env.CanonicalURL; + const notAtCanonicalUrl = env.CanonicalURL.length > 0 && window.location.href != env.CanonicalURL + "/"; + if (notAtCanonicalUrl) { + const isFirstVisit = Store.Load(Store.User, "SkipIntro") === null; + if (isFirstVisit) { + window.location.href = env.CanonicalURL; + } else { + this.transferLocalStorageToCanonicalUrl(); + } } + } public GeneratedEncounterId = env.EncounterId; @@ -36,4 +42,8 @@ let encounterId = this.JoinEncounterInput().split("/").pop(); return encounterId ? "enabled" : "disabled"; } + + private transferLocalStorageToCanonicalUrl() { + + } }
56b12b46551f8e831ea65522bade14c73eb6d18c
client/src/components/forms/errorsField.tsx
client/src/components/forms/errorsField.tsx
import * as _ from 'lodash'; import * as React from 'react'; export const ErrorsField = (errors: any) => { if (_.isArray(errors)) { return ( <div className="has-error form-group"> <div className="col-sm-10 col-lg-offset-2"> {errors.map((error) => <div className="help-block" key={error}>{error}</div>)} </div> </div> ); } return null; };
import * as _ from 'lodash'; import * as React from 'react'; export const ErrorsField = (errors: any) => { if (_.isArray(errors)) { return ( <div className="has-error form-group"> <div className="col-sm-10 col-lg-offset-2"> {errors.map((error) => <div className="help-block" key={error}>{error}</div>)} </div> </div> ); } else if (typeof errors === 'string') { return ( <div className="has-error form-group"> <div className="col-sm-10 col-lg-offset-2"> <div className="help-block">{errors}</div> </div> </div> ); } return null; };
Update errors field to handle string errors as well
Update errors field to handle string errors as well
TypeScript
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
--- +++ @@ -10,6 +10,14 @@ </div> </div> ); + } else if (typeof errors === 'string') { + return ( + <div className="has-error form-group"> + <div className="col-sm-10 col-lg-offset-2"> + <div className="help-block">{errors}</div> + </div> + </div> + ); } return null; };
5092855a3d5552264d2d6f5c52da470267d0dba3
src/SyntaxNodes/InlineSyntaxNode.ts
src/SyntaxNodes/InlineSyntaxNode.ts
import { SyntaxNode } from './SyntaxNode' export interface InlineSyntaxNode extends SyntaxNode { // Represents the text of the syntax node as it should appear inline. Some inline conventions // don't have any e.g. (footnotes, images). // // This method is used help to determine whether table cells are numeric. textAppearingInline(): string // Represents the searchable text of the syntax node. In contrast to `textAppearingInline`, // footnotes and images do have searchable text (footnotes have content, and images have a // description). // // This method is used to help section links match the most appropriate table of content entry. searchableText(): string }
import { SyntaxNode } from './SyntaxNode' export interface InlineSyntaxNode extends SyntaxNode { // Represents the text of the syntax node as it should appear inline. Some inline conventions // don't have any e.g. (footnotes, images). // // This method is ultimately used to help determine whether table cells are numeric. textAppearingInline(): string // Represents the searchable text of the syntax node. In contrast to `textAppearingInline`, // footnotes and images do have searchable text (footnotes have content, and images have a // description). // // This method is used to help match section links to the most appropriate table of content // entry. searchableText(): string }
Clarify a couple of comments
Clarify a couple of comments
TypeScript
mit
start/up,start/up
--- +++ @@ -5,13 +5,14 @@ // Represents the text of the syntax node as it should appear inline. Some inline conventions // don't have any e.g. (footnotes, images). // - // This method is used help to determine whether table cells are numeric. + // This method is ultimately used to help determine whether table cells are numeric. textAppearingInline(): string // Represents the searchable text of the syntax node. In contrast to `textAppearingInline`, // footnotes and images do have searchable text (footnotes have content, and images have a // description). // - // This method is used to help section links match the most appropriate table of content entry. + // This method is used to help match section links to the most appropriate table of content + // entry. searchableText(): string }
cfa1b339d3524659319f10aa6d681e9c74618d6f
lib/model/AbstractEntity.ts
lib/model/AbstractEntity.ts
import {isPresent} from "../utils/core"; import {attribute} from "../annotations"; import {AttributesMetadata} from "../metadata/AttributesMetadata"; export abstract class AbstractEntity<T> { @attribute() id?:string; constructor(params:Partial<T> = {}) { let attributesMetadata = AttributesMetadata.getForInstance(this); Object.keys(params).forEach(propertyName => { if (!attributesMetadata.isAttributeDefined(propertyName)) { console.warn(`${this.constructor.name} will be initialized with unknown param: ${propertyName}`) } this[propertyName] = params[propertyName as any]; }); } isPersisted():boolean { return isPresent(this.id); } }
import {isPresent} from "../utils/core"; import {attribute} from "../annotations"; import {AttributesMetadata} from "../metadata/AttributesMetadata"; export abstract class AbstractEntity<T> { @attribute() readonly id?:string; constructor(params:Partial<T> = {}) { if (isPresent((params as any).id)) { throw new Error("Params object passed to constructor cannot contain id property!") } let attributesMetadata = AttributesMetadata.getForInstance(this); Object.keys(params).forEach(propertyName => { if (!attributesMetadata.isAttributeDefined(propertyName)) { console.warn(`${this.constructor.name} will be initialized with unknown param: ${propertyName}`) } this[propertyName] = params[propertyName as any]; }); } isPersisted():boolean { return isPresent(this.id); } }
Add assertion for id property
Add assertion for id property
TypeScript
mit
robak86/neography
--- +++ @@ -3,11 +3,14 @@ import {AttributesMetadata} from "../metadata/AttributesMetadata"; export abstract class AbstractEntity<T> { - @attribute() id?:string; + @attribute() readonly id?:string; constructor(params:Partial<T> = {}) { + if (isPresent((params as any).id)) { + throw new Error("Params object passed to constructor cannot contain id property!") + } + let attributesMetadata = AttributesMetadata.getForInstance(this); - Object.keys(params).forEach(propertyName => { if (!attributesMetadata.isAttributeDefined(propertyName)) { console.warn(`${this.constructor.name} will be initialized with unknown param: ${propertyName}`)
62015fbd40cc15e8da471951854b79a525faf722
src/Calque/test/workspace-tests.ts
src/Calque/test/workspace-tests.ts
import Workspace = require('../core/Workspace'); describe("Workspace", () => { context("input = 1\r\n\2", () => { it("should split to 2 lines", () => { var workspace = new Workspace(); workspace.input("1\r\n\2"); chai.assert.equal(workspace.lines.length, 2); }); }); });
import Workspace = require('../core/Workspace'); describe("Workspace", () => { context("1; 2", () => { it("should split to 2 lines", () => { var workspace = new Workspace(); workspace.input("1 \n 2"); chai.assert.equal(workspace.lines.length, 2); }); }); context("sqrt(3^2 + 4^2)", () => { it(" = 5", () => { var workspace = new Workspace(); workspace.input("sqrt(3^2 + 4^2)"); chai.assert.equal(workspace.expressions[0].result, '5'); }); }); context("a=1; a+1", () => { it(" = 2", () => { var workspace = new Workspace(); workspace.input("a=1 \n a+1"); chai.assert.equal(workspace.expressions[1].result, '2'); }); }); context("a=1; b=a+1; last+1", () => { it(" = 4", () => { var workspace = new Workspace(); workspace.input("a=1 \n b=a+1 \n last+2"); chai.assert.equal(workspace.expressions[2].result, '4'); }); }); context("a = 2 * 2 +2 # And this", () => { it(" = 6", () => { var workspace = new Workspace(); workspace.input("a = 2 * 2 + 2 # And this = 6"); chai.assert.equal(workspace.expressions[0].result, '6'); }); }); context("pow2(x) = x ^ 2; pow2(6)", () => { it(" = 36", () => { var workspace = new Workspace(); workspace.input("pow2(x) = x ^ 2 \n pow2(6)"); chai.assert.equal(workspace.expressions[1].result, '36'); }); }); context("input a=1;a+1", () => { it("should generate file: a=1 = 1; a+1 = 2", () => { var workspace = new Workspace(); workspace.input("a=1 \n a+1"); chai.assert.equal(workspace.generateText(), 'a=1 = 1\r\n a+1 = 2\r\n'); }); }); });
Cover all help examples with workspace tests
Cover all help examples with workspace tests
TypeScript
mit
arthot/calque,arthot/calque,arthot/calque
--- +++ @@ -1,12 +1,59 @@ import Workspace = require('../core/Workspace'); describe("Workspace", () => { - context("input = 1\r\n\2", () => { + context("1; 2", () => { it("should split to 2 lines", () => { var workspace = new Workspace(); - workspace.input("1\r\n\2"); - + workspace.input("1 \n 2"); chai.assert.equal(workspace.lines.length, 2); }); }); + + context("sqrt(3^2 + 4^2)", () => { + it(" = 5", () => { + var workspace = new Workspace(); + workspace.input("sqrt(3^2 + 4^2)"); + chai.assert.equal(workspace.expressions[0].result, '5'); + }); + }); + + context("a=1; a+1", () => { + it(" = 2", () => { + var workspace = new Workspace(); + workspace.input("a=1 \n a+1"); + chai.assert.equal(workspace.expressions[1].result, '2'); + }); + }); + + context("a=1; b=a+1; last+1", () => { + it(" = 4", () => { + var workspace = new Workspace(); + workspace.input("a=1 \n b=a+1 \n last+2"); + chai.assert.equal(workspace.expressions[2].result, '4'); + }); + }); + + context("a = 2 * 2 +2 # And this", () => { + it(" = 6", () => { + var workspace = new Workspace(); + workspace.input("a = 2 * 2 + 2 # And this = 6"); + chai.assert.equal(workspace.expressions[0].result, '6'); + }); + }); + + context("pow2(x) = x ^ 2; pow2(6)", () => { + it(" = 36", () => { + var workspace = new Workspace(); + workspace.input("pow2(x) = x ^ 2 \n pow2(6)"); + chai.assert.equal(workspace.expressions[1].result, '36'); + }); + }); + + context("input a=1;a+1", () => { + it("should generate file: a=1 = 1; a+1 = 2", () => { + var workspace = new Workspace(); + workspace.input("a=1 \n a+1"); + chai.assert.equal(workspace.generateText(), 'a=1 = 1\r\n a+1 = 2\r\n'); + }); + }); });
9e8ac7765160161b02eb9a97d6fc66edec508aba
lib/commands/list-platforms.ts
lib/commands/list-platforms.ts
///<reference path="../.d.ts"/> import helpers = require("./../common/helpers"); import util = require("util") export class ListPlatformsCommand implements ICommand { constructor(private $platformService: IPlatformService, private $logger: ILogger) { } execute(args: string[]): IFuture<void> { return (() => { var availablePlatforms = this.$platformService.getAvailablePlatforms().wait(); this.$logger.out("Available platforms: %s", helpers.formatListOfNames(availablePlatforms)); var message = "No installed platforms found."; var installedPlatforms = this.$platformService.getInstalledPlatforms().wait(); if (installedPlatforms.length > 0){ message = util.format("Installed platforms: %s", helpers.formatListOfNames(installedPlatforms)); } this.$logger.out(message); }).future<void>()(); } } $injector.registerCommand("platform|*list", ListPlatformsCommand);
///<reference path="../.d.ts"/> import helpers = require("./../common/helpers"); import util = require("util") export class ListPlatformsCommand implements ICommand { constructor(private $platformService: IPlatformService, private $logger: ILogger) { } execute(args: string[]): IFuture<void> { return (() => { var availablePlatforms = this.$platformService.getAvailablePlatforms().wait(); if(availablePlatforms.length > 0) { this.$logger.out("Available platforms: %s", helpers.formatListOfNames(availablePlatforms)); } else { this.$logger.out("No available platforms found."); } var message = "No installed platforms found."; var installedPlatforms = this.$platformService.getInstalledPlatforms().wait(); if (installedPlatforms.length > 0){ message = util.format("Installed platforms: %s", helpers.formatListOfNames(installedPlatforms)); } this.$logger.out(message); }).future<void>()(); } } $injector.registerCommand("platform|*list", ListPlatformsCommand);
Fix message from platform list command
Fix message from platform list command
TypeScript
apache-2.0
tsvetie/nativescript-cli,NathanaelA/nativescript-cli,tsvetie/nativescript-cli,jbristowe/nativescript-cli,NativeScript/nativescript-cli,NathanaelA/nativescript-cli,lokilandon/nativescript-cli,e2l3n/nativescript-cli,lokilandon/nativescript-cli,NativeScript/nativescript-cli,NathanaelA/nativescript-cli,e2l3n/nativescript-cli,jbristowe/nativescript-cli,tsvetie/nativescript-cli,NathanaelA/nativescript-cli,e2l3n/nativescript-cli,NativeScript/nativescript-cli,NativeScript/nativescript-cli,tsvetie/nativescript-cli,jbristowe/nativescript-cli,lokilandon/nativescript-cli,tsvetie/nativescript-cli
--- +++ @@ -9,7 +9,11 @@ execute(args: string[]): IFuture<void> { return (() => { var availablePlatforms = this.$platformService.getAvailablePlatforms().wait(); - this.$logger.out("Available platforms: %s", helpers.formatListOfNames(availablePlatforms)); + if(availablePlatforms.length > 0) { + this.$logger.out("Available platforms: %s", helpers.formatListOfNames(availablePlatforms)); + } else { + this.$logger.out("No available platforms found."); + } var message = "No installed platforms found."; var installedPlatforms = this.$platformService.getInstalledPlatforms().wait();
abb229e91b83c06799d2f51200ff364afdc989b3
tests/cases/fourslash/unusedImports14FS.ts
tests/cases/fourslash/unusedImports14FS.ts
/// <reference path='fourslash.ts' /> // @noUnusedLocals: true // @Filename: file2.ts //// [| import /* 1 */ A /* 2 */, /* 3 */ { x } from './a'; |] //// console.log(A); // @Filename: file1.ts //// export default 10; //// export var x = 10; verify.rangeAfterCodeFix("import /* 1 */ A /* 2 */ from './a';");
/// <reference path='fourslash.ts' /> // @noUnusedLocals: true // @Filename: file2.ts //// [| import /* 1 */ A /* 2 */, /* 3 */ { /* 4 */ x /* 5 */ } /* 6 */ from './a'; |] //// console.log(A); // @Filename: file1.ts //// export default 10; //// export var x = 10; // It's ambiguous which token comment /* 6 */ applies to or whether it should be removed. // In the current implementation the comment is left behind, but this behavior isn't a requirement. verify.rangeAfterCodeFix("import /* 1 */ A /* 2 */ /* 6 */ from './a';");
Add a bit more validation around comments
Add a bit more validation around comments
TypeScript
apache-2.0
SaschaNaz/TypeScript,TukekeSoft/TypeScript,weswigham/TypeScript,basarat/TypeScript,TukekeSoft/TypeScript,chuckjaz/TypeScript,RyanCavanaugh/TypeScript,Eyas/TypeScript,kpreisser/TypeScript,Eyas/TypeScript,donaldpipowitch/TypeScript,microsoft/TypeScript,Eyas/TypeScript,donaldpipowitch/TypeScript,weswigham/TypeScript,microsoft/TypeScript,weswigham/TypeScript,Microsoft/TypeScript,Microsoft/TypeScript,RyanCavanaugh/TypeScript,chuckjaz/TypeScript,microsoft/TypeScript,basarat/TypeScript,kpreisser/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,chuckjaz/TypeScript,alexeagle/TypeScript,alexeagle/TypeScript,kitsonk/TypeScript,Eyas/TypeScript,minestarks/TypeScript,synaptek/TypeScript,synaptek/TypeScript,nojvek/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,basarat/TypeScript,nojvek/TypeScript,synaptek/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,TukekeSoft/TypeScript,kpreisser/TypeScript,Microsoft/TypeScript,chuckjaz/TypeScript,synaptek/TypeScript
--- +++ @@ -2,11 +2,14 @@ // @noUnusedLocals: true // @Filename: file2.ts -//// [| import /* 1 */ A /* 2 */, /* 3 */ { x } from './a'; |] +//// [| import /* 1 */ A /* 2 */, /* 3 */ { /* 4 */ x /* 5 */ } /* 6 */ from './a'; |] //// console.log(A); // @Filename: file1.ts //// export default 10; //// export var x = 10; -verify.rangeAfterCodeFix("import /* 1 */ A /* 2 */ from './a';"); + +// It's ambiguous which token comment /* 6 */ applies to or whether it should be removed. +// In the current implementation the comment is left behind, but this behavior isn't a requirement. +verify.rangeAfterCodeFix("import /* 1 */ A /* 2 */ /* 6 */ from './a';");
3be0c86dc8dedb49a055b04b8dd6fbe329ba5ba3
src/polyfills.ts
src/polyfills.ts
// This file includes polyfills needed by Angular 2 and is loaded before // the app. You can add your own extra polyfills to this file. import 'core-js/es6/symbol'; import 'core-js/es6/object'; import 'core-js/es6/function'; import 'core-js/es6/parse-int'; import 'core-js/es6/parse-float'; import 'core-js/es6/number'; import 'core-js/es6/math'; import 'core-js/es6/string'; import 'core-js/es6/date'; import 'core-js/es6/array'; import 'core-js/es6/regexp'; import 'core-js/es6/map'; import 'core-js/es6/set'; import 'core-js/es6/reflect'; import 'core-js/es7/reflect'; import 'zone.js/dist/zone'; // Proxy stub if (!('Proxy' in window)) { window['Proxy'] = {}; }
// This file includes polyfills needed by Angular 2 and is loaded before // the app. You can add your own extra polyfills to this file. import 'core-js/es6/symbol'; import 'core-js/es6/object'; import 'core-js/es6/function'; import 'core-js/es6/parse-int'; import 'core-js/es6/parse-float'; import 'core-js/es6/number'; import 'core-js/es6/math'; import 'core-js/es6/string'; import 'core-js/es6/date'; import 'core-js/es6/array'; import 'core-js/es6/regexp'; import 'core-js/es6/map'; import 'core-js/es6/set'; import 'core-js/es6/reflect'; import 'core-js/es7/reflect'; import 'zone.js/dist/zone';
Remove Proxy stub from build
test(proxy): Remove Proxy stub from build
TypeScript
mit
gund/ng-http-interceptor,gund/ng2-http-interceptor,gund/ng-http-interceptor,gund/ng2-http-interceptor,gund/ng-http-interceptor,gund/ng2-http-interceptor
--- +++ @@ -17,8 +17,3 @@ import 'core-js/es7/reflect'; import 'zone.js/dist/zone'; - -// Proxy stub -if (!('Proxy' in window)) { - window['Proxy'] = {}; -}
a4d573e816813280cf37b6b984bd2dd782c2e84d
modules/statics/src/index.ts
modules/statics/src/index.ts
export * from './base'; export * from './coins'; export * from './networks'; export * from './errors'; export * from './tokenConfig'; export { OfcCoin } from './ofc'; export { UtxoCoin } from './utxo'; export { AccountCoin, CeloCoin, ContractAddressDefinedToken, Erc20Coin, StellarCoin, EosCoin, AlgoCoin, AvaxERC20Token, SolCoin, HederaToken, AcaCoin, } from './account'; export { CoinMap } from './map';
export * from './base'; export * from './coins'; export * from './networks'; export * from './errors'; export * from './tokenConfig'; export { OfcCoin } from './ofc'; export { UtxoCoin } from './utxo'; export { AccountCoin, CeloCoin, ContractAddressDefinedToken, Erc20Coin, StellarCoin, EosCoin, AlgoCoin, AvaxERC20Token, SolCoin, HederaToken, } from './account'; export { CoinMap } from './map';
Revert "chore: export AcaCoin in statics"
Revert "chore: export AcaCoin in statics" This reverts commit 3cde22595192feddaa1bda7994c2886d5a7f7965.
TypeScript
apache-2.0
BitGo/BitGoJS,BitGo/BitGoJS,BitGo/BitGoJS,BitGo/BitGoJS
--- +++ @@ -16,6 +16,5 @@ AvaxERC20Token, SolCoin, HederaToken, - AcaCoin, } from './account'; export { CoinMap } from './map';
7ef9406a3024dc17e43ae4391b75a90b3c4dccab
client/src/constants/paginate.ts
client/src/constants/paginate.ts
export const PAGE_SIZE = 30; export function getOffset(page?: number): number | null { if (page == null || page <= 1) { return null; } return (page - 1) * PAGE_SIZE; } export function paginate(count: number): boolean { return count > PAGE_SIZE; } export function getNumPages(count: number): number { return Math.ceil(count / PAGE_SIZE); } export function paginateNext(currentPage: number, count: number): boolean { return currentPage < getNumPages(count); } export function paginatePrevious(currentPage: number): boolean { return currentPage > 1; } export function getPaginatedSlice(list: Array<any>, currentPage: number): Array<any> { let start = getOffset(currentPage) || 0; let end = start + PAGE_SIZE; return list.slice(start, end); }
import * as queryString from 'query-string'; export const PAGE_SIZE = 30; export function getOffset(page?: number): number | null { if (page == null || page <= 1) { return null; } return (page - 1) * PAGE_SIZE; } export function paginate(count: number): boolean { return count > PAGE_SIZE; } export function getNumPages(count: number): number { return Math.ceil(count / PAGE_SIZE); } export function paginateNext(currentPage: number, count: number): boolean { return currentPage < getNumPages(count); } export function paginatePrevious(currentPage: number): boolean { return currentPage > 1; } export function getPaginatedSlice(list: Array<any>): Array<any> { let pieces = location.href.split('?'); let offset = null; if (pieces.length > 1) { let search = queryString.parse(pieces[1]); offset = search.offset ? parseInt(search.offset, 10) : null; } let start = offset || 0; let end = start + PAGE_SIZE; return list.slice(start, end); }
Update pagination slice to use directly the query params for detecting the offset
Update pagination slice to use directly the query params for detecting the offset
TypeScript
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
--- +++ @@ -1,3 +1,5 @@ +import * as queryString from 'query-string'; + export const PAGE_SIZE = 30; export function getOffset(page?: number): number | null { @@ -23,8 +25,14 @@ return currentPage > 1; } -export function getPaginatedSlice(list: Array<any>, currentPage: number): Array<any> { - let start = getOffset(currentPage) || 0; +export function getPaginatedSlice(list: Array<any>): Array<any> { + let pieces = location.href.split('?'); + let offset = null; + if (pieces.length > 1) { + let search = queryString.parse(pieces[1]); + offset = search.offset ? parseInt(search.offset, 10) : null; + } + let start = offset || 0; let end = start + PAGE_SIZE; return list.slice(start, end); }
6c5336c41658381788ef0269a168eaa6e5cd6f8c
src/index.ts
src/index.ts
import { SandboxParameter } from './interfaces'; import nativeAddon from './nativeAddon'; import { SandboxProcess } from './sandboxProcess'; import { existsSync } from 'fs'; if (!existsSync('/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes')) { throw new Error("Your linux kernel doesn't support memory-swap account. To turn it on, add `cgroup_enable=memory swapaccount=1` to GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub and run `sudo update-grub`"); } const startSandbox = function (parameter: SandboxParameter) { return new Promise((res, rej) => { nativeAddon.StartChild(parameter, function (err, result) { if (err) rej(err); else res(new SandboxProcess(result.pid, parameter)); }); }); }; export { startSandbox };
import { SandboxParameter } from './interfaces'; import nativeAddon from './nativeAddon'; import { SandboxProcess } from './sandboxProcess'; import { existsSync } from 'fs'; if (!existsSync('/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes')) { throw new Error("Your linux kernel doesn't support memory-swap account. Please turn it on following the readme."); } const startSandbox = function (parameter: SandboxParameter) { return new Promise((res, rej) => { nativeAddon.StartChild(parameter, function (err, result) { if (err) rej(err); else res(new SandboxProcess(result.pid, parameter)); }); }); }; export { startSandbox };
Change the error message when the memsw is disabled.
Change the error message when the memsw is disabled.
TypeScript
mit
t123yh/simple-sandbox,t123yh/simple-sandbox
--- +++ @@ -4,7 +4,7 @@ import { existsSync } from 'fs'; if (!existsSync('/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes')) { - throw new Error("Your linux kernel doesn't support memory-swap account. To turn it on, add `cgroup_enable=memory swapaccount=1` to GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub and run `sudo update-grub`"); + throw new Error("Your linux kernel doesn't support memory-swap account. Please turn it on following the readme."); } const startSandbox = function (parameter: SandboxParameter) {
080e8bc364b06ea86f51711cccecf503a46628d3
tests/api.spec.ts
tests/api.spec.ts
import skift from '../src/index'; import { SplitTest } from '../src/splittest'; describe('Top-level api', () => { it('should export the object', () => { expect(typeof skift).toBe('object'); expect(skift).toBeDefined(); }); it('should be impossible to create an empty test', () => { expect(() => skift.create('Awesome test!').setup()).toThrowError(); expect(skift.getTest('Awesome test!')).toBeDefined(); expect(skift.getTest('Awesome test!') instanceof SplitTest).toBe(true); }); it('should be possible to get a variation', () => { const test = skift .create('Another test!') .addVariation({ name: 'Variation A' }); expect(test.getVariation('Variation A')).toBeDefined(); }); it('should be possible to setup a test with two variations and retrieve it by name', () => { const test = skift .create('Another awesome test!') .addVariation({ name: 'Variation C' }) .addVariation({ name: 'Variation D' }); expect(test.setup()).toBe(true); expect(skift.getTest('Another awesome test!')).toBeDefined(); expect(test === skift.getTest('Another awesome test!')).toBeTruthy(); }); });
import skift from '../src/index'; import { SplitTest } from '../src/splittest'; describe('Top-level api', () => { it('should export the object', () => { expect(typeof skift).toBe('object'); expect(skift).toBeDefined(); }); it('should be impossible to create an empty test', () => { expect(() => skift.create('Awesome test!').setup()).toThrowError(); expect(skift.getTest('Awesome test!')).toBeDefined(); expect(skift.getTest('Awesome test!') instanceof SplitTest).toBe(true); }); it('should be possible to get a variation', () => { const test = skift .create('Another test!') .addVariation({ name: 'Variation A' }); expect(test.getVariation('Variation A')).toBeDefined(); }); it('should be possible to setup a test with two variations and retrieve it by name', () => { const test = skift .create('Another awesome test!') .addVariation({ name: 'Variation C' }) .addVariation({ name: 'Variation D' }); expect(test.setup()).toBe(true); expect(skift.getTest('Another awesome test!')).toBeDefined(); expect(test === skift.getTest('Another awesome test!')).toBeTruthy(); }); it('should be possible to show the UI', () => { const testName = 'The test to check out!'; skift .create(testName) .addVariation({ name: 'Variation A' }) .addVariation({ name: 'Variation B' }) .setup(); skift.ui.show([ skift.getTest(testName) ]); const root = document.querySelector('div').shadowRoot; expect(root.querySelector('.skift-ui-container')).toBeDefined(); }); });
Add the test for the UI
Add the test for the UI
TypeScript
mit
trustpilot/skift,trustpilot/skift
--- +++ @@ -32,4 +32,18 @@ expect(skift.getTest('Another awesome test!')).toBeDefined(); expect(test === skift.getTest('Another awesome test!')).toBeTruthy(); }); + + it('should be possible to show the UI', () => { + const testName = 'The test to check out!'; + skift + .create(testName) + .addVariation({ name: 'Variation A' }) + .addVariation({ name: 'Variation B' }) + .setup(); + + skift.ui.show([ skift.getTest(testName) ]); + + const root = document.querySelector('div').shadowRoot; + expect(root.querySelector('.skift-ui-container')).toBeDefined(); + }); });
5eaf2814894e53d7f32d53193989f55d51fe3273
ui/src/tasks/api/v2/index.ts
ui/src/tasks/api/v2/index.ts
import AJAX from 'src/utils/ajax' import {Task} from 'src/types/v2/tasks' export const submitNewTask = async ( url, owner, org, flux: string ): Promise<Task> => { const request = { flux, organizationId: org.id, status: 'active', owner, } const {data} = await AJAX({url, data: request, method: 'POST'}) return data } export const updateTaskFlux = async (url, id, flux: string): Promise<Task> => { const completeUrl = `${url}/${id}` const request = { flux, } const {data} = await AJAX({url: completeUrl, data: request, method: 'PATCH'}) return data } export const getUserTasks = async (url, user): Promise<Task[]> => { const completeUrl = `${url}?user=${user.id}` const {data} = await AJAX({url: completeUrl}) return data } export const getTask = async (url, id): Promise<Task> => { const completeUrl = `${url}/${id}` const {data} = await AJAX({url: completeUrl}) return data } export const deleteTask = (url: string, taskID: string) => { const completeUrl = `${url}/${taskID}` return AJAX({url: completeUrl, method: 'DELETE'}) }
import AJAX from 'src/utils/ajax' import {Task} from 'src/types/v2/tasks' export const submitNewTask = async ( url, owner, org, flux: string ): Promise<Task> => { const request = { flux, organizationId: org.id, status: 'active', owner, } const {data} = await AJAX({url, data: request, method: 'POST'}) return data } export const updateTaskFlux = async (url, id, flux: string): Promise<Task> => { const completeUrl = `${url}/${id}` const request = { flux, } const {data} = await AJAX({url: completeUrl, data: request, method: 'PATCH'}) return data } export const getUserTasks = async (url, user): Promise<Task[]> => { const completeUrl = `${url}?user=${user.id}` const { data: {tasks}, } = await AJAX({url: completeUrl}) return tasks } export const getTask = async (url, id): Promise<Task> => { const completeUrl = `${url}/${id}` const { data: {task}, } = await AJAX({url: completeUrl}) return task } export const deleteTask = (url: string, taskID: string) => { const completeUrl = `${url}/${taskID}` return AJAX({url: completeUrl, method: 'DELETE'}) }
Fix api calls for tasks, tasks are now nested in response
Fix api calls for tasks, tasks are now nested in response
TypeScript
mit
influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdata/influxdb
--- +++ @@ -33,16 +33,20 @@ export const getUserTasks = async (url, user): Promise<Task[]> => { const completeUrl = `${url}?user=${user.id}` - const {data} = await AJAX({url: completeUrl}) + const { + data: {tasks}, + } = await AJAX({url: completeUrl}) - return data + return tasks } export const getTask = async (url, id): Promise<Task> => { const completeUrl = `${url}/${id}` - const {data} = await AJAX({url: completeUrl}) + const { + data: {task}, + } = await AJAX({url: completeUrl}) - return data + return task } export const deleteTask = (url: string, taskID: string) => {
04599bb207195ad126a51124d87a597825a3fa73
app/src/lib/stores/updates/update-remote-url.ts
app/src/lib/stores/updates/update-remote-url.ts
import { Repository } from '../../../models/repository' import { IAPIRepository } from '../../api' import { GitStore } from '../git-store' export const updateRemoteUrl = async ( gitStore: GitStore, repository: Repository, apiRepo: IAPIRepository ): Promise<void> => { // I'm not sure when these early exit conditions would be met. But when they are // we don't have enough information to continue so exit early! if (!gitStore.currentRemote) { return } if (!repository.gitHubRepository) { return } const remoteUrl = gitStore.currentRemote.url const updatedRemoteUrl = apiRepo.clone_url const isProtocolHttps = remoteUrl && remoteUrl.startsWith('https://') const usingDefaultRemote = gitStore.defaultRemote && gitStore.defaultRemote.url === repository.gitHubRepository.cloneURL if (isProtocolHttps && usingDefaultRemote && remoteUrl !== updatedRemoteUrl) { await gitStore.setRemoteURL(gitStore.currentRemote.name, updatedRemoteUrl) } }
import { Repository } from '../../../models/repository' import { IAPIRepository } from '../../api' import { GitStore } from '../git-store' export async function updateRemoteUrl( gitStore: GitStore, repository: Repository, apiRepo: IAPIRepository ): Promise<void> { // I'm not sure when these early exit conditions would be met. But when they are // we don't have enough information to continue so exit early! if (!gitStore.currentRemote) { return } if (!repository.gitHubRepository) { return } const remoteUrl = gitStore.currentRemote.url const updatedRemoteUrl = apiRepo.clone_url const isProtocolHttps = remoteUrl && remoteUrl.startsWith('https://') const usingDefaultRemote = gitStore.defaultRemote && gitStore.defaultRemote.url === repository.gitHubRepository.cloneURL if (isProtocolHttps && usingDefaultRemote && remoteUrl !== updatedRemoteUrl) { await gitStore.setRemoteURL(gitStore.currentRemote.name, updatedRemoteUrl) } }
Use the export function-style rather than export const
Use the export function-style rather than export const Co-Authored-By: Markus Olsson <c00736d1ddeb2cd1f4e803cdc39630b5b2784893@users.noreply.github.com>
TypeScript
mit
j-f1/forked-desktop,j-f1/forked-desktop,shiftkey/desktop,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,shiftkey/desktop,say25/desktop,desktop/desktop,desktop/desktop,kactus-io/kactus,artivilla/desktop,kactus-io/kactus,desktop/desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,say25/desktop
--- +++ @@ -2,11 +2,11 @@ import { IAPIRepository } from '../../api' import { GitStore } from '../git-store' -export const updateRemoteUrl = async ( +export async function updateRemoteUrl( gitStore: GitStore, repository: Repository, apiRepo: IAPIRepository -): Promise<void> => { +): Promise<void> { // I'm not sure when these early exit conditions would be met. But when they are // we don't have enough information to continue so exit early! if (!gitStore.currentRemote) {