commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
66c9f729592c011ef59d1529a73470cabf36c4a4
src/internal/ErrorBoundary/index.tsx
src/internal/ErrorBoundary/index.tsx
import React from 'react'; import { Flex } from '../../components/Flex'; import Alert from '../../components/Alert'; interface ErrorBoundaryState { error: any; } interface ErrorBoundaryProps { getErrorDisplay?: (error: any) => JSX.Element; } const DefaultErrorDisplay = () => ( <Flex flex={1} alignItems="center" justifyContent="center"> <Alert m={2} plaintext danger> Something went wrong </Alert> </Flex> ); export default class ErrorBoundary extends React.Component< ErrorBoundaryProps, ErrorBoundaryState > { constructor(props: ErrorBoundaryProps) { super(props); this.state = { error: null }; } static getDerivedStateFromError(error: any) { return { error }; } render() { if (this.state.error) { return this.props.getErrorDisplay ? ( this.props.getErrorDisplay(this.state.error) ) : ( <DefaultErrorDisplay /> ); } return this.props.children; } }
import React from 'react'; import isEqual from 'lodash/isEqual'; import { Flex } from '../../components/Flex'; import Alert from '../../components/Alert'; interface ErrorBoundaryState { error: any; } interface ErrorBoundaryProps { getErrorDisplay?: (error: any) => JSX.Element; } const DefaultErrorDisplay = () => ( <Flex flex={1} alignItems="center" justifyContent="center"> <Alert m={2} plaintext danger> Something went wrong </Alert> </Flex> ); export default class ErrorBoundary extends React.Component< ErrorBoundaryProps, ErrorBoundaryState > { constructor(props: ErrorBoundaryProps) { super(props); this.state = { error: null }; } static getDerivedStateFromError(error: any) { return { error }; } componentDidUpdate(prevProps: any) { if (!isEqual(prevProps, this.props)) { this.setState({ error: null }); } } render() { if (this.state.error) { return this.props.getErrorDisplay ? ( this.props.getErrorDisplay(this.state.error) ) : ( <DefaultErrorDisplay /> ); } return this.props.children; } }
Reset error boundary if props change
fix: Reset error boundary if props change Previously, the error boundary was stuck in the error state until it was unmounted and remounted. Change-type: patch Signed-off-by: Graham McCulloch <5ca27e75aea3e5e83a04c6cfa5f1b63d358cd03d@balena.io>
TypeScript
mit
resin-io-modules/resin-components,resin-io-modules/resin-components,resin-io-modules/resin-components
--- +++ @@ -1,4 +1,5 @@ import React from 'react'; +import isEqual from 'lodash/isEqual'; import { Flex } from '../../components/Flex'; import Alert from '../../components/Alert'; @@ -31,6 +32,12 @@ return { error }; } + componentDidUpdate(prevProps: any) { + if (!isEqual(prevProps, this.props)) { + this.setState({ error: null }); + } + } + render() { if (this.state.error) { return this.props.getErrorDisplay ? (
6085a4094a945e845f540605e21a9ac894be22bd
src/time/time.service.ts
src/time/time.service.ts
import { Injectable } from '@angular/core' import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import { NativeStorage } from 'ionic-native'; @Injectable() export class TimeService { private _url: string = 'https://script.google.com/macros/s/AKfycbyd5AcbAnWi2Yn0xhFRbyzS4qMq1VucMVgVvhul5XqS9HkAyJY/exec'; constructor(private _http: Http) {} getTime() : Observable<any> { var observableHttp: Observable<any> = this._http.get(this._url) .map((response : Response) => response.json()) .do(json => console.log('Received json: ' + JSON.stringify(json))) .do(json => this._cacheTime(json)); var observableLocal: Observable<any> = this._getCachedTime(); return Observable.concat(observableLocal, observableHttp); } private _cacheTime(json : any) : void { NativeStorage.setItem('current_time', json) .then( () => console.log('Stored item!'), error => console.error('Error storing item', error) ); } private _getCachedTime() : Observable<any> { return Observable.fromPromise(NativeStorage.getItem('current_time')); } }
import { Injectable } from '@angular/core' import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import { NativeStorage } from 'ionic-native'; @Injectable() export class TimeService { private _url: string = 'https://script.google.com/macros/s/AKfycbyd5AcbAnWi2Yn0xhFRbyzS4qMq1VucMVgVvhul5XqS9HkAyJY/exec'; constructor(private _http: Http) {} getTime() : Observable<any> { var observableHttp: Observable<any> = this._http.get(this._url) .map((response : Response) => response.json()) .do(json => console.log('Received json: ' + JSON.stringify(json))) .do(json => this._cacheTime(json)); var observableLocal: Observable<any> = this._getCachedTime(); return Observable.onErrorResumeNext(observableLocal, observableHttp); } private _cacheTime(json : any) : void { NativeStorage.setItem('current_time', json) .then( () => console.log('Stored item!'), error => console.error('Error storing item', error) ); } private _getCachedTime() : Observable<any> { return Observable.fromPromise(NativeStorage.getItem('current_time')); } }
Fix UPDATE NOW button to work after fresh installation
Fix UPDATE NOW button to work after fresh installation
TypeScript
apache-2.0
sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile
--- +++ @@ -15,7 +15,7 @@ .do(json => console.log('Received json: ' + JSON.stringify(json))) .do(json => this._cacheTime(json)); var observableLocal: Observable<any> = this._getCachedTime(); - return Observable.concat(observableLocal, observableHttp); + return Observable.onErrorResumeNext(observableLocal, observableHttp); } private _cacheTime(json : any) : void {
1a06e3df8f2375a6d274613d896f8f6ad29b4570
packages/lesswrong/lib/collections/tags/fragments.ts
packages/lesswrong/lib/collections/tags/fragments.ts
import { registerFragment } from '../../vulcan-lib'; registerFragment(` fragment TagBasicInfo on Tag { _id name slug oldSlugs core postCount deleted adminOnly defaultOrder suggestedAsFilter needsReview reviewedByUserId descriptionTruncationCount wikiGrade createdAt wikiOnly tagFlagsIds lesswrongWikiImportSlug lesswrongWikiImportRevision } `); registerFragment(` fragment TagFragment on Tag { ...TagBasicInfo description { html htmlHighlight plaintextDescription version } } `); registerFragment(` fragment TagRevisionFragment on Tag { ...TagBasicInfo description(version: $version) { version html htmlHighlight plaintextDescription user { ...UsersMinimumInfo } } } `); registerFragment(` fragment TagPreviewFragment on Tag { ...TagBasicInfo description { htmlHighlight version } } `); registerFragment(` fragment TagWithFlagsFragment on Tag { ...TagPreviewFragment tagFlags { ...TagFlagFragment } } `); registerFragment(` fragment TagEditFragment on Tag { ...TagBasicInfo description { ...RevisionEdit } } `); registerFragment(` fragment SunshineTagFragment on Tag { ...TagFragment user { ...UsersMinimumInfo } } `);
import { registerFragment } from '../../vulcan-lib'; registerFragment(` fragment TagBasicInfo on Tag { _id name slug oldSlugs core postCount deleted adminOnly defaultOrder suggestedAsFilter needsReview reviewedByUserId descriptionTruncationCount wikiGrade createdAt wikiOnly lesswrongWikiImportSlug lesswrongWikiImportRevision } `); registerFragment(` fragment TagFragment on Tag { ...TagBasicInfo description { html htmlHighlight plaintextDescription version } } `); registerFragment(` fragment TagRevisionFragment on Tag { ...TagBasicInfo description(version: $version) { version html htmlHighlight plaintextDescription user { ...UsersMinimumInfo } } } `); registerFragment(` fragment TagPreviewFragment on Tag { ...TagBasicInfo description { htmlHighlight version } } `); registerFragment(` fragment TagWithFlagsFragment on Tag { ...TagPreviewFragment tagFlags { ...TagFlagFragment } } `); registerFragment(` fragment TagEditFragment on Tag { ...TagBasicInfo description { ...RevisionEdit } } `); registerFragment(` fragment SunshineTagFragment on Tag { ...TagFragment user { ...UsersMinimumInfo } } `);
Remove tagFlagsIds from tag fragment
Remove tagFlagsIds from tag fragment
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -18,7 +18,6 @@ wikiGrade createdAt wikiOnly - tagFlagsIds lesswrongWikiImportSlug lesswrongWikiImportRevision }
23e8d93c0ea28d5d8913c860c7a9293404b2ea01
src/constants/path-info.ts
src/constants/path-info.ts
import { PathInfo } from './interfaces'; const PATH_INFOS: PathInfo[] = [ { path: /^\/$/, label: 'Home' }, { path: /^\/create-machine$/, label: 'Create Machine' }, { path: /^\/machines$/, label: 'Machines' }, { path: /^\/machines\/[a-zA-Z0-9]+$/, dynamicLabel: (route) => route.params.machineName }, { path: /^\/machines\/[a-zA-Z0-9]+\/containers$/, label: 'Containers' }, { path: /^\/machines\/[a-zA-Z0-9]+\/create-container$/, label: 'Create Container' } ]; export default PATH_INFOS;
import { PathInfo } from './interfaces'; const PATH_INFOS: PathInfo[] = [ { path: /^\/$/, label: 'Home' }, { path: /^\/create-machine$/, label: 'Create Machine' }, { path: /^\/machines$/, label: 'Machines' }, { path: /^\/machines\/[a-zA-Z0-9]+$/, dynamicLabel: (route) => route.params.machineName }, { path: /^\/machines\/[a-zA-Z0-9]+\/containers$/, label: 'Containers' }, { path: /^\/machines\/[a-zA-Z0-9]+\/create-container$/, label: 'Create Container' }, { path: /^\/machines\/[a-zA-Z0-9]+\/images$/, label: 'Images' } ]; export default PATH_INFOS;
Add machine image path info
Add machine image path info
TypeScript
apache-2.0
lawrence0819/neptune-front,lawrence0819/neptune-front
--- +++ @@ -24,6 +24,10 @@ { path: /^\/machines\/[a-zA-Z0-9]+\/create-container$/, label: 'Create Container' + }, + { + path: /^\/machines\/[a-zA-Z0-9]+\/images$/, + label: 'Images' } ];
5ca1c5dd0f963e447ec0c0b591adb4394b793e12
src/ManifestResource.ts
src/ManifestResource.ts
module Manifesto { export class ManifestResource extends JSONLDResource implements IManifestResource { options: IManifestoOptions; constructor(jsonld: any, options: IManifestoOptions) { super(jsonld); this.options = options; } getLabel(): string { return Utils.getLocalisedValue(this.getProperty('label'), this.options.locale); } getMetadata(): any{ var metadata: Object[] = this.getProperty('metadata'); // get localised value for each metadata item. for (var i = 0; i < metadata.length; i++) { var item: any = metadata[i]; item.label = Utils.getLocalisedValue(item.label, this.options.locale); item.value = Utils.getLocalisedValue(item.value, this.options.locale); } return metadata; } // todo: once UV download menu uses manifesto parsed objects, this can be moved back from Utils getRendering(format: RenderingFormat | string): IRendering { return Utils.getRendering(this, format); } // todo: once UV download menu uses manifesto parsed objects, this can be moved back from Utils getRenderings(): IRendering[] { return Utils.getRenderings(this); } getService(profile: ServiceProfile | string): IService { return Utils.getService(this, profile); } getServices(): IService[] { return Utils.getServices(this); } } }
module Manifesto { export class ManifestResource extends JSONLDResource implements IManifestResource { options: IManifestoOptions; constructor(jsonld: any, options: IManifestoOptions) { super(jsonld); this.options = options; } getLabel(): string { return Utils.getLocalisedValue(this.getProperty('label'), this.options.locale); } getMetadata(): any{ var metadata: Object[] = this.getProperty('metadata'); if (!metadata) return []; // get localised value for each metadata item. for (var i = 0; i < metadata.length; i++) { var item: any = metadata[i]; item.label = Utils.getLocalisedValue(item.label, this.options.locale); item.value = Utils.getLocalisedValue(item.value, this.options.locale); } return metadata; } // todo: once UV download menu uses manifesto parsed objects, this can be moved back from Utils getRendering(format: RenderingFormat | string): IRendering { return Utils.getRendering(this, format); } // todo: once UV download menu uses manifesto parsed objects, this can be moved back from Utils getRenderings(): IRendering[] { return Utils.getRenderings(this); } getService(profile: ServiceProfile | string): IService { return Utils.getService(this, profile); } getServices(): IService[] { return Utils.getServices(this); } } }
Check if no metadata is present
Check if no metadata is present
TypeScript
mit
viewdir/manifesto,viewdir/manifesto
--- +++ @@ -13,6 +13,9 @@ getMetadata(): any{ var metadata: Object[] = this.getProperty('metadata'); + + if (!metadata) + return []; // get localised value for each metadata item. for (var i = 0; i < metadata.length; i++) {
d765fdbf2517c151c69b9cb5afd86eff149cbce6
koa-static/koa-static.d.ts
koa-static/koa-static.d.ts
// Type definitions for koa-static v2.x // Project: https://github.com/koajs/static // Definitions by: Jerry Chin <https://github.com/hellopao/> // Definitions: https://github.com/hellopao/DefinitelyTyped /* =================== USAGE =================== import serve = require("koa-static"); var Koa = require('koa'); var app = new Koa(); app.use(serve(".")); =============================================== */ /// <reference path="../koa/koa.d.ts" /> declare module "koa-static" { import * as Koa from "koa"; function serve(root: string, opts?: { /** * Default file name, defaults to 'index.html' */ index?: boolean | string; /** * If true, serves after return next(),allowing any downstream middleware to respond first. */ defer?: boolean; /** * Browser cache max-age in milliseconds. defaults to 0 */ maxage?: number; /** * Allow transfer of hidden files. defaults to false */ hidden?: boolean; /** * Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true. */ gzip?: boolean; }): { (ctx: Koa.Context, next?: () => any): any }; export = serve; }
// Type definitions for koa-static v2.x // Project: https://github.com/koajs/static // Definitions by: Jerry Chin <https://github.com/hellopao/> // Definitions: https://github.com/hellopao/DefinitelyTyped /* =================== USAGE =================== import serve = require("koa-static"); var Koa = require('koa'); var app = new Koa(); app.use(serve(".")); =============================================== */ /// <reference path="../koa/koa.d.ts" /> declare module "koa-static" { import * as Koa from "koa"; function serve(root: string, opts?: { /** * Default file name, defaults to 'index.html' */ index?: boolean | string; /** * If true, serves after return next(),allowing any downstream middleware to respond first. */ defer?: boolean; /** * Browser cache max-age in milliseconds. defaults to 0 */ maxage?: number; /** * Allow transfer of hidden files. defaults to false */ hidden?: boolean; /** * Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true. */ gzip?: boolean; }): { (ctx: Koa.Context, next?: () => any): any }; namespace serve{} export = serve; }
Fix error TS2497 on import * as X from 'koa-static
Fix error TS2497 on import * as X from 'koa-static
TypeScript
mit
aciccarello/DefinitelyTyped,nainslie/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,yuit/DefinitelyTyped,arma-gast/DefinitelyTyped,psnider/DefinitelyTyped,mcrawshaw/DefinitelyTyped,schmuli/DefinitelyTyped,xStrom/DefinitelyTyped,progre/DefinitelyTyped,georgemarshall/DefinitelyTyped,abbasmhd/DefinitelyTyped,progre/DefinitelyTyped,HPFOD/DefinitelyTyped,micurs/DefinitelyTyped,benishouga/DefinitelyTyped,danfma/DefinitelyTyped,shlomiassaf/DefinitelyTyped,arusakov/DefinitelyTyped,nycdotnet/DefinitelyTyped,rolandzwaga/DefinitelyTyped,schmuli/DefinitelyTyped,jraymakers/DefinitelyTyped,rolandzwaga/DefinitelyTyped,QuatroCode/DefinitelyTyped,shlomiassaf/DefinitelyTyped,benishouga/DefinitelyTyped,AgentME/DefinitelyTyped,newclear/DefinitelyTyped,abner/DefinitelyTyped,ashwinr/DefinitelyTyped,QuatroCode/DefinitelyTyped,sledorze/DefinitelyTyped,gandjustas/DefinitelyTyped,nainslie/DefinitelyTyped,gandjustas/DefinitelyTyped,martinduparc/DefinitelyTyped,minodisk/DefinitelyTyped,AgentME/DefinitelyTyped,subash-a/DefinitelyTyped,subash-a/DefinitelyTyped,arma-gast/DefinitelyTyped,mcliment/DefinitelyTyped,gcastre/DefinitelyTyped,florentpoujol/DefinitelyTyped,pocesar/DefinitelyTyped,nycdotnet/DefinitelyTyped,syuilo/DefinitelyTyped,minodisk/DefinitelyTyped,smrq/DefinitelyTyped,mcrawshaw/DefinitelyTyped,magny/DefinitelyTyped,smrq/DefinitelyTyped,aciccarello/DefinitelyTyped,pocesar/DefinitelyTyped,danfma/DefinitelyTyped,alexdresko/DefinitelyTyped,rcchen/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,hellopao/DefinitelyTyped,newclear/DefinitelyTyped,amanmahajan7/DefinitelyTyped,georgemarshall/DefinitelyTyped,syuilo/DefinitelyTyped,aciccarello/DefinitelyTyped,georgemarshall/DefinitelyTyped,sledorze/DefinitelyTyped,scriby/DefinitelyTyped,zuzusik/DefinitelyTyped,abner/DefinitelyTyped,scriby/DefinitelyTyped,Penryn/DefinitelyTyped,johan-gorter/DefinitelyTyped,borisyankov/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,florentpoujol/DefinitelyTyped,johan-gorter/DefinitelyTyped,pocesar/DefinitelyTyped,arusakov/DefinitelyTyped,amanmahajan7/DefinitelyTyped,one-pieces/DefinitelyTyped,psnider/DefinitelyTyped,arusakov/DefinitelyTyped,damianog/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,jimthedev/DefinitelyTyped,chrismbarr/DefinitelyTyped,donnut/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,HPFOD/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,dsebastien/DefinitelyTyped,YousefED/DefinitelyTyped,martinduparc/DefinitelyTyped,jimthedev/DefinitelyTyped,amir-arad/DefinitelyTyped,hellopao/DefinitelyTyped,alvarorahul/DefinitelyTyped,chrismbarr/DefinitelyTyped,schmuli/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,yuit/DefinitelyTyped,magny/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,xStrom/DefinitelyTyped,hellopao/DefinitelyTyped,jimthedev/DefinitelyTyped,chrootsu/DefinitelyTyped,AgentME/DefinitelyTyped,benliddicott/DefinitelyTyped,daptiv/DefinitelyTyped,zuzusik/DefinitelyTyped,alvarorahul/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,borisyankov/DefinitelyTyped,Penryn/DefinitelyTyped,alexdresko/DefinitelyTyped,zuzusik/DefinitelyTyped,benishouga/DefinitelyTyped,damianog/DefinitelyTyped,isman-usoh/DefinitelyTyped,chrootsu/DefinitelyTyped,psnider/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,abbasmhd/DefinitelyTyped,rcchen/DefinitelyTyped,paulmorphy/DefinitelyTyped,jraymakers/DefinitelyTyped,dsebastien/DefinitelyTyped,ashwinr/DefinitelyTyped,YousefED/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,isman-usoh/DefinitelyTyped,use-strict/DefinitelyTyped,donnut/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AgentME/DefinitelyTyped,gcastre/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,martinduparc/DefinitelyTyped,use-strict/DefinitelyTyped,paulmorphy/DefinitelyTyped
--- +++ @@ -46,6 +46,6 @@ */ gzip?: boolean; }): { (ctx: Koa.Context, next?: () => any): any }; - + namespace serve{} export = serve; }
1c8cbd7b4a55b191122ad28409c346b9357688bc
.storybook/decorators.tsx
.storybook/decorators.tsx
import { FC, createElement as h } from 'react'; import { boolean, select, withKnobs } from "@storybook/addon-knobs"; import { BrowserRouter as Router } from 'react-router-dom'; const Root: FC<any> = props => ( <div id="story-root" {...props} style={{ backgroundColor: 'white', padding: '1em' }}> <Router> {props.children} </Router> </div> ); const decorator = storyFn => { return h(Root, {}, storyFn()); }; const simpleDecorator = Component => storyFn => h(Component, {}, storyFn()); export const root = decorator; export default root;
import { FC, createElement as h } from 'react'; import { boolean, select, withKnobs } from "@storybook/addon-knobs"; import { BrowserRouter as Router } from 'react-router-dom'; const Root: FC<any> = props => ( <div id="story-root" {...props} style={{ padding: '1em' }}> <Router> {props.children} </Router> </div> ); const decorator = storyFn => { return h(Root, {}, storyFn()); }; const simpleDecorator = Component => storyFn => h(Component, {}, storyFn()); export const root = decorator; export default root;
Remove white background from stories
Remove white background from stories This doesn't work well with the design.
TypeScript
mit
eliothill/home-office-digital-patterns,eliothill/home-office-digital-patterns,eliothill/home-office-digital-patterns
--- +++ @@ -4,7 +4,6 @@ const Root: FC<any> = props => ( <div id="story-root" {...props} style={{ - backgroundColor: 'white', padding: '1em' }}> <Router>
baf18cce6552a3baf773efdb12697fc3f82c1881
src/testing/index.ts
src/testing/index.ts
import { ComponentFixture } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; export function selectElement<T> (fixture: ComponentFixture<T>, locator: string) { return fixture.debugElement.query(By.css('h1')).nativeElement; }
import { ComponentFixture } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; export function selectElement<T> (fixture: ComponentFixture<T>, locator: string) { return fixture.debugElement.query(By.css(locator)).nativeElement; }
Fix element selector in spec testing module
Fix element selector in spec testing module
TypeScript
bsd-3-clause
cumulous/web,cumulous/web,cumulous/web,cumulous/web
--- +++ @@ -2,5 +2,5 @@ import { By } from '@angular/platform-browser'; export function selectElement<T> (fixture: ComponentFixture<T>, locator: string) { - return fixture.debugElement.query(By.css('h1')).nativeElement; + return fixture.debugElement.query(By.css(locator)).nativeElement; }
a3a9c9ece22ed9acdd5457d4858cdce864c91e6f
src/ui/utils/utils-m3u.ts
src/ui/utils/utils-m3u.ts
import * as path from 'path'; import * as fs from 'fs'; import * as chardet from 'chardet'; import * as iconv from 'iconv-lite'; const isFile = (path: string) => fs.lstatSync(path).isFile(); export const parse = (filePath: string): string[] => { try { const baseDir = path.parse(filePath).dir; const encoding = chardet.detectFileSync(filePath); const content = fs.readFileSync(filePath); if (typeof encoding !== 'string') { throw (new Error(`could not guess the file encoding (${filePath})`)); } const decodedContent = iconv.decode(content, encoding); const files = decodedContent .split('\n') .reduce((acc, line) => { if (line.length === 0) { return acc; } // If absolute path if (fs.existsSync(path.resolve(line)) && isFile(path.resolve(line))) { acc.push(path.resolve(line)); return acc; } // If relative Path if (fs.existsSync(path.resolve(baseDir, line)) && isFile(path.resolve(baseDir, line)) ) { acc.push(path.resolve(baseDir, line)); return acc; } return acc; }, [] as string[]); return files; } catch (err) { console.warn(err); } return []; };
import * as path from 'path'; import * as fs from 'fs'; import * as chardet from 'chardet'; import * as iconv from 'iconv-lite'; const isFile = (path: string) => fs.lstatSync(path).isFile(); export const parse = (filePath: string): string[] => { try { const baseDir = path.parse(filePath).dir; const encoding = chardet.detectFileSync(filePath); const content = fs.readFileSync(filePath); if (typeof encoding !== 'string') { throw (new Error(`could not guess the file encoding (${filePath})`)); } const decodedContent = iconv.decode(content, encoding); const files = decodedContent .split(/\r?\n/) .reduce((acc, line) => { if (line.length === 0) { return acc; } // If absolute path if (fs.existsSync(path.resolve(line)) && isFile(path.resolve(line))) { acc.push(path.resolve(line)); return acc; } // If relative Path if (fs.existsSync(path.resolve(baseDir, line)) && isFile(path.resolve(baseDir, line)) ) { acc.push(path.resolve(baseDir, line)); return acc; } return acc; }, [] as string[]); return files; } catch (err) { console.warn(err); } return []; };
Check for trailing carriage returns
Check for trailing carriage returns
TypeScript
mit
KeitIG/museeks,KeitIG/museeks,KeitIG/museeks
--- +++ @@ -18,7 +18,7 @@ const decodedContent = iconv.decode(content, encoding); const files = decodedContent - .split('\n') + .split(/\r?\n/) .reduce((acc, line) => { if (line.length === 0) { return acc;
d37a6a7fffe24727fd5f8a3184aaff9c35ba304c
gulp/module.ts
gulp/module.ts
import { watch, task } from 'gulp'; import { join } from 'path'; import { SRC, DIST, DEMO_DIST } from './constants'; import compileTs from './tasks/compileTs'; import clean from './tasks/clean'; const runSequence = require('run-sequence'); const src = join(SRC, '**/*.ts'); task('module:clean', clean(DIST)); task('module:ts:demo', compileTs(join(SRC, '**/*.ts'), null, DEMO_DIST)); task('module:watch', () => { watch(join(SRC, '**/*.ts'), ['module:ts:demo']); }); task('module:ts:separate', compileTs(src, DIST)); task('module:ts:umd', compileTs(src, DIST, { outFile: 'round-progress.umd.js', module: 'system' })); task('module:ts', ['module:ts:separate', 'module:ts:umd']); task('module:build', (done: any) => { runSequence('module:clean', 'module:ts', done); }); task('deploy', (done: any) => { runSequence('module:build', 'demo:deploy', done); });
import { watch, task } from 'gulp'; import { join } from 'path'; import { SRC, DIST, DEMO_DIST } from './constants'; import compileTs from './tasks/compileTs'; import clean from './tasks/clean'; const runSequence = require('run-sequence'); const src = join(SRC, '**/*.ts'); task('module:clean', clean(DIST)); task('module:ts:demo', compileTs(join(SRC, '**/*.ts'), DEMO_DIST)); task('module:watch', () => { watch(join(SRC, '**/*.ts'), ['module:ts:demo']); }); task('module:ts:separate', compileTs(src, DIST)); task('module:ts:umd', compileTs(src, DIST, { outFile: 'round-progress.umd.js', module: 'system' })); task('module:ts', ['module:ts:separate', 'module:ts:umd']); task('module:build', (done: any) => { runSequence('module:clean', 'module:ts', done); }); task('deploy', (done: any) => { runSequence('module:build', 'demo:deploy', done); });
Fix wrong demo method signature.
Fix wrong demo method signature.
TypeScript
mit
crisbeto/angular-svg-round-progressbar,crisbeto/angular-svg-round-progressbar
--- +++ @@ -10,7 +10,7 @@ task('module:clean', clean(DIST)); -task('module:ts:demo', compileTs(join(SRC, '**/*.ts'), null, DEMO_DIST)); +task('module:ts:demo', compileTs(join(SRC, '**/*.ts'), DEMO_DIST)); task('module:watch', () => { watch(join(SRC, '**/*.ts'), ['module:ts:demo']);
c5c7e9e8a1e35cf2d692f3cb30b7f6e45d5a5e15
packages/@glimmer/integration-tests/lib/modes/rehydration/builder.ts
packages/@glimmer/integration-tests/lib/modes/rehydration/builder.ts
import { RehydrateBuilder } from '@glimmer/runtime'; import { SimpleNode } from '@simple-dom/interface'; import { Environment, Cursor, ElementBuilder } from '@glimmer/interfaces'; export class DebugRehydrationBuilder extends RehydrateBuilder { clearedNodes: SimpleNode[] = []; remove(node: SimpleNode) { let next = super.remove(node); let el = node as Element; if (node.nodeType !== 8) { if (el.nodeType === 1) { // don't stat serialized cursor positions if (el.tagName !== 'SCRIPT' && !el.getAttribute('gmlr')) { this.clearedNodes.push(node); } } else { this.clearedNodes.push(node); } } return next; } } export function debugRehydration(env: Environment, cursor: Cursor): ElementBuilder { return DebugRehydrationBuilder.forInitialRender(env, cursor); }
import { RehydrateBuilder } from '@glimmer/runtime'; import { SimpleNode } from '@simple-dom/interface'; import { Environment, Cursor, ElementBuilder } from '@glimmer/interfaces'; export class DebugRehydrationBuilder extends RehydrateBuilder { clearedNodes: SimpleNode[] = []; remove(node: SimpleNode) { let next = super.remove(node); let el = node as Element; if (node.nodeType !== 8) { if (el.nodeType === 1) { // don't stat serialized cursor positions if (el.tagName !== 'SCRIPT' || !el.getAttribute('glmr')) { this.clearedNodes.push(node); } } else { this.clearedNodes.push(node); } } return next; } } export function debugRehydration(env: Environment, cursor: Cursor): ElementBuilder { return DebugRehydrationBuilder.forInitialRender(env, cursor); }
Fix DebugRehydrationBuilder's handling of serialized cursor positions.
Fix DebugRehydrationBuilder's handling of serialized cursor positions.
TypeScript
mit
glimmerjs/glimmer-vm,tildeio/glimmer,tildeio/glimmer,glimmerjs/glimmer-vm,glimmerjs/glimmer-vm,tildeio/glimmer
--- +++ @@ -12,7 +12,7 @@ if (node.nodeType !== 8) { if (el.nodeType === 1) { // don't stat serialized cursor positions - if (el.tagName !== 'SCRIPT' && !el.getAttribute('gmlr')) { + if (el.tagName !== 'SCRIPT' || !el.getAttribute('glmr')) { this.clearedNodes.push(node); } } else {
f60961947fc9471024081c3c76f940b864336e5f
src/background/presenters/IndicatorPresenter.ts
src/background/presenters/IndicatorPresenter.ts
export default class IndicatorPresenter { indicate(enabled: boolean): Promise<void> { let path = enabled ? 'resources/enabled_32x32.png' : 'resources/disabled_32x32.png'; return browser.browserAction.setIcon({ path }); } onClick(listener: (arg: browser.tabs.Tab) => void): void { browser.browserAction.onClicked.addListener(listener); } }
export default class IndicatorPresenter { indicate(enabled: boolean): Promise<void> { let path = enabled ? 'resources/enabled_32x32.png' : 'resources/disabled_32x32.png'; if (typeof browser.browserAction.setIcon === "function") { return browser.browserAction.setIcon({ path }); } else { // setIcon not supported on Android return Promise.resolve(); } } onClick(listener: (arg: browser.tabs.Tab) => void): void { browser.browserAction.onClicked.addListener(listener); } }
Fix setIcon warning on Android
Fix setIcon warning on Android
TypeScript
mit
ueokande/vim-vixen,ueokande/vim-vixen,ueokande/vim-vixen
--- +++ @@ -3,7 +3,13 @@ let path = enabled ? 'resources/enabled_32x32.png' : 'resources/disabled_32x32.png'; - return browser.browserAction.setIcon({ path }); + if (typeof browser.browserAction.setIcon === "function") { + return browser.browserAction.setIcon({ path }); + } + else { + // setIcon not supported on Android + return Promise.resolve(); + } } onClick(listener: (arg: browser.tabs.Tab) => void): void {
90a127d528bd09466de676126ca088cf0646b821
src/app/farming/reducer.ts
src/app/farming/reducer.ts
import { Reducer } from 'redux'; import { ActionType, getType } from 'typesafe-actions'; import * as actions from './basic-actions'; export interface FarmingState { // The actively farming store, if any readonly storeId?: string; // A counter for pending tasks that interrupt farming readonly numInterruptions: number; } export type FarmingAction = ActionType<typeof actions>; const initialState: FarmingState = { numInterruptions: 0, }; export const farming: Reducer<FarmingState, FarmingAction> = ( state: FarmingState = initialState, action: FarmingAction ) => { switch (action.type) { case getType(actions.start): return { ...state, storeId: action.payload, }; case getType(actions.stop): return { ...state, storeId: undefined, }; case getType(actions.interruptFarming): return { ...state, numInterruptions: state.numInterruptions + 1, }; case getType(actions.resumeFarming): return { ...state, numInterruptions: state.numInterruptions - 1, }; default: return state; } };
import { Reducer } from 'redux'; import { ActionType, getType } from 'typesafe-actions'; import * as actions from './basic-actions'; export interface FarmingState { // The actively farming store, if any readonly storeId?: string; // A counter for pending tasks that interrupt farming readonly numInterruptions: number; } export type FarmingAction = ActionType<typeof actions>; const initialState: FarmingState = { numInterruptions: 0, }; export const farming: Reducer<FarmingState, FarmingAction> = ( state: FarmingState = initialState, action: FarmingAction ) => { switch (action.type) { case getType(actions.start): return { ...state, storeId: action.payload, numInterruptions: 0, }; case getType(actions.stop): return { ...state, storeId: undefined, numInterruptions: 0, }; case getType(actions.interruptFarming): return { ...state, numInterruptions: state.numInterruptions + 1, }; case getType(actions.resumeFarming): return { ...state, numInterruptions: state.numInterruptions - 1, }; default: return state; } };
Reset farming interruptions on start/stop
Reset farming interruptions on start/stop
TypeScript
mit
delphiactual/DIM,DestinyItemManager/DIM,delphiactual/DIM,delphiactual/DIM,delphiactual/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM
--- +++ @@ -24,12 +24,14 @@ return { ...state, storeId: action.payload, + numInterruptions: 0, }; case getType(actions.stop): return { ...state, storeId: undefined, + numInterruptions: 0, }; case getType(actions.interruptFarming):
4876c6722a3d4167f0e4d8d05876fbcaf5960e6a
test/data/User.spec.ts
test/data/User.spec.ts
import {UserSchema, IUserModel} from "../../src/server/data/User"; import {GameSchema, IGameModel} from "../../src/server/data/GameModel"; import mongoose from "mongoose"; import assert from "assert"; const connectionString = "mongodb://localhost/test" const User = mongoose.model("User", UserSchema) as IUserModel; const GameModel = mongoose.model("GameModel", GameSchema) as IGameModel; describe("User", () => { beforeEach(async () => { await mongoose.connect(connectionString); await mongoose.connection.db.dropDatabase() }); afterEach(async () => { await mongoose.disconnect() }) describe("findOrCreate", () => { it("should create user", async () => { await User.findOrCreate("M4T4L4"); const users = await User.find().exec(); assert.equal(1, users.length, "users"); }); }); describe("addGame", () => { it("should add game for logged in user", async () => { const facebookId = "M4T4L4" let user = await User.findOrCreate(facebookId); User.updateName(user._id, "HerraMatala"); const game = await GameModel.findOrCreate("P3L1") await User.addGame(user._id, game); user = await User.findOne({facebookId}).exec(); assert.equal(user.games.length, 1, "added game"); assert.equal(user.games[0].title, "P3L1", "game title"); }); }); });
import {UserSchema, IUserModel} from "../../src/server/data/User"; import {GameSchema, IGameModel} from "../../src/server/data/GameModel"; import mongoose from "mongoose"; import assert from "assert"; const connectionString = "mongodb://localhost/test" const User = mongoose.model("User", UserSchema) as IUserModel; const GameModel = mongoose.model("GameModel", GameSchema) as IGameModel; describe("User", () => { beforeEach(async () => { await mongoose.connect(connectionString); await mongoose.connection.db.dropDatabase() }); afterEach(async () => { await mongoose.disconnect() }) describe("findOrCreate", () => { it("should create user", async () => { await User.findOrCreate("M4T4L4"); const users = await User.find().exec(); assert.equal(1, users.length, "users"); }); }); describe("addGame", () => { it("should add game for logged in user", async () => { const facebookId = "M4T4L4" let user = await User.findOrCreate(facebookId); const game = await GameModel.findOrCreate("P3L1") await User.addGame(user._id, game); user = await User.findOne({facebookId}).exec(); assert.equal(user.games.length, 1, "added game"); assert.equal(user.games[0].title, "P3L1", "game title"); }); }); });
Fix the unit test -> remove unnecessary stuff...
Fix the unit test -> remove unnecessary stuff...
TypeScript
mit
Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki
--- +++ @@ -31,7 +31,6 @@ const facebookId = "M4T4L4" let user = await User.findOrCreate(facebookId); - User.updateName(user._id, "HerraMatala"); const game = await GameModel.findOrCreate("P3L1") await User.addGame(user._id, game);
0b9f9362b94b52130e9a9f09971c4516fe503beb
ui/test/tests-index.ts
ui/test/tests-index.ts
// tslint:disable:interface-name // tslint:disable:no-empty-interface interface IWebpackRequire { context: any; } interface NodeRequire extends IWebpackRequire {} declare var require: NodeRequire; const srcContext = require.context("../src/app/", true, /\.ts$/); srcContext.keys().map(srcContext); const testContext = require.context("./", true, /spec\.ts$/); testContext.keys().map(testContext);
// tslint:disable:interface-name // tslint:disable:no-empty-interface interface IWebpackRequire { context: any; } interface NodeRequire extends IWebpackRequire {} const srcContext = require.context("../src/app/", true, /\.ts$/); srcContext.keys().map(srcContext); const testContext = require.context("./", true, /spec\.ts$/); testContext.keys().map(testContext);
Remove no longer needed declare.
Remove no longer needed declare.
TypeScript
mit
jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr
--- +++ @@ -3,7 +3,6 @@ interface IWebpackRequire { context: any; } interface NodeRequire extends IWebpackRequire {} -declare var require: NodeRequire; const srcContext = require.context("../src/app/", true, /\.ts$/); srcContext.keys().map(srcContext);
a5608af907a1b9d92bc23f69cecc8c191c862738
arduino-uno/tests/blink.ts
arduino-uno/tests/blink.ts
import { Sources, Sinks, HIGH, LOW, run, byte, createSinks } from '../../../src/boards/arduino-uno'; function toggle(value: byte): byte { return value == HIGH ? LOW : HIGH; } function blink(arduino: Sources): Sinks { const sinks: Sinks = createSinks(); sinks.LED$ = arduino.LED$.map(toggle); return sinks; } run(blink);
import { Sources, Sinks, HIGH, LOW, run, byte, createSinks } from '../src/arduino-uno'; function toggle(value: byte): byte { return value == HIGH ? LOW : HIGH; } function blink(arduino: Sources): Sinks { const sinks: Sinks = createSinks(); sinks.LED$ = arduino.LED$.map(toggle); return sinks; } run(blink);
Fix relative path to source file
Fix relative path to source file
TypeScript
mit
artfuldev/RIoT
--- +++ @@ -1,4 +1,4 @@ -import { Sources, Sinks, HIGH, LOW, run, byte, createSinks } from '../../../src/boards/arduino-uno'; +import { Sources, Sinks, HIGH, LOW, run, byte, createSinks } from '../src/arduino-uno'; function toggle(value: byte): byte { return value == HIGH ? LOW : HIGH;
60ad193ffd7f5dcc8309cca6553a79dcf197d17e
tools/env/base.ts
tools/env/base.ts
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/0.9.0', RELEASEVERSION: '0.9.0' }; 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/0.10.0', RELEASEVERSION: '0.10.0' }; export = BaseConfig;
Update release version to 0.10.0.
Update release version to 0.10.0.
TypeScript
mit
nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website
--- +++ @@ -3,8 +3,8 @@ const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', - RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.9.0', - RELEASEVERSION: '0.9.0' + RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.10.0', + RELEASEVERSION: '0.10.0' }; export = BaseConfig;
278b4586508aebd728b027e17b526bbe29444b06
core/i18n/intl.ts
core/i18n/intl.ts
import areIntlLocalesSupported from 'intl-locales-supported' export const importIntlPolyfill = async () => { const IntlPolyfill = await import('intl') global.Intl = IntlPolyfill.default } export const checkForIntlPolyfill = async (storeView) => { if (!global.Intl || !areIntlLocalesSupported(storeView.i18n.defaultLocale)) { await importIntlPolyfill() } }
import areIntlLocalesSupported from 'intl-locales-supported' export const importIntlPolyfill = async () => { const IntlPolyfill = await import('intl') global.Intl = IntlPolyfill.default } export const checkForIntlPolyfill = async (storeView) => { if (!(window || global).Intl || !areIntlLocalesSupported(storeView.i18n.defaultLocale)) { await importIntlPolyfill() } }
Add changes of @gibkigonzo for `window` support
Add changes of @gibkigonzo for `window` support
TypeScript
mit
pkarw/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront
--- +++ @@ -6,7 +6,7 @@ } export const checkForIntlPolyfill = async (storeView) => { - if (!global.Intl || !areIntlLocalesSupported(storeView.i18n.defaultLocale)) { + if (!(window || global).Intl || !areIntlLocalesSupported(storeView.i18n.defaultLocale)) { await importIntlPolyfill() } }
55240c9e6ae7cc3eb421fd361ac2502ef9c90034
frontend/src/webpolls.component.ts
frontend/src/webpolls.component.ts
import { Component, ViewEncapsulation } from "@angular/core"; import { AccountService } from "./auth/account.service"; import { Router } from "@angular/router"; /** * Main component for the application */ @Component({ encapsulation: ViewEncapsulation.None, selector: "wp-app", styleUrls: ["webpolls.css"], templateUrl: "webpolls.html", }) export class WebpollsComponent { constructor(private router: Router, public account: AccountService) {} public login() { this.account.requestLogin(); // tslint:disable-next-line:no-unused-expression this.router; // this is required for Augury to work in debug mode } public logout() { this.account.logout().subscribe(); } }
import { Component, ViewEncapsulation } from "@angular/core"; import { AccountService } from "./auth/account.service"; import { Router } from "@angular/router"; /** * Main component for the application */ @Component({ encapsulation: ViewEncapsulation.None, selector: "wp-app", templateUrl: "webpolls.html", }) export class WebpollsComponent { constructor(private router: Router, public account: AccountService) {} public login() { this.account.requestLogin(); // tslint:disable-next-line:no-unused-expression this.router; // this is required for Augury to work in debug mode } public logout() { this.account.logout().subscribe(); } }
Remove webpolls.css from styles in ts
Remove webpolls.css from styles in ts
TypeScript
mit
BenjaminSchubert/web-polls,BenjaminSchubert/web-polls,BenjaminSchubert/web-polls,BenjaminSchubert/web-polls,BenjaminSchubert/web-polls
--- +++ @@ -9,7 +9,6 @@ @Component({ encapsulation: ViewEncapsulation.None, selector: "wp-app", - styleUrls: ["webpolls.css"], templateUrl: "webpolls.html", }) export class WebpollsComponent {
f1e4a72edde1536ea82791c06b3a3850609b85ff
public/app/shared/stars/auth-stars.ts
public/app/shared/stars/auth-stars.ts
import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'; import { AcStars } from './stars'; import { ToastService } from '../../services/shared/toast.service'; import { AuthService } from '../../services/authentication/auth.service'; import { UserService } from '../../services/shared/user.service'; @Component({ selector: 'auth-ac-stars', template: ` <ac-stars [rating]="rating" (newRate)="onRate($event)" [starCount]="starCount"> </ac-stars> ` }) export class AuthAcStars implements OnInit { private _isLogged: boolean; private _isOwner: boolean; @Input() ownerUsername: boolean; @Input() starCount: number; @Input() rating: number; @Output() newRate = new EventEmitter(); constructor( private _toastService: ToastService, private _authService: AuthService, private _userService: UserService ) { } ngOnInit() { this._isLogged = this._authService.isLoggedIn(); let loggedUser = this._userService.getUserFromLocalStorage() || {}; this._isOwner = loggedUser.username === this.ownerUsername; } onRate(star: any) { if (!this._isLogged) { this._toastService.activate("Please login!"); event.stopPropagation(); } else if (this._isOwner) { this._toastService.activate("Invalid operation!"); event.stopPropagation(); } else { this.newRate.emit(star); } } }
import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'; import { AcStars } from './stars'; import { ToastService } from '../../services/shared/toast.service'; import { AuthService } from '../../services/authentication/auth.service'; import { UserService } from '../../services/shared/user.service'; @Component({ selector: 'auth-ac-stars', template: ` <ac-stars [rating]="rating" (newRate)="onRate($event)" [starCount]="starCount"> </ac-stars> ` }) export class AuthAcStars implements OnInit { private _isOwner: boolean; @Input() ownerUsername: boolean; @Input() starCount: number; @Input() rating: number; @Output() newRate = new EventEmitter(); constructor( private _toastService: ToastService, private _authService: AuthService, private _userService: UserService ) { } ngOnInit() { let loggedUser = this._userService.getUserFromLocalStorage() || {}; this._isOwner = loggedUser.username === this.ownerUsername; } onRate(star: any) { let isLoggedIn = this._authService.isLoggedIn(); if (!isLoggedIn) { this._toastService.activate("Please login!"); event.stopPropagation(); } else if (this._isOwner) { this._toastService.activate("Invalid operation!"); event.stopPropagation(); } else { this.newRate.emit(star); } } }
Fix stars logged in validation bug
Fix stars logged in validation bug
TypeScript
mit
ZmeiDev/stormtroopers,ZmeiDev/stormtroopers,ZmeiDev/stormtroopers
--- +++ @@ -16,7 +16,6 @@ ` }) export class AuthAcStars implements OnInit { - private _isLogged: boolean; private _isOwner: boolean; @Input() ownerUsername: boolean; @@ -31,14 +30,13 @@ ) { } ngOnInit() { - this._isLogged = this._authService.isLoggedIn(); - let loggedUser = this._userService.getUserFromLocalStorage() || {}; this._isOwner = loggedUser.username === this.ownerUsername; } onRate(star: any) { - if (!this._isLogged) { + let isLoggedIn = this._authService.isLoggedIn(); + if (!isLoggedIn) { this._toastService.activate("Please login!"); event.stopPropagation(); }
51885ae979f961adc174a621e655a35069224171
demo/src/app/app.module.ts
demo/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { PrettyJsonModule } from 'angular2-prettyjson'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { LinkedInSdkModule } from '../../temp'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, PrettyJsonModule, LinkedInSdkModule ], providers: [ { provide: 'apiKey', useValue: '77e6o5uw11lpyk' }, { provide: 'authorize', useValue: true} ], bootstrap: [AppComponent] }) export class AppModule { }
import { BrowserModule } from '@angular/platform-browser'; import { PrettyJsonModule } from 'angular2-prettyjson'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { LinkedInSdkModule } from '../../temp'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, PrettyJsonModule, LinkedInSdkModule ], providers: [ { provide: 'apiKey', useValue: 'YOUR_API_KEY' }, { provide: 'authorize', useValue: true} ], bootstrap: [AppComponent] }) export class AppModule { }
Revert "TravisCI Remove script config"
Revert "TravisCI Remove script config" This reverts commit c737aaabd2b9f81ad5bd9e73a256b6bc70787d14.
TypeScript
mit
evodeck/angular-linkedin-sdk,evodeck/angular-linkedin-sdk
--- +++ @@ -14,7 +14,7 @@ LinkedInSdkModule ], providers: [ - { provide: 'apiKey', useValue: '77e6o5uw11lpyk' }, + { provide: 'apiKey', useValue: 'YOUR_API_KEY' }, { provide: 'authorize', useValue: true} ], bootstrap: [AppComponent]
fd2324be6a55dc5a72e800b5807d30e0051a2b0b
charts/covidDataExplorer/CovidRadioControl.tsx
charts/covidDataExplorer/CovidRadioControl.tsx
import React from "react" import { observer } from "mobx-react" import { action } from "mobx" export interface RadioOption { label: string checked: boolean onChange: (checked: boolean) => void } @observer export class CovidRadioControl extends React.Component<{ name: string isCheckbox?: boolean options: RadioOption[] }> { @action.bound onChange(ev: React.ChangeEvent<HTMLInputElement>) { this.props.options[parseInt(ev.currentTarget.value)].onChange( ev.currentTarget.checked ) } render() { const name = this.props.name return ( <div className="CovidDataExplorerControl"> <div className="ControlHeader">{this.props.name}</div> {this.props.options.map((option, index) => ( <div key={index}> <label className={ option.checked ? "SelectedOption" : "Option" } > <input onChange={this.onChange} type={ this.props.isCheckbox ? "checkbox" : "radio" } name={name} data-track-note={`covid-click-${name}`} checked={option.checked} value={index} />{" "} {option.label} </label> </div> ))} </div> ) } }
import React from "react" import { observer } from "mobx-react" import { action } from "mobx" export interface RadioOption { label: string checked: boolean onChange: (checked: boolean) => void } @observer export class CovidRadioControl extends React.Component<{ name: string isCheckbox?: boolean options: RadioOption[] }> { @action.bound onChange(ev: React.ChangeEvent<HTMLInputElement>) { this.props.options[parseInt(ev.currentTarget.value)].onChange( ev.currentTarget.checked ) } render() { const name = this.props.name return ( <div className="CovidDataExplorerControl"> <div className="ControlHeader">{this.props.name}</div> {this.props.options.map((option, index) => ( <div key={index}> <label className={ option.checked ? "SelectedOption" : "Option" } data-track-note={`covid-click-${name}`} > <input onChange={this.onChange} type={ this.props.isCheckbox ? "checkbox" : "radio" } name={name} checked={option.checked} value={index} />{" "} {option.label} </label> </div> ))} </div> ) } }
Move data-track-note to <label> to capture label text content
Move data-track-note to <label> to capture label text content
TypeScript
mit
owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher
--- +++ @@ -31,6 +31,7 @@ className={ option.checked ? "SelectedOption" : "Option" } + data-track-note={`covid-click-${name}`} > <input onChange={this.onChange} @@ -38,7 +39,6 @@ this.props.isCheckbox ? "checkbox" : "radio" } name={name} - data-track-note={`covid-click-${name}`} checked={option.checked} value={index} />{" "}
fb778d8acc5d2985b1495e264c12490abe6bfb72
ts/tests/boards/arduino-uno/blink.ts
ts/tests/boards/arduino-uno/blink.ts
import { Sources, Sinks, HIGH, LOW, run, byte, createSinks } from '../../../src/boards/arduino-uno'; function toggle(value: byte): byte { return value == HIGH ? LOW : HIGH; } function blink(arduino: Sources): Sinks { const sinks = createSinks(); sinks.LED$ = arduino.LED$.map(toggle); return sinks; } run(blink);
import { Sources, Sinks, HIGH, LOW, run, byte, createSinks } from '../../../src/boards/arduino-uno'; function toggle(value: byte): byte { return value == HIGH ? LOW : HIGH; } function blink(arduino: Sources): Sinks { const sinks: Sinks = createSinks(); sinks.LED$ = arduino.LED$.map(toggle); return sinks; } run(blink);
Add type to variable declaration
Add type to variable declaration
TypeScript
mit
artfuldev/RIoT
--- +++ @@ -5,7 +5,7 @@ } function blink(arduino: Sources): Sinks { - const sinks = createSinks(); + const sinks: Sinks = createSinks(); sinks.LED$ = arduino.LED$.map(toggle); return sinks; }
48670678be9a01b7bf8451b210af9e43bef5b05e
src/types/state.ts
src/types/state.ts
import { AlphabetsData } from '@/types/alphabets' import { Sentence } from '@/types/phrases' /* * State * The Vuex store state */ export type State = { text: string alphabets: AlphabetsData phrases: Sentence[] settings: Settings } /* * Settings * Used for fine-tuning the output and stuff. Any of them can be * user-configurable if they're exposed to the UI */ export type Settings = { splits: string[] selectedAlphabets: string[] structure: string scaling: boolean watermark: boolean debug: boolean width: number foregroundColour: string backgroundColour: string config: Config } export type Config = { // TODO work out what the FUCK these mean s: BlockConfig p: BlockConfig d: BlockConfig f: BlockConfig v: VowelBlockConfig word: BlockConfig buffer: BufferConfig automatic: AutomaticConfig } export type BlockConfig = { height: number // Height of this letter above (inside) the word circle width: number // The base relativeAngularSize for a letter in this block } export type VowelBlockConfig = BlockConfig & { // What is r??????? r: number } export type BufferConfig = { letter: number phrase: number } export type AutomaticConfig = { // The naming scheme here is terrible scaledLessThan: number spiralMoreThan: number }
import { AlphabetsData } from '@/types/alphabets' import { Sentence } from '@/types/phrases' /* * State * The Vuex store state */ export type State = { text: string alphabets: AlphabetsData phrases: Sentence[] settings: Settings } /* * Settings * Used for fine-tuning the output and stuff. Any of them can be * user-configurable if they're exposed to the UI */ export type Settings = { splits: string[] selectedAlphabets: string[] scaling: boolean watermark: boolean debug: boolean width: number foregroundColour: string backgroundColour: string config: Config } export type Config = { // TODO work out what the FUCK these mean s: BlockConfig p: BlockConfig d: BlockConfig f: BlockConfig v: VowelBlockConfig word: BlockConfig buffer: BufferConfig automatic: AutomaticConfig sizeDependenceOnLength: number positionAlgorithm: 'Circular' | 'Spiral' } export type BlockConfig = { height: number // Height of this letter above (inside) the word circle width: number // The base relativeAngularSize for a letter in this block } export type VowelBlockConfig = BlockConfig & { // What is r??????? r: number } export type BufferConfig = { letter: number phrase: number } export type AutomaticConfig = { // The naming scheme here is terrible scaledLessThan: number spiralMoreThan: number }
Split up structure type into numeric size and string position
Split up structure type into numeric size and string position
TypeScript
mit
rossjrw/gallifreyo,rossjrw/gallifreyo,rossjrw/gallifreyo
--- +++ @@ -22,7 +22,6 @@ export type Settings = { splits: string[] selectedAlphabets: string[] - structure: string scaling: boolean watermark: boolean debug: boolean @@ -42,6 +41,8 @@ word: BlockConfig buffer: BufferConfig automatic: AutomaticConfig + sizeDependenceOnLength: number + positionAlgorithm: 'Circular' | 'Spiral' } export type BlockConfig = {
f6a0a080f46f3b6d159b565b45458c5e066cc63d
app/navbar.component.ts
app/navbar.component.ts
import {Component, EventEmitter} from 'angular2/core'; import {NavbarTab} from './navbartab'; @Component({ selector: 'navbar', template: `<nav class="navbar"> <div class="nav"> <a *ngFor="#tab of tabs" [class.active]="tab === selectedTab" (click)="onSelect(tab)" href="#"> {{tab.name}} </a> </div> </nav>`, inputs: ['selectedTab'], events: ['selectedTabChanged'] }) export class NavbarComponent { public selectedTab: NavbarTab; public selectedTabChanged = new EventEmitter<NavbarTab>(); private tabs: NavbarTab[] = [ { name: "Reminders", filter: (s: number) => { return s == 1 || s == 2 } }, { name: "Timers", filter: (s: number) => { return s == 0 } }, { name: "Logged", filter: (s: number) => { return s > 2 } } ] constructor() { this.onSelect(this.tabs[0]); } onSelect(tab: NavbarTab) { this.selectedTab = tab; this.selectedTabChanged.emit(tab); } }
import {Component, EventEmitter} from 'angular2/core'; import {NavbarTab} from './navbartab'; @Component({ selector: 'navbar', template: `<nav class="navbar"> <div class="nav"> <a *ngFor="#tab of tabs" [class.active]="tab === selectedTab" (click)="onSelect(tab)" href="#"> {{tab.name}} </a> </div> </nav>`, inputs: ['selectedTab'], events: ['selectedTabChanged'] }) export class NavbarComponent { public selectedTab: NavbarTab; public selectedTabChanged = new EventEmitter<NavbarTab>(); private tabs: NavbarTab[] = [ { name: "Reminders", filter: (s: number) => { return s == 1 || s == 2 } }, { name: "Timers", filter: (s: number) => { return s == 0 } }, { name: "Logged", filter: (s: number) => { return s > 2 } } ] constructor() { } ngOnInit() { this.onSelect(this.tabs[0]); } onSelect(tab: NavbarTab) { this.selectedTab = tab; this.selectedTabChanged.emit(tab); } }
Select the Reminders tab on load
Select the Reminders tab on load
TypeScript
mit
rzhw/redue,rzhw/redue,rzhw/redue
--- +++ @@ -25,7 +25,9 @@ { name: "Logged", filter: (s: number) => { return s > 2 } } ] - constructor() { + constructor() { } + + ngOnInit() { this.onSelect(this.tabs[0]); }
1b9360df5bb626c1d37e5144ef83d9da9c59a345
src/app/attribute-directives/tumblr-embedded-media.directive.ts
src/app/attribute-directives/tumblr-embedded-media.directive.ts
import {Directive, ElementRef, DoCheck} from '@angular/core'; @Directive({selector: '[tumblrEmbeddedMedia]'}) export class TumblrEmbeddedMediaDirective implements DoCheck { private el: ElementRef; constructor(el: ElementRef) { this.el = el; } ngDoCheck() { const mediaElements = this.el.nativeElement.querySelectorAll('img, video'); if (mediaElements.length > 0) { for (const mediaElement of mediaElements) { mediaElement.parentElement.style.marginLeft = 0; mediaElement.parentElement.style.marginRight = 0; mediaElement.setAttribute('width', '100%'); mediaElement.setAttribute('height', ''); if (mediaElement.nodeName === 'VIDEO') { mediaElement.removeAttribute('autoplay'); mediaElement.setAttribute('controls', ''); mediaElement.removeAttribute('muted'); mediaElement.setAttribute('preload', 'metadata'); mediaElement.muted = false; } } } } }
import {Directive, ElementRef, DoCheck} from '@angular/core'; @Directive({selector: '[tumblrEmbeddedMedia]'}) export class TumblrEmbeddedMediaDirective implements DoCheck { private el: ElementRef; constructor(el: ElementRef) { this.el = el; } ngDoCheck() { const mediaElements = this.el.nativeElement.querySelectorAll('img, video'); if (mediaElements.length > 0) { for (const mediaElement of mediaElements) { const parent = mediaElement.parentElement; // media embedded in a post if (parent.nodeName === 'FIGURE') { parent.style.marginLeft = 0; parent.style.marginRight = 0; if (parent.nextSibling && parent.nextSibling.nodeName !== 'FIGURE' && parent.nextSibling.setAttribute) { parent.nextSibling.setAttribute('switch-target', ''); } } mediaElement.setAttribute('width', '100%'); mediaElement.setAttribute('height', ''); mediaElement.setAttribute('switch-target', ''); if (mediaElement.nodeName === 'VIDEO') { mediaElement.removeAttribute('autoplay'); mediaElement.setAttribute('controls', ''); mediaElement.removeAttribute('muted'); mediaElement.setAttribute('preload', 'metadata'); mediaElement.muted = false; } } } } }
Add switch-target to embedded media and text following immediatly
Add switch-target to embedded media and text following immediatly
TypeScript
mit
zoehneto/tumblr-reader,zoehneto/tumblr-reader,zoehneto/tumblr-reader
--- +++ @@ -12,10 +12,21 @@ const mediaElements = this.el.nativeElement.querySelectorAll('img, video'); if (mediaElements.length > 0) { for (const mediaElement of mediaElements) { - mediaElement.parentElement.style.marginLeft = 0; - mediaElement.parentElement.style.marginRight = 0; + const parent = mediaElement.parentElement; + + // media embedded in a post + if (parent.nodeName === 'FIGURE') { + parent.style.marginLeft = 0; + parent.style.marginRight = 0; + + if (parent.nextSibling && parent.nextSibling.nodeName !== 'FIGURE' && parent.nextSibling.setAttribute) { + parent.nextSibling.setAttribute('switch-target', ''); + } + } + mediaElement.setAttribute('width', '100%'); mediaElement.setAttribute('height', ''); + mediaElement.setAttribute('switch-target', ''); if (mediaElement.nodeName === 'VIDEO') { mediaElement.removeAttribute('autoplay');
ac6d7e02ebc68c8769d7ad8a31463ff457554d9e
frontend/src/app/application-dashboard/service/application-dashboard.service.ts
frontend/src/app/application-dashboard/service/application-dashboard.service.ts
import {Injectable} from '@angular/core'; import {HttpClient} from "@angular/common/http"; import {Observable} from "rxjs/index"; import {IPage} from "../model/page.model"; @Injectable() export class ApplicationDashboardService { constructor(private http: HttpClient) { } getPagesForJobGroup(applicationId: number): Observable<IPage[]> { return this.http.get<IPage[]>("/applicationDashboard/getPagesForApplication", { params: { applicationId: applicationId.toString() } }); } }
import {Injectable} from '@angular/core'; import {HttpClient} from "@angular/common/http"; import {Observable} from "rxjs/index"; import {IPage} from "../model/page.model"; @Injectable() export class ApplicationDashboardService { constructor(private http: HttpClient) { } getPagesForJobGroup(applicationId: number): Observable<IPage[]> { return this.http.get<IPage[]>("/applicationDashboard/getPagesForApplication", { params: { applicationId: applicationId ? applicationId.toString() : "" } }); } }
Handle empty job group id in rest call for pages
[IT-2250] Handle empty job group id in rest call for pages
TypeScript
apache-2.0
IteraSpeed/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,IteraSpeed/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,IteraSpeed/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor
--- +++ @@ -12,7 +12,7 @@ getPagesForJobGroup(applicationId: number): Observable<IPage[]> { return this.http.get<IPage[]>("/applicationDashboard/getPagesForApplication", { params: { - applicationId: applicationId.toString() + applicationId: applicationId ? applicationId.toString() : "" } }); }
d82850d7e1672997e0e886e6abf08ab2c7b8cee6
src/TokenExceptions.ts
src/TokenExceptions.ts
import IToken from './IToken' import { GherkinException } from './Errors' export class UnexpectedTokenException extends GherkinException { public static create<TokenType>(token: IToken<TokenType>, expectedTokenTypes: string[]) { const message = `expected: ${expectedTokenTypes.join( ', ' )}, got '${token.getTokenValue().trim()}'` const location = tokenLocation(token) return this._create(message, location) } } export class UnexpectedEOFException extends GherkinException { public static create<TokenType>(token: IToken<TokenType>, expectedTokenTypes: string[]) { const message = `unexpected end of file, expected: ${expectedTokenTypes.join(', ')}` const location = tokenLocation(token) return this._create(message, location) } } function tokenLocation<TokenType>(token: IToken<TokenType>) { return token.location && token.location.line && token.line && token.line.indent !== undefined ? { line: token.location.line, column: token.line.indent + 1, } : token.location }
import IToken from './IToken' import { GherkinException } from './Errors' export class UnexpectedTokenException extends GherkinException { public static create<TokenType>(token: IToken<TokenType>, expectedTokenTypes: string[]) { const message = `expected: ${expectedTokenTypes.join(', ')}, got '${token .getTokenValue() .trim()}'` const location = tokenLocation(token) return this._create(message, location) } } export class UnexpectedEOFException extends GherkinException { public static create<TokenType>(token: IToken<TokenType>, expectedTokenTypes: string[]) { const message = `unexpected end of file, expected: ${expectedTokenTypes.join(', ')}` const location = tokenLocation(token) return this._create(message, location) } } function tokenLocation<TokenType>(token: IToken<TokenType>) { return token.location && token.location.line && token.line && token.line.indent !== undefined ? { line: token.location.line, column: token.line.indent + 1, } : token.location }
Downgrade hast-util-sanitize to 3.0.2 to avoid ESM errors
Downgrade hast-util-sanitize to 3.0.2 to avoid ESM errors
TypeScript
mit
cucumber/gherkin-javascript,cucumber/gherkin-javascript
--- +++ @@ -3,9 +3,9 @@ export class UnexpectedTokenException extends GherkinException { public static create<TokenType>(token: IToken<TokenType>, expectedTokenTypes: string[]) { - const message = `expected: ${expectedTokenTypes.join( - ', ' - )}, got '${token.getTokenValue().trim()}'` + const message = `expected: ${expectedTokenTypes.join(', ')}, got '${token + .getTokenValue() + .trim()}'` const location = tokenLocation(token)
910a0b016ae596f3a982af1140d39895b6467f32
packages/react-cosmos-shared2/src/FixtureLoader/FixtureCapture/shared/findRelevantElementPaths.ts
packages/react-cosmos-shared2/src/FixtureLoader/FixtureCapture/shared/findRelevantElementPaths.ts
import React from 'react'; import { findElementPaths, getExpectedElementAtPath } from './nodeTree'; type ExtendedComponentClass = React.ComponentClass & { cosmosCapture?: boolean; }; export function findRelevantElementPaths(node: React.ReactNode): string[] { const elPaths = findElementPaths(node); return elPaths.filter(elPath => { const { type } = getExpectedElementAtPath(node, elPath); if (typeof type === 'string') { return isInterestingTag(type); } const classType = type as ExtendedComponentClass; return classType.cosmosCapture !== false && isInterestingClass(classType); }); } function isInterestingTag(tagName: string) { // TODO: Make this customizable return tagName !== 'div' && tagName !== 'span'; } function isInterestingClass(type: React.ComponentClass) { // TODO: Make this customizable return type.name !== 'StyledComponent'; }
import React from 'react'; import { findElementPaths, getExpectedElementAtPath } from './nodeTree'; type ExtendedComponentClass = React.ComponentClass & { cosmosCapture?: boolean; }; export function findRelevantElementPaths(node: React.ReactNode): string[] { const elPaths = findElementPaths(node); return elPaths.filter(elPath => { const { type } = getExpectedElementAtPath(node, elPath); // Ignore symbol types, like StrictMode // https://github.com/react-cosmos/react-cosmos/issues/1249 if (typeof type === 'symbol') return false; if (typeof type === 'string') return isInterestingTag(type); const classType = type as ExtendedComponentClass; return classType.cosmosCapture !== false && isInterestingClass(classType); }); } function isInterestingTag(tagName: string) { // TODO: Make this customizable return tagName !== 'div' && tagName !== 'span'; } function isInterestingClass(type: React.ComponentClass) { // TODO: Make this customizable return type.name !== 'StyledComponent'; }
Enable using StrictMode in fixtures
Enable using StrictMode in fixtures
TypeScript
mit
skidding/react-cosmos,skidding/react-cosmos,skidding/cosmos,react-cosmos/react-cosmos,skidding/cosmos,react-cosmos/react-cosmos,react-cosmos/react-cosmos
--- +++ @@ -11,9 +11,11 @@ return elPaths.filter(elPath => { const { type } = getExpectedElementAtPath(node, elPath); - if (typeof type === 'string') { - return isInterestingTag(type); - } + // Ignore symbol types, like StrictMode + // https://github.com/react-cosmos/react-cosmos/issues/1249 + if (typeof type === 'symbol') return false; + + if (typeof type === 'string') return isInterestingTag(type); const classType = type as ExtendedComponentClass; return classType.cosmosCapture !== false && isInterestingClass(classType);
c7608162a4dfc500c04475cf45583f0e358d0037
packages/webdriverio/src/index.ts
packages/webdriverio/src/index.ts
import { Browser } from 'mugshot'; /** * API adapter for WebdriverIO to make working with it saner. */ export default class WebdriverIOAdapter implements Browser { private browser: WebDriver.ClientAsync & WebdriverIOAsync.Browser; constructor(browser: WebDriver.ClientAsync & WebdriverIOAsync.Browser) { this.browser = browser; } takeScreenshot = async () => this.browser.takeScreenshot(); getElementRect = async (selector: string) => { // @ts-ignore because the return type is not properly inferred const rect: DOMRect = await this.browser.execute( WebdriverIOAdapter.getBoundingRect, selector ); return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }; }; private static getBoundingRect(selector: string): DOMRect { // @ts-ignore because querySelector can be null and we don't // care about browsers that don't support it. return document.querySelector(selector).getBoundingClientRect(); } }
import { Browser } from 'mugshot'; /* istanbul ignore next because this will get stringified and sent to the browser */ function getBoundingRect(selector: string): DOMRect { // @ts-ignore because querySelector can be null and we don't // care about browsers that don't support it. return document.querySelector(selector).getBoundingClientRect(); } /** * API adapter for WebdriverIO to make working with it saner. */ export default class WebdriverIOAdapter implements Browser { private browser: WebDriver.ClientAsync & WebdriverIOAsync.Browser; constructor(browser: WebDriver.ClientAsync & WebdriverIOAsync.Browser) { this.browser = browser; } takeScreenshot = async () => this.browser.takeScreenshot(); getElementRect = async (selector: string) => { // @ts-ignore because the return type is not properly inferred const rect: DOMRect = await this.browser.execute( getBoundingRect, selector ); return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }; }; }
Fix stringified function breaking under istanbul
Fix stringified function breaking under istanbul
TypeScript
mit
uberVU/mugshot,uberVU/mugshot
--- +++ @@ -1,4 +1,11 @@ import { Browser } from 'mugshot'; + +/* istanbul ignore next because this will get stringified and sent to the browser */ +function getBoundingRect(selector: string): DOMRect { + // @ts-ignore because querySelector can be null and we don't + // care about browsers that don't support it. + return document.querySelector(selector).getBoundingClientRect(); +} /** * API adapter for WebdriverIO to make working with it saner. @@ -15,7 +22,7 @@ getElementRect = async (selector: string) => { // @ts-ignore because the return type is not properly inferred const rect: DOMRect = await this.browser.execute( - WebdriverIOAdapter.getBoundingRect, + getBoundingRect, selector ); @@ -26,10 +33,4 @@ height: rect.height }; }; - - private static getBoundingRect(selector: string): DOMRect { - // @ts-ignore because querySelector can be null and we don't - // care about browsers that don't support it. - return document.querySelector(selector).getBoundingClientRect(); - } }
acbd8bcdef198be98c248c90868233dcf02e8ab7
src/Components/form-group-component/form-group-component.spec.ts
src/Components/form-group-component/form-group-component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { FormGroupComponent } from './form-group-component'; describe('FormGroupComponent', () => { let component: FormGroupComponent; let fixture: ComponentFixture<FormGroupComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ FormGroupComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(FormGroupComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
import {async, ComponentFixture, TestBed} from "@angular/core/testing"; import {FormGroupComponent} from "./form-group-component"; import {ErrorMessageService} from "../../Services/error-message.service"; import {CUSTOM_ERROR_MESSAGES} from "../../Tokens/tokens"; import {errorMessageService} from "../../ng-bootstrap-form-validation.module"; describe('FormGroupComponent', () => { let component: FormGroupComponent; let fixture: ComponentFixture<FormGroupComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [FormGroupComponent], providers: [ { provide: ErrorMessageService, useFactory: errorMessageService, deps: [CUSTOM_ERROR_MESSAGES] }, { provide: CUSTOM_ERROR_MESSAGES, useValue: [] } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(FormGroupComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
Fix form group component test
Fix form group component test
TypeScript
mit
third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation
--- +++ @@ -1,25 +1,39 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import {async, ComponentFixture, TestBed} from "@angular/core/testing"; -import { FormGroupComponent } from './form-group-component'; +import {FormGroupComponent} from "./form-group-component"; +import {ErrorMessageService} from "../../Services/error-message.service"; +import {CUSTOM_ERROR_MESSAGES} from "../../Tokens/tokens"; +import {errorMessageService} from "../../ng-bootstrap-form-validation.module"; describe('FormGroupComponent', () => { - let component: FormGroupComponent; - let fixture: ComponentFixture<FormGroupComponent>; + let component: FormGroupComponent; + let fixture: ComponentFixture<FormGroupComponent>; - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ FormGroupComponent ] - }) - .compileComponents(); - })); + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [FormGroupComponent], + providers: [ + { + provide: ErrorMessageService, + useFactory: errorMessageService, + deps: [CUSTOM_ERROR_MESSAGES] + }, + { + provide: CUSTOM_ERROR_MESSAGES, + useValue: [] + } + ] + }) + .compileComponents(); + })); - beforeEach(() => { - fixture = TestBed.createComponent(FormGroupComponent); - component = fixture.componentInstance; - fixture.detectChanges(); - }); + beforeEach(() => { + fixture = TestBed.createComponent(FormGroupComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); - it('should create', () => { - expect(component).toBeTruthy(); - }); + it('should create', () => { + expect(component).toBeTruthy(); + }); });
2edee8cf9e3320ecb8a486dda36bdc18b795cbe6
java-front/languages/Java-1.5/expressions/types/bitwise-logical.ts
java-front/languages/Java-1.5/expressions/types/bitwise-logical.ts
module languages/Java-1.5/expressions/types/bitwise-logical imports include/Java lib/task/- lib/types/- lib/properties/- lib/relations/- languages/Java-1.5/types/types/primitives languages/Java-1.5/types/types/promotion type rules t@And(x, y) + t@ExcOr(x, y) + t@Or(x, y) : ty where x : x-ty and y : y-ty and ( ( x-ty <is: Integral() and y-ty <is: Integral() and <promote-bin> (x-ty, y-ty) => ty ) or ( x-ty == Boolean() and y-ty == Boolean() and Boolean() => ty ) ) else error "Expected numbers or booleans" on t t@LazyAnd(x, y) + t@LazyOr(x, y) : Boolean() where x : x-ty and y : y-ty and x-ty == Boolean() and y-ty == Boolean() else error "Expected booleans" on t Not(e) : ty where e : ty and ty == Boolean() else error "Expected boolean" on e Complement(e) : prom-ty where e : ty and <promote-un> ty => prom-ty and prom-ty <is: Integral() else error "Expected integral" on e
module languages/Java-1.5/expressions/types/bitwise-logical imports include/Java lib/task/- lib/types/- lib/properties/- lib/relations/- languages/Java-1.5/types/types/primitives languages/Java-1.5/types/types/promotion type rules t@And(x, y) + t@ExcOr(x, y) + t@Or(x, y) : ty where x : x-ty and y : y-ty and ( ( x-ty <is: Integral() and y-ty <is: Integral() and <promote-bin> (x-ty, y-ty) => ty ) or ( x-ty == Boolean() and y-ty == Boolean() and Boolean() => ty ) ) else error "Expected numbers or booleans" on t t@LazyAnd(x, y) + t@LazyOr(x, y) : Boolean() where x : x-ty and y : y-ty and x-ty == Boolean() and y-ty == Boolean() else error "Expected booleans" on t Not(e) : Boolean() where e : ty and ty == Boolean() else error "Expected boolean" on e Complement(e) : prom-ty where e : ty and <promote-un> ty => prom-ty and prom-ty <is: Integral() else error "Expected integral" on e
Fix wrong type of not expression.
Fix wrong type of not expression.
TypeScript
apache-2.0
metaborg/java-front,metaborg/java-front
--- +++ @@ -36,7 +36,7 @@ and x-ty == Boolean() and y-ty == Boolean() else error "Expected booleans" on t - Not(e) : ty + Not(e) : Boolean() where e : ty and ty == Boolean() else error "Expected boolean" on e
0a6d22a4c7840f7a7ffcd3cfbeacd886e77eb9d9
app/views/sessions/session/visualization/textvisualization/textvisualization.component.ts
app/views/sessions/session/visualization/textvisualization/textvisualization.component.ts
import FileResource from "../../../../../resources/fileresource"; import SessionDataService from "../../sessiondata.service"; class TextVisualizationController { static $inject = ['FileResource', '$scope', 'SessionDataService']; datasetId: string; data: string; constructor(private fileResource: FileResource, private $scope: ng.IScope, private SessionDataService: SessionDataService) { } $onInit() { this.fileResource.getData(this.SessionDataService.getSessionId(), this.datasetId).then( (resp: any) => { this.data = resp.data; }); } } export default { controller: TextVisualizationController, template: '<p>{{$ctrl.data}}</p>', bindings: { datasetId: '<' } }
import FileResource from "../../../../../resources/fileresource"; import SessionDataService from "../../sessiondata.service"; class TextVisualizationController { static $inject = ['FileResource', '$scope', 'SessionDataService']; datasetId: string; data: string; constructor(private fileResource: FileResource, private $scope: ng.IScope, private SessionDataService: SessionDataService) { } $onInit() { this.fileResource.getData(this.SessionDataService.getSessionId(), this.datasetId).then( (resp: any) => { this.$scope.$apply(() => { this.data = resp.data; }); }); } } export default { controller: TextVisualizationController, template: '<p>{{$ctrl.data}}</p>', bindings: { datasetId: '<' } }
Update view when we get the reponse
Update view when we get the reponse
TypeScript
mit
chipster/chipster-web,chipster/chipster-web,chipster/chipster-web
--- +++ @@ -13,7 +13,9 @@ $onInit() { this.fileResource.getData(this.SessionDataService.getSessionId(), this.datasetId).then( (resp: any) => { - this.data = resp.data; + this.$scope.$apply(() => { + this.data = resp.data; + }); }); }
555166bb60ce537936009bc8f886473c7e7a88cf
screensaver_ru.ts
screensaver_ru.ts
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0"> <context> <name>PanelScreenSaver</name> <message> <source>Panel Screensaver Global shortcut: &apos;%1&apos; cannot be registered</source> <translation>Глобальная Панель клавиш короткий путь Заставка: &apos;%1&apos; не могут быть зарегистрированы</translation> </message> </context> </TS>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="ru"> <context> <name>PanelScreenSaver</name> <message> <location filename="../panelscreensaver.cpp" line="52"/> <source>Lock Screen</source> <translation>Блокировать экран</translation> </message> <message> <location filename="../panelscreensaver.cpp" line="62"/> <source>Panel Screensaver: Global shortcut &apos;%1&apos; cannot be registered</source> <translation>Хранитель экрана панели: глобальное сочетание клавиш &apos;%1&apos; не может быть зарегистрировано</translation> </message> </context> </TS>
Revert "Commit from LXDE Pootle server by user LStranger.: 391 of 391 strings translated (0 need review)."
Revert "Commit from LXDE Pootle server by user LStranger.: 391 of 391 strings translated (0 need review)." This reverts commit d538764d91b1cf3ea993cdf0d6200eea2b2c9384. It appeared this change was wrong because it was out of sync.
TypeScript
lgpl-2.1
lxde/lxqt-l10n
--- +++ @@ -1,9 +1,17 @@ -<?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0"> +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE TS> +<TS version="2.1" language="ru"> <context> <name>PanelScreenSaver</name> <message> - <source>Panel Screensaver Global shortcut: &apos;%1&apos; cannot be registered</source> - <translation>Глобальная Панель клавиш короткий путь Заставка: &apos;%1&apos; не могут быть зарегистрированы</translation> + <location filename="../panelscreensaver.cpp" line="52"/> + <source>Lock Screen</source> + <translation>Блокировать экран</translation> + </message> + <message> + <location filename="../panelscreensaver.cpp" line="62"/> + <source>Panel Screensaver: Global shortcut &apos;%1&apos; cannot be registered</source> + <translation>Хранитель экрана панели: глобальное сочетание клавиш &apos;%1&apos; не может быть зарегистрировано</translation> </message> </context> </TS>
cf4e14adace565fb38c9fea4630ddf2a687fb3b2
generators/app/templates/src/index.ts
generators/app/templates/src/index.ts
export * from './<%- ngModuleFilename %>'; // all components that will be codegen'd need to be exported for AOT to work export * from './helloWorld.component';
export * from './<%- ngModuleFilename.replace('.ts', '') %>'; // all components that will be codegen'd need to be exported for AOT to work export * from './helloWorld.component';
Remove .ts from module filename import
Remove .ts from module filename import
TypeScript
mit
mattlewis92/generator-angular-library,mattlewis92/generator-angular-library,mattlewis92/generator-angular-library
--- +++ @@ -1,4 +1,4 @@ -export * from './<%- ngModuleFilename %>'; +export * from './<%- ngModuleFilename.replace('.ts', '') %>'; // all components that will be codegen'd need to be exported for AOT to work export * from './helloWorld.component';
b830f908ae488308596a9dd50d42e0275cab96fc
projects/angular2-cookie-law/src/lib/angular2-cookie-law.service.ts
projects/angular2-cookie-law/src/lib/angular2-cookie-law.service.ts
/** * angular2-cookie-law * * Copyright 2016-2018, @andreasonny83, All rights reserved. * * @author: @andreasonny83 <andreasonny83@gmail.com> */ import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class Angular2CookieLawService { public seen(cookieName: string = 'cookieLawSeen'): boolean { const cookies: Array<string> = document.cookie.split(';'); return this.cookieExisits(cookieName, cookies); } public storeCookie(cookieName: string, expiration?: number): void { return this.setCookie(cookieName, expiration); } private cookieExisits(name: string, cookies: Array<string>): boolean { const cookieName = `${name}=`; return cookies.reduce((prev, curr) => prev || curr.trim().search(cookieName) > -1, false); } private setCookie(name: string, expiration?: number): void { const now: Date = new Date(); const exp: Date = new Date(now.getTime() + expiration * 86400000); const cookieString = encodeURIComponent(name) + `=true;path=/;expires=${exp.toUTCString()};`; document.cookie = cookieString; } }
/** * angular2-cookie-law * * Copyright 2016-2018, @andreasonny83, All rights reserved. * * @author: @andreasonny83 <andreasonny83@gmail.com> */ import { Inject, Injectable, PLATFORM_ID } from '@angular/core'; import { DOCUMENT, isPlatformBrowser } from '@angular/common'; @Injectable({ providedIn: 'root' }) export class Angular2CookieLawService { constructor( @Inject(DOCUMENT) private doc: any, @Inject(PLATFORM_ID) private platform: Object ) { } public seen(cookieName: string = 'cookieLawSeen'): boolean { let cookies: Array<string> = []; if (isPlatformBrowser(this.platform)) { cookies = this.doc.cookie.split(';'); } return this.cookieExisits(cookieName, cookies); } public storeCookie(cookieName: string, expiration?: number): void { return this.setCookie(cookieName, expiration); } private cookieExisits(name: string, cookies: Array<string>): boolean { const cookieName = `${name}=`; return cookies.reduce((prev, curr) => prev || curr.trim().search(cookieName) > -1, false); } private setCookie(name: string, expiration?: number): void { const now: Date = new Date(); const exp: Date = new Date(now.getTime() + expiration * 86400000); const cookieString = encodeURIComponent(name) + `=true;path=/;expires=${exp.toUTCString()};`; if (isPlatformBrowser(this.platform)) { this.doc.cookie = cookieString; } } }
Reimplement fix for Angular Universal compatibility and make sure it doesn't break the production build
Reimplement fix for Angular Universal compatibility and make sure it doesn't break the production build
TypeScript
mit
andreasonny83/angular2-cookie-law,andreasonny83/angular2-cookie-law,andreasonny83/angular2-cookie-law
--- +++ @@ -6,14 +6,25 @@ * @author: @andreasonny83 <andreasonny83@gmail.com> */ -import { Injectable } from '@angular/core'; +import { Inject, Injectable, PLATFORM_ID } from '@angular/core'; +import { DOCUMENT, isPlatformBrowser } from '@angular/common'; @Injectable({ providedIn: 'root' }) export class Angular2CookieLawService { + + constructor( + @Inject(DOCUMENT) private doc: any, + @Inject(PLATFORM_ID) private platform: Object + ) { } + public seen(cookieName: string = 'cookieLawSeen'): boolean { - const cookies: Array<string> = document.cookie.split(';'); + let cookies: Array<string> = []; + + if (isPlatformBrowser(this.platform)) { + cookies = this.doc.cookie.split(';'); + } return this.cookieExisits(cookieName, cookies); } @@ -36,6 +47,8 @@ const cookieString = encodeURIComponent(name) + `=true;path=/;expires=${exp.toUTCString()};`; - document.cookie = cookieString; + if (isPlatformBrowser(this.platform)) { + this.doc.cookie = cookieString; + } } }
e315e8aa4ce8acc3d4173f8b43f034b0e802c731
src/Test/Ast/Config/Image.ts
src/Test/Ast/Config/Image.ts
import { expect } from 'chai' import Up from '../../../index' import { ImageNode } from '../../../SyntaxNodes/ImageNode' import { DocumentNode } from '../../../SyntaxNodes/DocumentNode' describe('The term that represents image conventions', () => { const up = new Up({ terms: { image: 'see' } }) it('comes from the "image" config term', () => { const markup = '[see: Chrono Cross logo][https://example.com/cc.png]' expect(up.toAst(markup)).to.be.eql( new DocumentNode([ new ImageNode('Chrono Cross logo', 'https://example.com/cc.png') ])) }) it('is case-insensitive even when custom', () => { const lowercase = '[see: Chrono Cross logo][https://example.com/cc.png]' const mixedCase = '[SeE: Chrono Cross logo][https://example.com/cc.png]' expect(up.toAst(mixedCase)).to.be.eql(up.toAst(lowercase)) }) })
import { expect } from 'chai' import Up from '../../../index' import { ImageNode } from '../../../SyntaxNodes/ImageNode' import { DocumentNode } from '../../../SyntaxNodes/DocumentNode' describe('The term that represents image conventions', () => { const up = new Up({ terms: { image: 'see' } }) it('comes from the "image" config term', () => { const markup = '[see: Chrono Cross logo][https://example.com/cc.png]' expect(up.toAst(markup)).to.be.eql( new DocumentNode([ new ImageNode('Chrono Cross logo', 'https://example.com/cc.png') ])) }) it('is case-insensitive even when custom', () => { const lowercase = '[see: Chrono Cross logo][https://example.com/cc.png]' const mixedCase = '[SeE: Chrono Cross logo][https://example.com/cc.png]' expect(up.toAst(mixedCase)).to.be.eql(up.toAst(lowercase)) }) it('ignores any regular expression syntax', () => { const markup = '[+see+: Chrono Cross logo][https://example.com/cc.png]' expect(Up.toAst(markup, { terms: { image: '+see+' } })).to.be.eql( new DocumentNode([ new ImageNode('Chrono Cross logo', 'https://example.com/cc.png') ])) }) it('can have multiple variations', () => { const markup = '[look: Chrono Cross logo](https://example.com/cc.png) [view: Chrono Cross logo](https://example.com/cc.png)' expect(Up.toAst(markup, { terms: { video: ['view', 'look'] } })).to.be.eql( new DocumentNode([ new ImageNode('Chrono Cross logo', 'https://example.com/cc.png'), new ImageNode('Chrono Cross logo', 'https://example.com/cc.png') ])) }) })
Add 2 tests, 1 failing
Add 2 tests, 1 failing
TypeScript
mit
start/up,start/up
--- +++ @@ -24,4 +24,23 @@ expect(up.toAst(mixedCase)).to.be.eql(up.toAst(lowercase)) }) + + it('ignores any regular expression syntax', () => { + const markup = '[+see+: Chrono Cross logo][https://example.com/cc.png]' + + expect(Up.toAst(markup, { terms: { image: '+see+' } })).to.be.eql( + new DocumentNode([ + new ImageNode('Chrono Cross logo', 'https://example.com/cc.png') + ])) + }) + + it('can have multiple variations', () => { + const markup = '[look: Chrono Cross logo](https://example.com/cc.png) [view: Chrono Cross logo](https://example.com/cc.png)' + + expect(Up.toAst(markup, { terms: { video: ['view', 'look'] } })).to.be.eql( + new DocumentNode([ + new ImageNode('Chrono Cross logo', 'https://example.com/cc.png'), + new ImageNode('Chrono Cross logo', 'https://example.com/cc.png') + ])) + }) })
2e0c128ba193c14bd61a2ec415eb69293e5373ae
src/utils/Urls.ts
src/utils/Urls.ts
export class Urls { public static image(key: string, size: number): string { return `https://d1cuyjsrcm0gby.cloudfront.net/${key}/thumb-${size}.jpg?origin=mapillary.webgl`; } public static mesh(key: string): string { return `https://d1cuyjsrcm0gby.cloudfront.net/${key}/sfm/v1.0/atomic_mesh.json`; } public static proto_mesh(key: string): string { return `http://mapillary-mesh2pbf.mapillary.io/v2/mesh/${key}`; } } export default Urls;
export class Urls { public static image(key: string, size: number): string { return `https://d1cuyjsrcm0gby.cloudfront.net/${key}/thumb-${size}.jpg?origin=mapillary.webgl`; } public static mesh(key: string): string { return `https://d1cuyjsrcm0gby.cloudfront.net/${key}/sfm/v1.0/atomic_mesh.json`; } public static proto_mesh(key: string): string { return `https://d1brzeo354iq2l.cloudfront.net/v2/mesh/${key}`; } } export default Urls;
Use cloudfront for mes2pbf address
Use cloudfront for mes2pbf address
TypeScript
mit
mapillary/mapillary-js,mapillary/mapillary-js
--- +++ @@ -8,7 +8,7 @@ } public static proto_mesh(key: string): string { - return `http://mapillary-mesh2pbf.mapillary.io/v2/mesh/${key}`; + return `https://d1brzeo354iq2l.cloudfront.net/v2/mesh/${key}`; } }
9a3b81daab3fd2ca3134eacc1425b8b42b783865
src/lib/convert.ts
src/lib/convert.ts
class Convert { static baseMIDINum = 69; // ref: // - https://github.com/watilde/beeplay/blob/master/src/modules/nn.js static keyToNote(name: string): number { var KEYS = [ "c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b" ]; var index = (name.indexOf("#") !== -1) ? 2 : 1; var note = name.substring(0, index).toLowerCase(); var number = Number(name.substring(index)) + 1; return KEYS.indexOf(note) + 12 * number; } // ref: // - http://mohayonao.hatenablog.com/entry/2012/05/25/215159 // - http://www.g200kg.com/jp/docs/tech/notefreq.html static noteToFreq(num: number): number { return 440 * Math.pow(Math.pow(2, 1/12), num - this.baseMIDINum); } } export = Convert;
class Convert { /**! * Copyright (c) 2014 Daijiro Wachi <daijiro.wachi@gmail.com> * Released under the MIT license * https://github.com/watilde/beeplay/blob/master/src/modules/nn.js */ static keyToNote(name: string): number { var KEYS = [ "c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b" ]; var index = (name.indexOf("#") !== -1) ? 2 : 1; var note = name.substring(0, index).toLowerCase(); var num = Number(name.substring(index)) + 1; return KEYS.indexOf(note) + 12 * num; } // ref: // - http://mohayonao.hatenablog.com/entry/2012/05/25/215159 // - http://www.g200kg.com/jp/docs/tech/notefreq.html static noteToFreq(num: number): number { return 440 * Math.pow(Math.pow(2, 1/12), num - 69); } } export = Convert;
Add license notation for Convert.keyToNote()
Add license notation for Convert.keyToNote()
TypeScript
mit
kubosho/ano-gakki,kubosho/ano-gakki,kubosho/ano-gakki,kubosho/ano-gakki
--- +++ @@ -1,8 +1,9 @@ class Convert { - static baseMIDINum = 69; - - // ref: - // - https://github.com/watilde/beeplay/blob/master/src/modules/nn.js + /**! + * Copyright (c) 2014 Daijiro Wachi <daijiro.wachi@gmail.com> + * Released under the MIT license + * https://github.com/watilde/beeplay/blob/master/src/modules/nn.js + */ static keyToNote(name: string): number { var KEYS = [ "c", "c#", @@ -15,15 +16,15 @@ ]; var index = (name.indexOf("#") !== -1) ? 2 : 1; var note = name.substring(0, index).toLowerCase(); - var number = Number(name.substring(index)) + 1; - return KEYS.indexOf(note) + 12 * number; + var num = Number(name.substring(index)) + 1; + return KEYS.indexOf(note) + 12 * num; } // ref: // - http://mohayonao.hatenablog.com/entry/2012/05/25/215159 // - http://www.g200kg.com/jp/docs/tech/notefreq.html static noteToFreq(num: number): number { - return 440 * Math.pow(Math.pow(2, 1/12), num - this.baseMIDINum); + return 440 * Math.pow(Math.pow(2, 1/12), num - 69); } }
bc4d08716879e837841a53174448fb9c6178498b
test/cronParser.ts
test/cronParser.ts
import chai = require("chai"); import { CronParser } from "../src/cronParser"; let assert = chai.assert; describe("CronParser", function () { describe("parse", function () { it("should parse 5 part cron", function () { assert.equal(new CronParser("* * * * *").parse().length, 7); }); it("should parse 6 part cron with year", function () { assert.equal(new CronParser("* * * * * 2015").parse()[6], "2015"); assert.equal(new CronParser("* * * * * 2015").parse()[0], ""); }); it("should parse 6 part cron with year", function () { assert.equal(new CronParser("* * * * * 2015").parse()[6], "2015"); assert.equal(new CronParser("* * * * * 2015").parse()[0], ""); }); it("should blow up if expression is crap", function () { assert.throws(function () { new CronParser("sdlksCRAPdlkskl- dds").parse() }, 'Expression has only 2 parts. At least 5 parts are required.'); }); }); });
import chai = require("chai"); import { CronParser } from "../src/cronParser"; let assert = chai.assert; describe("CronParser", function () { describe("parse", function () { it("should parse 5 part cron", function () { assert.equal(new CronParser("* * * * *").parse().length, 7); }); it("should parse 6 part cron with year", function () { assert.equal(new CronParser("* * * * * 2015").parse()[6], "2015"); assert.equal(new CronParser("* * * * * 2015").parse()[0], ""); }); it("should parse 6 part cron with year", function () { assert.equal(new CronParser("* * * * * 2015").parse()[6], "2015"); assert.equal(new CronParser("* * * * * 2015").parse()[0], ""); }); it("should error if expression is not valid", function () { assert.throws(function () { new CronParser("sdlksCRAPdlkskl- dds").parse() }, 'Expression has only 2 parts. At least 5 parts are required.'); }); }); });
Make test description more elegant
Make test description more elegant
TypeScript
mit
bradyholt/cRonstrue,bradyholt/cRonstrue
--- +++ @@ -18,7 +18,7 @@ assert.equal(new CronParser("* * * * * 2015").parse()[0], ""); }); - it("should blow up if expression is crap", function () { + it("should error if expression is not valid", function () { assert.throws(function () { new CronParser("sdlksCRAPdlkskl- dds").parse() }, 'Expression has only 2 parts. At least 5 parts are required.'); }); });
0950df4cb6f398f4397c265cae92b3751a858b77
packages/notebook/src/index.ts
packages/notebook/src/index.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import '../style/index.css'; export * from './actions'; export * from './celltools'; export * from './default-toolbar'; export * from './model'; export * from './modelfactory'; export * from './panel'; export * from './tracker'; export * from './widget'; export * from './widgetfactory'; export * from './modestatus'; export * from './truststatus';
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import '../style/index.css'; export * from './actions'; export * from './notebooktools'; export * from './default-toolbar'; export * from './model'; export * from './modelfactory'; export * from './panel'; export * from './tracker'; export * from './widget'; export * from './widgetfactory'; export * from './modestatus'; export * from './truststatus';
Fix compile error with obsolete import
Fix compile error with obsolete import
TypeScript
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
--- +++ @@ -4,7 +4,7 @@ import '../style/index.css'; export * from './actions'; -export * from './celltools'; +export * from './notebooktools'; export * from './default-toolbar'; export * from './model'; export * from './modelfactory';
849f8f306c9ea5b7b4385a9ce2ac2d50ef357300
packages/shared/lib/interfaces/calendar/Invite.ts
packages/shared/lib/interfaces/calendar/Invite.ts
import { ICAL_ATTENDEE_ROLE, ICAL_ATTENDEE_STATUS } from '../../calendar/constants'; import { CachedKey } from '../CachedKey'; import { Calendar, CalendarSettings } from './Calendar'; import { CalendarEvent } from './Event'; import { VcalAttendeeProperty, VcalOrganizerProperty, VcalVeventComponent } from './VcalModel'; export interface PartstatActions { accept: () => Promise<void>; acceptTentatively: () => Promise<void>; decline: () => Promise<void>; retryCreateEvent: (partstat: ICAL_ATTENDEE_STATUS) => Promise<void>; retryUpdateEvent: (partstat: ICAL_ATTENDEE_STATUS) => Promise<void>; } export interface CalendarWidgetData { calendar: Calendar; isCalendarDisabled: boolean; memberID?: string; addressKeys?: CachedKey[]; calendarKeys?: CachedKey[]; calendarSettings?: CalendarSettings; } export interface Participant { vcalComponent: VcalAttendeeProperty | VcalOrganizerProperty; name: string; emailAddress: string; partstat?: ICAL_ATTENDEE_STATUS; role?: ICAL_ATTENDEE_ROLE; addressID?: string; displayName?: string; } export interface SavedInviteData { savedEvent: CalendarEvent; savedVevent: VcalVeventComponent; savedVcalAttendee: VcalAttendeeProperty; }
import { ICAL_ATTENDEE_ROLE, ICAL_ATTENDEE_STATUS } from '../../calendar/constants'; import { CachedKey } from '../CachedKey'; import { Calendar, CalendarSettings } from './Calendar'; import { CalendarEvent } from './Event'; import { VcalAttendeeProperty, VcalOrganizerProperty, VcalVeventComponent } from './VcalModel'; export interface PartstatActions { accept: () => Promise<void>; acceptTentatively: () => Promise<void>; decline: () => Promise<void>; retryCreateEvent: (partstat: ICAL_ATTENDEE_STATUS) => Promise<void>; retryUpdateEvent: (partstat: ICAL_ATTENDEE_STATUS) => Promise<void>; } export interface CalendarWidgetData { calendar: Calendar; isCalendarDisabled: boolean; calendarNeedsUserAction: boolean; memberID?: string; addressKeys?: CachedKey[]; calendarKeys?: CachedKey[]; calendarSettings?: CalendarSettings; } export interface Participant { vcalComponent: VcalAttendeeProperty | VcalOrganizerProperty; name: string; emailAddress: string; partstat?: ICAL_ATTENDEE_STATUS; role?: ICAL_ATTENDEE_ROLE; addressID?: string; displayName?: string; } export interface SavedInviteData { savedEvent: CalendarEvent; savedVevent: VcalVeventComponent; savedVcalAttendee: VcalAttendeeProperty; }
Add new Boolean to CalendarWidgetData interface
Add new Boolean to CalendarWidgetData interface CALWEB-1475
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -15,6 +15,7 @@ export interface CalendarWidgetData { calendar: Calendar; isCalendarDisabled: boolean; + calendarNeedsUserAction: boolean; memberID?: string; addressKeys?: CachedKey[]; calendarKeys?: CachedKey[];
e0aa0ca31e99a406b852ed6686a3c24d64309301
saleor/static/dashboard-next/storybook/Stories.test.ts
saleor/static/dashboard-next/storybook/Stories.test.ts
import createGenerateClassName from "@material-ui/core/styles/createGenerateClassName"; import initStoryshots from "@storybook/addon-storyshots"; import { configure, render } from "enzyme"; import * as Adapter from "enzyme-adapter-react-16"; import toJSON from "enzyme-to-json"; configure({ adapter: new Adapter() }); jest.mock("@material-ui/core/styles/createGenerateClassName"); (createGenerateClassName as any).mockImplementation( () => (rule, stylesheet) => { return [stylesheet.options.meta, rule.key, "id"].join("-"); } ); initStoryshots({ configPath: "saleor/static/dashboard-next/storybook/", test({ story }) { const result = render((story as any).render()); expect(toJSON(result)).toMatchSnapshot(); } });
import createGenerateClassName from "@material-ui/core/styles/createGenerateClassName"; import initStoryshots from "@storybook/addon-storyshots"; import { configure, render } from "enzyme"; import * as Adapter from "enzyme-adapter-react-16"; import toJSON from "enzyme-to-json"; configure({ adapter: new Adapter() }); jest.mock("@material-ui/core/styles/createGenerateClassName"); (createGenerateClassName as any).mockImplementation( () => (rule, stylesheet) => { return [stylesheet.options.meta, rule.key, "id"].join("-"); } ); initStoryshots({ configPath: "saleor/static/dashboard-next/storybook/", test({ story }) { const result = render(story.render() as any); expect(toJSON(result)).toMatchSnapshot(); } });
Apply any to a whole argument
Apply any to a whole argument
TypeScript
bsd-3-clause
maferelo/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor,UITools/saleor
--- +++ @@ -16,7 +16,7 @@ initStoryshots({ configPath: "saleor/static/dashboard-next/storybook/", test({ story }) { - const result = render((story as any).render()); + const result = render(story.render() as any); expect(toJSON(result)).toMatchSnapshot(); } });
175b7bdc43fc8c5363330cc9d5630be4673b2b7a
packages/lesswrong/components/recommendations/withContinueReading.ts
packages/lesswrong/components/recommendations/withContinueReading.ts
import gql from 'graphql-tag'; import { useQuery } from 'react-apollo'; import { getFragment } from '../../lib/vulcan-lib'; export const useContinueReading = () => { // FIXME: For some unclear reason, using a ...fragment in the 'sequence' part // of this query doesn't work (leads to a 400 Bad Request), so this is expanded // out to a short list of individual fields. const continueReadingQuery = gql` query ContinueReadingQuery { ContinueReading { sequence { _id title gridImageId canonicalCollectionSlug } collection { _id title slug gridImageId } nextPost { ...PostsList } numRead numTotal lastReadTime } } ${getFragment("PostsList")} `; const { data, loading, error } = useQuery(continueReadingQuery, { ssr: true, }); return { continueReading: data.ContinueReading, loading, error }; }
import gql from 'graphql-tag'; import { useQuery } from 'react-apollo'; import { getFragment } from '../../lib/vulcan-lib'; export const useContinueReading = () => { // FIXME: For some unclear reason, using a ...fragment in the 'sequence' part // of this query doesn't work (leads to a 400 Bad Request), so this is expanded // out to a short list of individual fields. const continueReadingQuery = gql` query ContinueReadingQuery { ContinueReading { sequence { _id title gridImageId canonicalCollectionSlug } collection { _id title slug gridImageId } nextPost { ...PostsList } numRead numTotal lastReadTime } } ${getFragment("PostsList")} `; const { data, loading, error } = useQuery(continueReadingQuery, { ssr: true, }); return { continueReading: data?.ContinueReading, loading, error }; }
Fix an error in intermediate loading states which showed up in Sentry but didn't have any visible symptoms
Fix an error in intermediate loading states which showed up in Sentry but didn't have any visible symptoms
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -37,7 +37,7 @@ }); return { - continueReading: data.ContinueReading, + continueReading: data?.ContinueReading, loading, error }; }
14f533f5f5f86609233cb37b7d22feb407899f9a
lit_nlp/examples/custom_module/potato.ts
lit_nlp/examples/custom_module/potato.ts
/** * @fileoverview They're red, they're white, they're brown, * they get that way under-ground... * * This defines a custom module, which we'll import in main.ts to include in * the LIT app. */ // tslint:disable:no-new-decorators import {customElement} from 'lit/decorators'; import { html} from 'lit'; import {styleMap} from 'lit/directives/style-map'; import {LitModule} from '../../client/core/lit_module'; import {ModelInfoMap, Spec} from '../../client/lib/types'; /** Custom LIT module. Delicious baked, mashed, or fried. */ @customElement('potato-module') export class PotatoModule extends LitModule { static title = 'Potato'; static override numCols = 4; static template = () => { return html`<potato-module></potato-module>`; }; override render() { const style = styleMap({'width': '100%', 'height': '100%'}); // clang-format off return html` <a href="https://potato.io/"> <img src="static/potato.svg" style=${style}> </a>`; // clang-format on } static shouldDisplayModule(modelSpecs: ModelInfoMap, datasetSpec: Spec) { return true; } } declare global { interface HTMLElementTagNameMap { 'potato-module': PotatoModule; } }
/** * @fileoverview They're red, they're white, they're brown, * they get that way under-ground... * * This defines a custom module, which we'll import in main.ts to include in * the LIT app. */ // tslint:disable:no-new-decorators import {customElement} from 'lit/decorators'; import { html} from 'lit'; import {styleMap} from 'lit/directives/style-map'; import {LitModule} from '../../client/core/lit_module'; import {ModelInfoMap, Spec} from '../../client/lib/types'; /** Custom LIT module. Delicious baked, mashed, or fried. */ @customElement('potato-module') export class PotatoModule extends LitModule { static override title = 'Potato'; static override numCols = 4; static override template = () => { return html`<potato-module></potato-module>`; }; override render() { const style = styleMap({'width': '100%', 'height': '100%'}); // clang-format off return html` <a href="https://potato.io/"> <img src="static/potato.svg" style=${style}> </a>`; // clang-format on } static override shouldDisplayModule(modelSpecs: ModelInfoMap, datasetSpec: Spec) { return true; } } declare global { interface HTMLElementTagNameMap { 'potato-module': PotatoModule; } }
Add the override keyword to class members in TypeScript files
Add the override keyword to class members in TypeScript files TypeScript’s override keyword (added in 4.3) works similarly to @Override in Java. It makes the intention clear and ensures there is actually a member in the base class with the same name. This helps with things like: - Typos in the overriding member name - Remember to rename members in sub classes when renaming an overridden member in a base class class Parent { foo() {} } class Child extends Parent { override bar() {} // ~~~ This member cannot have an 'override' modifier because it is not declared in the base class 'Parent'. } This change will not cause a runtime change: the override keyword is not present in the resulting JavaScript. PiperOrigin-RevId: 405900549
TypeScript
apache-2.0
PAIR-code/lit,pair-code/lit,pair-code/lit,pair-code/lit,PAIR-code/lit,pair-code/lit,PAIR-code/lit,PAIR-code/lit,PAIR-code/lit,pair-code/lit
--- +++ @@ -17,9 +17,9 @@ /** Custom LIT module. Delicious baked, mashed, or fried. */ @customElement('potato-module') export class PotatoModule extends LitModule { - static title = 'Potato'; + static override title = 'Potato'; static override numCols = 4; - static template = () => { + static override template = () => { return html`<potato-module></potato-module>`; }; @@ -33,7 +33,7 @@ // clang-format on } - static shouldDisplayModule(modelSpecs: ModelInfoMap, datasetSpec: Spec) { + static override shouldDisplayModule(modelSpecs: ModelInfoMap, datasetSpec: Spec) { return true; } }
d4eea028016092b36d9177616c9e6bb96df9abee
client/src/app/shared/angular/timestamp-route-transformer.directive.ts
client/src/app/shared/angular/timestamp-route-transformer.directive.ts
import { Directive, EventEmitter, HostListener, Output } from '@angular/core' @Directive({ selector: '[timestampRouteTransformer]' }) export class TimestampRouteTransformerDirective { @Output() timestampClicked = new EventEmitter<number>() @HostListener('click', ['$event']) public onClick ($event: Event) { const target = $event.target as HTMLLinkElement if (target.hasAttribute('href')) { const ngxLink = document.createElement('a') ngxLink.href = target.getAttribute('href') // we only care about reflective links if (ngxLink.host !== window.location.host) return const ngxLinkParams = new URLSearchParams(ngxLink.search) if (ngxLinkParams.has('start')) { const separators = ['h', 'm', 's'] const start = ngxLinkParams .get('start') .match(new RegExp('(\\d{1,9}[' + separators.join('') + '])','g')) // match digits before any given separator .map(t => { if (t.includes('h')) return parseInt(t, 10) * 3600 if (t.includes('m')) return parseInt(t, 10) * 60 return parseInt(t, 10) }) .reduce((acc, t) => acc + t) this.timestampClicked.emit(start) } $event.preventDefault() } return } }
import { Directive, EventEmitter, HostListener, Output } from '@angular/core' @Directive({ selector: '[timestampRouteTransformer]' }) export class TimestampRouteTransformerDirective { @Output() timestampClicked = new EventEmitter<number>() @HostListener('click', ['$event']) public onClick ($event: Event) { const target = $event.target as HTMLLinkElement if (target.hasAttribute('href') !== true) return const ngxLink = document.createElement('a') ngxLink.href = target.getAttribute('href') // we only care about reflective links if (ngxLink.host !== window.location.host) return const ngxLinkParams = new URLSearchParams(ngxLink.search) if (ngxLinkParams.has('start') !== true) return const separators = ['h', 'm', 's'] const start = ngxLinkParams .get('start') .match(new RegExp('(\\d{1,9}[' + separators.join('') + '])','g')) // match digits before any given separator .map(t => { if (t.includes('h')) return parseInt(t, 10) * 3600 if (t.includes('m')) return parseInt(t, 10) * 60 return parseInt(t, 10) }) .reduce((acc, t) => acc + t) this.timestampClicked.emit(start) $event.preventDefault() } }
Fix relative links in video description
Fix relative links in video description
TypeScript
agpl-3.0
Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube
--- +++ @@ -10,31 +10,30 @@ public onClick ($event: Event) { const target = $event.target as HTMLLinkElement - if (target.hasAttribute('href')) { - const ngxLink = document.createElement('a') - ngxLink.href = target.getAttribute('href') + if (target.hasAttribute('href') !== true) return - // we only care about reflective links - if (ngxLink.host !== window.location.host) return + const ngxLink = document.createElement('a') + ngxLink.href = target.getAttribute('href') - const ngxLinkParams = new URLSearchParams(ngxLink.search) - if (ngxLinkParams.has('start')) { - const separators = ['h', 'm', 's'] - const start = ngxLinkParams - .get('start') - .match(new RegExp('(\\d{1,9}[' + separators.join('') + '])','g')) // match digits before any given separator - .map(t => { - if (t.includes('h')) return parseInt(t, 10) * 3600 - if (t.includes('m')) return parseInt(t, 10) * 60 - return parseInt(t, 10) - }) - .reduce((acc, t) => acc + t) - this.timestampClicked.emit(start) - } + // we only care about reflective links + if (ngxLink.host !== window.location.host) return - $event.preventDefault() - } + const ngxLinkParams = new URLSearchParams(ngxLink.search) + if (ngxLinkParams.has('start') !== true) return - return + const separators = ['h', 'm', 's'] + const start = ngxLinkParams + .get('start') + .match(new RegExp('(\\d{1,9}[' + separators.join('') + '])','g')) // match digits before any given separator + .map(t => { + if (t.includes('h')) return parseInt(t, 10) * 3600 + if (t.includes('m')) return parseInt(t, 10) * 60 + return parseInt(t, 10) + }) + .reduce((acc, t) => acc + t) + + this.timestampClicked.emit(start) + + $event.preventDefault() } }
f9aee6fab8256a3fdba3e66c6a260a169b8f38df
lib/theming/src/utils.ts
lib/theming/src/utils.ts
import { rgba, lighten, darken } from 'polished'; export const mkColor = (color: string) => ({ color }); // Passing arguments that can't be converted to RGB such as linear-gradient // to library polished's functions such as lighten or darken throws the error // that crashes the entire storybook. It needs to be guarded when arguments // of those functions are from user input. const isColorVarChangeable = (color: string) => { return !!color.match(/(gradient|var)/); }; const applyPolished = (type: string, color: string) => { if (type === 'darken') { return rgba(`${darken(1, color)}`, 0.95); } if (type === 'lighten') { return rgba(`${lighten(1, color)}`, 0.95); } return color; }; const colorFactory = (type: string) => (color: string) => { if (isColorVarChangeable(color)) { return color; } // Guard anything that is not working with polished. try { return applyPolished(type, color); } catch (error) { return color; } }; export const lightenColor = colorFactory('lighten'); export const darkenColor = colorFactory('darken');
import { rgba, lighten, darken } from 'polished'; import { logger } from '@storybook/client-logger'; export const mkColor = (color: string) => ({ color }); // Check if it is a string. This is for the sake of warning users // and the successive guarding logics that use String methods. const isColorString = (color: string) => { if (typeof color !== 'string') { logger.warn( `Color passed to theme object should be a string. Instead` + `${color}(${typeof color}) was passed.` ); return false; } return true; }; // Passing arguments that can't be converted to RGB such as linear-gradient // to library polished's functions such as lighten or darken throws the error // that crashes the entire storybook. It needs to be guarded when arguments // of those functions are from user input. const isColorVarChangeable = (color: string) => { return !!color.match(/(gradient|var)/); }; const applyPolished = (type: string, color: string) => { if (type === 'darken') { return rgba(`${darken(1, color)}`, 0.95); } if (type === 'lighten') { return rgba(`${lighten(1, color)}`, 0.95); } return color; }; const colorFactory = (type: string) => (color: string) => { if (!isColorString(color)) { return color; } if (isColorVarChangeable(color)) { return color; } // Guard anything that is not working with polished. try { return applyPolished(type, color); } catch (error) { return color; } }; export const lightenColor = colorFactory('lighten'); export const darkenColor = colorFactory('darken');
Add validation of user input
Add validation of user input
TypeScript
mit
storybooks/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook
--- +++ @@ -1,6 +1,22 @@ import { rgba, lighten, darken } from 'polished'; +import { logger } from '@storybook/client-logger'; + export const mkColor = (color: string) => ({ color }); + +// Check if it is a string. This is for the sake of warning users +// and the successive guarding logics that use String methods. +const isColorString = (color: string) => { + if (typeof color !== 'string') { + logger.warn( + `Color passed to theme object should be a string. Instead` + + `${color}(${typeof color}) was passed.` + ); + return false; + } + + return true; +}; // Passing arguments that can't be converted to RGB such as linear-gradient // to library polished's functions such as lighten or darken throws the error @@ -23,6 +39,10 @@ }; const colorFactory = (type: string) => (color: string) => { + if (!isColorString(color)) { + return color; + } + if (isColorVarChangeable(color)) { return color; }
6dac157aef5b2addbabe0fb23fb091cb574e53e0
app/javascript/retrospring/features/lists/membership.ts
app/javascript/retrospring/features/lists/membership.ts
import Rails from '@rails/ujs'; import { showNotification, showErrorNotification } from 'utilities/notifications'; import I18n from 'retrospring/i18n'; export function listMembershipHandler(event: Event): void { const checkbox = event.target as HTMLInputElement; const list = checkbox.dataset.list; let memberCount = Number(document.querySelector(`span#${list}-members`).innerHTML); checkbox.setAttribute('disabled', 'disabled'); memberCount += checkbox.checked ? 1 : -1; Rails.ajax({ url: '/ajax/list_membership', type: 'POST', data: new URLSearchParams({ list: list, user: checkbox.dataset.user, add: String(checkbox.checked) }).toString(), success: (data) => { if (data.success) { checkbox.checked = data.checked; document.querySelector(`span#${list}-members`).innerHTML = memberCount.toString(); } showNotification(data.message, data.success); }, error: (data, status, xhr) => { console.log(data, status, xhr); showErrorNotification(I18n.translate('frontend.error.message')); }, complete: () => { checkbox.removeAttribute('disabled'); } }); }
import Rails from '@rails/ujs'; import { showNotification, showErrorNotification } from 'utilities/notifications'; import I18n from 'retrospring/i18n'; export function listMembershipHandler(event: Event): void { const checkbox = event.target as HTMLInputElement; const list = checkbox.dataset.list; const memberCountElement: HTMLElement = document.querySelector(`span#${list}-members`); let memberCount = Number(memberCountElement.dataset.count); checkbox.setAttribute('disabled', 'disabled'); memberCount += checkbox.checked ? 1 : -1; Rails.ajax({ url: '/ajax/list_membership', type: 'POST', data: new URLSearchParams({ list: list, user: checkbox.dataset.user, add: String(checkbox.checked) }).toString(), success: (data) => { if (data.success) { checkbox.checked = data.checked; memberCountElement.innerHTML = memberCountElement.dataset.i18n.replace('%{count}', memberCount.toString()); memberCountElement.dataset.count = memberCount.toString(); } showNotification(data.message, data.success); }, error: (data, status, xhr) => { console.log(data, status, xhr); showErrorNotification(I18n.translate('frontend.error.message')); }, complete: () => { checkbox.removeAttribute('disabled'); } }); }
Adjust TypeScript logic for list member count
Adjust TypeScript logic for list member count
TypeScript
agpl-3.0
Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring
--- +++ @@ -5,7 +5,8 @@ export function listMembershipHandler(event: Event): void { const checkbox = event.target as HTMLInputElement; const list = checkbox.dataset.list; - let memberCount = Number(document.querySelector(`span#${list}-members`).innerHTML); + const memberCountElement: HTMLElement = document.querySelector(`span#${list}-members`); + let memberCount = Number(memberCountElement.dataset.count); checkbox.setAttribute('disabled', 'disabled'); @@ -22,7 +23,8 @@ success: (data) => { if (data.success) { checkbox.checked = data.checked; - document.querySelector(`span#${list}-members`).innerHTML = memberCount.toString(); + memberCountElement.innerHTML = memberCountElement.dataset.i18n.replace('%{count}', memberCount.toString()); + memberCountElement.dataset.count = memberCount.toString(); } showNotification(data.message, data.success);
5c920eb71b1f53bbc43c6820edd51e29ebb0e656
directive/templates/directive.ts
directive/templates/directive.ts
/// <reference path="../../app.d.ts" /> 'use strict'; angular.module('<%= appname %>') .directive('<%= camelName %>', function () { return { restrict: 'EA', <% if (needTemplate) { %>templateUrl: 'directives/<%= dashName %>/<%= dashName %>.html', <% } %>link: function (scope, element) { element.text('<%= camelName %> directive'); } }; });
/// <reference path="../../app.d.ts" /> 'use strict'; module <%= capName %>App.Directives.<%= camelName %> { angular.module('<%= appname %>') .directive('<%= camelName %>', function () { return { restrict: 'EA', <% if (needTemplate) { %>templateUrl: 'directives/<%= dashName %>/<%= dashName %>.html', <% } %>link: function (scope, element, attrs) { element.text('<%= camelName %> directive'); } }; }); }
Update Directive Template for Typescript
Client: Update Directive Template for Typescript
TypeScript
bsd-3-clause
NovaeWorkshop/Nova,NovaeWorkshop/Nova,NovaeWorkshop/Nova
--- +++ @@ -1,13 +1,17 @@ /// <reference path="../../app.d.ts" /> 'use strict'; -angular.module('<%= appname %>') - .directive('<%= camelName %>', function () { - return { - restrict: 'EA', - <% if (needTemplate) { %>templateUrl: 'directives/<%= dashName %>/<%= dashName %>.html', - <% } %>link: function (scope, element) { - element.text('<%= camelName %> directive'); - } - }; +module <%= capName %>App.Directives.<%= camelName %> { + + angular.module('<%= appname %>') + .directive('<%= camelName %>', function () { + return { + restrict: 'EA', + <% if (needTemplate) { %>templateUrl: 'directives/<%= dashName %>/<%= dashName %>.html', + <% } %>link: function (scope, element, attrs) { + element.text('<%= camelName %> directive'); + } + }; }); + +}
5a3b201875e0d7b73e8b707c7aa35052c7692706
tests-integration/test-browser-umd.spec.ts
tests-integration/test-browser-umd.spec.ts
// @types/puppeteer causing a lot of conflicts with @types/node. Removing for now. //import puppeteer, { Browser, Page } from 'puppeteer'; const puppeteer = require( 'puppeteer' ); describe( 'Autolinker.js UMD file in browser', function() { let browser: any; // :Browser let page: any; // :Page beforeAll( async () => { browser = await puppeteer.launch( { headless: true } ); page = await browser.newPage(); // Print errors from the page page.on( 'pageerror', ( err: Error ) => console.error( err ) ); await page.goto( `file://${__dirname}/test-browser-umd.html`, { waitUntil: 'load' } ); } ); afterAll( async () => { await browser.close(); } ); it( 'should have the `window.Autolinker` global, and Autolinker should work', async () => { const innerHTML = await page.evaluate( () => { return ( document as any ).querySelector( '#result' ).innerHTML.trim(); } ); expect( innerHTML ).toBe( 'Go to <a href="http://google.com">google.com</a>' ); } ); } );
// @types/puppeteer causing a lot of conflicts with @types/node. Removing for now. //import puppeteer, { Browser, Page } from 'puppeteer'; const puppeteer = require( 'puppeteer' ); describe( 'Autolinker.js UMD file in browser', function() { let browser: any; // :Browser let page: any; // :Page beforeAll( async () => { browser = await puppeteer.launch( { headless: true } ); page = await browser.newPage(); // Print errors from the page page.on( 'pageerror', ( err: Error ) => console.error( err ) ); await page.goto( `file://${__dirname}/test-browser-umd.html`, { waitUntil: 'load' } ); } ); afterAll( async () => { await browser.close(); } ); it( 'should have the `window.Autolinker` global, and Autolinker should work', async () => { const innerHTML = await page.evaluate( () => { return ( document as any ).querySelector( '#result' ).innerHTML.trim(); } ); expect( innerHTML ).toBe( 'Go to <a href="http://google.com">google.com</a>' ); } ); it( 'should expose `Autolinker.matcher.Matcher` so that it can be extended', async () => { const typeofMatcher = await page.evaluate( () => { return typeof ( window as any ).Autolinker.matcher.Matcher; } ); expect( typeofMatcher ).toBe( 'function' ); // constructor function } ); } );
Add test for Autolinker.matcher.Matcher in browser
Add test for Autolinker.matcher.Matcher in browser
TypeScript
mit
gregjacobs/Autolinker.js,gregjacobs/Autolinker.js,gregjacobs/Autolinker.js,closeio/Autolinker.js,closeio/Autolinker.js,closeio/Autolinker.js,closeio/Autolinker.js,gregjacobs/Autolinker.js
--- +++ @@ -30,5 +30,14 @@ expect( innerHTML ).toBe( 'Go to <a href="http://google.com">google.com</a>' ); } ); + + + it( 'should expose `Autolinker.matcher.Matcher` so that it can be extended', async () => { + const typeofMatcher = await page.evaluate( () => { + return typeof ( window as any ).Autolinker.matcher.Matcher; + } ); + + expect( typeofMatcher ).toBe( 'function' ); // constructor function + } ); } );
8db66113420dbcf3e2a2d0625e164f628341aa3e
src/bonziri.ts
src/bonziri.ts
/// <reference path="bonziri.impl.ts" /> //'use strict' namespace Bonziri { export function generateScenario(jsonText: string): Scenario { return Impl.generateScenario(jsonText); } }
/// <reference path="bonziri.impl.ts" /> //'use strict' namespace Bonziri { export function generateScenario(jsonText: string): Scenario { try { return Impl.generateScenario(jsonText); } catch (e) { alert(e); throw e; } } }
Add try-catch statement in Bonziri decoding
Add try-catch statement in Bonziri decoding
TypeScript
mit
kndysfm/bonziri,kndysfm/bonziri,kndysfm/bonziri,kndysfm/bonziri
--- +++ @@ -4,7 +4,12 @@ namespace Bonziri { export function generateScenario(jsonText: string): Scenario { - return Impl.generateScenario(jsonText); + try { + return Impl.generateScenario(jsonText); + } catch (e) { + alert(e); + throw e; + } } }
84094b61ee1e204285a1123378698440f622d032
server/chat-jsx.ts
server/chat-jsx.ts
/** * PS custom HTML elements and Preact handling. * By Mia and Zarel */ import preact from 'preact'; import render from 'preact-render-to-string'; import {Utils} from '../lib'; /** For easy concenation of Preact nodes with strings */ export function html( strings: TemplateStringsArray, ...args: (preact.VNode | string | number | null | undefined)[] ) { let buf = strings[0]; let i = 0; while (i < args.length) { buf += typeof args[i] === 'string' || typeof args[i] === 'number' ? Utils.escapeHTML(args[i] as string | number) : render(args[i] as preact.VNode); buf += strings[++i]; } return buf; } /** client-side custom elements */ export interface PSElements extends preact.JSX.IntrinsicElements { youtube: {src: string}; twitch: {src: string, width?: number, height?: number}; spotify: {src: string}; username: {name?: string, children: string}; psicon: {pokemon: string} | {item: string} | {type: string} | {category: string}; } export {render}; export type VNode = preact.VNode; export const h = preact.h; export const Fragment = preact.Fragment;
/** * PS custom HTML elements and Preact handling. * By Mia and Zarel */ import preact from 'preact'; import render from 'preact-render-to-string'; import {Utils} from '../lib'; /** For easy concenation of Preact nodes with strings */ export function html( strings: TemplateStringsArray, ...args: (preact.VNode | string | number | null | undefined)[] ) { let buf = strings[0]; let i = 0; while (i < args.length) { buf += typeof args[i] === 'string' || typeof args[i] === 'number' ? Utils.escapeHTML(args[i] as string | number) : render(args[i] as preact.VNode); buf += strings[++i]; } return buf; } /** client-side custom elements */ export interface PSElements extends preact.JSX.IntrinsicElements { youtube: {src: string}; twitch: {src: string, width?: number, height?: number}; spotify: {src: string}; username: {name?: string, class?: string}; psicon: {pokemon: string} | {item: string} | {type: string} | {category: string}; } export {render}; export type VNode = preact.VNode; export const h = preact.h; export const Fragment = preact.Fragment;
Fix definition for <username> in JSX
Fix definition for <username> in JSX (Apparently `children` is defined elsewhere...)
TypeScript
mit
xfix/Pokemon-Showdown,xfix/Pokemon-Showdown,svivian/Pokemon-Showdown,svivian/Pokemon-Showdown,xfix/Pokemon-Showdown,svivian/Pokemon-Showdown,xfix/Pokemon-Showdown,svivian/Pokemon-Showdown,svivian/Pokemon-Showdown,xfix/Pokemon-Showdown
--- +++ @@ -26,7 +26,7 @@ youtube: {src: string}; twitch: {src: string, width?: number, height?: number}; spotify: {src: string}; - username: {name?: string, children: string}; + username: {name?: string, class?: string}; psicon: {pokemon: string} | {item: string} | {type: string} | {category: string}; }
d1cc00981c8641e98bbd30d41c797310d498e0af
src/components/MdePreview.tsx
src/components/MdePreview.tsx
import * as React from "react"; import {GenerateMarkdownPreview} from "../types"; import {Simulate} from "react-dom/test-utils"; import load = Simulate.load; export interface ReactMdePreviewProps { className?: string; previewRef?: (ref: MdePreview) => void; emptyPreviewHtml?: string; minHeight: number; generateMarkdownPreview: GenerateMarkdownPreview; markdown: string; } export interface ReactMdePreviewState { loading: boolean; html?: string; } export class MdePreview extends React.Component<ReactMdePreviewProps, ReactMdePreviewState> { previewRef: HTMLDivElement; constructor(props) { super(props); this.state = { loading: true, } } componentDidMount(): void { const {markdown, generateMarkdownPreview} = this.props; generateMarkdownPreview(markdown).then((previewHtml) => { this.setState({ html: previewHtml, loading: false }); }); } render() { const {className, minHeight, emptyPreviewHtml} = this.props; const {loading, html} = this.state; const finalHtml = loading ? emptyPreviewHtml : html; return ( <div className={`mde-preview ${className || ""}`} style={{minHeight: minHeight + 10}}> <div className="mde-preview-content" dangerouslySetInnerHTML={{__html: finalHtml || "<p>&nbsp;</p>"}} ref={(p) => this.previewRef = p} /> </div> ); } }
import * as React from "react"; import {GenerateMarkdownPreview} from "../types"; import * as classNames from "classnames"; export interface ReactMdePreviewProps { className?: string; previewRef?: (ref: MdePreview) => void; emptyPreviewHtml?: string; minHeight: number; generateMarkdownPreview: GenerateMarkdownPreview; markdown: string; } export interface ReactMdePreviewState { loading: boolean; html?: string; } export class MdePreview extends React.Component<ReactMdePreviewProps, ReactMdePreviewState> { previewRef: HTMLDivElement; constructor(props) { super(props); this.state = { loading: true, } } componentDidMount(): void { const {markdown, generateMarkdownPreview} = this.props; generateMarkdownPreview(markdown).then((previewHtml) => { this.setState({ html: previewHtml, loading: false }); }); } render() { const {className, minHeight, emptyPreviewHtml} = this.props; const {html, loading} = this.state; const finalHtml = loading ? emptyPreviewHtml : html; return ( <div className={classNames("mde-preview", {className, loading})} style={{minHeight: minHeight + 10}}> <div className="mde-preview-content" dangerouslySetInnerHTML={{__html: finalHtml || "<p>&nbsp;</p>"}} ref={(p) => this.previewRef = p} /> </div> ); } }
Add CSS class loading to the preview
Add CSS class loading to the preview
TypeScript
mit
andrerpena/react-mde,andrerpena/react-mde,andrerpena/react-mde
--- +++ @@ -1,7 +1,6 @@ import * as React from "react"; import {GenerateMarkdownPreview} from "../types"; -import {Simulate} from "react-dom/test-utils"; -import load = Simulate.load; +import * as classNames from "classnames"; export interface ReactMdePreviewProps { className?: string; @@ -39,10 +38,10 @@ render() { const {className, minHeight, emptyPreviewHtml} = this.props; - const {loading, html} = this.state; + const {html, loading} = this.state; const finalHtml = loading ? emptyPreviewHtml : html; return ( - <div className={`mde-preview ${className || ""}`} style={{minHeight: minHeight + 10}}> + <div className={classNames("mde-preview", {className, loading})} style={{minHeight: minHeight + 10}}> <div className="mde-preview-content" dangerouslySetInnerHTML={{__html: finalHtml || "<p>&nbsp;</p>"}}
defe9dce72e8518106ae38eeb782d133fb07f377
src/api/hosts/create.ts
src/api/hosts/create.ts
import { RequestHandler } from 'express' import { create, CreateHost } from './db' const handler: RequestHandler = async (req, res) => { const hostname = req.body.hostname || '' const vanityHostname = req.body.hostname || hostname || 'localhost' const dockerPort = req.body.dockerPort || 2375 const proxyIp = req.body.proxyIp || '' const sshPort = req.body.sshPort || 22 const capacity = req.body.capacity || 5 let credentialsId: number | null = Number(req.body.credentialsId) if (credentialsId < 1) { credentialsId = null } const hasHostname = !!hostname.length if (hasHostname) { res.status(400).json({ message: 'Invalid SSH username provided: Must provided credentials if providing a hostname' }) return } const body: CreateHost = { hostname, dockerPort, sshPort, capacity, vanityHostname, proxyIp, credentialsId } try { const result = await create(body) res.json({ ...body, id: result[0] }) } catch (ex) { res.status(500) res.json({ message: ex.message || ex }) } } export default handler
import { RequestHandler } from 'express' import { create, CreateHost } from './db' const handler: RequestHandler = async (req, res) => { const hostname = req.body.hostname || '' const vanityHostname = req.body.hostname || hostname || 'localhost' const dockerPort = req.body.dockerPort || 2375 const proxyIp = req.body.proxyIp || '' const sshPort = req.body.sshPort || 22 const capacity = req.body.capacity || 5 let credentialsId: number | null = Number(req.body.credentialsId) if (credentialsId < 1) { credentialsId = null } const body: CreateHost = { hostname, dockerPort, sshPort, capacity, vanityHostname, proxyIp, credentialsId } try { const result = await create(body) res.json({ ...body, id: result[0] }) } catch (ex) { res.status(500) res.json({ message: ex.message || ex }) } } export default handler
Remove ssh username check when providing hostname
Remove ssh username check when providing hostname
TypeScript
mit
the-concierge/concierge,the-concierge/concierge,the-concierge/concierge
--- +++ @@ -11,15 +11,6 @@ let credentialsId: number | null = Number(req.body.credentialsId) if (credentialsId < 1) { credentialsId = null - } - - const hasHostname = !!hostname.length - - if (hasHostname) { - res.status(400).json({ - message: 'Invalid SSH username provided: Must provided credentials if providing a hostname' - }) - return } const body: CreateHost = {
649348a41d5f64910f8c02633b3e5d36c4b584c0
packages/lesswrong/client/vulcan-lib/apollo-client/apolloClient.ts
packages/lesswrong/client/vulcan-lib/apollo-client/apolloClient.ts
import { ApolloClient, InMemoryCache, ApolloLink } from '@apollo/client'; import { BatchHttpLink } from '@apollo/client/link/batch-http'; import { apolloCacheVoteablePossibleTypes } from '../../../lib/make_voteable'; import meteorAccountsLink from './links/meteor'; import errorLink from './links/error'; export const createApolloClient = () => { const cache = new InMemoryCache({ possibleTypes: { ...apolloCacheVoteablePossibleTypes() } }) .restore((window as any).__APOLLO_STATE__); //ssr const httpLink = new BatchHttpLink({ uri: '/graphql', credentials: 'same-origin', }); return new ApolloClient({ link: ApolloLink.from([errorLink, meteorAccountsLink, httpLink]), cache }); };
import { ApolloClient, InMemoryCache, ApolloLink } from '@apollo/client'; import { BatchHttpLink } from '@apollo/client/link/batch-http'; import { apolloCacheVoteablePossibleTypes } from '../../../lib/make_voteable'; import meteorAccountsLink from './links/meteor'; import errorLink from './links/error'; export const createApolloClient = () => { const cache = new InMemoryCache({ possibleTypes: { ...apolloCacheVoteablePossibleTypes() } }) .restore((window as any).__APOLLO_STATE__); //ssr const httpLink = new BatchHttpLink({ uri: '/graphql', credentials: 'same-origin', batchMax: 50, }); return new ApolloClient({ link: ApolloLink.from([errorLink, meteorAccountsLink, httpLink]), cache }); };
Increase the maximum queries per batch in BatchHttpLink from 10 to 50
Increase the maximum queries per batch in BatchHttpLink from 10 to 50 In posts with a lot of Elicit predictions or hover-previewable links, this prevents excessive http requests and rerenders (previously it would make one http request for every 10).
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -15,6 +15,7 @@ const httpLink = new BatchHttpLink({ uri: '/graphql', credentials: 'same-origin', + batchMax: 50, }); return new ApolloClient({
0af57639ed8b9b0db032986ec0d8a0ab3cf4c8af
src/app/player-extendable-list/player-extendable-list.component.ts
src/app/player-extendable-list/player-extendable-list.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { Player } from '../core/player.model'; import { PlayerService } from '../core/player.service'; @Component({ selector: 'player-extendable-list', templateUrl: './player-extendable-list.component.html', styleUrls: ['./player-extendable-list.component.scss'] }) export class PlayerExtendableListComponent implements OnInit { @Input() players: Player[]; cachedPlayers: Player[]; hasError: boolean; @Input() newPlayerName: string; constructor(private playerService: PlayerService) { } ngOnInit() { this.players = this.playerService.players; this.cachedPlayers = this.playerService.getCachedPlayers(); this.newPlayerName = null; } addPlayer() { if(!this.newPlayerName || '' == this.newPlayerName ) return; for(let idx = 0; idx < this.players.length; idx++) { if(this.newPlayerName == this.players[idx].name) { this.hasError = true; return; } } this.playerService.addPlayer(new Player(this.newPlayerName)); this.newPlayerName = null; this.hasError = false; } addCachedPlayer(player: Player) { if(!player.isIn(this.players)) { this.playerService.addPlayer(player); } } // removeCachedPlayer removePlayer(idx: number) { this.playerService.deletePlayer(idx); } }
import { Component, OnInit, Input } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { Player } from '../core/player.model'; import { PlayerService } from '../core/player.service'; @Component({ selector: 'player-extendable-list', templateUrl: './player-extendable-list.component.html', styleUrls: ['./player-extendable-list.component.scss'] }) export class PlayerExtendableListComponent implements OnInit { @Input() players: Player[]; cachedPlayers: Player[]; hasError: boolean; @Input() newPlayerName: string; constructor(private playerService: PlayerService) { } ngOnInit() { this.players = this.playerService.players; this.cachedPlayers = this.playerService.getCachedPlayers(); this.newPlayerName = null; } addPlayer() { this.hasError = false; if(!this.newPlayerName || '' == this.newPlayerName ) return; let newPlayer = new Player(this.newPlayerName) if(!newPlayer.isIn(this.players)){ this.playerService.addPlayer(newPlayer); this.newPlayerName = null; } else { this.hasError = true; } } addCachedPlayer(player: Player) { if(!player.isIn(this.players)) { this.playerService.addPlayer(player); } } // removeCachedPlayer removePlayer(idx: number) { this.playerService.deletePlayer(idx); } }
Use the same login for checking errors in addPlayer as well
Use the same login for checking errors in addPlayer as well
TypeScript
mit
hodossy/darts-scorer,hodossy/darts-scorer,hodossy/darts-scorer
--- +++ @@ -25,16 +25,15 @@ } addPlayer() { + this.hasError = false; if(!this.newPlayerName || '' == this.newPlayerName ) return; - for(let idx = 0; idx < this.players.length; idx++) { - if(this.newPlayerName == this.players[idx].name) { - this.hasError = true; - return; - } + let newPlayer = new Player(this.newPlayerName) + if(!newPlayer.isIn(this.players)){ + this.playerService.addPlayer(newPlayer); + this.newPlayerName = null; + } else { + this.hasError = true; } - this.playerService.addPlayer(new Player(this.newPlayerName)); - this.newPlayerName = null; - this.hasError = false; } addCachedPlayer(player: Player) {
565959190db1a92b7244e3ae204cc7dfc247c77f
src/app/controlls/game-controll.ts
src/app/controlls/game-controll.ts
const FINISH_ZONE_KEY = 'finish-zone'; import {Boat} from '../sprites/boat'; export class GameControll { constructor(private game: Phaser.Game) { } public createBoat(x: number, y: number) { const boat = new Boat(this.game, x, y); this.game.add.existing(boat); this.game.physics.p2.enable(boat, true); boat.body.onBeginContact.add(this.completeLevel, this.game.state); boat.setupBody(); return boat; } private completeLevel(body) { if (body.sprite.key === FINISH_ZONE_KEY) { this.game.state.start('HighScore'); console.log('level completed'); } } }
const FINISH_ZONE_KEY = 'finish-zone'; import {Boat} from '../sprites/boat'; export class GameControll { constructor(private game: Phaser.Game) { } public createBoat(x: number, y: number) { const boat = new Boat(this.game, x, y); this.game.add.existing(boat); this.game.physics.p2.enable(boat, true); boat.body.onBeginContact.add(this.completeLevel, this.game.state); boat.setupBody(); return boat; } private completeLevel(body) { if (body.sprite.key === FINISH_ZONE_KEY) { let highScore = JSON.parse(localStorage.getItem('highScore')); highScore.push({userName: localStorage.getItem('userName'), score: 5}); localStorage.setItem('highScore', JSON.stringify(highScore)); this.game.state.start('HighScore'); console.log('level completed'); } } }
Add highscore results (part ;))
Add highscore results (part ;))
TypeScript
mit
bartoszbobin/global-game-jame-2017,bartoszbobin/global-game-jame-2017,bartoszbobin/global-game-jame-2017,bartoszbobin/global-game-jame-2017
--- +++ @@ -18,6 +18,10 @@ private completeLevel(body) { if (body.sprite.key === FINISH_ZONE_KEY) { + let highScore = JSON.parse(localStorage.getItem('highScore')); + highScore.push({userName: localStorage.getItem('userName'), score: 5}); + localStorage.setItem('highScore', JSON.stringify(highScore)); + this.game.state.start('HighScore'); console.log('level completed'); }
30084d7c97317747cb42cab0e570b0053deaf439
client/src/client.ts
client/src/client.ts
'use strict'; import * as path from 'path'; import { workspace, ExtensionContext } from 'vscode'; import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient'; export function activate(context: ExtensionContext) { let serverModule = context.asAbsolutePath(path.join('server', 'server.js')); // Server debug options let debugOptions = { execArgv: ["--debug=5701"] }; // Server options let serverOptions: ServerOptions = { run : { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } } // Client options let clientOptions: LanguageClientOptions = { documentSelector: ['php'], synchronize: { configurationSection: 'PHP Mess Detector' } } // Create and start the client let client = new LanguageClient('vscode-phpmd', 'PHP Mess Detector', serverOptions, clientOptions) let disposable = client.start(); console.log("PHP Mess Detector started"); // Push the disposable to the context's subscriptions so that the // client can be deactivated on extension deactivation context.subscriptions.push(disposable); }
'use strict'; import * as path from 'path'; import { workspace, ExtensionContext } from 'vscode'; import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient'; export function activate(context: ExtensionContext) { let serverModule = context.asAbsolutePath(path.join('server', 'server.js')); // Server debug options let debugOptions = { execArgv: ["--nolazy", "--debug=6009"] }; // Server options let serverOptions: ServerOptions = { run : { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } } // Client options let clientOptions: LanguageClientOptions = { documentSelector: ['php'], synchronize: { configurationSection: 'PHP Mess Detector' } } // Create and start the client let client = new LanguageClient('vscode-phpmd', 'PHP Mess Detector', serverOptions, clientOptions) let disposable = client.start(); console.log("PHP Mess Detector started"); // Push the disposable to the context's subscriptions so that the // client can be deactivated on extension deactivation context.subscriptions.push(disposable); }
Update debug port and options
Update debug port and options
TypeScript
mit
sandhje/vscode-phpmd
--- +++ @@ -9,7 +9,7 @@ let serverModule = context.asAbsolutePath(path.join('server', 'server.js')); // Server debug options - let debugOptions = { execArgv: ["--debug=5701"] }; + let debugOptions = { execArgv: ["--nolazy", "--debug=6009"] }; // Server options let serverOptions: ServerOptions = {
55c13b22c569969d7e8e4482b9882628346944cb
modules/effects/src/actions.ts
modules/effects/src/actions.ts
import { Injectable, Inject } from '@angular/core'; import { Action, ScannedActionsSubject } from '@ngrx/store'; import { Observable } from 'rxjs/Observable'; import { Operator } from 'rxjs/Operator'; import { filter } from 'rxjs/operator/filter'; @Injectable() export class Actions<V = Action> extends Observable<V> { constructor(@Inject(ScannedActionsSubject) source?: Observable<V>) { super(); if (source) { this.source = source; } } lift<R>(operator: Operator<V, R>): Observable<R> { const observable = new Actions<R>(); observable.source = this; observable.operator = operator; return observable; } ofType(...allowedTypes: string[]): Actions<V> { return filter.call(this, (action: Action) => allowedTypes.some(type => type === action.type) ); } }
import { Injectable, Inject } from '@angular/core'; import { Action, ScannedActionsSubject } from '@ngrx/store'; import { Observable } from 'rxjs/Observable'; import { Operator } from 'rxjs/Operator'; import { filter } from 'rxjs/operator/filter'; @Injectable() export class Actions<V = Action> extends Observable<V> { constructor(@Inject(ScannedActionsSubject) source?: Observable<V>) { super(); if (source) { this.source = source; } } lift<R>(operator: Operator<V, R>): Observable<R> { const observable = new Actions<R>(); observable.source = this; observable.operator = operator; return observable; } ofType<V2 extends V = V>(...allowedTypes: string[]): Actions<V2> { return filter.call(this, (action: Action) => allowedTypes.some(type => type === action.type) ); } }
Add generic type to the "ofType" operator
feat(Effects): Add generic type to the "ofType" operator
TypeScript
mit
brandonroberts/platform,brandonroberts/platform,brandonroberts/platform,brandonroberts/platform
--- +++ @@ -21,7 +21,7 @@ return observable; } - ofType(...allowedTypes: string[]): Actions<V> { + ofType<V2 extends V = V>(...allowedTypes: string[]): Actions<V2> { return filter.call(this, (action: Action) => allowedTypes.some(type => type === action.type) );
b85a69a7b83a097c2b88e82bbb308bcfc5c1a775
ui/src/ifql/components/FuncListItem.tsx
ui/src/ifql/components/FuncListItem.tsx
import React, {PureComponent} from 'react' interface Props { name: string onAddNode: (name: string) => void selectedFunc: string onSetSelectedFunc: (name: string) => void } export default class FuncListItem extends PureComponent<Props> { public render() { const {name} = this.props return ( <li onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} className={`ifql-func--item ${this.getActiveClass()}`} > {name} </li> ) } private getActiveClass(): string { const {name, selectedFunc} = this.props return name === selectedFunc ? 'active' : '' } private handleMouseEnter = () => { this.props.onSetSelectedFunc(this.props.name) } private handleClick = () => { this.props.onAddNode(this.props.name) } }
import React, {PureComponent} from 'react' interface Props { name: string onAddNode: (name: string) => void selectedFunc: string onSetSelectedFunc: (name: string) => void } export default class FuncListItem extends PureComponent<Props> { public render() { const {name} = this.props return ( <li onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} className={`ifql-func--item ${this.activeClass}`} > {name} </li> ) } private get activeClass(): string { const {name, selectedFunc} = this.props return name === selectedFunc ? 'active' : '' } private handleMouseEnter = () => { this.props.onSetSelectedFunc(this.props.name) } private handleClick = () => { this.props.onAddNode(this.props.name) } }
Make func list item active class into a getter
Make func list item active class into a getter
TypeScript
mit
influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdata/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb
--- +++ @@ -15,14 +15,14 @@ <li onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} - className={`ifql-func--item ${this.getActiveClass()}`} + className={`ifql-func--item ${this.activeClass}`} > {name} </li> ) } - private getActiveClass(): string { + private get activeClass(): string { const {name, selectedFunc} = this.props return name === selectedFunc ? 'active' : '' }
5e42a253807199e8f0d8af06b08aac53bb0bef15
app/src/container/App.tsx
app/src/container/App.tsx
import * as React from "react"; import { BrowserRouter, Redirect, Route } from "react-router-dom"; import SignIn from "./SignIn"; import Tasks from "./Tasks"; export default class extends React.Component { public render() { return ( <BrowserRouter> <div> <Route path="/" render={() => <Redirect to="/tasks" />} /> <Route path="/tasks" render={() => <Redirect to="/tasks/todo" />} /> <Route path="/tasks/todo" render={() => <Tasks />} /> <Route path="/tasks/done" render={() => <Tasks {...{ done: true }} />} /> <Route path="/sign-in" component={SignIn} /> </div> </BrowserRouter> ); } }
import * as React from "react"; import { BrowserRouter, Redirect, Route } from "react-router-dom"; import SignIn from "./SignIn"; import Tasks from "./Tasks"; export default class extends React.Component { public render() { return ( <BrowserRouter> <div> <Route exact={true} path="/" render={() => <Redirect to="/tasks" />} /> <Route exact={true} path="/tasks" render={() => <Redirect to="/tasks/todo" />} /> <Route exact={true} path="/tasks/todo" render={() => <Tasks />} /> <Route exact={true} path="/tasks/done" render={() => <Tasks {...{ done: true }} />} /> <Route exact={true} path="/sign-in" component={SignIn} /> </div> </BrowserRouter> ); } }
Set exact options on routes
Set exact options on routes
TypeScript
mit
raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d
--- +++ @@ -9,11 +9,11 @@ return ( <BrowserRouter> <div> - <Route path="/" render={() => <Redirect to="/tasks" />} /> - <Route path="/tasks" render={() => <Redirect to="/tasks/todo" />} /> - <Route path="/tasks/todo" render={() => <Tasks />} /> - <Route path="/tasks/done" render={() => <Tasks {...{ done: true }} />} /> - <Route path="/sign-in" component={SignIn} /> + <Route exact={true} path="/" render={() => <Redirect to="/tasks" />} /> + <Route exact={true} path="/tasks" render={() => <Redirect to="/tasks/todo" />} /> + <Route exact={true} path="/tasks/todo" render={() => <Tasks />} /> + <Route exact={true} path="/tasks/done" render={() => <Tasks {...{ done: true }} />} /> + <Route exact={true} path="/sign-in" component={SignIn} /> </div> </BrowserRouter> );
53880b782b5ec6b84d856c7eaadd530d2ebb0498
test/utils.ts
test/utils.ts
import { ChartConfig, ChartConfigProps } from "charts/ChartConfig" import * as fixtures from "./fixtures" export function createConfig(props: Partial<ChartConfigProps>) { const config = new ChartConfig(new ChartConfigProps(props)) // ensureValidConfig() is only run on non-node environments, so we have // to manually trigger it. config.ensureValidConfig() return config } export function setupChart( id: 677 | 792, varId: 3512 | 104402, configOverrides?: Partial<ChartConfigProps> ) { const props = new ChartConfigProps({ ...fixtures.readChart(id), ...configOverrides }) const chart = new ChartConfig(props) chart.receiveData(fixtures.readVariable(varId)) return chart }
import { ChartConfig, ChartConfigProps } from "charts/ChartConfig" import * as fixtures from "./fixtures" export function createConfig(props?: Partial<ChartConfigProps>) { const config = new ChartConfig(new ChartConfigProps(props)) // ensureValidConfig() is only run on non-node environments, so we have // to manually trigger it. config.ensureValidConfig() return config } export function setupChart( id: 677 | 792, varId: 3512 | 104402, configOverrides?: Partial<ChartConfigProps> ) { const props = new ChartConfigProps({ ...fixtures.readChart(id), ...configOverrides }) const chart = new ChartConfig(props) chart.receiveData(fixtures.readVariable(varId)) return chart }
Make props optional in createConfig()
Make props optional in createConfig()
TypeScript
mit
OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher
--- +++ @@ -2,7 +2,7 @@ import * as fixtures from "./fixtures" -export function createConfig(props: Partial<ChartConfigProps>) { +export function createConfig(props?: Partial<ChartConfigProps>) { const config = new ChartConfig(new ChartConfigProps(props)) // ensureValidConfig() is only run on non-node environments, so we have // to manually trigger it.
745e63789707562e087f0e980cdb863de889ab9e
packages/react-input-feedback/src/index.ts
packages/react-input-feedback/src/index.ts
import { defaultTo, lensProp, merge, over, pipe } from 'ramda' import { ComponentClass, createElement as r, SFC } from 'react' import SequentialId from 'react-sequential-id' import { mapProps } from 'recompose' import { WrappedFieldProps } from 'redux-form' export type Component<P> = string | ComponentClass<P> | SFC<P> export interface IInputProps { components: { error: Component<any> input: Component<any> wrapper: Component<any> } } export type InputProps = IInputProps & WrappedFieldProps export type PartialInputProps = Partial<IInputProps> & WrappedFieldProps function Input({ components, input, meta, ...props }: InputProps) { const { error, touched } = meta const showError = touched && !!error return r(SequentialId, {}, (errorId: string) => r( components.wrapper, {}, r(components.input, { 'aria-describedby': showError ? errorId : null, 'aria-invalid': showError, ...props, ...input, }), showError && r(components.error, { id: errorId }, error), ), ) } const withDefaultComponents: ( component: Component<InputProps>, ) => Component<PartialInputProps> = mapProps( over( lensProp('components'), pipe( defaultTo({}), merge({ error: 'span', input: 'input', wrapper: 'span' }), ), ), ) export default withDefaultComponents(Input)
import { ComponentClass, createElement as r, SFC } from 'react' import SequentialId, { ISequentialIdProps } from 'react-sequential-id' import { WrappedFieldProps } from 'redux-form' export type Component<P> = string | ComponentClass<P> | SFC<P> export interface IInputComponents { error: Component<any> input: Component<any> wrapper: Component<any> } export interface IInputProps { components: IInputComponents } export type InputProps = IInputProps & WrappedFieldProps export { ISequentialIdProps } function Input({ components: c = {}, input, meta, ...props }: InputProps) { const components: IInputComponents = { error: 'span', input: 'input', wrapper: 'span', ...c, } const { error, touched } = meta const showError = touched && !!error return r(SequentialId, {}, (errorId: string) => r( components.wrapper, {}, r(components.input, { 'aria-describedby': showError ? errorId : null, 'aria-invalid': showError, ...props, ...input, }), showError && r(components.error, { id: errorId }, error), ), ) } export default Input
Stop using ramda and recompose
Stop using ramda and recompose
TypeScript
mit
thirdhand/components,thirdhand/components
--- +++ @@ -1,23 +1,30 @@ -import { defaultTo, lensProp, merge, over, pipe } from 'ramda' import { ComponentClass, createElement as r, SFC } from 'react' -import SequentialId from 'react-sequential-id' -import { mapProps } from 'recompose' +import SequentialId, { ISequentialIdProps } from 'react-sequential-id' import { WrappedFieldProps } from 'redux-form' export type Component<P> = string | ComponentClass<P> | SFC<P> +export interface IInputComponents { + error: Component<any> + input: Component<any> + wrapper: Component<any> +} + export interface IInputProps { - components: { - error: Component<any> - input: Component<any> - wrapper: Component<any> - } + components: IInputComponents } export type InputProps = IInputProps & WrappedFieldProps -export type PartialInputProps = Partial<IInputProps> & WrappedFieldProps -function Input({ components, input, meta, ...props }: InputProps) { +export { ISequentialIdProps } + +function Input({ components: c = {}, input, meta, ...props }: InputProps) { + const components: IInputComponents = { + error: 'span', + input: 'input', + wrapper: 'span', + ...c, + } const { error, touched } = meta const showError = touched && !!error return r(SequentialId, {}, (errorId: string) => @@ -35,16 +42,4 @@ ) } -const withDefaultComponents: ( - component: Component<InputProps>, -) => Component<PartialInputProps> = mapProps( - over( - lensProp('components'), - pipe( - defaultTo({}), - merge({ error: 'span', input: 'input', wrapper: 'span' }), - ), - ), -) - -export default withDefaultComponents(Input) +export default Input
ce4fc223ed0051dabcc3ca6d45079b7f20271962
packages/ui-interpreter/src/ui/Console.tsx
packages/ui-interpreter/src/ui/Console.tsx
import * as React from 'react' import Store from '../store' import Snapshot from './Snapshot' import { observer } from 'mobx-react' import ConsoleInput from './ConsoleInput' import Toolbar from './Toolbar' function Console({ store }: { store: Store }) { const style = { position: 'relative', overflow: 'auto' } const snapshots = store.snapshots.map((s, idx) => <Snapshot key={`snapshot-${idx}`} snapshotData={s} store={store} /> ) return ( <div style={style}> <Toolbar store={store} /> {snapshots} <ConsoleInput store={store} /> </div> ) } export default observer(Console)
import * as React from 'react' import Store from '../store' import Snapshot from './Snapshot' import { observer } from 'mobx-react' import ConsoleInput from './ConsoleInput' import Toolbar from './Toolbar' function Console({ store }: { store: Store }) { const style = { position: 'relative' } const snapshots = store.snapshots.map((s, idx) => <Snapshot key={`snapshot-${idx}`} snapshotData={s} store={store} /> ) return ( <div style={style}> <Toolbar store={store} /> {snapshots} <ConsoleInput store={store} /> </div> ) } export default observer(Console)
Remove extraneous scrollbar in console
Remove extraneous scrollbar in console
TypeScript
mit
evansb/respace,evansb/respace,evansb/respace,respace-js/respace,respace-js/respace
--- +++ @@ -6,10 +6,7 @@ import Toolbar from './Toolbar' function Console({ store }: { store: Store }) { - const style = { - position: 'relative', - overflow: 'auto' - } + const style = { position: 'relative' } const snapshots = store.snapshots.map((s, idx) => <Snapshot key={`snapshot-${idx}`} snapshotData={s} store={store} /> )
722fb44fc80cfcb3e7d47daa08fdf54cbe4531a3
src/marketplace/details/plan/actions.ts
src/marketplace/details/plan/actions.ts
import { openModalDialog } from '@waldur/modal/actions'; export const showOfferingPlanDescription = planDescription => openModalDialog('marketplaceOfferingPlanDescription', {resolve: {plan_description: planDescription}, size: 'md'}); export const showPlanDetailsDialog = resourceId => openModalDialog('marketplacePlanDetailsDialog', {resolve: {resourceId}, size: 'md'});
import { openModalDialog } from '@waldur/modal/actions'; export const showOfferingPlanDescription = planDescription => openModalDialog('marketplaceOfferingPlanDescription', {resolve: {plan_description: planDescription}, size: 'md'}); export const showPlanDetailsDialog = resourceId => openModalDialog('marketplacePlanDetailsDialog', {resolve: {resourceId}, size: 'lg'});
Enlarge plan details dialog width to fit table
Enlarge plan details dialog width to fit table [WAL-2588]
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -4,4 +4,4 @@ openModalDialog('marketplaceOfferingPlanDescription', {resolve: {plan_description: planDescription}, size: 'md'}); export const showPlanDetailsDialog = resourceId => - openModalDialog('marketplacePlanDetailsDialog', {resolve: {resourceId}, size: 'md'}); + openModalDialog('marketplacePlanDetailsDialog', {resolve: {resourceId}, size: 'lg'});
3975095eba742a2df6ffeacaf03e50b1c8edc826
src/jpcontrol.ts
src/jpcontrol.ts
'use strict'; import * as vscode from 'vscode'; import * as jmespath from 'jmespath'; export class JMESPathController { private _outputChannel: vscode.OutputChannel; private _lastExpression: string; private _lastResult: any; constructor() { this._outputChannel = vscode.window.createOutputChannel('JMESPath'); this._lastExpression = ''; } evaluateJMESPathExpression() { let editor = vscode.window.activeTextEditor; let jsonText = editor.document.getText(); let jsonDoc = JSON.parse(jsonText); vscode.window.showInputBox({ placeHolder: '', prompt: 'Enter a JMESPath expression' }).then(value => { let query = value; try { let result = jmespath.search(jsonDoc, query); this.displayOnOutputChannel(JSON.stringify(result, null, 2)); } catch (err) { let errorMessage = `${err.name}: ${err.message}`; vscode.window.showErrorMessage(errorMessage); } }); } private displayOnOutputChannel(message: string) { this._outputChannel.clear(); this._outputChannel.append(message); this._outputChannel.show(); } }
'use strict'; import * as vscode from 'vscode'; import * as jmespath from 'jmespath'; export class JMESPathController { private _outputChannel: vscode.OutputChannel; private _lastExpression: string; private _lastResult: any; constructor() { this._outputChannel = vscode.window.createOutputChannel('JMESPath'); this._lastExpression = ''; } evaluateJMESPathExpression() { let editor = vscode.window.activeTextEditor; let jsonText = editor.document.getText(); let jsonDoc = JSON.parse(jsonText); vscode.window.showInputBox({ placeHolder: '', prompt: 'Enter a JMESPath expression' }).then(value => { if (!value) { return; } let query = value; try { let result = jmespath.search(jsonDoc, query); this.displayOnOutputChannel(JSON.stringify(result, null, 2)); } catch (err) { let errorMessage = `${err.name}: ${err.message}`; vscode.window.showErrorMessage(errorMessage); } }); } private displayOnOutputChannel(message: string) { this._outputChannel.clear(); this._outputChannel.append(message); this._outputChannel.show(); } }
Fix bug when user cancels input text
Fix bug when user cancels input text
TypeScript
apache-2.0
jmespath/jmespath.vscode
--- +++ @@ -21,6 +21,9 @@ placeHolder: '', prompt: 'Enter a JMESPath expression' }).then(value => { + if (!value) { + return; + } let query = value; try { let result = jmespath.search(jsonDoc, query);
b7b58fa337c234b9cc21f9fa3b22a745d57ad875
components/datasource-selector/select-type-to-add-layer-dialog.component.ts
components/datasource-selector/select-type-to-add-layer-dialog.component.ts
/** * DEPRECATED * * @deprecated */ import {Component, Input} from '@angular/core'; import {HsDatasourcesService} from './datasource-selector.service'; @Component({ selector: 'hs-select-type-to-add-layer', template: require('./partials/select-type-to-add-layer-dialog.html'), }) export class HsSelectTypeToAddLayerDialogComponent { @Input() layer; @Input() types; @Input() endpoint; modalVisible; alertChoose; layerType; //do not rename to 'type', would clash in the template constructor(private hsDatasourcesService: HsDatasourcesService) { this.modalVisible = true; } add(): void { if (this.layerType === undefined) { this.alertChoose = true; } else { this.modalVisible = false; this.hsDatasourcesService.addLayerToMap( this.endpoint, this.layer, this.layerType ); } } }
import {Component, Input} from '@angular/core'; import {HsDatasourcesService} from './datasource-selector.service'; import {HsLayoutService} from '../layout/layout.service'; @Component({ selector: 'hs-select-type-to-add-layer', template: require('./partials/select-type-to-add-layer-dialog.html'), }) export class HsSelectTypeToAddLayerDialogComponent { @Input() layer; @Input() types; @Input() endpoint; modalVisible; alertChoose; layerType; //do not rename to 'type', would clash in the template constructor( private hsDatasourcesService: HsDatasourcesService, private HsLayoutService: HsLayoutService ) { this.modalVisible = true; } add(): void { if (this.layerType === undefined) { this.alertChoose = true; } else { this.modalVisible = false; this.hsDatasourcesService.addLayerToMap( this.endpoint, this.layer, this.layerType ); this.HsLayoutService.setMainPanel('layermanager'); } } }
Switch to layermanager after adding wfs layer from layman
Switch to layermanager after adding wfs layer from layman
TypeScript
mit
hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng
--- +++ @@ -1,11 +1,7 @@ -/** - * DEPRECATED - * - * @deprecated - */ import {Component, Input} from '@angular/core'; import {HsDatasourcesService} from './datasource-selector.service'; +import {HsLayoutService} from '../layout/layout.service'; @Component({ selector: 'hs-select-type-to-add-layer', @@ -20,7 +16,10 @@ alertChoose; layerType; //do not rename to 'type', would clash in the template - constructor(private hsDatasourcesService: HsDatasourcesService) { + constructor( + private hsDatasourcesService: HsDatasourcesService, + private HsLayoutService: HsLayoutService + ) { this.modalVisible = true; } @@ -34,6 +33,7 @@ this.layer, this.layerType ); + this.HsLayoutService.setMainPanel('layermanager'); } } }
a74f7fabbf3661f3d002c88c51c36e5596834c16
commands/component/templates/spec.ts
commands/component/templates/spec.ts
/* ts-lint:disable:no-unused-variable */ import { TestBed, async } from '@angular/core/testing'; import { {{ componentName }} } from './{{ selector }}.component'; describe('{{ componentName }}', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [ {{ componentName }} ], }); TestBed.compileComponents(); }); it('should create the {{ selector }}', async(() => { const fixture = TestBed.createComponent({{ componentName }}); const component = fixture.debugElement.componentInstance; expect(component).toBeTruthy(); })); });
/* ts-lint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { {{ componentName }} } from './{{ selector }}.component'; describe('{{ componentName }}', () => { let component: {{ componentName }}; let fixture: ComponentFixture<{{ componentName }}>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ {{ componentName }} ], }); TestBed.compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent({{ componentName }}); component = fixture.debugElement.componentInstance; }); it('should create the {{ selector }}', () => { expect(component).toBeTruthy(); }); });
Update to the testing of components.
Update to the testing of components. The setup now falls more inline with the guidelines from https://angular.io/docs/ts/latest/guide/testing.html#!#async-in-before-each
TypeScript
mit
gonzofish/angular-library-set,gonzofish/angular-librarian,gonzofish/angular-library-set,gonzofish/angular-library-set,gonzofish/angular-librarian,gonzofish/angular-librarian
--- +++ @@ -1,21 +1,26 @@ /* ts-lint:disable:no-unused-variable */ -import { TestBed, async } from '@angular/core/testing'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { {{ componentName }} } from './{{ selector }}.component'; describe('{{ componentName }}', () => { - beforeEach(() => { + let component: {{ componentName }}; + let fixture: ComponentFixture<{{ componentName }}>; + + beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ {{ componentName }} ], }); TestBed.compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent({{ componentName }}); + component = fixture.debugElement.componentInstance; }); - it('should create the {{ selector }}', async(() => { - const fixture = TestBed.createComponent({{ componentName }}); - const component = fixture.debugElement.componentInstance; - + it('should create the {{ selector }}', () => { expect(component).toBeTruthy(); - })); + }); });
6f269ce6c879e0970c2dd2a3e1e322982f07dd04
packages/db-kit/bin/cli.ts
packages/db-kit/bin/cli.ts
import { start } from "@truffle/db-kit/cli"; async function main() { await start(); } main();
#!/usr/bin/env node import { start } from "@truffle/db-kit/cli"; async function main() { await start(); } main();
Add missing shebang and chmod +x
Add missing shebang and chmod +x
TypeScript
mit
ConsenSys/truffle
--- +++ @@ -1,3 +1,4 @@ +#!/usr/bin/env node import { start } from "@truffle/db-kit/cli"; async function main() {
0fff23dbe6fdbb9341805ba67fb307ee0bd5e1d0
pages/_document.tsx
pages/_document.tsx
import Document, { Head, Main, NextScript, NextDocumentContext } from 'next/document'; import * as http from 'http'; type MyDocumentProps = { locale: string; localeDataScript: string; }; export default class MyDocument extends Document<MyDocumentProps> { static async getInitialProps(context: NextDocumentContext) { const props = await super.getInitialProps(context); const req = context.req as http.IncomingMessage & MyDocumentProps; return { ...props, locale: req.locale, localeDataScript: req.localeDataScript }; } render() { return ( <html> <Head /> <body> <Main /> <script dangerouslySetInnerHTML={{ __html: this.props.localeDataScript }} /> <NextScript /> </body> </html> ); } }
import * as React from 'react'; import Document, { Head, Main, NextScript, NextDocumentContext } from 'next/document'; import * as http from 'http'; type MyDocumentProps = { locale: string; localeDataScript: string; }; export default class MyDocument extends Document<MyDocumentProps> { static async getInitialProps(context: NextDocumentContext) { const props = await super.getInitialProps(context); const req = context.req as http.IncomingMessage & MyDocumentProps; return { ...props, locale: req.locale, localeDataScript: req.localeDataScript }; } render() { return ( <html> <Head> <title>Krasnodar Dev Days</title> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> </Head> <body> <Main /> <script dangerouslySetInnerHTML={{ __html: this.props.localeDataScript }} /> <NextScript /> </body> </html> ); } }
Add default title and meta viewport tags
Add default title and meta viewport tags
TypeScript
mit
krddevdays/krddevdays.ru,krddevdays/krddevdays.ru
--- +++ @@ -1,3 +1,4 @@ +import * as React from 'react'; import Document, { Head, Main, NextScript, NextDocumentContext } from 'next/document'; import * as http from 'http'; @@ -21,7 +22,10 @@ render() { return ( <html> - <Head /> + <Head> + <title>Krasnodar Dev Days</title> + <meta name="viewport" content="initial-scale=1.0, width=device-width" /> + </Head> <body> <Main /> <script
4d05189d8dbd6807684ff74d5ae502d05bced42a
tests/cases/conformance/classes/classDeclarations/mergedInheritedClassInterface.ts
tests/cases/conformance/classes/classDeclarations/mergedInheritedClassInterface.ts
interface BaseInterface { required: number; optional?: number; } declare class BaseClass { baseMethod(); x2: number; } interface Child extends BaseInterface { x3: number; } declare class Child extends BaseClass { x4: number; method(); } // checks if properties actually were merged var child : Child; child.required; child.optional; child.x3; child.x4; child.baseMethod(); child.method();
interface BaseInterface { required: number; optional?: number; } declare class BaseClass { baseMethod(); baseNumber: number; } interface Child extends BaseInterface { additional: number; } declare class Child extends BaseClass { classNumber: number; method(); } // checks if properties actually were merged var child : Child; child.required; child.optional; child.additional; child.baseNumber; child.classNumber; child.baseMethod(); child.method();
Improve naming of test members
Improve naming of test members
TypeScript
apache-2.0
mmoskal/TypeScript,basarat/TypeScript,donaldpipowitch/TypeScript,Eyas/TypeScript,synaptek/TypeScript,nycdotnet/TypeScript,vilic/TypeScript,nycdotnet/TypeScript,donaldpipowitch/TypeScript,evgrud/TypeScript,kpreisser/TypeScript,ionux/TypeScript,DLehenbauer/TypeScript,basarat/TypeScript,alexeagle/TypeScript,vilic/TypeScript,thr0w/Thr0wScript,erikmcc/TypeScript,mihailik/TypeScript,jwbay/TypeScript,thr0w/Thr0wScript,donaldpipowitch/TypeScript,fabioparra/TypeScript,AbubakerB/TypeScript,kitsonk/TypeScript,blakeembrey/TypeScript,donaldpipowitch/TypeScript,fabioparra/TypeScript,kpreisser/TypeScript,chuckjaz/TypeScript,nojvek/TypeScript,mmoskal/TypeScript,Microsoft/TypeScript,yortus/TypeScript,yortus/TypeScript,mmoskal/TypeScript,minestarks/TypeScript,ionux/TypeScript,jwbay/TypeScript,jeremyepling/TypeScript,alexeagle/TypeScript,yortus/TypeScript,samuelhorwitz/typescript,SaschaNaz/TypeScript,ionux/TypeScript,SaschaNaz/TypeScript,DLehenbauer/TypeScript,DLehenbauer/TypeScript,mmoskal/TypeScript,nycdotnet/TypeScript,TukekeSoft/TypeScript,AbubakerB/TypeScript,ziacik/TypeScript,samuelhorwitz/typescript,kitsonk/TypeScript,chuckjaz/TypeScript,basarat/TypeScript,blakeembrey/TypeScript,blakeembrey/TypeScript,evgrud/TypeScript,plantain-00/TypeScript,fabioparra/TypeScript,kimamula/TypeScript,SaschaNaz/TypeScript,weswigham/TypeScript,yortus/TypeScript,microsoft/TypeScript,vilic/TypeScript,synaptek/TypeScript,jeremyepling/TypeScript,jwbay/TypeScript,TukekeSoft/TypeScript,mihailik/TypeScript,Eyas/TypeScript,samuelhorwitz/typescript,alexeagle/TypeScript,kimamula/TypeScript,mihailik/TypeScript,erikmcc/TypeScript,plantain-00/TypeScript,Eyas/TypeScript,jeremyepling/TypeScript,AbubakerB/TypeScript,jwbay/TypeScript,nojvek/TypeScript,plantain-00/TypeScript,ionux/TypeScript,ziacik/TypeScript,minestarks/TypeScript,samuelhorwitz/typescript,weswigham/TypeScript,Eyas/TypeScript,evgrud/TypeScript,nojvek/TypeScript,erikmcc/TypeScript,kimamula/TypeScript,nojvek/TypeScript,synaptek/TypeScript,Microsoft/TypeScript,synaptek/TypeScript,vilic/TypeScript,blakeembrey/TypeScript,microsoft/TypeScript,thr0w/Thr0wScript,plantain-00/TypeScript,basarat/TypeScript,evgrud/TypeScript,kpreisser/TypeScript,weswigham/TypeScript,minestarks/TypeScript,chuckjaz/TypeScript,microsoft/TypeScript,nycdotnet/TypeScript,ziacik/TypeScript,fabioparra/TypeScript,ziacik/TypeScript,mihailik/TypeScript,SaschaNaz/TypeScript,chuckjaz/TypeScript,AbubakerB/TypeScript,DLehenbauer/TypeScript,kitsonk/TypeScript,kimamula/TypeScript,TukekeSoft/TypeScript,RyanCavanaugh/TypeScript,thr0w/Thr0wScript,RyanCavanaugh/TypeScript,Microsoft/TypeScript,RyanCavanaugh/TypeScript,erikmcc/TypeScript
--- +++ @@ -5,15 +5,15 @@ declare class BaseClass { baseMethod(); - x2: number; + baseNumber: number; } interface Child extends BaseInterface { - x3: number; + additional: number; } declare class Child extends BaseClass { - x4: number; + classNumber: number; method(); } @@ -21,7 +21,8 @@ var child : Child; child.required; child.optional; -child.x3; -child.x4; +child.additional; +child.baseNumber; +child.classNumber; child.baseMethod(); child.method();
c1ca35eac16c733262862856954a395207f7cbad
whisper/pages/index.tsx
whisper/pages/index.tsx
import {ApolloQueryResult} from "@apollo/client" import {GetStaticPropsResult} from "next" import {Fragment, FC} from "react" import PostsPayload from "type/api/PostsPayload" import getApollo from "lib/graphql/client/getApollo" import withError from "lib/error/withError" import layout from "lib/hoc/layout" import BlogLayout from "layout/Blog" import Preview from "component/Post/Preview" import getPosts from "api/query/posts.gql" type PageProps = ApolloQueryResult<PostsPayload> export const getStaticProps = withError( async (): Promise<GetStaticPropsResult<PageProps>> => { const client = getApollo() const props = await client.query<PostsPayload>({query: getPosts}) return { props, } } ) const Home: FC<PageProps> = ({data}) => { const {posts} = data return ( <main> { posts.list.length ? ( <Fragment> {posts.list.map(post => <Preview key={post.id} post={post} />)} </Fragment> ) : <div>There's no posts</div> } </main> ) } export default layout(BlogLayout)(Home)
import {ApolloQueryResult} from "@apollo/client" import {GetStaticPropsResult} from "next" import {Fragment, FC} from "react" import PostsPayload from "type/api/PostsPayload" import getApollo from "lib/graphql/client/getApollo" import withError from "lib/error/withError" import layout from "lib/hoc/layout" import BlogLayout from "layout/Blog" import Preview from "component/Post/Preview" import getPosts from "api/query/posts.gql" type PageProps = ApolloQueryResult<PostsPayload> export const getStaticProps = withError( async (): Promise<GetStaticPropsResult<PageProps>> => { const client = getApollo() const props = await client.query<PostsPayload>({query: getPosts}) return { props, revalidate: 60 } } ) const Home: FC<PageProps> = ({data}) => { const {posts} = data return ( <main> { posts.list.length ? ( <Fragment> {posts.list.map(post => <Preview key={post.id} post={post} />)} </Fragment> ) : <div>There's no posts</div> } </main> ) } export default layout(BlogLayout)(Home)
Add an option to revalidate home page
Add an option to revalidate home page
TypeScript
mit
octet-stream/eri,octet-stream/eri
--- +++ @@ -23,6 +23,7 @@ return { props, + revalidate: 60 } } )
643bb44ab4a0d1d8310ac31aba621bbe86150a02
packages/truffle-db/src/loaders/index.ts
packages/truffle-db/src/loaders/index.ts
import { TruffleDB } from "truffle-db"; import { ArtifactsLoader } from "./artifacts"; import { schema as rootSchema } from "truffle-db/schema"; import { Workspace, schema } from "truffle-db/workspace"; const tmp = require("tmp"); import { makeExecutableSchema } from "@gnd/graphql-tools"; import { gql } from "apollo-server"; //dummy query here because of known issue with Apollo mutation-only schemas const typeDefs = gql` type Mutation { loadArtifacts: Boolean } type Query { dummy: String } `; const resolvers = { Mutation: { loadArtifacts: { resolve: async (_, args, { artifactsDirectory, contractsDirectory, db }, info) => { const compilationConfig = { contracts_directory: contractsDirectory, contracts_build_directory: tmp.dirSync({ unsafeCleanup: true }), all: true } const loader = new ArtifactsLoader(db, compilationConfig); loader.load(); } } } } export const loaderSchema = makeExecutableSchema({ typeDefs, resolvers });
import { TruffleDB } from "truffle-db"; import { ArtifactsLoader } from "./artifacts"; import { schema as rootSchema } from "truffle-db/schema"; import { Workspace, schema } from "truffle-db/workspace"; const tmp = require("tmp"); import { makeExecutableSchema } from "@gnd/graphql-tools"; import { gql } from "apollo-server"; //dummy query here because of known issue with Apollo mutation-only schemas const typeDefs = gql` type Mutation { loadArtifacts: Boolean } type Query { dummy: String } `; const resolvers = { Mutation: { loadArtifacts: { resolve: async (_, args, { artifactsDirectory, contractsDirectory, db }, info) => { const tempDir = tmp.dirSync({ unsafeCleanup: true }) const compilationConfig = { contracts_directory: contractsDirectory, contracts_build_directory: tempDir.name, all: true } const loader = new ArtifactsLoader(db, compilationConfig); await loader.load() tempDir.removeCallback(); return true; } } } } export const loaderSchema = makeExecutableSchema({ typeDefs, resolvers });
Use tmp directory for build in manual truffle compile
Use tmp directory for build in manual truffle compile
TypeScript
mit
ConsenSys/truffle
--- +++ @@ -22,14 +22,17 @@ Mutation: { loadArtifacts: { resolve: async (_, args, { artifactsDirectory, contractsDirectory, db }, info) => { + const tempDir = tmp.dirSync({ unsafeCleanup: true }) const compilationConfig = { contracts_directory: contractsDirectory, - contracts_build_directory: tmp.dirSync({ unsafeCleanup: true }), + contracts_build_directory: tempDir.name, all: true } const loader = new ArtifactsLoader(db, compilationConfig); - loader.load(); + await loader.load() + tempDir.removeCallback(); + return true; } } }
06e00f620e630158c46e02e77397458394531b87
src/app/components/widgets/menu.component.ts
src/app/components/widgets/menu.component.ts
import {Renderer2} from '@angular/core'; import {MenuContext, MenuService} from '../menu-service'; /** * @author Daniel de Oliveira * @author Thomas Kleinke */ export abstract class MenuComponent { public opened: boolean = false; private removeMouseEventListener: Function|undefined; constructor(private renderer: Renderer2, protected menuService: MenuService, private buttonElementId: string, private menuElementsPrefix: string) {} public toggle() { if (this.opened) { this.close(); } else { this.open(); } } public open() { this.opened = true; this.removeMouseEventListener = this.renderer.listen( 'document', 'click', event => this.handleMouseEvent(event)); } public close() { this.opened = false; if (this.removeMouseEventListener) this.removeMouseEventListener(); } private handleMouseEvent(event: any) { if (this.menuService.getContext() === MenuContext.MODAL) return; let target = event.target; let inside = false; do { if (target.id === this.buttonElementId || target.id.startsWith(this.menuElementsPrefix)) { inside = true; break; } target = target.parentNode; } while (target); if (!inside) this.close(); } }
import {Renderer2} from '@angular/core'; import {MenuContext, MenuService} from '../menu-service'; /** * @author Daniel de Oliveira * @author Thomas Kleinke */ export abstract class MenuComponent { public opened: boolean = false; private removeMouseEventListener: Function|undefined; constructor(private renderer: Renderer2, protected menuService: MenuService, private buttonElementId: string, private menuElementsPrefix: string) {} public toggle() { if (this.opened) { this.close(); } else { this.open(); } } public open() { this.opened = true; this.removeMouseEventListener = this.renderer.listen( 'document', 'click', event => this.handleMouseEvent(event)); } public close() { this.opened = false; if (this.removeMouseEventListener) this.removeMouseEventListener(); } private handleMouseEvent(event: any) { if (this.menuService.getContext() === MenuContext.MODAL) return; let target = event.target; let inside = false; do { if (target.id && (target.id === this.buttonElementId || target.id.startsWith(this.menuElementsPrefix))) { inside = true; break; } target = target.parentNode; } while (target); if (!inside) this.close(); } }
Fix closing layer & matrix menus
Fix closing layer & matrix menus
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -56,7 +56,7 @@ let inside = false; do { - if (target.id === this.buttonElementId || target.id.startsWith(this.menuElementsPrefix)) { + if (target.id && (target.id === this.buttonElementId || target.id.startsWith(this.menuElementsPrefix))) { inside = true; break; }
eb60ceab61185828f2c11a3c8b66f7703372df0b
lib/src/types.ts
lib/src/types.ts
import * as ReactNative from 'react-native'; import { LinearGradientProps } from 'react-native-linear-gradient'; export type StretchyImage = | ReactNative.ImageURISource | ReactNative.ImageRequireSource; export type StretchyOnScroll = ( position: number, reachedToBottomOfHeader: boolean, ) => void; export interface StretchyProps { backgroundColor?: string; image?: StretchyImage; imageHeight?: number; imageResizeMode?: ReactNative.ImageResizeMode; imageWrapperStyle?: ReactNative.ViewStyle; foreground?: React.ReactElement; onScroll?: StretchyOnScroll; gradient?: Pick< LinearGradientProps, | 'colors' | 'start' | 'end' | 'locations' | 'useAngle' | 'angleCenter' | 'angle' >; }
import * as ReactNative from 'react-native'; import { LinearGradientProps } from 'react-native-linear-gradient'; export type StretchyImage = ReactNative.ImageSourcePropType export type StretchyOnScroll = ( position: number, reachedToBottomOfHeader: boolean, ) => void; export interface StretchyProps { backgroundColor?: string; image?: StretchyImage; imageHeight?: number; imageResizeMode?: ReactNative.ImageResizeMode; imageWrapperStyle?: ReactNative.ViewStyle; foreground?: React.ReactElement; onScroll?: StretchyOnScroll; gradient?: Pick< LinearGradientProps, | 'colors' | 'start' | 'end' | 'locations' | 'useAngle' | 'angleCenter' | 'angle' >; }
Use ImageSourcePropType for StretchyImage type
Use ImageSourcePropType for StretchyImage type
TypeScript
mit
hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy
--- +++ @@ -1,9 +1,7 @@ import * as ReactNative from 'react-native'; import { LinearGradientProps } from 'react-native-linear-gradient'; -export type StretchyImage = - | ReactNative.ImageURISource - | ReactNative.ImageRequireSource; +export type StretchyImage = ReactNative.ImageSourcePropType export type StretchyOnScroll = ( position: number,
029ac8c2e4b16d3532b254776c8c47f41d9c4999
src/utils/extend.ts
src/utils/extend.ts
import { Stream } from 'xstream'; export function shallowCopy(target: Object, source: Object) { for (var key in source) if (source.hasOwnProperty(key)) target[key] = source[key]; } export function shallowExtend(target: Object, ...sources: Object[]): Object { sources.forEach(source => shallowCopy(target, source)); return target; } export function shallowExtendNew(target: Object, ...sources: Object[]): Object { return shallowExtend({}, target, sources); } export function merge<T>(target: T, ...sources: T[]): T { return shallowExtendNew(target, sources) as T; } export function take<T>(main$: Stream<T>, default$: Stream<T>): Stream<T> { return main$ == undefined ? default$ : main$; }
import { Stream } from 'xstream'; export function shallowCopy(target: Object, source: Object) { for (var key in source) if (source.hasOwnProperty(key)) target[key] = source[key]; } export function shallowExtend(target: Object, ...sources: Object[]): Object { sources.forEach(source => shallowCopy(target, source)); return target; } export function shallowExtendNew(target: Object, ...sources: Object[]): Object { return shallowExtend({}, ...[target, ...sources]); } export function merge<T>(target: T, ...sources: T[]): T { return shallowExtendNew(target, ...sources) as T; } export function take<T>(main$: Stream<T>, default$: Stream<T>): Stream<T> { return main$ == undefined ? default$ : main$; }
Fix merge to pass tests
Fix merge to pass tests
TypeScript
mit
cyclic-ui/cyclic-ui,cyclic-ui/cyclic-ui
--- +++ @@ -12,11 +12,11 @@ } export function shallowExtendNew(target: Object, ...sources: Object[]): Object { - return shallowExtend({}, target, sources); + return shallowExtend({}, ...[target, ...sources]); } export function merge<T>(target: T, ...sources: T[]): T { - return shallowExtendNew(target, sources) as T; + return shallowExtendNew(target, ...sources) as T; } export function take<T>(main$: Stream<T>, default$: Stream<T>): Stream<T> {
e472e1e61f452ac57a04521ae741410cce454198
app/src/ui/repository-settings/fork-contribution-target-description.tsx
app/src/ui/repository-settings/fork-contribution-target-description.tsx
import * as React from 'react' import { ForkContributionTarget } from '../../models/workflow-preferences' import { RepositoryWithForkedGitHubRepository } from '../../models/repository' interface IForkSettingsDescription { readonly repository: RepositoryWithForkedGitHubRepository readonly forkContributionTarget: ForkContributionTarget } export function ForkSettingsDescription(props: IForkSettingsDescription) { // We can't use the getNonForkGitHubRepository() helper since we need to calculate // the value based on the temporary form state. const targetRepository = props.forkContributionTarget === ForkContributionTarget.Self ? props.repository.gitHubRepository : props.repository.gitHubRepository.parent return ( <ul className="fork-settings-description"> <li> Pull requests targeting <strong>{targetRepository.fullName}</strong>{' '} will be shown in the pull request list. </li> <li> Issues will be created in <strong>{targetRepository.fullName}</strong>. </li> <li> "View on Github" will open <strong>{targetRepository.fullName}</strong>{' '} in the browser. </li> <li> New branches will be based on{' '} <strong>{targetRepository.fullName}</strong>'s default branch. </li> </ul> ) }
import * as React from 'react' import { ForkContributionTarget } from '../../models/workflow-preferences' import { RepositoryWithForkedGitHubRepository } from '../../models/repository' interface IForkSettingsDescription { readonly repository: RepositoryWithForkedGitHubRepository readonly forkContributionTarget: ForkContributionTarget } export function ForkSettingsDescription(props: IForkSettingsDescription) { // We can't use the getNonForkGitHubRepository() helper since we need to calculate // the value based on the temporary form state. const targetRepository = props.forkContributionTarget === ForkContributionTarget.Self ? props.repository.gitHubRepository : props.repository.gitHubRepository.parent return ( <ul className="fork-settings-description"> <li> Pull requests targeting <strong>{targetRepository.fullName}</strong>{' '} will be shown in the pull request list. </li> <li> Issues will be created in <strong>{targetRepository.fullName}</strong>. </li> <li> "View on Github" will open <strong>{targetRepository.fullName}</strong>{' '} in the browser. </li> <li> New branches will be based on{' '} <strong>{targetRepository.fullName}</strong>'s default branch. </li> <li> Autocompletion of user and issues will be based on{' '} <strong>{targetRepository.fullName}</strong>. </li> </ul> ) }
Include line about autocomplete in fork preferences
Include line about autocomplete in fork preferences
TypeScript
mit
artivilla/desktop,say25/desktop,say25/desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,say25/desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,shiftkey/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,kactus-io/kactus,kactus-io/kactus,desktop/desktop
--- +++ @@ -32,6 +32,10 @@ New branches will be based on{' '} <strong>{targetRepository.fullName}</strong>'s default branch. </li> + <li> + Autocompletion of user and issues will be based on{' '} + <strong>{targetRepository.fullName}</strong>. + </li> </ul> ) }
6d8dbedcbd27f6eb2b1bc0e7b223100def826396
src/index.ts
src/index.ts
import * as express from "express" const app = express() app.get('/', (req, res) => { res.send('Hello Typescript!'); }) app.get('/:name', (req, res) => { const name: string = req.params.name; res.send('Hello ' + name + '!'); }) app.listen('8080') console.log('\nApp is running. To view it, open a web browser to http://localhost:8080.\nTo be greeted by the app, visit http://localhost:8080/YourName.\n\nQuit app with ctrl+c.')
import * as express from 'express' const app = express() app.get('/', (req, res) => { res.send('Hello Typescript!'); }) app.get('/:name', (req, res) => { const name: string = req.params.name; res.send('Hello ' + name + '!'); }) app.listen('8080') console.log('\nApp is running. To view it, open a web browser to http://localhost:8080.\nTo be greeted by the app, visit http://localhost:8080/YourName.\n\nQuit app with ctrl+c.')
Change an import statement from double quotes to single quotes.
Change an import statement from double quotes to single quotes.
TypeScript
agpl-3.0
majtom2grndctrl/hello-typescript-express
--- +++ @@ -1,4 +1,4 @@ -import * as express from "express" +import * as express from 'express' const app = express()
69d9febb874207981fac2f1d10a7f98ffbf0ce29
src/models/message.ts
src/models/message.ts
import mongoose from 'mongoose'; import Message from '@/interfaces/Message'; export interface IMessageModel extends Message, mongoose.Document { _receivers: mongoose.Types.DocumentArray<mongoose.Types.Subdocument>; } export const userRessourceSchema = new mongoose.Schema({ name: String, mail: String, language: String, payload: Object, }); export const messageSchema = new mongoose.Schema({ platform: String, template: String, sender: { name: String, mail: String, }, payload: [ { language: String, payload: Object, }, ], receivers: [ userRessourceSchema ], trackLinks: Boolean, }); const messageModel: mongoose.Model<IMessageModel> = mongoose.model('Message', messageSchema); export default messageModel;
import mongoose from 'mongoose'; import Message from '@/interfaces/Message'; export interface IUserRessourceModel extends mongoose.Types.Subdocument { name: string, mail: string, language: string, payload: any, }; export interface IMessageModel extends Message, mongoose.Document { _receivers: mongoose.Types.DocumentArray<IUserRessourceModel>; } export const userRessourceSchema = new mongoose.Schema({ name: String, mail: String, language: String, payload: Object, }); export const messageSchema = new mongoose.Schema({ platform: String, template: String, sender: { name: String, mail: String, }, payload: [ { language: String, payload: Object, }, ], receivers: [ userRessourceSchema ], trackLinks: Boolean, }); const messageModel: mongoose.Model<IMessageModel> = mongoose.model('Message', messageSchema); export default messageModel;
Undo unwanted change in MessageModel
Undo unwanted change in MessageModel
TypeScript
mit
schulcloud/node-notification-service,schulcloud/node-notification-service,schulcloud/node-notification-service
--- +++ @@ -1,8 +1,15 @@ import mongoose from 'mongoose'; import Message from '@/interfaces/Message'; +export interface IUserRessourceModel extends mongoose.Types.Subdocument { + name: string, + mail: string, + language: string, + payload: any, +}; + export interface IMessageModel extends Message, mongoose.Document { - _receivers: mongoose.Types.DocumentArray<mongoose.Types.Subdocument>; + _receivers: mongoose.Types.DocumentArray<IUserRessourceModel>; } export const userRessourceSchema = new mongoose.Schema({
ab9286c5885bbf298384ff82ad392a3474899a63
game/hud/src/gql/fragments/WeaponStatsFragment.ts
game/hud/src/gql/fragments/WeaponStatsFragment.ts
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import gql from 'graphql-tag'; export const WeaponStatsFragment = gql` fragment WeaponStats on WeaponStat_Single { piercingDamage piercingBleed piercingArmorPenetration slashingDamage slashingBleed slashingArmorPenetration crushingDamage fallbackCrushingDamage disruption deflectionAmount physicalProjectileSpeed knockbackAmount stability falloffMinDistance falloffMaxDistance falloffReduction deflectionRecovery staminaCost physicalPreparationTime physicalRecoveryTime range } `;
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import gql from 'graphql-tag'; export const WeaponStatsFragment = gql` fragment WeaponStats on WeaponStat_Single { piercingDamage piercingBleed piercingArmorPenetration slashingDamage slashingBleed slashingArmorPenetration crushingDamage fallbackCrushingDamage magicPower disruption deflectionAmount physicalProjectileSpeed knockbackAmount stability falloffMinDistance falloffMaxDistance falloffReduction deflectionRecovery staminaCost physicalPreparationTime physicalRecoveryTime range } `;
Add magicPower to WeaponStats fragment
Add magicPower to WeaponStats fragment
TypeScript
mpl-2.0
Mehuge/Camelot-Unchained,CUModSquad/Camelot-Unchained,Mehuge/Camelot-Unchained,csegames/Camelot-Unchained,csegames/Camelot-Unchained,Mehuge/Camelot-Unchained,csegames/Camelot-Unchained,CUModSquad/Camelot-Unchained,CUModSquad/Camelot-Unchained
--- +++ @@ -16,6 +16,7 @@ slashingArmorPenetration crushingDamage fallbackCrushingDamage + magicPower disruption deflectionAmount physicalProjectileSpeed
1e02cd5c638337697d2e28ce75526c050939351a
tools/utils/seed/server.ts
tools/utils/seed/server.ts
import * as express from 'express'; import * as openResource from 'open'; import * as serveStatic from 'serve-static'; import * as codeChangeTool from './code_change_tools'; import {resolve} from 'path'; import {APP_BASE, DOCS_DEST, DOCS_PORT, COVERAGE_PORT} from '../../config'; export function serveSPA() { codeChangeTool.listen(); } export function serveDocs() { let server = express(); server.use( APP_BASE, serveStatic(resolve(process.cwd(), DOCS_DEST)) ); server.listen(DOCS_PORT, () => openResource('http://localhost:' + DOCS_PORT + APP_BASE) ); } export function serveCoverage() { let server = express(); server.use( APP_BASE, serveStatic(resolve(process.cwd(), 'coverage')) ); server.listen(COVERAGE_PORT, () => openResource('http://localhost:' + COVERAGE_PORT + APP_BASE) ); }
import * as express from 'express'; import * as openResource from 'open'; import * as serveStatic from 'serve-static'; import * as codeChangeTool from './code_change_tools'; import {resolve} from 'path'; import {APP_BASE, DOCS_DEST, DOCS_PORT, COVERAGE_PORT} from '../../config'; export function serveSPA() { codeChangeTool.listen(); } export function notifyLiveReload(e:any) { let fileName = e.path; codeChangeTool.changed(fileName); } export function serveDocs() { let server = express(); server.use( APP_BASE, serveStatic(resolve(process.cwd(), DOCS_DEST)) ); server.listen(DOCS_PORT, () => openResource('http://localhost:' + DOCS_PORT + APP_BASE) ); } export function serveCoverage() { let server = express(); server.use( APP_BASE, serveStatic(resolve(process.cwd(), 'coverage')) ); server.listen(COVERAGE_PORT, () => openResource('http://localhost:' + COVERAGE_PORT + APP_BASE) ); }
Add function to notify browser-sync
fix(build): Add function to notify browser-sync
TypeScript
mit
osulp/oe-ng2-seed,arun-awnics/mesomeds-ng2,idrabenia/angular2-crud,nickaranz/robinhood-ui,jigarpt/angular-seed-semi,idready/Bloody-Prophety-NG2,AnnaCasper/finance-tool,DallasAngularSuperHeroes/dash-ng2,Aurimas-Norkus/angular2-seed-arch,nlopezcenteno/angular2-seed,booleanVirus/POC,mraible/angular2-tutorial,natarajanmca11/angular2-seed,shaggyshelar/Linkup,maniche04/ngIntranet,vyakymenko/angular-seed-express,davidstellini/bvl-pay,adobley/angular2-tdd-workshop,liuy97/angular2-material-seed,davewragg/agot-spa,mraible/angular2-tutorial,tiagomapmarques/angular-examples_books,miltador/unichat,tobiaseisenschenk/data-cube,TOKOFE/team-todo,Aurimas-Norkus/angular2-seed-arch,christophersanson/js-demo-fe,chnoumis/angular2-seed-advanced,lfarran/angular2-seed-advanced,jacerider/angle-seed,guilhebl/offer-web,vyakymenko/angular-seed-express,CNSKnight/ng2-CNSKalc,m-abs/angular2-seed-advanced,origamyllc/Mangular,rtang03/fabric-seed,millea1/tips1,billsworld/angular2-seed,AngularShowcase/angular2-seed-ng2-highcharts,vyakymenko/angular-seed-express,millea1/tips1,idready/Philosophers,idready/Bloody-Prophety-NG2,shaggyshelar/Linkup,JohnCashmore/angular2-seed,hoangnguyenba/chat-app,dspies/boot-angular2-seed,miltador/unichat,zertyz/observatorio-SUAS,suigezi/angular2-seed,ManasviA/Dashboard,GeoscienceAustralia/gnss-site-manager,pskaarup/marge,CNSKnight/angular2-seed-advanced,miltador/unichat,deanQj/angular2-seed-bric,prabhatsharma/bwa2,millea1/tips1,fr-esco/angular-seed,CNSKnight/angular2-seed-advanced,vip32/eventfeedback,ilvestoomas/angular-seed-advanced,larsnolden/MLB,NathanWalker/angular2-seed-advanced,sanastasiadis/angular-seed-openlayers,ppanthony/angular-seed-tutorial,zertyz/observatorio-SUAS,radiorabe/raar-ui,BlackMr/angular2seed2new,ppanthony/angular-seed-tutorial,smartnosemm/angular2-seed-express,davewragg/agot-spa,AngularShowcase/angular2-seed-ng2-highcharts,natarajanmca11/angular2-seed,hoangnguyenba/chat-app,OlivierVoyer/angular-seed-advanced,lhoezee/faithreg1,MgCoders/angular-seed,dspies/boot-angular2-seed,natarajanmca11/angular2-seed,pieczkus/whyblogfront,Shyiy/angular-seed,origamyllc/Mangular,fredrikbergqvist/ng2.bergqvist.it,larsnolden/MLB,nie-ine/raeber-website,Spencer-Lewis/BandBoard2,mgechev/angular2-seed,CordanoCorey/growtell,AnnaCasper/finance-tool,jelgar1/fpl-api,fart-one/monitor-ngx,Nightapes/angular2-seed,sylviefiat/bdmer3,mgechev/angular2-seed,rtang03/fabric-seed,llwt/angular-seed-advanced,trutoo/startatalk-native,oblong-antelope/oblong-web,pratheekhegde/a2-redux,JohnnyQQQQ/angular-seed-material2,ilvestoomas/angular-seed-advanced,Sn3b/angular-seed-advanced,tobiaseisenschenk/data-cube,dmitriyse/angular2-seed,Bigous/angular2-seed-ng2-highcharts,billsworld/angular2-seed,JohnCashmore/angular2-seed,talentspear/a2-redux,christophersanson/js-demo-fe,ronikurnia1/ClientApp,AWNICS/mesomeds-ng2,CNSKnight/ng2-CNSKalc,mgechev/angular2-seed,felipecamargo/ACSC-SBPL-M,lhoezee/faithreg1,jelgar1/fpl-api,sylviefiat/bdmer3,pratheekhegde/a2-redux,Jimmysh/angular2-seed-advanced,wenzelj/nativescript-angular,idready/Philosophers,tarlepp/angular2-seed,zertyz/angular-seed-advanced-spikes,ilvestoomas/angular-seed-advanced,trevordaniels/ang2seed-advanced,chnoumis/angular2-seed-advanced,deanQj/angular2-seed-bric,mattk25/Apologetics,Bigous/angular2-seed-ng2-highcharts,JohnnyQQQQ/angular-seed-material2,fredrikbergqvist/ng2.bergqvist.it,BlackMr/angular2seed2new,hookom/climbontheway,wenzelj/nativescript-angular,hoangnguyenba/chatapp,billsworld/angular2-seed,shaggyshelar/Linkup,zertyz/edificando-o-controle-interno,pieczkus/whyblogfront,vip32/eventfeedback,felipecamargo/ACSC-SBPL-M,lhoezee/faithreg1,vip32/eventfeedback,booleanVirus/POC,ronikurnia1/ClientApp,jacerider/angle-seed,nie-ine/raeber-website,radiorabe/raar-ui,trevordaniels/ang2seed-advanced,davidstellini/bvl-pay,sanastasiadis/angular-seed-openlayers,AWNICS/mesomeds-ng2,radiorabe/raar-ui,alexmanning23/uafl-web,osulp/oe-ng2-seed,JohnnyQQQQ/md-dashboard,lfarran/angular2-seed-advanced,zertyz/angular2-seed-advanced-spikes2,vip32/eventfeedback,JLou/JandelouFront,llwt/angular-seed-advanced,BlackMr/angular2seed2new,ManasviA/Dashboard,euangoddard/name-that-cheese,rvanmarkus/studio-eve,euangoddard/name-that-cheese,OlivierVoyer/angular-seed-advanced,nickaranz/robinhood-ui,fart-one/monitor-ngx,NathanWalker/angular-seed-advanced,NathanWalker/angular-seed-advanced,rvanmarkus/studio-eve,GeoscienceAustralia/gnss-site-manager,zertyz/angular2-seed-advanced-spikes2,rawnics/mesomeds-ng2,idready/Philosophers,lfarran/angular2-seed-advanced,fart-one/monitor-ngx,sylviefiat/bdmer3,ghsyeung/ng2-component-intro,alantreadway/homedash,zertyz/angular2-seed-advanced-spikes2,AnnaCasper/finance-tool,watonyweng/angular-seed,prabhatsharma/bwa2,nie-ine/raeber-website,lilia-simeonova/project-estimations,tiagomapmarques/angular-examples_books,pratheekhegde/a2-redux,booleanVirus/POC,zertyz/edificando-o-controle-interno,Sn3b/angular-seed-advanced,mattk25/Apologetics,hookom/climbontheway,zertyz/observatorio-SUAS,JLou/JandelouFront,zertyz/angular-seed-advanced-spikes,mraible/angular2-tutorial,tarlepp/angular2-seed,origamyllc/Mangular,zertyz/observatorio-SUAS-formularios,Karasuni/angular-seed,ysyun/angular-seed-stub-api-environment,DallasAngularSuperHeroes/dash-ng2,CordanoCorey/growtell,radiorabe/raar-ui,ManasviA/Dashboard,nlopezcenteno/angular2-seed,zertyz/observatorio-SUAS-formularios,idrabenia/angular2-crud,larsnolden/MLB,wenzelj/nativescript-angular,dmitriyse/angular2-seed,ghsyeung/ng2-component-intro,dspies/boot-angular2-seed,Nightapes/angular2-seed,nlopezcenteno/angular2-seed,Spencer-Lewis/BandBoard2,guilhebl/offer-web,davidstellini/bvl-pay,ManasviA/Dashboard,NathanWalker/angular-seed-advanced,pskaarup/marge,mgechev/angular-seed,trutoo/startatalk-native,alantreadway/homedash,zertyz/observatorio-SUAS,pocmanu/angular2-seed-advanced,GeoscienceAustralia/gnss-site-manager,jelgar1/fpl-api,rvanmarkus/studio-eve,Aurimas-Norkus/angular2-seed-arch,jasonlevinsohn/jarvis-dashboard,alexmanning23/uafl-web,NathanWalker/angular2-seed-advanced,jigarpt/angular-seed-semi,liuy97/angular2-material-seed,pocmanu/angular2-seed-advanced,suigezi/angular2-seed,adobley/angular2-tdd-workshop,ysyun/angular-seed-stub-api-environment,Shyiy/angular-seed,oblong-antelope/oblong-web,JohnnyQQQQ/angular-seed-material2,nie-ine/raeber-website,arun-awnics/mesomeds-ng2,dspies/boot-angular2-seed,abhibly/Angular2-Seed-Project,suigezi/angular2-seed,Karasuni/angular-seed,Spencer-Lewis/BandBoard2,OlivierVoyer/angular-seed-advanced,CNSKnight/ng2-CNSKalc,rvanmarkus/studio-eve,nickaranz/robinhood-ui,alexmanning23/uafl-web,ronikurnia1/ClientApp,abhibly/Angular2-Seed-Project,jigarpt/angular-seed-semi,idrabenia/angular2-crud,MgCoders/angular-seed,fr-esco/angular-seed,alantreadway/homedash,OlivierVoyer/angular-seed-advanced,hoangnguyenba/chatapp,JohnnyQQQQ/md-dashboard,tiagomapmarques/angular-examples_books,osulp/oe-ng2-seed,maniche04/ngIntranet,mgechev/angular-seed,AWNICS/mesomeds-ng2,talentspear/a2-redux,smartnosemm/angular2-seed-express,fredrikbergqvist/ng2.bergqvist.it,hookom/climbontheway,CNSKnight/angular2-seed-advanced,liuy97/angular2-material-seed,sanastasiadis/angular-seed-openlayers,arun-awnics/mesomeds-ng2,prabhatsharma/bwa2,rtang03/fabric-seed,idready/Bloody-Prophety-NG2,m-abs/angular2-seed-advanced,deanQj/angular2-seed-bric,trutoo/startatalk-native,Bigous/angular2-seed-ng2-highcharts,TOKOFE/team-todo,lilia-simeonova/project-estimations,pocmanu/angular2-seed-advanced,ppanthony/angular-seed-tutorial,Sn3b/angular-seed-advanced,llwt/angular-seed-advanced,tctc91/angular2-wordpress-portfolio,guilhebl/offer-web,Karasuni/angular-seed,TOKOFE/team-todo,rtang03/fabric-seed,dmitriyse/angular2-seed,oblong-antelope/oblong-web,davewragg/agot-spa,hookom/climbontheway,talentspear/a2-redux,maniche04/ngIntranet,rawnics/mesomeds-ng2,fr-esco/angular-seed,m-abs/angular2-seed-advanced,Shyiy/angular-seed,felipecamargo/ACSC-SBPL-M,rtang03/fabric-seed,CordanoCorey/growtell,MgCoders/angular-seed,mattk25/Apologetics,jacerider/angle-seed,tobiaseisenschenk/data-cube,christophersanson/js-demo-fe,Nightapes/angular2-seed,NathanWalker/angular2-seed-advanced,lilia-simeonova/project-estimations,rawnics/mesomeds-ng2,jasonlevinsohn/jarvis-dashboard,ysyun/angular-seed-stub-api-environment,JLou/JandelouFront,zertyz/observatorio-SUAS-formularios,ysyun/angular-seed-stub-api-environment,zertyz/edificando-o-controle-interno,Jimmysh/angular2-seed-advanced,abhibly/Angular2-Seed-Project,adobley/angular2-tdd-workshop,pskaarup/marge,JohnnyQQQQ/md-dashboard,smartnosemm/angular2-seed-express,dmitriyse/angular2-seed,tctc91/angular2-wordpress-portfolio,hoangnguyenba/chatapp,pieczkus/whyblogfront,chnoumis/angular2-seed-advanced,AngularShowcase/angular2-seed-ng2-highcharts,zertyz/angular-seed-advanced-spikes,hoangnguyenba/chat-app,JohnCashmore/angular2-seed,MgCoders/angular-seed,tctc91/angular2-wordpress-portfolio,adobley/angular2-tdd-workshop,tarlepp/angular2-seed,jasonlevinsohn/jarvis-dashboard,DallasAngularSuperHeroes/dash-ng2,mgechev/angular-seed,trevordaniels/ang2seed-advanced,watonyweng/angular-seed,Jimmysh/angular2-seed-advanced,ghsyeung/ng2-component-intro,euangoddard/name-that-cheese
--- +++ @@ -7,6 +7,11 @@ export function serveSPA() { codeChangeTool.listen(); +} + +export function notifyLiveReload(e:any) { + let fileName = e.path; + codeChangeTool.changed(fileName); } export function serveDocs() {
49bd1778b60e5331a744588b6548856f98f5e651
src/app/app.component.ts
src/app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', // styleUrls: ['./app.component.css'] styles: [`h3 {color: lightseagreen;}`] }) export class AppComponent { }
import {Component, ViewEncapsulation} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', // styleUrls: ['./app.component.css'] styles: [`h3 {color: lightseagreen;}`], encapsulation: ViewEncapsulation.Emulated // Native, None }) export class AppComponent { }
Add View Encapsulation property to App Component (l62)
Add View Encapsulation property to App Component (l62)
TypeScript
mit
topvova/angular-app,topvova/angular-app,topvova/angular-app
--- +++ @@ -1,10 +1,12 @@ -import { Component } from '@angular/core'; +import {Component, ViewEncapsulation} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', // styleUrls: ['./app.component.css'] - styles: [`h3 {color: lightseagreen;}`] + styles: [`h3 {color: lightseagreen;}`], + encapsulation: ViewEncapsulation.Emulated // Native, None + }) export class AppComponent { }
e204d51c3a76559d93e99c1f2e2bd9a4a0cb328f
csComp/directives/LayersList/LayersDirectiveCtrl.ts
csComp/directives/LayersList/LayersDirectiveCtrl.ts
module LayersDirective { export interface ILayersDirectiveScope extends ng.IScope { vm: LayersDirectiveCtrl; } export class LayersDirectiveCtrl { private scope: ILayersDirectiveScope; // $inject annotation. // It provides $injector with information about dependencies to be injected into constructor // it is better to have it close to the constructor, because the parameters must match in count and type. // See http://docs.angularjs.org/guide/di public static $inject = [ '$scope', 'layerService' ]; // dependencies are injected via AngularJS $injector // controller's name is registered in Application.ts and specified from ng-controller attribute in index.html constructor( private $scope : ILayersDirectiveScope, private $layerService: csComp.Services.LayerService ) { $scope.vm = this; } public toggleLayer(layer: csComp.Services.ProjectLayer): void { layer.enabled = !layer.enabled; if (layer.enabled) { this.$layerService.addLayer(layer); } else { this.$layerService.removeLayer(layer); } // NOTE EV: You need to call apply only when an event is received outside the angular scope. // However, make sure you are not calling this inside an angular apply cycle, as it will generate an error. if (this.$scope.$root.$$phase != '$apply' && this.$scope.$root.$$phase != '$digest') { this.$scope.$apply(); } } } }
module LayersDirective { export interface ILayersDirectiveScope extends ng.IScope { vm: LayersDirectiveCtrl; } export class LayersDirectiveCtrl { private scope: ILayersDirectiveScope; // $inject annotation. // It provides $injector with information about dependencies to be injected into constructor // it is better to have it close to the constructor, because the parameters must match in count and type. // See http://docs.angularjs.org/guide/di public static $inject = [ '$scope', 'layerService' ]; // dependencies are injected via AngularJS $injector // controller's name is registered in Application.ts and specified from ng-controller attribute in index.html constructor( private $scope : ILayersDirectiveScope, private $layerService: csComp.Services.LayerService ) { $scope.vm = this; } public toggleLayer(layer: csComp.Services.ProjectLayer): void { //layer.enabled = !layer.enabled; if (layer.enabled) { this.$layerService.addLayer(layer); } else { this.$layerService.removeLayer(layer); } // NOTE EV: You need to call apply only when an event is received outside the angular scope. // However, make sure you are not calling this inside an angular apply cycle, as it will generate an error. if (this.$scope.$root.$$phase != '$apply' && this.$scope.$root.$$phase != '$digest') { this.$scope.$apply(); } } } }
FIX Layers would no longer load.
FIX Layers would no longer load.
TypeScript
mit
rinzeb/csWeb,mkuzak/csWeb,c-martinez/csWeb,indodutch/csWeb,c-martinez/csWeb,c-martinez/csWeb,mkuzak/csWeb,TNOCS/csWeb,TNOCS/csWeb,Maartenvm/csWeb,Maartenvm/csWeb,rinzeb/csWeb,TNOCS/csWeb,rinzeb/csWeb,indodutch/csWeb,mkuzak/csWeb,indodutch/csWeb,Maartenvm/csWeb,mkuzak/csWeb,Maartenvm/csWeb
--- +++ @@ -25,7 +25,7 @@ } public toggleLayer(layer: csComp.Services.ProjectLayer): void { - layer.enabled = !layer.enabled; + //layer.enabled = !layer.enabled; if (layer.enabled) { this.$layerService.addLayer(layer); } else {
88ba78fda736fe08429948522b823e12994f8ecb
src/dart_indent_fixer.ts
src/dart_indent_fixer.ts
"use strict"; import * as vs from "vscode"; import { config } from "./config"; export class DartIndentFixer { onDidChangeActiveTextEditor(editor: vs.TextEditor) { if (editor && editor.document.languageId === "dart" && config.setIndentation) { editor.options = { insertSpaces: true, tabSize: 2 }; } } }
"use strict"; import * as vs from "vscode"; import * as path from "path"; import { config } from "./config"; export class DartIndentFixer { onDidChangeActiveTextEditor(editor: vs.TextEditor) { if (!(editor && editor.document)) return; let isDart = editor.document.languageId === "dart"; let isPubspec = editor.document.languageId === "yaml" && path.basename(editor.document.fileName).toLowerCase() == "pubspec.yaml"; if (config.setIndentation && (isDart || isPubspec)) { editor.options = { insertSpaces: true, tabSize: 2 }; } } }
Apply 2-space indents to pubspec.yaml too.
Apply 2-space indents to pubspec.yaml too. Fixes #140.
TypeScript
mit
Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code
--- +++ @@ -1,11 +1,17 @@ "use strict"; import * as vs from "vscode"; +import * as path from "path"; import { config } from "./config"; export class DartIndentFixer { onDidChangeActiveTextEditor(editor: vs.TextEditor) { - if (editor && editor.document.languageId === "dart" && config.setIndentation) { + if (!(editor && editor.document)) + return; + + let isDart = editor.document.languageId === "dart"; + let isPubspec = editor.document.languageId === "yaml" && path.basename(editor.document.fileName).toLowerCase() == "pubspec.yaml"; + if (config.setIndentation && (isDart || isPubspec)) { editor.options = { insertSpaces: true, tabSize: 2
f18a8787adf25e16ae1e37617a760ea4093196d9
app/app.component.ts
app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<h1>{{title}}</h1><h2>{{hero.name}} details!</h2><div><label>id: </label>{{hero.id}}</div><div><label>name: </label>{{hero.name}}</div>' }) export class AppComponent { title = 'Tour of Heroes'; hero: Hero = { id: 10000, name: 'Windstorm' }; } export class Hero { id: number; name: string; }
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: <h1>{{title}}</h1> <h2>{{hero.name}} details!</h2> <div><label>id: </label>{{hero.id}}</div> <div><label>name: </label>{{hero.name}}</div> }) export class AppComponent { title = 'Tour of Heroes'; hero: Hero = { id: 10000, name: 'Windstorm' }; } export class Hero { id: number; name: string; }
Change template to multi-line. Should not change UI
Change template to multi-line. Should not change UI
TypeScript
mit
atbtm/Angular2-Pull-Repo,atbtm/Angular2-Pull-Repo,atbtm/Angular2-Pull-Repo
--- +++ @@ -2,7 +2,11 @@ @Component({ selector: 'my-app', - template: '<h1>{{title}}</h1><h2>{{hero.name}} details!</h2><div><label>id: </label>{{hero.id}}</div><div><label>name: </label>{{hero.name}}</div>' + template: + <h1>{{title}}</h1> + <h2>{{hero.name}} details!</h2> + <div><label>id: </label>{{hero.id}}</div> + <div><label>name: </label>{{hero.name}}</div> }) export class AppComponent { title = 'Tour of Heroes';
3e3144eed8aab6476eefb5c8a38a451279f10fa6
app/main/index.ts
app/main/index.ts
import * as path from "path"; import * as url from "url"; // tslint:disable-next-line no-implicit-dependencies import { app } from "electron"; import * as fs from "fs-extra"; import ActionHubWindow from "./ActionHubWindow"; import { configDirPath, configName } from "./defaults"; fs.emptyDirSync(configDirPath); const window = new ActionHubWindow(app, path.join(configDirPath, configName)); app.on("ready", () => { window.initializeWindow(); if (process.env.NODE_ENV === "development") { window.debug(); } window.window.loadURL( url.format( process.env.HOT ? { hostname: "localhost", port: process.env.PORT || 8080, protocol: "http" } : { pathname: path.join(__dirname, "index.html"), protocol: "file:", slashes: true } ) ); }); app.on("window-all-closed", () => { app.quit(); });
import * as path from "path"; import * as url from "url"; // tslint:disable-next-line no-implicit-dependencies import { app } from "electron"; import * as fs from "fs-extra"; import ActionHubWindow from "./ActionHubWindow"; import { configDirPath, configName } from "./defaults"; fs.ensureDirSync(configDirPath); const window = new ActionHubWindow(app, path.join(configDirPath, configName)); app.on("ready", () => { window.initializeWindow(); if (process.env.NODE_ENV === "development") { window.debug(); } window.window.loadURL( url.format( process.env.HOT ? { hostname: "localhost", port: process.env.PORT || 8080, protocol: "http" } : { pathname: path.join(__dirname, "index.html"), protocol: "file:", slashes: true } ) ); }); app.on("window-all-closed", () => { app.quit(); });
Fix typo emptyDirSync to ensureDirSync
Fix typo emptyDirSync to ensureDirSync
TypeScript
mit
ocboogie/action-hub,ocboogie/action-hub,ocboogie/action-hub
--- +++ @@ -8,7 +8,7 @@ import ActionHubWindow from "./ActionHubWindow"; import { configDirPath, configName } from "./defaults"; -fs.emptyDirSync(configDirPath); +fs.ensureDirSync(configDirPath); const window = new ActionHubWindow(app, path.join(configDirPath, configName)); app.on("ready", () => {
cf55a5d2f904588f205ac012e57142d800873966
src/app/journal/journal.component.spec.ts
src/app/journal/journal.component.spec.ts
import { JournalComponent } from './journal.component'; import { AnalysisService } from '../analysis/service/analysis.service'; import {DateChooserService} from '../shared/date-chooser.service'; describe('JournalComponent', () => { let component: JournalComponent; let analysisService: AnalysisService; let dateChooserService: DateChooserService; beforeEach(() => { component = new JournalComponent(analysisService, dateChooserService); }); it('should create JournalComponent', () => { expect(component).toBeTruthy(); }); });
import { JournalComponent } from './journal.component'; import { Observable } from 'rxjs'; import { ConsumptionReport } from '../analysis/model/consumptionReport'; class DateChooserServiceStub { getChosenDateAsObservable(): Observable<Date> { return Observable.of(new Date()); } } class AnalysisServiceStub { initConsumptionAnalysis() { } getConsumptionReport() { return Observable.of(new ConsumptionReport()); } } describe('JournalComponent', () => { let component: JournalComponent; let analysisService: any = new AnalysisServiceStub(); let dateChooserService: any = new DateChooserServiceStub(); beforeEach(() => { component = new JournalComponent(analysisService, dateChooserService); component.ngOnInit(); }); it('should create JournalComponent', () => { expect(component).toBeTruthy(); }); it('should switch new hint available', () => { expect(component.newHintAvailable).toBeTruthy(); component.showNewHint(); expect(component.newHintAvailable).toBeFalsy(); }); it('should change coach visibility', () => { expect(component.mobCoachVisible).toBeFalsy(); component.mobCoachVisibility(); expect(component.mobCoachVisible).toBeTruthy(); }); });
Write tests for the journal component
Write tests for the journal component
TypeScript
mit
stefanamport/nuba,stefanamport/nuba,stefanamport/nuba
--- +++ @@ -1,17 +1,48 @@ import { JournalComponent } from './journal.component'; -import { AnalysisService } from '../analysis/service/analysis.service'; -import {DateChooserService} from '../shared/date-chooser.service'; +import { Observable } from 'rxjs'; +import { ConsumptionReport } from '../analysis/model/consumptionReport'; + +class DateChooserServiceStub { + getChosenDateAsObservable(): Observable<Date> { + return Observable.of(new Date()); + } +} + +class AnalysisServiceStub { + initConsumptionAnalysis() { } + + getConsumptionReport() { + return Observable.of(new ConsumptionReport()); + } +} describe('JournalComponent', () => { let component: JournalComponent; - let analysisService: AnalysisService; - let dateChooserService: DateChooserService; + let analysisService: any = new AnalysisServiceStub(); + let dateChooserService: any = new DateChooserServiceStub(); beforeEach(() => { component = new JournalComponent(analysisService, dateChooserService); + component.ngOnInit(); }); it('should create JournalComponent', () => { expect(component).toBeTruthy(); }); + + it('should switch new hint available', () => { + expect(component.newHintAvailable).toBeTruthy(); + + component.showNewHint(); + + expect(component.newHintAvailable).toBeFalsy(); + }); + + it('should change coach visibility', () => { + expect(component.mobCoachVisible).toBeFalsy(); + + component.mobCoachVisibility(); + + expect(component.mobCoachVisible).toBeTruthy(); + }); });
1e8f0e281c9d3762e3e22a555496b418605160b7
src/app/game/join-form/game-join-form.spec.ts
src/app/game/join-form/game-join-form.spec.ts
import { GameJoinFormComponent } from './game-join-form.component'; import {TestComponentBuilder, addProviders, inject, async, ComponentFixture} from '@angular/core/testing'; import { Router } from '@angular/router'; class MockRouter {} describe('join-form game component', () => { let builder; beforeEach(() => { addProviders([ { provide: Router, useClass: MockRouter } ]); }); beforeEach(inject([TestComponentBuilder], (tcb) => { builder = tcb; })); // @TODO: come back to this once async tests work better /*it('should render join-form game form', async(() => { builder.createAsync(GameJoinFormComponent) .then((fixture: ComponentFixture<GameJoinFormComponent>) => { fixture.detectChanges(); let compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('input[name="gameCode"]').length).toBeGreaterThan(0); }); }));*/ });
/* tslint:disable:no-unused-variable */ import { addProviders, async, inject } from '@angular/core/testing'; import { GameJoinFormComponent } from './game-join-form.component'; import { Router } from '@angular/router'; class MockRouter {} describe('GameJoinFormComponent: Testing', () => { beforeEach(() => { addProviders( [ { provide: Router, useClass: MockRouter }, GameJoinFormComponent ] ); }); it('should create the join game form component', inject([GameJoinFormComponent], (component: GameJoinFormComponent) => { expect(component).toBeTruthy(); })); });
Add a test for the join game form component
Add a test for the join game form component
TypeScript
mit
s-robertson/things-angular,s-robertson/things-angular,s-robertson/things-angular,s-robertson/things-angular
--- +++ @@ -1,33 +1,23 @@ +/* tslint:disable:no-unused-variable */ + +import { addProviders, async, inject } from '@angular/core/testing'; import { GameJoinFormComponent } from './game-join-form.component'; -import {TestComponentBuilder, - addProviders, - inject, - async, - ComponentFixture} from '@angular/core/testing'; import { Router } from '@angular/router'; class MockRouter {} -describe('join-form game component', () => { - let builder; - +describe('GameJoinFormComponent: Testing', () => { beforeEach(() => { - addProviders([ - { provide: Router, useClass: MockRouter } - ]); + addProviders( + [ + { provide: Router, useClass: MockRouter }, + GameJoinFormComponent + ] + ); }); - beforeEach(inject([TestComponentBuilder], (tcb) => { - builder = tcb; - })); - - // @TODO: come back to this once async tests work better - /*it('should render join-form game form', async(() => { - builder.createAsync(GameJoinFormComponent) - .then((fixture: ComponentFixture<GameJoinFormComponent>) => { - fixture.detectChanges(); - let compiled = fixture.debugElement.nativeElement; - expect(compiled.querySelector('input[name="gameCode"]').length).toBeGreaterThan(0); - }); - }));*/ + it('should create the join game form component', + inject([GameJoinFormComponent], (component: GameJoinFormComponent) => { + expect(component).toBeTruthy(); + })); });
be2513b266e5bdeddb384d975eac98f5e3135d0a
tests/runners/runnerfactory.ts
tests/runners/runnerfactory.ts
///<reference path="runnerbase.ts" /> ///<reference path="compiler/runner.ts" /> ///<reference path="fourslash/fsrunner.ts" /> ///<reference path="projects/runner.ts" /> ///<reference path="unittest/unittestrunner.ts" /> class RunnerFactory { private runners = {}; public addTest(name: string) { if (/tests\\cases\\compiler/.test(name)) { this.runners['compiler'] = this.runners['compiler'] || new CompilerBaselineRunner(); this.runners['compiler'].addTest(Harness.userSpecifiedroot + name); } else if (/tests\\cases\\fourslash/.test(name)) { this.runners['fourslash'] = this.runners['fourslash'] || new FourslashRunner(); this.runners['fourslash'].addTest(Harness.userSpecifiedroot + name); } else { this.runners['unitTestRunner'] = this.runners['unitTestRunner'] || new UnitTestRunner(); this.runners['unitTestRunner'].addTest(Harness.userSpecifiedroot + name); } } public getRunners() { var runners = []; for (var p in this.runners) { runners.push(this.runners[p]); } return runners; } }
///<reference path="runnerbase.ts" /> ///<reference path="compiler/runner.ts" /> ///<reference path="fourslash/fsrunner.ts" /> ///<reference path="projects/runner.ts" /> ///<reference path="unittest/unittestrunner.ts" /> class RunnerFactory { private runners = {}; public addTest(name: string) { var normalizedName = name.replace(/\\/g, "/"); // normalize slashes so either kind can be used on the command line if (/tests\/cases\/compiler/.test(normalizedName)) { this.runners['compiler'] = this.runners['compiler'] || new CompilerBaselineRunner(); this.runners['compiler'].addTest(Harness.userSpecifiedroot + name); } else if (/tests\/cases\/fourslash/.test(normalizedName)) { this.runners['fourslash'] = this.runners['fourslash'] || new FourslashRunner(); this.runners['fourslash'].addTest(Harness.userSpecifiedroot + name); } else { this.runners['unitTestRunner'] = this.runners['unitTestRunner'] || new UnitTestRunner(); this.runners['unitTestRunner'].addTest(Harness.userSpecifiedroot + name); } } public getRunners() { var runners = []; for (var p in this.runners) { runners.push(this.runners[p]); } return runners; } }
Allow either slash type to be used in command line to harness
Allow either slash type to be used in command line to harness
TypeScript
apache-2.0
fdecampredon/jsx-typescript-old-version,popravich/typescript,tarruda/typescript,guidobouman/typescript,mbebenita/shumway.ts,mbrowne/typescript-dci,mbrowne/typescript-dci,mbebenita/shumway.ts,popravich/typescript,popravich/typescript,mbrowne/typescript-dci,hippich/typescript,rbirkby/typescript,vcsjones/typescript,fdecampredon/jsx-typescript-old-version,tarruda/typescript,tarruda/typescript,fdecampredon/jsx-typescript-old-version,hippich/typescript,guidobouman/typescript,rbirkby/typescript,hippich/typescript,rbirkby/typescript,mbebenita/shumway.ts,guidobouman/typescript,mbrowne/typescript-dci
--- +++ @@ -8,11 +8,12 @@ private runners = {}; public addTest(name: string) { - if (/tests\\cases\\compiler/.test(name)) { + var normalizedName = name.replace(/\\/g, "/"); // normalize slashes so either kind can be used on the command line + if (/tests\/cases\/compiler/.test(normalizedName)) { this.runners['compiler'] = this.runners['compiler'] || new CompilerBaselineRunner(); this.runners['compiler'].addTest(Harness.userSpecifiedroot + name); } - else if (/tests\\cases\\fourslash/.test(name)) { + else if (/tests\/cases\/fourslash/.test(normalizedName)) { this.runners['fourslash'] = this.runners['fourslash'] || new FourslashRunner(); this.runners['fourslash'].addTest(Harness.userSpecifiedroot + name); } else {
c2cc79fab0d07597e835dc6399d44596ce4021bf
source/danger/peril_platform.ts
source/danger/peril_platform.ts
import { GitHub } from "danger/distribution/platforms/GitHub" import { Platform } from "danger/distribution/platforms/platform" import { dsl } from "./danger_run" const getPerilPlatformForDSL = (type: dsl, github: GitHub | null, githubEvent: any): Platform => { if (type === dsl.pr && github) { return github } else { const nullFunc: any = () => "" const platform: Platform = { createComment: github ? github.createComment : nullFunc, deleteMainComment: github ? github.deleteMainComment : nullFunc, editMainComment: github ? github.editMainComment : nullFunc, getPlatformDSLRepresentation: async () => { return githubEvent }, getPlatformGitRepresentation: async () => { return {} as any }, name: "", updateOrCreateComment: github!.updateOrCreateComment, } return platform } } export default getPerilPlatformForDSL
import { GitHub } from "danger/distribution/platforms/GitHub" import { Platform } from "danger/distribution/platforms/platform" import { dsl } from "./danger_run" const getPerilPlatformForDSL = (type: dsl, github: GitHub | null, githubEvent: any): Platform => { if (type === dsl.pr && github) { return github } else { const nullFunc: any = () => "" const platform: Platform = { createComment: github ? github.createComment : nullFunc, deleteMainComment: github ? github.deleteMainComment : nullFunc, editMainComment: github ? github.editMainComment : nullFunc, getPlatformDSLRepresentation: async () => { return githubEvent }, getPlatformGitRepresentation: async () => { return {} as any }, name: "", updateOrCreateComment: github ? github.updateOrCreateComment : nullFunc, } return platform } } export default getPerilPlatformForDSL
Add a check for the issue
Add a check for the issue
TypeScript
mit
danger/peril,danger/peril,danger/peril,danger/peril,danger/peril
--- +++ @@ -19,7 +19,7 @@ return {} as any }, name: "", - updateOrCreateComment: github!.updateOrCreateComment, + updateOrCreateComment: github ? github.updateOrCreateComment : nullFunc, } return platform }
c230e8d2d6f700ad205acebaf82dc8adba4f0c35
ERClient/src/app/emotion-to-color.pipe.spec.ts
ERClient/src/app/emotion-to-color.pipe.spec.ts
/* tslint:disable:no-unused-variable */ import { TestBed, async } from '@angular/core/testing'; import { EmotionToColorPipe } from './emotion-to-color.pipe'; describe('EmotionToColorPipe', () => { it('create an instance', () => { let pipe = new EmotionToColorPipe(); expect(pipe).toBeTruthy(); }); });
/* tslint:disable:no-unused-variable */ import { TestBed, async } from '@angular/core/testing'; import { EmotionToColorPipe } from './emotion-to-color.pipe'; describe('EmotionToColorPipe', () => { it('create an instance', () => { let pipe = new EmotionToColorPipe(); expect(pipe).toBeTruthy(); }); it('transform a value', () => { let pipe = new EmotionToColorPipe(); expect(pipe.transform('surprise')).toEqual('gold'); }); it('transform an unknown value', () => { let pipe = new EmotionToColorPipe(); expect(pipe.transform('aaa')).toEqual('black'); }); });
Add test cases for EmotiontoColor pipe
Add test cases for EmotiontoColor pipe
TypeScript
apache-2.0
shioyang/EmotionalReader,shioyang/EmotionalReader,shioyang/EmotionalReader
--- +++ @@ -8,4 +8,14 @@ let pipe = new EmotionToColorPipe(); expect(pipe).toBeTruthy(); }); + + it('transform a value', () => { + let pipe = new EmotionToColorPipe(); + expect(pipe.transform('surprise')).toEqual('gold'); + }); + + it('transform an unknown value', () => { + let pipe = new EmotionToColorPipe(); + expect(pipe.transform('aaa')).toEqual('black'); + }); });
0e9a7606c2132c1d4816778df991347f708a5fcc
app/scripts/components/page/Page.tsx
app/scripts/components/page/Page.tsx
import React, { ReactNode } from 'react'; import { connect } from 'react-redux'; import { DefaultState, ThunkDispatchProp } from '../../interfaces'; import Header from './Header'; import Footer from './Footer'; type PageProps = { children: ReactNode; }; type PageStateProps = Pick<DefaultState, 'toast' | 'theme' | 'loading'>; const Page: React.FC<PageProps & PageStateProps & ThunkDispatchProp> = (props) => { React.useEffect(() => { document.body.classList.remove('default', 'midnight'); document.body.classList.add(props.theme); localStorage.setItem('theme', props.theme); }, [props.theme]); return ( <> <Header /> <main>{props.children}</main> <Footer /> {props.loading ? ( <div className="overlay overlay-loading"> <div className="overlay-container shadow"> <div className="pac-man" /> </div> </div> ) : null} {props.toast ? <div className="toast">{props.toast}</div> : null} </> ); }; const mapStateToProps = (state: DefaultState): PageStateProps => ({ toast: state.toast, theme: state.theme, loading: state.loadingOverlay, }); export default connect(mapStateToProps)(Page);
import React, { ReactNode } from 'react'; import { connect } from 'react-redux'; import { useLocation } from 'react-router'; import { DefaultState, ThunkDispatchProp } from '../../interfaces'; import Header from './Header'; import Footer from './Footer'; type PageProps = { children: ReactNode; }; type PageStateProps = Pick<DefaultState, 'toast' | 'theme' | 'loading'>; const Page: React.FC<PageProps & PageStateProps & ThunkDispatchProp> = (props) => { const location = useLocation(); React.useEffect(() => { document.title = `Tomlin - ${location.pathname}`; }); React.useEffect(() => { document.body.classList.remove('default', 'midnight'); document.body.classList.add(props.theme); localStorage.setItem('theme', props.theme); }, [props.theme]); return ( <> <Header /> <main>{props.children}</main> <Footer /> {props.loading ? ( <div className="overlay overlay-loading"> <div className="overlay-container shadow"> <div className="pac-man" /> </div> </div> ) : null} {props.toast ? <div className="toast">{props.toast}</div> : null} </> ); }; const mapStateToProps = (state: DefaultState): PageStateProps => ({ toast: state.toast, theme: state.theme, loading: state.loadingOverlay, }); export default connect(mapStateToProps)(Page);
Update site title with location data
Update site title with location data
TypeScript
mit
benct/tomlin-web,benct/tomlin-web
--- +++ @@ -1,5 +1,6 @@ import React, { ReactNode } from 'react'; import { connect } from 'react-redux'; +import { useLocation } from 'react-router'; import { DefaultState, ThunkDispatchProp } from '../../interfaces'; @@ -12,6 +13,12 @@ type PageStateProps = Pick<DefaultState, 'toast' | 'theme' | 'loading'>; const Page: React.FC<PageProps & PageStateProps & ThunkDispatchProp> = (props) => { + const location = useLocation(); + + React.useEffect(() => { + document.title = `Tomlin - ${location.pathname}`; + }); + React.useEffect(() => { document.body.classList.remove('default', 'midnight'); document.body.classList.add(props.theme);
af0fa718d38ea2ae4e4a11d3bc1de848a4de8161
src/core/LogEvent.ts
src/core/LogEvent.ts
/** * @module core */ /** */ import {LogLevel} from "./LogLevel"; export class LogEvent { /** * Models a logging event. * @constructor * @param {String} _categoryName name of category * @param {LogLevel} _level level of message * @param {Array} _data objects to log * @param _context */ constructor(private _categoryName: string, private _level: LogLevel, private _data: any[], private _context: any) {} private _startTime = new Date(); get startTime(): Date { return this._startTime; } public get categoryName(): string { return this._categoryName; } public get level(): LogLevel { return this._level; } public get formatedLevel(): string { return (this.level.toString() + " ").slice(0, 5); } public get data(): any[] { return this._data; } public get context(): Map<string, any> { return this._context; } public get cluster(): any { return {}; } public get pid() { return this.context.get("pid"); } }
/** * @module core */ /** */ import {LogLevel} from "./LogLevel"; export class LogEvent { /** * Models a logging event. * @constructor * @param {String} _categoryName name of category * @param {LogLevel} _level level of message * @param {Array} _data objects to log * @param _context */ constructor(private _categoryName: string, private _level: LogLevel, private _data: any[], private _context: any) {} private _startTime = new Date(); get startTime(): Date { return this.data && this.data[0] && this.data[0].time ? this.data[0].time : this._startTime; } public get categoryName(): string { return this._categoryName; } public get level(): LogLevel { return this._level; } public get formatedLevel(): string { return (this.level.toString() + " ").slice(0, 5); } public get data(): any[] { return this._data; } public get context(): Map<string, any> { return this._context; } public get cluster(): any { return {}; } public get pid() { return this.context.get("pid"); } }
Add time field support to replace original startTime by a custom time
feat: Add time field support to replace original startTime by a custom time
TypeScript
mit
Romakita/ts-log-debug,Romakita/ts-log-debug
--- +++ @@ -18,7 +18,7 @@ private _startTime = new Date(); get startTime(): Date { - return this._startTime; + return this.data && this.data[0] && this.data[0].time ? this.data[0].time : this._startTime; } public get categoryName(): string {
e0ebe44331b3c52f69081fc4af9045fce9941a87
packages/@sanity/base/src/user-color/useUserColor.ts
packages/@sanity/base/src/user-color/useUserColor.ts
import {of} from 'rxjs' import {useObservable} from '../util/useObservable' import {useUserColorManager} from './provider' import {UserColor} from './types' import React from 'react' export function useUserColor(userId: string | null): Readonly<UserColor> | null { const manager = useUserColorManager() return useObservable( userId === null ? of(null) : React.useMemo(() => manager.listen(userId), [userId]) ) }
import {of} from 'rxjs' import {useObservable} from '../util/useObservable' import {useUserColorManager} from './provider' import {UserColor} from './types' import React from 'react' export function useUserColor(userId: string | null): UserColor | null { const manager = useUserColorManager() return useObservable( userId === null ? of(null) : React.useMemo(() => manager.listen(userId), [userId]) ) }
Fix readonly being applied twice for user color
[base] Fix readonly being applied twice for user color
TypeScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
--- +++ @@ -4,7 +4,7 @@ import {UserColor} from './types' import React from 'react' -export function useUserColor(userId: string | null): Readonly<UserColor> | null { +export function useUserColor(userId: string | null): UserColor | null { const manager = useUserColorManager() return useObservable( userId === null ? of(null) : React.useMemo(() => manager.listen(userId), [userId])
c86f8024f9e43e90bf034ab0e4eb9babe32f603f
src/utils/content.ts
src/utils/content.ts
import { Validate } from './validate'; export interface IContentOptions { trimWhiteSpace: boolean; preserveIndentation: boolean; replaceNewLines: false | string; } export interface IContentExtractorOptions { content?: Partial<IContentOptions>; } export function validateContentOptions(options: IContentExtractorOptions): void { Validate.optional.booleanProperty(options, 'options.content.trimWhiteSpace'); Validate.optional.booleanProperty(options, 'options.content.preserveIndentation'); if (options.content && options.content.replaceNewLines !== undefined && options.content.replaceNewLines !== false && typeof options.content.replaceNewLines !== 'string') { throw new TypeError(`Property 'options.content.replaceNewLines' must be false or a string`); } } export function normalizeContent(content: string, options: IContentOptions): string { if (options.trimWhiteSpace) { content = content.replace(/^\n+|\s+$/g, ''); } if (!options.preserveIndentation) { content = content.replace(/^[ \t]+/mg, ''); } if (typeof options.replaceNewLines === 'string') { content = content.replace(/\n/g, options.replaceNewLines); } return content; }
import { Validate } from './validate'; export interface IContentOptions { trimWhiteSpace: boolean; preserveIndentation: boolean; replaceNewLines: false | string; } export interface IContentExtractorOptions { content?: Partial<IContentOptions>; } export function validateContentOptions(options: IContentExtractorOptions): void { Validate.optional.booleanProperty(options, 'options.content.trimWhiteSpace'); Validate.optional.booleanProperty(options, 'options.content.preserveIndentation'); if (options.content && options.content.replaceNewLines !== undefined && options.content.replaceNewLines !== false && typeof options.content.replaceNewLines !== 'string') { throw new TypeError(`Property 'options.content.replaceNewLines' must be false or a string`); } } export function normalizeContent(content: string, options: IContentOptions): string { content = content.replace(/\r\n/g, '\n'); if (options.trimWhiteSpace) { content = content.replace(/^\n+|\s+$/g, ''); } if (!options.preserveIndentation) { content = content.replace(/^[ \t]+/mg, ''); } if (typeof options.replaceNewLines === 'string') { content = content.replace(/\n/g, options.replaceNewLines); } return content; }
Normalize newlines in extracted JS string literals
Normalize newlines in extracted JS string literals
TypeScript
mit
lukasgeiter/gettext-extractor,lukasgeiter/gettext-extractor,lukasgeiter/gettext-extractor
--- +++ @@ -20,6 +20,7 @@ } export function normalizeContent(content: string, options: IContentOptions): string { + content = content.replace(/\r\n/g, '\n'); if (options.trimWhiteSpace) { content = content.replace(/^\n+|\s+$/g, ''); }
95b8da21e35669f8caa0e7e8598af2502d924804
src/utils/hitItem.ts
src/utils/hitItem.ts
import { Hit, Requester } from '../types'; import { generateBadges } from './badges'; import { truncate } from './formatting'; type ExceptionStatus = 'neutral' | 'warning' | 'critical'; export interface ExceptionDescriptor { status?: ExceptionStatus; title?: string; description?: string; } const generateExceptions = (groupId: string): ExceptionDescriptor[] => { return groupId.startsWith('[Error:groupId]-') ? [ { status: 'warning', title: 'You are not qualified.' } ] : []; }; export const generateItemProps = (hit: Hit, requester: Requester | undefined) => { const { requesterName, groupId, title } = hit; const actions = [ { icon: 'view', external: true, url: `https://www.mturk.com/mturk/preview?groupId=${groupId}` }, { primary: true, external: true, icon: 'add', url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}` } ]; return { attributeOne: requesterName, attributeTwo: truncate(title, 80), badges: generateBadges(requester), actions, exceptions: generateExceptions(groupId) }; };
import { Hit, Requester } from '../types'; import { generateBadges } from './badges'; import { truncate } from './formatting'; type ExceptionStatus = 'neutral' | 'warning' | 'critical'; export interface ExceptionDescriptor { status?: ExceptionStatus; title?: string; description?: string; } const generateExceptions = (groupId: string): ExceptionDescriptor[] => { return groupId.startsWith('[Error:groupId]-') ? [ { status: 'warning', title: 'You are not qualified.' } ] : []; }; export const generateItemProps = (hit: Hit, requester: Requester | undefined) => { const { requesterName, groupId, title } = hit; const actions = [ // { // icon: 'view', // external: true, // url: `https://www.mturk.com/mturk/preview?groupId=${groupId}` // }, { primary: true, external: true, content: 'Accept', accessibilityLabel: 'Accept', icon: 'add', url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}` } ]; return { attributeOne: requesterName, attributeTwo: truncate(title, 80), badges: generateBadges(requester), actions, exceptions: generateExceptions(groupId) }; };
Remove preview button and add text label to add hit button.
Remove preview button and add text label to add hit button.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -19,14 +19,16 @@ const { requesterName, groupId, title } = hit; const actions = [ - { - icon: 'view', - external: true, - url: `https://www.mturk.com/mturk/preview?groupId=${groupId}` - }, + // { + // icon: 'view', + // external: true, + // url: `https://www.mturk.com/mturk/preview?groupId=${groupId}` + // }, { primary: true, external: true, + content: 'Accept', + accessibilityLabel: 'Accept', icon: 'add', url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}` }
3d0031c023f055fdb439d9033a053935f8698611
modern/src/runtime/Wac.ts
modern/src/runtime/Wac.ts
import MakiObject from "./MakiObject"; import { unimplementedWarning } from "../utils"; class Wac extends MakiObject { /** * getclassname() * * Returns the class name for the object. * @ret The class name. */ getclassname() { return "Wac"; } getguid(): string { return unimplementedWarning("getguid"); } getname(): string { return unimplementedWarning("getname"); } sendcommand( cmd: string, param1: number, param2: number, param3: string ): number { return unimplementedWarning("sendcommand"); } show(): void { return unimplementedWarning("show"); } hide(): void { return unimplementedWarning("hide"); } isvisible(): boolean { return unimplementedWarning("isvisible"); } // @ts-ignore This (deprecated) method's signature does not quite match the // same method on MakiObject. This method is not used by any skins as far as // we know, so we'll just ignore the issue for now. onnotify(notifstr: string, a: string, b: number): void { this.js_trigger("onNotify", notifstr, a, b); } onshow(): void { this.js_trigger("onShow"); } onhide(): void { this.js_trigger("onHide"); } setstatusbar(onoff: boolean): void { return unimplementedWarning("setstatusbar"); } getstatusbar(): boolean { return unimplementedWarning("getstatusbar"); } } export default Wac;
import MakiObject from "./MakiObject"; import { unimplementedWarning } from "../utils"; class Wac extends MakiObject { /** * getclassname() * * Returns the class name for the object. * @ret The class name. */ getclassname() { return "Wac"; } getguid(): string { return unimplementedWarning("getguid"); } getname(): string { return unimplementedWarning("getname"); } sendcommand( cmd: string, param1: number, param2: number, param3: string ): number { return unimplementedWarning("sendcommand"); } show(): void { return unimplementedWarning("show"); } hide(): void { return unimplementedWarning("hide"); } isvisible(): boolean { return unimplementedWarning("isvisible"); } onnotify(command: string, param: string, a: number, b: number): number { this.js_trigger("onNotify", command, param, a, b); return unimplementedWarning("onnotify"); } onshow(): void { this.js_trigger("onShow"); } onhide(): void { this.js_trigger("onHide"); } setstatusbar(onoff: boolean): void { return unimplementedWarning("setstatusbar"); } getstatusbar(): boolean { return unimplementedWarning("getstatusbar"); } } export default Wac;
Use patched type for onnotify
Use patched type for onnotify
TypeScript
mit
captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js
--- +++ @@ -41,11 +41,9 @@ return unimplementedWarning("isvisible"); } - // @ts-ignore This (deprecated) method's signature does not quite match the - // same method on MakiObject. This method is not used by any skins as far as - // we know, so we'll just ignore the issue for now. - onnotify(notifstr: string, a: string, b: number): void { - this.js_trigger("onNotify", notifstr, a, b); + onnotify(command: string, param: string, a: number, b: number): number { + this.js_trigger("onNotify", command, param, a, b); + return unimplementedWarning("onnotify"); } onshow(): void {
e408506aa89f84e922c33e207eec8499d96609ce
client/src/shared/calc.helper.ts
client/src/shared/calc.helper.ts
/** * Several static helper functions for calculations. */ export class Calc { public static maxIntegerValue = Math.pow(2, 31); public static partPercentage = (part: number, total: number) => (part / total) * 100; public static profitPercentage = (old: number, newAmount: number) => ((newAmount - old) / old) * 100; public static wholeHoursLeft = (duration: number) => Math.floor(duration / (3600000)); public static wholeDaysLeft = (duration: number) => Math.floor(duration / (86400000)); /** * Generate a random string from a range of 62 characters * @param {number} length - The length of the desired string * @return {string} - The randomly generated string */ public static generateRandomString(length: number): string { let output = ''; const possibleCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < length; i++) { output += possibleCharacters.charAt(Math.floor(Math.random() * possibleCharacters.length)); } return output; } }
/** * Several static helper functions for calculations. */ export class Calc { public static maxIntegerValue = 0x7FFFFFFF; public static partPercentage = (part: number, total: number) => (part / total) * 100; public static profitPercentage = (old: number, newAmount: number) => ((newAmount - old) / old) * 100; public static wholeHoursLeft = (duration: number) => Math.floor(duration / (3600000)); public static wholeDaysLeft = (duration: number) => Math.floor(duration / (86400000)); /** * Generate a random string from a range of 62 characters * @param {number} length - The length of the desired string * @return {string} - The randomly generated string */ public static generateRandomString(length: number): string { let output = ''; const possibleCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < length; i++) { output += possibleCharacters.charAt(Math.floor(Math.random() * possibleCharacters.length)); } return output; } }
Change maxIntegerValue to correct number.
Change maxIntegerValue to correct number.
TypeScript
mit
Ionaru/EVE-Track,Ionaru/EVE-Track,Ionaru/EVE-Track
--- +++ @@ -3,7 +3,7 @@ */ export class Calc { - public static maxIntegerValue = Math.pow(2, 31); + public static maxIntegerValue = 0x7FFFFFFF; public static partPercentage = (part: number, total: number) => (part / total) * 100; public static profitPercentage = (old: number, newAmount: number) => ((newAmount - old) / old) * 100;
81177b7c75672f81d74433438cfd3f04ad47d60b
app/core/datastore/pouchdb/sync-process.ts
app/core/datastore/pouchdb/sync-process.ts
import {Observable} from 'rxjs'; export interface SyncProcess { url: string; cancel(): void; observe: Observable<any>; } export enum SyncStatus { Offline = "OFFLINE", Unknown = "UNKNOWN", Pushing = "PUSHING", Pulling = "PULLING", InSync = "IN_SYNC", Error = "ERROR", AuthenticationError = "AUTHENTICATION_ERROR", AuthorizationError = "AUTHORIZATION_ERROR" }
import {Observable} from 'rxjs'; export interface SyncProcess { url: string; cancel(): void; observe: Observable<any>; } export enum SyncStatus { Offline = "OFFLINE", Pushing = "PUSHING", Pulling = "PULLING", InSync = "IN_SYNC", Error = "ERROR", AuthenticationError = "AUTHENTICATION_ERROR", AuthorizationError = "AUTHORIZATION_ERROR" }
Remove unknown from sync statuses
Remove unknown from sync statuses
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -9,7 +9,6 @@ export enum SyncStatus { Offline = "OFFLINE", - Unknown = "UNKNOWN", Pushing = "PUSHING", Pulling = "PULLING", InSync = "IN_SYNC",
cd2e0926f9de77fe8ef714de341a71521e51fe02
config/webpack.ts
config/webpack.ts
import path from 'path'; import options from '../utils/commandOptions'; /** * 该文件还会在客户端环境执行, 用结构赋值的方式会取不到值 * 因为客户端是基于文本匹配替换的值 */ // eslint-disable-next-line prefer-destructuring const env = process.env; function getFirstNotUndefined(...values) { for (let i = 0; i < values.length; i++) { if (values[i] !== undefined) { return values[i]; } } return null; } export default { commonn: { autoPrefix: { enable: true, options: { browsers: ['last 3 versions'], }, }, }, build: { env: { NODE_ENV: '"production"', }, index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist/fiora'), assetsPublicPath: getFirstNotUndefined(options.publicPath, env.PublicPath, ''), productionSourceMap: false, productionGzip: false, productionGzipExtensions: ['js', 'css'], bundleAnalyzerReport: process.env.npm_config_report, }, dev: { env: { NODE_ENV: '"development"', }, host: 'localhost', port: 8080, autoOpenBrowser: false, assetsPublicPath: '', proxyTable: {}, cssSourceMap: false, }, };
import path from 'path'; import options from '../utils/commandOptions'; /** * 该文件还会在客户端环境执行, 用结构赋值的方式会取不到值 * 因为客户端是基于文本匹配替换的值 */ // eslint-disable-next-line prefer-destructuring const env = process.env; function getFirstNotUndefined(...values) { for (let i = 0; i < values.length; i++) { if (values[i] !== undefined) { return values[i]; } } return null; } export default { commonn: { autoPrefix: { enable: true, options: { browsers: ['last 3 versions'], }, }, }, build: { env: { NODE_ENV: '"production"', }, index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist/fiora'), assetsPublicPath: getFirstNotUndefined(options.publicPath, env.PublicPath, '/'), productionSourceMap: false, productionGzip: false, productionGzipExtensions: ['js', 'css'], bundleAnalyzerReport: process.env.npm_config_report, }, dev: { env: { NODE_ENV: '"development"', }, host: 'localhost', port: 8080, autoOpenBrowser: false, assetsPublicPath: '', proxyTable: {}, cssSourceMap: false, }, };
Solve the problem with font.woff assets file 404
chore: Solve the problem with font.woff assets file 404
TypeScript
mit
yinxin630/fiora,yinxin630/fiora,yinxin630/fiora
--- +++ @@ -32,7 +32,7 @@ }, index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist/fiora'), - assetsPublicPath: getFirstNotUndefined(options.publicPath, env.PublicPath, ''), + assetsPublicPath: getFirstNotUndefined(options.publicPath, env.PublicPath, '/'), productionSourceMap: false, productionGzip: false, productionGzipExtensions: ['js', 'css'],