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
b989a2827233aea0e8c767932c3b713cddb15e77
src/routes/stickynotesAPI.ts
src/routes/stickynotesAPI.ts
import * as api from '../libs/api'; import * as stickynotes from '../libs/stickynotes'; import RoutesFunction from './routesFunction'; export default ((app, db) => { app.get('/stickynotes', async (req, res) => { try { const note = await stickynotes.get(db, req.user.user, req.body.moduleId); api.success(res, { stickynote: note }); } catch (err) { api.error(res, err); } }); app.put('/stickynotes', async (req, res) => { try { await stickynotes.post(db, req.user.user, req.body.moduleId, req.body.text); api.success(res); } catch (err) { api.error(res, err); } }); }) as RoutesFunction;
import * as api from '../libs/api'; import * as stickynotes from '../libs/stickynotes'; import RoutesFunction from './routesFunction'; export default ((app, db) => { app.get('/stickynotes', async (req, res) => { try { const note = await stickynotes.get(db, req.user.user, req.query.moduleId); api.success(res, { stickynote: note }); } catch (err) { api.error(res, err); } }); app.put('/stickynotes', async (req, res) => { try { await stickynotes.post(db, req.user.user, req.body.moduleId, req.body.text); api.success(res); } catch (err) { api.error(res, err); } }); }) as RoutesFunction;
Fix get stickynotes from url param
Fix get stickynotes from url param
TypeScript
mit
michaelgira23/MyMICDS-v2,michaelgira23/MyMICDS-v2
--- +++ @@ -6,7 +6,7 @@ app.get('/stickynotes', async (req, res) => { try { - const note = await stickynotes.get(db, req.user.user, req.body.moduleId); + const note = await stickynotes.get(db, req.user.user, req.query.moduleId); api.success(res, { stickynote: note }); } catch (err) { api.error(res, err);
7a1e35f8cc388867ad8cc48eee5865e9377aa164
coffee-chats/src/main/webapp/src/components/GroupMembersList.tsx
coffee-chats/src/main/webapp/src/components/GroupMembersList.tsx
import React from "react"; import {Member, MembershipStatus} from "../entity/Member"; import {Box, Card, CardContent, List, Typography} from "@material-ui/core"; import {GroupMemberListItem} from "./GroupMemberListItem"; import {User} from "../entity/User"; interface GroupMembersListProps { members: Member[]; status: MembershipStatus; setMembershipStatus: (status: MembershipStatus, user: User) => Promise<void>; } export function GroupMembersList({members, status, setMembershipStatus}: GroupMembersListProps) { return ( <Box mt={2}> <Card> <CardContent> <Typography color="textSecondary" gutterBottom> Members </Typography> <List> {members.map(member => ( <GroupMemberListItem member={member} status={status} setMembershipStatus={setMembershipStatus} /> ))} </List> </CardContent> </Card> </Box> ) }
import React from "react"; import {Member, MembershipStatus} from "../entity/Member"; import {Box, Card, CardContent, List, Typography} from "@material-ui/core"; import {GroupMemberListItem} from "./GroupMemberListItem"; import {User} from "../entity/User"; interface GroupMembersListProps { members: Member[]; status: MembershipStatus; setMembershipStatus: (status: MembershipStatus, user: User) => Promise<void>; } export function GroupMembersList({members, status, setMembershipStatus}: GroupMembersListProps) { return ( <Box mt={2}> <Card> <CardContent> <Typography color="textSecondary" gutterBottom> Members </Typography> <List> {members.map(member => ( <GroupMemberListItem key={member.user.id} member={member} status={status} setMembershipStatus={setMembershipStatus} /> ))} </List> </CardContent> </Card> </Box> ) }
Add a missing key property
Add a missing key property
TypeScript
apache-2.0
googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020
--- +++ @@ -22,6 +22,7 @@ <List> {members.map(member => ( <GroupMemberListItem + key={member.user.id} member={member} status={status} setMembershipStatus={setMembershipStatus}
32b805744765d8f48b21a0d55d6d0260c92e541e
APM-Final/src/app/user/auth.guard.ts
APM-Final/src/app/user/auth.guard.ts
import { Injectable } from '@angular/core'; import { CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router, Route } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate, CanLoad { constructor(private authService: AuthService, private router: Router) { } canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.checkLoggedIn(state.url); } canLoad(route: Route): boolean { return this.checkLoggedIn(route.path); } checkLoggedIn(url: string): boolean { if (this.authService.isLoggedIn) { return true; } // Retain the attempted URL for redirection this.authService.redirectUrl = url; this.router.navigate(['/login']); return false; } }
import { Injectable } from '@angular/core'; import { CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router, Route, UrlSegment } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root', }) export class AuthGuard implements CanActivate, CanLoad { constructor(private authService: AuthService, private router: Router) { } canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.checkLoggedIn(state.url); } // Use the segments to build the full route // when using canLoad canLoad(route: Route, segments: UrlSegment[]): boolean { return this.checkLoggedIn(segments.join('/')); } checkLoggedIn(url: string): boolean { if (this.authService.isLoggedIn) { return true; } // Retain the attempted URL for redirection this.authService.redirectUrl = url; this.router.navigate(['/login']); return false; } }
Update canLoad to access full route (w/parameters)
Update canLoad to access full route (w/parameters)
TypeScript
mit
DeborahK/Angular-Routing,DeborahK/Angular-Routing,DeborahK/Angular-Routing
--- +++ @@ -1,10 +1,10 @@ import { Injectable } from '@angular/core'; -import { CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router, Route } from '@angular/router'; +import { CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router, Route, UrlSegment } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; @Injectable({ - providedIn: 'root' + providedIn: 'root', }) export class AuthGuard implements CanActivate, CanLoad { @@ -17,8 +17,10 @@ return this.checkLoggedIn(state.url); } - canLoad(route: Route): boolean { - return this.checkLoggedIn(route.path); + // Use the segments to build the full route + // when using canLoad + canLoad(route: Route, segments: UrlSegment[]): boolean { + return this.checkLoggedIn(segments.join('/')); } checkLoggedIn(url: string): boolean {
f10189a8f32be9a779bcf47f7dd8f5007f616905
projects/core/src/lib/buttons/telegram.ts
projects/core/src/lib/buttons/telegram.ts
import { Platform } from '@angular/cdk/platform'; import { HttpClient } from '@angular/common/http'; import { ShareButtonBase } from './base'; import { IShareButton, ShareMetaTags } from '../share.models'; export class TelegramButton extends ShareButtonBase { protected _supportedMetaTags: ShareMetaTags = { url: 'url', description: 'text' }; get desktop(): string { return 'https://t.me/share/url?'; } constructor(protected _props: IShareButton, protected _url: () => string, protected _http: HttpClient, protected _platform: Platform, protected _document: Document, protected _windowSize: string, protected _disableButtonClick: (disable: boolean) => void) { super(_props, _url, _http, _platform, _document, _windowSize, _disableButtonClick); } click(metaTags: ShareMetaTags): Window | null | void { // Add the URL to message body metaTags.description += `\r\n${this._url()}`; const serializedMetaTags = this._serializeMetaTags(metaTags); return this._open(serializedMetaTags); } }
import { Platform } from '@angular/cdk/platform'; import { HttpClient } from '@angular/common/http'; import { ShareButtonBase } from './base'; import { IShareButton, ShareMetaTags } from '../share.models'; export class TelegramButton extends ShareButtonBase { protected _supportedMetaTags: ShareMetaTags = { url: 'url', description: 'text' }; get desktop(): string { return 'https://t.me/share/url?'; } constructor(protected _props: IShareButton, protected _url: () => string, protected _http: HttpClient, protected _platform: Platform, protected _document: Document, protected _windowSize: string, protected _disableButtonClick: (disable: boolean) => void, protected _logger: (text: string) => void) { super(_props, _url, _http, _platform, _document, _windowSize, _disableButtonClick, _logger); } }
Remove URL from Telegram message since its already supported
regression: Remove URL from Telegram message since its already supported
TypeScript
mit
MurhafSousli/ng2-sharebuttons,MurhafSousli/ng2-sharebuttons,MurhafSousli/ng2-sharebuttons
--- +++ @@ -20,14 +20,8 @@ protected _platform: Platform, protected _document: Document, protected _windowSize: string, - protected _disableButtonClick: (disable: boolean) => void) { - super(_props, _url, _http, _platform, _document, _windowSize, _disableButtonClick); - } - - click(metaTags: ShareMetaTags): Window | null | void { - // Add the URL to message body - metaTags.description += `\r\n${this._url()}`; - const serializedMetaTags = this._serializeMetaTags(metaTags); - return this._open(serializedMetaTags); + protected _disableButtonClick: (disable: boolean) => void, + protected _logger: (text: string) => void) { + super(_props, _url, _http, _platform, _document, _windowSize, _disableButtonClick, _logger); } }
a0719b2bf7cda47a0cf974277a1c326a9c23ef5b
server/app.ts
server/app.ts
import * as bodyParser from 'body-parser'; import * as dotenv from 'dotenv'; import * as express from 'express'; import * as morgan from 'morgan'; import * as mongoose from 'mongoose'; import * as path from 'path'; import setRoutes from './routes'; const app = express(); dotenv.load({ path: '.env' }); app.set('port', (process.env.PORT || 3000)); app.use('/', express.static(path.join(__dirname, '../public'))); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); if (process.env.NODE_ENV === 'test') { mongoose.connect(process.env.MONGODB_TEST_URI); } else { app.use(morgan('dev')); mongoose.connect(process.env.MONGODB_URI); } const db = mongoose.connection; (<any>mongoose).Promise = global.Promise; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', () => { console.log('Connected to MongoDB'); setRoutes(app); app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, '../public/index.html')); }); if (!module.parent) { app.listen(app.get('port'), () => { console.log('Angular Full Stack listening on port ' + app.get('port')); }); } }); export { app };
import * as bodyParser from 'body-parser'; import * as dotenv from 'dotenv'; import * as express from 'express'; import * as morgan from 'morgan'; import * as mongoose from 'mongoose'; import * as path from 'path'; import setRoutes from './routes'; const app = express(); dotenv.load({ path: '.env' }); app.set('port', (process.env.PORT || 3000)); app.use('/', express.static(path.join(__dirname, '../public'))); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); let mongodbURI; if (process.env.NODE_ENV === 'test') { mongodbURI = process.env.MONGODB_TEST_URI; } else { mongodbURI = process.env.MONGODB_URI; app.use(morgan('dev')); } mongoose.Promise = global.Promise; const mongodb = mongoose.connect(mongodbURI, { useMongoClient: true }); mongodb .then((db) => { console.log('Connected to MongoDB on', db.host + ':' + db.port); setRoutes(app); app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, '../public/index.html')); }); if (!module.parent) { app.listen(app.get('port'), () => { console.log('Angular Full Stack listening on port ' + app.get('port')); }); } }) .catch((err) => { console.error(err); }); export { app };
Fix the deprecation warning about mongoose open() function
Fix the deprecation warning about mongoose open() function
TypeScript
mit
hasman16/rent-a-ref,DavideViolante/Angular-Full-Stack,DavideViolante/Angular-Full-Stack,hasman16/rent-a-ref,DavideViolante/Angular2-Express-Mongoose,DavideViolante/Angular2-Express-Mongoose,DavideViolante/Angular2-Express-Mongoose,DavideViolante/Angular-Full-Stack,DavideViolante/Angular-Full-Stack,hasman16/rent-a-ref
--- +++ @@ -15,32 +15,36 @@ app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); +let mongodbURI; if (process.env.NODE_ENV === 'test') { - mongoose.connect(process.env.MONGODB_TEST_URI); + mongodbURI = process.env.MONGODB_TEST_URI; } else { + mongodbURI = process.env.MONGODB_URI; app.use(morgan('dev')); - mongoose.connect(process.env.MONGODB_URI); } -const db = mongoose.connection; -(<any>mongoose).Promise = global.Promise; +mongoose.Promise = global.Promise; +const mongodb = mongoose.connect(mongodbURI, { useMongoClient: true }); -db.on('error', console.error.bind(console, 'connection error:')); -db.once('open', () => { - console.log('Connected to MongoDB'); +mongodb + .then((db) => { + console.log('Connected to MongoDB on', db.host + ':' + db.port); - setRoutes(app); + setRoutes(app); - app.get('/*', function(req, res) { - res.sendFile(path.join(__dirname, '../public/index.html')); - }); + app.get('/*', function(req, res) { + res.sendFile(path.join(__dirname, '../public/index.html')); + }); - if (!module.parent) { - app.listen(app.get('port'), () => { - console.log('Angular Full Stack listening on port ' + app.get('port')); - }); - } + if (!module.parent) { + app.listen(app.get('port'), () => { + console.log('Angular Full Stack listening on port ' + app.get('port')); + }); + } + }) + .catch((err) => { + console.error(err); }); export { app };
c4740c4613d3b1c6e26af7da240c97ea32c6f8fe
src/dropbox.ts
src/dropbox.ts
import { Dropbox } from 'dropbox'; import { User, Rule, RuleService as rs } from './models'; import _ = require('underscore'); export class DropboxService { client: Dropbox; constructor(token?: string) { this.client = new Dropbox({clientId: process.env.DROPBOX_KEY, accessToken: token}); (this.client as any).setClientSecret(process.env.DROPBOX_SECRET); } async runRules(user: User, rules: Rule[]) { rules = _.sortBy(rules, 'rank'); let files = await this.client.filesListFolder({ path: (user.sortingFolder as string), limit: 100, }); // TODO handle files.has_more // TODO log info let moves = []; for (let file of files.entries) { // Only move files, not folders if (file['.tag'] !== 'file') { continue; } for (let rule of rules) { if (rs.matches(rule, file.name)) { let to_path = (rule.dest as string); moves.push(this.client.filesMoveV2({ from_path: (file.path_lower as string), to_path, autorename: true, })); // Once there's a matching rule, move to next file break; } } } // TODO handle conflicts return await Promise.all(moves); } } function dbxClient(token?: string): DropboxService { return new DropboxService(token); } export default dbxClient;
import { Dropbox } from 'dropbox'; import { User, Rule, RuleService as rs } from './models'; import _ = require('underscore'); export class DropboxService { client: Dropbox; constructor(token?: string) { this.client = new Dropbox({clientId: process.env.DROPBOX_KEY, accessToken: token}); (this.client as any).setClientSecret(process.env.DROPBOX_SECRET); } async runRules(user: User, rules: Rule[]) { rules = _.sortBy(rules, 'rank'); let files = await this.client.filesListFolder({ path: (user.sortingFolder as string), limit: 100, }); // TODO handle files.has_more // TODO log info let moves = []; for (let file of files.entries) { // Only move files, not folders if (file['.tag'] !== 'file') { continue; } for (let rule of rules) { if (rs.matches(rule, file.name)) { let to_path = [rule.dest, file.name].join('/'); moves.push(this.client.filesMoveV2({ from_path: (file.path_lower as string), to_path, autorename: true, })); // Once there's a matching rule, move to next file break; } } } // TODO handle conflicts return await Promise.all(moves); } } function dbxClient(token?: string): DropboxService { return new DropboxService(token); } export default dbxClient;
Use full destination path for move
Use full destination path for move
TypeScript
bsd-2-clause
mustpax/sortmybox,mustpax/sortmybox,mustpax/sortmybox
--- +++ @@ -26,7 +26,7 @@ } for (let rule of rules) { if (rs.matches(rule, file.name)) { - let to_path = (rule.dest as string); + let to_path = [rule.dest, file.name].join('/'); moves.push(this.client.filesMoveV2({ from_path: (file.path_lower as string), to_path,
f9b953e6b16d85d8531c8e9a6f89e8730a3b33a7
src/v2/components/UserSettings/queries/UserSettingsQuery.ts
src/v2/components/UserSettings/queries/UserSettingsQuery.ts
import gql from 'graphql-tag' export default gql` query MySettings { me { __typename id first_name last_name email slug unconfirmed_email bio is_premium home_path can { edit_profile_description } settings { receive_email receive_tips_emails exclude_from_indexes receive_newsletter show_nsfw } } } `
import gql from 'graphql-tag' export default gql` query MySettings { me { __typename id first_name last_name email slug unconfirmed_email bio is_premium home_path can { edit_profile_description } settings { exclude_from_indexes show_nsfw } } } `
Make sure this file is checked in, remove unneeded nodes
Make sure this file is checked in, remove unneeded nodes
TypeScript
mit
aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell
--- +++ @@ -17,10 +17,7 @@ edit_profile_description } settings { - receive_email - receive_tips_emails exclude_from_indexes - receive_newsletter show_nsfw } }
55bf3e3ff01d5eeaedc206715be04b26fc305cb6
src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts
src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts
/* @internal */ namespace ts.codefix { registerCodeFix({ errorCodes: [Diagnostics.Class_0_incorrectly_implements_interface_1.code], getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; const start = context.span.start; const token = getTokenAtPosition(sourceFile, start); const checker = context.program.getTypeChecker(); if (token.kind === SyntaxKind.Identifier && isClassLike(token.parent)) { const classDeclaration = <ClassDeclaration>token.parent; const startPos: number = classDeclaration.members.pos; const classMembers = ts.map(getNamedClassMembers(classDeclaration), member => member.name.getText()); const trackingAddedMembers: string[] = []; const interfaceClauses = ts.getClassImplementsHeritageClauseElements(classDeclaration); let textChanges: TextChange[] = undefined; for (let i = 0; interfaceClauses && i < interfaceClauses.length; i++) { const newChanges = getCodeFixChanges(interfaceClauses[i], classMembers, startPos, checker, /*reference*/ false, trackingAddedMembers, context.newLineCharacter); // getMissingAbstractMemberChanges(classDeclaration, checker, context.newLineCharacter); textChanges = textChanges ? textChanges.concat(newChanges) : newChanges; } if (textChanges && textChanges.length > 0) { return [{ description: getLocaleSpecificMessage(Diagnostics.Implement_interface_on_class), changes: [{ fileName: sourceFile.fileName, textChanges: textChanges }] }]; } } return undefined; } }); }
/* @internal */ namespace ts.codefix { registerCodeFix({ errorCodes: [Diagnostics.Class_0_incorrectly_implements_interface_1.code], getCodeActions: (context: CodeFixContext) => { const sourceFile = context.sourceFile; const start = context.span.start; const token = getTokenAtPosition(sourceFile, start); const checker = context.program.getTypeChecker(); if (token.kind === SyntaxKind.Identifier && isClassLike(token.parent)) { const classDeclaration = <ClassDeclaration>token.parent; const startPos: number = classDeclaration.members.pos; const insertion = getMissingInterfaceMembersInsertion(classDeclaration, checker, context.newLineCharacter); if(insertion && insertion.length) { return [{ description: getLocaleSpecificMessage(Diagnostics.Implement_interface_on_class), changes: [{ fileName: sourceFile.fileName, textChanges: [{ span: { start: startPos, length: 0 }, newText: insertion }] }] }]; } } return undefined; } }); }
Use new engine for interface fixes
Use new engine for interface fixes
TypeScript
apache-2.0
mihailik/TypeScript,TukekeSoft/TypeScript,Microsoft/TypeScript,Eyas/TypeScript,Microsoft/TypeScript,TukekeSoft/TypeScript,Microsoft/TypeScript,erikmcc/TypeScript,nojvek/TypeScript,chuckjaz/TypeScript,erikmcc/TypeScript,basarat/TypeScript,mihailik/TypeScript,donaldpipowitch/TypeScript,kitsonk/TypeScript,alexeagle/TypeScript,microsoft/TypeScript,nojvek/TypeScript,kitsonk/TypeScript,alexeagle/TypeScript,basarat/TypeScript,minestarks/TypeScript,microsoft/TypeScript,jwbay/TypeScript,synaptek/TypeScript,SaschaNaz/TypeScript,jwbay/TypeScript,chuckjaz/TypeScript,erikmcc/TypeScript,TukekeSoft/TypeScript,minestarks/TypeScript,DLehenbauer/TypeScript,chuckjaz/TypeScript,SaschaNaz/TypeScript,alexeagle/TypeScript,Eyas/TypeScript,basarat/TypeScript,SaschaNaz/TypeScript,microsoft/TypeScript,synaptek/TypeScript,kpreisser/TypeScript,RyanCavanaugh/TypeScript,DLehenbauer/TypeScript,donaldpipowitch/TypeScript,Eyas/TypeScript,jwbay/TypeScript,synaptek/TypeScript,RyanCavanaugh/TypeScript,kpreisser/TypeScript,donaldpipowitch/TypeScript,erikmcc/TypeScript,weswigham/TypeScript,minestarks/TypeScript,weswigham/TypeScript,synaptek/TypeScript,basarat/TypeScript,DLehenbauer/TypeScript,chuckjaz/TypeScript,jwbay/TypeScript,weswigham/TypeScript,kitsonk/TypeScript,SaschaNaz/TypeScript,mihailik/TypeScript,nojvek/TypeScript,kpreisser/TypeScript,mihailik/TypeScript,RyanCavanaugh/TypeScript,DLehenbauer/TypeScript,nojvek/TypeScript,donaldpipowitch/TypeScript,Eyas/TypeScript
--- +++ @@ -11,24 +11,18 @@ if (token.kind === SyntaxKind.Identifier && isClassLike(token.parent)) { const classDeclaration = <ClassDeclaration>token.parent; const startPos: number = classDeclaration.members.pos; - const classMembers = ts.map(getNamedClassMembers(classDeclaration), member => member.name.getText()); - const trackingAddedMembers: string[] = []; - const interfaceClauses = ts.getClassImplementsHeritageClauseElements(classDeclaration); - let textChanges: TextChange[] = undefined; + const insertion = getMissingInterfaceMembersInsertion(classDeclaration, checker, context.newLineCharacter); - for (let i = 0; interfaceClauses && i < interfaceClauses.length; i++) { - const newChanges = getCodeFixChanges(interfaceClauses[i], classMembers, startPos, checker, /*reference*/ false, trackingAddedMembers, context.newLineCharacter); - // getMissingAbstractMemberChanges(classDeclaration, checker, context.newLineCharacter); - textChanges = textChanges ? textChanges.concat(newChanges) : newChanges; - } - - if (textChanges && textChanges.length > 0) { + if(insertion && insertion.length) { return [{ description: getLocaleSpecificMessage(Diagnostics.Implement_interface_on_class), changes: [{ fileName: sourceFile.fileName, - textChanges: textChanges + textChanges: [{ + span: { start: startPos, length: 0 }, + newText: insertion + }] }] }]; }
270df4226461076cc8b2ec8883eadc19c060b3ec
src/models/Event.ts
src/models/Event.ts
import { Company, User } from '.' export interface Event { readonly id: string readonly companyName: string readonly company: Company readonly responsible: User readonly schedule: string readonly location: string readonly privateDescription: string readonly publicDescription: string readonly date: Date readonly beforeSurveys: string[] readonly afterSurveys: string[] readonly pictures: string[] readonly published: boolean readonly checkedInUsers: User[] notCheckedInUsers: User[] }
import { Company, User } from '.' export interface Event { readonly id: string readonly company: Company readonly responsible: User readonly location: string readonly privateDescription: string readonly publicDescription: string readonly date: Date readonly beforeSurvey: string readonly afterSurvey: string readonly pictures: string[] readonly published: boolean }
Update event model in models
Update event model in models
TypeScript
mit
studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord
--- +++ @@ -2,18 +2,14 @@ export interface Event { readonly id: string - readonly companyName: string readonly company: Company readonly responsible: User - readonly schedule: string readonly location: string readonly privateDescription: string readonly publicDescription: string readonly date: Date - readonly beforeSurveys: string[] - readonly afterSurveys: string[] + readonly beforeSurvey: string + readonly afterSurvey: string readonly pictures: string[] readonly published: boolean - readonly checkedInUsers: User[] - notCheckedInUsers: User[] }
8bfc8aa4fccd936727e2b117638b122d6be956b5
ui/src/idai_shapes/Shapes.tsx
ui/src/idai_shapes/Shapes.tsx
import React, { ReactElement, useEffect, useState } from 'react'; import { Route, Switch } from 'react-router'; import { BrowserRouter } from 'react-router-dom'; import ImageView from '../shared/image/ImageView'; import { doLogout, getPersistedLogin, LoginContext } from '../shared/login'; import LoginForm from '../shared/loginform/LoginForm'; import NotFound from '../shared/NotFound'; import Browse from './browse/Browse'; import Home from './home/Home'; import ShapesNav from './navbar/ShapesNav'; import Draw from './draw/Draw'; export default function Shapes(): ReactElement { const [loginData, setLoginData] = useState(getPersistedLogin()); useEffect(() => { document.title = 'iDAI.shapes'; }, []); return ( <BrowserRouter> <LoginContext.Provider value={ loginData }> <ShapesNav onLogout={ doLogout(setLoginData) } /> <Switch> <Route path={ '/' } exact component={ Home } /> <Route path={ '/document/:documentId?' } component={ Browse } /> <Route path={ '/login' }> <LoginForm onLogin={ setLoginData } /> </Route> <Route path="/image/idaishapes/:id" component={ ImageView } /> <Route path={ '/draw' } component={ Draw } /> <Route component={ NotFound } /> </Switch> </LoginContext.Provider> </BrowserRouter> ); }
import React, { ReactElement, useEffect, useState } from 'react'; import { Route, Switch } from 'react-router'; import { BrowserRouter } from 'react-router-dom'; import ImageView from '../shared/image/ImageView'; import { doLogout, getPersistedLogin, LoginContext } from '../shared/login'; import LoginForm from '../shared/loginform/LoginForm'; import NotFound from '../shared/NotFound'; import Browse from './browse/Browse'; import Home from './home/Home'; import ShapesNav from './navbar/ShapesNav'; import Draw from './draw/Draw'; export default function Shapes(): ReactElement { const [loginData, setLoginData] = useState(getPersistedLogin()); useEffect(() => { document.title = 'iDAI.shapes'; }, []); return ( <BrowserRouter> <LoginContext.Provider value={ loginData }> <ShapesNav onLogout={ doLogout(setLoginData) } /> <Switch> <Route path={ '/' } exact component={ Home } /> <Route path={ '/document/:documentId?' } component={ Browse } /> <Route path={ '/login' }> <LoginForm onLogin={ setLoginData } /> </Route> <Route path="/image/:project/:id" component={ ImageView } /> <Route path={ '/draw' } component={ Draw } /> <Route component={ NotFound } /> </Switch> </LoginContext.Provider> </BrowserRouter> ); }
Fix routing for image component in iDAI.shapes
Fix routing for image component in iDAI.shapes
TypeScript
apache-2.0
dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web
--- +++ @@ -30,7 +30,7 @@ <Route path={ '/login' }> <LoginForm onLogin={ setLoginData } /> </Route> - <Route path="/image/idaishapes/:id" component={ ImageView } /> + <Route path="/image/:project/:id" component={ ImageView } /> <Route path={ '/draw' } component={ Draw } /> <Route component={ NotFound } /> </Switch>
e8bf21c46494a48e52468c105eda23d232007d60
packages/toc/src/index.ts
packages/toc/src/index.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. export * from './toc'; export * from './registry'; export * from './generators';
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. // Note: keep in alphabetical order... export * from './generators'; export * from './registry'; export * from './toc';
Reorder imports and add note
Reorder imports and add note
TypeScript
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
--- +++ @@ -1,6 +1,7 @@ // Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. +// Note: keep in alphabetical order... +export * from './generators'; +export * from './registry'; export * from './toc'; -export * from './registry'; -export * from './generators';
b4703b6703ca3b12ccdfaae50116052182a38acf
packages/components/containers/filePreview/UnsupportedPreview.tsx
packages/components/containers/filePreview/UnsupportedPreview.tsx
import React from 'react'; import { c } from 'ttag'; import unsupportedPreviewSvg from 'design-system/assets/img/shared/preview-unsupported.svg'; import corruptedPreviewSvg from 'design-system/assets/img/shared/preview-corrupted.svg'; import { PrimaryButton } from '../../components'; interface Props { type?: 'file' | 'image'; onSave?: () => void; } const UnsupportedPreview = ({ onSave, type = 'file' }: Props) => { return ( <div className="centered-absolute aligncenter"> <img className="mb1" src={type === 'file' ? unsupportedPreviewSvg : corruptedPreviewSvg} alt={c('Info').t`Unsupported file`} /> <h2 className="p0-25 bold">{c('Info').t`No preview available`}</h2> {onSave && ( <PrimaryButton className="pm-button--large w150p bold" onClick={onSave}>{c('Action') .t`Download`}</PrimaryButton> )} </div> ); }; export default UnsupportedPreview;
import React from 'react'; import { c } from 'ttag'; import unsupportedPreviewSvg from 'design-system/assets/img/shared/preview-unsupported.svg'; import corruptedPreviewSvg from 'design-system/assets/img/shared/preview-corrupted.svg'; import { PrimaryButton } from '../../components'; import { useActiveBreakpoint } from '../../hooks'; import { classnames } from '../../helpers'; interface Props { type?: 'file' | 'image'; onSave?: () => void; } const UnsupportedPreview = ({ onSave, type = 'file' }: Props) => { const { isNarrow } = useActiveBreakpoint(); return ( <div className="centered-absolute aligncenter w100 pl1 pr1"> <img className={classnames(['mb1', isNarrow ? 'w150p' : 'w200p'])} src={type === 'file' ? unsupportedPreviewSvg : corruptedPreviewSvg} alt={c('Info').t`Unsupported file`} /> <h2 className={classnames(['p0-25 bold', isNarrow && 'h3'])}>{c('Info').t`No preview available`}</h2> {onSave && ( <PrimaryButton className={classnames(['bold', !isNarrow && 'pm-button--large w150p'])} onClick={onSave} >{c('Action').t`Download`}</PrimaryButton> )} </div> ); }; export default UnsupportedPreview;
Add mobile view for unsupported preview
[DRVWEB-781] Add mobile view for unsupported preview
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -3,6 +3,8 @@ import unsupportedPreviewSvg from 'design-system/assets/img/shared/preview-unsupported.svg'; import corruptedPreviewSvg from 'design-system/assets/img/shared/preview-corrupted.svg'; import { PrimaryButton } from '../../components'; +import { useActiveBreakpoint } from '../../hooks'; +import { classnames } from '../../helpers'; interface Props { type?: 'file' | 'image'; @@ -10,17 +12,23 @@ } const UnsupportedPreview = ({ onSave, type = 'file' }: Props) => { + const { isNarrow } = useActiveBreakpoint(); + return ( - <div className="centered-absolute aligncenter"> + <div className="centered-absolute aligncenter w100 pl1 pr1"> <img - className="mb1" + className={classnames(['mb1', isNarrow ? 'w150p' : 'w200p'])} src={type === 'file' ? unsupportedPreviewSvg : corruptedPreviewSvg} alt={c('Info').t`Unsupported file`} /> - <h2 className="p0-25 bold">{c('Info').t`No preview available`}</h2> + + <h2 className={classnames(['p0-25 bold', isNarrow && 'h3'])}>{c('Info').t`No preview available`}</h2> + {onSave && ( - <PrimaryButton className="pm-button--large w150p bold" onClick={onSave}>{c('Action') - .t`Download`}</PrimaryButton> + <PrimaryButton + className={classnames(['bold', !isNarrow && 'pm-button--large w150p'])} + onClick={onSave} + >{c('Action').t`Download`}</PrimaryButton> )} </div> );
1b9a7a39583e37a778aee7aaa0531c414adb4c46
packages/react-day-picker/src/components/Table/Table.tsx
packages/react-day-picker/src/components/Table/Table.tsx
import * as React from 'react'; import { Head, Row } from '../../components'; import { useDayPicker } from '../../hooks'; import { UIElement } from '../../types'; import { getWeeks } from './utils/getWeeks'; /** * The props for the [[Table]] component. */ export interface TableProps { /** The month used to render the table */ displayMonth: Date; } /** * Render the table with the calendar. */ export function Table(props: TableProps): JSX.Element { const { locale, fixedWeeks, classNames, styles, hideHead } = useDayPicker(); const weeks = getWeeks(props.displayMonth, { locale, fixedWeeks }); return ( <table className={classNames?.[UIElement.Table]} style={styles?.[UIElement.Table]} > {!hideHead && <Head />} <tbody className={classNames?.[UIElement.TBody]} style={styles?.[UIElement.TBody]} > {Object.keys(weeks).map((weekNumber) => ( <Row displayMonth={props.displayMonth} key={weekNumber} dates={weeks[weekNumber]} weekNumber={Number(weekNumber)} /> ))} </tbody> </table> ); }
import * as React from 'react'; import { Head } from '../../components'; import { useDayPicker } from '../../hooks'; import { UIElement } from '../../types'; import { getWeeks } from './utils/getWeeks'; /** * The props for the [[Table]] component. */ export interface TableProps { /** The month used to render the table */ displayMonth: Date; } /** * Render the table with the calendar. */ export function Table(props: TableProps): JSX.Element { const { locale, fixedWeeks, classNames, styles, hideHead, components: { Row } } = useDayPicker(); const weeks = getWeeks(props.displayMonth, { locale, fixedWeeks }); return ( <table className={classNames?.[UIElement.Table]} style={styles?.[UIElement.Table]} > {!hideHead && <Head />} <tbody className={classNames?.[UIElement.TBody]} style={styles?.[UIElement.TBody]} > {Object.keys(weeks).map((weekNumber) => ( <Row displayMonth={props.displayMonth} key={weekNumber} dates={weeks[weekNumber]} weekNumber={Number(weekNumber)} /> ))} </tbody> </table> ); }
Enable use of Row custom component
Enable use of Row custom component
TypeScript
mit
gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker
--- +++ @@ -1,6 +1,6 @@ import * as React from 'react'; -import { Head, Row } from '../../components'; +import { Head } from '../../components'; import { useDayPicker } from '../../hooks'; import { UIElement } from '../../types'; import { getWeeks } from './utils/getWeeks'; @@ -17,7 +17,14 @@ * Render the table with the calendar. */ export function Table(props: TableProps): JSX.Element { - const { locale, fixedWeeks, classNames, styles, hideHead } = useDayPicker(); + const { + locale, + fixedWeeks, + classNames, + styles, + hideHead, + components: { Row } + } = useDayPicker(); const weeks = getWeeks(props.displayMonth, { locale, fixedWeeks }); return (
901ccee8092d082434d37ed9d2fab69b2804eed7
app/pages/session-detail/session-detail.ts
app/pages/session-detail/session-detail.ts
import { Component } from '@angular/core'; import { NavParams } from 'ionic-angular'; import { UserData } from '../../providers/user-data'; @Component({ templateUrl: 'build/pages/session-detail/session-detail.html' }) export class SessionDetailPage { session: any; loggedIn = false; showParticipate = true; constructor( public navParams: NavParams, public userData: UserData ) { this.session = navParams.data; this.userData.hasLoggedIn().then((hasLoggedIn) => { this.loggedIn = hasLoggedIn === 'true'; this.showParticipate = true; }); } addParticipation() { console.log('Clicked participate'); this.showParticipate = false; } cancelParticipation() { console.log('Clicked on cancel'); this.showParticipate = true; } }
import { Component } from '@angular/core'; import { NavParams } from 'ionic-angular'; import { UserData } from '../../providers/user-data'; @Component({ templateUrl: 'build/pages/session-detail/session-detail.html' }) export class SessionDetailPage { session: any; loggedIn = false; showParticipate = true; constructor( public navParams: NavParams, public userData: UserData ) { this.session = navParams.data; this.userData.hasLoggedIn().then((hasLoggedIn) => { this.loggedIn = hasLoggedIn === 'true'; this.showParticipate = true; }); } addParticipation() { console.log('Clicked participate'); this.userData.addFavorite(this.session.name); this.showParticipate = false; } cancelParticipation() { console.log('Clicked on cancel'); this.userData.removeFavorite(this.session.name); this.showParticipate = true; } }
Add session to favourite when user participate to it
Add session to favourite when user participate to it
TypeScript
apache-2.0
laodice/ionic-conference-app-session2,laodice/ionic-conference-app-session2,laodice/ionic-conference-app-session2
--- +++ @@ -27,11 +27,13 @@ addParticipation() { console.log('Clicked participate'); + this.userData.addFavorite(this.session.name); this.showParticipate = false; } cancelParticipation() { console.log('Clicked on cancel'); + this.userData.removeFavorite(this.session.name); this.showParticipate = true; } }
78a397e070335dafd4ed69001e0818d966498627
FrontEnd/src/app/app.module.ts
FrontEnd/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import {RoutingModule} from './router/router.module'; import {RouterModule, Routes} from '@angular/router'; import {TaskModule} from './task/task.module'; import { provideAuth } from 'angular2-jwt'; import { AppComponent } from './app.component'; import { LandingpageComponent } from "./landingpage.component"; import { UserprofileComponent } from './userprofile/userprofile.component'; import { HeaderComponent } from './shared/header/header.component'; @NgModule({ declarations: [ AppComponent, LandingpageComponent, UserprofileComponent, HeaderComponent, ], imports: [ RoutingModule, BrowserModule, FormsModule, HttpModule, TaskModule, ], providers: [ provideAuth({ headerPrefix: 'JWT' }) ], bootstrap: [AppComponent] }) export class AppModule { }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule, Http, RequestOptions } from '@angular/http'; import {RoutingModule} from './router/router.module'; import {RouterModule, Routes} from '@angular/router'; import {TaskModule} from './task/task.module'; import {AuthConfig, AuthHttp } from 'angular2-jwt'; import { AppComponent } from './app.component'; import { LandingpageComponent } from "./landingpage.component"; import { UserprofileComponent } from './userprofile/userprofile.component'; import { HeaderComponent } from './shared/header/header.component'; export function authHttpServiceFactory(http: Http, options: RequestOptions) { return new AuthHttp( new AuthConfig({headerPrefix: 'JWT'}), http, options); } @NgModule({ declarations: [ AppComponent, LandingpageComponent, UserprofileComponent, HeaderComponent, ], imports: [ RoutingModule, BrowserModule, FormsModule, HttpModule, TaskModule, ], providers: [ { provide: AuthHttp, useFactory: authHttpServiceFactory, deps: [ Http, RequestOptions ] } ], bootstrap: [AppComponent] }) export class AppModule { }
Adjust angular2-jwt configuration to remove an error when the app reloads
Adjust angular2-jwt configuration to remove an error when the app reloads
TypeScript
apache-2.0
toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile
--- +++ @@ -1,17 +1,20 @@ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; -import { HttpModule } from '@angular/http'; +import { HttpModule, Http, RequestOptions } from '@angular/http'; import {RoutingModule} from './router/router.module'; import {RouterModule, Routes} from '@angular/router'; import {TaskModule} from './task/task.module'; -import { provideAuth } from 'angular2-jwt'; +import {AuthConfig, AuthHttp } from 'angular2-jwt'; import { AppComponent } from './app.component'; import { LandingpageComponent } from "./landingpage.component"; import { UserprofileComponent } from './userprofile/userprofile.component'; import { HeaderComponent } from './shared/header/header.component'; +export function authHttpServiceFactory(http: Http, options: RequestOptions) { + return new AuthHttp( new AuthConfig({headerPrefix: 'JWT'}), http, options); +} @NgModule({ declarations: [ @@ -29,9 +32,11 @@ ], providers: [ - provideAuth({ - headerPrefix: 'JWT' - }) + { + provide: AuthHttp, + useFactory: authHttpServiceFactory, + deps: [ Http, RequestOptions ] + } ], bootstrap: [AppComponent] })
5943cc27789df7136b63ffcbc77ed6ae39425378
generators/app/templates/src/app/shell/__material-simple.shell.component.ts
generators/app/templates/src/app/shell/__material-simple.shell.component.ts
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { MediaChange, MediaObserver } from '@angular/flex-layout'; import { MatSidenav } from '@angular/material'; import { filter } from 'rxjs/operators'; import { untilDestroyed } from '@app/core'; @Component({ selector: 'app-shell', templateUrl: './shell.component.html', styleUrls: ['./shell.component.scss'] }) export class ShellComponent implements OnInit, OnDestroy { @ViewChild('sidenav') sidenav!: MatSidenav; constructor(private media: MediaObserver) { } ngOnInit() { // Automatically close side menu on screens > sm breakpoint this.media.media$ .pipe( filter((change: MediaChange) => (change.mqAlias !== 'xs' && change.mqAlias !== 'sm')), untilDestroyed(this) ) .subscribe(() => this.sidenav.close()); } ngOnDestroy() { // Needed for automatic unsubscribe with untilDestroyed } }
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { MediaChange, MediaObserver } from '@angular/flex-layout'; import { MatSidenav } from '@angular/material'; import { filter } from 'rxjs/operators'; import { untilDestroyed } from '@app/core'; @Component({ selector: 'app-shell', templateUrl: './shell.component.html', styleUrls: ['./shell.component.scss'] }) export class ShellComponent implements OnInit, OnDestroy { @ViewChild('sidenav') sidenav!: MatSidenav; constructor(private media: MediaObserver) { } ngOnInit() { // Automatically close side menu on screens > sm breakpoint this.media .asObservable() .pipe( filter((changes: MediaChange[]) => changes.some(change => change.mqAlias !== 'xs' && change.mqAlias !== 'sm')), untilDestroyed(this) ) .subscribe(() => this.sidenav.close()); } ngOnDestroy() { // Needed for automatic unsubscribe with untilDestroyed } }
Fix @angular/flex-layout deprecated media$ usage
Fix @angular/flex-layout deprecated media$ usage
TypeScript
mit
ngx-rocket/generator-ngx-rocket,angular-starter-kit/generator-ngx-app,ngx-rocket/generator-ngx-rocket,angular-starter-kit/generator-ngx-app,angular-starter-kit/generator-ngx-app,ngx-rocket/generator-ngx-rocket,angular-starter-kit/generator-ngx-app,ngx-rocket/generator-ngx-rocket
--- +++ @@ -18,9 +18,10 @@ ngOnInit() { // Automatically close side menu on screens > sm breakpoint - this.media.media$ + this.media + .asObservable() .pipe( - filter((change: MediaChange) => (change.mqAlias !== 'xs' && change.mqAlias !== 'sm')), + filter((changes: MediaChange[]) => changes.some(change => change.mqAlias !== 'xs' && change.mqAlias !== 'sm')), untilDestroyed(this) ) .subscribe(() => this.sidenav.close());
f407586d381d36b241b92bf0d2a322fba4dc6f6d
packages/skatejs/src/types.ts
packages/skatejs/src/types.ts
export interface CustomElement extends HTMLElement { attributeChangedCallback?(name: string, oldValue: string, newValue: string); childrenUpdated?(); connectedCallback?(); disconnectedCallback?(); forceUpdate?(); props?: Object; render?(); renderer?: (root: Root, func: () => any) => void; renderRoot?: Root; shouldUpdate?(props: Object, state: Object); state?: Object; updated?(props: Object, state: Object); } export interface CustomElementConstructor { new (): CustomElement; is?: string; observedAttributes?: Array<string>; props?: {}; } export type NormalizedPropType = { deserialize: (string) => any; serialize: (any) => string | void; source: (string) => string | void; target: (string) => string | void; }; export type NormalizedPropTypes = Array<{ propName: string; propType: NormalizedPropType; }>; export type ObservedAttributes = Array<string>; export type PropType = | ArrayConstructor | BooleanConstructor | NumberConstructor | ObjectConstructor | StringConstructor | NormalizedPropType; export type PropTypes = { [s: string]: PropType; }; export type Root = HTMLElement | ShadowRoot;
export interface CustomElement extends HTMLElement { attributeChangedCallback?(name: string, oldValue: string, newValue: string); childrenUpdated?(); connectedCallback?(); disconnectedCallback?(); forceUpdate?(); props?: Object; render?(); renderer?: (root: Root, func: () => any) => void; renderRoot?: Root; shouldUpdate?(props: Object, state: Object); state?: Object; updated?(props: Object, state: Object); } export interface CustomElementConstructor { new (): CustomElement; is?: string; observedAttributes?: Array<string>; name: string; props?: {}; } export type DenormalizedPropType = { deserialize: void | ((string) => any); serialize: void | ((any) => string | void); source: string | void | ((string) => string | void); target: string | void | ((string) => string | void); }; export type NormalizedPropType = { deserialize: (string) => any; serialize: (any) => string | void; source: string | void; target: string | void; }; export type NormalizedPropTypes = Array<{ propName: string; propType: NormalizedPropType; }>; export type ObservedAttributes = Array<string>; export type PropType = | ArrayConstructor | BooleanConstructor | NumberConstructor | ObjectConstructor | StringConstructor | DenormalizedPropType; export type PropTypes = { [s: string]: PropType; }; export type Root = HTMLElement | ShadowRoot;
Add a denormalized prop type.
Add a denormalized prop type.
TypeScript
mit
skatejs/skatejs,skatejs/skatejs,skatejs/skatejs
--- +++ @@ -17,14 +17,22 @@ new (): CustomElement; is?: string; observedAttributes?: Array<string>; + name: string; props?: {}; } + +export type DenormalizedPropType = { + deserialize: void | ((string) => any); + serialize: void | ((any) => string | void); + source: string | void | ((string) => string | void); + target: string | void | ((string) => string | void); +}; export type NormalizedPropType = { deserialize: (string) => any; serialize: (any) => string | void; - source: (string) => string | void; - target: (string) => string | void; + source: string | void; + target: string | void; }; export type NormalizedPropTypes = Array<{ @@ -40,7 +48,7 @@ | NumberConstructor | ObjectConstructor | StringConstructor - | NormalizedPropType; + | DenormalizedPropType; export type PropTypes = { [s: string]: PropType;
12bf19c5ce0d2737fe70a56be000cf2e5ed50885
packages/react-day-picker/src/hooks/useSelection/useSelectRange.ts
packages/react-day-picker/src/hooks/useSelection/useSelectRange.ts
import { useState } from 'react'; import { DayClickEventHandler, ModifierStatus, SelectMode } from '../../types'; import { DateRange } from '../../types/DateRange'; import { addToRange } from './utils/addToRange'; export type RangeSelectionHandler = (day: Date) => void; export type UseRangeSelect = { selected: DateRange | undefined; onDayClick: DayClickEventHandler; reset: () => void; }; export type UseRangeCallback = ( range: DateRange | undefined, day: Date, modifiers: ModifierStatus, e: React.MouseEvent ) => void; /** Hook to handle range selections. */ export function useRangeSelect( mode: SelectMode, defaultValue?: unknown, required = false, callback?: UseRangeCallback ): UseRangeSelect { const initialValue = mode === 'range' && defaultValue ? (defaultValue as DateRange) : undefined; const [selected, setSelected] = useState(initialValue); const onDayClick: DayClickEventHandler = (day, modifiers, e) => { setSelected((currentValue) => { const newValue = addToRange(day, currentValue, required); callback?.(newValue, day, modifiers, e); setSelected(newValue); return newValue; }); return; }; const reset = () => { setSelected(initialValue || undefined); }; return { selected, onDayClick, reset }; }
import { useState } from 'react'; import { DayClickEventHandler, ModifierStatus, SelectMode } from '../../types'; import { DateRange } from '../../types/DateRange'; import { addToRange } from './utils/addToRange'; export type UseRangeSelect = { selected: DateRange | undefined; onDayClick: DayClickEventHandler; reset: () => void; }; export type RangeSelectionHandler = ( range: DateRange | undefined, day: Date, modifiers: ModifierStatus, e: React.MouseEvent ) => void; /** Hook to handle range selections. */ export function useRangeSelect( mode: SelectMode, defaultValue?: unknown, required = false, callback?: RangeSelectionHandler ): UseRangeSelect { const initialValue = mode === 'range' && defaultValue ? (defaultValue as DateRange) : undefined; const [selected, setSelected] = useState(initialValue); const onDayClick: DayClickEventHandler = (day, modifiers, e) => { setSelected((currentValue) => { const newValue = addToRange(day, currentValue, required); callback?.(newValue, day, modifiers, e); setSelected(newValue); return newValue; }); return; }; const reset = () => { setSelected(initialValue || undefined); }; return { selected, onDayClick, reset }; }
Fix wrong type in callback
Fix wrong type in callback
TypeScript
mit
gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker
--- +++ @@ -3,8 +3,6 @@ import { DayClickEventHandler, ModifierStatus, SelectMode } from '../../types'; import { DateRange } from '../../types/DateRange'; import { addToRange } from './utils/addToRange'; - -export type RangeSelectionHandler = (day: Date) => void; export type UseRangeSelect = { selected: DateRange | undefined; @@ -12,7 +10,7 @@ reset: () => void; }; -export type UseRangeCallback = ( +export type RangeSelectionHandler = ( range: DateRange | undefined, day: Date, modifiers: ModifierStatus, @@ -24,7 +22,7 @@ mode: SelectMode, defaultValue?: unknown, required = false, - callback?: UseRangeCallback + callback?: RangeSelectionHandler ): UseRangeSelect { const initialValue = mode === 'range' && defaultValue ? (defaultValue as DateRange) : undefined;
e78f36a609c9177e36fdd4e28a103acd422b4627
v1/index.d.ts
v1/index.d.ts
/** * CloudEvent class definition */ export class Cloudevent { public constructor(spec?: any, formatter?: any); public format(): any; public toString(): string; public id(id: string): Cloudevent; public getId(): string; public source(source: string): Cloudevent; public getSource(): string; public getSpecversion(): string; public type(type: string): Cloudevent; public getType(): string; public dataContentType(dct: string): Cloudevent; public getDataContentType(): string; public dataschema(schema: string): Cloudevent; public getDataschema(): string; public subject(subject: string): Cloudevent; public getSubject(): string; public time(time: Date): Cloudevent; public getTime(): Date; public data(data: any): Cloudevent; public getData(): any; } /** * HTTP emitter for Structured mode */ export class StructuredHTTPEmitter { public constructor(configuration?: any); public emit(event: Cloudevent): Promise; } /** * Function to create CloudEvents instances */ export declare function event(): Cloudevent; export default Cloudevent;
/** * CloudEvent class definition */ export class Cloudevent { public constructor(spec?: any, formatter?: any); public format(): any; public toString(): string; public id(id: string): Cloudevent; public getId(): string; public source(source: string): Cloudevent; public getSource(): string; public getSpecversion(): string; public type(type: string): Cloudevent; public getType(): string; public dataContentType(dct: string): Cloudevent; public getDataContentType(): string; public dataschema(schema: string): Cloudevent; public getDataschema(): string; public subject(subject: string): Cloudevent; public getSubject(): string; public time(time: Date): Cloudevent; public getTime(): Date; public data(data: any): Cloudevent; public getData(): any; } /** * HTTP emitter for Structured mode */ export class StructuredHTTPEmitter { public constructor(configuration?: any); public emit(event: Cloudevent): Promise<any>; } /** * Function to create CloudEvents instances */ export declare function event(): Cloudevent; export default Cloudevent;
Fix return type of emit to use generics
Fix return type of emit to use generics Signed-off-by: Fabio José <34f3a7e4e4d9fe971c99ebc4af947a5309eca653@gmail.com>
TypeScript
apache-2.0
cloudevents/sdk-javascript,cloudevents/sdk-javascript
--- +++ @@ -40,7 +40,7 @@ export class StructuredHTTPEmitter { public constructor(configuration?: any); - public emit(event: Cloudevent): Promise; + public emit(event: Cloudevent): Promise<any>; } /**
1db4c94d12009e0382cf195bb734348d74f4bdb8
src/smc-webapp/frame-editors/rmd-editor/actions.ts
src/smc-webapp/frame-editors/rmd-editor/actions.ts
/* R Markdown Editor Actions */ import { Actions } from "../markdown-editor/actions"; import { convert } from "./rmd2md"; import { FrameTree } from "../frame-tree/types"; export class RmdActions extends Actions { _init2(): void { if (!this.is_public) { // one extra thing after markdown. this._init_rmd2md(); } } _init_rmd2md(): void { this._syncstring.on("save-to-disk", () => this._run_rmd2md()); this._run_rmd2md(); } async _run_rmd2md(time?: number): Promise<void> { // TODO: should only run knitr if at least one frame is visible showing preview? // maybe not, since might want to show error. this.set_status("Running knitr..."); let markdown: string; try { markdown = await convert(this.project_id, this.path, time); } catch (err) { this.set_error(err); return; } finally { this.set_status(""); } this.setState({ content: markdown }); } _raw_default_frame_tree(): FrameTree { if (this.is_public) { return { type: "cm" }; } else { return { direction: "col", type: "node", first: { type: "cm" }, second: { type: "markdown" } }; } } }
/* R Markdown Editor Actions */ import { Actions } from "../markdown-editor/actions"; import { convert } from "./rmd2md"; import { FrameTree } from "../frame-tree/types"; export class RmdActions extends Actions { _init2(): void { if (!this.is_public) { // one extra thing after markdown. this._init_rmd2md(); } } _init_rmd2md(): void { this._syncstring.on("save-to-disk", () => this._run_rmd2md()); this._run_rmd2md(); } async _run_rmd2md(time?: number): Promise<void> { // TODO: should only run knitr if at least one frame is visible showing preview? // maybe not, since might want to show error. this.set_status("Running knitr..."); let markdown: string; try { markdown = await convert(this.project_id, this.path, time); } catch (err) { this.set_error(err); return; } finally { this.set_status(""); } this.setState({ value: markdown }); } _raw_default_frame_tree(): FrameTree { if (this.is_public) { return { type: "cm" }; } else { return { direction: "col", type: "node", first: { type: "cm" }, second: { type: "markdown" } }; } } }
Fix instance of content not converted to value
Fix instance of content not converted to value
TypeScript
agpl-3.0
tscholl2/smc,sagemathinc/smc,DrXyzzy/smc,sagemathinc/smc,tscholl2/smc,sagemathinc/smc,sagemathinc/smc,DrXyzzy/smc,tscholl2/smc,tscholl2/smc,tscholl2/smc,DrXyzzy/smc,DrXyzzy/smc
--- +++ @@ -32,7 +32,7 @@ } finally { this.set_status(""); } - this.setState({ content: markdown }); + this.setState({ value: markdown }); } _raw_default_frame_tree(): FrameTree {
5036ac71a5856b870801a4f7c698c55a7e469682
src/components/Router.tsx
src/components/Router.tsx
import React from 'react' import NotePage from './NotePage' import { useRouteParams } from '../lib/router' import { StyledNotFoundPage } from './styled' export default () => { const routeParams = useRouteParams() switch (routeParams.name) { case 'storages.notes': return <NotePage /> } return ( <StyledNotFoundPage> <h1>Page not found</h1> <p>Check the URL or click other link in the left side navigation.</p> </StyledNotFoundPage> ) }
import React from 'react' import NotePage from './NotePage' import { useRouteParams } from '../lib/router' import { StyledNotFoundPage } from './styled' export default () => { const routeParams = useRouteParams() switch (routeParams.name) { case 'storages.allNotes': case 'storages.notes': case 'storages.trashCan': case 'storages.tags.show': return <NotePage /> } return ( <StyledNotFoundPage> <h1>Page not found</h1> <p>Check the URL or click other link in the left side navigation.</p> </StyledNotFoundPage> ) }
Use NotePage for other routes
Use NotePage for other routes
TypeScript
mit
Sarah-Seo/Inpad,Sarah-Seo/Inpad
--- +++ @@ -6,7 +6,10 @@ export default () => { const routeParams = useRouteParams() switch (routeParams.name) { + case 'storages.allNotes': case 'storages.notes': + case 'storages.trashCan': + case 'storages.tags.show': return <NotePage /> } return (
72635008fd6e6fcd9599d516ff73812893ac4120
app/src/cors.ts
app/src/cors.ts
/**  * @file CORS middleware  * @author Dave Ross <dave@davidmichaelross.com>  */ import { Application, Request, Response } from "polka" export default function corsAllowAll(server: Application) { server.use("/*", function (req: Request, res: Response, next: Function) { res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS' ) res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') if (req.method === 'OPTIONS') { res.statusCode = 200 res.end() } else { next() } }); }
/**  * @file CORS middleware  * @author Dave Ross <dave@davidmichaelross.com>  */ import { Application, Request, Response } from "polka" export default function corsAllowAll(server: Application) { server.use("*", function (req: Request, res: Response, next: Function) { res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS' ) res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') if (req.method === 'OPTIONS') { res.statusCode = 200 res.end() } else { next() } }); }
Apply CORS to all API URLs
Apply CORS to all API URLs
TypeScript
mit
daveross/catalogopolis-api,daveross/catalogopolis-api
--- +++ @@ -7,7 +7,7 @@ export default function corsAllowAll(server: Application) { - server.use("/*", function (req: Request, res: Response, next: Function) { + server.use("*", function (req: Request, res: Response, next: Function) { res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS' ) res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
1ae8d70fff30e038968bdbf89c188260faf57efd
packages/view/src/br.ts
packages/view/src/br.ts
import { Paper } from "./paper"; // Determines if a <br> in the editable area is part of the document or a doorstop at the end of a block. export function isBRPlaceholder(paper: Paper, node: Node) { if (node.nodeName !== 'BR') return false; return isLastNode(paper, node); } // Check if this is the last node (not counting empty text nodes) function isLastNode(paper: Paper, node: Node) { let next = node.nextSibling; while (next && next.nodeValue === '') next = next.nextSibling; if (next) return false; return !node.parentNode || paper.blocks.matches(node.parentNode as Element) ? true : isLastNode(paper, node.parentNode); }
import { Paper } from "./paper"; // Determines if a <br> in the editable area is part of the document or a doorstop at the end of a block. export function isBRPlaceholder(paper: Paper, node: Node) { if (node.nodeName !== 'BR') return false; return isLastNode(paper, node); } // Check if this is the last node (not counting empty text nodes) function isLastNode(paper: Paper, node: Node) { let next = node.nextSibling; while (next && next.nodeValue === '') next = next.nextSibling; if (next) { if (next.nodeType === Node.ELEMENT_NODE) { return paper.blocks.matches(next as Element) || next.firstChild?.nodeType === Node.ELEMENT_NODE && paper.blocks.matches(next.firstChild as Element); } } return !node.parentNode || paper.blocks.matches(node.parentNode as Element) ? true : isLastNode(paper, node.parentNode); }
Fix selection-off issue with trailing BRs in lists
Fix selection-off issue with trailing BRs in lists
TypeScript
mit
jacwright/typewriter,jacwright/typewriter
--- +++ @@ -10,6 +10,10 @@ function isLastNode(paper: Paper, node: Node) { let next = node.nextSibling; while (next && next.nodeValue === '') next = next.nextSibling; - if (next) return false; + if (next) { + if (next.nodeType === Node.ELEMENT_NODE) { + return paper.blocks.matches(next as Element) || next.firstChild?.nodeType === Node.ELEMENT_NODE && paper.blocks.matches(next.firstChild as Element); + } + } return !node.parentNode || paper.blocks.matches(node.parentNode as Element) ? true : isLastNode(paper, node.parentNode); }
43c897bd040705566b1822dc2b434c743086a99c
lib/adapters/AS2TextFieldAdapter.ts
lib/adapters/AS2TextFieldAdapter.ts
import TextFieldAdapter = require("awayjs-player/lib/adapters/TextFieldAdapter"); import AdaptedTextField = require("awayjs-player/lib/display/AdaptedTextField"); class AS2TextFieldAdapter implements TextFieldAdapter { private _adaptee:AdaptedTextField; private _embedFonts : boolean; constructor(adaptee : AdaptedTextField) { // create an empty text field if none is passed this._adaptee = adaptee || new AdaptedTextField(); } get adaptee() : AdaptedTextField { return this._adaptee; } clone(newAdaptee:AdaptedTextField):TextFieldAdapter { return new AS2TextFieldAdapter(newAdaptee); } get embedFonts() : boolean { return this._embedFonts; } set embedFonts(value:boolean) { this._embedFonts = value; } get text():boolean { return this._adaptee.text; } set text(value:string) { this._adaptee.text = value; } } export = AS2TextFieldAdapter;
import TextFieldAdapter = require("awayjs-player/lib/adapters/TextFieldAdapter"); import AdaptedTextField = require("awayjs-player/lib/display/AdaptedTextField"); class AS2TextFieldAdapter implements TextFieldAdapter { private _adaptee:AdaptedTextField; private _embedFonts : boolean; constructor(adaptee : AdaptedTextField) { // create an empty text field if none is passed this._adaptee = adaptee || new AdaptedTextField(); } get adaptee() : AdaptedTextField { return this._adaptee; } clone(newAdaptee:AdaptedTextField):TextFieldAdapter { return new AS2TextFieldAdapter(newAdaptee); } get embedFonts() : boolean { return this._embedFonts; } set embedFonts(value:boolean) { this._embedFonts = value; } get text():string { return this._adaptee.text; } set text(value:string) { this._adaptee.text = value; } } export = AS2TextFieldAdapter;
Fix access types TextField adapter
Fix access types TextField adapter
TypeScript
apache-2.0
awayjs/awayjs-player,awayjs/awayjs-player,awayjs/awayjs-player
--- +++ @@ -32,7 +32,7 @@ this._embedFonts = value; } - get text():boolean + get text():string { return this._adaptee.text; }
9825b786ee83d5fa9b0e5d49f3e1565fa68dc8c4
source/lib/stoprint/errors.ts
source/lib/stoprint/errors.ts
import {Alert} from 'react-native' export const showGeneralError = (onDismiss: () => any) => { Alert.alert( 'An unexpected error occurred', "We're sorry, but we have lost communication with Papercut. Please try again.", [{text: 'OK', onPress: onDismiss}], ) }
import {Alert} from 'react-native' export const showGeneralError = (onDismiss: () => any): void => { Alert.alert( 'An unexpected error occurred', "We're sorry, but we have lost communication with Papercut. Please try again.", [{text: 'OK', onPress: onDismiss}], ) }
Add return types on boundary functions
l/stoprint: Add return types on boundary functions Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
TypeScript
agpl-3.0
StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native
--- +++ @@ -1,6 +1,6 @@ import {Alert} from 'react-native' -export const showGeneralError = (onDismiss: () => any) => { +export const showGeneralError = (onDismiss: () => any): void => { Alert.alert( 'An unexpected error occurred', "We're sorry, but we have lost communication with Papercut. Please try again.",
eba587272e84e65507ac3491f17cc16a873081f4
src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular-ui/src/lib/configuration.ts
src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular-ui/src/lib/configuration.ts
import { InjectionToken } from '@angular/core'; export interface ConfigActions { [key: string]: boolean } export interface PictureparkUIConfiguration { 'ContentBrowserComponent': ConfigActions, 'BasketComponent': ConfigActions } export const PICTUREPARK_UI_CONFIGURATION = new InjectionToken<string>('PICTUREPARK_UI_CONFIGURATION'); export function PictureparkUIConfigurationFactory() { return<PictureparkUIConfiguration> { 'ContentBrowserComponent': { select: true, downloadContent: true, shareContent: true }, 'BasketComponent': { downloadContent: true, shareContent: true } } }
import { InjectionToken } from '@angular/core'; export interface ConfigActions { [key: string]: boolean } export interface PictureparkUIConfiguration { 'ContentBrowserComponent': ConfigActions, 'BasketComponent': ConfigActions } export const PICTUREPARK_UI_CONFIGURATION = new InjectionToken<string>('PICTUREPARK_UI_CONFIGURATION'); export function PictureparkUIConfigurationFactory() { return<PictureparkUIConfiguration> { 'ContentBrowserComponent': { select: true, downloadContent: true, shareContent: true }, 'BasketComponent': { downloadContent: true, shareContent: true } } }
Make action button configurable implementation
PP9-8544: Make action button configurable implementation
TypeScript
mit
Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript
--- +++ @@ -10,6 +10,7 @@ } export const PICTUREPARK_UI_CONFIGURATION = new InjectionToken<string>('PICTUREPARK_UI_CONFIGURATION'); + export function PictureparkUIConfigurationFactory() { return<PictureparkUIConfiguration> { 'ContentBrowserComponent': {
3d95072fb4786ce10a70e69229214b18b898a497
app/src/components/tree/tree.service.spec.ts
app/src/components/tree/tree.service.spec.ts
/// <reference path="../../../../typings/jasmine/jasmine.d.ts" /> /// <reference path="../../../../typings/angularjs/angular-mocks.d.ts" /> 'use strict'; describe('app.tree.TreeService', () => { var treeService : app.tree.TreeService; beforeEach(angular.mock.module('app.tree')); beforeEach(inject(($injector) => { treeService = $injector.get('TreeService'); })); it('should be able to return elements via id', () => { //expect(treeService.getElement(1)).toBeDefined(); //expect(treeService.getElement(1)).toEqual(new app.tree.TreeElement(1, app.tree.TreeElementType.Button, [])) }) });
/// <reference path="../../../../typings/jasmine/jasmine.d.ts" /> /// <reference path="../../../../typings/angularjs/angular-mocks.d.ts" /> 'use strict'; describe('app.tree.TreeService', () => { var treeService : app.tree.TreeService; beforeEach(angular.mock.module('app.tree')); beforeEach(inject(($injector) => { treeService = $injector.get('TreeService'); })); /*it('should be able to return elements via id', () => { //expect(treeService.getElement(1)).toBeDefined(); //expect(treeService.getElement(1)).toEqual(new app.tree.TreeElement(1, app.tree.TreeElementType.Button, [])) })*/ });
Change test, it was not working
Change test, it was not working
TypeScript
mit
pancho111203/JsonFormsEditor,eclipsesource/JsonFormsEditor,pancho111203/JsonFormsEditor,eclipsesource/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,pancho111203/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,pancho111203/JsonFormsEditor,eclipsesource/JsonFormsEditor,eclipsesource/JsonFormsEditor
--- +++ @@ -13,8 +13,8 @@ })); - it('should be able to return elements via id', () => { + /*it('should be able to return elements via id', () => { //expect(treeService.getElement(1)).toBeDefined(); //expect(treeService.getElement(1)).toEqual(new app.tree.TreeElement(1, app.tree.TreeElementType.Button, [])) - }) + })*/ });
b233d0261c89dbf08d939100b01e3684e1e78986
src/app/model/DataControl.ts
src/app/model/DataControl.ts
export class DataControl { sortBy = 'id'; order = 'ascending'; pageSize = 10; page = 1; }
export class DataControl { sortBy = ''; order = 'ascending'; pageSize = 10; page = 1; }
Set default sort by Relevance instead of accession
Set default sort by Relevance instead of accession
TypeScript
unknown
BD2K-DDI/ddi-web-app,OmicsDI/ddi-web-app,OmicsDI/ddi-web-app,OmicsDI/ddi-web-app,BD2K-DDI/ddi-web-app
--- +++ @@ -1,5 +1,5 @@ export class DataControl { - sortBy = 'id'; + sortBy = ''; order = 'ascending'; pageSize = 10; page = 1;
fe52083cf376a9a495f85659de2b29d805992c40
src/components/StageInfo.tsx
src/components/StageInfo.tsx
// Cleanup CSS! import '../App.css'; import { Component } from 'react'; import * as React from 'react'; export default class StageInfo extends Component<any, any> { constructor(props: any, context: any) { super(props, context); } render() { const numSelected = this.props.cards.filter( (c: any) => c.mark == this.props.stage).length; const needed = this.props.cardsNeeded[this.props.stage] let button = null if (numSelected == needed) { button = <span onClick={(e: any) => { e.stopPropagation(); this.props.onAdvanceStage(this.props.stage)} } style={{ paddingLeft: '10px', cursor: 'pointer' }}> Advance </span> } return ( <h1 className="instructions"> <span style={{paddingRight: '10px'}} key={'Round_' + this.props.stage}>Round {this.props.stage} </span> Select the things you value the most: <span className="progress"> <span className="number-selected" key={numSelected}>{numSelected}</span> / {needed} </span> {button != null? button: null} </h1> ); } }
import './StageInfo.css'; import { Component } from 'react'; import * as React from 'react'; export default class StageInfo extends Component<any, any> { constructor(props: any, context: any) { super(props, context); } render() { const numSelected = this.props.cards.filter( (c: any) => c.mark == this.props.stage).length; const needed = this.props.cardsNeeded[this.props.stage] let button = null if (numSelected == needed) { button = <span onClick={(e: any) => { e.stopPropagation(); this.props.onAdvanceStage(this.props.stage)} } style={{ paddingLeft: '10px', cursor: 'pointer' }}> Advance </span> } return ( <h1 className="instructions"> <span style={{paddingRight: '10px'}} key={'Round_' + this.props.stage}>Round {this.props.stage} </span> Select the things you value the most: <span className="progress"> <span className="number-selected" key={numSelected}>{numSelected}</span> / {needed} </span> {button != null? button: null} </h1> ); } }
Fix bug in CSS import
Fix bug in CSS import
TypeScript
apache-2.0
flubstep/engvalues,flubstep/engvalues,flubstep/engvalues
--- +++ @@ -1,5 +1,4 @@ -// Cleanup CSS! -import '../App.css'; +import './StageInfo.css'; import { Component } from 'react'; import * as React from 'react';
be078ecf5994ddd4a2c66b7d05998d6a9953a88b
packages/most-nth/src/most-nth.d.ts
packages/most-nth/src/most-nth.d.ts
import { Stream } from 'most'; export function nth<T>(index: number): (stream: Stream<T>) => Promise<T>; export function first<T>(stream: Stream<T>): Promise<T>; export function last<T>(stream: Stream<T>): Promise<T>;
import { Stream } from 'most'; export function nth<T>(index: number): (stream: Stream<T>) => Promise<T | undefined>; export function first<T>(stream: Stream<T>): Promise<T | undefined>; export function last<T>(stream: Stream<T>): Promise<T | undefined>;
Fix the resolve type of most-nth functions
Fix the resolve type of most-nth functions
TypeScript
bsd-3-clause
craft-ai/most-utils,craft-ai/most-utils
--- +++ @@ -1,5 +1,5 @@ import { Stream } from 'most'; -export function nth<T>(index: number): (stream: Stream<T>) => Promise<T>; -export function first<T>(stream: Stream<T>): Promise<T>; -export function last<T>(stream: Stream<T>): Promise<T>; +export function nth<T>(index: number): (stream: Stream<T>) => Promise<T | undefined>; +export function first<T>(stream: Stream<T>): Promise<T | undefined>; +export function last<T>(stream: Stream<T>): Promise<T | undefined>;
ed674d727942e7219c7f413afa7d73ef23e298d2
types/storybook-addon-jsx/index.d.ts
types/storybook-addon-jsx/index.d.ts
// Type definitions for storybook-addon-jsx 5.4 // Project: https://github.com/storybooks/storybook // Definitions by: James Newell <https://github.com/jameslnewell> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import '@storybook/react'; import { ReactNode, ReactElement } from 'react'; type displayNameFunc<T> = (element: ReactElement<T>) => string; declare module '@storybook/react' { interface Options { skip?: number; enableBeautify?: boolean; onBeforeRender?: (domString: string) => string; displayName?: string | displayNameFunc; } interface Story { addWithJSX(kind: string, fn: () => ReactNode, options?: Options): Story; } }
// Type definitions for storybook-addon-jsx 5.4 // Project: https://github.com/storybooks/storybook // Definitions by: James Newell <https://github.com/jameslnewell> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import '@storybook/react'; import { ReactNode, ReactElement } from 'react'; type displayNameFunc = (element: ReactElement<any>) => string; declare module '@storybook/react' { interface Options { skip?: number; enableBeautify?: boolean; onBeforeRender?: (domString: string) => string; displayName?: string | displayNameFunc; } interface Story { addWithJSX(kind: string, fn: () => ReactNode, options?: Options): Story; } }
Replace type for props with unknown
Replace type for props with unknown Otherwise, you need to pass a type T to `Options` first in order to get that type in `displayNameFunc`, which is overkill.
TypeScript
mit
georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped
--- +++ @@ -7,7 +7,7 @@ import '@storybook/react'; import { ReactNode, ReactElement } from 'react'; -type displayNameFunc<T> = (element: ReactElement<T>) => string; +type displayNameFunc = (element: ReactElement<any>) => string; declare module '@storybook/react' { interface Options {
303c87cbad1e2e8766ad1ffbf8639697351c9ab3
src/app/pages/menu/menu.component.ts
src/app/pages/menu/menu.component.ts
import { Component } from '@angular/core'; import { AppState } from '../../app.service'; @Component({ selector: 'menu', styleUrls: ['./menu-components.scss'], templateUrl: './menu.components.html' }) export class MenuComponent { constructor( private appState: AppState ) {} public toProjects() { console.log('to projects'); } public toParents() { console.log('to parents'); } public tostudents() { console.log('to students'); } public picture() { const user = this.appState.get('user'); return user && user.picture ? user.picture : ''; } }
import { Component } from '@angular/core'; import { AppState } from '../../app.service'; const profileTransforms = 'c_fill,g_face,h_200,q_auto:best,r_max,w_200' const defaultPictureUrl = `http://res.cloudinary.com/wagoid/image/upload/${profileTransforms}/empty-profile_h8q7mo.png`; @Component({ selector: 'menu', styleUrls: ['./menu-components.scss'], templateUrl: './menu.components.html' }) export class MenuComponent { constructor( private appState: AppState ) {} public toProjects() { console.log('to projects'); } public toParents() { console.log('to parents'); } public tostudents() { console.log('to students'); } public picture() { const user = this.appState.get('user'); return user && user.picture ? user.picture : defaultPictureUrl; } }
Add default profile picture url
Add default profile picture url
TypeScript
mit
gcriva/gcriva-frontend,gcriva/gcriva-frontend,gcriva/gcriva-frontend,gcriva/gcriva-frontend
--- +++ @@ -1,5 +1,9 @@ import { Component } from '@angular/core'; import { AppState } from '../../app.service'; + +const profileTransforms = 'c_fill,g_face,h_200,q_auto:best,r_max,w_200' +const defaultPictureUrl = + `http://res.cloudinary.com/wagoid/image/upload/${profileTransforms}/empty-profile_h8q7mo.png`; @Component({ selector: 'menu', @@ -26,6 +30,6 @@ public picture() { const user = this.appState.get('user'); - return user && user.picture ? user.picture : ''; + return user && user.picture ? user.picture : defaultPictureUrl; } }
4b18946ca75f00a897a23274ff72a5a89a048169
app/test/unit/commit-identity-test.ts
app/test/unit/commit-identity-test.ts
import * as chai from 'chai' const expect = chai.expect import { CommitIdentity } from '../../src/models/commit-identity' describe('CommitIdentity', () => { describe('#parseIdent', () => { it('understands a normal ident string', () => { const identity = CommitIdentity.parseIdentity('Markus Olsson <markus@github.com> 1475670580 +0200') expect(identity).not.to.be.null expect(identity!.name).to.equal('Markus Olsson') expect(identity!.email).to.equal('markus@github.com') }) it('parses even if the email address isn\'t a normal email', () => { const identity = CommitIdentity.parseIdentity('Markus Olsson <Markus Olsson> 1475670580 +0200') expect(identity).not.to.be.null expect(identity!.name).to.equal('Markus Olsson') expect(identity!.email).to.equal('Markus Olsson') }) }) })
import { expect, use as chaiUse } from 'chai' chaiUse(require('chai-datetime')) import { CommitIdentity } from '../../src/models/commit-identity' describe('CommitIdentity', () => { describe('#parseIdent', () => { it('understands a normal ident string', () => { const identity = CommitIdentity.parseIdentity('Markus Olsson <markus@github.com> 1475670580 +0200') expect(identity).not.to.be.null expect(identity!.name).to.equal('Markus Olsson') expect(identity!.email).to.equal('markus@github.com') expect(identity!.date).to.equalTime(new Date('2016-10-05T12:29:40.000Z')) }) }) it('parses even if the email address isn\'t a normal email', () => { const identity = CommitIdentity.parseIdentity('Markus Olsson <Markus Olsson> 1475670580 +0200') expect(identity).not.to.be.null expect(identity!.name).to.equal('Markus Olsson') expect(identity!.email).to.equal('Markus Olsson') }) }) })
Add test for date parsing
Add test for date parsing
TypeScript
mit
kactus-io/kactus,BugTesterTest/desktops,gengjiawen/desktop,artivilla/desktop,artivilla/desktop,BugTesterTest/desktops,kactus-io/kactus,kactus-io/kactus,say25/desktop,gengjiawen/desktop,BugTesterTest/desktops,hjobrien/desktop,hjobrien/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,say25/desktop,say25/desktop,kactus-io/kactus,BugTesterTest/desktops,shiftkey/desktop,gengjiawen/desktop,j-f1/forked-desktop,shiftkey/desktop,gengjiawen/desktop,hjobrien/desktop,j-f1/forked-desktop,hjobrien/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop
--- +++ @@ -1,5 +1,6 @@ -import * as chai from 'chai' -const expect = chai.expect +import { expect, use as chaiUse } from 'chai' + +chaiUse(require('chai-datetime')) import { CommitIdentity } from '../../src/models/commit-identity' @@ -11,6 +12,8 @@ expect(identity!.name).to.equal('Markus Olsson') expect(identity!.email).to.equal('markus@github.com') + expect(identity!.date).to.equalTime(new Date('2016-10-05T12:29:40.000Z')) + }) }) it('parses even if the email address isn\'t a normal email', () => {
1a5fc941ce53a3e192a388b0caa65922078e96e4
packages/next/build/babel/plugins/commonjs.ts
packages/next/build/babel/plugins/commonjs.ts
import {PluginObj} from '@babel/core' import {NodePath} from '@babel/traverse' import {Program} from '@babel/types' import commonjsPlugin from '@babel/plugin-transform-modules-commonjs' // Rewrite imports using next/<something> to next-server/<something> export default function NextToNextServer (...args: any): PluginObj { const commonjs = commonjsPlugin(...args) return { visitor: { Program: { exit (path: NodePath<Program>, state) { let foundModuleExports = false path.traverse({ MemberExpression ( path: any ) { if (path.node.object.name !== 'module') return if (path.node.property.name !== 'exports') return foundModuleExports = true console.log('FOUND', state.file.opts.filename) } }) if (!foundModuleExports) { console.log('NOT FOUND', state.file.opts.filename) return } commonjs.visitor.Program.exit.call(this, path, state) } } } } }
import {PluginObj} from '@babel/core' import {NodePath} from '@babel/traverse' import {Program} from '@babel/types' import commonjsPlugin from '@babel/plugin-transform-modules-commonjs' // Rewrite imports using next/<something> to next-server/<something> export default function NextToNextServer (...args: any): PluginObj { const commonjs = commonjsPlugin(...args) return { visitor: { Program: { exit (path: NodePath<Program>, state) { let foundModuleExports = false path.traverse({ MemberExpression ( path: any ) { if (path.node.object.name !== 'module') return if (path.node.property.name !== 'exports') return foundModuleExports = true } }) if (!foundModuleExports) { return } commonjs.visitor.Program.exit.call(this, path, state) } } } } }
Remove console.log after verifying the correct files are ignored
Remove console.log after verifying the correct files are ignored
TypeScript
mit
flybayer/next.js,zeit/next.js,JeromeFitz/next.js,BlancheXu/test,BlancheXu/test,azukaru/next.js,JeromeFitz/next.js,JeromeFitz/next.js,BlancheXu/test,zeit/next.js,azukaru/next.js,azukaru/next.js,azukaru/next.js,zeit/next.js,flybayer/next.js,flybayer/next.js,flybayer/next.js,JeromeFitz/next.js
--- +++ @@ -17,12 +17,10 @@ if (path.node.object.name !== 'module') return if (path.node.property.name !== 'exports') return foundModuleExports = true - console.log('FOUND', state.file.opts.filename) } }) if (!foundModuleExports) { - console.log('NOT FOUND', state.file.opts.filename) return }
5c02770c93ed19355e9f5661c9a89fa6c4fbc18d
src/util.ts
src/util.ts
import * as path from "path"; import * as glob from "glob"; let _posixifyRegExp = new RegExp("\\\\", "g"); export function posixify(path:string) { return path.replace(_posixifyRegExp, "/"); } export function copy<T extends {}>(obj:T):T { let neue:T = {} as T; for(let key in obj) { neue[key] = obj[key]; } return neue; } export function findPrograms(workspacePath:string) { let programFiles:string[] = []; for(let filepath of glob.sync(workspacePath + "/*.js")) { programFiles.push(posixify(filepath)); } return programFiles; } export function findWatchers(watcherPaths:string[], relative = false) { let watcherFiles:string[] = []; for(let watcherPath of watcherPaths) { for(let filepath of glob.sync(watcherPath + "/**/*.js")) { if(filepath === __filename) continue; if(relative) filepath = path.relative(watcherPath, filepath); watcherFiles.push(posixify(filepath)); } } return watcherFiles; } export function escapeSingleQuotes(str:string) { return str.replace("'", "\\'"); }
import * as path from "path"; import * as glob from "glob"; let _posixifyRegExp = new RegExp("\\\\", "g"); export function posixify(path:string) { return path.replace(_posixifyRegExp, "/"); } export function copy<T extends {}>(obj:T):T { let neue:T = {} as T; for(let key in obj) { neue[key] = obj[key]; } return neue; } export function findPrograms(workspacePath:string) { let programFiles:string[] = []; for(let filepath of glob.sync(workspacePath + "/*.js")) { programFiles.push(posixify(filepath)); } return programFiles; } export function findWatchers(watcherPaths:string[], relative = false) { let watcherFiles:string[] = []; for(let watcherPath of watcherPaths) { for(let filepath of glob.sync(watcherPath + "/**/*.js")) { if(filepath === __filename) continue; if(relative) filepath = path.relative(watcherPath, filepath); watcherFiles.push(posixify(filepath)); } } return watcherFiles; } export function escapeSingleQuotes(str:string) { return str.replace(/'/gm, "\\'"); }
Fix incomplete escaping of single quotes
Fix incomplete escaping of single quotes
TypeScript
apache-2.0
witheve/eve-starter,witheve/eve-starter,witheve/eve-starter
--- +++ @@ -35,5 +35,5 @@ } export function escapeSingleQuotes(str:string) { - return str.replace("'", "\\'"); + return str.replace(/'/gm, "\\'"); }
c4b7c26605b8678783e45d4b97673f37679a15d5
src/frontend/launcherComponent/src/app/core/service/navbar-service/navbar.service.ts
src/frontend/launcherComponent/src/app/core/service/navbar-service/navbar.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '../../../../environments/environment'; import { catchError, map, retry } from 'rxjs/operators'; import { handleError } from '../../../shared/helper/handleError'; import { AppSettings } from '../../../shared/interface/app-settings.interface'; import { Observable } from 'rxjs'; const API_URL_NAVBAR = environment.apiUrl.navbar; @Injectable() export class NavbarService { constructor(private http: HttpClient) { } getNavbar(): Observable<any> { return this.http.get<AppSettings>(API_URL_NAVBAR).pipe( map( data => { data.tipologie.map( tipologia => { tipologia.codiceDescrizione = `${tipologia.descrizione} (${tipologia.codice})`; }); }), retry(3), catchError(handleError) ); } }
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '../../../../environments/environment'; import { catchError, map, retry } from 'rxjs/operators'; import { handleError } from '../../../shared/helper/handleError'; import { AppSettings } from '../../../shared/interface/app-settings.interface'; import { Observable } from 'rxjs'; const API_URL_NAVBAR = environment.apiUrl.navbar; @Injectable() export class NavbarService { constructor(private http: HttpClient) { } getNavbar(): Observable<any> { return this.http.get<AppSettings>(API_URL_NAVBAR).pipe( map((data: AppSettings) => { const result = data; result.tipologie.map(tipologia => { tipologia.codiceDescrizione = `${tipologia.descrizione} (${tipologia.codice})`; }); return result; }), retry(3), catchError(handleError) ); } }
Fix mapper AppSettings di Navbar
Fix mapper AppSettings di Navbar
TypeScript
agpl-3.0
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
--- +++ @@ -17,10 +17,12 @@ getNavbar(): Observable<any> { return this.http.get<AppSettings>(API_URL_NAVBAR).pipe( - map( data => { - data.tipologie.map( tipologia => { + map((data: AppSettings) => { + const result = data; + result.tipologie.map(tipologia => { tipologia.codiceDescrizione = `${tipologia.descrizione} (${tipologia.codice})`; }); + return result; }), retry(3), catchError(handleError)
bf9d4f7379547c5058c594ef495243d61d2001ec
src/utils/fetch-data.ts
src/utils/fetch-data.ts
import * as fetch from 'isomorphic-fetch' export default async (endpoint: string): Promise<Record<string, unknown> | Record<string, unknown>[]> => { const response = await fetch(`https://data.police.uk/api${endpoint}`) return response.json() }
import * as fetch from 'isomorphic-fetch' // eslint-disable-next-line @typescript-eslint/no-explicit-any export default async (endpoint: string): Promise<any> => { const response = await fetch(`https://data.police.uk/api${endpoint}`) return response.json() }
Revert "fix fetch data result type"
Revert "fix fetch data result type" This reverts commit 6a6e2dd3093d69e932a1abf793c79a53f7d6c69a.
TypeScript
mit
AlexChesters/ukpd,AlexChesters/ukpd,AlexChesters/ukpd
--- +++ @@ -1,6 +1,7 @@ import * as fetch from 'isomorphic-fetch' -export default async (endpoint: string): Promise<Record<string, unknown> | Record<string, unknown>[]> => { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export default async (endpoint: string): Promise<any> => { const response = await fetch(`https://data.police.uk/api${endpoint}`) return response.json() }
054461ab62456ed59800f27b42bd7a527d40449c
app/app.component.ts
app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<h1>{{title}}</h1><h2>{{hero}} details!</h2>' }) export class AppComponent { title = 'Tour of Heroes'; hero = 'Windstorm'; }
import { Component } from '@angular/core'; export class Hero { id: number; name: string; } @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: 1, name: 'Windstorm' }; }
Add Hero class and update AppComponent template to use ES2015 string template
Add Hero class and update AppComponent template to use ES2015 string template
TypeScript
mit
jjhampton/angular2-tour-of-heroes,jjhampton/angular2-tour-of-heroes,jjhampton/angular2-tour-of-heroes
--- +++ @@ -1,10 +1,24 @@ import { Component } from '@angular/core'; + +export class Hero { + id: number; + name: string; +} @Component({ selector: 'my-app', - template: '<h1>{{title}}</h1><h2>{{hero}} details!</h2>' + 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 = 'Windstorm'; + hero: Hero = { + id: 1, + name: 'Windstorm' + }; }
51a4a7f7e13e5cac17c0e4f960542a81f74dba40
src/components/global-style/global-style.tsx
src/components/global-style/global-style.tsx
import { Component, Prop, State, Element, Watch, } from '@stencil/core'; @Component({ tag: 'c-global-style', styleUrl: 'global-style.scss', }) export class GlobalStyle { @Prop({ context: 'store' }) ContextStore: any; /** Per default, this will inherit the value from c-theme name property */ @Prop({ mutable: true }) theme: string; @State() store: any; @State() tagName: string; @State() currentTheme: object; @Element() el: HTMLElement; @Watch('theme') setTheme(name = undefined) { this.theme = name || this.store.getState().theme.name; this.currentTheme = this.store.getState().themes[this.theme]; } async loadLibs() { await import('jquery'); await import('bootstrap'); } componentWillLoad() { this.loadLibs(); this.store = this.ContextStore || (window as any).CorporateUi.store; this.setTheme(this.theme); this.store.subscribe(() => this.setTheme()); } componentDidLoad() { this.tagName = this.el.nodeName.toLowerCase(); } render() { return this.currentTheme ? <style>{ this.currentTheme[this.tagName] }</style> : ''; } }
import { Component, Prop, State, Element, Watch, } from '@stencil/core'; @Component({ tag: 'c-global-style', styleUrl: 'global-style.scss', }) export class GlobalStyle { @Prop({ context: 'store' }) ContextStore: any; /** Per default, this will inherit the value from c-theme name property */ @Prop({ mutable: true }) theme: string; @State() store: any; @State() tagName: string; @State() currentTheme: object; @Element() el: HTMLElement; @Watch('theme') setTheme(name = undefined) { this.theme = name || this.store.getState().theme.name; this.currentTheme = this.store.getState().themes[this.theme]; } async loadLibs() { const jquery = await import('jquery'); window.CorporateUi.$ = jquery.default; await import('bootstrap'); } componentWillLoad() { this.loadLibs(); this.store = this.ContextStore || (window as any).CorporateUi.store; this.setTheme(this.theme); this.store.subscribe(() => this.setTheme()); } componentDidLoad() { this.tagName = this.el.nodeName.toLowerCase(); } render() { return this.currentTheme ? <style>{ this.currentTheme[this.tagName] }</style> : ''; } }
Enable jQuery in global Corporate UI
Enable jQuery in global Corporate UI - Add jquery to CorporateUI so it is accessible from project to modify bootstrap script
TypeScript
mit
scania/corporate-ui,scania/corporate-ui
--- +++ @@ -27,7 +27,8 @@ } async loadLibs() { - await import('jquery'); + const jquery = await import('jquery'); + window.CorporateUi.$ = jquery.default; await import('bootstrap'); }
c644843b090bc62385398d581c93ff90d7f028ac
applications/mail/src/app/components/conversation/TrashWarning.tsx
applications/mail/src/app/components/conversation/TrashWarning.tsx
import React from 'react'; import { c } from 'ttag'; import { InlineLinkButton, Icon } from 'react-components'; interface Props { inTrash: boolean; filter: boolean; onToggle: () => void; } const TrashWarning = ({ inTrash, filter, onToggle }: Props) => { return ( <div className="bordered-container m0-5 mb1 p1 flex flex-nowrap flex-items-center flex-spacebetween bg-global-highlight"> <div className="flex flex-nowrap flex-items-center"> <Icon name="trash" className="mr1" /> <span> {inTrash ? c('Info').t`This conversation contains non-trashed messages.` : c('Info').t`This conversation contains trashed messages.`} </span> </div> <InlineLinkButton onClick={onToggle} className="ml0-5 underline"> {inTrash ? filter ? c('Action').t`Show messages` : c('Action').t`Hide messages` : filter ? c('Action').t`Show messages` : c('Action').t`Hide messages`} </InlineLinkButton> </div> ); }; export default TrashWarning;
import React from 'react'; import { c } from 'ttag'; import { InlineLinkButton, Icon } from 'react-components'; interface Props { inTrash: boolean; filter: boolean; onToggle: () => void; } const TrashWarning = ({ inTrash, filter, onToggle }: Props) => { return ( <div className="bordered-container m0-5 mb1 p1 flex flex-nowrap flex-items-center flex-spacebetween bg-white-dm"> <div className="flex flex-nowrap flex-items-center"> <Icon name="trash" className="mr1" /> <span> {inTrash ? c('Info').t`This conversation contains non-trashed messages.` : c('Info').t`This conversation contains trashed messages.`} </span> </div> <InlineLinkButton onClick={onToggle} className="ml0-5 underline"> {inTrash ? filter ? c('Action').t`Show messages` : c('Action').t`Hide messages` : filter ? c('Action').t`Show messages` : c('Action').t`Hide messages`} </InlineLinkButton> </div> ); }; export default TrashWarning;
Fix [MAILWEB-950] show trashed message not themed - bad color
Fix [MAILWEB-950] show trashed message not themed - bad color
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -10,7 +10,7 @@ const TrashWarning = ({ inTrash, filter, onToggle }: Props) => { return ( - <div className="bordered-container m0-5 mb1 p1 flex flex-nowrap flex-items-center flex-spacebetween bg-global-highlight"> + <div className="bordered-container m0-5 mb1 p1 flex flex-nowrap flex-items-center flex-spacebetween bg-white-dm"> <div className="flex flex-nowrap flex-items-center"> <Icon name="trash" className="mr1" /> <span>
583b3571d7a9fffb1e8c5ad579b7bc5a1b2f7a1e
src/main.ts
src/main.ts
import program = require('commander'); program .version('0.2.7') .usage('new <name> [property:type...]') .command('new <name> [property:type...]', 'generate a Web Component'); program.parse(process.argv);
import program = require('commander'); const version = require('../package.json')['version']; program .version(version) .usage('new <name> [property:type...]') .command('new <name> [property:type...]', 'generate a Web Component'); program.parse(process.argv);
Load CLI version from package.json
Load CLI version from package.json
TypeScript
mit
abraham/nutmeg-cli,abraham/nutmeg-cli,abraham/nutmeg-cli
--- +++ @@ -1,7 +1,8 @@ import program = require('commander'); +const version = require('../package.json')['version']; program - .version('0.2.7') + .version(version) .usage('new <name> [property:type...]') .command('new <name> [property:type...]', 'generate a Web Component');
3835bf23795aca8f2a60ea2c0d7b4674e3802c7b
src/plugins/edit-form/edit-form.component.ts
src/plugins/edit-form/edit-form.component.ts
import { Component, Optional, Input, OnInit, OnDestroy } from '@angular/core'; import { RootService } from '../../infrastructure/component/index'; import { PluginComponent } from '../plugin.component'; import { EditFormView } from 'ng2-qgrid/plugin/edit-form/edit.form.view'; import { FormGroup } from '@angular/forms'; import { ViewCoreService } from 'ng2-qgrid/main'; import { ColumnModel } from 'ng2-qgrid/core/column-type/column.model'; @Component({ selector: 'q-grid-edit-form', templateUrl: './edit-form.component.html' }) export class EditFormComponent extends PluginComponent implements OnInit, OnDestroy { @Input() title: string; private columns: ColumnModel[]; constructor( @Optional() root: RootService) { super(root); } ngOnInit() { const model = this.model; this.columns = model.data().columns; this.context.$implicit["getKey"] = (column: ColumnModel) => { return column.type ? `edit-form-${column.type}.tpl.html` : 'edit-form-default.tpl.html'; } } ngOnDestroy() { } }
import { Component, Optional, Input, OnInit, OnDestroy } from '@angular/core'; import { RootService } from '../../infrastructure/component/index'; import { PluginComponent } from '../plugin.component'; import { EditFormView } from 'ng2-qgrid/plugin/edit-form/edit.form.view'; import { FormGroup } from '@angular/forms'; import { ViewCoreService } from 'ng2-qgrid/main'; import { ColumnModel } from 'ng2-qgrid/core/column-type/column.model'; @Component({ selector: 'q-grid-edit-form', templateUrl: './edit-form.component.html' }) export class EditFormComponent extends PluginComponent implements OnInit, OnDestroy { @Input() title: string; private columns: ColumnModel[]; constructor( @Optional() root: RootService) { super(root); } ngOnInit() { const model = this.model; this.columns = model.data().columns; } ngOnDestroy() { } getKey(column: ColumnModel): string { return column.type ? `edit-form-${column.type}.tpl.html` : 'edit-form-default.tpl.html'; } }
Define getKey as a class member
Define getKey as a class member
TypeScript
mit
azkurban/ng2,qgrid/ng2,qgrid/ng2,qgrid/ng2,azkurban/ng2,azkurban/ng2
--- +++ @@ -22,12 +22,13 @@ ngOnInit() { const model = this.model; this.columns = model.data().columns; - this.context.$implicit["getKey"] = (column: ColumnModel) => { - return column.type ? `edit-form-${column.type}.tpl.html` : 'edit-form-default.tpl.html'; - } } ngOnDestroy() { } + + getKey(column: ColumnModel): string { + return column.type ? `edit-form-${column.type}.tpl.html` : 'edit-form-default.tpl.html'; + } }
a7b7d7773fd6d33de3ae6f6786cd2aab6c046311
tests/__tests__/tsx-errors.spec.ts
tests/__tests__/tsx-errors.spec.ts
import runJest from '../__helpers__/runJest'; const tmpDescribe = parseInt(process.version.substr(1, 2)) >= 8 ? xdescribe : describe; tmpDescribe('TSX Errors', () => { it('should show the correct error locations in the typescript files', () => { const result = runJest('../button', ['--no-cache', '-u']); const stderr = result.stderr.toString(); expect(result.status).toBe(1); expect(stderr).toContain('Button.tsx:18:17'); expect(stderr).toContain('Button.test.tsx:15:12'); }); });
import runJest from '../__helpers__/runJest'; import * as React from 'react'; const nodeVersion = parseInt(process.version.substr(1, 2)); const reactVersion = parseInt(React.version.substr(0, 2)); const tmpDescribe = nodeVersion >= 8 && reactVersion >= 16 ? xdescribe : describe; tmpDescribe('TSX Errors', () => { it('should show the correct error locations in the typescript files', () => { const result = runJest('../button', ['--no-cache', '-u']); const stderr = result.stderr.toString(); expect(result.status).toBe(1); expect(stderr).toContain('Button.tsx:18:17'); expect(stderr).toContain('Button.test.tsx:15:12'); }); });
Drop the tsx error test only for node versions >= 8 and react versions >=16
Drop the tsx error test only for node versions >= 8 and react versions >=16
TypeScript
mit
kulshekhar/ts-jest,kulshekhar/ts-jest
--- +++ @@ -1,7 +1,11 @@ import runJest from '../__helpers__/runJest'; +import * as React from 'react'; + +const nodeVersion = parseInt(process.version.substr(1, 2)); +const reactVersion = parseInt(React.version.substr(0, 2)); const tmpDescribe = - parseInt(process.version.substr(1, 2)) >= 8 ? xdescribe : describe; + nodeVersion >= 8 && reactVersion >= 16 ? xdescribe : describe; tmpDescribe('TSX Errors', () => { it('should show the correct error locations in the typescript files', () => {
3aa9c2499e643ba9888109468386e4dea49535d9
components/add-layers/vector/add-layers-vector.component.ts
components/add-layers/vector/add-layers-vector.component.ts
import {Component} from '@angular/core'; import {HsAddLayersVectorService} from './add-layers-vector.service'; import {HsLayoutService} from '../../layout/layout.service'; @Component({ selector: 'hs-add-layers-vector', template: require('./add-vector-layer.directive.html'), }) export class HsAddLayersVectorComponent { srs = 'EPSG:4326'; title = ''; extract_styles = false; abstract: string; url: string; constructor( private HsAddLayersVectorService: HsAddLayersVectorService, private HsLayoutService: HsLayoutService ) {} /** * Handler for adding nonwms service, file in template. * * @function add */ async add() { const layer = await this.HsAddLayersVectorService.addVectorLayer( '', this.url, this.title, this.abstract, this.srs, {extractStyles: this.extract_styles} ); this.HsAddLayersVectorService.fitExtent(layer); HsLayoutService.setMainPanel('layermanager'); return layer; } }
import {Component} from '@angular/core'; import {HsAddLayersVectorService} from './add-layers-vector.service'; import {HsLayoutService} from '../../layout/layout.service'; @Component({ selector: 'hs-add-layers-vector', template: require('./add-vector-layer.directive.html'), }) export class HsAddLayersVectorComponent { srs = 'EPSG:4326'; title = ''; extract_styles = false; abstract: string; url: string; constructor( private HsAddLayersVectorService: HsAddLayersVectorService, private HsLayoutService: HsLayoutService ) {} /** * Handler for adding nonwms service, file in template. * * @function add */ async add() { const layer = await this.HsAddLayersVectorService.addVectorLayer( '', this.url, this.title, this.abstract, this.srs, {extractStyles: this.extract_styles} ); this.HsAddLayersVectorService.fitExtent(layer); this.HsLayoutService.setMainPanel('layermanager'); return layer; } }
Fix missing 'this' for HsLayoutService
Fix missing 'this' for HsLayoutService
TypeScript
mit
hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng
--- +++ @@ -34,7 +34,7 @@ {extractStyles: this.extract_styles} ); this.HsAddLayersVectorService.fitExtent(layer); - HsLayoutService.setMainPanel('layermanager'); + this.HsLayoutService.setMainPanel('layermanager'); return layer; } }
11127f40d8b9e435d67701a218c29ecff55e4dbd
src/clangPath.ts
src/clangPath.ts
'use strict'; import fs = require('fs'); import path = require('path'); var binPathCache: { [bin: string]: string; } = {} export function getBinPath(binname: string) { binname = correctBinname(binname); if (binPathCache[binname]) return binPathCache[binname]; // clang-format.executable has a valid absolute path if (fs.existsSync(binname)) { binPathCache[binname] = binname; return binname; } if (process.env["PATH"]) { var pathparts = process.env["PATH"].split(path.delimiter); for (var i = 0; i < pathparts.length; i++) { let binpath = path.join(pathparts[i], binname); if (fs.existsSync(binpath)) { binPathCache[binname] = binpath; return binpath; } } } // Else return the binary name directly (this will likely always fail downstream) binPathCache[binname] = binname; return binname; } function correctBinname(binname: string) { if (process.platform === 'win32') { if(binname.substr(binname.length - 4).toLowerCase() !== '.exe') { return binname + ".exe"; } else { return binname; } } else { return binname } }
'use strict'; import fs = require('fs'); import path = require('path'); var binPathCache: { [bin: string]: string; } = {} export function getBinPath(binname: string) { if (binPathCache[binname]) return binPathCache[binname]; for (let binNameToSearch of correctBinname(binname)) { // clang-format.executable has a valid absolute path if (fs.existsSync(binNameToSearch)) { binPathCache[binname] = binNameToSearch; return binNameToSearch; } if (process.env["PATH"]) { var pathparts = process.env["PATH"].split(path.delimiter); for (var i = 0; i < pathparts.length; i++) { let binpath = path.join(pathparts[i], binNameToSearch); if (fs.existsSync(binpath)) { binPathCache[binname] = binpath; return binpath; } } } } // Else return the binary name directly (this will likely always fail downstream) binPathCache[binname] = binname; return binname; } function correctBinname(binname: string): [string] { if (process.platform === 'win32') { return [binname + '.exe', binname + '.cmd', binname]; } else { return [binname] } }
Improve executable search on Windows
Improve executable search on Windows Search for the plain provided binary as well as appending a .cmd suffix. This fixes issue where providing a valid path to an executable would not work as expected because the plug-in would append `.exe`
TypeScript
mit
xaverh/vscode-clang-format-provider
--- +++ @@ -6,23 +6,23 @@ var binPathCache: { [bin: string]: string; } = {} export function getBinPath(binname: string) { - binname = correctBinname(binname); - if (binPathCache[binname]) return binPathCache[binname]; - // clang-format.executable has a valid absolute path - if (fs.existsSync(binname)) { - binPathCache[binname] = binname; - return binname; - } - - if (process.env["PATH"]) { - var pathparts = process.env["PATH"].split(path.delimiter); - for (var i = 0; i < pathparts.length; i++) { - let binpath = path.join(pathparts[i], binname); - if (fs.existsSync(binpath)) { - binPathCache[binname] = binpath; - return binpath; + for (let binNameToSearch of correctBinname(binname)) { + // clang-format.executable has a valid absolute path + if (fs.existsSync(binNameToSearch)) { + binPathCache[binname] = binNameToSearch; + return binNameToSearch; + } + + if (process.env["PATH"]) { + var pathparts = process.env["PATH"].split(path.delimiter); + for (var i = 0; i < pathparts.length; i++) { + let binpath = path.join(pathparts[i], binNameToSearch); + if (fs.existsSync(binpath)) { + binPathCache[binname] = binpath; + return binpath; + } } } } @@ -32,14 +32,10 @@ return binname; } -function correctBinname(binname: string) { +function correctBinname(binname: string): [string] { if (process.platform === 'win32') { - if(binname.substr(binname.length - 4).toLowerCase() !== '.exe') { - return binname + ".exe"; - } else { - return binname; - } + return [binname + '.exe', binname + '.cmd', binname]; } else { - return binname + return [binname] } }
e1a407c6fc8677ffb5e8716576a727222f7c29f2
routes/updateProductReviews.ts
routes/updateProductReviews.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import utils = require('../lib/utils') const challenges = require('../data/datacache').challenges const db = require('../data/mongodb') const security = require('../lib/insecurity') // vuln-code-snippet start noSqlReviewsChallenge forgedReviewChallenge noSqlCommandChallenge module.exports = function productReviews () { return (req, res, next) => { const user = security.authenticatedUsers.from(req) // vuln-code-snippet vuln-line forgedReviewChallenge db.reviews.update( { _id: req.body.id }, // vuln-code-snippet vuln-line noSqlReviewsChallenge noSqlCommandChallenge { $set: { message: req.body.message } }, { multi: true } ).then( result => { utils.solveIf(challenges.noSqlReviewsChallenge, () => { return result.modified > 1 }) // vuln-code-snippet hide-line utils.solveIf(challenges.forgedReviewChallenge, () => { return user?.data && result.original[0].author !== user.data.email && result.modified === 1 }) // vuln-code-snippet hide-line res.json(result) }, err => { res.status(500).json(err) }) } } // vuln-code-snippet end noSqlReviewsChallenge forgedReviewChallenge noSqlCommandChallenge
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import utils = require('../lib/utils') const challenges = require('../data/datacache').challenges const db = require('../data/mongodb') const security = require('../lib/insecurity') // vuln-code-snippet start noSqlReviewsChallenge forgedReviewChallenge module.exports = function productReviews () { return (req, res, next) => { const user = security.authenticatedUsers.from(req) // vuln-code-snippet vuln-line forgedReviewChallenge db.reviews.update( { _id: req.body.id }, // vuln-code-snippet vuln-line noSqlReviewsChallenge { $set: { message: req.body.message } }, { multi: true } // vuln-code-snippet vuln-line noSqlReviewsChallenge ).then( result => { utils.solveIf(challenges.noSqlReviewsChallenge, () => { return result.modified > 1 }) // vuln-code-snippet hide-line utils.solveIf(challenges.forgedReviewChallenge, () => { return user?.data && result.original[0].author !== user.data.email && result.modified === 1 }) // vuln-code-snippet hide-line res.json(result) }, err => { res.status(500).json(err) }) } } // vuln-code-snippet end noSqlReviewsChallenge forgedReviewChallenge
Remove wrongly located vuln snippet for "NoSql DoS" challenge
Remove wrongly located vuln snippet for "NoSql DoS" challenge
TypeScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
--- +++ @@ -8,14 +8,14 @@ const db = require('../data/mongodb') const security = require('../lib/insecurity') -// vuln-code-snippet start noSqlReviewsChallenge forgedReviewChallenge noSqlCommandChallenge +// vuln-code-snippet start noSqlReviewsChallenge forgedReviewChallenge module.exports = function productReviews () { return (req, res, next) => { const user = security.authenticatedUsers.from(req) // vuln-code-snippet vuln-line forgedReviewChallenge db.reviews.update( - { _id: req.body.id }, // vuln-code-snippet vuln-line noSqlReviewsChallenge noSqlCommandChallenge + { _id: req.body.id }, // vuln-code-snippet vuln-line noSqlReviewsChallenge { $set: { message: req.body.message } }, - { multi: true } + { multi: true } // vuln-code-snippet vuln-line noSqlReviewsChallenge ).then( result => { utils.solveIf(challenges.noSqlReviewsChallenge, () => { return result.modified > 1 }) // vuln-code-snippet hide-line @@ -26,4 +26,4 @@ }) } } -// vuln-code-snippet end noSqlReviewsChallenge forgedReviewChallenge noSqlCommandChallenge +// vuln-code-snippet end noSqlReviewsChallenge forgedReviewChallenge
463e1938e893dec5049b8b1a83736e83783246f4
simple-git/src/lib/plugins/timout-plugin.ts
simple-git/src/lib/plugins/timout-plugin.ts
import { SimpleGitOptions } from '../types'; import { SimpleGitPlugin } from './simple-git-plugin'; import { GitPluginError } from '../errors/git-plugin-error'; export function timeoutPlugin({block}: Exclude<SimpleGitOptions['timeout'], undefined>): SimpleGitPlugin<'spawn.after'> | void { if (block > 0) { return { type: 'spawn.after', action(_data, context) { let timeout: NodeJS.Timeout; function wait() { timeout && clearTimeout(timeout); timeout = setTimeout(kill, block); } function stop() { context.spawned.stdout?.off('data', wait); context.spawned.stderr?.off('data', wait); context.spawned.off('exit', stop); context.spawned.off('close', stop); } function kill() { stop() context.kill( new GitPluginError(undefined, 'timeout', `block timeout reached`) ); } context.spawned.stdout?.on('data', wait); context.spawned.stderr?.on('data', wait); context.spawned.on('exit', stop); context.spawned.on('close', stop); wait(); } } } }
import { SimpleGitOptions } from '../types'; import { SimpleGitPlugin } from './simple-git-plugin'; import { GitPluginError } from '../errors/git-plugin-error'; export function timeoutPlugin({block}: Exclude<SimpleGitOptions['timeout'], undefined>): SimpleGitPlugin<'spawn.after'> | void { if (block > 0) { return { type: 'spawn.after', action(_data, context) { let timeout: NodeJS.Timeout; function wait() { timeout && clearTimeout(timeout); timeout = setTimeout(kill, block); } function stop() { context.spawned.stdout?.off('data', wait); context.spawned.stderr?.off('data', wait); context.spawned.off('exit', stop); context.spawned.off('close', stop); timeout && clearTimeout(timeout); } function kill() { stop() context.kill( new GitPluginError(undefined, 'timeout', `block timeout reached`) ); } context.spawned.stdout?.on('data', wait); context.spawned.stderr?.on('data', wait); context.spawned.on('exit', stop); context.spawned.on('close', stop); wait(); } } } }
Clear timeout upon stop to avoid hanging the process
Clear timeout upon stop to avoid hanging the process
TypeScript
mit
steveukx/git-js,steveukx/git-js
--- +++ @@ -21,6 +21,7 @@ context.spawned.stderr?.off('data', wait); context.spawned.off('exit', stop); context.spawned.off('close', stop); + timeout && clearTimeout(timeout); } function kill() {
b9eef160f4b9ee3140b7de7f678db578fbbd2f17
src/core/domain/services/predefinedHooks/validation.hook.ts
src/core/domain/services/predefinedHooks/validation.hook.ts
const commonHooks = require('feathers-hooks-common'); const Ajv = require('ajv'); import { IServiceHooks, IHook, ISchema } from '../IService'; export const validationHooks = (schemas: { create: ISchema, update: ISchema } , beforeHooks: IHook): void => { beforeHooks.create.push(validateSchema(schemas.create)); beforeHooks.update.push(validateSchema(schemas.update)); }; const validateSchema = (schema: ISchema): Function => { return commonHooks.validateSchema(schema, Ajv, { allErrors: true, format: 'full', addNewError: addNewError }); }; const addNewError = (prev: any, ajvError: any, itemsLen: number, index: number): any => { let property; let message; prev = prev || {}; console.log(ajvError); switch (ajvError.keyword) { case 'additionalProperties': property = ajvError.params.additionalProperty; message = 'invalid property'; break; case 'required': property = ajvError.params.missingProperty; message = 'required'; break; default: property = ajvError.dataPath.split('.')[1]; message = ajvError.message; } prev[property] = message; return prev; };
import * as lodash from 'lodash'; const commonHooks = require('feathers-hooks-common'); const Ajv = require('ajv'); import { IServiceHooks, IHook, ISchema } from '../IService'; export const validationHooks = (schemas: { create: ISchema, update?: ISchema } , beforeHooks: IHook): void => { beforeHooks.create.push(validateSchema(schemas.create)); if (!lodash.isNil(schemas.update)) { beforeHooks.update.push(validateSchema(schemas.update)); beforeHooks.patch.push(validateSchema(schemas.update)); } }; const validateSchema = (schema: ISchema): Function => { return commonHooks.validateSchema(schema, Ajv, { allErrors: true, format: 'full', addNewError: addNewError }); }; const addNewError = (prev: any, ajvError: any, itemsLen: number, index: number): any => { let property; let message; prev = prev || {}; console.log(ajvError); switch (ajvError.keyword) { case 'additionalProperties': property = ajvError.params.additionalProperty; message = 'invalid property'; break; case 'required': property = ajvError.params.missingProperty; message = 'required'; break; default: property = ajvError.dataPath.split('.')[1]; message = ajvError.message; } prev[property] = message; return prev; };
Check if schemas.update is nil
Check if schemas.update is nil
TypeScript
mit
sauli6692/ibc-server
--- +++ @@ -1,11 +1,16 @@ +import * as lodash from 'lodash'; const commonHooks = require('feathers-hooks-common'); const Ajv = require('ajv'); import { IServiceHooks, IHook, ISchema } from '../IService'; -export const validationHooks = (schemas: { create: ISchema, update: ISchema } , beforeHooks: IHook): void => { +export const validationHooks = (schemas: { create: ISchema, update?: ISchema } , beforeHooks: IHook): void => { beforeHooks.create.push(validateSchema(schemas.create)); - beforeHooks.update.push(validateSchema(schemas.update)); + + if (!lodash.isNil(schemas.update)) { + beforeHooks.update.push(validateSchema(schemas.update)); + beforeHooks.patch.push(validateSchema(schemas.update)); + } }; const validateSchema = (schema: ISchema): Function => {
46cc2b67c95b607e67cbab045a97744feda3fcd5
src/constants.ts
src/constants.ts
export namespace constants { export namespace headers.request { // standard forwarded for header export const X_FORWARDED_FOR = 'X-Forwarded-For'; // standard forwarded proto header export const X_FORWARDED_PROTO = 'X-Forwarded-Proto'; // standard forwarded port header export const X_FORWARDED_PORT = 'X-Forwarded-Port'; // specifies the original timeout from client side export const X_FORWARDED_NODESWORK_CLIENT_TIMEOUT = 'X-Forwarded-Client-Timeout'; } export namespace headers.response { // standard server header export const SERVER = 'SERVER'; // indicate the response is generated by which applet or which product export const NODESWORK_PRODUCER = 'NODESWORK-PRODUCER'; // indicate the response is generated by which particular host export const NODESWORK_PRODUCER_HOST = 'NODESWORK-PRODUCER-HOST'; // indicate the producing time export const NODESWORK_PRODUCER_DURATION = 'NODESWORK-PRODUCER-DURATION'; } }
export namespace constants { export namespace headers.request { // standard forwarded for header export const X_FORWARDED_FOR = 'X-Forwarded-For'; // standard forwarded proto header export const X_FORWARDED_PROTO = 'X-Forwarded-Proto'; // standard forwarded port header export const X_FORWARDED_PORT = 'X-Forwarded-Port'; // specifies the original timeout from client side export const X_FORWARDED_NODESWORK_CLIENT_TIMEOUT = 'X-Forwarded-Client-Timeout'; } export namespace headers.response { // standard server header export const SERVER = 'SERVER'; // indicate the response is generated by which applet or which product export const NODESWORK_PRODUCER = 'Nodeswork-Producer'; // indicate the response is generated by which particular host export const NODESWORK_PRODUCER_HOST = 'Nodeswork-Producer-Host'; // indicate the producing time export const NODESWORK_PRODUCER_DURATION = 'Nodeswork-Producer-Duration'; } }
Change the header name as standardized.
Change the header name as standardized.
TypeScript
apache-2.0
nodeswork/sbase,nodeswork/sbase
--- +++ @@ -21,12 +21,12 @@ export const SERVER = 'SERVER'; // indicate the response is generated by which applet or which product - export const NODESWORK_PRODUCER = 'NODESWORK-PRODUCER'; + export const NODESWORK_PRODUCER = 'Nodeswork-Producer'; // indicate the response is generated by which particular host - export const NODESWORK_PRODUCER_HOST = 'NODESWORK-PRODUCER-HOST'; + export const NODESWORK_PRODUCER_HOST = 'Nodeswork-Producer-Host'; // indicate the producing time - export const NODESWORK_PRODUCER_DURATION = 'NODESWORK-PRODUCER-DURATION'; + export const NODESWORK_PRODUCER_DURATION = 'Nodeswork-Producer-Duration'; } }
947118d38c95958dfa50dfc2e3c961984f8c2737
example/index.ts
example/index.ts
import { odata2openapi } from '../src/'; odata2openapi('http://services.odata.org/V3/Northwind/Northwind.svc/$metadata') .then(swagger => console.log(JSON.stringify(swagger, null, 2))) .catch(error => console.error(error))
import { odata2openapi } from '../src/'; const url = process.argv[2] || 'http://services.odata.org/V3/Northwind/Northwind.svc/$metadata'; odata2openapi(url) .then(swagger => console.log(JSON.stringify(swagger, null, 2))) .catch(error => console.error(error))
Load url from command line.
Load url from command line.
TypeScript
mit
akorchev/odata2openapi
--- +++ @@ -1,5 +1,7 @@ import { odata2openapi } from '../src/'; -odata2openapi('http://services.odata.org/V3/Northwind/Northwind.svc/$metadata') +const url = process.argv[2] || 'http://services.odata.org/V3/Northwind/Northwind.svc/$metadata'; + +odata2openapi(url) .then(swagger => console.log(JSON.stringify(swagger, null, 2))) .catch(error => console.error(error))
28a1c5a1de78edca59579341d97ca6f774618057
components/site/site-model.ts
components/site/site-model.ts
import { Model } from '../model/model.service'; import { SiteTheme } from './theme/theme-model'; import { SiteContentBlock } from './content-block/content-block-model'; import { SiteBuild } from './build/build-model'; export class Site extends Model { static STATUS_INACTIVE = 'inactive'; static STATUS_ACTIVE = 'active'; static STATUS_REMOVED = 'removed'; url: string; user: any; game?: any; theme: SiteTheme; content_blocks: SiteContentBlock[]; is_static: boolean; build?: SiteBuild; status: string; constructor( data: any = {} ) { super( data ); if ( data.theme ) { this.theme = new SiteTheme( data.theme ); } if ( data.content_blocks ) { this.content_blocks = SiteContentBlock.populate( data.content_blocks ); } if ( data.build ) { this.build = new SiteBuild( data.build ); } } } Model.create( Site );
import { Model } from '../model/model.service'; import { SiteTheme } from './theme/theme-model'; import { SiteContentBlock } from './content-block/content-block-model'; import { SiteBuild } from './build/build-model'; export class Site extends Model { static STATUS_INACTIVE = 'inactive'; static STATUS_ACTIVE = 'active'; static STATUS_REMOVED = 'removed'; url: string; user: any; game?: any; theme: SiteTheme; content_blocks: SiteContentBlock[]; is_static: boolean; build?: SiteBuild; title?: string; description?: string; ga_tracking_id?: string; status: string; constructor( data: any = {} ) { super( data ); if ( data.theme ) { this.theme = new SiteTheme( data.theme ); } if ( data.content_blocks ) { this.content_blocks = SiteContentBlock.populate( data.content_blocks ); } if ( data.build ) { this.build = new SiteBuild( data.build ); } } $save() { if ( this.id ) { return this.$_save( `/web/dash/sites/save/${this.id}`, 'site' ); } else { throw new Error( `Can't save new site.` ); } } } Model.create( Site );
Add in some fields for Site models. Also added a $save method
Add in some fields for Site models. Also added a $save method
TypeScript
mit
gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib
--- +++ @@ -16,6 +16,9 @@ content_blocks: SiteContentBlock[]; is_static: boolean; build?: SiteBuild; + title?: string; + description?: string; + ga_tracking_id?: string; status: string; constructor( data: any = {} ) @@ -34,6 +37,16 @@ this.build = new SiteBuild( data.build ); } } + + $save() + { + if ( this.id ) { + return this.$_save( `/web/dash/sites/save/${this.id}`, 'site' ); + } + else { + throw new Error( `Can't save new site.` ); + } + } } Model.create( Site );
31639bad878f4e09d6496f933656ba8c7bae35fd
tests/density.ts
tests/density.ts
import Canvasimo from '../src'; import getContextStub from './helpers/get-context-stub'; describe('density', () => { const element = document.createElement('canvas'); jest.spyOn(element, 'getContext').mockImplementation(getContextStub); const instance = new Canvasimo(element).setWidth(100); const ctx = instance.getCurrentContext(); it('should explicitly set the font size upon creation', () => { expect(ctx.font).toBe('normal normal normal 10px sans-serif'); expect(instance.getFontSize()).toBe(10); expect(element.width).toBe(100); expect(instance.getWidth()).toBe(100); }); it('updates font size when changing the density', () => { instance.setDensity(2); expect(ctx.font).toBe('normal normal normal 20px sans-serif'); expect(instance.getFontSize()).toBe(10); expect(element.width).toBe(200); expect(instance.getWidth()).toBe(100); }); it('retains density when the canvas is cleared (without changing the canvas size)', () => { // Fake browser font reset ctx.font = '10px sans-serif'; instance.clearCanvas(); expect(ctx.font).toBe('normal normal normal 20px sans-serif'); expect(instance.getFontSize()).toBe(10); expect(element.width).toBe(200); expect(instance.getWidth()).toBe(100); }); });
import Canvasimo from '../src'; import getContextStub from './helpers/get-context-stub'; describe('density', () => { const element = document.createElement('canvas'); jest.spyOn(element, 'getContext').mockImplementation(getContextStub); const instance = new Canvasimo(element).setWidth(100); const ctx = instance.getCurrentContext(); it('should explicitly set the font size upon creation', () => { expect(ctx.font).toBe('normal normal normal 10px sans-serif'); expect(instance.getFontSize()).toBe(10); expect(element.width).toBe(100); expect(instance.getWidth()).toBe(100); }); it('updates font size when changing the density', () => { instance.setDensity(2); expect(ctx.font).toBe('normal normal normal 20px sans-serif'); expect(instance.getFontSize()).toBe(10); expect(element.width).toBe(200); expect(instance.getWidth()).toBe(100); }); it('retains density when the canvas is cleared (without changing the canvas size)', () => { instance.clearCanvas(); expect(ctx.font).toBe('normal normal normal 20px sans-serif'); expect(instance.getFontSize()).toBe(10); expect(element.width).toBe(200); expect(instance.getWidth()).toBe(100); }); });
Remove fake browser font reset
Remove fake browser font reset
TypeScript
mit
JakeSidSmith/sensible-canvas-interface,JakeSidSmith/canvasimo,JakeSidSmith/canvasimo
--- +++ @@ -25,8 +25,6 @@ }); it('retains density when the canvas is cleared (without changing the canvas size)', () => { - // Fake browser font reset - ctx.font = '10px sans-serif'; instance.clearCanvas(); expect(ctx.font).toBe('normal normal normal 20px sans-serif');
fd182746cb47c60ceddffdf236925334caf06e68
extensions/markdown-language-features/src/commands/showPreviewSecuritySelector.ts
extensions/markdown-language-features/src/commands/showPreviewSecuritySelector.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { Command } from '../commandManager'; import { PreviewSecuritySelector } from '../security'; import { isMarkdownFile } from '../util/file'; import { MarkdownPreviewManager } from '../features/previewManager'; export class ShowPreviewSecuritySelectorCommand implements Command { public readonly id = 'markdown.showPreviewSecuritySelector'; public constructor( private readonly previewSecuritySelector: PreviewSecuritySelector, private readonly previewManager: MarkdownPreviewManager ) { } public execute(resource: string | undefined) { if (resource) { const source = vscode.Uri.parse(resource).query; this.previewSecuritySelector.showSecutitySelectorForResource(vscode.Uri.parse(source)); } else if (vscode.window.activeTextEditor && isMarkdownFile(vscode.window.activeTextEditor.document)) { this.previewSecuritySelector.showSecutitySelectorForResource(vscode.window.activeTextEditor.document.uri); } else if (this.previewManager.activePreviewResource) { this.previewSecuritySelector.showSecutitySelectorForResource(this.previewManager.activePreviewResource); } } }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { Command } from '../commandManager'; import { PreviewSecuritySelector } from '../security'; import { isMarkdownFile } from '../util/file'; import { MarkdownPreviewManager } from '../features/previewManager'; export class ShowPreviewSecuritySelectorCommand implements Command { public readonly id = 'markdown.showPreviewSecuritySelector'; public constructor( private readonly previewSecuritySelector: PreviewSecuritySelector, private readonly previewManager: MarkdownPreviewManager ) { } public execute(resource: string | undefined) { if (this.previewManager.activePreviewResource) { this.previewSecuritySelector.showSecutitySelectorForResource(this.previewManager.activePreviewResource); } else if (resource) { const source = vscode.Uri.parse(resource); this.previewSecuritySelector.showSecutitySelectorForResource(source.query ? vscode.Uri.parse(source.query) : source); } else if (vscode.window.activeTextEditor && isMarkdownFile(vscode.window.activeTextEditor.document)) { this.previewSecuritySelector.showSecutitySelectorForResource(vscode.window.activeTextEditor.document.uri); } } }
Fix can't change markdown security level for directly opened file
Fix can't change markdown security level for directly opened file Fixes #46424
TypeScript
mit
landonepps/vscode,microlv/vscode,microlv/vscode,microlv/vscode,DustinCampbell/vscode,0xmohit/vscode,eamodio/vscode,mjbvz/vscode,Microsoft/vscode,landonepps/vscode,joaomoreno/vscode,cleidigh/vscode,microsoft/vscode,microsoft/vscode,DustinCampbell/vscode,joaomoreno/vscode,microlv/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,Microsoft/vscode,microsoft/vscode,microlv/vscode,hoovercj/vscode,the-ress/vscode,microlv/vscode,the-ress/vscode,DustinCampbell/vscode,joaomoreno/vscode,cleidigh/vscode,0xmohit/vscode,mjbvz/vscode,joaomoreno/vscode,0xmohit/vscode,DustinCampbell/vscode,mjbvz/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,0xmohit/vscode,Microsoft/vscode,DustinCampbell/vscode,eamodio/vscode,the-ress/vscode,eamodio/vscode,microlv/vscode,landonepps/vscode,eamodio/vscode,rishii7/vscode,0xmohit/vscode,mjbvz/vscode,hoovercj/vscode,microsoft/vscode,microlv/vscode,landonepps/vscode,microlv/vscode,hoovercj/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,joaomoreno/vscode,microsoft/vscode,mjbvz/vscode,cleidigh/vscode,Microsoft/vscode,cleidigh/vscode,rishii7/vscode,cleidigh/vscode,joaomoreno/vscode,joaomoreno/vscode,hoovercj/vscode,joaomoreno/vscode,hoovercj/vscode,cleidigh/vscode,DustinCampbell/vscode,landonepps/vscode,hoovercj/vscode,rishii7/vscode,eamodio/vscode,microsoft/vscode,the-ress/vscode,mjbvz/vscode,mjbvz/vscode,the-ress/vscode,microsoft/vscode,the-ress/vscode,microlv/vscode,cleidigh/vscode,hoovercj/vscode,rishii7/vscode,DustinCampbell/vscode,Microsoft/vscode,joaomoreno/vscode,the-ress/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,mjbvz/vscode,hoovercj/vscode,microlv/vscode,mjbvz/vscode,Microsoft/vscode,Microsoft/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,mjbvz/vscode,hoovercj/vscode,joaomoreno/vscode,Microsoft/vscode,DustinCampbell/vscode,DustinCampbell/vscode,0xmohit/vscode,landonepps/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,rishii7/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,eamodio/vscode,mjbvz/vscode,hoovercj/vscode,DustinCampbell/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,eamodio/vscode,eamodio/vscode,rishii7/vscode,microsoft/vscode,hoovercj/vscode,Microsoft/vscode,hoovercj/vscode,rishii7/vscode,joaomoreno/vscode,rishii7/vscode,DustinCampbell/vscode,landonepps/vscode,rishii7/vscode,0xmohit/vscode,cleidigh/vscode,mjbvz/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,DustinCampbell/vscode,cleidigh/vscode,landonepps/vscode,rishii7/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,microlv/vscode,cleidigh/vscode,DustinCampbell/vscode,microsoft/vscode,joaomoreno/vscode,rishii7/vscode,joaomoreno/vscode,the-ress/vscode,0xmohit/vscode,the-ress/vscode,eamodio/vscode,mjbvz/vscode,eamodio/vscode,0xmohit/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,eamodio/vscode,landonepps/vscode,hoovercj/vscode,DustinCampbell/vscode,landonepps/vscode,cleidigh/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Microsoft/vscode,the-ress/vscode,the-ress/vscode,eamodio/vscode,0xmohit/vscode,the-ress/vscode,microsoft/vscode,cleidigh/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,the-ress/vscode,hoovercj/vscode,microlv/vscode,cleidigh/vscode,Microsoft/vscode,mjbvz/vscode,landonepps/vscode,Microsoft/vscode,hoovercj/vscode,joaomoreno/vscode,rishii7/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,DustinCampbell/vscode,microlv/vscode,0xmohit/vscode,microlv/vscode,landonepps/vscode,DustinCampbell/vscode,rishii7/vscode,the-ress/vscode,landonepps/vscode,eamodio/vscode,0xmohit/vscode,hoovercj/vscode,rishii7/vscode,0xmohit/vscode,rishii7/vscode,cleidigh/vscode,rishii7/vscode,microlv/vscode,rishii7/vscode,eamodio/vscode,cleidigh/vscode,0xmohit/vscode,cleidigh/vscode,joaomoreno/vscode,microlv/vscode
--- +++ @@ -18,13 +18,13 @@ ) { } public execute(resource: string | undefined) { - if (resource) { - const source = vscode.Uri.parse(resource).query; - this.previewSecuritySelector.showSecutitySelectorForResource(vscode.Uri.parse(source)); + if (this.previewManager.activePreviewResource) { + this.previewSecuritySelector.showSecutitySelectorForResource(this.previewManager.activePreviewResource); + } else if (resource) { + const source = vscode.Uri.parse(resource); + this.previewSecuritySelector.showSecutitySelectorForResource(source.query ? vscode.Uri.parse(source.query) : source); } else if (vscode.window.activeTextEditor && isMarkdownFile(vscode.window.activeTextEditor.document)) { this.previewSecuritySelector.showSecutitySelectorForResource(vscode.window.activeTextEditor.document.uri); - } else if (this.previewManager.activePreviewResource) { - this.previewSecuritySelector.showSecutitySelectorForResource(this.previewManager.activePreviewResource); } } }
9c1aa1ef7c271c434e9b878ee22ffe4789c2a8c4
src/app/app.ts
src/app/app.ts
import { Component, View, ElementRef } from 'angular2/angular2'; @Component({ selector: 'app' }) @View({ templateUrl: './app.html' }) export class App { constructor(elementRef : ElementRef) { } }
import { Component, View, ElementRef } from 'angular2/angular2'; @Component({ selector: 'app' }) @View({ templateUrl: 'app/app.html' }) export class App { constructor(elementRef : ElementRef) { } }
Remove relative path to templateUrl. It does not work.
Remove relative path to templateUrl. It does not work.
TypeScript
mit
tbragaf/ng2-seed,tbragaf/ng2-typescript,tbragaf/ng2-seed,tbragaf/ng2-seed,tbragaf/ng2-typescript,tbragaf/ng2-typescript
--- +++ @@ -4,7 +4,7 @@ selector: 'app' }) @View({ - templateUrl: './app.html' + templateUrl: 'app/app.html' }) export class App { constructor(elementRef : ElementRef) { }
a55e742ac24f5b40e41f01305ad88bc1f9d85ffc
packages/neutrino-preset-tux/src/extractCss.ts
packages/neutrino-preset-tux/src/extractCss.ts
import ExtractTextPlugin from 'extract-text-webpack-plugin' export default function extractCss(neutrino: any) { const { config } = neutrino const styleRule = config.module.rule('style') // We prepend the extract loader by clearing the uses and adding them back in order. // Clone existing uses. const existingUses = styleRule.uses.toConfig() styleRule // Clear uses .uses .clear() .end() // Add extract-css loader first. .use('extract-css') .loader(require.resolve('extract-text-webpack-plugin/loader')) .options({ omit: 1, remove: true, }) .end() // Then add existing uses again. .merge(existingUses) // Add plugin to save extracted css. config.plugin('extract-css') .use(ExtractTextPlugin, [{ filename: '[name].[chunkhash].bundle.css', }]) }
import ExtractTextPlugin from 'extract-text-webpack-plugin' export default function extractCss(neutrino: any) { const { config } = neutrino // Prepend extract text loader before style loader. prependUse(config.module.rule('style'), (rule: any) => rule.use('extract-css') .loader(require.resolve('extract-text-webpack-plugin/loader')) .options({ omit: 1, remove: true, }) ) // Add plugin to save extracted css. config.plugin('extract-css') .use(ExtractTextPlugin, [{ filename: '[name].[chunkhash].bundle.css', }]) } // For loaders, the order matters. In this case we want to prepend // a loader before existing loaders. const prependUse = (rule: any, cb: any) => { const existingUses = rule.uses.entries() rule.uses.clear() cb(rule) rule.uses.merge(existingUses) }
Clean up extract css magic
Clean up extract css magic
TypeScript
mit
aranja/tux,aranja/tux,aranja/tux
--- +++ @@ -2,27 +2,16 @@ export default function extractCss(neutrino: any) { const { config } = neutrino - const styleRule = config.module.rule('style') - // We prepend the extract loader by clearing the uses and adding them back in order. - // Clone existing uses. - const existingUses = styleRule.uses.toConfig() - - styleRule - // Clear uses - .uses - .clear() - .end() - // Add extract-css loader first. - .use('extract-css') + // Prepend extract text loader before style loader. + prependUse(config.module.rule('style'), (rule: any) => + rule.use('extract-css') .loader(require.resolve('extract-text-webpack-plugin/loader')) .options({ omit: 1, remove: true, }) - .end() - // Then add existing uses again. - .merge(existingUses) + ) // Add plugin to save extracted css. config.plugin('extract-css') @@ -30,3 +19,12 @@ filename: '[name].[chunkhash].bundle.css', }]) } + +// For loaders, the order matters. In this case we want to prepend +// a loader before existing loaders. +const prependUse = (rule: any, cb: any) => { + const existingUses = rule.uses.entries() + rule.uses.clear() + cb(rule) + rule.uses.merge(existingUses) +}
1863fe01d5feb499dbdbdcfe473300f48f573a04
src/og-components/og-loading-spinner/directives/og-loading-spinner.ts
src/og-components/og-loading-spinner/directives/og-loading-spinner.ts
import "../css/og-loading-spinner.less"; import { OgLoadingSpinnerScope } from "og-components/og-loading-spinner/types"; import OgLoadingSpinnerView from "og-components/og-loading-spinner/views/loading.html"; export default class OgLoadingSpinnerDirective { public constructor() { const directive: angular.IDirective = { restrict: "A", scope: { message: "=ogLoadingSpinner" }, templateUrl: OgLoadingSpinnerView, link: (scope: OgLoadingSpinnerScope): string => (scope.loadingMessage = "" === scope.message ? "Loading" : scope.message) }; return directive; } public static factory(): OgLoadingSpinnerDirective { return new OgLoadingSpinnerDirective(); } } OgLoadingSpinnerDirective.factory.$inject = [];
import "../css/og-loading-spinner.less"; import { OgLoadingSpinnerScope } from "og-components/og-loading-spinner/types"; import OgLoadingSpinnerView from "og-components/og-loading-spinner/views/loading.html"; export default class OgLoadingSpinnerDirective { public constructor() { const directive: angular.IDirective = { restrict: "A", scope: { message: "=ogLoadingSpinner" }, templateUrl: OgLoadingSpinnerView, link: (scope: OgLoadingSpinnerScope): string => (scope.loadingMessage = undefined === scope.message || "" === scope.message ? "Loading" : scope.message) }; return directive; } public static factory(): OgLoadingSpinnerDirective { return new OgLoadingSpinnerDirective(); } } OgLoadingSpinnerDirective.factory.$inject = [];
Fix loading spinner message not appearing
Fix loading spinner message not appearing
TypeScript
mit
scottohara/loot,scottohara/loot,scottohara/loot,scottohara/loot
--- +++ @@ -10,7 +10,7 @@ message: "=ogLoadingSpinner" }, templateUrl: OgLoadingSpinnerView, - link: (scope: OgLoadingSpinnerScope): string => (scope.loadingMessage = "" === scope.message ? "Loading" : scope.message) + link: (scope: OgLoadingSpinnerScope): string => (scope.loadingMessage = undefined === scope.message || "" === scope.message ? "Loading" : scope.message) }; return directive;
d8044519a69accdee907ce474408634c9e52799a
src/lib/nameOldEigenQueries.ts
src/lib/nameOldEigenQueries.ts
import { error } from "./loggers" import { RequestHandler } from "express" export const nameOldEigenQueries: RequestHandler = (req, _res, next) => { const agent = req.headers["user-agent"] if (agent && agent.includes("Eigen")) { const { query } = req.body as { query: string } if (!query.startsWith("query ")) { if (query.includes("saved_artworks")) { // https://github.com/artsy/eigen/blob/master/Artsy/Networking/favorites.graphql req.body.query = `query FavoritesQuery ${query}` } else if (query.includes("sale_artworks")) { // https://github.com/artsy/eigen/blob/master/Artsy/Networking/artworks_in_sale.graphql req.body.query = `query ArtworksInSaleQuery ${query}` } else if (query.includes("sale_artworks")) { // https://github.com/artsy/eigen/blob/master/Artsy/Networking/conversations.graphql req.body.query = `query TotalUnreadCountQuery ${query}` } else { error(`Unpexpected Eigen query: ${query}`) } } } next() }
import { error } from "./loggers" import { RequestHandler } from "express" export const nameOldEigenQueries: RequestHandler = (req, _res, next) => { const agent = req.headers["user-agent"] if (agent && agent.includes("Eigen")) { const { query } = req.body as { query: string } if (!query.startsWith("query ")) { if (query.includes("saved_artworks")) { // https://github.com/artsy/eigen/blob/master/Artsy/Networking/favorites.graphql req.body.query = `query FavoritesQuery ${query}` } else if (query.includes("sale_artworks")) { // https://github.com/artsy/eigen/blob/master/Artsy/Networking/artworks_in_sale.graphql req.body.query = `query ArtworksInSaleQuery ${query}` } else if (query.includes("totalUnreadCount")) { // https://github.com/artsy/eigen/blob/master/Artsy/Networking/conversations.graphql req.body.query = `query TotalUnreadCountQuery ${query}` } else { error(`Unpexpected Eigen query: ${query}`) } } } next() }
Fix typo in catch for unread count in eigen
Fix typo in catch for unread count in eigen
TypeScript
mit
artsy/metaphysics,artsy/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1
--- +++ @@ -12,7 +12,7 @@ } else if (query.includes("sale_artworks")) { // https://github.com/artsy/eigen/blob/master/Artsy/Networking/artworks_in_sale.graphql req.body.query = `query ArtworksInSaleQuery ${query}` - } else if (query.includes("sale_artworks")) { + } else if (query.includes("totalUnreadCount")) { // https://github.com/artsy/eigen/blob/master/Artsy/Networking/conversations.graphql req.body.query = `query TotalUnreadCountQuery ${query}` } else {
0e83f14c13658eeac4449809476e4cf405221264
packages/lesswrong/components/comments/CommentsItem/_comments-unit-tests.tsx
packages/lesswrong/components/comments/CommentsItem/_comments-unit-tests.tsx
import React from 'react'; import { shallow, configure } from 'enzyme'; import { expect } from 'meteor/practicalmeteor:chai'; import { CommentsItem } from './CommentsItem' import Adapter from 'enzyme-adapter-react-16'; configure({ adapter: new Adapter() }) export const commentMockProps = { router: {params:""}, comment: {_id:"", user:{username:""}}, post:{_id:"",slug:""}, classes: {commentStyling:{}} } describe('CommentsItem', () => { const CommentsItemUntyped = (CommentsItem as any); it('renders reply-button when logged in', () => { const commentsItem = shallow(<CommentsItemUntyped currentUser={{}} {...commentMockProps} />) expect(commentsItem.find(".comments-item-reply-link")).to.have.length(1); }); it('renders reply-button when NOT logged in', () => { const commentsItem = shallow(<CommentsItemUntyped {...commentMockProps} />) expect(commentsItem.find(".comments-item-reply-link")).to.have.length(1); }); });
// STUBBED // These unit tests were super brittle/broken because they use Enzyme shallow // rendering rather than real rendering, and were made without all the // infrastructure for setting up a proper React context for use in unit tests. // If we make a better React component unit testing setup, maybe bring these // back. /*import React from 'react'; import { shallow, configure } from 'enzyme'; import { expect } from 'meteor/practicalmeteor:chai'; import { CommentsItem } from './CommentsItem' import Adapter from 'enzyme-adapter-react-16'; configure({ adapter: new Adapter() }) export const commentMockProps = { router: {params:""}, comment: {_id:"", user:{username:""}}, post:{_id:"",slug:""}, classes: {commentStyling:{}} } describe('CommentsItem', () => { const CommentsItemUntyped = (CommentsItem as any); it('renders reply-button when logged in', () => { const commentsItem = shallow(<CommentsItemUntyped currentUser={{}} {...commentMockProps} />) expect(commentsItem.find(".comments-item-reply-link")).to.have.length(1); }); it('renders reply-button when NOT logged in', () => { const commentsItem = shallow(<CommentsItemUntyped {...commentMockProps} />) expect(commentsItem.find(".comments-item-reply-link")).to.have.length(1); }); });*/
Remove broken Enzyme shallow-rendering unit tests
Remove broken Enzyme shallow-rendering unit tests
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -1,4 +1,10 @@ -import React from 'react'; +// STUBBED +// These unit tests were super brittle/broken because they use Enzyme shallow +// rendering rather than real rendering, and were made without all the +// infrastructure for setting up a proper React context for use in unit tests. +// If we make a better React component unit testing setup, maybe bring these +// back. +/*import React from 'react'; import { shallow, configure } from 'enzyme'; import { expect } from 'meteor/practicalmeteor:chai'; import { CommentsItem } from './CommentsItem' @@ -22,4 +28,4 @@ const commentsItem = shallow(<CommentsItemUntyped {...commentMockProps} />) expect(commentsItem.find(".comments-item-reply-link")).to.have.length(1); }); -}); +});*/
90be56f98f0aeef64225db2589083786d02672c8
modules/layout/styled-component.tsx
modules/layout/styled-component.tsx
import * as React from 'react' import {View} from 'react-native' import type {ViewStyle} from 'react-native' export type PropsType = { children?: React.ReactNode style?: ViewStyle props: ViewStyle } export const StyledComponent = ({children, style, ...props}: PropsType) => { return <View style={[props, style]}>{children}</View> }
import * as React from 'react' import {View} from 'react-native' import type {ViewStyle} from 'react-native' export interface PropsType extends ViewStyle { children?: React.ReactNode style?: ViewStyle } export const StyledComponent = ({children, style, ...props}: PropsType) => { return <View style={[props, style]}>{children}</View> }
Replace PropsType implementation with extended interface
m/layout: Replace PropsType implementation with extended interface It looks like most of the uses of StyledComponent (SC) were aiming to pass down keys of ViewStyle to the underlying style prop on View. To replicate this, we can _extend the interface_, essentially just adding a couple of extra props for the child and baked-in style prop. Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
TypeScript
agpl-3.0
StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native
--- +++ @@ -2,10 +2,9 @@ import {View} from 'react-native' import type {ViewStyle} from 'react-native' -export type PropsType = { +export interface PropsType extends ViewStyle { children?: React.ReactNode style?: ViewStyle - props: ViewStyle } export const StyledComponent = ({children, style, ...props}: PropsType) => {
6710356c13f0639181755863914fdcdd287661bc
Mechanism/RenderObjects/Animations/Animation.ts
Mechanism/RenderObjects/Animations/Animation.ts
class Animation { private animators: { [animatedPropertyName: string]: Animator } = { }; private currentFrame = 0; finalAction: FinalAnimationAction; isRunning: boolean; private animationEndedHost = ObservableEventHost.create<() => void>(); get animationEnded(): ObservableEvent<() => void> { return this.animationEndedHost; }; constructor(public frameCount: number) { } run(frame: number = 0): void { this.currentFrame = frame; this.isRunning = true; } setAnimator(animator: Animator) { this.animators[animator.name] = animator; } advance(frameCount: number, object: RenderObject): FinalAnimationAction | undefined { const nextFrame = this.currentFrame + frameCount; const animators = this.animators; for (const animatorName in animators) { if (animators.hasOwnProperty(animatorName)) { animators[animatorName].apply(object, nextFrame); } } this.currentFrame = nextFrame; if (this.frameCount === nextFrame) { this.isRunning = false; this.animationEndedHost.dispatch(fn => {}); return this.finalAction; } return undefined; } static loop(frame: number = 0): FinalAnimationAction { return new FinalAnimationAction(frame); } static goto(frame: number = 0, animation: string): FinalAnimationAction { return new FinalAnimationAction(frame, animation); } }
class Animation { private animators: { [animatedPropertyName: string]: Animator } = { }; private currentFrame = 0; finalAction: FinalAnimationAction; isRunning: boolean; private animationEndedHost = ObservableEventHost.create<() => void>(); get animationEnded(): ObservableEvent<() => void> { return this.animationEndedHost; }; constructor(public frameCount: number) { } run(frame: number = 0): void { this.currentFrame = frame; this.isRunning = true; } setAnimator(animator: Animator) { this.animators[animator.name] = animator; } advance(frameCount: number, object: RenderObject): FinalAnimationAction | undefined { const nextFrame = this.currentFrame + frameCount; const animators = this.animators; for (const animatorName in animators) { if (animators.hasOwnProperty(animatorName)) { animators[animatorName].apply(object, nextFrame); } } this.currentFrame = nextFrame; if (this.frameCount === nextFrame) { this.isRunning = false; this.animationEndedHost.dispatch(fn => fn()); return this.finalAction; } return undefined; } static loop(frame: number = 0): FinalAnimationAction { return new FinalAnimationAction(frame); } static goto(frame: number = 0, animation: string): FinalAnimationAction { return new FinalAnimationAction(frame, animation); } }
Fix animation ended event dispatching.
Fix animation ended event dispatching.
TypeScript
apache-2.0
Dia6lo/Mechanism,Dia6lo/Mechanism,Dia6lo/Mechanism
--- +++ @@ -31,7 +31,7 @@ this.currentFrame = nextFrame; if (this.frameCount === nextFrame) { this.isRunning = false; - this.animationEndedHost.dispatch(fn => {}); + this.animationEndedHost.dispatch(fn => fn()); return this.finalAction; } return undefined;
26d736d4e15cedc3731976bd6b0c50ae3e6ade7a
client/Commands/Command.test.ts
client/Commands/Command.test.ts
import { getDefaultSettings } from "../Settings/Settings"; import { Store } from "../Utility/Store"; import { Command } from "./Command"; describe("Command", () => { test("Should use a default keybinding", () => { const command = new Command("some-command-id", "Some Command", jest.fn(), "default-keybinding", "square"); expect(command.KeyBinding).toEqual("default-keybinding"); }); test("Should load a saved keybinding", () => { const settings = getDefaultSettings(); settings.Commands = [ { Name: "some-command-id", KeyBinding: "saved-keybinding", ShowOnActionBar: true } ]; Store.Save(Store.User, "Settings", settings); const command = new Command("some-command-id", "Some Command", jest.fn(), "default-keybinding", "square"); expect(command.KeyBinding).toEqual("saved-keybinding"); }); test("Should load a legacy keybinding", () => { Store.Save(Store.KeyBindings, "Add Note", "legacy-keybinding"); const command = new Command("add-tag", "Add Tag", jest.fn(), "default-keybinding", "square"); expect(command.KeyBinding).toEqual("legacy-keybinding"); }); });
import { getDefaultSettings } from "../Settings/Settings"; import { Store } from "../Utility/Store"; import { Command } from "./Command"; describe("Command", () => { test("Should use a default keybinding", () => { const command = new Command("some-command-id", "Some Command", jest.fn(), "default-keybinding", "square"); expect(command.KeyBinding).toEqual("default-keybinding"); }); test("Should load a saved keybinding", () => { const settings = getDefaultSettings(); settings.Commands = [ { Name: "some-command-id", KeyBinding: "saved-keybinding", ShowOnActionBar: true } ]; Store.Save(Store.User, "Settings", settings); const command = new Command("some-command-id", "Some Command", jest.fn(), "default-keybinding", "square"); expect(command.KeyBinding).toEqual("saved-keybinding"); }); test("Should load a keybinding with a legacy id", () => { const settings = getDefaultSettings(); settings.Commands = [ { Name: "Add Note", KeyBinding: "legacy-keybinding", ShowOnActionBar: true } ]; Store.Save(Store.User, "Settings", settings); const command = new Command("add-tag", "Add Tag", jest.fn(), "default-keybinding", "square"); expect(command.KeyBinding).toEqual("legacy-keybinding"); }); test("Should load a keybinding from the old Store", () => { Store.Save(Store.KeyBindings, "Add Note", "legacy-keybinding"); const command = new Command("add-tag", "Add Tag", jest.fn(), "default-keybinding", "square"); expect(command.KeyBinding).toEqual("legacy-keybinding"); }); });
Test both legacy keybinding scenarios
Test both legacy keybinding scenarios
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -23,7 +23,21 @@ expect(command.KeyBinding).toEqual("saved-keybinding"); }); - test("Should load a legacy keybinding", () => { + test("Should load a keybinding with a legacy id", () => { + const settings = getDefaultSettings(); + settings.Commands = [ + { + Name: "Add Note", + KeyBinding: "legacy-keybinding", + ShowOnActionBar: true + } + ]; + Store.Save(Store.User, "Settings", settings); + const command = new Command("add-tag", "Add Tag", jest.fn(), "default-keybinding", "square"); + expect(command.KeyBinding).toEqual("legacy-keybinding"); + }); + + test("Should load a keybinding from the old Store", () => { Store.Save(Store.KeyBindings, "Add Note", "legacy-keybinding"); const command = new Command("add-tag", "Add Tag", jest.fn(), "default-keybinding", "square"); expect(command.KeyBinding).toEqual("legacy-keybinding");
6d34951db9cb4511b8b2407090a060b14f9e8fb3
src/index.ts
src/index.ts
import { Observable } from 'rxjs'; import { FilterOptions } from './collection'; export { Database } from './database'; export { Collection } from './collection'; export { Query } from './query'; /** * IDatabase * ... */ export interface IDatabase { collection( name ): ICollection; } /** * ICollection * ... */ export interface ICollection { find( filter: any, options: FilterOptions ): IQuery; insert( doc: any ): Observable<any>; update( filter: any, changes: any ): Observable<any[]>; remove( filter: any ): Observable<any[]>; } /** * IQuery * ... */ export interface IQuery { value(): Observable<any[]>; } /** * Persistor * ... */ export interface IPersistorFactory { create( collectionName: string ): IPersistor; } /** * Persistor * ... */ export interface IPersistor { load(): Promise<any[]>; store( docs: any[]): Promise<any>; remove( docs: any[]): Promise<any>; }
import { Observable } from 'rxjs'; import { FilterOptions } from './collection'; export { Database } from './database'; export { Collection } from './collection'; export { Query } from './query'; /** * IDatabase * IDatabase contains a set of collections which stores documents. */ export interface IDatabase { collection( name ): ICollection; } /** * ICollection * ICollection contains a set of documents which can be manipulated * using collection methods. It uses a IPersistor to store data. */ export interface ICollection { find( filter: any, options: FilterOptions ): IQuery; insert( doc: any ): Observable<any>; update( filter: any, changes: any ): Observable<any[]>; remove( filter: any ): Observable<any[]>; } /** * IQuery * IQuery wraps the result of a collection find query. */ export interface IQuery { value(): Observable<any[]>; } /** * IPersistorFactory * IPersistorFactory creates a Persistors for collections to store data. */ export interface IPersistorFactory { create( collectionName: string ): IPersistor; } /** * IPersistor * IPersistor stores data in a permanent storage location. With default * options, data may get stored in IndexedDB, WebSQL or LocalStorage. * Each collection has it's own IPersistor instance to store data. */ export interface IPersistor { load(): Promise<any[]>; store( docs: any[]): Promise<any>; remove( docs: any[]): Promise<any>; }
Add comments for exported interface types
Add comments for exported interface types
TypeScript
mit
Cinergix/rxdata,Cinergix/rxdata
--- +++ @@ -1,12 +1,13 @@ import { Observable } from 'rxjs'; import { FilterOptions } from './collection'; + export { Database } from './database'; export { Collection } from './collection'; export { Query } from './query'; /** * IDatabase - * ... + * IDatabase contains a set of collections which stores documents. */ export interface IDatabase { collection( name ): ICollection; @@ -14,7 +15,8 @@ /** * ICollection - * ... + * ICollection contains a set of documents which can be manipulated + * using collection methods. It uses a IPersistor to store data. */ export interface ICollection { find( filter: any, options: FilterOptions ): IQuery; @@ -25,23 +27,25 @@ /** * IQuery - * ... + * IQuery wraps the result of a collection find query. */ export interface IQuery { value(): Observable<any[]>; } /** - * Persistor - * ... + * IPersistorFactory + * IPersistorFactory creates a Persistors for collections to store data. */ export interface IPersistorFactory { create( collectionName: string ): IPersistor; } /** - * Persistor - * ... + * IPersistor + * IPersistor stores data in a permanent storage location. With default + * options, data may get stored in IndexedDB, WebSQL or LocalStorage. + * Each collection has it's own IPersistor instance to store data. */ export interface IPersistor { load(): Promise<any[]>;
f8bf68eccb7d9c818e02bc4cc6b171796b59ef47
src/index.ts
src/index.ts
/* tslint:disable */ import Task from './task'; import Either from './either'; import Option from './option'; import * as Object from './object' import * as List from './list'; import * as Math from './math'; import * as String from './string'; import id from './id'; import print from './print'; export { Task, Either, Option, Object, List, Math, String, id, print }
/* tslint:disable */ import Task from './task'; import Either from './either'; import Option from './option'; import * as _Object from './object'; import * as List from './list'; import * as Math from './math'; import * as String from './string'; import id from './id'; import print from './print'; export { Task, Either, Option, _Object as Object, List, Math, String, id, print }
Fix the conflict with Object
Fix the conflict with Object
TypeScript
mit
AyaMorisawa/node-powerful
--- +++ @@ -3,11 +3,11 @@ import Task from './task'; import Either from './either'; import Option from './option'; -import * as Object from './object' +import * as _Object from './object'; import * as List from './list'; import * as Math from './math'; import * as String from './string'; import id from './id'; import print from './print'; -export { Task, Either, Option, Object, List, Math, String, id, print } +export { Task, Either, Option, _Object as Object, List, Math, String, id, print }
83718b0c43bacf759a0f6034e09ab63d839fd774
src/react/reactquestionhtml.tsx
src/react/reactquestionhtml.tsx
import * as React from "react"; import { SurveyQuestionElementBase } from "./reactquestionelement"; import { QuestionHtmlModel } from "../question_html"; import { ReactQuestionFactory } from "./reactquestionfactory"; export class SurveyQuestionHtml extends SurveyQuestionElementBase { constructor(props: any) { super(props); } protected get question(): QuestionHtmlModel { return this.questionBase as QuestionHtmlModel; } render(): JSX.Element { if (!this.question || !this.question.html) return null; var htmlValue = { __html: this.question.locHtml.renderedHtml }; return ( <div className={this.question.cssClasses} dangerouslySetInnerHTML={htmlValue} /> ); } } ReactQuestionFactory.Instance.registerQuestion("html", props => { return React.createElement(SurveyQuestionHtml, props); });
import * as React from "react"; import { SurveyQuestionElementBase } from "./reactquestionelement"; import { QuestionHtmlModel } from "../question_html"; import { ReactQuestionFactory } from "./reactquestionfactory"; export class SurveyQuestionHtml extends SurveyQuestionElementBase { constructor(props: any) { super(props); } protected get question(): QuestionHtmlModel { return this.questionBase as QuestionHtmlModel; } render(): JSX.Element { if (!this.question || !this.question.html) return null; var htmlValue = { __html: this.question.locHtml.renderedHtml }; return ( <div className={this.question.cssClasses.root} dangerouslySetInnerHTML={htmlValue} /> ); } } ReactQuestionFactory.Instance.registerQuestion("html", props => { return React.createElement(SurveyQuestionHtml, props); });
Fix the bug with html question css class in react
Fix the bug with html question css class in react
TypeScript
mit
surveyjs/surveyjs,andrewtelnov/surveyjs,andrewtelnov/surveyjs,andrewtelnov/surveyjs,surveyjs/surveyjs,surveyjs/surveyjs,surveyjs/surveyjs
--- +++ @@ -15,7 +15,7 @@ var htmlValue = { __html: this.question.locHtml.renderedHtml }; return ( <div - className={this.question.cssClasses} + className={this.question.cssClasses.root} dangerouslySetInnerHTML={htmlValue} /> );
ff6cd91aaecbafb1aa2335724e7f7ab6cc469395
src/eds-ui/src/main/frontend/app/dashboard/queue.component.ts
src/eds-ui/src/main/frontend/app/dashboard/queue.component.ts
import {Component, Input} from "@angular/core"; import {RabbitQueue} from "../queueing/models/RabbitQueue"; @Component({ selector: 'rabbit-queue', template: ` <div class="progress"> <div class="small">{{getName(queue?.name)}} ({{queue?.messages_ready}} @ {{queue?.message_stats?.publish_details.rate}}/s)</div> <ngb-progressbar min="0" max="{{queueRateMax}}" value="{{item?.publish_details?.rate}}" [ngClass]="getQueueRateAsWidthStylePercent(queue)"></ngb-progressbar> </div> ` }) export class QueueComponent { @Input() queue : RabbitQueue; queueRateMax : number = 100; getQueueRateAsWidthStylePercent(queue : RabbitQueue){ if (!queue || !queue.message_stats || !queue.message_stats.publish_details || !queue.message_stats.publish_details.rate) return {width : '0%'}; var pcnt = (queue.message_stats.publish_details.rate * 100) / this.queueRateMax; return {width : pcnt + '%'}; } getName(name : String) { var hyphen = name.indexOf('-'); if (hyphen === -1) return name; return name.substr(hyphen+1); } }
import {Component, Input} from "@angular/core"; import {RabbitQueue} from "../queueing/models/RabbitQueue"; @Component({ selector: 'rabbit-queue', template: ` <div class="progress"> <div class="small">{{getName(queue?.name)}} ({{queue?.messages_ready}} @ {{queue?.message_stats?.publish_details?.rate}}/s)</div> <ngb-progressbar min="0" max="{{queueRateMax}}" value="{{item?.publish_details?.rate}}" [ngClass]="getQueueRateAsWidthStylePercent(queue)"></ngb-progressbar> </div> ` }) export class QueueComponent { @Input() queue : RabbitQueue; queueRateMax : number = 100; getQueueRateAsWidthStylePercent(queue : RabbitQueue){ if (!queue || !queue.message_stats || !queue.message_stats.publish_details || !queue.message_stats.publish_details.rate) return {width : '0%'}; var pcnt = (queue.message_stats.publish_details.rate * 100) / this.queueRateMax; return {width : pcnt + '%'}; } getName(name : String) { var hyphen = name.indexOf('-'); if (hyphen === -1) return name; return name.substr(hyphen+1); } }
Fix for message rate when not yet published
Fix for message rate when not yet published
TypeScript
apache-2.0
endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS
--- +++ @@ -6,7 +6,7 @@ template: ` <div class="progress"> - <div class="small">{{getName(queue?.name)}} ({{queue?.messages_ready}} @ {{queue?.message_stats?.publish_details.rate}}/s)</div> + <div class="small">{{getName(queue?.name)}} ({{queue?.messages_ready}} @ {{queue?.message_stats?.publish_details?.rate}}/s)</div> <ngb-progressbar min="0" max="{{queueRateMax}}"
182094049249ac43391946647c1bf11315ef2d97
webpack/__tests__/verification_support_test.ts
webpack/__tests__/verification_support_test.ts
jest.mock("../util", () => ({ getParam: () => "STUB_PARAM" })); jest.mock("axios", () => ({ default: { put: () => ({ data: { FAKE_TOKEN: true } }) } })); jest.mock("../session", () => ({ Session: { replaceToken: jest.fn() } })); jest.mock("../api/api", () => ({ API: { setBaseUrl: jest.fn(), fetchBrowserLocation: jest.fn(() => "http://altavista.com:80"), current: { verificationPath: jest.fn((t: string) => `/stubbed/${t}`), baseUrl: "http://altavista.com:80" } } })); import { fail, FAILURE_PAGE, attempt } from "../verification_support"; import { API } from "../api/api"; import { Session } from "../session"; import axios from "axios"; import { getParam } from "../util"; describe("fail()", () => { it("writes a failure message", () => { expect(fail).toThrow(); expect(document.documentElement.outerHTML).toContain(FAILURE_PAGE); }); }); describe("attempt()", () => { it("tries to verify the user", async () => { await attempt(); expect(Session.replaceToken).toHaveBeenCalledWith({ "FAKE_TOKEN": true }); const FAKE_PATH = API.current.verificationPath(getParam("token")); expect(axios.put).toHaveBeenCalledWith(FAKE_PATH); }); });
jest.mock("../util", () => ({ getParam: () => "STUB_PARAM" })); jest.mock("axios", () => ({ default: { put: jest.fn(() => ({ data: { FAKE_TOKEN: true } })) } })); jest.mock("../session", () => ({ Session: { replaceToken: jest.fn() } })); jest.mock("../api/api", () => ({ API: { setBaseUrl: jest.fn(), fetchBrowserLocation: jest.fn(() => "http://altavista.com:80"), current: { verificationPath: jest.fn((t: string) => `/stubbed/${t}`), baseUrl: "http://altavista.com:80" } } })); import { fail, FAILURE_PAGE, attempt } from "../verification_support"; import { API } from "../api/api"; import { Session } from "../session"; import axios from "axios"; import { getParam } from "../util"; describe("fail()", () => { it("writes a failure message", () => { expect(fail).toThrow(); expect(document.documentElement.outerHTML).toContain(FAILURE_PAGE); }); }); describe("attempt()", () => { it("tries to verify the user", async () => { await attempt(); expect(Session.replaceToken).toHaveBeenCalledWith({ "FAKE_TOKEN": true }); const FAKE_PATH = API.current.verificationPath(getParam("token")); expect(axios.put).toHaveBeenCalledWith(FAKE_PATH); }); });
Use jest.fn() instead of real function
Use jest.fn() instead of real function
TypeScript
mit
RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,FarmBot/farmbot-web-app,FarmBot/farmbot-web-app,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app
--- +++ @@ -2,7 +2,7 @@ jest.mock("axios", () => ({ default: { - put: () => ({ data: { FAKE_TOKEN: true } }) + put: jest.fn(() => ({ data: { FAKE_TOKEN: true } })) } }));
edd74e64c39ff52f08551016559c1c28184020fe
src/__tests__/BooleanField.spec.ts
src/__tests__/BooleanField.spec.ts
import { assert as t } from "chai"; import BooleanField from "../BooleanField"; describe("Checkbox", () => { it("should instantiate with default Options", () => { const field = new BooleanField(); t.equal(field.defaultValue, false); t.equal(typeof field.validator, "function"); const field2 = new BooleanField(true, { disabled: true }); t.equal(field2.defaultValue, true); t.equal(field2.disabled, true); const field3 = new BooleanField(true); t.equal(field3.defaultValue, true); t.equal(field3.disabled, false); }); it("should toggle", () => { const field = new BooleanField(); t.equal(field.value, false); field.toggle(); t.equal(field.value, true); }); });
import { assert as t } from "chai"; import BooleanField from "../BooleanField"; describe("Checkbox", () => { it("should instantiate with default Options", () => { const field = new BooleanField(); t.equal(field.defaultValue, false); t.equal(typeof field.validator, "function"); const field2 = new BooleanField(true, { disabled: true }); t.equal(field2.defaultValue, true); t.equal(field2.disabled, true); const field3 = new BooleanField(true); t.equal(field3.defaultValue, true); t.equal(field3.disabled, false); }); it("should toggle", () => { const field = new BooleanField(); t.equal(field.value, false); field.toggle(); t.equal(field.value, true); const field2 = new BooleanField(false); t.equal(field2.value, false); field2.toggle(); t.equal(field2.value, true); }); });
Extend BooleanField value test case
Extend BooleanField value test case
TypeScript
mit
marvinhagemeister/mobx-form-reactions
--- +++ @@ -22,5 +22,11 @@ field.toggle(); t.equal(field.value, true); + + const field2 = new BooleanField(false); + t.equal(field2.value, false); + + field2.toggle(); + t.equal(field2.value, true); }); });
b3f2ea8edd74bb6321cd8caf3e9ef3cc90158a7d
src/main-window/saveBeforeClosing.ts
src/main-window/saveBeforeClosing.ts
import { BrowserWindow, dialog, MessageBoxOptions } from "electron" import { userWantsToSaveTranscript } from "../app/ipcChannelNames" import { setEditorIsDirty } from "./saveFile" const dialogOptions: MessageBoxOptions = { title: "Save changes before closing?", type: "question", message: "Do you want to save your most recent transcript changes before you go?", buttons: ["Save Transcript", "Don't Save Transcript"], defaultId: 0, } export const saveBeforeClosing = (window: BrowserWindow) => { dialog.showMessageBox(window, dialogOptions, (response: number) => { if (response === 0) { window.webContents.send(userWantsToSaveTranscript) return null } else if (response === 1) { setEditorIsDirty(false) return null } }) } // mainWindow.on("close", function(e) { // var choice = require("electron").dialog.showMessageBox(this, { // type: "question", // buttons: ["Yes", "No"], // title: "Confirm", // message: "Are you sure you want to quit?", // }) // if (choice == 1) { // e.preventDefault() // } // })
import { BrowserWindow, dialog, ipcRenderer, MessageBoxOptions } from "electron" import { userWantsToSaveTranscript } from "../app/ipcChannelNames" import { setEditorIsDirty } from "./saveFile" const dialogOptions: MessageBoxOptions = { title: "Save changes before closing?", type: "question", message: "Do you want to save your most recent transcript changes before you go?", buttons: ["Save Transcript", "Don't Save Transcript"], defaultId: 0, } export const saveBeforeClosing = (window: BrowserWindow) => { dialog.showMessageBox(window, dialogOptions, (response: number) => { if (response === 0) { ipcRenderer.sendSync(userWantsToSaveTranscript) return null } else if (response === 1) { setEditorIsDirty(false) window.close() } }) } // mainWindow.on("close", function(e) { // var choice = require("electron").dialog.showMessageBox(this, { // type: "question", // buttons: ["Yes", "No"], // title: "Confirm", // message: "Are you sure you want to quit?", // }) // if (choice == 1) { // e.preventDefault() // } // })
Quit when the editor isn't dirty
Quit when the editor isn't dirty
TypeScript
agpl-3.0
briandk/transcriptase,briandk/transcriptase
--- +++ @@ -1,4 +1,4 @@ -import { BrowserWindow, dialog, MessageBoxOptions } from "electron" +import { BrowserWindow, dialog, ipcRenderer, MessageBoxOptions } from "electron" import { userWantsToSaveTranscript } from "../app/ipcChannelNames" import { setEditorIsDirty } from "./saveFile" @@ -13,11 +13,12 @@ export const saveBeforeClosing = (window: BrowserWindow) => { dialog.showMessageBox(window, dialogOptions, (response: number) => { if (response === 0) { - window.webContents.send(userWantsToSaveTranscript) + ipcRenderer.sendSync(userWantsToSaveTranscript) + return null } else if (response === 1) { setEditorIsDirty(false) - return null + window.close() } }) }
9ab7b43d9a885db78522c542dc8cb365eb35e407
src/modules/EmojiTranslatorModule.ts
src/modules/EmojiTranslatorModule.ts
import { emojiData } from "../utils/emojiData"; export class EmojiTranslatorModule { public init() { const input = document.getElementById('input') as HTMLTextAreaElement; input.addEventListener('keyup', event => { // TODO: Restore cursor to where it was. if (event.which !== 32) return; input.value = input.value.split(' ').map(word => { const found = emojiData.find(item => item.triggers.includes(word)); if (found) { return found.emoji; } return word; }).join(' '); }); } }
import { emojiData } from "../utils/emojiData"; export class EmojiTranslatorModule { public init() { const input = document.getElementById("input") as HTMLTextAreaElement; input.addEventListener("keyup", event => { const { selectionStart, selectionEnd } = input; if (event.which !== 32) return; input.value = input.value .split(" ") .map(word => { const found = emojiData.find(item => item.triggers.includes(word)); if (found) { return found.emoji; } return word; }) .join(" "); input.setSelectionRange(selectionStart, selectionEnd); }); } }
Maintain cursor position when replacing emojis.
Maintain cursor position when replacing emojis. Fixes #4.
TypeScript
isc
MadaraUchiha/se-chat-dark-theme-plus
--- +++ @@ -2,18 +2,21 @@ export class EmojiTranslatorModule { public init() { - const input = document.getElementById('input') as HTMLTextAreaElement; - input.addEventListener('keyup', event => { - // TODO: Restore cursor to where it was. + const input = document.getElementById("input") as HTMLTextAreaElement; + input.addEventListener("keyup", event => { + const { selectionStart, selectionEnd } = input; if (event.which !== 32) return; - input.value = input.value.split(' ').map(word => { - const found = emojiData.find(item => item.triggers.includes(word)); - if (found) { - return found.emoji; - } - return word; - }).join(' '); + input.value = input.value + .split(" ") + .map(word => { + const found = emojiData.find(item => item.triggers.includes(word)); + if (found) { + return found.emoji; + } + return word; + }) + .join(" "); + input.setSelectionRange(selectionStart, selectionEnd); }); - } }
09f7361f86e2597f5e652032384bcd819c768cba
src/models/config.ts
src/models/config.ts
import * as path from 'path'; import * as file from './file'; export interface IConfig { appKey?: string; userKey?: string; apiBaseUrl?: string; } export let appConfig: IConfig = { appKey: 'hmsk.HXLcVOeFfHhKPwZvdKBCgpyyTvtqrDAw', apiBaseUrl: 'http://api.misskey.xyz' }; let userConfigDirPath = path.join((process.platform === 'win32') ? process.env.HOMEPATH : process.env.HOME, '.disskey'); let userConfigFilePath = path.join(userConfigDirPath, 'config.json'); export function loadUserConfig(): Promise<IConfig> { 'use strict'; return file.existFile(userConfigFilePath).then(exist => { if (exist) { return file.readJsonFile<IConfig>(userConfigFilePath); } else { saveUserConfig(appConfig); return Promise.resolve({}); } }); } export function saveUserConfig(userConfig: IConfig): void { 'use strict'; file.writeJsonFile(userConfigFilePath, userConfig); }
import * as path from 'path'; import * as file from './file'; export interface IConfig { appKey?: string; userKey?: string; apiBaseUrl?: string; } export const appConfig: IConfig = { appKey: 'hmsk.HXLcVOeFfHhKPwZvdKBCgpyyTvtqrDAw', apiBaseUrl: 'http://api.misskey.xyz' }; const userConfigDirPath = path.join((process.platform === 'win32') ? process.env.HOMEPATH : process.env.HOME, '.disskey'); const userConfigFilePath = path.join(userConfigDirPath, 'config.json'); export function loadUserConfig(): Promise<IConfig> { 'use strict'; return file.existFile(userConfigFilePath).then(exist => { if (exist) { return file.readJsonFile<IConfig>(userConfigFilePath); } else { saveUserConfig(appConfig); return Promise.resolve({}); } }); } export function saveUserConfig(userConfig: IConfig): void { 'use strict'; file.writeJsonFile(userConfigFilePath, userConfig); }
Use const instead of let
Use const instead of let
TypeScript
mit
AyaMorisawa/Disskey,AyaMorisawa/Disskey,AyaMorisawa/Disskey
--- +++ @@ -7,13 +7,13 @@ apiBaseUrl?: string; } -export let appConfig: IConfig = { +export const appConfig: IConfig = { appKey: 'hmsk.HXLcVOeFfHhKPwZvdKBCgpyyTvtqrDAw', apiBaseUrl: 'http://api.misskey.xyz' }; -let userConfigDirPath = path.join((process.platform === 'win32') ? process.env.HOMEPATH : process.env.HOME, '.disskey'); -let userConfigFilePath = path.join(userConfigDirPath, 'config.json'); +const userConfigDirPath = path.join((process.platform === 'win32') ? process.env.HOMEPATH : process.env.HOME, '.disskey'); +const userConfigFilePath = path.join(userConfigDirPath, 'config.json'); export function loadUserConfig(): Promise<IConfig> { 'use strict';
e6c8cc73cfdcbdf61334ff46100215efda7dd7ab
lib/msal-common/src/request/CommonEndSessionRequest.ts
lib/msal-common/src/request/CommonEndSessionRequest.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { AccountInfo } from "../account/AccountInfo"; /** * CommonEndSessionRequest * - account - Account object that will be logged out of. All tokens tied to this account will be cleared. * - postLogoutRedirectUri - URI to navigate to after logout page. * - correlationId - Unique GUID set per request to trace a request end-to-end for telemetry purposes. * - idTokenHint - ID Token used by B2C to validate logout if required by the policy */ export type CommonEndSessionRequest = { correlationId: string account?: AccountInfo, postLogoutRedirectUri?: string | null, idTokenHint?: string };
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { AccountInfo } from "../account/AccountInfo"; /** * CommonEndSessionRequest * - account - Account object that will be logged out of. All tokens tied to this account will be cleared. * - postLogoutRedirectUri - URI to navigate to after logout page. * - correlationId - Unique GUID set per request to trace a request end-to-end for telemetry purposes. * - idTokenHint - ID Token used by B2C to validate logout if required by the policy */ export type CommonEndSessionRequest = { correlationId: string account?: AccountInfo | null, postLogoutRedirectUri?: string | null, idTokenHint?: string };
Update EndSessionRequest account type def
Update EndSessionRequest account type def
TypeScript
mit
AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js
--- +++ @@ -14,7 +14,7 @@ */ export type CommonEndSessionRequest = { correlationId: string - account?: AccountInfo, + account?: AccountInfo | null, postLogoutRedirectUri?: string | null, idTokenHint?: string };
e5aac0e59ae188c1d90e8441203ffff358c8448b
frontend/src/app/app.component.spec.ts
frontend/src/app/app.component.spec.ts
import { TestBed, async } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).compileComponents(); })); it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); })); it(`should have as title 'app works!'`, async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('app works!'); })); it('should render title in a h1 tag', async(() => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('app works!'); })); });
import { TestBed, async } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], imports: [ RouterTestingModule ] }).compileComponents(); })); it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); })); it(`should have as title 'app works!'`, async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('app works!'); })); it('should render title in a h1 tag', async(() => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('app works!'); })); });
Fix to the "router-outlet is not a known element" problem.
Fix to the "router-outlet is not a known element" problem.
TypeScript
mit
frt/happyscheduler,frt/happyscheduler,frt/happyscheduler,frt/happyscheduler
--- +++ @@ -1,4 +1,5 @@ import { TestBed, async } from '@angular/core/testing'; +import { RouterTestingModule } from '@angular/router/testing'; import { AppComponent } from './app.component'; @@ -8,6 +9,9 @@ declarations: [ AppComponent ], + imports: [ + RouterTestingModule + ] }).compileComponents(); }));
a1fc323e19d5d41667e0392606f41473e10446fb
Assets/.tiled/platforms.tsx
Assets/.tiled/platforms.tsx
<?xml version="1.0" encoding="UTF-8"?> <tileset name="platforms" tilewidth="128" tileheight="128" spacing="1" tilecount="4" columns="4"> <image source="C:/Users/Monkey/Desktop/platform sprites.png" width="515" height="128"/> <tile id="0"> <objectgroup draworder="index"> <object id="1" x="-0.333333" y="0.666667" width="128" height="74"/> </objectgroup> </tile> <tile id="1"> <objectgroup draworder="index"> <object id="1" x="52.6667" y="0.666667" width="74" height="128"/> </objectgroup> </tile> <tile id="2"> <objectgroup draworder="index"> <object id="1" x="0" y="52.6667" width="128" height="74"/> </objectgroup> </tile> <tile id="3"> <objectgroup draworder="index"> <object id="1" x="0.666667" y="0" width="74" height="128"/> </objectgroup> </tile> </tileset>
<?xml version="1.0" encoding="UTF-8"?> <tileset name="platforms" tilewidth="128" tileheight="128" spacing="1" tilecount="4" columns="4"> <image source="../Tiled2Unity/Textures/platform sprites.png" width="515" height="128"/> <tile id="0"> <objectgroup draworder="index"> <object id="1" x="-0.333333" y="0.666667" width="128" height="74"/> </objectgroup> </tile> <tile id="1"> <objectgroup draworder="index"> <object id="1" x="52.6667" y="0.666667" width="74" height="128"/> </objectgroup> </tile> <tile id="2"> <objectgroup draworder="index"> <object id="1" x="0" y="52.6667" width="128" height="74"/> </objectgroup> </tile> <tile id="3"> <objectgroup draworder="index"> <object id="1" x="0.666667" y="0" width="74" height="128"/> </objectgroup> </tile> </tileset>
Make tile image relative to project
Make tile image relative to project [skip ci]
TypeScript
mit
virtuoushub/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,whoa-algebraic/game-off-2016
--- +++ @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <tileset name="platforms" tilewidth="128" tileheight="128" spacing="1" tilecount="4" columns="4"> - <image source="C:/Users/Monkey/Desktop/platform sprites.png" width="515" height="128"/> + <image source="../Tiled2Unity/Textures/platform sprites.png" width="515" height="128"/> <tile id="0"> <objectgroup draworder="index"> <object id="1" x="-0.333333" y="0.666667" width="128" height="74"/>
b276bee3768a997a7b5ae290c0096f7517cd016b
packages/components/components/link/AppLink.tsx
packages/components/components/link/AppLink.tsx
import React from 'react'; import { Link as ReactRouterLink } from 'react-router-dom'; import { APP_NAMES, isSSOMode, isStandaloneMode } from 'proton-shared/lib/constants'; import { getAppHref, getAppHrefBundle } from 'proton-shared/lib/apps/helper'; import Href, { Props as HrefProps } from './Href'; import { useAuthentication, useConfig } from '../..'; export interface Props extends HrefProps { to: string; toApp?: APP_NAMES; } const AppLink = ({ to, toApp, children, ...rest }: Props) => { const { APP_NAME } = useConfig(); const authentication = useAuthentication(); if (toApp && toApp !== APP_NAME) { if (isSSOMode) { const localID = authentication.getLocalID?.(); const href = getAppHref(to, toApp, localID); return ( <Href target="_blank" {...rest} href={href}> {children} </Href> ); } if (isStandaloneMode) { return null; } const href = getAppHrefBundle(to, toApp); return ( <Href {...rest} href={href} target="_self"> {children} </Href> ); } return ( <ReactRouterLink to={to} {...rest}> {children} </ReactRouterLink> ); }; export default AppLink;
import React from 'react'; import { Link as ReactRouterLink } from 'react-router-dom'; import { APP_NAMES, isSSOMode, isStandaloneMode } from 'proton-shared/lib/constants'; import { getAppHref, getAppHrefBundle } from 'proton-shared/lib/apps/helper'; import Href, { Props as HrefProps } from './Href'; import { useAuthentication, useConfig } from '../..'; import Tooltip from '../tooltip/Tooltip'; export interface Props extends HrefProps { to: string; toApp?: APP_NAMES; } const AppLink = ({ to, toApp, children, ...rest }: Props) => { const { APP_NAME } = useConfig(); const authentication = useAuthentication(); if (toApp && toApp !== APP_NAME) { if (isSSOMode) { const localID = authentication.getLocalID?.(); const href = getAppHref(to, toApp, localID); return ( <Href target="_blank" {...rest} href={href}> {children} </Href> ); } if (isStandaloneMode) { return ( <Tooltip className={rest.className} title="Disabled in standalone mode"> {children} </Tooltip> ); } const href = getAppHrefBundle(to, toApp); return ( <Href {...rest} href={href} target="_self"> {children} </Href> ); } return ( <ReactRouterLink to={to} {...rest}> {children} </ReactRouterLink> ); }; export default AppLink;
Fix app link in standalone mode
Fix app link in standalone mode
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -5,6 +5,7 @@ import Href, { Props as HrefProps } from './Href'; import { useAuthentication, useConfig } from '../..'; +import Tooltip from '../tooltip/Tooltip'; export interface Props extends HrefProps { to: string; @@ -26,7 +27,11 @@ ); } if (isStandaloneMode) { - return null; + return ( + <Tooltip className={rest.className} title="Disabled in standalone mode"> + {children} + </Tooltip> + ); } const href = getAppHrefBundle(to, toApp); return (
fcb23ed2eeca80c1f58ecd5d05bdeb4c31ed93a2
packages/@sanity/desk-tool/src/panes/documentPane/changesPanel/helpers.ts
packages/@sanity/desk-tool/src/panes/documentPane/changesPanel/helpers.ts
import {Diff, AnnotationDetails, visitDiff} from '@sanity/field/diff' export function collectLatestAuthorAnnotations(diff: Diff): AnnotationDetails[] { const authorMap = new Map<string, AnnotationDetails>() visitDiff(diff, child => { if (child.action === 'unchanged' || !('annotation' in child) || !child.annotation) { return true } const {author, timestamp} = child.annotation const previous = authorMap.get(author) if (!previous || previous.timestamp < timestamp) { authorMap.set(author, child.annotation) } return true }) return Array.from(authorMap.values()).sort( (a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp) ) }
import {Diff, AnnotationDetails, visitDiff} from '@sanity/field/diff' export function collectLatestAuthorAnnotations(diff: Diff): AnnotationDetails[] { const authorMap = new Map<string, AnnotationDetails>() visitDiff(diff, child => { if (child.action === 'unchanged' || !('annotation' in child) || !child.annotation) { return true } const {author, timestamp} = child.annotation const previous = authorMap.get(author) if (!previous || previous.timestamp < timestamp) { authorMap.set(author, child.annotation) } return true }) return Array.from(authorMap.values()).sort((a, b) => (a.timestamp < b.timestamp ? 1 : -1)) }
Use string comparison for faster sorting
[desk-tool] Use string comparison for faster sorting
TypeScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
--- +++ @@ -16,7 +16,5 @@ return true }) - return Array.from(authorMap.values()).sort( - (a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp) - ) + return Array.from(authorMap.values()).sort((a, b) => (a.timestamp < b.timestamp ? 1 : -1)) }
9853ed4e216e8c49cf75d690ba504ad038230bb4
types/react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx
types/react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx
import * as React from 'react'; import { Text } from 'react-native'; import ScrollableTabView from 'react-native-scrollable-tab-view'; interface MyTextProperties extends React.Props<MyText> { tabLabel: string; text: string; } class MyText extends React.Component<MyTextProperties, {}> { constructor(props: MyTextProperties) { super(props); } render(): JSX.Element { return( <Text>this.props.text</Text> ); } } class ScrollableTabViewDemo extends React.Component<{}, {}> { constructor(props: ScrollableTabViewDemo) { super(props); } render(): JSX.Element { return ( <ScrollableTabView> <MyText tabLabel='t1' text='t1'></MyText> <MyText tabLabel='t2' text='t2'></MyText> <MyText tabLabel='t3' text='t3'></MyText> </ScrollableTabView> ); } protected componentWillMount?(): void { } protected componentWillUnmount?(): void { } }
import * as React from 'react'; import { Text } from 'react-native'; import ScrollableTabView from 'react-native-scrollable-tab-view'; interface MyTextProperties extends React.Props<MyText> { tabLabel: string; text: string; } class MyText extends React.Component<MyTextProperties, {}> { constructor(props: MyTextProperties) { super(props); } render(): JSX.Element { return( <Text>this.props.text</Text> ); } } class ScrollableTabViewDemo extends React.Component<{}, {}> { constructor(props: ScrollableTabViewDemo) { super(props); } render(): JSX.Element { return ( <ScrollableTabView> <MyText tabLabel='t1' text='t1'></MyText> <MyText tabLabel='t2' text='t2'></MyText> <MyText tabLabel='t3' text='t3'></MyText> </ScrollableTabView> ); } componentWillMount?(): void { } componentWillUnmount?(): void { } }
Make ComponentLifecycle inherited methods public
Make ComponentLifecycle inherited methods public
TypeScript
mit
arusakov/DefinitelyTyped,minodisk/DefinitelyTyped,benishouga/DefinitelyTyped,mcliment/DefinitelyTyped,zuzusik/DefinitelyTyped,minodisk/DefinitelyTyped,arusakov/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,aciccarello/DefinitelyTyped,abbasmhd/DefinitelyTyped,chrootsu/DefinitelyTyped,ashwinr/DefinitelyTyped,aciccarello/DefinitelyTyped,zuzusik/DefinitelyTyped,borisyankov/DefinitelyTyped,benliddicott/DefinitelyTyped,alexdresko/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,isman-usoh/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,zuzusik/DefinitelyTyped,arusakov/DefinitelyTyped,jimthedev/DefinitelyTyped,benishouga/DefinitelyTyped,QuatroCode/DefinitelyTyped,magny/DefinitelyTyped,ashwinr/DefinitelyTyped,AgentME/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,nycdotnet/DefinitelyTyped,QuatroCode/DefinitelyTyped,dsebastien/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,one-pieces/DefinitelyTyped,abbasmhd/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,alexdresko/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,magny/DefinitelyTyped,aciccarello/DefinitelyTyped,AgentME/DefinitelyTyped,amir-arad/DefinitelyTyped,jimthedev/DefinitelyTyped,jimthedev/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,nycdotnet/DefinitelyTyped,isman-usoh/DefinitelyTyped,chrootsu/DefinitelyTyped,benishouga/DefinitelyTyped,georgemarshall/DefinitelyTyped
--- +++ @@ -36,9 +36,9 @@ ); } - protected componentWillMount?(): void { + componentWillMount?(): void { } - protected componentWillUnmount?(): void { + componentWillUnmount?(): void { } }
6802b48fb128255429ffd11abc7bb034ac827f8a
build/webpack.web.config.ts
build/webpack.web.config.ts
import * as ExtractTextPlugin from 'extract-text-webpack-plugin'; import * as path from 'path'; import * as webpack from 'webpack'; import * as merge from 'webpack-merge'; import createConfig from './webpack.base.config'; const webConfig: webpack.Configuration = { entry: { db: path.resolve(__dirname, '../src/data/db.json') }, output: { library: 'VueThailandAddress' }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'db' }) ] }; const configs: webpack.Configuration[] = [ merge(createConfig(), webConfig, { output: { filename: '[name].js' }, plugins: [ new ExtractTextPlugin('vue-thailand-address.css') ] }), merge(createConfig(true), webConfig, { output: { filename: '[name].min.js' }, plugins: [ new ExtractTextPlugin('vue-thailand-address.min.css') ] }) ]; export default configs;
import * as ExtractTextPlugin from 'extract-text-webpack-plugin'; import * as path from 'path'; import * as webpack from 'webpack'; import * as merge from 'webpack-merge'; import createConfig from './webpack.base.config'; const webConfig: webpack.Configuration = { entry: { db: path.resolve(__dirname, '../src/data/db.json') }, output: { library: 'VueThailandAddress' }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'db' }) ], externals: { vue: 'Vue' } }; const configs: webpack.Configuration[] = [ merge(createConfig(), webConfig, { output: { filename: '[name].js' }, plugins: [ new ExtractTextPlugin('vue-thailand-address.css') ] }), merge(createConfig(true), webConfig, { output: { filename: '[name].min.js' }, plugins: [ new ExtractTextPlugin('vue-thailand-address.min.css') ] }) ]; export default configs;
Exclude vue from web bundle
:wrench: Exclude vue from web bundle
TypeScript
mit
gluons/vue-thailand-address
--- +++ @@ -16,7 +16,10 @@ new webpack.optimize.CommonsChunkPlugin({ name: 'db' }) - ] + ], + externals: { + vue: 'Vue' + } }; const configs: webpack.Configuration[] = [
2ec14cc5cedd6d5380b9ae58d9d925f462aaf962
src/service/window.service.ts
src/service/window.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class WindowService { get nativeWindow() : any { return _window(); } } function _window() : any { // return the global native browser window object return window || undefined; }
import { Injectable } from '@angular/core'; @Injectable() export class WindowService { get nativeWindow() : any { return _window(); } } function _window() : any { // return the global native browser window object return typeof window != 'undefined' ? window : undefined; }
Fix for window being undefined on Node.
Fix for window being undefined on Node. This is related to the same issue #6 where if you just try use window which is undeclared on Node then Angular Universal crashes. A simple check makes sure window is not undefined, before using it.
TypeScript
mit
MurhafSousli/ng2-sharebuttons,MurhafSousli/ng2-sharebuttons,tinesoft/ng2-sharebuttons,MurhafSousli/ng2-sharebuttons,tinesoft/ng2-sharebuttons,tinesoft/ng2-sharebuttons
--- +++ @@ -11,5 +11,5 @@ function _window() : any { // return the global native browser window object - return window || undefined; + return typeof window != 'undefined' ? window : undefined; }
a6c3ea1a2dbaf794c2765dc559ad088d334c569f
packages/universal-cookie-express/src/index.ts
packages/universal-cookie-express/src/index.ts
// @ts-ignore import Cookies, { CookieChangeOptions } from 'universal-cookie'; export default function universalCookieMiddleware() { return function(req: any, res: any, next: () => void) { req.universalCookies = new Cookies(req.headers.cookie || ''); req.universalCookies.addEventListener((change: CookieChangeOptions) => { if (!res.cookie || res.headersSent) { return; } if (change.value === undefined) { res.clearCookie(change.name, change.options); } else { const expressOpt = Object.assign({}, change.options); if (expressOpt.maxAge) { // the standard for maxAge is seconds but express uses milliseconds expressOpt.maxAge = change.options.maxAge * 1000; } res.cookie(change.name, change.value, expressOpt); } }); next(); }; }
// @ts-ignore import Cookies, { CookieChangeOptions } from 'universal-cookie'; export default function universalCookieMiddleware() { return function(req: any, res: any, next: () => void) { req.universalCookies = new Cookies(req.headers.cookie || ''); req.universalCookies.addEventListener((change: CookieChangeOptions) => { if (!res.cookie || res.headersSent) { return; } if (change.value === undefined) { res.clearCookie(change.name, change.options); } else { const expressOpt = Object.assign({}, change.options); if (expressOpt.maxAge && change.options && change.options.maxAge) { // the standard for maxAge is seconds but express uses milliseconds expressOpt.maxAge = change.options.maxAge * 1000; } res.cookie(change.name, change.value, expressOpt); } }); next(); }; }
Add missing nullcheck for maxAge on express middleware
Add missing nullcheck for maxAge on express middleware
TypeScript
mit
reactivestack/cookies,eXon/react-cookie,reactivestack/cookies,reactivestack/cookies
--- +++ @@ -13,7 +13,7 @@ res.clearCookie(change.name, change.options); } else { const expressOpt = Object.assign({}, change.options); - if (expressOpt.maxAge) { + if (expressOpt.maxAge && change.options && change.options.maxAge) { // the standard for maxAge is seconds but express uses milliseconds expressOpt.maxAge = change.options.maxAge * 1000; }
9de57674dcb98cbb06525f3f50356d182443ded2
docs/docs/snippets/providers/getting-started-service.ts
docs/docs/snippets/providers/getting-started-service.ts
import {Injectable} from "@tsed/common"; import {Calendar} from "../models/Calendar"; @Service() export class CalendarsService { private readonly calendars: Calendar[] = []; create(calendar: Calendar) { this.calendars.push(calendar); } findAll(): Calendar[] { return this.calendars; } }
import {Service} from "@tsed/common"; import {Calendar} from "../models/Calendar"; @Service() export class CalendarsService { private readonly calendars: Calendar[] = []; create(calendar: Calendar) { this.calendars.push(calendar); } findAll(): Calendar[] { return this.calendars; } }
Correct service declaration with propper decorator
fix(docs): Correct service declaration with propper decorator
TypeScript
mit
Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators
--- +++ @@ -1,4 +1,4 @@ -import {Injectable} from "@tsed/common"; +import {Service} from "@tsed/common"; import {Calendar} from "../models/Calendar"; @Service()
35935df05966a44dee0a71fa9ce2faa7b2f4955f
typescript/grade-school/grade-school.ts
typescript/grade-school/grade-school.ts
export default class GradeSchool { private roster: Map<number, string[]> constructor() { this.roster = new Map<number, string[]>() } public studentRoster(): ReadonlyMap<string, string[]> { const result = new Map<string, string[]>(); this.roster.forEach((students, grade) => { // Use array.slice() to prevent modifications of roster outside this // module result.set(grade.toString(), students.slice()) }) return result; } public addStudent(name: string, grade: number): void { this.removeStudentIfAlreadyExists(name); const currentStudentsInGrade = this.roster.get(grade) || [] const newStudentsInGrade = [...currentStudentsInGrade, name].sort() this.roster.set(grade, newStudentsInGrade) } public studentsInGrade(grade: number): string[] { const currentStudentsInGrade = this.roster.get(grade) if (currentStudentsInGrade) { return [...currentStudentsInGrade] } return [] } private removeStudentIfAlreadyExists(name: string) { let newRoster = new Map<number, string[]>(); this.roster.forEach((students, grade) => { const newStudents = students.filter(student => student !== name) newRoster.set(grade, newStudents); }) this.roster = newRoster; } }
export default class GradeSchool { private roster: Map<number, string[]> constructor() { this.roster = new Map<number, string[]>() } public studentRoster(): ReadonlyMap<string, string[]> { const result = new Map<string, string[]>(); this.roster.forEach((students, grade) => { result.set(grade.toString(), [...students]) }) return result; } public addStudent(name: string, grade: number): void { this.removeStudentIfAlreadyExists(name); const students = this.studentsInGrade(grade); const newStudents = [...students, name].sort() this.roster.set(grade, newStudents) } public studentsInGrade(grade: number): string[] { const students = this.roster.get(grade) if (students) { return [...students] } return [] } private removeStudentIfAlreadyExists(name: string) { let newRoster = new Map<number, string[]>(); this.roster.forEach((students, grade) => { const newStudents = students.filter(student => student !== name) newRoster.set(grade, newStudents); }) this.roster = newRoster; } }
Refactor to use spread operator for immutable array operations
Refactor to use spread operator for immutable array operations
TypeScript
mit
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
--- +++ @@ -10,24 +10,22 @@ public studentRoster(): ReadonlyMap<string, string[]> { const result = new Map<string, string[]>(); this.roster.forEach((students, grade) => { - // Use array.slice() to prevent modifications of roster outside this - // module - result.set(grade.toString(), students.slice()) + result.set(grade.toString(), [...students]) }) return result; } public addStudent(name: string, grade: number): void { this.removeStudentIfAlreadyExists(name); - const currentStudentsInGrade = this.roster.get(grade) || [] - const newStudentsInGrade = [...currentStudentsInGrade, name].sort() - this.roster.set(grade, newStudentsInGrade) + const students = this.studentsInGrade(grade); + const newStudents = [...students, name].sort() + this.roster.set(grade, newStudents) } public studentsInGrade(grade: number): string[] { - const currentStudentsInGrade = this.roster.get(grade) - if (currentStudentsInGrade) { - return [...currentStudentsInGrade] + const students = this.roster.get(grade) + if (students) { + return [...students] } return [] }
fe5e696831189ad72061ad3e7e248e283bf281ed
setup-tests.ts
setup-tests.ts
import {configure} from 'enzyme' import * as Adapter from 'enzyme-adapter-react-16' import 'jest-enzyme' // Set up Enzyme configure({adapter: new (Adapter as any)()}) // tslint:disable-line:no-any // For React 16 Object.assign(global, { requestAnimationFrame(callback: Function) { setTimeout(callback, 0) }, }) // Add code to execute before tests are run
import {configure} from 'enzyme' import * as Adapter from 'enzyme-adapter-react-16' import 'jest-enzyme' // Set up Enzyme configure({adapter: new (Adapter as any)()}) // tslint:disable-line:no-any // Add code to execute before tests are run
Remove attempt at raf fix
Remove attempt at raf fix
TypeScript
mit
jupl/astraea,jupl/astraea
--- +++ @@ -5,11 +5,4 @@ // Set up Enzyme configure({adapter: new (Adapter as any)()}) // tslint:disable-line:no-any -// For React 16 -Object.assign(global, { - requestAnimationFrame(callback: Function) { - setTimeout(callback, 0) - }, -}) - // Add code to execute before tests are run
a5cbeaf7737ea7c465076a547caad5bb2e71558d
src/sagas/calculateHash.ts
src/sagas/calculateHash.ts
import { put, call, select } from 'redux-saga/effects' import { hashCalculated } from '../actions' import type { State } from '../store' import type { Hash } from '../types' type ArrayBuffer = State['arrayBuffer'] type HashType = State['hashType'] const getHash = async ( arrayBuffer: ArrayBuffer, hashType: HashType ): Promise<Hash> => { if (arrayBuffer && hashType) { const hashBuffer = await crypto.subtle.digest(hashType, arrayBuffer) const hashArray = Array.from(new Uint8Array(hashBuffer)) const hashHex = hashArray .map((b) => ('00' + b.toString(16)).slice(-2)) .join('') return hashHex } return '' } const getArrayBuffer = (state: State): ArrayBuffer => state.arrayBuffer const getHashType = (state: State): HashType => state.hashType export const calculateHash = function* () { const arrayBuffer: ArrayBuffer = yield select(getArrayBuffer) const hashType: HashType = yield select(getHashType) const hash: Hash = yield call(getHash, arrayBuffer, hashType) yield put(hashCalculated(hash)) }
import { put, call, select } from 'redux-saga/effects' import { hashCalculated } from '../actions' import type { State } from '../store' import type { HashType, Hash } from '../types' const getFileHash = async ( arrayBuffer: ArrayBuffer, hashType: HashType ): Promise<Hash> => { const hashBuffer = await crypto.subtle.digest(hashType, arrayBuffer) const hashArray = Array.from(new Uint8Array(hashBuffer)) const hashHex = hashArray .map((b) => ('00' + b.toString(16)).slice(-2)) .join('') return hashHex } export const calculateHash = function* () { const { arrayBuffer, hashType }: State = yield select() if (!arrayBuffer || !hashType) { return } const hash: Hash = yield call(getFileHash, arrayBuffer, hashType) yield put(hashCalculated(hash)) }
Update calculate hash saga - Use a single state selector - Clean up types - Move null checks outside hash calculation function
Update calculate hash saga - Use a single state selector - Clean up types - Move null checks outside hash calculation function
TypeScript
mit
joelgeorgev/file-hash-verifier,joelgeorgev/file-hash-verifier
--- +++ @@ -2,34 +2,28 @@ import { hashCalculated } from '../actions' import type { State } from '../store' -import type { Hash } from '../types' +import type { HashType, Hash } from '../types' -type ArrayBuffer = State['arrayBuffer'] -type HashType = State['hashType'] - -const getHash = async ( +const getFileHash = async ( arrayBuffer: ArrayBuffer, hashType: HashType ): Promise<Hash> => { - if (arrayBuffer && hashType) { - const hashBuffer = await crypto.subtle.digest(hashType, arrayBuffer) - const hashArray = Array.from(new Uint8Array(hashBuffer)) - const hashHex = hashArray - .map((b) => ('00' + b.toString(16)).slice(-2)) - .join('') - return hashHex - } - return '' + const hashBuffer = await crypto.subtle.digest(hashType, arrayBuffer) + const hashArray = Array.from(new Uint8Array(hashBuffer)) + const hashHex = hashArray + .map((b) => ('00' + b.toString(16)).slice(-2)) + .join('') + + return hashHex } -const getArrayBuffer = (state: State): ArrayBuffer => state.arrayBuffer -const getHashType = (state: State): HashType => state.hashType +export const calculateHash = function* () { + const { arrayBuffer, hashType }: State = yield select() -export const calculateHash = function* () { - const arrayBuffer: ArrayBuffer = yield select(getArrayBuffer) - const hashType: HashType = yield select(getHashType) + if (!arrayBuffer || !hashType) { + return + } - const hash: Hash = yield call(getHash, arrayBuffer, hashType) - + const hash: Hash = yield call(getFileHash, arrayBuffer, hashType) yield put(hashCalculated(hash)) }
9d0a2f5b441c002d41dda871c479fd5839c56c53
src/constants.ts
src/constants.ts
import * as path from 'path'; export const DEFAULT_APP_NAME = 'APP'; // Update both DEFAULT_ELECTRON_VERSION and DEFAULT_CHROME_VERSION together, // and update app / package.json / devDeps / electron to value of DEFAULT_ELECTRON_VERSION export const DEFAULT_ELECTRON_VERSION = '12.0.10'; export const DEFAULT_CHROME_VERSION = '89.0.4389.128'; // Update each of these periodically // https://product-details.mozilla.org/1.0/firefox_versions.json export const DEFAULT_FIREFOX_VERSION = '89.0'; // https://en.wikipedia.org/wiki/Safari_version_history export const DEFAULT_SAFARI_VERSION = { majorVersion: 14, version: '14.0.3', webkitVersion: '610.4.3.1.7', }; export const ELECTRON_MAJOR_VERSION = parseInt( DEFAULT_ELECTRON_VERSION.split('.')[0], 10, ); export const PLACEHOLDER_APP_DIR = path.join(__dirname, './../', 'app');
import * as path from 'path'; export const DEFAULT_APP_NAME = 'APP'; // Update both DEFAULT_ELECTRON_VERSION and DEFAULT_CHROME_VERSION together, // and update app / package.json / devDeps / electron to value of DEFAULT_ELECTRON_VERSION export const DEFAULT_ELECTRON_VERSION = '12.0.11'; export const DEFAULT_CHROME_VERSION = '89.0.4389.128'; // Update each of these periodically // https://product-details.mozilla.org/1.0/firefox_versions.json export const DEFAULT_FIREFOX_VERSION = '89.0'; // https://en.wikipedia.org/wiki/Safari_version_history export const DEFAULT_SAFARI_VERSION = { majorVersion: 14, version: '14.0.3', webkitVersion: '610.4.3.1.7', }; export const ELECTRON_MAJOR_VERSION = parseInt( DEFAULT_ELECTRON_VERSION.split('.')[0], 10, ); export const PLACEHOLDER_APP_DIR = path.join(__dirname, './../', 'app');
Bump default Electron to 12.0.11
Bump default Electron to 12.0.11
TypeScript
bsd-2-clause
jiahaog/Nativefier,jiahaog/Nativefier,jiahaog/Nativefier
--- +++ @@ -4,7 +4,7 @@ // Update both DEFAULT_ELECTRON_VERSION and DEFAULT_CHROME_VERSION together, // and update app / package.json / devDeps / electron to value of DEFAULT_ELECTRON_VERSION -export const DEFAULT_ELECTRON_VERSION = '12.0.10'; +export const DEFAULT_ELECTRON_VERSION = '12.0.11'; export const DEFAULT_CHROME_VERSION = '89.0.4389.128'; // Update each of these periodically
9900e7233ca879c727336c9cc2e05dfcc1fbefe3
src/app/settings/settings.component.ts
src/app/settings/settings.component.ts
import { Component } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { TopNav } from '../shared/index'; import { SettingsService } from './settings.service'; import { UserSettings, UserAdmin, BoardAdmin } from './index'; @Component({ selector: 'tb-settings', templateUrl: 'app/settings/settings.component.html', providers: [ SettingsService ] }) export class Settings { constructor(private settings: SettingsService, private title: Title) { title.setTitle('TaskBoard - Settings'); } }
import { Component } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { TopNav } from '../shared/index'; import { SettingsService } from './settings.service'; import { UserSettings, UserAdmin, BoardAdmin } from './index'; @Component({ selector: 'tb-settings', templateUrl: 'app/settings/settings.component.html', providers: [ SettingsService ] }) export class Settings { constructor(private settings: SettingsService, private title: Title) { // SettingsService is loaded here so the same instance is available // to all child components. title.setTitle('TaskBoard - Settings'); } }
Add note about non-obvious usage
Add note about non-obvious usage
TypeScript
mit
kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard
--- +++ @@ -16,6 +16,8 @@ }) export class Settings { constructor(private settings: SettingsService, private title: Title) { + // SettingsService is loaded here so the same instance is available + // to all child components. title.setTitle('TaskBoard - Settings'); } }
6b473271967984ecb8788a87da0eefcc3f94a5ff
src/gitlab.ts
src/gitlab.ts
import Renderer from './renderer' class GitLabRenderer extends Renderer { renderSwitch() { } getCodeDOM() { return <HTMLElement>document.querySelector('.blob-content code') } getFontWidth() { const $ = <HTMLElement>document.querySelector('#LC1 > span') return $.getBoundingClientRect().width / $.innerText.length } getPadding() { return { left: 10, top: 10 } } } const renderer = new GitLabRenderer()
import Renderer from './renderer' class GitLabRenderer extends Renderer { renderSwitch() { } getCodeDOM() { return <HTMLElement>document.querySelector('.blob-content code') } getCode() { const lines = this.$code.children return [].map.call(lines, line => line.innerText).join('\n') } getFontWidth() { const $ = <HTMLElement>document.querySelector('#LC1 > span') return $.getBoundingClientRect().width / $.innerText.length } getPadding() { return { left: 10, top: 10 } } } const renderer = new GitLabRenderer()
Fix GitLab missing empty line
Fix GitLab missing empty line
TypeScript
mit
pd4d10/intelli-octo,pd4d10/intelli-octo,pd4d10/intelli-octo
--- +++ @@ -6,6 +6,11 @@ getCodeDOM() { return <HTMLElement>document.querySelector('.blob-content code') + } + + getCode() { + const lines = this.$code.children + return [].map.call(lines, line => line.innerText).join('\n') } getFontWidth() {
b947f60453fb54512a682eac5276dd7d87bf0cdf
test/runTests.ts
test/runTests.ts
import * as path from 'path'; import { runTests } from '@vscode/test-electron'; async function main() { try { // The folder containing the Extension Manifest package.json // Passed to `--extensionDevelopmentPath` const extensionDevelopmentPath = path.resolve(__dirname, '../'); // The path to the extension test script // Passed to --extensionTestsPath const extensionTestsPath = path.resolve(__dirname, './index'); // Download VS Code, unzip it and run the integration test await runTests({ extensionDevelopmentPath, extensionTestsPath }); } catch (err) { console.error('Failed to run tests'); process.exit(1); } } main();
import * as path from 'path'; import { runTests } from '@vscode/test-electron'; async function main() { try { // The folder containing the Extension Manifest package.json // Passed to `--extensionDevelopmentPath` const extensionDevelopmentPath = path.resolve(__dirname, '../../'); // The path to the extension test script // Passed to --extensionTestsPath const extensionTestsPath = path.resolve(__dirname, './index'); // Download VS Code, unzip it and run the integration test await runTests({ extensionDevelopmentPath, extensionTestsPath }); } catch (err) { console.error('Failed to run tests'); process.exit(1); } } main();
Fix `npm test` - didn't activate the extension
Fix `npm test` - didn't activate the extension
TypeScript
mit
ipatalas/vscode-postfix-ts,ipatalas/vscode-postfix-ts
--- +++ @@ -6,7 +6,7 @@ try { // The folder containing the Extension Manifest package.json // Passed to `--extensionDevelopmentPath` - const extensionDevelopmentPath = path.resolve(__dirname, '../'); + const extensionDevelopmentPath = path.resolve(__dirname, '../../'); // The path to the extension test script // Passed to --extensionTestsPath
6a4d326f89dc3edec61a339262d873b082e6ddeb
typeorm/index.ts
typeorm/index.ts
import { ConnectionOptions } from 'typeorm'; import * as fs from 'fs'; import { Configuration } from '../helpers/environment'; console.log(Configuration.DB_HOST) export const connectionOptions: ConnectionOptions = { type: "mongodb", url: Configuration.DB_HOST, synchronize: true, logging: false, useNewUrlParser: true, entities: [ "typeorm/models/**/*.ts" ], migrations: [ "typeorm/migration/**/*.ts" ], subscribers: [ "typeorm/subscriber/**/*.ts" ] };
import { ConnectionOptions } from 'typeorm'; import * as fs from 'fs'; import { Configuration } from '../helpers/environment'; import * as path from 'path'; console.log(Configuration.DB_HOST) export const connectionOptions: ConnectionOptions = { type: "mongodb", url: Configuration.DB_HOST, synchronize: true, logging: false, useNewUrlParser: true, entities: [ "typeorm/models/**/*.ts", path.join(__dirname, "models/**/*.ts") ], migrations: [ "typeorm/migration/**/*.ts" ], subscribers: [ "typeorm/subscriber/**/*.ts" ] };
Create a secondary models area for pm2
Create a secondary models area for pm2
TypeScript
apache-2.0
Goyatuzo/LurkerBot,Goyatuzo/LurkerBot
--- +++ @@ -1,6 +1,7 @@ import { ConnectionOptions } from 'typeorm'; import * as fs from 'fs'; import { Configuration } from '../helpers/environment'; +import * as path from 'path'; console.log(Configuration.DB_HOST) @@ -11,7 +12,8 @@ logging: false, useNewUrlParser: true, entities: [ - "typeorm/models/**/*.ts" + "typeorm/models/**/*.ts", + path.join(__dirname, "models/**/*.ts") ], migrations: [ "typeorm/migration/**/*.ts"
f9d139620f66f0c3c0ff2ac8a1b7c2ebf467b883
src/components/story-list.ts
src/components/story-list.ts
import { bindable, customElement } from 'aurelia-framework'; @customElement('hn-story-list') export class StoryList { @bindable() private readonly stories: any[]; @bindable() private readonly offset: number; }
import { bindable, customElement } from 'aurelia-framework'; @customElement('hn-story-list') export class StoryList { @bindable() readonly stories: any[]; @bindable() readonly offset: number; }
Correct visibility of StoryList custom element
Correct visibility of StoryList custom element
TypeScript
isc
MikeBull94/aurelia-hacker-news,michaelbull/aurelia-hacker-news,michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news,michaelbull/aurelia-hacker-news
--- +++ @@ -5,6 +5,6 @@ @customElement('hn-story-list') export class StoryList { - @bindable() private readonly stories: any[]; - @bindable() private readonly offset: number; + @bindable() readonly stories: any[]; + @bindable() readonly offset: number; }
63506238c59cfa6f99a0179b597884108b9638e4
src/popup/tooltip-button/actions.ts
src/popup/tooltip-button/actions.ts
import { createAction } from 'redux-act' import { getTooltipState, setTooltipState } from '../../content-tooltip/utils' import { remoteFunction } from '../../util/webextensionRPC' import { Thunk } from '../types' import * as selectors from './selectors' const processEventRPC = remoteFunction('processEvent') export const setSidebarFlag = createAction<boolean>('tooltip/setSidebarFlag') export const setTooltipFlag = createAction<boolean>('tooltip/setTooltipFlag') export const init: () => Thunk = () => async dispatch => { const [sidebar, tooltip] = await Promise.all([getTooltipState()]) dispatch(setSidebarFlag(sidebar)) } export const toggleTooltipFlag: () => Thunk = () => async ( dispatch, getState, ) => { const state = getState() const wasEnabled = selectors.isTooltipEnabled(state) processEventRPC({ type: wasEnabled ? 'disableTooltipPopup' : 'enableTooltipPopup', }) await setTooltipState(!wasEnabled) dispatch(setTooltipFlag(!wasEnabled)) } export const showTooltip: () => Thunk = () => async () => { await remoteFunction('showContentTooltip')() }
import { createAction } from 'redux-act' import { getTooltipState, setTooltipState } from '../../content-tooltip/utils' import { remoteFunction } from '../../util/webextensionRPC' import { Thunk } from '../types' import * as selectors from './selectors' const processEventRPC = remoteFunction('processEvent') export const setTooltipFlag = createAction<boolean>('tooltip/setTooltipFlag') export const init: () => Thunk = () => async dispatch => { const sidebar = await getTooltipState() dispatch(setTooltipFlag(sidebar)) } export const toggleTooltipFlag: () => Thunk = () => async ( dispatch, getState, ) => { const state = getState() const wasEnabled = selectors.isTooltipEnabled(state) processEventRPC({ type: wasEnabled ? 'disableTooltipPopup' : 'enableTooltipPopup', }) await setTooltipState(!wasEnabled) dispatch(setTooltipFlag(!wasEnabled)) } export const showTooltip: () => Thunk = () => async () => { await remoteFunction('showContentTooltip')() }
Fix loading of tooltip state in popup
Fix loading of tooltip state in popup
TypeScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -7,12 +7,11 @@ const processEventRPC = remoteFunction('processEvent') -export const setSidebarFlag = createAction<boolean>('tooltip/setSidebarFlag') export const setTooltipFlag = createAction<boolean>('tooltip/setTooltipFlag') export const init: () => Thunk = () => async dispatch => { - const [sidebar, tooltip] = await Promise.all([getTooltipState()]) - dispatch(setSidebarFlag(sidebar)) + const sidebar = await getTooltipState() + dispatch(setTooltipFlag(sidebar)) } export const toggleTooltipFlag: () => Thunk = () => async (
bb227d5c3a2f2288c74640323ea14b5ce516fc99
public/app/core/components/EmptyListCTA/EmptyListCTA.test.tsx
public/app/core/components/EmptyListCTA/EmptyListCTA.test.tsx
import React from 'react'; import renderer from 'react-test-renderer'; import EmptyListCTA from './EmptyListCTA'; const model = { title: 'Title', buttonIcon: 'ga css class', buttonLink: 'http://url/to/destination', buttonTitle: 'Click me', onClick: 'handler', proTip: 'This is a tip', proTipLink: 'http://url/to/tip/destination', proTipLinkTitle: 'Learn more', proTipTarget: '_blank', }; describe('EmptyListCTA', () => { it('renders correctly', () => { const tree = renderer.create(<EmptyListCTA model={model} />).toJSON(); expect(tree).toMatchSnapshot(); }); });
import React from 'react'; import renderer from 'react-test-renderer'; import EmptyListCTA from './EmptyListCTA'; const model = { title: 'Title', buttonIcon: 'ga css class', buttonLink: 'http://url/to/destination', buttonTitle: 'Click me', onClick: jest.fn(), proTip: 'This is a tip', proTipLink: 'http://url/to/tip/destination', proTipLinkTitle: 'Learn more', proTipTarget: '_blank', }; describe('EmptyListCTA', () => { it('renders correctly', () => { const tree = renderer.create(<EmptyListCTA model={model} />).toJSON(); expect(tree).toMatchSnapshot(); }); });
Use jest.fn instead of string.
Use jest.fn instead of string.
TypeScript
agpl-3.0
grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana
--- +++ @@ -7,7 +7,7 @@ buttonIcon: 'ga css class', buttonLink: 'http://url/to/destination', buttonTitle: 'Click me', - onClick: 'handler', + onClick: jest.fn(), proTip: 'This is a tip', proTipLink: 'http://url/to/tip/destination', proTipLinkTitle: 'Learn more',
55871cbb473d61479286806e3086147360a0d290
src/execution.ts
src/execution.ts
import * as exec from '@actions/exec' import * as cacheDependencies from './cache-dependencies' import * as cacheConfiguration from './cache-configuration' export async function execute( executable: string, root: string, argv: string[] ): Promise<BuildResult> { await cacheDependencies.restoreCachedDependencies(root) await cacheConfiguration.restoreCachedConfiguration(root) let publishing = false let buildScanUrl: string | undefined const status: number = await exec.exec(executable, argv, { cwd: root, ignoreReturnCode: true, listeners: { stdline: (line: string) => { if (line.startsWith('Publishing build scan...')) { publishing = true } if (publishing && line.length === 0) { publishing = false } if (publishing && line.startsWith('http')) { buildScanUrl = line.trim() publishing = false } } } }) return new BuildResultImpl(status, buildScanUrl) } export interface BuildResult { readonly status: number readonly buildScanUrl?: string } class BuildResultImpl implements BuildResult { constructor(readonly status: number, readonly buildScanUrl?: string) {} }
import * as exec from '@actions/exec' import * as cacheDependencies from './cache-dependencies' import * as cacheConfiguration from './cache-configuration' export async function execute( executable: string, root: string, argv: string[] ): Promise<BuildResult> { await cacheDependencies.restoreCachedDependencies(root) await cacheConfiguration.restoreCachedConfiguration(root) let publishing = false let buildScanUrl: string | undefined const status: number = await exec.exec(executable, argv, { cwd: root, ignoreReturnCode: true, listeners: { stdline: (line: string) => { if (line.includes('Publishing build scan...')) { publishing = true } if (publishing && line.startsWith('http')) { buildScanUrl = line.trim() publishing = false } } } }) return new BuildResultImpl(status, buildScanUrl) } export interface BuildResult { readonly status: number readonly buildScanUrl?: string } class BuildResultImpl implements BuildResult { constructor(readonly status: number, readonly buildScanUrl?: string) {} }
Simplify build scan url extraction
Simplify build scan url extraction
TypeScript
mit
eskatos/gradle-command-action,eskatos/gradle-command-action,eskatos/gradle-command-action
--- +++ @@ -18,11 +18,8 @@ ignoreReturnCode: true, listeners: { stdline: (line: string) => { - if (line.startsWith('Publishing build scan...')) { + if (line.includes('Publishing build scan...')) { publishing = true - } - if (publishing && line.length === 0) { - publishing = false } if (publishing && line.startsWith('http')) { buildScanUrl = line.trim()
04534a2709a97d051cca2ec58d5c3e99f5e5a9c5
src/site/app/lib/components/pioneer-tree-handle/pioneer-tree-handle.component.ts
src/site/app/lib/components/pioneer-tree-handle/pioneer-tree-handle.component.ts
/** * Adds drag and drop functionality to pioneer-tree-node child elements */ import { Component, Input, HostListener } from '@angular/core'; import { IPioneerTreeExpandedNode } from "../../models/pioneer-tree-expanded-node.model" @Component({ selector: '[pioneer-tree-handle],[pt-handle]', template: ` <span class="pioneer-tree-handle"> <ng-content> </ng-content> </span> ` }) export class PioneerTreeHandleComponent { @Input() node: IPioneerTreeExpandedNode; @HostListener('dragstart', ['$event']) onDragStart(event: Event) { console.log('drag started'); } @HostListener('dragend') onDragEnd() { alert('drag ended'); } }
/** * Adds drag and drop functionality to pioneer-tree-node child elements */ import { Component, Input, HostListener, HostBinding } from '@angular/core'; import { IPioneerTreeExpandedNode } from "../../models/pioneer-tree-expanded-node.model" @Component({ selector: '[pioneer-tree-handle],[pt-handle]', template: ` <span class="pioneer-tree-handle"> <ng-content> </ng-content> </span> ` }) export class PioneerTreeHandleComponent { @Input() node: IPioneerTreeExpandedNode; @HostBinding('draggable') get draggable() { return true; } @HostListener('dragstart', ['$event']) onDragStart(event: Event) { console.log('drag started ' + event); } @HostListener('dragend') onDragEnd() { alert('drag ended'); } }
Enable draggle attribute on handle
Enable draggle attribute on handle
TypeScript
mit
PioneerCode/pioneer-tree,PioneerCode/pioneer-tree,PioneerCode/pioneer-tree
--- +++ @@ -1,7 +1,7 @@ /** * Adds drag and drop functionality to pioneer-tree-node child elements */ -import { Component, Input, HostListener } from '@angular/core'; +import { Component, Input, HostListener, HostBinding } from '@angular/core'; import { IPioneerTreeExpandedNode } from "../../models/pioneer-tree-expanded-node.model" @Component({ @@ -16,13 +16,18 @@ export class PioneerTreeHandleComponent { @Input() node: IPioneerTreeExpandedNode; - @HostListener('dragstart', ['$event']) - onDragStart(event: Event) { - console.log('drag started'); - } + @HostBinding('draggable') + get draggable() { + return true; + } - @HostListener('dragend') - onDragEnd() { - alert('drag ended'); - } + @HostListener('dragstart', ['$event']) + onDragStart(event: Event) { + console.log('drag started ' + event); + } + + @HostListener('dragend') + onDragEnd() { + alert('drag ended'); + } }
9d222122005cee4a5cb78026008c8ed3a5176496
src/app/app.component.ts
src/app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: "/app/app.component.tpl.html" }) export class AppComponent { operation:string; firstvalue:number = 0; scdvalue:number = 0; result:number = 0; listOperation: Array<{firstvalue:number,scdvalue:number,operation:string}>; process(operation:string, firstvalue:number, scdvalue:number):void{ } addition():void{ } multiplication(): void{ } substration(): void{ } }
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: "/app/app.component.tpl.html" }) export class AppComponent { operation: string = 'x'; fstvalue: number = 0; scdvalue: number = 0; result: number = 0; listOperation: Array<{ firstvalue: number, scdvalue: number, operation: string }>; constructor() { this.result = this.multiplication(this.fstvalue,this.scdvalue); } process(operation: string, firstvalue: number, scdvalue: number): void { } addition(firstvalue: number, scdvalue: number): number { let result:number; return result; } multiplication(firstvalue: number, scdvalue: number): number { let result:number; return result; } substration(firstvalue: number, scdvalue: number): number { let result:number; return result; } }
Add default parameters of calculator method
Add default parameters of calculator method
TypeScript
mit
ngako/angular2-poc,ngako/angular2-poc,ngako/angular2-poc
--- +++ @@ -5,25 +5,32 @@ templateUrl: "/app/app.component.tpl.html" }) export class AppComponent { - operation:string; - firstvalue:number = 0; - scdvalue:number = 0; - result:number = 0; - listOperation: Array<{firstvalue:number,scdvalue:number,operation:string}>; + operation: string = 'x'; + fstvalue: number = 0; + scdvalue: number = 0; + result: number = 0; + listOperation: Array<{ firstvalue: number, scdvalue: number, operation: string }>; - process(operation:string, firstvalue:number, scdvalue:number):void{ + constructor() { + this.result = this.multiplication(this.fstvalue,this.scdvalue); + } + + process(operation: string, firstvalue: number, scdvalue: number): void { } - addition():void{ - + addition(firstvalue: number, scdvalue: number): number { + let result:number; + return result; } - multiplication(): void{ - + multiplication(firstvalue: number, scdvalue: number): number { + let result:number; + return result; } - substration(): void{ - + substration(firstvalue: number, scdvalue: number): number { + let result:number; + return result; } - } +}
724b7af463a162805fec646bb58056c7db539502
packages/firebase-functions/minimum-version/functions/src/index.ts
packages/firebase-functions/minimum-version/functions/src/index.ts
import { https } from 'firebase-functions'; const MIN_VERSION = '1.1.0'; exports.minimumVersion = https.onRequest(async (_, res) => { res.status(200).send(JSON.stringify({ minVersion: MIN_VERSION })); });
import { https } from 'firebase-functions'; const MIN_VERSION = '1.1.1'; exports.minimumVersion = https.onRequest(async (_, res) => { res.status(200).send(JSON.stringify({ minVersion: MIN_VERSION })); });
Update minimum mobile app version
Update minimum mobile app version
TypeScript
mit
cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack
--- +++ @@ -1,6 +1,6 @@ import { https } from 'firebase-functions'; -const MIN_VERSION = '1.1.0'; +const MIN_VERSION = '1.1.1'; exports.minimumVersion = https.onRequest(async (_, res) => { res.status(200).send(JSON.stringify({ minVersion: MIN_VERSION }));
a1e11ccd69f927bc81064e6c4d388ae0b5a7b423
turingarena-web-client/web/projects/turingarena-contest/src/app/auth.service.ts
turingarena-web-client/web/projects/turingarena-contest/src/app/auth.service.ts
import { Injectable } from '@angular/core'; import { Apollo } from 'apollo-angular'; export interface Auth { token: string; userId: string; } @Injectable({ providedIn: 'root', }) export class AuthService { constructor( private readonly apollo: Apollo, ) { } getAuth = (): Auth | undefined => { try { const authString = localStorage.getItem('auth'); if (authString === null) { return undefined; } return JSON.parse(authString) as Auth; } catch (e) { localStorage.removeItem('userId'); return undefined; } } setAuth = async (auth: Auth | undefined) => { if (auth === undefined) { localStorage.removeItem('auth'); } else { localStorage.setItem('auth', JSON.stringify(auth)); } await this.apollo.getClient().resetStore(); } }
import { Injectable } from '@angular/core'; import { Apollo } from 'apollo-angular'; export interface Auth { token: string; userId: string; } @Injectable({ providedIn: 'root', }) export class AuthService { constructor( private readonly apollo: Apollo, ) { } getAuth = (): Auth | undefined => { try { const authString = localStorage.getItem('auth'); if (authString === null) { return undefined; } return JSON.parse(authString) as Auth; } catch (e) { localStorage.removeItem('userId'); return undefined; } } setAuth = async (auth: Auth | undefined) => { const client = this.apollo.getClient(); client.stop(); if (auth === undefined) { localStorage.removeItem('auth'); } else { localStorage.setItem('auth', JSON.stringify(auth)); } await client.resetStore(); await client.reFetchObservableQueries(); } }
Fix issues with Apollo and login/logout
Fix issues with Apollo and login/logout
TypeScript
mpl-2.0
algorithm-ninja/task-wizard,algorithm-ninja/task-wizard,algorithm-ninja/task-wizard
--- +++ @@ -29,12 +29,17 @@ } setAuth = async (auth: Auth | undefined) => { + const client = this.apollo.getClient(); + + client.stop(); + if (auth === undefined) { localStorage.removeItem('auth'); } else { localStorage.setItem('auth', JSON.stringify(auth)); } - await this.apollo.getClient().resetStore(); + await client.resetStore(); + await client.reFetchObservableQueries(); } }
4447a3dbe5343df92fde677c084ea36e45f3b7d8
test/metrics.ts
test/metrics.ts
const nodeMetrics = require("../lib/metrics"); const assert = require("assert"); describe("pause test", () => { // Start up the pause detector before(() => nodeMetrics.log_metrics("source", 10000)); it("test2", (done) => { assert.equal(nodeMetrics._get_last_period_pause_ms(), 0); process.nextTick(() => { // Do a bunch of stuff to monopolize the event loop let total = 0; for (let i = 0; i < 1500000000; i++) { total += i; } // Confirm that the last_period_pause_ms was increased setTimeout(() => { assert(nodeMetrics._get_last_period_pause_ms() > 1000); done(); }, 100); }); }); });
const nodeMetrics = require("../lib/metrics"); const assert = require("assert"); describe("Pause test", () => { // Start up the pause detector before(() => nodeMetrics.log_metrics("source", 10000)); it("should record a later time after event loop is blocked", (done) => { assert.equal(nodeMetrics._get_last_period_pause_ms(), 0); process.nextTick(() => { // Do a bunch of stuff to monopolize the event loop let total = 0; for (let i = 0; i < 1500000000; i++) { total += i; } // Confirm that the last_period_pause_ms was increased setTimeout(() => { assert(nodeMetrics._get_last_period_pause_ms() > 1000); done(); }, 100); }); }); });
Rename test cases for clarity
test: Rename test cases for clarity
TypeScript
apache-2.0
Clever/node-process-metrics,Clever/node-process-metrics
--- +++ @@ -1,11 +1,11 @@ const nodeMetrics = require("../lib/metrics"); const assert = require("assert"); -describe("pause test", () => { +describe("Pause test", () => { // Start up the pause detector before(() => nodeMetrics.log_metrics("source", 10000)); - it("test2", (done) => { + it("should record a later time after event loop is blocked", (done) => { assert.equal(nodeMetrics._get_last_period_pause_ms(), 0); process.nextTick(() => {
878ad624c21e3fb899d893a6340a393727ba75fd
generators/app/templates/test/greeter-spec.ts
generators/app/templates/test/greeter-spec.ts
import { Greeter } from '../src/greeter'; import * as chai from 'chai'; var expect = chai.expect; describe('greeter', () => { it('should greet with message', () => { var greeter = new Greeter('friend'); expect(greeter.greet()).to.equal('Bonjour, friend!'); }); });
<% if (isWindows) { %><reference path="../node_modules/@types/mocha/index.d.ts" /><% } %> import { Greeter } from "../src/greeter"; import * as chai from "chai"; const expect = chai.expect; describe("greeter", () => { it("should greet with message", () => { const greeter = new Greeter("friend"); expect(greeter.greet()).to.equal("Bonjour, friend!"); }); });
Add windows workaround for ts-node issue
Add windows workaround for ts-node issue
TypeScript
mit
ospatil/generator-node-typescript,ospatil/generator-node-typescript
--- +++ @@ -1,11 +1,12 @@ -import { Greeter } from '../src/greeter'; -import * as chai from 'chai'; +<% if (isWindows) { %><reference path="../node_modules/@types/mocha/index.d.ts" /><% } %> +import { Greeter } from "../src/greeter"; +import * as chai from "chai"; -var expect = chai.expect; +const expect = chai.expect; -describe('greeter', () => { - it('should greet with message', () => { - var greeter = new Greeter('friend'); - expect(greeter.greet()).to.equal('Bonjour, friend!'); +describe("greeter", () => { + it("should greet with message", () => { + const greeter = new Greeter("friend"); + expect(greeter.greet()).to.equal("Bonjour, friend!"); }); });
473963f24bf558600de3d9305f4b455d3e8de1c2
src/app/home/home.controller.ts
src/app/home/home.controller.ts
/// <reference path="../../types/types.ts"/> class HomeController implements core.IHomeController { price: number; rent: number; expected_price_increase: number; expected_rent_increase: number; mortgage_rate: number; /* @ngInject */ constructor(private $scope: ng.IScope, private $location: ng.ILocationService) { var self = this; this.price = $location.search().p || 250000; this.rent = $location.search().r || 1400; this.expected_rent_increase = $location.search().ri || 5.0; this.expected_price_increase = $location.search().p || 4.0; this.mortgage_rate = $location.search().mr || 4.0; var update_function = function() { $location.search("p", self.price); $location.search("r", self.rent); $location.search("pi", self.expected_price_increase); $location.search("ri", self.expected_rent_increase); $location.search("mr", self.mortgage_rate); } $scope.$watch(function() { return self.price; }, update_function); } } angular .module("home.index", []) .controller("HomeController", HomeController);
/// <reference path="../../types/types.ts"/> class HomeController implements core.IHomeController { price: number; rent: number; expected_price_increase: number; expected_rent_increase: number; mortgage_rate: number; /* @ngInject */ constructor(private $scope: ng.IScope, private $location: ng.ILocationService) { var self = this; // We want copy-pastable URLs so we're storing all the default // values immediately as URL params. We then synchronise page and // URL every time any value changes. Using short names to avoid // uber-long URLs. this.price = $location.search().p || 250000; this.rent = $location.search().r || 1400; this.expected_rent_increase = $location.search().ri || 5.0; this.expected_price_increase = $location.search().p || 4.0; this.mortgage_rate = $location.search().mr || 4.0; var update_function = function() { $location.search("p", self.price); $location.search("r", self.rent); $location.search("pi", self.expected_price_increase); $location.search("ri", self.expected_rent_increase); $location.search("mr", self.mortgage_rate); } $scope.$watch(function() { return self.price; }, update_function); } } angular .module("home.index", []) .controller("HomeController", HomeController);
Add comment on URL sync code.
Add comment on URL sync code.
TypeScript
mit
WeAreWizards/crumpets,WeAreWizards/crumpets,WeAreWizards/crumpets
--- +++ @@ -11,6 +11,11 @@ /* @ngInject */ constructor(private $scope: ng.IScope, private $location: ng.ILocationService) { var self = this; + + // We want copy-pastable URLs so we're storing all the default + // values immediately as URL params. We then synchronise page and + // URL every time any value changes. Using short names to avoid + // uber-long URLs. this.price = $location.search().p || 250000; this.rent = $location.search().r || 1400; this.expected_rent_increase = $location.search().ri || 5.0;
d494542241b32d2d9a75a5825aaee4cca0849990
transpiler/src/emitter/index.ts
transpiler/src/emitter/index.ts
import { Node, SyntaxKind, SourceFile } from 'typescript'; import { emitImportDeclaration } from './imports'; import { emitFunctionLikeDeclaration } from './functions'; import { emitExpressionStatement, emitCallExpressionStatement } from './expressions'; import { emitIdentifier, emitType } from './identifiers'; import { emitSourceFile } from './source'; import { Context } from '../contexts'; export interface EmitResult { context: Context; emitted_string: string; } export const emit = (node: Node, context: Context): EmitResult => { switch (node.kind) { case SyntaxKind.SourceFile: return emitSourceFile(<any>node, context); case SyntaxKind.ImportDeclaration: return emitImportDeclaration(<any>node, context); case SyntaxKind.FunctionDeclaration: return emitFunctionLikeDeclaration(<any>node, context); case SyntaxKind.ExpressionStatement: return emitExpressionStatement(<any>node, context); case SyntaxKind.CallExpression: return emitCallExpressionStatement(<any>node, context); case SyntaxKind.Identifier: return emitIdentifier(<any>node, context); case SyntaxKind.TypeReference: return emitType(<any>node, context); case SyntaxKind.EndOfFileToken: return { context, emitted_string: 'end' }; default: throw new Error(`unknown syntax kind ${SyntaxKind[node.kind]}`); } };
import { Node, SyntaxKind, SourceFile } from 'typescript'; import { emitImportDeclaration } from './imports'; import { emitFunctionLikeDeclaration } from './functions'; import { emitExpressionStatement, emitCallExpressionStatement } from './expressions'; import { emitIdentifier, emitType } from './identifiers'; import { emitBlock } from './blocks'; import { emitSourceFile } from './source'; import { emitReturnStatement } from './statements'; import { Context } from '../contexts'; export interface EmitResult { context: Context; emitted_string: string; } const ignore = (node: Node, context: Context): EmitResult => ({ context, emitted_string: `ignored ${SyntaxKind[node.kind]}` }) export const emit = (node: Node, context: Context): EmitResult => { switch (node.kind) { case SyntaxKind.SourceFile: return emitSourceFile(<any>node, context); case SyntaxKind.ImportDeclaration: return emitImportDeclaration(<any>node, context); case SyntaxKind.FunctionDeclaration: return emitFunctionLikeDeclaration(<any>node, context); case SyntaxKind.ExpressionStatement: return emitExpressionStatement(<any>node, context); case SyntaxKind.CallExpression: return emitCallExpressionStatement(<any>node, context); case SyntaxKind.Identifier: return emitIdentifier(<any>node, context); case SyntaxKind.TypeReference: return emitType(<any>node, context); case SyntaxKind.Block: return emitBlock(<any>node, context); case SyntaxKind.ReturnStatement: return emitReturnStatement(<any>node, context); case SyntaxKind.EndOfFileToken: return { context, emitted_string: 'end' }; case SyntaxKind.ConditionalExpression: return ignore(node, context); case SyntaxKind.VariableStatement: return ignore(node, context); case SyntaxKind.BinaryExpression: return ignore(node, context); default: throw new Error(`unknown syntax kind ${SyntaxKind[node.kind]}`); } };
Add ability to blissfully ignore certain nodes
Add ability to blissfully ignore certain nodes
TypeScript
mit
artfuldev/RIoT
--- +++ @@ -3,13 +3,20 @@ import { emitFunctionLikeDeclaration } from './functions'; import { emitExpressionStatement, emitCallExpressionStatement } from './expressions'; import { emitIdentifier, emitType } from './identifiers'; +import { emitBlock } from './blocks'; import { emitSourceFile } from './source'; +import { emitReturnStatement } from './statements'; import { Context } from '../contexts'; export interface EmitResult { context: Context; emitted_string: string; } + +const ignore = (node: Node, context: Context): EmitResult => ({ + context, + emitted_string: `ignored ${SyntaxKind[node.kind]}` +}) export const emit = (node: Node, context: Context): EmitResult => { switch (node.kind) { @@ -20,7 +27,12 @@ case SyntaxKind.CallExpression: return emitCallExpressionStatement(<any>node, context); case SyntaxKind.Identifier: return emitIdentifier(<any>node, context); case SyntaxKind.TypeReference: return emitType(<any>node, context); + case SyntaxKind.Block: return emitBlock(<any>node, context); + case SyntaxKind.ReturnStatement: return emitReturnStatement(<any>node, context); case SyntaxKind.EndOfFileToken: return { context, emitted_string: 'end' }; + case SyntaxKind.ConditionalExpression: return ignore(node, context); + case SyntaxKind.VariableStatement: return ignore(node, context); + case SyntaxKind.BinaryExpression: return ignore(node, context); default: throw new Error(`unknown syntax kind ${SyntaxKind[node.kind]}`); } };