Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use mock server to retrieve a project
import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Group, Project } from '../+models'; import { ApiService, AuthenticationService } from './'; @Injectable() export class ProjectsService { private projectsUrl = ApiService.baseUrl + '/projects'; constructor(private $http: Http) {} getProjectList(): Promise<Group[]> { let headers = new Headers({ 'Authorization': AuthenticationService.getToken() }); let options = new RequestOptions({ headers: headers }); return this.$http .get(this.projectsUrl, options) .toPromise() .then((response: Response) => response.json() as Group[]) .catch(error => Promise.reject(error)); } getProject(owner: string, repo: string): Promise<Project> { return this.getProjectList() .then((projectList: Group[]) => { let group = projectList.find(function(project: Group) { return project.user.pseudo === owner; }); let projects = group.projects; return projects.find(function(project: Project) { return project.name === repo; }); }) } }
import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Group, Project } from '../+models'; import { ApiService, AuthenticationService } from './'; @Injectable() export class ProjectsService { private all = () => `${ApiService.baseUrl}/projects`; private one = (owner: string, repo: string) => `${ApiService.baseUrl}/projects/${owner}/${repo}`; constructor(private $http: Http) {} getProjectList(): Promise<Group[]> { let headers = new Headers({ 'Authorization': AuthenticationService.getToken() }); let options = new RequestOptions({ headers: headers }); return this.$http .get(this.all(), options) .toPromise() .then((response: Response) => response.json() as Group[]) .catch(error => Promise.reject(error)); } getProject(owner: string, repo: string): Promise<Project> { let headers = new Headers({ 'Authorization': AuthenticationService.getToken() }); let options = new RequestOptions({ headers: headers }); return this.$http .get(this.one(owner, repo), options) .toPromise() .then((response: Response) => response.json() as Project) .catch(error => Promise.reject(error)); } }
Remove rxjs from media queries
import store from '../store/store'; import { setPhonePortrait } from '../shell/actions'; import { Observable, defer, fromEventPattern, asapScheduler } from 'rxjs'; import { map, startWith, subscribeOn } from 'rxjs/operators'; // This seems like a good breakpoint for portrait based on https://material.io/devices/ // We can't use orientation:portrait because Android Chrome messes up when the keyboard is shown: https://www.chromestatus.com/feature/5656077370654720 const phoneWidthQuery = window.matchMedia('(max-width: 540px)'); /** * Return whether we're in phone-portrait mode right now. */ export function isPhonePortraitFromMediaQuery() { return phoneWidthQuery.matches; } /** * Return an observable sequence of phone-portrait statuses. */ function isPhonePortraitStream(): Observable<boolean> { return defer(() => fromEventPattern<MediaQueryList>( (h: (this: MediaQueryList, ev: MediaQueryListEvent) => any) => phoneWidthQuery.addListener(h), (h: (this: MediaQueryList, ev: MediaQueryListEvent) => any) => phoneWidthQuery.removeListener(h) ).pipe( map((e: MediaQueryList) => e.matches), startWith(phoneWidthQuery.matches), subscribeOn(asapScheduler) ) ); } isPhonePortraitStream().subscribe((isPhonePortrait) => store.dispatch(setPhonePortrait(isPhonePortrait)) );
import store from '../store/store'; import { setPhonePortrait } from '../shell/actions'; // This seems like a good breakpoint for portrait based on https://material.io/devices/ // We can't use orientation:portrait because Android Chrome messes up when the keyboard is shown: https://www.chromestatus.com/feature/5656077370654720 const phoneWidthQuery = window.matchMedia('(max-width: 540px)'); phoneWidthQuery.addListener((e) => { store.dispatch(setPhonePortrait(e.matches)); }); /** * Return whether we're in phone-portrait mode right now. */ export function isPhonePortraitFromMediaQuery() { return phoneWidthQuery.matches; }
Disable js/ts features for the private scheme
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export const file = 'file'; export const untitled = 'untitled'; export const git = 'git'; /** Live share scheme */ export const vsls = 'vsls'; export const walkThroughSnippet = 'walkThroughSnippet'; export const semanticSupportedSchemes = [ file, untitled, ]; /** * File scheme for which JS/TS language feature should be disabled */ export const disabledSchemes = new Set([ git, vsls ]);
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export const file = 'file'; export const untitled = 'untitled'; export const git = 'git'; export const privateScheme = 'private'; /** Live share scheme */ export const vsls = 'vsls'; export const walkThroughSnippet = 'walkThroughSnippet'; export const semanticSupportedSchemes = [ file, untitled, ]; /** * File scheme for which JS/TS language feature should be disabled */ export const disabledSchemes = new Set([ git, vsls, privateScheme, ]);
Use Object.assign instead of _.clone.
import * as e from "./Enums"; import * as _ from "lodash"; import {memoize} from "./Decorators"; import {Attributes} from "./Interfaces"; export const attributesFlyweight = _.memoize( (attributes: Attributes): Attributes => _.clone(attributes), (attributes: Dictionary<any>) => { const ordered: Dictionary<any> = {}; Object.keys(attributes).sort().forEach(key => ordered[key] = attributes[key]); return JSON.stringify(ordered); } ); export default class Char { static empty = Char.flyweight(" ", {}); @memoize() static flyweight(char: string, attributes: Attributes) { return new Char(char, attributesFlyweight(attributes)); } constructor(private char: string, private _attributes: Attributes) { if (char.length !== 1) { throw(`Char can be created only from a single character; passed ${char.length}: ${char}`); } } getCharCode(): e.KeyCode { return (<any>e.KeyCode)[e.KeyCode[this.char.charCodeAt(0)]]; } get attributes(): Attributes { return this._attributes; } toString(): string { return this.char; } isSpecial(): boolean { // http://www.asciitable.com/index/asciifull.gif const charCode = this.char.charCodeAt(0); return charCode < 32; } }
import * as e from "./Enums"; import * as _ from "lodash"; import {memoize} from "./Decorators"; import {Attributes} from "./Interfaces"; export const attributesFlyweight = _.memoize( (attributes: Attributes): Attributes => Object.assign({}, attributes), (attributes: Dictionary<any>) => { const ordered: Dictionary<any> = {}; Object.keys(attributes).sort().forEach(key => ordered[key] = attributes[key]); return JSON.stringify(ordered); } ); export default class Char { static empty = Char.flyweight(" ", {}); @memoize() static flyweight(char: string, attributes: Attributes) { return new Char(char, attributesFlyweight(attributes)); } constructor(private char: string, private _attributes: Attributes) { if (char.length !== 1) { throw(`Char can be created only from a single character; passed ${char.length}: ${char}`); } } getCharCode(): e.KeyCode { return (<any>e.KeyCode)[e.KeyCode[this.char.charCodeAt(0)]]; } get attributes(): Attributes { return this._attributes; } toString(): string { return this.char; } isSpecial(): boolean { // http://www.asciitable.com/index/asciifull.gif const charCode = this.char.charCodeAt(0); return charCode < 32; } }
Fix openerTabId warning on Android
import TabPresenter from '../presenters/TabPresenter'; export default class LinkUseCase { private tabPresenter: TabPresenter; constructor() { this.tabPresenter = new TabPresenter(); } openToTab(url: string, tabId: number): Promise<any> { return this.tabPresenter.open(url, tabId); } openNewTab(url: string, openerId: number, background: boolean): Promise<any> { return this.tabPresenter.create(url, { openerTabId: openerId, active: !background }); } }
import TabPresenter from '../presenters/TabPresenter'; export default class LinkUseCase { private tabPresenter: TabPresenter; constructor() { this.tabPresenter = new TabPresenter(); } openToTab(url: string, tabId: number): Promise<any> { return this.tabPresenter.open(url, tabId); } openNewTab(url: string, openerId: number, background: boolean): Promise<any> { // openerTabId not supported on Android let properties = typeof browser.tabs.Tab === "object" ? { openerTabId: openerId, active: !background } : { active: !background }; return this.tabPresenter.create(url, properties); } }
Make security service contract's loginWithCredentionals of ts client sync with its default implementation
module Bit.Contracts { export interface Token { access_token: string; expires_in: number; token_type: string; login_date: Date; } export interface ISecurityService { isLoggedIn(): boolean; login(state?: any): void; logout(): void; loginWithCredentials(username: string, password: string, client_id: string, client_secret: string, scopes: string[], saveToken: boolean): Promise<Token>; getCurrentToken(): Token; } }
module Bit.Contracts { export interface Token { access_token: string; expires_in: number; token_type: string; login_date: Date; } export interface ISecurityService { isLoggedIn(): boolean; login(state?: any): void; logout(): void; loginWithCredentials(username: string, password: string, client_id: string, client_secret: string, scopes?: string[], saveToken?: boolean): Promise<Token>; getCurrentToken(): Token; } }
Change key size from 1538 bits to 2048 bits
// 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. import * as forge from 'node-forge'; // Keys are in OpenSSH format export class KeyPair { public: string; private: string; } // Generates an RSA keypair using forge export function generateKeyPair(): KeyPair { const pair = forge.pki.rsa.generateKeyPair({bits: 1538}); // trim() the string because forge adds a trailing space to // public keys which really messes things up later. return { public: forge.ssh.publicKeyToOpenSSH(pair.publicKey, '').trim(), private: forge.ssh.privateKeyToOpenSSH(pair.privateKey, '').trim() }; }
// 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. import * as forge from 'node-forge'; // Keys are in OpenSSH format export class KeyPair { public: string; private: string; } // Generates an RSA keypair using forge export function generateKeyPair(): KeyPair { const pair = forge.pki.rsa.generateKeyPair({bits: 2048}); // trim() the string because forge adds a trailing space to // public keys which really messes things up later. return { public: forge.ssh.publicKeyToOpenSSH(pair.publicKey, '').trim(), private: forge.ssh.privateKeyToOpenSSH(pair.privateKey, '').trim() }; }
Disable save button when saving is happening in the background
import { Component, OnInit } from '@angular/core'; import {ChapterService} from "../chapter.service"; import {ActivatedRoute, Router} from "@angular/router"; import {Chapter} from "../../models/chapter"; @Component({ selector: 'wn-write', templateUrl: './write.component.html', styleUrls: ['./write.component.css'] }) export class WriteComponent implements OnInit { parentChapter: Chapter; newChapter:Chapter = new Chapter(); loaded:boolean = false; constructor(private _chapterService:ChapterService, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.route.params.subscribe(params =>{ let parentId = params['parentChapter']; if(parentId){ this._chapterService.getChapter(parentId).subscribe(chapter =>{ this.parentChapter = chapter; this.newChapter.parent = this.parentChapter._id; this.newChapter.book = this.parentChapter.book; this.loaded = true; }) } }) } saveChapter(){ this.newChapter.author='59c3995ddd8415653e5ebc87';//TODO Create userservice to get current user this._chapterService.saveChapter(this.newChapter).subscribe((chapterId)=>{ this.parentChapter.childrenIds.push(chapterId); this._chapterService.updateChapter(this.parentChapter).subscribe((response)=>{ this.router.navigate(['read', chapterId]); }); }) } }
import { Component, OnInit } from '@angular/core'; import {ChapterService} from "../chapter.service"; import {ActivatedRoute, Router} from "@angular/router"; import {Chapter} from "../../models/chapter"; @Component({ selector: 'wn-write', templateUrl: './write.component.html', styleUrls: ['./write.component.css'] }) export class WriteComponent implements OnInit { parentChapter: Chapter; newChapter:Chapter = new Chapter(); loaded:boolean = false; constructor(private _chapterService:ChapterService, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.route.params.subscribe(params =>{ let parentId = params['parentChapter']; if(parentId){ this._chapterService.getChapter(parentId).subscribe(chapter =>{ this.parentChapter = chapter; this.newChapter.parent = this.parentChapter._id; this.newChapter.book = this.parentChapter.book; this.loaded = true; }) } }) } saveChapter(){ this.loaded = false; this.newChapter.author='59c3995ddd8415653e5ebc87';//TODO Create userservice to get current user this._chapterService.saveChapter(this.newChapter).subscribe((chapterId)=>{ this.parentChapter.childrenIds.push(chapterId); this._chapterService.updateChapter(this.parentChapter).subscribe((response)=>{ this.loaded = true; this.router.navigate(['read', chapterId]); }); }) } }
Check that tests for comments in tsconfig tests extended files
import { } from 'jest'; import { } from 'node'; import * as ts from 'typescript'; import * as fs from 'fs'; jest.mock('path'); describe('parse tsconfig with comments', () => { const configFile1 = './tests/tsconfig-test/allows-comments.json'; const configFile2 = './tests/tsconfig-test/allows-comments2.json'; beforeEach(() => { // Set up some mocked out file info before each test require('path').__setBaseDir('./tests/tsconfig-test'); }); it('the two config files should exist', () => { expect(fs.existsSync(configFile1)).toBe(true); expect(fs.existsSync(configFile2)).toBe(true); }); it('the two config files should have comments', () => { // We test for comments by trying to use JSON.parse // which should fail. expect(() => { JSON.parse(fs.readFileSync(configFile1, 'utf8')); }).toThrowError(); expect(() => { JSON.parse(fs.readFileSync(configFile2, 'utf8')); }).toThrowError(); }); it('should correctly read allow-comments.json', () => { const { getTSConfig } = require('../../src/utils'); expect(() => { getTSConfig({ '__TS_CONFIG__': 'allows-comments.json' }); }).not.toThrow(); }); });
import { } from 'jest'; import { } from 'node'; import * as ts from 'typescript'; import * as fs from 'fs'; import * as tsconfig from 'tsconfig'; jest.mock('path'); describe('parse tsconfig with comments', () => { const configFile1 = './tests/tsconfig-test/allows-comments.json'; const configFile2 = './tests/tsconfig-test/allows-comments2.json'; beforeEach(() => { // Set up some mocked out file info before each test require('path').__setBaseDir('./tests/tsconfig-test'); }); it('the two config files should exist', () => { expect(fs.existsSync(configFile1)).toBe(true); expect(fs.existsSync(configFile2)).toBe(true); }); it('the two config files should have comments', () => { // We test for comments by trying to use JSON.parse // which should fail. expect(() => { JSON.parse(fs.readFileSync(configFile1, 'utf8')); }).toThrowError(); expect(() => { JSON.parse(fs.readFileSync(configFile2, 'utf8')); }).toThrowError(); }); it('one config file should extend the other', () => { const content = fs.readFileSync(configFile1, 'utf8'); const config = tsconfig.parse(content, configFile1); expect(config.extends).toEqual('allows-comments2.json'); }); it('should correctly read allow-comments.json', () => { const { getTSConfig } = require('../../src/utils'); expect(() => { getTSConfig({ '__TS_CONFIG__': 'allows-comments.json' }); }).not.toThrow(); }); });
Create secure (https) XMLRPC client
import puppeteer from 'puppeteer'; import * as xmlrpc from 'xmlrpc'; import { Bot } from './bot'; import { Doku } from './doku'; import { onExit } from './on_exit'; import { Renderer } from './render'; // Used by our .service initfile to find the bot process. process.title = 'comicsbot'; interface Config { discordToken: string doku: { user: string, password: string, baseUrl: string, }, } (async () => { let config: Config = require('../config/config.json'); const doku = new Doku(xmlrpc.createClient({ url: config.doku.baseUrl + 'lib/exe/xmlrpc.php', cookies: true, })); await doku.login(config.doku.user, config.doku.password); const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'], handleSIGINT: false, handleSIGTERM: false, handleSIGHUP: false, }); onExit(browser.close); const render = new Renderer('../config/render.js', doku, browser, config.doku.baseUrl); const bot = new Bot(render); bot.connect(config.discordToken); onExit(bot.destroy); })();
import puppeteer from 'puppeteer'; import * as xmlrpc from 'xmlrpc'; import { Bot } from './bot'; import { Doku } from './doku'; import { onExit } from './on_exit'; import { Renderer } from './render'; // Used by our .service initfile to find the bot process. process.title = 'comicsbot'; interface Config { discordToken: string doku: { user: string, password: string, baseUrl: string, }, } (async () => { let config: Config = require('../config/config.json'); const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'], handleSIGINT: false, handleSIGTERM: false, handleSIGHUP: false, }); onExit(browser.close); // TODO(dotdoom): createClient vs createSecureClient based on protocol in URL. const doku = new Doku(xmlrpc.createSecureClient({ url: config.doku.baseUrl + 'lib/exe/xmlrpc.php', cookies: true, // headers: { // 'User-Agent': await browser.userAgent(), // }, })); await doku.login(config.doku.user, config.doku.password); const render = new Renderer('../config/render.js', doku, browser, config.doku.baseUrl); const bot = new Bot(render); bot.connect(config.discordToken); onExit(bot.destroy); })();
Add thank-you component to routing
// tslint:disable-next-line:max-line-length import { AudiologistNavigationComponent } from './audiologist-navigation/audiologist-navigation.component'; import { CheckInComponent } from './check-in/check-in.component'; import { Routes } from '@angular/router'; import { HomeComponent } from './home'; import { NoContentComponent } from './no-content'; import { DataResolver } from './app.resolver'; export const ROUTES: Routes = [ { path: '', component: HomeComponent }, { path: 'home', component: HomeComponent }, { path: 'login', component: CheckInComponent}, { path: 'audio-nav', component: AudiologistNavigationComponent}, { path: '**', component: NoContentComponent }, ];
// tslint:disable-next-line:max-line-length import { AudiologistNavigationComponent } from './audiologist-navigation/audiologist-navigation.component'; import { CheckInComponent } from './check-in/check-in.component'; import { Routes } from '@angular/router'; import { HomeComponent } from './home'; import { NoContentComponent } from './no-content'; import { ThankYouComponent } from './thank-you/thank-you.component'; import { DataResolver } from './app.resolver'; export const ROUTES: Routes = [ { path: '', component: HomeComponent }, { path: 'home', component: HomeComponent }, { path: 'login', component: CheckInComponent}, { path: 'audio-nav', component: AudiologistNavigationComponent}, { path: 'thank-you', component: ThankYouComponent}, { path: '**', component: NoContentComponent }, ];
Fix maches matchMedia to render horizontal or vertical menu by adding max-height check also
import React, { ReactElement } from 'react' import { useMatchMedia, useI18n } from 'hooks' import { Header, Title } from 'components/Layout' import Menu, { Item } from 'components/Layout/Menu' import AnimatedPatterns from 'components/AnimatedPatterns' import LanguageSwitcher from 'components/LanguageSwitcher' import styles from './styles.module.sass' export default function App(): ReactElement { const matches = useMatchMedia('max-width: 500px') const { getAllMessages } = useI18n() const { supporters, literature, software, design, about, contact, } = getAllMessages() return ( <div className="App"> <Header classNames={[styles.header]}> <LanguageSwitcher /> <Title>DALTON MENEZES</Title> <Menu horizontal={!matches} withBullets={!matches} classNames={[styles.menu]} > <Item to="/supporters">{supporters}</Item> <Item to="/literature">{literature}</Item> <Item to="/software">{software}</Item> <Item to="/design">{design}</Item> <Item to="/about">{about}</Item> <Item to="/contact">{contact}</Item> </Menu> </Header> <AnimatedPatterns /> </div> ) }
import React, { ReactElement } from 'react' import { useMatchMedia, useI18n } from 'hooks' import { Header, Title } from 'components/Layout' import Menu, { Item } from 'components/Layout/Menu' import AnimatedPatterns from 'components/AnimatedPatterns' import LanguageSwitcher from 'components/LanguageSwitcher' import styles from './styles.module.sass' export default function App(): ReactElement { const { getAllMessages } = useI18n() const matcheWidth = useMatchMedia('max-width: 500px') const matcheHeight = useMatchMedia('max-height: 320px') const matchMedia = matcheWidth && !matcheHeight const { supporters, literature, software, design, about, contact, } = getAllMessages() return ( <div className="App"> <Header classNames={[styles.header]}> <LanguageSwitcher /> <Title>DALTON MENEZES</Title> <Menu horizontal={!matchMedia} withBullets={!matchMedia} classNames={[styles.menu]} > <Item to="/supporters">{supporters}</Item> <Item to="/literature">{literature}</Item> <Item to="/software">{software}</Item> <Item to="/design">{design}</Item> <Item to="/about">{about}</Item> <Item to="/contact">{contact}</Item> </Menu> </Header> <AnimatedPatterns /> </div> ) }
Reset search on page change
import { filter, map } from 'rxjs/operators' import { Component, OnInit } from '@angular/core' import { NavigationEnd, Router } from '@angular/router' import { getParameterByName } from '../shared/misc/utils' @Component({ selector: 'my-header', templateUrl: './header.component.html', styleUrls: [ './header.component.scss' ] }) export class HeaderComponent implements OnInit { searchValue = '' constructor (private router: Router) {} ngOnInit () { this.router.events .pipe( filter(e => e instanceof NavigationEnd), map(() => getParameterByName('search', window.location.href)), filter(searchQuery => !!searchQuery) ) .subscribe(searchQuery => this.searchValue = searchQuery) } doSearch () { this.router.navigate([ '/videos', 'search' ], { queryParams: { search: this.searchValue } }) } }
import { filter, map } from 'rxjs/operators' import { Component, OnInit } from '@angular/core' import { NavigationEnd, Router } from '@angular/router' import { getParameterByName } from '../shared/misc/utils' @Component({ selector: 'my-header', templateUrl: './header.component.html', styleUrls: [ './header.component.scss' ] }) export class HeaderComponent implements OnInit { searchValue = '' constructor (private router: Router) {} ngOnInit () { this.router.events .pipe( filter(e => e instanceof NavigationEnd), map(() => getParameterByName('search', window.location.href)) ) .subscribe(searchQuery => this.searchValue = searchQuery || '') } doSearch () { this.router.navigate([ '/videos', 'search' ], { queryParams: { search: this.searchValue } }) } }
Change symbol type to lowercase
import { Emitter } from "event-emitter"; declare namespace pipe { interface EmitterPipe { close(): void; } } declare function pipe(source: Emitter, target: Emitter, emitMethodName?: string | Symbol): pipe.EmitterPipe; export = pipe;
import { Emitter } from "event-emitter"; declare namespace pipe { interface EmitterPipe { close(): void; } } declare function pipe(source: Emitter, target: Emitter, emitMethodName?: string | symbol): pipe.EmitterPipe; export = pipe;
Refactor mocks - add seed
import faker from 'faker'; export class Faker { private static get positiveInteger(): number { return faker.random.number({ min: 0, max: Number.MAX_SAFE_INTEGER, precision: 1, }); } private static get className(): string { return faker.lorem.word(); } static get modelName(): string { return this.className; } static get limit(): number { return this.positiveInteger; } static get skip(): number { return this.positiveInteger; } };
import faker from 'faker'; import { Filter, Schema, ModelConstructor, } from '../types'; function positiveInteger(): number { return faker.random.number(Number.MAX_SAFE_INTEGER); } function className(): string { return faker.lorem.word(); } function propertyName(): string { return faker.lorem.word().toLowerCase(); } function type(): string { return faker.lorem.word().toLowerCase(); } const seed = positiveInteger(); console.log(`Running with seed ${seed}`) faker.seed(seed); export class Faker { static get modelName(): string { return className(); } static get schema() { return {} } static schemaByPropertyCount(count: number): Schema<any> { let schema = {}; for (let i = 0; i < count; i++) { const name = propertyName(); schema[name] = { type: type() }; if (faker.random.boolean) schema[name].defaultValue = faker.lorem.text; } return schema; } static get limit(): number { return positiveInteger(); } static get skip(): number { return positiveInteger(); } };
Add compare ids into state.
import {MstSvt} from "../../../model/master/Master"; import {MstSkillContainer, MstSvtSkillContainer, MstCombineSkillContainer} from "../../../model/impl/MstContainer"; export interface MstGoal { appVer: string; svtRawData: Array<MstSvt>; svtSkillData: MstSvtSkillContainer; skillCombineData: MstCombineSkillContainer; skillData: MstSkillContainer; current: Goal; goals: Array<Goal>; } export interface Goal { id: string; // UUID name: string; servants: Array<GoalSvt>; } export interface GoalSvt { svtId: number; skills: Array<GoalSvtSkill>; } export interface GoalSvtSkill { skillId: number; level: number; } export const defaultCurrentGoal = { id: "current", name: "current", servants: [], } as Goal; export const defaultMstGoal = { appVer: undefined, current: undefined, goals: [], } as MstGoal;
import {MstSvt} from "../../../model/master/Master"; import {MstSkillContainer, MstSvtSkillContainer, MstCombineSkillContainer} from "../../../model/impl/MstContainer"; export interface MstGoal { appVer: string; svtRawData: Array<MstSvt>; svtSkillData: MstSvtSkillContainer; skillCombineData: MstCombineSkillContainer; skillData: MstSkillContainer; current: Goal; goals: Array<Goal>; compareSourceId: string; // UUID of one Goal compareTargetId: string; // UUID of one Goal } export interface Goal { id: string; // UUID name: string; servants: Array<GoalSvt>; } export interface GoalSvt { svtId: number; skills: Array<GoalSvtSkill>; } export interface GoalSvtSkill { skillId: number; level: number; } export const defaultCurrentGoal = { id: "current", name: "current", servants: [], } as Goal; export const defaultMstGoal = { appVer: undefined, current: undefined, goals: [], compareSourceId: "current", compareTargetId: "current", } as MstGoal;
Remove extraneous channel type in Context model.
import * as Discord from 'discord.js'; import * as mongoose from 'mongoose'; import { logInteraction } from '../helpers/logger'; export default class Context { id: string; bot: Discord.Client; channel: Discord.TextChannel | Discord.DMChannel | Discord.NewsChannel; guild: Discord.Guild; msg: string; preferences: mongoose.Document; db: mongoose.Connection; shard: number; logInteraction; constructor(id: string, bot: Discord.Client, channel: Discord.TextChannel | Discord.DMChannel | Discord.NewsChannel, guild: Discord.Guild, msg: string, preferences: mongoose.Document, db: mongoose.Connection) { this.id = id; this.bot = bot; this.msg = msg; this.channel = channel; this.guild = guild; this.preferences = preferences; this.db = db; this.shard = guild.shardID; this.logInteraction = logInteraction; } }
import * as Discord from 'discord.js'; import * as mongoose from 'mongoose'; import { logInteraction } from '../helpers/logger'; export default class Context { id: string; bot: Discord.Client; channel: Discord.TextChannel | Discord.DMChannel; guild: Discord.Guild; msg: string; preferences: mongoose.Document; db: mongoose.Connection; shard: number; logInteraction; constructor(id: string, bot: Discord.Client, channel: Discord.TextChannel | Discord.DMChannel, guild: Discord.Guild, msg: string, preferences: mongoose.Document, db: mongoose.Connection) { this.id = id; this.bot = bot; this.msg = msg; this.channel = channel; this.guild = guild; this.preferences = preferences; this.db = db; this.shard = guild.shardID; this.logInteraction = logInteraction; } }
Add Nightwatch schematics to e2e command
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { ArchitectCommand } from '../models/architect-command'; import { Arguments } from '../models/interface'; import { Schema as E2eCommandSchema } from './e2e'; export class E2eCommand extends ArchitectCommand<E2eCommandSchema> { public readonly target = 'e2e'; public readonly multiTarget = true; public readonly missingTargetError = ` Cannot find "e2e" target for the specified project. You should add a package that implements end-to-end testing capabilities. For example: Cypress: ng add @cypress/schematic WebdriverIO: ng add @wdio/schematics More options will be added to the list as they become available. `; async initialize(options: E2eCommandSchema & Arguments) { if (!options.help) { return super.initialize(options); } } }
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { ArchitectCommand } from '../models/architect-command'; import { Arguments } from '../models/interface'; import { Schema as E2eCommandSchema } from './e2e'; export class E2eCommand extends ArchitectCommand<E2eCommandSchema> { public readonly target = 'e2e'; public readonly multiTarget = true; public readonly missingTargetError = ` Cannot find "e2e" target for the specified project. You should add a package that implements end-to-end testing capabilities. For example: Cypress: ng add @cypress/schematic Nightwatch: ng add @nightwatch/schematics WebdriverIO: ng add @wdio/schematics More options will be added to the list as they become available. `; async initialize(options: E2eCommandSchema & Arguments) { if (!options.help) { return super.initialize(options); } } }
Use basename to extract class name
import * as fs from "fs"; import * as vscode from "vscode"; import MemberTypes from "./MemberTypes"; class ParsedPhpClass { public name: string; public properties: MemberTypes = new MemberTypes(); public methods: MemberTypes = new MemberTypes(); } function parsePhpToObject(phpClass: string): ParsedPhpClass { const parsed = new ParsedPhpClass(); const propertyRegex = /(public|protected|private) \$(.*) (?==)/g; let propertyMatches = propertyRegex.exec(phpClass); while (propertyMatches != null) { parsed.properties[propertyMatches[1]].push(propertyMatches[2]); propertyMatches = propertyRegex.exec(phpClass); } const methodRegex = /(public|protected|private) (.*function) (.*)(?=\()/g; let methodMatches = methodRegex.exec(phpClass); while (methodMatches != null) { parsed.methods[methodMatches[1]].push(methodMatches[3]); methodMatches = methodRegex.exec(phpClass); } return parsed; } export default async function parse(filePath: string) { const phpClassAsString = await new Promise<string>((resolve, reject) => { fs.readFile(filePath, null, (err, data) => { if (err) { reject(err); } else { resolve(data.toString("utf8")); } }); }); const parsed = parsePhpToObject(phpClassAsString); parsed.name = filePath.match(/.*[\/\\](\w*).php$/i)[1]; return parsed; }
import * as fs from "fs"; import * as path from "path"; import * as vscode from "vscode"; import MemberTypes from "./MemberTypes"; class ParsedPhpClass { public name: string; public properties: MemberTypes = new MemberTypes(); public methods: MemberTypes = new MemberTypes(); } function parsePhpToObject(phpClass: string): ParsedPhpClass { const parsed = new ParsedPhpClass(); const propertyRegex = /(public|protected|private) \$(.*) (?==)/g; let propertyMatches = propertyRegex.exec(phpClass); while (propertyMatches != null) { parsed.properties[propertyMatches[1]].push(propertyMatches[2]); propertyMatches = propertyRegex.exec(phpClass); } const methodRegex = /(public|protected|private) (.*function) (.*)(?=\()/g; let methodMatches = methodRegex.exec(phpClass); while (methodMatches != null) { parsed.methods[methodMatches[1]].push(methodMatches[3]); methodMatches = methodRegex.exec(phpClass); } return parsed; } export default async function parse(filePath: string) { const phpClassAsString = await new Promise<string>((resolve, reject) => { fs.readFile(filePath, null, (err, data) => { if (err) { reject(err); } else { resolve(data.toString("utf8")); } }); }); const parsed = parsePhpToObject(phpClassAsString); parsed.name = path.basename(filePath, '.php'); return parsed; }
Use Page component in books page
import * as React from "react"; import { connect } from "react-redux"; import { Redirect } from "react-router-dom"; import { IBook } from "../lib/books"; import "./style/Books.css"; interface IProps { books: IBook[]; signedIn: boolean; } class Books extends React.Component<IProps> { public render() { if (!this.props.signedIn) { return <Redirect to="/sign-in" />; } return ( <div className="Books-container"> {JSON.stringify(this.props.books)} </div> ); } } export default connect( ({ authState, books }) => ({ ...authState, ...books }), {}, )(Books);
import * as React from "react"; import { connect } from "react-redux"; import { Redirect } from "react-router-dom"; import { IBook } from "../lib/books"; import Page from "./Page"; import "./style/Books.css"; interface IProps { books: IBook[]; signedIn: boolean; } class Books extends React.Component<IProps> { public render() { return ( <Page {...{ menu: false }}> {JSON.stringify(this.props.books)} </Page> ); } } export default connect(({ books }) => books)(Books);
Introduce snapshot size limit as plugin option for OpenStack offering
import * as React from 'react'; import { FormContainer, SelectField } from '@waldur/form-react'; import { translate } from '@waldur/i18n'; export const OpenStackPluginOptionsForm = ({ container, locale }) => { const STORAGE_MODE_OPTIONS = React.useMemo( () => [ { label: translate('Fixed — use common storage quota'), value: 'fixed', }, { label: translate( 'Dynamic — use separate volume types for tracking pricing', ), value: 'dynamic', }, ], locale, ); return ( <FormContainer {...container}> <SelectField name="storage_mode" label={translate('Storage mode')} options={STORAGE_MODE_OPTIONS} simpleValue={true} required={true} description={translate( 'Offering needs to be saved before pricing for dynamic components could be set.', )} /> </FormContainer> ); };
import * as React from 'react'; import { FormContainer, SelectField, NumberField } from '@waldur/form-react'; import { translate } from '@waldur/i18n'; export const OpenStackPluginOptionsForm = ({ container }) => { const STORAGE_MODE_OPTIONS = React.useMemo( () => [ { label: translate('Fixed — use common storage quota'), value: 'fixed', }, { label: translate( 'Dynamic — use separate volume types for tracking pricing', ), value: 'dynamic', }, ], [], ); return ( <FormContainer {...container}> <SelectField name="storage_mode" label={translate('Storage mode')} options={STORAGE_MODE_OPTIONS} simpleValue={true} required={true} description={translate( 'Offering needs to be saved before pricing for dynamic components could be set.', )} /> <NumberField name="snapshot_size_limit_gb" label={translate('Snapshot size limit')} unit="GB" /> </FormContainer> ); };
Fix image positioning to be absolute centered and scale both w/h
import * as React from 'react'; import * as mobxReact from 'mobx-react'; import * as mio from '../'; @mobxReact.observer export class ChapterView extends React.Component<{vm: mio.ChapterViewModel}> { // TODO: Inline styles like this are pretty bad, eh. render() { return ( <div onClick={e => this._onClick(e)} style={{bottom: 0, left: 0, right: 0, position: 'absolute', top: 0}}> <img src={this.props.vm.img} style={{ display: 'block', height: '100%', margin: '0 auto' }} /> </div> ); } private _onClick(e: React.MouseEvent<HTMLDivElement>) { let tresholdX = window.innerWidth / 2; let tresholdY = window.innerHeight / 3; if (e.clientY < tresholdY) { this.props.vm.close(); } else if (e.clientX < tresholdX) { this.props.vm.nextPageAsync(); } else { this.props.vm.previousPageAsync(); } } }
import * as React from 'react'; import * as mobxReact from 'mobx-react'; import * as mio from '../'; @mobxReact.observer export class ChapterView extends React.Component<{vm: mio.ChapterViewModel}> { // TODO: Inline styles like this are pretty bad, eh. render() { return ( <div onClick={e => this._onClick(e)} style={{bottom: 0, left: 0, right: 0, position: 'absolute', top: 0}}> <img src={this.props.vm.img} style={{ display: 'block', maxHeight: '100%', maxWidth: '100%', position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)' }} /> </div> ); } private _onClick(e: React.MouseEvent<HTMLDivElement>) { let tresholdX = window.innerWidth / 2; let tresholdY = window.innerHeight / 3; if (e.clientY < tresholdY) { this.props.vm.close(); } else if (e.clientX < tresholdX) { this.props.vm.nextPageAsync(); } else { this.props.vm.previousPageAsync(); } } }
Update logic for feedback status bar color
import {Response} from "quill-marking-logic" interface Attempt { response: Response } function getAnswerState(attempt: Attempt|undefined): boolean { if (attempt) { return (!!attempt.response.optimal && attempt.response.author === undefined) } return false } export default getAnswerState;
import {Response} from "quill-marking-logic" interface Attempt { response: Response } function getAnswerState(attempt: Attempt|undefined): boolean { if (attempt) { return (attempt.response.optimal) } return false } export default getAnswerState;
Add support for new blockchain fields.
import { ProjectWizardData } from './project-wizard-data.model'; export class Project { public projectName: string; public freelancer: string; public client: string; public startDate: number; public endDate: number; public budget: number; public paymentType: string; public paymentTrigger: string; public description: string; public deliverables: string; public jobRequirements: string[]; public location: string; public hoursPerWeek: number; public creatorID?: string; public status?: string; public lastUpdated?: number; public static convert(wizardData: ProjectWizardData): Project { return { projectName: wizardData.project.projectName, freelancer: wizardData.freelancer.kvkNumber, client: wizardData.client.kvkNumber, startDate: +Date.UTC(wizardData.project.startYear, +wizardData.project.startMonth - 1, wizardData.project.startDay), endDate: +Date.UTC(wizardData.project.endYear, +wizardData.project.endMonth - 1, wizardData.project.endDay), budget: +wizardData.project.budget, paymentType: wizardData.project.paymentMethod, paymentTrigger: wizardData.project.paymentTrigger, description: wizardData.project.projectDescription, deliverables: '', jobRequirements: [], location: '', hoursPerWeek: 0 }; } }
import { ProjectWizardData } from './project-wizard-data.model'; export class Project { public projectName: string; public freelancer: string; public client: string; public startDate: number; public endDate: number; public budget: number; public billingMethod: string; public paymentType: string; public paymentTrigger: string; public paymentComments: string; public description: string; public deliverables: string; public jobRequirements: string[]; public location: string; public hoursPerWeek: number; public creatorID?: string; public status?: string; public lastUpdated?: number; public static convert(wizardData: ProjectWizardData): Project { return { projectName: wizardData.project.projectName, freelancer: wizardData.freelancer.kvkNumber, client: wizardData.client.kvkNumber, startDate: +Date.UTC(wizardData.project.startYear, +wizardData.project.startMonth - 1, wizardData.project.startDay), endDate: +Date.UTC(wizardData.project.endYear, +wizardData.project.endMonth - 1, wizardData.project.endDay), budget: +wizardData.project.budget, billingMethod: wizardData.project.paymentMethod, paymentType: wizardData.project.budgetType, paymentTrigger: wizardData.project.paymentTrigger, paymentComments: wizardData.project.paymentInfo, description: wizardData.project.projectDescription, deliverables: '', jobRequirements: [], location: '', hoursPerWeek: 0 }; } }
Disable accept and preview buttons according to user's qualifications.
import * as React from 'react'; import { ButtonGroup, Button } from '@shopify/polaris'; import { SearchResult } from '../../types'; import TOpticonButton from './TOpticonButton'; import { generateAcceptUrl, generatePreviewUrl } from '../../utils/urls'; export interface Props { readonly hit: SearchResult; } class MiscActionsPopOver extends React.PureComponent<Props, never> { public render() { const { hit: { groupId, requester } } = this.props; return ( <ButtonGroup> <Button plain external url={generateAcceptUrl(groupId)}> Accept </Button> <Button plain external url={generatePreviewUrl(groupId)}> Preview </Button> <TOpticonButton requesterId={requester.id} turkopticon={requester.turkopticon} /> </ButtonGroup> ); } } export default MiscActionsPopOver;
import * as React from 'react'; import { ButtonGroup, Button } from '@shopify/polaris'; import { SearchResult } from '../../types'; import TOpticonButton from './TOpticonButton'; import { generateAcceptUrl, generatePreviewUrl } from '../../utils/urls'; export interface Props { readonly hit: SearchResult; } class MiscActionsPopOver extends React.PureComponent<Props, never> { public render() { const { hit: { groupId, requester, qualified, canPreview } } = this.props; return ( <ButtonGroup> <Button plain external url={generateAcceptUrl(groupId)} disabled={!qualified} > Accept </Button> <Button plain external url={generatePreviewUrl(groupId)} disabled={!canPreview} > Preview </Button> <TOpticonButton requesterId={requester.id} turkopticon={requester.turkopticon} /> </ButtonGroup> ); } } export default MiscActionsPopOver;
Add a contextual type in test case
/// <reference path='fourslash.ts' /> ////var x = "/*1*/string"; ////function f(a = "/*2*/initial value") { } goTo.marker("1"); verify.renameInfoFailed(); goTo.marker("2"); verify.renameInfoFailed();
/// <reference path='fourslash.ts' /> ////var y: "string" = "string; ////var x = "/*1*/string"; ////function f(a = "/*2*/initial value") { } goTo.marker("1"); verify.renameInfoFailed(); goTo.marker("2"); verify.renameInfoFailed();
Fix "empty textures" error on empty canvas
/** * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Alexander Rose <alexander.rose@weirdbyte.de> */ import { DrawPass } from './draw'; import { PickPass } from './pick'; import { MultiSamplePass } from './multi-sample'; import { WebGLContext } from '../../mol-gl/webgl/context'; import { AssetManager } from '../../mol-util/assets'; export class Passes { readonly draw: DrawPass; readonly pick: PickPass; readonly multiSample: MultiSamplePass; constructor(private webgl: WebGLContext, assetManager: AssetManager, attribs: Partial<{ pickScale: number, enableWboit: boolean, enableDpoit: boolean }> = {}) { const { gl } = webgl; this.draw = new DrawPass(webgl, assetManager, gl.drawingBufferWidth, gl.drawingBufferHeight, attribs.enableWboit || false, attribs.enableDpoit || false); this.pick = new PickPass(webgl, this.draw, attribs.pickScale || 0.25); this.multiSample = new MultiSamplePass(webgl, this.draw); } updateSize() { const { gl } = this.webgl; this.draw.setSize(gl.drawingBufferWidth, gl.drawingBufferHeight); this.pick.syncSize(); this.multiSample.syncSize(); } }
/** * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Alexander Rose <alexander.rose@weirdbyte.de> */ import { DrawPass } from './draw'; import { PickPass } from './pick'; import { MultiSamplePass } from './multi-sample'; import { WebGLContext } from '../../mol-gl/webgl/context'; import { AssetManager } from '../../mol-util/assets'; export class Passes { readonly draw: DrawPass; readonly pick: PickPass; readonly multiSample: MultiSamplePass; constructor(private webgl: WebGLContext, assetManager: AssetManager, attribs: Partial<{ pickScale: number, enableWboit: boolean, enableDpoit: boolean }> = {}) { const { gl } = webgl; this.draw = new DrawPass(webgl, assetManager, gl.drawingBufferWidth, gl.drawingBufferHeight, attribs.enableWboit || false, attribs.enableDpoit || false); this.pick = new PickPass(webgl, this.draw, attribs.pickScale || 0.25); this.multiSample = new MultiSamplePass(webgl, this.draw); } updateSize() { const { gl } = this.webgl; // Avoid setting dimensions to 0x0 because it causes "empty textures are not allowed" error. const width = Math.max(gl.drawingBufferWidth, 2); const height = Math.max(gl.drawingBufferHeight, 2); this.draw.setSize(width, height); this.pick.syncSize(); this.multiSample.syncSize(); } }
Fix parse function return in shell-quote
// Type definitions for shell-quote 1.6 // Project: https://github.com/substack/node-shell-quote // Definitions by: Jason Cheatham <https://github.com/jason0x43> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 export function quote(args: string[]): string; export function parse( cmd: string, env?: { [key: string]: string } | ((key: string) => string | object), opts?: { [key: string]: string } ): string[];
// Type definitions for shell-quote 1.6 // Project: https://github.com/substack/node-shell-quote // Definitions by: Jason Cheatham <https://github.com/jason0x43> // Cameron Diver <https://github.com/CameronDiver> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 export type ParseEntry = | string | { op: string } | { op: 'glob'; pattern: string } | { comment: string }; export function quote(args: string[]): string; export function parse( cmd: string, env?: { [key: string]: string } | ((key: string) => string | object), opts?: { [key: string]: string } ): ParseEntry[];
Fix tslint issue in test env
import React from 'react'; import ModalContext from './context'; // eslint-disable-next-line import { IModalContext } from './types'; const withModalContext = <T extends object>(Component: React.ComponentType<T>): React.ComponentType<T> => { class ComponentHOC extends React.Component<T> { modal: React.RefObject<any>; instance: React.ComponentType<T>; constructor(props: T) { super(props); this.modal = React.createRef(); } static get displayName() { return `withModalContext(${Component.displayName || Component.name})`; } openModal = () => { $(this.modal.current).modal('show'); // trick because we use custom styles // for modal coming from superdesk $('.modal-backdrop').addClass('modal__backdrop'); } closeModal = () => { $(this.modal.current).modal('hide'); } render() { const modalStore: IModalContext = { openModal: this.openModal, closeModal: this.closeModal, modalRef: this.modal, }; return ( <ModalContext.Provider value={modalStore}> <Component {...this.props} ref={(el) => this.instance = el} /> </ModalContext.Provider> ); } } return ComponentHOC; }; export default withModalContext;
import React from 'react'; import ModalContext from './context'; // eslint-disable-next-line import { IModalContext } from './types'; const withModalContext = <T extends object>(Component: React.ComponentType<T>): React.ComponentType<T> => { class ComponentHOC extends React.Component<T> { modal: React.RefObject<any>; instance: React.ComponentType<T>; constructor(props: T) { super(props); this.modal = React.createRef(); } static get displayName() { return `withModalContext(${Component.displayName || Component.name})`; } openModal = () => { $(this.modal.current).modal('show'); // trick because we use custom styles // for modal coming from superdesk $('.modal-backdrop').addClass('modal__backdrop'); } closeModal = () => { $(this.modal.current).modal('hide'); } render() { const modalStore: IModalContext = { openModal: this.openModal, closeModal: this.closeModal, modalRef: this.modal, }; return ( <ModalContext.Provider value={modalStore}> <Component {...this.props} ref={(el) => this.instance = el} /> </ModalContext.Provider> ); } } return ComponentHOC as any; }; export default withModalContext;
Include headings within blockquotes in TOC
import { RichOutlineSyntaxNode } from './RichOutlineSyntaxNode' import { UpDocument } from './UpDocument' import { Writer } from '../Writing/Writer' export class Blockquote extends RichOutlineSyntaxNode { // As a rule, we don't want to include any blockquoted content in the table of contents. descendantsToIncludeInTableOfContents(): UpDocument.TableOfContents.Entry[] { return [] } write(writer: Writer): string { return writer.blockquote(this) } protected BLOCKQUOTE(): void { } }
import { RichOutlineSyntaxNode } from './RichOutlineSyntaxNode' import { Writer } from '../Writing/Writer' export class Blockquote extends RichOutlineSyntaxNode { write(writer: Writer): string { return writer.blockquote(this) } protected BLOCKQUOTE(): void { } }
Add missing semicolon in test
/* highlight.js definition by Niklas Mollenhauer Last Update: 10.09.2013 Source Code: https://github.com/isagalaev/highlight.js Project Page: http://softwaremaniacs.org/soft/highlight/en/ */ /// <reference path="highlightjs.d.ts" /> import hljs = require("highlight.js"); var code = "using System;\npublic class Test\n{\npublic static void Main()\n{\n// your code goes here\n}\n}"; var lang = "cs"; hljs.configure({ tabReplace: " " }) // 4 spaces var hl = hljs.highlight(lang, code).value; hl = hljs.highlightAuto(code).value;
/* highlight.js definition by Niklas Mollenhauer Last Update: 10.09.2013 Source Code: https://github.com/isagalaev/highlight.js Project Page: http://softwaremaniacs.org/soft/highlight/en/ */ /// <reference path="highlightjs.d.ts" /> import hljs = require("highlight.js"); var code = "using System;\npublic class Test\n{\npublic static void Main()\n{\n// your code goes here\n}\n}"; var lang = "cs"; hljs.configure({ tabReplace: " " }); // 4 spaces var hl = hljs.highlight(lang, code).value; hl = hljs.highlightAuto(code).value;
Sort domotics devices by label/name
import { Component, OnInit } from '@angular/core'; import { ConfigService } from '../_services/config.service'; import { timer } from 'rxjs'; import { OpenhabService } from '../_services/openhab.service'; @Component({ selector: 'app-domotics', templateUrl: './domotics.component.html', styleUrls: ['./domotics.component.scss'] }) export class DomoticsComponent implements OnInit { items: any[]; error: any; constructor(private openhab: OpenhabService, private config: ConfigService) { } ngOnInit(): void { timer(0, this.config.configuration.domotics.refreshRate).subscribe(() => this.update()); } update() { this.openhab.getItems(this.config.configuration.domotics.showGroup) .subscribe( data => { this.items = data; this.error = undefined; }, error => this.error = error); }}
import { Component, OnInit } from '@angular/core'; import { ConfigService } from '../_services/config.service'; import { timer } from 'rxjs'; import { OpenhabService } from '../_services/openhab.service'; @Component({ selector: 'app-domotics', templateUrl: './domotics.component.html', styleUrls: ['./domotics.component.scss'] }) export class DomoticsComponent implements OnInit { items: any[]; error: any; constructor(private openhab: OpenhabService, private config: ConfigService) { } ngOnInit(): void { timer(0, this.config.configuration.domotics.refreshRate).subscribe(() => this.update()); } update() { this.openhab.getItems(this.config.configuration.domotics.showGroup) .subscribe( data => { this.items = data .sort((a, b) => (a.label || a.name) > (b.label || b.name) ? 1 : (a.label || a.name) < (b.label || b.name) ? -1 : 0); this.error = undefined; }, error => this.error = error); }}
Add import in unit test
import {async, TestBed} from "@angular/core/testing"; import {AppComponent} from "./app.component"; import {MdSidenavModule, MdSnackBarModule} from "@angular/material"; import {MainToolbarComponent} from "./main-toolbar/main-toolbar.component"; import {AccountButtonComponent} from "./account-button/account-button.component"; import {HintsComponent} from "./hints/hints.component"; import {SlickModule} from "ngx-slick"; import {HotkeyModule} from "angular2-hotkeys"; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MdSidenavModule, SlickModule.forRoot(), HotkeyModule.forRoot(), MdSnackBarModule], declarations: [ AppComponent, MainToolbarComponent, AccountButtonComponent, HintsComponent ], }).compileComponents(); })); it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); })); });
import {async, TestBed} from "@angular/core/testing"; import {AppComponent} from "./app.component"; import {MdSidenavModule, MdSnackBarModule} from "@angular/material"; import {MainToolbarComponent} from "./main-toolbar/main-toolbar.component"; import {AccountButtonComponent} from "./account-button/account-button.component"; import {HintsComponent} from "./hints/hints.component"; import {SlickModule} from "ngx-slick"; import {HotkeyModule} from "angular2-hotkeys"; import {GraphComponent} from "./graph/graph.component"; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MdSidenavModule, SlickModule.forRoot(), HotkeyModule.forRoot(), MdSnackBarModule], declarations: [ AppComponent, MainToolbarComponent, AccountButtonComponent, HintsComponent, GraphComponent ], }).compileComponents(); })); it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); })); });
Create privateClassName for the sticky header
import { classNamePrefix } from "./consts"; export const sortArrowClassName = classNamePrefix + "sortArrow"; export const activeSortArrowClassName = classNamePrefix + "sortArrow--active"; export const ascendantSortArrowClassName = classNamePrefix + "sortArrow--ascendant"; export const descendantSortArrowClassName = classNamePrefix + "sortArrow--descendant"; export const selectionCellClassName = classNamePrefix + "selectionCell";
import { classNamePrefix } from "./consts"; export const sortArrowClassName = classNamePrefix + "sortArrow"; export const activeSortArrowClassName = classNamePrefix + "sortArrow--active"; export const ascendantSortArrowClassName = classNamePrefix + "sortArrow--ascendant"; export const descendantSortArrowClassName = classNamePrefix + "sortArrow--descendant"; export const selectionCellClassName = classNamePrefix + "selectionCell"; export const stickyHeaderClassName = classNamePrefix + "stickyHeader";
Return empty array when include not defined
import { JSONAPIResourceObject } from './jsonapi-resource-object.model'; export class JSONAPIResponse<T extends JSONAPIResourceObject | JSONAPIResourceObject[]> { public data: T; public included: JSONAPIResourceObject[]; public constructor(json: {data: any, included?: any}) { this.data = json.data; this.included = json.included; } public toPayload(): T { return this.data; } public toIncluded(): JSONAPIResourceObject | JSONAPIResourceObject[] { return this.included; } public toIncludedByType<U extends JSONAPIResourceObject>(type: string): U[] { return <U[]>this.included.filter((include: JSONAPIResourceObject) => include.type === type); } public toJSON(): {data: T, included?: JSONAPIResourceObject | JSONAPIResourceObject[]} { if (this.included) { return {data: this.data, included: this.included}; } else { return {data: this.data}; } } }
import { JSONAPIResourceObject } from './jsonapi-resource-object.model'; export class JSONAPIResponse<T extends JSONAPIResourceObject | JSONAPIResourceObject[]> { public data: T; public included: JSONAPIResourceObject[]; public constructor(json: {data: any, included?: any}) { this.data = json.data; this.included = json.included; } public toPayload(): T { return this.data; } public toIncluded(): JSONAPIResourceObject | JSONAPIResourceObject[] { return this.included; } public toIncludedByType<U extends JSONAPIResourceObject>(type: string): U[] { if (!this.included) { return []; } return <U[]>this.included.filter((include: JSONAPIResourceObject) => include.type === type); } public toJSON(): {data: T, included?: JSONAPIResourceObject | JSONAPIResourceObject[]} { if (this.included) { return {data: this.data, included: this.included}; } else { return {data: this.data}; } } }
Fix import for bootstrap effects token
import { OpaqueToken, Provider } from '@angular/core'; import { flatten } from './util'; import { CONNECT_EFFECTS_PROVIDER } from './effects'; import { STATE_UPDATES_PROVIDER } from './state-updates'; export const BOOTSTRAP_EFFECTS = new OpaqueToken('@ngrx/effects Bootstrap Effects'); export function runEffects(...effects: any[]) { const allEffects = flatten(effects).map(effect => new Provider(BOOTSTRAP_EFFECTS, { useClass: effect, multi: true })); return [ ...allEffects, CONNECT_EFFECTS_PROVIDER, STATE_UPDATES_PROVIDER ]; }
import { OpaqueToken, Provider } from '@angular/core'; import { flatten } from './util'; import { CONNECT_EFFECTS_PROVIDER, BOOTSTRAP_EFFECTS } from './effects'; import { STATE_UPDATES_PROVIDER } from './state-updates'; export function runEffects(...effects: any[]) { const allEffects = flatten(effects).map(effect => new Provider(BOOTSTRAP_EFFECTS, { useClass: effect, multi: true })); return [ ...allEffects, CONNECT_EFFECTS_PROVIDER, STATE_UPDATES_PROVIDER ]; }
Remove unused function in nevercode
import { Env, CISource } from "../ci_source" import { ensureEnvKeysExist, ensureEnvKeysAreInt } from "../ci_source_helpers" /** * Nevercode.io CI Integration * * Environment Variables Documented: https://developer.nevercode.io/v1.0/docs/environment-variables-files */ export class Nevercode implements CISource { constructor(private readonly env: Env) {} get name(): string { return "Nevercode" } get isCI(): boolean { return ensureEnvKeysExist(this.env, ["NEVERCODE"]) } get isPR(): boolean { const mustHave = ["NEVERCODE_PULL_REQUEST", "NEVERCODE_REPO_SLUG"] const mustBeInts = ["NEVERCODE_GIT_PROVIDER_PULL_REQUEST", "NEVERCODE_PULL_REQUEST_NUMBER"] return ( ensureEnvKeysExist(this.env, mustHave) && ensureEnvKeysAreInt(this.env, mustBeInts) && this.env.NEVERCODE_PULL_REQUEST == "true" ) } get pullRequestID(): string { return this.env.NEVERCODE_PULL_REQUEST_NUMBER } get repoSlug(): string { return this.env.NEVERCODE_REPO_SLUG } get supportedPlatforms(): string[] { return ["github"] } get ciRunURL() { return process.env.NEVERCODE_BUILD_URL } private get branchName(): string { if (this.isPR) { return this.env.NEVERCODE_PULL_REQUEST_SOURCE } else { return this.env.NEVERCODE_BRANCH } } }
import { Env, CISource } from "../ci_source" import { ensureEnvKeysExist, ensureEnvKeysAreInt } from "../ci_source_helpers" /** * Nevercode.io CI Integration * * Environment Variables Documented: https://developer.nevercode.io/v1.0/docs/environment-variables-files */ export class Nevercode implements CISource { constructor(private readonly env: Env) {} get name(): string { return "Nevercode" } get isCI(): boolean { return ensureEnvKeysExist(this.env, ["NEVERCODE"]) } get isPR(): boolean { const mustHave = ["NEVERCODE_PULL_REQUEST", "NEVERCODE_REPO_SLUG"] const mustBeInts = ["NEVERCODE_GIT_PROVIDER_PULL_REQUEST", "NEVERCODE_PULL_REQUEST_NUMBER"] return ( ensureEnvKeysExist(this.env, mustHave) && ensureEnvKeysAreInt(this.env, mustBeInts) && this.env.NEVERCODE_PULL_REQUEST == "true" ) } get pullRequestID(): string { return this.env.NEVERCODE_PULL_REQUEST_NUMBER } get repoSlug(): string { return this.env.NEVERCODE_REPO_SLUG } get supportedPlatforms(): string[] { return ["github"] } get ciRunURL() { return process.env.NEVERCODE_BUILD_URL } }
Fix - icon alignment for overview
import React from 'react'; import { Icon } from '../../components'; import { usePermissions } from '../../hooks'; import { classnames } from '../../helpers'; import Sections from './Sections'; import { SectionConfig } from '../../components/layout'; const IndexSection = ({ pages, limit = 4 }: { pages: SectionConfig[]; limit?: number }) => { const permissions = usePermissions(); return ( <div className="overview-grid"> {pages.map(({ icon, text, to, subsections = [], permissions: pagePermissions }) => { return ( <section key={to} className={classnames([ 'overview-grid-item bordered-container bg-white-dm tiny-shadow-container p2', subsections.length > limit && 'overview-grid-item--tall', ])} > <h2 className="h6 mb1"> <Icon name={icon} className="mr0-5" /> <strong>{text}</strong> </h2> <Sections to={to} subsections={subsections} text={text} permissions={permissions} pagePermissions={pagePermissions} /> </section> ); })} </div> ); }; export default IndexSection;
import React from 'react'; import { Icon } from '../../components'; import { usePermissions } from '../../hooks'; import { classnames } from '../../helpers'; import Sections from './Sections'; import { SectionConfig } from '../../components/layout'; const IndexSection = ({ pages, limit = 4 }: { pages: SectionConfig[]; limit?: number }) => { const permissions = usePermissions(); return ( <div className="overview-grid"> {pages.map(({ icon, text, to, subsections = [], permissions: pagePermissions }) => { return ( <section key={to} className={classnames([ 'overview-grid-item bordered-container bg-white-dm tiny-shadow-container p2', subsections.length > limit && 'overview-grid-item--tall', ])} > <h2 className="h6 mb1 flex flex-items-center flex-nowrap"> <Icon name={icon} className="mr0-5 flex-item-noshrink" /> <strong className="ellipsis" title={text}> {text} </strong> </h2> <Sections to={to} subsections={subsections} text={text} permissions={permissions} pagePermissions={pagePermissions} /> </section> ); })} </div> ); }; export default IndexSection;
Add template support for random number
import 'zone.js'; import 'reflect-metadata'; import { Component } from '@angular/core'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; @Component({ selector: 'i-am', template: '<h2> I am {{ status }} </h2>' }) export class IAmAliveComponent { status: string; constructor() { this.status = 'Alive'; } } @NgModule({ imports: [BrowserModule], declarations: [IAmAliveComponent], bootstrap: [IAmAliveComponent] }) export class PhilTestModule { } platformBrowserDynamic().bootstrapModule(PhilTestModule);
import 'zone.js'; import 'reflect-metadata'; import { Component } from '@angular/core'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; @Component({ selector: 'i-am', template: '<h2> I am {{ status }} </h2><br/><h3>Your lucky number is {{ randNum }}</h3>' }) export class IAmAliveComponent { status: string; randNum: number; constructor() { this.status = 'Alive'; this.randNum = 42; } } @NgModule({ imports: [BrowserModule], declarations: [IAmAliveComponent], bootstrap: [IAmAliveComponent] }) export class PhilTestModule { } platformBrowserDynamic().bootstrapModule(PhilTestModule);
Support tags with "issues" in their name, i.e. "known_issues".
import { match } from 'tiny-types'; import { ArbitraryTag, IssueTag, ManualTag, Tag } from './'; /** * @package */ export class Tags { private static Pattern = /^@([\w-]+)[:\s]?(.*)/i; public static from(text: string): Tag[] { const [ , type, val ] = Tags.Pattern.exec(text); return match<Tag[]>(type.toLowerCase()) .when('manual', _ => [ new ManualTag() ]) // todo: map as arbitrary tag if value === ''; look up ticket id .when(/issues?/, _ => val.split(',').map(value => new IssueTag(value.trim()))) .else(value => [ new ArbitraryTag(value.trim()) ]); } }
import { match } from 'tiny-types'; import { ArbitraryTag, IssueTag, ManualTag, Tag } from './'; /** * @package */ export class Tags { private static Pattern = /^@([\w-]+)[:\s]?(.*)/i; public static from(text: string): Tag[] { const [ , type, val ] = Tags.Pattern.exec(text); return match<Tag[]>(type.toLowerCase()) .when('manual', _ => [ new ManualTag() ]) // todo: map as arbitrary tag if value === ''; look up ticket id .when(/^issues?$/, _ => val.split(',').map(value => new IssueTag(value.trim()))) .else(value => [ new ArbitraryTag(value.trim()) ]); } }
Add semicolon to separate styles
import React from "react" import styled from "styled-components" import * as fonts from "../Assets/Fonts" import { media } from "./Helpers" type TitleSize = "xxsmall" | "small" | "medium" | "large" | "xlarge" | "xxlarge" interface TitleProps extends React.HTMLProps<HTMLDivElement> { titleSize?: TitleSize color?: string } const titleSizes = { xxsmall: "13px", small: "25px", medium: "30px", large: "37px", xlarge: "50px", xxlarge: "72px", } const Title: React.SFC<TitleProps> = props => { const newProps: TitleProps = { ...props } delete newProps.titleSize return <div {...newProps}>{props.children}</div> } const StyledTitle = styled(Title)` font-size: ${props => titleSizes[props.titleSize]}; color: ${props => props.color}; margin: 20px 0; ${fonts.secondary.style} ${media.sm` font-size: ${titleSizes.small}; `}; ` StyledTitle.defaultProps = { titleSize: "medium", color: "inherit", } export default StyledTitle
import React from "react" import styled from "styled-components" import * as fonts from "../Assets/Fonts" import { media } from "./Helpers" type TitleSize = "xxsmall" | "small" | "medium" | "large" | "xlarge" | "xxlarge" interface TitleProps extends React.HTMLProps<HTMLDivElement> { titleSize?: TitleSize color?: string } const titleSizes = { xxsmall: "13px", small: "25px", medium: "30px", large: "37px", xlarge: "50px", xxlarge: "72px", } const Title: React.SFC<TitleProps> = props => { const newProps: TitleProps = { ...props } delete newProps.titleSize return <div {...newProps}>{props.children}</div> } const StyledTitle = styled(Title)` font-size: ${props => titleSizes[props.titleSize]}; color: ${props => props.color}; margin: 20px 0; ${fonts.secondary.style}; ${media.sm` font-size: ${titleSizes.small}; `}; ` StyledTitle.defaultProps = { titleSize: "medium", color: "inherit", } export default StyledTitle
Add test for new position format
import {SunAndMoonConfigCtrl} from "../src/config_ctrl"; describe("SunAndMoonConfigCtrl", () => { it("config_ctrl should support old position format", () => { SunAndMoonConfigCtrl.prototype.current = { jsonData: { position: { latitude: 48, longitude: 10 } } }; const cc = new SunAndMoonConfigCtrl(); expect(cc.current.jsonData).toEqual({latitude: 48, longitude: 10}); }); });
import {SunAndMoonConfigCtrl} from "../src/config_ctrl"; describe("SunAndMoonConfigCtrl", () => { it("config_ctrl should support new position format", () => { SunAndMoonConfigCtrl.prototype.current = { jsonData: { latitude: 48, longitude: 10 } }; const cc = new SunAndMoonConfigCtrl(); expect(cc.current.jsonData).toEqual({latitude: 48, longitude: 10}); }); it("config_ctrl should support old position format", () => { SunAndMoonConfigCtrl.prototype.current = { jsonData: { position: { latitude: 48, longitude: 10 } } }; const cc = new SunAndMoonConfigCtrl(); expect(cc.current.jsonData).toEqual({latitude: 48, longitude: 10}); }); });
Make select field more robust if options list is not defined.
import * as React from 'react'; import Select from 'react-select'; export const SelectField = (props) => { const { input, simpleValue, options, ...rest } = props; return ( <Select {...rest} name={input.name} value={ simpleValue || typeof input.value !== 'object' ? options.filter((option) => option.value === input.value) : input.value } onChange={(newValue: any) => simpleValue ? input.onChange(newValue.value) : input.onChange(newValue) } options={options} onBlur={() => { if (!props.noUpdateOnBlur) { // See also: https://github.com/erikras/redux-form/issues/1185 props.input.onBlur(props.input.value); } }} /> ); };
import * as React from 'react'; import Select from 'react-select'; export const SelectField = (props) => { const { input, simpleValue, options, ...rest } = props; return ( <Select {...rest} name={input.name} value={ (simpleValue || typeof input.value !== 'object') && options ? options.filter((option) => option.value === input.value) : input.value } onChange={(newValue: any) => simpleValue ? input.onChange(newValue.value) : input.onChange(newValue) } options={options} onBlur={() => { if (!props.noUpdateOnBlur) { // See also: https://github.com/erikras/redux-form/issues/1185 props.input.onBlur(props.input.value); } }} /> ); };
Add className to Tooltip component
import React from 'react'; import { Manager, Popper, Arrow } from 'react-popper'; interface IwithTooltipProps { placement?: string; content: string | ((props: any) => JSX.Element); } export default function withTooltip(WrappedComponent) { return class extends React.Component<IwithTooltipProps, any> { constructor(props) { super(props); this.setState = this.setState.bind(this); this.state = { placement: this.props.placement || 'auto', show: false, }; } componentWillReceiveProps(nextProps) { if (nextProps.placement && nextProps.placement !== this.state.placement) { this.setState(prevState => { return { ...prevState, placement: nextProps.placement, }; }); } } renderContent(content) { if (typeof content === 'function') { // If it's a function we assume it's a React component const ReactComponent = content; return <ReactComponent />; } return content; } render() { const { content } = this.props; return ( <Manager className="popper__manager"> <WrappedComponent {...this.props} tooltipSetState={this.setState} /> {this.state.show ? ( <Popper placement={this.state.placement} className="popper"> {this.renderContent(content)} <Arrow className="popper__arrow" /> </Popper> ) : null} </Manager> ); } }; }
import React from 'react'; import { Manager, Popper, Arrow } from 'react-popper'; interface IwithTooltipProps { placement?: string; content: string | ((props: any) => JSX.Element); className?: string; } export default function withTooltip(WrappedComponent) { return class extends React.Component<IwithTooltipProps, any> { constructor(props) { super(props); this.setState = this.setState.bind(this); this.state = { placement: this.props.placement || 'auto', show: false, }; } componentWillReceiveProps(nextProps) { if (nextProps.placement && nextProps.placement !== this.state.placement) { this.setState(prevState => { return { ...prevState, placement: nextProps.placement, }; }); } } renderContent(content) { if (typeof content === 'function') { // If it's a function we assume it's a React component const ReactComponent = content; return <ReactComponent />; } return content; } render() { const { content, className } = this.props; return ( <Manager className={`popper__manager ${className || ''}`}> <WrappedComponent {...this.props} tooltipSetState={this.setState} /> {this.state.show ? ( <Popper placement={this.state.placement} className="popper"> {this.renderContent(content)} <Arrow className="popper__arrow" /> </Popper> ) : null} </Manager> ); } }; }
Set size of slides to 100% width and height
/** * Created by sigurdbergsvela on 15.01.14. */ ///<reference path="defs/jquery.d.ts"/> class JSlider { private _options = { }; private sliderWrapper : JQuery; private slidesWrapper : JQuery; private slides : JQuery; private currentSlide : number; /** * Creates a new slider out of an HTMLElement * * The htmlElement is expected to be the wrapper of the slider. * The structur is expected to be * <div> <!--The slider wrapper--> * <ul> <!--The slides--> * <li></li> <!--A Single slide--> * <li></li> <!--A Single slide--> * <li></li> <!--A Single slide--> * </ul> * </div> * * The ul element will be gived display:block, and all the LI elements will * be given a width and height of 100%; * * options * .delay : How long between each slide, -1 for no automated sliding */ constructor(sliderWrapper : HTMLDivElement, options : Object = {}) { this._options['delay'] = options['delay'] || 100; this.sliderWrapper = jQuery(sliderWrapper); this.slidesWrapper = this.sliderWrapper.children("ul"); this.slides = this.slidesWrapper.children("li"); this.currentSlide = 0; } public start() : void { } }
/** * Created by sigurdbergsvela on 15.01.14. */ ///<reference path="defs/jquery.d.ts"/> class JSlider { private _options = { }; private sliderWrapper : JQuery; private slidesWrapper : JQuery; private slides : JQuery; private currentSlide : number; /** * Creates a new slider out of an HTMLElement * * The htmlElement is expected to be the wrapper of the slider. * The structur is expected to be * <div> <!--The slider wrapper--> * <ul> <!--The slides--> * <li></li> <!--A Single slide--> * <li></li> <!--A Single slide--> * <li></li> <!--A Single slide--> * </ul> * </div> * * The ul element will be gived display:block, and all the LI elements will * be given a width and height of 100%; * * options * .delay : How long between each slide, -1 for no automated sliding */ constructor(sliderWrapper : HTMLDivElement, options : Object = {}) { this._options['delay'] = options['delay'] || 100; this.sliderWrapper = jQuery(sliderWrapper); this.slidesWrapper = this.sliderWrapper.children("ul"); this.slides = this.slidesWrapper.children("li"); this.currentSlide = 0; this.slides.css({ "height" : "100%", "width" : "100%" }); } public start() : void { } }
Add passing NSFL block test
import { expect } from 'chai' import Up from '../../../index' import { InlineNsflNode } from '../../../SyntaxNodes/InlineNsflNode' describe("The text in an inline NSFL convention's label", () => { it("uses the provided term for 'toggleNsfl'", () => { const up = new Up({ i18n: { terms: { toggleNsfl: 'show/hide' } } }) const node = new InlineNsflNode([]) const html = '<span class="up-nsfl up-revealable">' + '<label for="up-nsfl-1">show/hide</label>' + '<input id="up-nsfl-1" type="checkbox">' + '<span></span>' + '</span>' expect(up.toHtml(node)).to.be.eql(html) }) })
import { expect } from 'chai' import Up from '../../../index' import { InlineNsflNode } from '../../../SyntaxNodes/InlineNsflNode' import { NsflBlockNode } from '../../../SyntaxNodes/NsflBlockNode' describe("The text in an inline NSFL convention's label", () => { it("uses the provided term for 'toggleNsfl'", () => { const up = new Up({ i18n: { terms: { toggleNsfl: 'show/hide' } } }) const node = new InlineNsflNode([]) const html = '<span class="up-nsfl up-revealable">' + '<label for="up-nsfl-1">show/hide</label>' + '<input id="up-nsfl-1" type="checkbox">' + '<span></span>' + '</span>' expect(up.toHtml(node)).to.be.eql(html) }) }) describe("The text in an inline NSFL convention's label", () => { it("uses the provided term for 'toggleNsfl'", () => { const up = new Up({ i18n: { terms: { toggleNsfl: 'show/hide' } } }) const node = new NsflBlockNode([]) const html = '<div class="up-nsfl up-revealable">' + '<label for="up-nsfl-1">show/hide</label>' + '<input id="up-nsfl-1" type="checkbox">' + '<div></div>' + '</div>' expect(up.toHtml(node)).to.be.eql(html) }) })
Create project object before running tasks
/// <reference path="./typings/bundle.d.ts" /> import {task, src, dest, watch} from 'gulp'; import * as ts from 'gulp-typescript'; import * as tslint from 'gulp-tslint'; import * as babel from 'gulp-babel'; task('build', ['build:ts']); function buildTypeScript(): ts.CompilationStream { const project = ts.createProject('tsconfig.json', { typescript: require('typescript') }); return project.src().pipe(ts(project)); } task('build:ts', () => buildTypeScript() .pipe(babel()) .pipe(dest('./built')) ); task('lint', () => src('./src/**/*.ts') .pipe(tslint({ tslint: require('tslint') })) .pipe(tslint.report('verbose')) ); task('test', ['build', 'lint']); task('watch', ['build'], () => watch('./src/**/*.ts', ['build:ts']) );
/// <reference path="./typings/bundle.d.ts" /> import {task, src, dest, watch} from 'gulp'; import * as ts from 'gulp-typescript'; import * as tslint from 'gulp-tslint'; import * as babel from 'gulp-babel'; task('build', ['build:ts']); const project = ts.createProject('tsconfig.json', { typescript: require('typescript') }); function buildTypeScript(): ts.CompilationStream { return project.src().pipe(ts(project)); } task('build:ts', () => buildTypeScript() .pipe(babel()) .pipe(dest('./built')) ); task('lint', () => src('./src/**/*.ts') .pipe(tslint({ tslint: require('tslint') })) .pipe(tslint.report('verbose')) ); task('test', ['build', 'lint']); task('watch', ['build'], () => watch('./src/**/*.ts', ['build:ts']) );
Set static to send method
import { Component, Inject, Injector, bind } from 'angular2/angular2'; import {Router, ROUTER_DIRECTIVES} from 'angular2/router'; @Component({ directives: [ ROUTER_DIRECTIVES ] }) export class AnalyticsService { //Set the analytics id of the page we want to send data id : string = "UA-70134683-1"; constructor(public router: Router){ //we instantiate the google analytics service window.ga('create', this.id, 'auto'); this.router.subscribe(this.onRouteChanged); } onRouteChanged(path){ //should we send more data? window.ga('send', 'pageview', { 'page' : path}); } //Manual send send(type : string){ if (window.ga) window.ga('send', type); } }
import { Component, Inject, Injector, bind } from 'angular2/angular2'; import {Router, ROUTER_DIRECTIVES} from 'angular2/router'; @Component({ directives: [ ROUTER_DIRECTIVES ] }) export class AnalyticsService { //Set the analytics id of the page we want to send data id : string = "UA-70134683-1"; constructor(public router: Router){ //we instantiate the google analytics service window.ga('create', this.id, 'auto'); //We set the router to call onRouteChanged every time we change the page this.router.subscribe(this.onRouteChanged); } onRouteChanged(path){ //should we send more data? window.ga('send', 'pageview', { 'page' : path}); } //Manual send. static send(type : string){ if (window.ga) window.ga('send', type); } }
Add 'Hajime-chan is No. 1' to the invalid list
export * from "./interface"; import {GinBuilder} from "./builder"; export {GinBuilder} from "./builder"; export * from "./enum"; export * from "./filter"; export const gindownloader = new GinBuilder();
export * from "./interface"; import {GinBuilder} from "./builder"; export {GinBuilder, MangaHereBuilder} from "./builder"; export * from "./enum"; export * from "./filter"; export * from "./parser"; export const gindownloader = new GinBuilder(); export {MangaHereConfig} from "./manga/mangahere/config"; export {RequestRetryStrategy} from "./strategies/retry_strategy"; export {MangaHereParser} from "./manga/mangahere/parser"; export {mangahereLogger} from "./manga/mangahere/logger"; export {MangaHereGenre} from "./manga/mangahere/genre"; export {MangaRequestResult} from "./util/mangaRequestResult"; export {RetryRequestFactory} from "./factories/retryRequest";
Add refrence to the shim so VSCode does not throw errors
import { expect } from "chai"; import * as skinview3d from "../src/skinview3d"; import skin1_8Default from "./textures/skin-1.8-default-no_hd.png"; import skin1_8Slim from "./textures/skin-1.8-slim-no_hd.png"; import skinOldDefault from "./textures/skin-old-default-no_hd.png"; describe("detect model of texture", () => { it("1.8 default", async () => { const image = document.createElement("img"); image.src = skin1_8Default; await Promise.resolve(); expect(skinview3d.isSlimSkin(image)).to.equal(false); }); it("1.8 slim", async () => { const image = document.createElement("img"); image.src = skin1_8Slim; await Promise.resolve(); expect(skinview3d.isSlimSkin(image)).to.equal(true); }); it("old default", async () => { const image = document.createElement("img"); image.src = skinOldDefault; await Promise.resolve(); expect(skinview3d.isSlimSkin(image)).to.equal(false); }); });
/// <reference path="shims.d.ts"/> import { expect } from "chai"; import * as skinview3d from "../src/skinview3d"; import skin1_8Default from "./textures/skin-1.8-default-no_hd.png"; import skin1_8Slim from "./textures/skin-1.8-slim-no_hd.png"; import skinOldDefault from "./textures/skin-old-default-no_hd.png"; import skinLegacyHatDefault from "./textures/skin-legacyhat-default-no_hd.png"; describe("detect model of texture", () => { it("1.8 default", async () => { const image = document.createElement("img"); image.src = skin1_8Default; await Promise.resolve(); expect(skinview3d.isSlimSkin(image)).to.equal(false); }); it("1.8 slim", async () => { const image = document.createElement("img"); image.src = skin1_8Slim; await Promise.resolve(); expect(skinview3d.isSlimSkin(image)).to.equal(true); }); it("old default", async () => { const image = document.createElement("img"); image.src = skinOldDefault; await Promise.resolve(); expect(skinview3d.isSlimSkin(image)).to.equal(false); }); /* TODO: implement transparent hat check for 64x32 skins it("legacy hat test", async () => { const image = document.createElement("img"); image.src = skinLegacyHatDefault; await Promise.resolve(); }); */ });
Update group detail state to props mapping
import { connect, Dispatch } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { AppState } from '../constants/types'; import GroupDetail from '../components/groupDetail'; import * as actions from '../actions/group'; export function mapStateToProps(state: AppState, params: any) { let groupSequence = parseInt(params.match.params.groupSequence, 10); let results; state.groups.uniqueNames.forEach(function (uniqueName: string, idx: number) { if (state.groups.ByUniqueNames[uniqueName].sequence === groupSequence) { results = {group: state.groups.ByUniqueNames[uniqueName]}; } }); if (!results) { results = {group: null}; } return results; } export interface DispatchProps { onDelete?: () => any; fetchData?: () => any; } export function mapDispatchToProps(dispatch: Dispatch<actions.GroupAction>, params: any): DispatchProps { return { onDelete: () => dispatch(() => undefined), fetchData: () => dispatch( actions.fetchGroup( params.match.params.user, params.match.params.projectName, params.match.params.groupSequence)) }; } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(GroupDetail));
import { connect, Dispatch } from 'react-redux'; import { withRouter } from 'react-router-dom'; import * as _ from 'lodash'; import { AppState } from '../constants/types'; import GroupDetail from '../components/groupDetail'; import * as actions from '../actions/group'; import { getGroupUniqueName } from '../constants/utils'; export function mapStateToProps(state: AppState, params: any) { let groupUniqueName = getGroupUniqueName( params.match.params.user, params.match.params.projectName, params.match.params.groupSequence); return _.includes(state.groups.uniqueNames, groupUniqueName) ? {group: state.groups.ByUniqueNames[groupUniqueName]} : {group: null}; } export interface DispatchProps { onDelete?: () => any; fetchData?: () => any; } export function mapDispatchToProps(dispatch: Dispatch<actions.GroupAction>, params: any): DispatchProps { return { onDelete: () => dispatch(() => undefined), fetchData: () => dispatch( actions.fetchGroup( params.match.params.user, params.match.params.projectName, params.match.params.groupSequence)) }; } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(GroupDetail));
Rename expert contract state: Pending -> Waiting for proposals
import * as classNames from 'classnames'; import * as React from 'react'; import { react2angular } from 'react2angular'; import { RequestState } from './types'; interface ExpertRequestStateProps { model: { state: RequestState; }; } const LabelClasses = { Active: '', Pending: 'progress-bar-warning', Cancelled: 'progress-bar-danger', Finished: 'progress-bar-success', }; const getLabelClass = (state: RequestState): string => LabelClasses[state] || 'label-info'; export const ExpertRequestState = (props: ExpertRequestStateProps) => ( <div className="progress pull-left state-indicator m-b-none"> <span className={classNames(getLabelClass(props.model.state), 'progress-bar', 'p-w-sm', 'full-width')}> {props.model.state.toUpperCase()} </span> </div> ); export default react2angular(ExpertRequestState, ['model']);
import * as classNames from 'classnames'; import * as React from 'react'; import { react2angular } from 'react2angular'; import { RequestState } from './types'; interface ExpertRequestStateProps { model: { state: RequestState; }; } const LabelClasses = { Active: '', Pending: 'progress-bar-warning', Cancelled: 'progress-bar-danger', Finished: 'progress-bar-success', }; const getLabelClass = (state: RequestState): string => LabelClasses[state] || 'label-info'; const getLabel = (state: RequestState): string => { if (state === 'Pending') { return 'Waiting for proposals'.toUpperCase(); } return state.toUpperCase(); }; export const ExpertRequestState = (props: ExpertRequestStateProps) => ( <div className="progress pull-left state-indicator m-b-none"> <span className={classNames(getLabelClass(props.model.state), 'progress-bar', 'p-w-sm', 'full-width')}> {getLabel(props.model.state)} </span> </div> ); export default react2angular(ExpertRequestState, ['model']);
Fix computeRadiationValue for scan measures
import { Store } from '@ngxs/store'; import { Observable } from 'rxjs'; import { Measure, Step } from '../measures/measure'; import { AbstractDevice } from './abstract-device'; export abstract class AbstractDeviceService<T extends AbstractDevice> { protected textDecoder = new TextDecoder('utf8'); constructor(protected store: Store) {} abstract getDeviceInfo(device: T): Observable<Partial<T>>; abstract saveDeviceParams(device: T): Observable<any>; abstract startMeasureScan(device: T, stopSignal: Observable<any>): Observable<Step>; computeRadiationValue(measure: Measure): number { if (measure.endTime && measure.hitsNumber) { const duration = (measure.endTime - measure.startTime) / 1000; const hitsNumberPerSec = measure.hitsNumber / duration; return this.convertHitsNumberPerSec(hitsNumberPerSec); } else { throw new Error('Incorrect measure : missing endTime or hitsNumber'); } } protected abstract convertHitsNumberPerSec(hitsNumberPerSec: number): number; abstract connectDevice(device: T): Observable<any>; abstract disconnectDevice(device: T): Observable<any>; protected abstract decodeDataPackage(buffer: ArrayBuffer | ArrayBuffer[]): Step | null; }
import { Store } from '@ngxs/store'; import { Observable } from 'rxjs'; import { Measure, Step } from '../measures/measure'; import { AbstractDevice } from './abstract-device'; export abstract class AbstractDeviceService<T extends AbstractDevice> { protected textDecoder = new TextDecoder('utf8'); constructor(protected store: Store) {} abstract getDeviceInfo(device: T): Observable<Partial<T>>; abstract saveDeviceParams(device: T): Observable<any>; abstract startMeasureScan(device: T, stopSignal: Observable<any>): Observable<Step>; computeRadiationValue(measure: Measure): number { if (measure.endTime && measure.hitsNumber !== undefined) { const duration = (measure.endTime - measure.startTime) / 1000; const hitsNumberPerSec = measure.hitsNumber / duration; return this.convertHitsNumberPerSec(hitsNumberPerSec); } else { throw new Error('Incorrect measure : missing endTime or hitsNumber'); } } protected abstract convertHitsNumberPerSec(hitsNumberPerSec: number): number; abstract connectDevice(device: T): Observable<any>; abstract disconnectDevice(device: T): Observable<any>; protected abstract decodeDataPackage(buffer: ArrayBuffer | ArrayBuffer[]): Step | null; }
Allow text to be entered into custom css editor
import * as React from "react"; import { ChangeEvent } from "react"; import { ColorResult, SketchPicker } from "react-color"; import { PlayerViewCustomStyles } from "../../../common/PlayerViewSettings"; import { StylesChooser } from "./StylesChooser"; export interface CustomCSSEditorProps { currentCSS: string; currentStyles: PlayerViewCustomStyles; updateCSS: (css: string) => void; updateStyle: (name: keyof PlayerViewCustomStyles, value: string) => void; } interface State { manualCSS: string; } export class CustomCSSEditor extends React.Component<CustomCSSEditorProps, State> { constructor(props: CustomCSSEditorProps) { super(props); this.state = { manualCSS: this.props.currentCSS }; } private updateCSS = (event: ChangeEvent<HTMLTextAreaElement>) => { this.setState({ manualCSS: event.target.value }); this.props.updateCSS(event.target.value); } public render() { return <div className="custom-css-editor"> <p>Epic Initiative is enabled.</p> <StylesChooser currentStyles={this.props.currentStyles} updateStyle={this.props.updateStyle} /> <h4>Additional CSS</h4> <textarea rows={10} onChange={this.updateCSS} value={this.props.currentCSS} /> </div>; } }
import * as React from "react"; import { ChangeEvent } from "react"; import { ColorResult, SketchPicker } from "react-color"; import { PlayerViewCustomStyles } from "../../../common/PlayerViewSettings"; import { StylesChooser } from "./StylesChooser"; export interface CustomCSSEditorProps { currentCSS: string; currentStyles: PlayerViewCustomStyles; updateCSS: (css: string) => void; updateStyle: (name: keyof PlayerViewCustomStyles, value: string) => void; } interface State { manualCSS: string; } export class CustomCSSEditor extends React.Component<CustomCSSEditorProps, State> { constructor(props: CustomCSSEditorProps) { super(props); this.state = { manualCSS: this.props.currentCSS }; } private updateCSS = (event: ChangeEvent<HTMLTextAreaElement>) => { this.setState({ manualCSS: event.target.value }); this.props.updateCSS(event.target.value); } public render() { return <div className="custom-css-editor"> <p>Epic Initiative is enabled.</p> <StylesChooser currentStyles={this.props.currentStyles} updateStyle={this.props.updateStyle} /> <h4>Additional CSS</h4> <textarea rows={10} onChange={this.updateCSS} value={this.state.manualCSS} /> </div>; } }
Add ability to disable rows from being sorted
import { ReactNode } from 'react'; import Icon from '../icon/Icon'; import { TableRow } from '../table'; import { OrderableElement, OrderableHandle } from '../orderable'; interface Props { index: number; className?: string; cells?: ReactNode[]; } const OrderableTableRow = ({ index, cells = [], className, ...rest }: Props) => ( <OrderableElement index={index}> <TableRow cells={[ <OrderableHandle key="icon"> <span className="flex" data-testid="table:order-icon"> <Icon className="mtauto mbauto cursor-row-resize" name="align-justify" /> </span> </OrderableHandle>, ...cells, ]} className={className} {...rest} /> </OrderableElement> ); export default OrderableTableRow;
import { ReactNode } from 'react'; import Icon from '../icon/Icon'; import { TableRow } from '../table'; import { OrderableElement, OrderableHandle } from '../orderable'; interface Props { index: number; className?: string; cells?: ReactNode[]; disableSort?: boolean; } const OrderableTableRow = ({ index, cells = [], className, disableSort, ...rest }: Props) => { if (disableSort) { return <TableRow cells={['', ...cells]} className={className} {...rest} />; } return ( <OrderableElement index={index}> <TableRow cells={[ <OrderableHandle key="icon"> <span className="flex" data-testid="table:order-icon"> <Icon className="mtauto mbauto cursor-row-resize" name="align-justify" /> </span> </OrderableHandle>, ...cells, ]} className={className} {...rest} /> </OrderableElement> ); }; export default OrderableTableRow;
Fix storybook issue trying to import type only json-schema package
import { FormatValidator, FormatDefinition } from 'ajv'; import { UiSchema as rjsfUiSchema } from '@rjsf/core'; import { Widget } from './widgets/widget-util'; export { JSONSchema7 as JSONSchema } from 'json-schema'; export const JsonTypes = { array: 'array', object: 'object', number: 'number', integer: 'integer', string: 'string', boolean: 'boolean', null: 'null', } as const; export interface JsonTypesTypeMap { array: unknown[]; object: {}; number: number; integer: number; string: string; boolean: boolean; null: null; } export type DefinedValue = | number | string | boolean | { [key: string]: any } | any[]; export type Value = DefinedValue | null; export interface UiSchema extends Pick<rjsfUiSchema, 'ui:options' | 'ui:order'> { 'ui:widget'?: string; 'ui:title'?: string; 'ui:description'?: string; 'ui:value'?: Value; } export interface Format { name: string; format: FormatValidator | FormatDefinition; widget?: Widget; }
import { FormatValidator, FormatDefinition } from 'ajv'; import { UiSchema as rjsfUiSchema } from '@rjsf/core'; import { Widget } from './widgets/widget-util'; export type { JSONSchema7 as JSONSchema } from 'json-schema'; export const JsonTypes = { array: 'array', object: 'object', number: 'number', integer: 'integer', string: 'string', boolean: 'boolean', null: 'null', } as const; export interface JsonTypesTypeMap { array: unknown[]; object: {}; number: number; integer: number; string: string; boolean: boolean; null: null; } export type DefinedValue = | number | string | boolean | { [key: string]: any } | any[]; export type Value = DefinedValue | null; export interface UiSchema extends Pick<rjsfUiSchema, 'ui:options' | 'ui:order'> { 'ui:widget'?: string; 'ui:title'?: string; 'ui:description'?: string; 'ui:value'?: Value; } export interface Format { name: string; format: FormatValidator | FormatDefinition; widget?: Widget; }
Change the page-header component to import template.
import { Component, Inject, Input } from 'ng-metadata/core'; @Component({ selector: 'gj-page-header', templateUrl: '/app/components/page-header/page-header.html', legacy: { transclude: { coverButtons: '?gjPageHeaderCoverButtons', content: 'gjPageHeaderContent', spotlight: '?gjPageHeaderSpotlight', nav: '?gjPageHeaderNav', controls: '?gjPageHeaderControls', } }, }) export class PageHeaderComponent { @Input( '<?' ) coverMediaItem: any; @Input( '<?' ) shouldAffixNav: boolean; constructor( @Inject( 'Screen' ) private screen: any ) { } }
import { Component, Inject, Input } from 'ng-metadata/core'; import template from './page-header.html'; @Component({ selector: 'gj-page-header', templateUrl: template, legacy: { transclude: { coverButtons: '?gjPageHeaderCoverButtons', content: 'gjPageHeaderContent', spotlight: '?gjPageHeaderSpotlight', nav: '?gjPageHeaderNav', controls: '?gjPageHeaderControls', } }, }) export class PageHeaderComponent { @Input( '<?' ) coverMediaItem: any; @Input( '<?' ) shouldAffixNav: boolean; constructor( @Inject( 'Screen' ) private screen: any ) { } }
Use the user's endpoint when creating an API
import User from '../user' const Octokat = require('octokat') export interface Repo { cloneUrl: string, htmlUrl: string, name: string owner: { avatarUrl: string, login: string type: 'user' | 'org' }, private: boolean, stargazersCount: number } export default class API { private client: any public constructor(user: User) { // TODO: Use the user's endpoint this.client = new Octokat({token: user.getToken()}) } public async fetchRepos(): Promise<Repo[]> { const results: Repo[] = [] let nextPage = this.client.user.repos while (nextPage) { const request = await nextPage.fetch() results.push(...request.items) nextPage = request.nextPage } return results } }
import User from '../user' const Octokat = require('octokat') export interface Repo { cloneUrl: string, htmlUrl: string, name: string owner: { avatarUrl: string, login: string type: 'user' | 'org' }, private: boolean, stargazersCount: number } export default class API { private client: any public constructor(user: User) { this.client = new Octokat({token: user.getToken(), rootURL: user.getEndpoint()}) } public async fetchRepos(): Promise<Repo[]> { const results: Repo[] = [] let nextPage = this.client.user.repos while (nextPage) { const request = await nextPage.fetch() results.push(...request.items) nextPage = request.nextPage } return results } }
Clear localstorage release notes flag
import {Extension} from './extension'; // Initialize extension const extension = new Extension(); extension.start(); chrome.runtime.onInstalled.addListener(({reason}) => { if (reason === 'install') { // TODO: Show help page. chrome.tabs.create({url: 'http://darkreader.org/blog/dynamic-theme/'}); extension.news.markAsRead('dynamic-theme'); } }); declare const __DEBUG__: boolean; const DEBUG = __DEBUG__; if (DEBUG) { // Reload extension on connection const listen = () => { const req = new XMLHttpRequest(); req.open('GET', 'http://localhost:8890/', true); req.overrideMimeType('text/plain'); req.onload = () => { if (req.status >= 200 && req.status < 300 && req.responseText === 'reload') { chrome.runtime.reload(); } else { setTimeout(listen, 2000); } }; req.onerror = () => setTimeout(listen, 2000); req.send(); }; setTimeout(listen, 2000); }
import {Extension} from './extension'; // Initialize extension const extension = new Extension(); extension.start(); chrome.runtime.onInstalled.addListener(({reason}) => { if (reason === 'install') { // TODO: Show help page. chrome.tabs.create({url: 'http://darkreader.org/blog/dynamic-theme/'}); extension.news.markAsRead('dynamic-theme'); } if (Boolean(localStorage.getItem('darkreader-4-release-notes-shown'))) { extension.news.markAsRead('dynamic-theme') .then(() => localStorage.removeItem('darkreader-4-release-notes-shown')); } }); declare const __DEBUG__: boolean; const DEBUG = __DEBUG__; if (DEBUG) { // Reload extension on connection const listen = () => { const req = new XMLHttpRequest(); req.open('GET', 'http://localhost:8890/', true); req.overrideMimeType('text/plain'); req.onload = () => { if (req.status >= 200 && req.status < 300 && req.responseText === 'reload') { chrome.runtime.reload(); } else { setTimeout(listen, 2000); } }; req.onerror = () => setTimeout(listen, 2000); req.send(); }; setTimeout(listen, 2000); }
Disable recording network activity in dev tools for now.
import { NativeModules } from "react-native" const { Emission } = NativeModules let metaphysicsURL let gravityURL if (Emission && Emission.gravityAPIHost && Emission.metaphysicsAPIHost) { metaphysicsURL = Emission.metaphysicsAPIHost gravityURL = Emission.gravityAPIHost } else { metaphysicsURL = "https://metaphysics-production.artsy.net" gravityURL = "https://api.artsy.net" } export { metaphysicsURL, gravityURL } // Disable the native polyfill during development, which will make network requests show-up in the Chrome dev-tools. // Specifically, in our case, we get to see the Relay requests. // // It will be `undefined` unless running inside Chrome. // declare var global: any if (__DEV__ && global.originalXMLHttpRequest !== undefined) { global.XMLHttpRequest = global.originalXMLHttpRequest // tslint:disable-next-line:no-var-requires require("react-relay/lib/RelayNetworkDebug").init() }
import { NativeModules } from "react-native" const { Emission } = NativeModules let metaphysicsURL let gravityURL if (Emission && Emission.gravityAPIHost && Emission.metaphysicsAPIHost) { metaphysicsURL = Emission.metaphysicsAPIHost gravityURL = Emission.gravityAPIHost } else { metaphysicsURL = "https://metaphysics-production.artsy.net" gravityURL = "https://api.artsy.net" } export { metaphysicsURL, gravityURL } // Disable the native polyfill during development, which will make network requests show-up in the Chrome dev-tools. // Specifically, in our case, we get to see the Relay requests. // // It will be `undefined` unless running inside Chrome. // declare var global: any if (__DEV__ && global.originalXMLHttpRequest !== undefined) { /** * TODO: Recording network access in Chrome Dev Tools is disabled for now. * * @see https://github.com/jhen0409/react-native-debugger/issues/209 */ // global.XMLHttpRequest = global.originalXMLHttpRequest // tslint:disable-next-line:no-var-requires require("react-relay/lib/RelayNetworkDebug").init() }
Fix documentation: s/public credential/public key credential/
import {base64urlToBuffer, bufferToBase64url} from "./base64url"; import {CredentialCreationOptionsJSON, CredentialRequestOptionsJSON, PublicKeyCredentialWithAssertionJSON, PublicKeyCredentialWithAttestationJSON} from "./json"; import {convert} from "./schema-format"; import {credentialCreationOptions, credentialRequestOptions, publicKeyCredentialWithAssertion, publicKeyCredentialWithAttestation} from "./webauthn-schema"; export async function create(requestJSON: CredentialCreationOptionsJSON): Promise<PublicKeyCredentialWithAttestationJSON> { const request = convert(base64urlToBuffer, credentialCreationOptions, requestJSON); const credential = (await navigator.credentials.create(request)) as PublicKeyCredential; return convert(bufferToBase64url, publicKeyCredentialWithAttestation, credential); } export async function get(requestJSON: CredentialRequestOptionsJSON): Promise<PublicKeyCredentialWithAssertionJSON> { const request = convert(base64urlToBuffer, credentialRequestOptions, requestJSON); const response = (await navigator.credentials.get(request)) as PublicKeyCredential; return convert(bufferToBase64url, publicKeyCredentialWithAssertion, response); } declare global { interface Window { PublicKeyCredential: any | undefined; } } // This function does a simple check to test for the credential management API // functions we need, and an indication of public credential authentication // support. // https://developers.google.com/web/updates/2018/03/webauthn-credential-management export function supported(): boolean { return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get && window.PublicKeyCredential); }
import {base64urlToBuffer, bufferToBase64url} from "./base64url"; import {CredentialCreationOptionsJSON, CredentialRequestOptionsJSON, PublicKeyCredentialWithAssertionJSON, PublicKeyCredentialWithAttestationJSON} from "./json"; import {convert} from "./schema-format"; import {credentialCreationOptions, credentialRequestOptions, publicKeyCredentialWithAssertion, publicKeyCredentialWithAttestation} from "./webauthn-schema"; export async function create(requestJSON: CredentialCreationOptionsJSON): Promise<PublicKeyCredentialWithAttestationJSON> { const request = convert(base64urlToBuffer, credentialCreationOptions, requestJSON); const credential = (await navigator.credentials.create(request)) as PublicKeyCredential; return convert(bufferToBase64url, publicKeyCredentialWithAttestation, credential); } export async function get(requestJSON: CredentialRequestOptionsJSON): Promise<PublicKeyCredentialWithAssertionJSON> { const request = convert(base64urlToBuffer, credentialRequestOptions, requestJSON); const response = (await navigator.credentials.get(request)) as PublicKeyCredential; return convert(bufferToBase64url, publicKeyCredentialWithAssertion, response); } declare global { interface Window { PublicKeyCredential: any | undefined; } } // This function does a simple check to test for the credential management API // functions we need, and an indication of public key credential authentication // support. // https://developers.google.com/web/updates/2018/03/webauthn-credential-management export function supported(): boolean { return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get && window.PublicKeyCredential); }
Fix a test so that we don't get duplicate declaration errors.
//@target: ES6 //@declaration: true class C { static [Symbol.iterator] = 0; static [Symbol.toPrimitive]() { } static get [Symbol.toPrimitive]() { return ""; } static set [Symbol.toPrimitive](x) { } }
//@target: ES6 //@declaration: true class C { static [Symbol.iterator] = 0; static [Symbol.isConcatSpreadable]() { } static get [Symbol.toPrimitive]() { return ""; } static set [Symbol.toPrimitive](x) { } }
Add route to list available routes
/** * Express routes configurations */ export abstract class ExpressRouter { protected express: any; public abstract start(): void; constructor(express: any) { this.express = express; this.defaultRoutes(); } private defaultRoutes(): void { this.express.get("/", (req, res) => res.json({ status: "NTask API TEste" })); this.express.get("/routes", (req, res) => res.json({ routes: this.express._router.stack })); } }
/** * Express routes configurations */ export abstract class ExpressRouter { protected express: any; public abstract start(): void; constructor(express: any) { this.express = express; this.defaultRoutes(); } private defaultRoutes(): void { this.express.get("/", (req, res) => res.json({ status: "NTask API TEste" })); this.express.get("/routes", (req, res) => res.json({ routes: this.printRoutes() })); } private printRoutes(): string[] { let routes: string[] = []; this.express._router.stack.forEach(r => { if (r.route && r.route.path) { routes.push(r.route.path); } }); return routes; } }
Make type and category fields in offering configuration form non-clearable.
import * as React from 'react'; import { FieldArray } from 'redux-form'; import { SelectAsyncField, FormContainer, SelectField, } from '@waldur/form-react'; import { OfferingAttributes } from './OfferingAttributes'; import { OfferingOptions } from './OfferingOptions'; import { OfferingPlans } from './OfferingPlans'; export const OfferingConfigureStep = props => ( <> <FormContainer submitting={props.submitting} labelClass="col-sm-3" controlClass="col-sm-9" clearOnUnmount={false}> <SelectField name="type" label={props.translate('Type')} required={true} options={props.offeringTypes} /> <SelectAsyncField name="category" label={props.translate('Category')} loadOptions={props.loadCategories} required={true} labelKey="title" valueKey="url" /> </FormContainer> {props.category && <OfferingAttributes {...props}/>} <FieldArray name="plans" component={OfferingPlans} /> {props.showOptions && <FieldArray name="options" component={OfferingOptions}/>} </> );
import * as React from 'react'; import { FieldArray } from 'redux-form'; import { SelectAsyncField, FormContainer, SelectField, } from '@waldur/form-react'; import { OfferingAttributes } from './OfferingAttributes'; import { OfferingOptions } from './OfferingOptions'; import { OfferingPlans } from './OfferingPlans'; export const OfferingConfigureStep = props => ( <> <FormContainer submitting={props.submitting} labelClass="col-sm-3" controlClass="col-sm-9" clearOnUnmount={false}> <SelectField name="type" label={props.translate('Type')} required={true} options={props.offeringTypes} clearable={false} /> <SelectAsyncField name="category" label={props.translate('Category')} loadOptions={props.loadCategories} required={true} labelKey="title" valueKey="url" clearable={false} /> </FormContainer> {props.category && <OfferingAttributes {...props}/>} <FieldArray name="plans" component={OfferingPlans} /> {props.showOptions && <FieldArray name="options" component={OfferingOptions}/>} </> );
Increase release version number to 1.0.4
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.3', RELEASEVERSION: '1.0.3' }; export = BaseConfig;
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.4', RELEASEVERSION: '1.0.4' }; export = BaseConfig;
Fix alias of username argument
import fs from 'fs'; import libpath from 'path'; import _yargs from 'yargs'; const packageInfo = JSON.parse(fs.readFileSync(libpath.resolve(__dirname, '../../package.json'), 'utf8')); const yargs = _yargs .demand(1) .usage( ` Upload-GPhotos ${packageInfo.version} Usage: upload-gphotos file [...] [--no-output-json] [--quiet] [-r retry] [-u username] [-p password] [-a albumname] `.trim(), ) .help('help') .options({ retry: { alias: 'r', type: 'number', default: 3, desc: 'The number of times to retry when failed uploads.', }, username: { alias: 'username', type: 'string', desc: 'Google account username.', }, password: { alias: 'p', type: 'string', desc: 'Google account password.', }, album: { alias: 'a', type: 'array', default: [] as string[], desc: 'An albums to put uploaded files.', }, quiet: { type: 'boolean', default: false, desc: 'Prevent to show progress.', }, 'output-json': { type: 'boolean', default: true, desc: 'Output information of uploading as JSON.', }, help: { alias: 'h', type: 'boolean', desc: 'Show help.', }, version: { alias: 'v', type: 'boolean', desc: 'Show version number.', }, }); export { yargs };
import fs from 'fs'; import libpath from 'path'; import _yargs from 'yargs'; const packageInfo = JSON.parse(fs.readFileSync(libpath.resolve(__dirname, '../../package.json'), 'utf8')); const yargs = _yargs .demand(1) .usage( ` Upload-GPhotos ${packageInfo.version} Usage: upload-gphotos file [...] [--no-output-json] [--quiet] [-r retry] [-u username] [-p password] [-a albumname] `.trim(), ) .help('help') .options({ retry: { alias: 'r', type: 'number', default: 3, desc: 'The number of times to retry when failed uploads.', }, username: { alias: 'u', type: 'string', desc: 'Google account username.', }, password: { alias: 'p', type: 'string', desc: 'Google account password.', }, album: { alias: 'a', type: 'array', default: [] as string[], desc: 'An albums to put uploaded files.', }, quiet: { type: 'boolean', default: false, desc: 'Prevent to show progress.', }, 'output-json': { type: 'boolean', default: true, desc: 'Output information of uploading as JSON.', }, help: { alias: 'h', type: 'boolean', desc: 'Show help.', }, version: { alias: 'v', type: 'boolean', desc: 'Show version number.', }, }); export { yargs };
FIX incorrect style usage of numbers in addon-center
const styles = { style: { position: 'fixed', top: 0, left: 0, bottom: 0, right: 0, display: 'flex', alignItems: 'center', overflow: 'auto', }, innerStyle: { margin: 'auto', maxHeight: '100%', // Hack for centering correctly in IE11 }, } as const; export default styles;
const styles = { style: { position: 'fixed', top: '0', left: '0', bottom: '0', right: '0', display: 'flex', alignItems: 'center', overflow: 'auto', }, innerStyle: { margin: 'auto', maxHeight: '100%', // Hack for centering correctly in IE11 }, } as const; export default styles;
Make types compatible with TS <= 3.6
declare class OrderedMap<T = any> { private constructor(content: Array<string | T>) get(key: string): T | undefined update(key: string, value: T, newKey?: string): OrderedMap<T> remove(key: string): OrderedMap<T> addToStart(key: string, value: T): OrderedMap<T> addToEnd(key: string, value: T): OrderedMap<T> addBefore(place: string, key: string, value: T): OrderedMap<T> forEach(fn: (key: string, value: T) => any): void prepend(map: MapLike<T>): OrderedMap<T> append(map: MapLike<T>): OrderedMap<T> subtract(map: MapLike<T>): OrderedMap<T> get size(): number static from<T>(map: MapLike<T>): OrderedMap<T> } type MapLike<T = any> = Record<string, T> | OrderedMap<T> export = OrderedMap
declare class OrderedMap<T = any> { private constructor(content: Array<string | T>) get(key: string): T | undefined update(key: string, value: T, newKey?: string): OrderedMap<T> remove(key: string): OrderedMap<T> addToStart(key: string, value: T): OrderedMap<T> addToEnd(key: string, value: T): OrderedMap<T> addBefore(place: string, key: string, value: T): OrderedMap<T> forEach(fn: (key: string, value: T) => any): void prepend(map: MapLike<T>): OrderedMap<T> append(map: MapLike<T>): OrderedMap<T> subtract(map: MapLike<T>): OrderedMap<T> readonly size: number static from<T>(map: MapLike<T>): OrderedMap<T> } type MapLike<T = any> = Record<string, T> | OrderedMap<T> export = OrderedMap
Use store2 instead of direct localStorage.
import { window } from 'global'; import { useCallback, useEffect, useState } from 'react'; import { Selection, StoryRef } from './types'; const retrieveLastViewedStoryIds = (): StoryRef[] => { try { const raw = window.localStorage.getItem('lastViewedStoryIds'); const val = typeof raw === 'string' && JSON.parse(raw); if (!val || !Array.isArray(val)) return []; if (!val.some((item) => typeof item === 'object' && item.storyId && item.refId)) return []; return val; } catch (e) { return []; } }; const storeLastViewedStoryIds = (items: StoryRef[]) => { try { window.localStorage.setItem('lastViewedStoryIds', JSON.stringify(items)); } catch (e) { // do nothing } }; export const useLastViewed = (selection: Selection) => { const [lastViewed, setLastViewed] = useState(retrieveLastViewedStoryIds); const updateLastViewed = useCallback( (story: StoryRef) => setLastViewed((state: StoryRef[]) => { const index = state.findIndex( ({ storyId, refId }) => storyId === story.storyId && refId === story.refId ); if (index === 0) return state; const update = index === -1 ? [story, ...state] : [story, ...state.slice(0, index), ...state.slice(index + 1)]; storeLastViewedStoryIds(update); return update; }), [] ); useEffect(() => { if (selection) updateLastViewed(selection); }, [selection]); return lastViewed; };
import { useCallback, useEffect, useState } from 'react'; import store from 'store2'; import { Selection, StoryRef } from './types'; const retrieveLastViewedStoryIds = (): StoryRef[] => { const items = store.get('lastViewedStoryIds'); if (!items || !Array.isArray(items)) return []; if (!items.some((item) => typeof item === 'object' && item.storyId && item.refId)) return []; return items; }; export const useLastViewed = (selection: Selection) => { const [lastViewed, setLastViewed] = useState(retrieveLastViewedStoryIds); const updateLastViewed = useCallback( (story: StoryRef) => setLastViewed((state: StoryRef[]) => { const index = state.findIndex( ({ storyId, refId }) => storyId === story.storyId && refId === story.refId ); if (index === 0) return state; const update = index === -1 ? [story, ...state] : [story, ...state.slice(0, index), ...state.slice(index + 1)]; store.set('lastViewedStoryIds', update); return update; }), [] ); useEffect(() => { if (selection) updateLastViewed(selection); }, [selection]); return lastViewed; };
Revert "Commit from LXDE Pootle server by user LStranger.: 391 of 391 strings translated (0 need review)."
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0"> <context> <name>ShowDesktop</name> <message> <source>Show Desktop: Global shortcut &apos;%1&apos; cannot be registered</source> <translation>Показать рабочий стол: Глобальное короткие клавиш &apos;%1&apos; не могут быть зарегистрированы</translation> </message> <message> <source>Show Desktop</source> <translation>Показать рабочий стол</translation> </message> </context> </TS>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="ru"> <context> <name>ShowDesktop</name> <message> <location filename="../showdesktop.cpp" line="44"/> <source>Show desktop</source> <translation>Показать рабочий стол</translation> </message> <message> <location filename="../showdesktop.cpp" line="54"/> <source>Show Desktop: Global shortcut &apos;%1&apos; cannot be registered</source> <translation>Показать рабочий стол: глобальное сочетание клавиш &apos;%1&apos; не может быть зарегистрировано</translation> </message> <message> <location filename="../showdesktop.cpp" line="59"/> <source>Show Desktop</source> <translation>Показать рабочий стол</translation> </message> </context> </TS>
Add scope and fix templateUrl:
import { SearchController } from './search.controller'; export function digimapSearch(): ng.IDirective { return { restrict: 'E', templateUrl: '/app/components/search/search.html', controller: SearchController, controllerAs: 'vm' }; }
import { SearchController } from './search.controller'; export function digimapSearch(): ng.IDirective { return { restrict: 'E', scope: { extraValues: '=' }, templateUrl: 'app/components/search/search.html', controller: SearchController, controllerAs: 'vm' }; }
Delete useless trailing white spaces
export class TwitterApplicationComponent implements ng.IComponentOptions { public template: string = ` <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#/">Tweet app</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="#/" title="Tweets">Tweets</a></li> <li><a href="#/about" title="About">About</a></li> </ul> </div> </div> </nav> <div ng-view></div>`; }
export class TwitterApplicationComponent implements ng.IComponentOptions { public template: string = ` <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#/">Tweet app</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="#/" title="Tweets">Tweets</a></li> <li><a href="#/about" title="About">About</a></li> </ul> </div> </div> </nav> <div ng-view></div>`; }
Merge module and component as default behavior.
import { chain, externalSchematic, Rule } from '@angular-devkit/schematics'; import { Schema as NgComponentOptions } from '@schematics/angular/component/schema'; import { findModuleFromOptions } from '@schematics/angular/utility/find-module'; import { buildDefaultPath, getProject } from '@schematics/angular/utility/project'; export interface ScamOptions extends NgComponentOptions { separateModule: boolean; } export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => { const project = getProject(tree, options.project); const modulePath = findModuleFromOptions(tree, { ...options, path: options.path || buildDefaultPath(project) }); tree.read(modulePath); return tree; }; 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, _mergeModuleIntoComponentFile(options) ]; } return chain(ruleList); }
import { chain, externalSchematic, Rule } from '@angular-devkit/schematics'; import { Schema as NgComponentOptions } from '@schematics/angular/component/schema'; import { findModuleFromOptions } from '@schematics/angular/utility/find-module'; import { buildDefaultPath, getProject } from '@schematics/angular/utility/project'; export interface ScamOptions extends NgComponentOptions { separateModule: boolean; } export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => { const project = getProject(tree, options.project); const modulePath = findModuleFromOptions(tree, { ...options, path: options.path || buildDefaultPath(project) }); tree.read(modulePath); // @todo: read module content. // @todo: merge module content in component. // @todo: remove module file. return tree; }; 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, _mergeModuleIntoComponentFile(options) ]; } return chain(ruleList); }
Fix uncaught exception in request
import * as http from 'http'; import * as https from 'https'; export default { test: (uri: string): boolean => /^https*:\/\//.test(uri), read: (url: string): Promise<http.IncomingMessage> => { return new Promise((resolve, reject) => { const get = url.indexOf('https') === 0 ? https.get : http.get; // @ts-ignore get(url, (res) => { const statusCode = res['statusCode']; const contentType = res['headers']['content-type']; if (statusCode === 200 && contentType.indexOf('audio/mpeg') > -1) { resolve(res); } else { reject({ statusCode: statusCode, contentType: contentType }); } }); }); } }
import * as http from 'http'; import * as https from 'https'; export default { test: (uri: string): boolean => /^https*:\/\//.test(uri), read: (url: string): Promise<http.IncomingMessage> => { return new Promise((resolve, reject) => { const get = url.indexOf('https') === 0 ? https.get : http.get; let res_ = null; const onError = (err) => { if (res_) { res_.emit('error', err); } }; const clientRequest = get(url, (res) => { const statusCode = res['statusCode']; const contentType = res['headers']['content-type']; if (statusCode === 200 && contentType.indexOf('audio/mpeg') > -1) { const onEnd = () => { clientRequest.off('error', onError); res.off('end', onEnd); }; res.on('end', onEnd); res_ = res; resolve(res); } else { reject({ statusCode: statusCode, contentType: contentType }); } }); clientRequest.on('error', onError); }); }, };
Set default export path to file location path
import { app, BrowserWindow, dialog } from 'electron' import { basename } from 'path' import { supportedFiles } from '../ui/settings/supported-files' export function showOpenDialog(mainWindow: BrowserWindow): Promise<string> { return new Promise((resolve) => { dialog.showOpenDialog( mainWindow!, { filters: [{ name: '', extensions: removeDotFromExtensions(supportedFiles) }], properties: ['openFile'] }, (filePaths: string[]) => { if (!filePaths) return resolve(filePaths[0]) } ) }) } export function showExportDialog(mainWindow: BrowserWindow, fileName: string): Promise<string> { return new Promise((resolve) => { dialog.showSaveDialog( mainWindow!, { defaultPath: `${app.getPath('downloads')}/${basename(fileName)}.png` }, (selectedFileName: string) => { if (!selectedFileName) return resolve(selectedFileName) } ) }) } function removeDotFromExtensions(extt: string[]): string[] { const res: string[] = [] extt.forEach((element) => { res.push(element.substring(1)) }) return res }
import { BrowserWindow, dialog } from 'electron' import { basename } from 'path' import { supportedFiles } from '../ui/settings/supported-files' export function showOpenDialog(mainWindow: BrowserWindow): Promise<string> { return new Promise((resolve) => { dialog.showOpenDialog( mainWindow!, { filters: [{ name: '', extensions: removeDotFromExtensions(supportedFiles) }], properties: ['openFile'] }, (filePaths: string[]) => { if (!filePaths) return resolve(filePaths[0]) } ) }) } export function showExportDialog(mainWindow: BrowserWindow, fileName: string): Promise<string> { return new Promise((resolve) => { dialog.showSaveDialog( mainWindow!, { defaultPath: `${basename(fileName)}.png` }, (selectedFileName: string) => { if (!selectedFileName) return resolve(selectedFileName) } ) }) } function removeDotFromExtensions(extension: string[]): string[] { const result: string[] = [] extension.forEach((element) => { result.push(element.substring(1)) }) return result }
Discard milliseconds when parsing dates (sqlite doesn't do milliseconds for datetime)
import {Schema, transform, arrayOf} from "idealizr"; export const game = new Schema("games"); export const user = new Schema("users"); export const collection = new Schema("collections"); export const downloadKey = new Schema("downloadKeys"); function parseDate(input: string) { // without `+0` it parses a local date - this is the fastest // way to parse a UTC date. // see https://jsperf.com/parse-utc-date return new Date(input + "+0"); } const date = transform(parseDate); game.define({ user, created_at: date, published_at: date, }); collection.define({ games: arrayOf(game), created_at: date, updated_at: date, }); downloadKey.define({ game, created_at: date, updated_at: date, });
import {Schema, transform, arrayOf} from "idealizr"; export const game = new Schema("games"); export const user = new Schema("users"); export const collection = new Schema("collections"); export const downloadKey = new Schema("downloadKeys"); function parseDate(input: string) { // without `+0` it parses a local date - this is the fastest // way to parse a UTC date. // see https://jsperf.com/parse-utc-date const date = new Date(input + "+0"); // we don't store milliseconds in the db anyway, // so let's just discard it here date.setMilliseconds(0); return date; } const date = transform(parseDate); game.define({ user, created_at: date, published_at: date, }); collection.define({ games: arrayOf(game), created_at: date, updated_at: date, }); downloadKey.define({ game, created_at: date, updated_at: date, });
Call done() when async task finishes
import { getResolvedLocale } from '../helpers/get-resolved-locale.js'; import { APP_INDEX_URL } from './constants.js'; import { ok, strictEqual, } from './helpers/typed-assert.js'; describe('timezones', () => { before(async () => { await browser.url(APP_INDEX_URL); }); function hasFullICU() { try { const january = new Date(9e8); const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); return spanish.format(january) === 'enero'; } catch (err) { return false; } } it(`supports full ICU`, async () => { ok(hasFullICU()); strictEqual( Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: 'numeric', }).format(new Date('2020-02-02')), 'Feb 2, 2020' ); strictEqual(getResolvedLocale(), 'en-US'); const content = await browser.executeAsync(async () => { const a = document.createElement('app-datepicker'); document.body.appendChild(a); await a.updateComplete; return ( Array.from( a.shadowRoot?.querySelectorAll('.full-calendar__day') ?? [] )[2]?.outerHTML ?? 'nil' ); }); console.debug('1', content); strictEqual(content, ''); }); });
import { getResolvedLocale } from '../helpers/get-resolved-locale.js'; import { APP_INDEX_URL } from './constants.js'; import { ok, strictEqual, } from './helpers/typed-assert.js'; describe('timezones', () => { before(async () => { await browser.url(APP_INDEX_URL); }); function hasFullICU() { try { const january = new Date(9e8); const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); return spanish.format(january) === 'enero'; } catch (err) { return false; } } it(`supports full ICU`, async () => { ok(hasFullICU()); strictEqual( Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: 'numeric', }).format(new Date('2020-02-02')), 'Feb 2, 2020' ); strictEqual(getResolvedLocale(), 'en-US'); const content = await browser.executeAsync(async (done) => { const a = document.createElement('app-datepicker'); document.body.appendChild(a); await a.updateComplete; done( Array.from( a.shadowRoot?.querySelectorAll('.full-calendar__day') ?? [] )[2]?.outerHTML ?? 'nil' ); }); console.debug('1', content); strictEqual(content, ''); }); });
Make datastore helpers test meaningful
import { isProjectDocument } from "../../src/datastore/helpers"; describe('helpers', () => { it('isProjectDocument', () => { const result = isProjectDocument({ resource: { id: 'project' }} as any); expect(true).toBeTruthy(); }); });
import { isProjectDocument } from '../../src/datastore/helpers'; describe('helpers', () => { it('isProjectDocument', () => { const result = isProjectDocument({ resource: { id: 'project' }} as any); expect(result).toBeTruthy(); }); });
Use constructor to set state
import React, { Component } from "react" import styled from "styled-components" import { NewsHeadline } from "../News/NewsHeadline" import { NewsSections } from "../News/NewsSections" interface Props { article: any isTruncated?: boolean } interface State { isTruncated: boolean } interface NewsContainerProps { isTruncated: boolean } export class NewsLayout extends Component<Props, State> { state = { isTruncated: this.props.isTruncated || true, } render() { const { article } = this.props const { isTruncated } = this.state return ( <NewsContainer onClick={() => this.setState({ isTruncated: false, })} isTruncated={isTruncated} > <NewsHeadline article={article} /> <NewsSections article={article} isTruncated={isTruncated} /> </NewsContainer> ) } } const NewsContainer = styled.div` max-width: 780px; margin: 40px auto; ${(props: NewsContainerProps) => props.isTruncated && ` &:hover { outline: 1px solid gray; outline-offset: 30px; } `}; `
import React, { Component } from "react" import styled from "styled-components" import { NewsHeadline } from "../News/NewsHeadline" import { NewsSections } from "../News/NewsSections" interface Props { article: any isTruncated?: boolean } interface State { isTruncated: boolean } interface NewsContainerProps { isTruncated: boolean } export class NewsLayout extends Component<Props, State> { constructor(props: Props) { super(props) this.state = { isTruncated: this.props.isTruncated || true, } } render() { const { article } = this.props const { isTruncated } = this.state return ( <NewsContainer onClick={() => this.setState({ isTruncated: false, })} isTruncated={isTruncated} > <NewsHeadline article={article} /> <NewsSections article={article} isTruncated={isTruncated} /> </NewsContainer> ) } } const NewsContainer = styled.div` max-width: 780px; margin: 40px auto; ${(props: NewsContainerProps) => props.isTruncated && ` &:hover { outline: 1px solid gray; outline-offset: 30px; } `}; `
Set minimum and maximum to transaction amount
import * as _ from 'lodash'; import * as moment from 'moment'; import { badRequest } from 'boom'; import * as Joi from 'joi'; namespace schemas { export const username = Joi.string().token().empty().min(2).max(20).label('Username'); export const password = Joi.string().empty().min(1).label('Password'); export const user = Joi.object().keys({ username, password }).options({ stripUnknown: true }).label('User'); export const transactionAmount = Joi.number().precision(2).label('Transaction amount'); export const groupName = Joi.string().min(4).max(255).label('Group name'); export const alternativeLoginKey = Joi.string().empty().label('Alternative login key'); export const timestamp = Joi.date().label('Timestamp'); } function validateSchema<T>(schema: Joi.Schema, value: T): T { const result = schema.validate(value); if (result.error) { throw badRequest(result.error.message, result.error.details); } return result.value; } export default { user: _.partial(validateSchema, schemas.user), username: _.partial(validateSchema, schemas.username), password: _.partial(validateSchema, schemas.password), transactionAmount: _.partial(validateSchema, schemas.transactionAmount), groupName: _.partial(validateSchema, schemas.groupName), alternativeLoginKey: _.partial(validateSchema, schemas.alternativeLoginKey), timestamp: (time: any): moment.Moment => moment(validateSchema(schemas.timestamp, time)).utc(), };
import * as _ from 'lodash'; import * as moment from 'moment'; import { badRequest } from 'boom'; import * as Joi from 'joi'; namespace schemas { export const username = Joi.string().token().empty().min(2).max(20).label('Username'); export const password = Joi.string().empty().min(1).label('Password'); export const user = Joi.object().keys({ username, password }).options({ stripUnknown: true }).label('User'); export const transactionAmount = Joi.number().precision(2).min(-1e+6).max(1e+6).label('Transaction amount'); export const groupName = Joi.string().min(4).max(255).label('Group name'); export const alternativeLoginKey = Joi.string().empty().label('Alternative login key'); export const timestamp = Joi.date().label('Timestamp'); } function validateSchema<T>(schema: Joi.Schema, value: T): T { const result = schema.validate(value); if (result.error) { throw badRequest(result.error.message, result.error.details); } return result.value; } export default { user: _.partial(validateSchema, schemas.user), username: _.partial(validateSchema, schemas.username), password: _.partial(validateSchema, schemas.password), transactionAmount: _.partial(validateSchema, schemas.transactionAmount), groupName: _.partial(validateSchema, schemas.groupName), alternativeLoginKey: _.partial(validateSchema, schemas.alternativeLoginKey), timestamp: (time: any): moment.Moment => moment(validateSchema(schemas.timestamp, time)).utc(), };
Add ability to unselect a team after picking
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { Game } from './game'; @Component({ selector: 'duel-game', templateUrl: './game.component.html', styleUrls: ['./game.component.css'], }) export class GameComponent { @Input() game: Game; @Output() onPicked = new EventEmitter<string>(); pick(team: string): void { this.game.selectedTeam = team; } isSelected(team: string): boolean { return this.game.selectedTeam === team; } }
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { Game } from './game'; @Component({ selector: 'duel-game', templateUrl: './game.component.html', styleUrls: ['./game.component.css'], }) export class GameComponent { @Input() game: Game; @Output() onPicked = new EventEmitter<string>(); pick(team: string): void { if (this.game.selectedTeam === team) { this.game.selectedTeam = undefined; } else { this.game.selectedTeam = team; } } isSelected(team: string): boolean { return this.game.selectedTeam === team; } }
Convert date to usable string to populate input
import {Component, Input, Output, OnInit, EventEmitter} from 'angular2/core'; import {FormBuilder, ControlGroup, Validators} from 'angular2/common'; import {Game} from '../shared/models/game.model'; @Component({ selector: 'agot-game-form', moduleId: module.id, templateUrl: './game-form.html', styleUrls: ['./game-form.css'] }) export class GameFormComponent implements OnInit { @Input() game:Game; @Output() submit = new EventEmitter<any>(); // TODO check type? gameForm:ControlGroup; constructor(private _FormBuilder:FormBuilder) { } ngOnInit() { this.serialiseGameToForm(); } onSubmit() { console.log(this.gameForm.value, this.game); this.deserialiseFormToGame(); // TODO //this.submit.emit(this.game); } private deserialiseFormToGame() { // set date to string // set deck from deckId? // set other? }; private serialiseGameToForm() { this.gameForm = this._FormBuilder.group({ date: [this.convertDateString(), Validators.required], coreSetCount: [this.game.coreSetCount, Validators.required], deckType: [this.game.deckType.deckTypeId, Validators.required], gamePlayers: [this.game.gamePlayers, Validators.required], }); }; private convertDateString() { // TODO what is the right bastard string format here? return this.game.date; }; }
import {Component, Input, Output, OnInit, EventEmitter} from 'angular2/core'; import {FormBuilder, ControlGroup, Validators} from 'angular2/common'; import {Game} from '../shared/models/game.model'; @Component({ selector: 'agot-game-form', moduleId: module.id, templateUrl: './game-form.html', styleUrls: ['./game-form.css'], }) export class GameFormComponent implements OnInit { @Input() game:Game; @Output() submit = new EventEmitter<any>(); // TODO check type? gameForm:ControlGroup; constructor(private _FormBuilder:FormBuilder) { } ngOnInit() { this.serialiseGameToForm(); } onSubmit() { console.log(this.gameForm.value, this.game); this.deserialiseFormToGame(); // TODO //this.submit.emit(this.game); } private deserialiseFormToGame() { // set date to string // set deck from deckId? // set other? }; private serialiseGameToForm() { this.gameForm = this._FormBuilder.group({ date: [this.convertDateString(), Validators.required], coreSetCount: [this.game.coreSetCount, Validators.required], deckType: [this.game.deckType.deckTypeId, Validators.required], gamePlayers: [this.game.gamePlayers, Validators.required], }); }; private convertDateString() { // have to remove the time and timezone to populate the control correctly return this.game.date.slice(0, 10); }; }
Allow nested links; fail a test
import { parseInlineConventions } from './ParseInlineConventions' import { TextConsumer } from '../TextConsumer' import { applyBackslashEscaping } from '../TextHelpers' import { LinkNode } from '../../SyntaxNodes/LinkNode' import { InlineParserArgs, InlineParser } from './InlineParser' export function parseLink(args: InlineParserArgs): boolean { const consumer = new TextConsumer(args.text) const linkNode = new LinkNode(args.parentNode) // Links cannot be nested within other links if (linkNode.ancestors().some(ancestor => ancestor instanceof LinkNode)) { return false } // TODO: Handle terminator? return ( // Parse the opening bracket consumer.consumeIfMatches('[') // Parse the link's content and the URL arrow && parseInlineConventions({ text: consumer.remainingText(), parentNode: linkNode, terminator: ' -> ', then: (resultNodes, lengthParsed) => { consumer.skip(lengthParsed) linkNode.addChildren(resultNodes) } }) // Parse the URL and the closing bracket && consumer.consumeUpTo({ needle: ']', then: (url) => { linkNode.url = applyBackslashEscaping(url) args.then([linkNode], consumer.lengthConsumed()) } }) ) }
import { parseInlineConventions } from './ParseInlineConventions' import { TextConsumer } from '../TextConsumer' import { applyBackslashEscaping } from '../TextHelpers' import { LinkNode } from '../../SyntaxNodes/LinkNode' import { InlineParserArgs, InlineParser } from './InlineParser' export function parseLink(args: InlineParserArgs): boolean { const consumer = new TextConsumer(args.text) const linkNode = new LinkNode(args.parentNode) // TODO: Handle terminator? return ( // Parse the opening bracket consumer.consumeIfMatches('[') // Parse the link's content and the URL arrow && parseInlineConventions({ text: consumer.remainingText(), parentNode: linkNode, terminator: ' -> ', then: (resultNodes, lengthParsed) => { consumer.skip(lengthParsed) linkNode.addChildren(resultNodes) } }) // Parse the URL and the closing bracket && consumer.consumeUpTo({ needle: ']', then: (url) => { linkNode.url = applyBackslashEscaping(url) args.then([linkNode], consumer.lengthConsumed()) } }) ) }
Fix "Form elements do not have associated labels"
import React, { useState, FunctionComponent, ChangeEvent } from "react"; type Props = { initialVolume: number; onChangeVolume: (volume: number) => void; }; const Component: FunctionComponent<Props> = props => { const [volume, setVolume] = useState(props.initialVolume); const onChange = (event: ChangeEvent<HTMLInputElement>) => { const volume = parseFloat(event.target.value); setVolume(volume); props.onChangeVolume(volume); }; return ( <form id="controls"> Volume{" "} <input type="range" min="0" max="1" step="0.01" value={volume} onChange={onChange} /> </form> ); }; export default Component;
import React, { useState, FunctionComponent, ChangeEvent } from "react"; type Props = { initialVolume: number; onChangeVolume: (volume: number) => void; }; const Component: FunctionComponent<Props> = props => { const [volume, setVolume] = useState(props.initialVolume); const onChange = (event: ChangeEvent<HTMLInputElement>) => { const volume = parseFloat(event.target.value); setVolume(volume); props.onChangeVolume(volume); }; return ( <form id="controls"> <label> Volume{" "} <input type="range" min="0" max="1" step="0.01" value={volume} onChange={onChange} /> </label> </form> ); }; export default Component;
Return unsuccessful on 429 error code.
import axios from 'axios'; import { API_URL } from '../constants'; // import { validateHitAccept } from '../utils/parsing'; export interface HitAcceptResponse { readonly successful: boolean; } /** * Strange code ahead, explanation: * * 1. This API call will *always* hit the catch block in production. * 2. This is because successfully accepting a HIT will redirect to a HTTP URL, * prompting the browser to cancel the request. * 3. Failing to accept a HIT will also hit the catch block because of a 404. * 4. We get the 404 only by sending in a nonsense string as the format. * 5. Therefore, if the request ends in a 404, the accept failed. * 6. Otherwise, it was successful. */ export const sendHitAcceptRequest = async ( groupId: string ): Promise<HitAcceptResponse> => { try { await axios.get<Document>( `${API_URL}/projects/${groupId}/tasks/accept_random`, { params: { format: 'gibberish' }, responseType: 'document' } ); return { successful: true }; } catch (e) { if (e.response && e.response.status === 404) { return { successful: false }; } else { return { successful: true }; } } };
import axios from 'axios'; import { API_URL } from '../constants'; import { validateHitAccept } from '../utils/parsing'; export interface HitAcceptResponse { readonly successful: boolean; } /** * Strange code ahead, explanation: * * 1. This API call will *always* hit the catch block in production. * 2. This is because successfully accepting a HIT will redirect to a HTTP URL, * prompting the browser to cancel the request. * 3. Failing to accept a HIT will also hit the catch block because of a 404. * 4. We get the 404 only by sending in a nonsense string as the format. * 5. Therefore, if the request ends in a 404, the accept failed. * 6. Otherwise, it was successful. */ export const sendHitAcceptRequest = async ( groupId: string ): Promise<HitAcceptResponse> => { try { const response = await axios.get<Document>( `${API_URL}/projects/${groupId}/tasks/accept_random`, { params: { format: 'gibberish' }, responseType: 'document' } ); return { successful: validateHitAccept(response.data) }; } catch (e) { if ( (e.response && e.response.status === 404) || (e.response && e.response.status === 429) ) { return { successful: false }; } else { return { successful: true }; } } };
Fix typo in printIncompatibleYarnError function
import { red, yellow } from "chalk" import { existsSync } from "fs" import { join } from "./path" import { applyPatch } from "./applyPatches" import { bold, green } from "chalk" const yarnPatchFile = join(__dirname, "../yarn.patch") export default function patchYarn(appPath: string) { try { applyPatch(yarnPatchFile) const yarnVersion = require(join( appPath, "node_modules", "yarn", "package.json", )).version console.log(`${bold("yarn")}@${yarnVersion} ${green("✔")}`) } catch (e) { if (existsSync(join(appPath, "node_modules", "yarn"))) { printIncompatibleYarnError() } else { printNoYarnWarning() } } } function printIncompatibleYarnError() { console.error(` ${red.bold("***ERROR***")} ${red(`This version of patch-package in incompatible with your current local version of yarn. Please update both.`)} `) } function printNoYarnWarning() { console.warn(` ${yellow.bold("***Warning***")} You asked patch-package to patch yarn, but you don't seem to have yarn installed `) }
import { red, yellow } from "chalk" import { existsSync } from "fs" import { join } from "./path" import { applyPatch } from "./applyPatches" import { bold, green } from "chalk" const yarnPatchFile = join(__dirname, "../yarn.patch") export default function patchYarn(appPath: string) { try { applyPatch(yarnPatchFile) const yarnVersion = require(join( appPath, "node_modules", "yarn", "package.json", )).version console.log(`${bold("yarn")}@${yarnVersion} ${green("✔")}`) } catch (e) { if (existsSync(join(appPath, "node_modules", "yarn"))) { printIncompatibleYarnError() } else { printNoYarnWarning() } } } function printIncompatibleYarnError() { console.error(` ${red.bold("***ERROR***")} ${red(`This version of patch-package is incompatible with your current local version of yarn. Please update both.`)} `) } function printNoYarnWarning() { console.warn(` ${yellow.bold("***Warning***")} You asked patch-package to patch yarn, but you don't seem to have yarn installed `) }
Move collection* to collections subdirectory.
import '../shims.js'; import { Component } from '@angular/core'; import { bootstrap } from '@angular/platform-browser-dynamic'; import { HTTP_PROVIDERS } from '@angular/http'; import { RESOURCE_PROVIDERS } from 'ng2-resource-rest'; import { CollectionsComponent } from './collections.component.ts'; @Component({ selector: 'qi-app', template: '<qi-collections></qi-collections>', directives: [CollectionsComponent] }) class AppComponent { } bootstrap(AppComponent, [HTTP_PROVIDERS, RESOURCE_PROVIDERS]);
import '../shims.js'; import { Component } from '@angular/core'; import { bootstrap } from '@angular/platform-browser-dynamic'; import { HTTP_PROVIDERS } from '@angular/http'; import { RESOURCE_PROVIDERS } from 'ng2-resource-rest'; import { CollectionsComponent } from './collections/collections.component.ts'; @Component({ selector: 'qi-app', template: '<qi-collections></qi-collections>', directives: [CollectionsComponent] }) class AppComponent { } bootstrap(AppComponent, [HTTP_PROVIDERS, RESOURCE_PROVIDERS]);
Tweak color of non-active state
import { color, Sans, sharedTabsStyles, space, TabsContainer, } from "@artsy/palette" import { Link, LinkProps } from "found" import React from "react" import styled from "styled-components" export const RouteTabs = styled(TabsContainer)` a { ${sharedTabsStyles.tabContainer}; :not(:last-child) { margin-right: ${space(3)}px; } color: ${color("black30")}; text-decoration: none; &.active { color: ${color("black100")}; ${sharedTabsStyles.activeTabContainer}; } } ` export const RouteTab: React.FC<LinkProps> = ({ children, ...props }) => { return ( <Link {...props} activeClassName="active"> <Sans size="3t" weight="medium"> {children} </Sans> </Link> ) } RouteTabs.displayName = "RouteTabs" RouteTab.displayName = "RouteTab"
import { color, Sans, sharedTabsStyles, space, TabsContainer, } from "@artsy/palette" import { Link, LinkProps } from "found" import React from "react" import styled from "styled-components" export const RouteTabs = styled(TabsContainer)` a { ${sharedTabsStyles.tabContainer}; :not(:last-child) { margin-right: ${space(3)}px; } color: ${color("black60")}; text-decoration: none; &.active { color: ${color("black100")}; ${sharedTabsStyles.activeTabContainer}; } } ` export const RouteTab: React.FC<LinkProps> = ({ children, ...props }) => { return ( <Link {...props} activeClassName="active"> <Sans size="3t" weight="medium"> {children} </Sans> </Link> ) } RouteTabs.displayName = "RouteTabs" RouteTab.displayName = "RouteTab"
Fix year formatting in accounting period selector.
import { DateTime } from 'luxon'; import { PeriodOption } from '@waldur/form/types'; export const reactSelectMenuPortaling = (): any => ({ menuPortalTarget: document.body, styles: { menuPortal: (base) => ({ ...base, zIndex: 9999 }) }, menuPosition: 'fixed', menuPlacement: 'bottom', }); export const datePickerOverlayContainerInDialogs = () => ({ calendarPlacement: 'bottom', calendarContainer: document.getElementsByClassName('modal-dialog')[0], }); export const makeLastTwelveMonthsFilterPeriods = (): PeriodOption[] => { let date = DateTime.now().startOf('month'); const choices = []; for (let i = 0; i < 12; i++) { const month = date.month; const year = date.year; const label = date.toFormat('MMMM, YYYY'); choices.push({ label, value: { year, month, current: i === 0 }, }); date = date.minus({ months: 1 }); } return choices; };
import { DateTime } from 'luxon'; import { PeriodOption } from '@waldur/form/types'; export const reactSelectMenuPortaling = (): any => ({ menuPortalTarget: document.body, styles: { menuPortal: (base) => ({ ...base, zIndex: 9999 }) }, menuPosition: 'fixed', menuPlacement: 'bottom', }); export const datePickerOverlayContainerInDialogs = () => ({ calendarPlacement: 'bottom', calendarContainer: document.getElementsByClassName('modal-dialog')[0], }); export const makeLastTwelveMonthsFilterPeriods = (): PeriodOption[] => { let date = DateTime.now().startOf('month'); const choices = []; for (let i = 0; i < 12; i++) { const month = date.month; const year = date.year; const label = date.toFormat('MMMM, yyyy'); choices.push({ label, value: { year, month, current: i === 0 }, }); date = date.minus({ months: 1 }); } return choices; };
Fix column class for React table: avoid table options modification.
import * as React from 'react'; import './TableHeader.scss'; import { Column, Sorting } from './types'; interface Props { columns: Column[]; onSortClick?: (orderField: string, currentSorting: Sorting) => any; currentSorting?: Sorting; } const TableHeader = ({ columns, onSortClick, currentSorting }: Props) => ( <thead> <tr> {columns.map((column, index) => ( <th key={index} className={column.orderField ? column.className += ' sorting-column' : column.className} onClick={column.orderField && (() => onSortClick(column.orderField, currentSorting))}> {column.title} {(column.orderField && (currentSorting && column.orderField !== currentSorting.field)) && <i className="fa fa-sort m-l-xs"/>} {(currentSorting && column.orderField === currentSorting.field) && <i className={`fa fa-sort-${currentSorting.mode} m-l-xs`}/>} </th> ))} </tr> </thead> ); export default TableHeader;
import * as classNames from 'classnames'; import * as React from 'react'; import './TableHeader.scss'; import { Column, Sorting } from './types'; interface Props { columns: Column[]; onSortClick?: (orderField: string, currentSorting: Sorting) => any; currentSorting?: Sorting; } const TableHeader = ({ columns, onSortClick, currentSorting }: Props) => ( <thead> <tr> {columns.map((column, index) => ( <th key={index} className={classNames(column.className, column.orderField && 'sorting-column')} onClick={column.orderField && (() => onSortClick(column.orderField, currentSorting))}> {column.title} {(column.orderField && (currentSorting && column.orderField !== currentSorting.field)) && <i className="fa fa-sort m-l-xs"/>} {(currentSorting && column.orderField === currentSorting.field) && <i className={`fa fa-sort-${currentSorting.mode} m-l-xs`}/>} </th> ))} </tr> </thead> ); export default TableHeader;
Allow optional style params to Concierge block
import * as React from 'react'; import Header from '../header/index'; import Sidebar from '../sidebar/index'; import Content from '../content/index'; import * as menus from './navigation'; import Body from './body'; type ConciergeParams = { params: { category: string; item?: string; }, } const Concierge = ({ params }: ConciergeParams) => ( <div style={styles}> <Header items={menus.getTopLevel()} /> <Body> <Sidebar root={menus.getItem(params.category).href} options={menus.getOptions(params.category)} /> <Content> {menus.getContent(params.category, params.item)} </Content> </Body> </div> ); export default Concierge; const styles: React.CSSProperties = { fontFamily: 'Helvetica', display: 'flex', flexFlow: 'column', height: '100vh' }
import * as React from 'react'; import Header from '../header/index'; import Sidebar from '../sidebar/index'; import Content from '../content/index'; import * as menus from './navigation'; import Body from './body'; import mergeToClass from '../merge-style'; type ConciergeParams = { styles?: {}; params: { category: string; item?: string; }, } const Concierge = ({ params, styles = {} }: ConciergeParams) => ( <div className={mergeToClass(conciergeStyles, styles)}> <Header items={menus.getTopLevel()} /> <Body> <Sidebar params={menus.getOptions(params.category)} /> <Content> {menus.getContent(params.category, params.item)} </Content> </Body> </div> ); export default Concierge; const conciergeStyles: React.CSSProperties = { fontFamily: 'Helvetica', display: 'flex', flexFlow: 'column', height: '100vh' }
Fix type error in status code
import * as React from 'react'; import {Route} from 'react-router-dom'; export interface StatusCodeProps { code: number; children?: React.ReactNode; } export default function Status({children, code}: StatusCodeProps) { return ( <Route render={({staticContext}) => { // there is no `staticContext` on the client, so // we need to guard against that here if (staticContext) staticContext.status = code; return children; }} /> ); } module.exports = Status; module.exports.default = Status;
import * as React from 'react'; import {Route} from 'react-router-dom'; export interface StatusCodeProps { code: number; children?: React.ReactNode; } export default function Status({children, code}: StatusCodeProps) { return ( <Route render={({staticContext}) => { // there is no `staticContext` on the client, so // we need to guard against that here if (staticContext) { (staticContext as any).status = code; staticContext.statusCode = code; } return children; }} /> ); } module.exports = Status; module.exports.default = Status;
Revert "Test if CI fails on a broken unit test."
"use strict"; import chai from "chai"; import {Config} from "../src/app/config"; import {RouterConfigurationStub} from "./stubs"; describe("Config test suite", () => { it("should initialize correctly", () => { let routerConfiguration = new RouterConfigurationStub(); let sut = new Config(); sut.configureRouter(routerConfiguration); chai.expect(routerConfiguration.title).to.equals("Hello Worl1d"); chai.expect(routerConfiguration.map.calledOnce).to.equals(true); }); });
"use strict"; import chai from "chai"; import {Config} from "../src/app/config"; import {RouterConfigurationStub} from "./stubs"; describe("Config test suite", () => { it("should initialize correctly", () => { let routerConfiguration = new RouterConfigurationStub(); let sut = new Config(); sut.configureRouter(routerConfiguration); chai.expect(routerConfiguration.title).to.equals("Hello World"); chai.expect(routerConfiguration.map.calledOnce).to.equals(true); }); });
Add index to startDate in video view table
import { AllowNull, BelongsTo, Column, CreatedAt, ForeignKey, Model, Table } from 'sequelize-typescript' import { VideoModel } from './video' import * as Sequelize from 'sequelize' @Table({ tableName: 'videoView', indexes: [ { fields: [ 'videoId' ] } ] }) export class VideoViewModel extends Model<VideoViewModel> { @CreatedAt createdAt: Date @AllowNull(false) @Column(Sequelize.DATE) startDate: Date @AllowNull(false) @Column(Sequelize.DATE) endDate: Date @AllowNull(false) @Column views: number @ForeignKey(() => VideoModel) @Column videoId: number @BelongsTo(() => VideoModel, { foreignKey: { allowNull: false }, onDelete: 'CASCADE' }) Video: VideoModel }
import { AllowNull, BelongsTo, Column, CreatedAt, ForeignKey, Model, Table } from 'sequelize-typescript' import { VideoModel } from './video' import * as Sequelize from 'sequelize' @Table({ tableName: 'videoView', indexes: [ { fields: [ 'videoId' ] }, { fields: [ 'startDate' ] } ] }) export class VideoViewModel extends Model<VideoViewModel> { @CreatedAt createdAt: Date @AllowNull(false) @Column(Sequelize.DATE) startDate: Date @AllowNull(false) @Column(Sequelize.DATE) endDate: Date @AllowNull(false) @Column views: number @ForeignKey(() => VideoModel) @Column videoId: number @BelongsTo(() => VideoModel, { foreignKey: { allowNull: false }, onDelete: 'CASCADE' }) Video: VideoModel }
Add workaround for the move to a new house.
export class RelativeConverter { convert(input: number[]): number[] { const copy: number[] = input.slice(0); let previousValue = copy.shift(); return copy.map(function (value) { let result; if (previousValue != null && value != null) { result = value - previousValue; } else { result = 0; } previousValue = value; return result; }); } }
export class RelativeConverter { convert(input: number[]): number[] { const copy: number[] = [...input]; let previousValue = copy.shift(); return copy.map(function (value) { let result; if (previousValue != null && value != null) { const diff = value - previousValue; // This is a bad workaround for moving house: // The meter return absolute values, so there's a big difference // between the old and new meter. // (only visible in the year view, since that's the only // view that has old and new measurements in the same view) // // A downside is that this hides one month of data. if (diff < -4400) { result = 0; } else { result = diff; } } else { result = 0; } previousValue = value; return result; }); } }
Include git hash for index view
import { Request, Response } from 'express'; import type { IBoard } from '../types/trello'; import { TrelloService } from '../services/trelloService'; export function index(_: Request, res: Response): Response { return res.send(':)'); } export async function healthCheck(_: Request, res: Response): Promise<Response> { try { const trello = new TrelloService(); const boards = await trello.listBoards(); return res.json({ ok: true, boards: boards.map((board: IBoard) => board.name), }); } catch (ex) { return res.status(500).json({ ok: false, err: { code: ex.code, message: ex.message, stack: ex.stack, }, }); } }
import { Request, Response } from 'express'; import type { IBoard } from '../types/trello'; import { TrelloService } from '../services/trelloService'; export function index(_: Request, res: Response): Response { return res.send(`:)<br />${process.env.GIT_REV || ''}`); } export async function healthCheck(_: Request, res: Response): Promise<Response> { try { const trello = new TrelloService(); const boards = await trello.listBoards(); return res.json({ ok: true, boards: boards.map((board: IBoard) => board.name), }); } catch (ex) { return res.status(500).json({ ok: false, err: { code: ex.code, message: ex.message, stack: ex.stack, }, }); } }
Fix employee detection in OSS version
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import {useEffect} from 'react'; import LegacyApp from './LegacyApp'; import fbConfig from '../fb-stubs/config'; import {isFBEmployee} from '../utils/fbEmployee'; import {Logger} from '../fb-interfaces/Logger'; import isSandyEnabled from '../utils/isSandyEnabled'; import {SandyApp} from '../sandy-chrome/SandyApp'; import {notification} from 'antd'; import isProduction from '../utils/isProduction'; type Props = {logger: Logger}; export default function App(props: Props) { useEffect(() => { if (fbConfig.warnFBEmployees && isProduction()) { isFBEmployee().then(() => { notification.warning({ placement: 'bottomLeft', message: 'Please use Flipper@FB', description: ( <> You are using the open-source version of Flipper. Install the internal build from Managed Software Center to get access to more plugins. </> ), duration: null, }); }); } }, []); return isSandyEnabled() ? <SandyApp /> : <LegacyApp logger={props.logger} />; }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import {useEffect} from 'react'; import LegacyApp from './LegacyApp'; import fbConfig from '../fb-stubs/config'; import {isFBEmployee} from '../utils/fbEmployee'; import {Logger} from '../fb-interfaces/Logger'; import isSandyEnabled from '../utils/isSandyEnabled'; import {SandyApp} from '../sandy-chrome/SandyApp'; import {notification} from 'antd'; import isProduction from '../utils/isProduction'; type Props = {logger: Logger}; export default function App(props: Props) { useEffect(() => { if (fbConfig.warnFBEmployees && isProduction()) { isFBEmployee().then((isEmployee) => { if (isEmployee) { notification.warning({ placement: 'bottomLeft', message: 'Please use Flipper@FB', description: ( <> You are using the open-source version of Flipper. Install the internal build from Managed Software Center to get access to more plugins. </> ), duration: null, }); } }); } }, []); return isSandyEnabled() ? <SandyApp /> : <LegacyApp logger={props.logger} />; }
Add todo to where builder
import {WhereLiteralQueryPart} from "../match/WhereLiteralQueryPart"; export class WhereBuilder { literal(queryPart:string):WhereLiteralQueryPart { return new WhereLiteralQueryPart(queryPart) } }
import {WhereLiteralQueryPart} from "../match/WhereLiteralQueryPart"; export class WhereBuilder<T = any> { literal(queryPart:string):WhereLiteralQueryPart { return new WhereLiteralQueryPart(queryPart) } //TODO: attribute<K extends keyof T>(prop:T) {} // where(w => [w.attribute('id').in([1,2,3,4,])] }
Add the RocketChatAssociationModel back in
import { IRocketletAuthorInfo } from './IRocketletAuthorInfo'; import { IRocketletInfo } from './IRocketletInfo'; export { IRocketletAuthorInfo, IRocketletInfo };
import { IRocketletAuthorInfo } from './IRocketletAuthorInfo'; import { IRocketletInfo } from './IRocketletInfo'; import { RocketChatAssociationModel } from './RocketChatAssociationModel'; export { IRocketletAuthorInfo, IRocketletInfo, RocketChatAssociationModel };
Store an array of entries rather than a map.
import { Command } from "./command"; export class CommandTable { private name: string; private inherit: CommandTable[] = []; private commands: Map<string, Command> = new Map(); constructor (name: string, inherit: CommandTable[]) { this.name = name; this.inherit = inherit; } }
import { Command } from "./command"; export class CommandTableEntry { name: string; command: Command; } export class CommandTable { private name: string; private inherit: CommandTable[] = []; private commands: CommandTableEntry[] = []; constructor (name: string, inherit: CommandTable[]) { this.name = name; this.inherit = inherit; } }