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
a199b983beafc9e42fe83a9e873f8b4024f69be0
src/types/alphabets.ts
src/types/alphabets.ts
/* * Alphabet storage */ export type AlphabetsData = { [name: string]: AlphabetData } export type AlphabetData = { priority: number action: string letters: LetterData[] } export type LetterData = { value: string block: string action?: string } export type ShermanLetterData = LetterData & { dots?: number vert?: number lines: number }
/* * Alphabet storage */ export type Block = "s" | "p" | "d" | "f" | "v" export type AlphabetsData = { [name: string]: AlphabetData } export type AlphabetData = { priority: number action: string letters: LetterData[] } export type LetterData = { value: string block: string action?: string } export type ShermanLetterData = LetterData & { dots?: number vert?: number lines: number }
Add a type for block names
Add a type for block names
TypeScript
mit
rossjrw/gallifreyo,rossjrw/gallifreyo,rossjrw/gallifreyo
--- +++ @@ -1,6 +1,8 @@ /* * Alphabet storage */ + +export type Block = "s" | "p" | "d" | "f" | "v" export type AlphabetsData = { [name: string]: AlphabetData
3a77fff3af2b407ff12db58afa97072d101ae50d
app/common/config/__tests__/parseFile.ts
app/common/config/__tests__/parseFile.ts
import parseFile from "../parseFile"; import ParsingError from "../ParsingError"; const incorrectTomlFilePath = "./app/common/configParser/__tests__/incorrect.toml"; const tomlObj = { tmol: "is", pretty: { cool: "foo" } }; test("Parses known file types", () => { expect(parseFile("./app/common/configParser/__tests__/correct.toml")).toEqual( tomlObj ); }); test("Injects file path to ParsingError", () => { try { parseFile(incorrectTomlFilePath); } catch (e) { expect(e instanceof ParsingError).toBeTruthy(); } }); test("Injects file path to ParsingError", () => { try { parseFile(incorrectTomlFilePath); } catch (e) { if (!(e instanceof ParsingError)) { throw e; } expect(e.filePath).toBe(incorrectTomlFilePath); } });
import parseFile from "../parseFile"; import ParsingError from "../ParsingError"; const incorrectTomlFilePath = "./app/common/config/__tests__/incorrect.toml"; const tomlObj = { tmol: "is", pretty: { cool: "foo" } }; test("Parses known file types", () => { expect(parseFile("./app/common/config/__tests__/correct.toml")).toEqual( tomlObj ); }); test("Injects file path to ParsingError", () => { try { parseFile(incorrectTomlFilePath); } catch (e) { expect(e instanceof ParsingError).toBeTruthy(); } }); test("Injects file path to ParsingError", () => { try { parseFile(incorrectTomlFilePath); } catch (e) { if (!(e instanceof ParsingError)) { throw e; } expect(e.filePath).toBe(incorrectTomlFilePath); } });
Fix tests from last commit
Fix tests from last commit
TypeScript
mit
ocboogie/action-hub,ocboogie/action-hub,ocboogie/action-hub
--- +++ @@ -1,8 +1,7 @@ import parseFile from "../parseFile"; import ParsingError from "../ParsingError"; -const incorrectTomlFilePath = - "./app/common/configParser/__tests__/incorrect.toml"; +const incorrectTomlFilePath = "./app/common/config/__tests__/incorrect.toml"; const tomlObj = { tmol: "is", @@ -12,7 +11,7 @@ }; test("Parses known file types", () => { - expect(parseFile("./app/common/configParser/__tests__/correct.toml")).toEqual( + expect(parseFile("./app/common/config/__tests__/correct.toml")).toEqual( tomlObj ); });
cf54f03e1c3e4f286c5582e2e9ce79eefc475b30
static/services/filter.ts
static/services/filter.ts
import {Filter} from '../models/filter'; export class FilterService { order = { count: { name: '_count', desc: true }, min: { name: 'min_duration', desc: true }, max: { name: 'max_duration', desc: true }, p25: { name: 'percentiles_duration.25', desc: true }, p50: { name: 'percentiles_duration.50', desc: true }, p75: { name: 'percentiles_duration.75', desc: true }, p95: { name: 'percentiles_duration.95', desc: true }, p99: { name: 'percentiles_duration.99', desc: true }, } state: Filter; constructor(private $location: ng.ILocationService, private $cookies: ng.cookies.ICookiesService) { this.refresh(); } static $inject = ["$location", "$cookies"]; refresh(): Filter { var params = this.$location.search(); this.state = new Filter(this.$location.search(), this.$cookies.get('dtrace_system')); return this.state; } set_location() { const cur_state = this.state.get(); const location_state = this.$location.search(); var equal = true; angular.forEach(cur_state, (value, key) => { if(location_state[key] !== value){ equal = false; } }); if(!equal) this.$location.search(cur_state); } clear(){ this.$location.search({}); this.refresh(); this.set_location(); } }
import {Filter} from '../models/filter'; export class FilterService { order = { count: { name: '_count', desc: true }, min: { name: 'min_duration', desc: true }, max: { name: 'max_duration', desc: true }, p25: { name: 'percentiles_duration.25', desc: true }, p50: { name: 'percentiles_duration.50', desc: true }, p75: { name: 'percentiles_duration.75', desc: true }, p95: { name: 'percentiles_duration.95', desc: true }, p99: { name: 'percentiles_duration.99', desc: true }, } state: Filter; constructor(private $location: ng.ILocationService, private $cookies: ng.cookies.ICookiesService) { this.refresh(); } static $inject = ["$location", "$cookies"]; refresh(): Filter { var params = this.$location.search(); this.state = new Filter(this.$location.search(), this.$cookies.get('dtrace_system')); return this.state; } set_location() { const cur_state = this.state.get(); const location_state = this.$location.search(); if(!angular.equals(cur_state, location_state)) this.$location.search(cur_state); } clear(){ this.$location.search({}); this.refresh(); this.set_location(); } }
Fix location state and current state comparison
Fix location state and current state comparison
TypeScript
mit
ditrace/web,ditrace/web,ditrace/web
--- +++ @@ -29,13 +29,7 @@ set_location() { const cur_state = this.state.get(); const location_state = this.$location.search(); - var equal = true; - angular.forEach(cur_state, (value, key) => { - if(location_state[key] !== value){ - equal = false; - } - }); - if(!equal) + if(!angular.equals(cur_state, location_state)) this.$location.search(cur_state); }
7cb1b7d956765a654018afa8b6a3ba4d5214ba5d
app/src/ui/changes/undo-commit.tsx
app/src/ui/changes/undo-commit.tsx
import * as React from 'react' import * as moment from 'moment' import { Commit } from '../../lib/local-git-operations' import { EmojiText } from '../lib/emoji-text' interface IUndoCommitProps { /** The function to call when the Undo button is clicked. */ readonly onUndo: () => void /** The commit to undo. */ readonly commit: Commit readonly emoji: Map<string, string> } /** The Undo Commit component. */ export class UndoCommit extends React.Component<IUndoCommitProps, void> { public render() { const relative = moment(this.props.commit.authorDate).fromNow() return ( <div id='undo-commit'> <div className='commit-info'> <div className='ago'>Committed {relative}</div> <EmojiText emoji={this.props.emoji} className='summary'>{this.props.commit.summary}</EmojiText> </div> <div className='actions'> <button className='button' onClick={() => this.props.onUndo()}>Undo</button> </div> </div> ) } }
import * as React from 'react' import { Commit } from '../../lib/local-git-operations' import { EmojiText } from '../lib/emoji-text' import { RelativeTime } from '../relative-time' interface IUndoCommitProps { /** The function to call when the Undo button is clicked. */ readonly onUndo: () => void /** The commit to undo. */ readonly commit: Commit readonly emoji: Map<string, string> } /** The Undo Commit component. */ export class UndoCommit extends React.Component<IUndoCommitProps, void> { public render() { const authorDate = this.props.commit.authorDate return ( <div id='undo-commit'> <div className='commit-info'> <div className='ago'>Committed <RelativeTime date={authorDate} /></div> <EmojiText emoji={this.props.emoji} className='summary'>{this.props.commit.summary}</EmojiText> </div> <div className='actions'> <button className='button' onClick={() => this.props.onUndo()}>Undo</button> </div> </div> ) } }
Use auto updating relative time in undo commit
Use auto updating relative time in undo commit
TypeScript
mit
kactus-io/kactus,kactus-io/kactus,say25/desktop,artivilla/desktop,gengjiawen/desktop,hjobrien/desktop,shiftkey/desktop,hjobrien/desktop,artivilla/desktop,gengjiawen/desktop,j-f1/forked-desktop,gengjiawen/desktop,BugTesterTest/desktops,say25/desktop,shiftkey/desktop,desktop/desktop,artivilla/desktop,artivilla/desktop,BugTesterTest/desktops,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,BugTesterTest/desktops,desktop/desktop,gengjiawen/desktop,hjobrien/desktop,j-f1/forked-desktop,shiftkey/desktop,hjobrien/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,desktop/desktop,BugTesterTest/desktops,kactus-io/kactus,desktop/desktop
--- +++ @@ -1,8 +1,8 @@ import * as React from 'react' -import * as moment from 'moment' import { Commit } from '../../lib/local-git-operations' import { EmojiText } from '../lib/emoji-text' +import { RelativeTime } from '../relative-time' interface IUndoCommitProps { /** The function to call when the Undo button is clicked. */ @@ -17,11 +17,11 @@ /** The Undo Commit component. */ export class UndoCommit extends React.Component<IUndoCommitProps, void> { public render() { - const relative = moment(this.props.commit.authorDate).fromNow() + const authorDate = this.props.commit.authorDate return ( <div id='undo-commit'> <div className='commit-info'> - <div className='ago'>Committed {relative}</div> + <div className='ago'>Committed <RelativeTime date={authorDate} /></div> <EmojiText emoji={this.props.emoji} className='summary'>{this.props.commit.summary}</EmojiText> </div> <div className='actions'>
8041a9d4a2c6e9bd506623006b57d8d9883a056d
src/components/SearchResultsItem.tsx
src/components/SearchResultsItem.tsx
import React from 'react'; import styled from 'styled-components'; import { EdamamRecipe } from '../types/edamam'; import LazyLoadImage from './LazyLoadImage'; const Block = styled.article` border: 1px solid #dcdcdc; border-radius: 5px; box-shadow: 1px 3px 3px rgba(0, 0, 0, 0.4); transition: all 0.2s ease-in-out; :hover { border-color: #acacac; transform: scale(1.01); } `; const Header = styled.h2` font-size: 18px; margin: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; `; const RecipeImage = styled(LazyLoadImage)` object-fit: cover; width: 100%; `; const SearchResultsItem = ({ image, label }: EdamamRecipe) => ( <Block> <Header title={label}>{label}</Header> <RecipeImage src={image} alt={label} /> </Block> ); export default SearchResultsItem;
import React from 'react'; import styled from 'styled-components'; import { EdamamRecipe } from '../types/edamam'; import { titleCase } from '../utils'; import LazyLoadImage from './LazyLoadImage'; const Block = styled.article` border: 1px solid #dcdcdc; border-radius: 5px; box-shadow: 1px 3px 3px rgba(0, 0, 0, 0.4); transition: all 0.2s ease-in-out; :hover { border-color: #acacac; transform: scale(1.01); } `; const Header = styled.h2` font-size: 18px; margin: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; `; const RecipeImage = styled(LazyLoadImage)` object-fit: cover; width: 100%; `; const SearchResultsItem = ({ image, label }: EdamamRecipe) => { const formattedLabel: string = titleCase(label); return ( <Block> <Header title={formattedLabel}>{formattedLabel}</Header> <RecipeImage src={image} alt={formattedLabel} /> </Block> ); }; export default SearchResultsItem;
Format recipe title as title case
Format recipe title as title case
TypeScript
mit
mbchoa/recipeek,mbchoa/recipeek,mbchoa/recipeek
--- +++ @@ -2,6 +2,7 @@ import styled from 'styled-components'; import { EdamamRecipe } from '../types/edamam'; +import { titleCase } from '../utils'; import LazyLoadImage from './LazyLoadImage'; @@ -29,11 +30,14 @@ width: 100%; `; -const SearchResultsItem = ({ image, label }: EdamamRecipe) => ( - <Block> - <Header title={label}>{label}</Header> - <RecipeImage src={image} alt={label} /> - </Block> -); +const SearchResultsItem = ({ image, label }: EdamamRecipe) => { + const formattedLabel: string = titleCase(label); + return ( + <Block> + <Header title={formattedLabel}>{formattedLabel}</Header> + <RecipeImage src={image} alt={formattedLabel} /> + </Block> + ); +}; export default SearchResultsItem;
0a9a3887b5bc7d87f3f509f3d28dc2b1ce698408
components/_util/getRequestAnimationFrame.tsx
components/_util/getRequestAnimationFrame.tsx
const availablePrefixs = ['moz', 'ms', 'webkit']; function requestAnimationFramePolyfill() { let lastTime = 0; return function(callback) { const currTime = new Date().getTime(); const timeToCall = Math.max(0, 16 - (currTime - lastTime)); const id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } export default function getRequestAnimationFrame() { if (typeof window === 'undefined') { return () => {}; } if (window.requestAnimationFrame) { return window.requestAnimationFrame; } const prefix = availablePrefixs.filter(key => `${key}RequestAnimationFrame` in window)[0]; return prefix ? window[`${prefix}RequestAnimationFrame`] : requestAnimationFramePolyfill(); } export function cancelRequestAnimationFrame(id) { if (typeof window === 'undefined') { return null; } if (window.cancelAnimationFrame) { return window.cancelAnimationFrame(id); } const prefix = availablePrefixs.filter(key => `${key}CancelAnimationFrame` in window || `${key}CancelRequestAnimationFrame` in window, )[0]; return prefix ? (window[`${prefix}CancelAnimationFrame`] || window[`${prefix}CancelRequestAnimationFrame`]).call(this, id) : clearTimeout(id); }
const availablePrefixs = ['moz', 'ms', 'webkit']; function requestAnimationFramePolyfill() { let lastTime = 0; return function(callback) { const currTime = new Date().getTime(); const timeToCall = Math.max(0, 16 - (currTime - lastTime)); const id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } export default function getRequestAnimationFrame() { if (typeof window === 'undefined') { return () => {}; } if (window.requestAnimationFrame) { // https://github.com/vuejs/vue/issues/4465 return window.requestAnimationFrame.bind(window); } const prefix = availablePrefixs.filter(key => `${key}RequestAnimationFrame` in window)[0]; return prefix ? window[`${prefix}RequestAnimationFrame`] : requestAnimationFramePolyfill(); } export function cancelRequestAnimationFrame(id) { if (typeof window === 'undefined') { return null; } if (window.cancelAnimationFrame) { return window.cancelAnimationFrame(id); } const prefix = availablePrefixs.filter(key => `${key}CancelAnimationFrame` in window || `${key}CancelRequestAnimationFrame` in window, )[0]; return prefix ? (window[`${prefix}CancelAnimationFrame`] || window[`${prefix}CancelRequestAnimationFrame`]).call(this, id) : clearTimeout(id); }
Fix Invalid calling object in IE with eval-source-map mode of webpack-dev-server
Fix Invalid calling object in IE with eval-source-map mode of webpack-dev-server close #7060 ref https://github.com/vuejs/vue/issues/4465
TypeScript
mit
zheeeng/ant-design,havefive/ant-design,havefive/ant-design,RaoHai/ant-design,vgeyi/ant-design,ant-design/ant-design,ant-design/ant-design,ant-design/ant-design,marswong/ant-design,marswong/ant-design,vgeyi/ant-design,elevensky/ant-design,icaife/ant-design,vgeyi/ant-design,icaife/ant-design,RaoHai/ant-design,havefive/ant-design,zheeeng/ant-design,vgeyi/ant-design,elevensky/ant-design,marswong/ant-design,havefive/ant-design,RaoHai/ant-design,zheeeng/ant-design,elevensky/ant-design,icaife/ant-design,zheeeng/ant-design,elevensky/ant-design,ant-design/ant-design,RaoHai/ant-design,marswong/ant-design,icaife/ant-design
--- +++ @@ -16,7 +16,8 @@ return () => {}; } if (window.requestAnimationFrame) { - return window.requestAnimationFrame; + // https://github.com/vuejs/vue/issues/4465 + return window.requestAnimationFrame.bind(window); } const prefix = availablePrefixs.filter(key => `${key}RequestAnimationFrame` in window)[0];
d0cc8dff0d4f6361bde4dc93708e452802e80ffc
app/src/component/BooksMenu.tsx
app/src/component/BooksMenu.tsx
import { convertCountryIntoBookStoreUrl } from "domain-layer/book"; import * as React from "react"; import { connect } from "react-redux"; import { IBook } from "../lib/books"; import { actionCreators } from "../redux/books"; import CreateMediaItem from "./CreateMediaItem"; import ItemsMenu from "./ItemsMenu"; import Link from "./Link"; import SimpleBook from "./SimpleBook"; import TrendingItems from "./TrendingItems"; interface IProps { country: string | null; createItem: (url: string) => void; done: boolean; onItemsStateChange: (done: boolean) => void; trendingItems: IBook[]; } class BooksMenu extends React.Component<IProps> { public render() { const { country, createItem, trendingItems } = this.props; return ( <ItemsMenu {...this.props} createItem={ <CreateMediaItem createItem={createItem} placeholder="Book URL of Rakuten Books or Better World Books" />} doneButtonText="read" todoButtonText="to read" > <TrendingItems itemComponent={SimpleBook} trendingItems={trendingItems} /> {country && <Link href={convertCountryIntoBookStoreUrl(country)} > Search online </Link>} </ItemsMenu> ); } } export default connect( ({ books, environment }) => ({ ...books, ...environment }), actionCreators, )(BooksMenu);
import { convertCountryIntoBookStoreUrl } from "domain-layer/book"; import * as React from "react"; import Search = require("react-icons/lib/md/search"); import { connect } from "react-redux"; import { IBook } from "../lib/books"; import { actionCreators } from "../redux/books"; import CreateMediaItem from "./CreateMediaItem"; import ItemsMenu from "./ItemsMenu"; import Link from "./Link"; import NoBoxButton from "./NoBoxButton"; import SimpleBook from "./SimpleBook"; import TrendingItems from "./TrendingItems"; interface IProps { country: string | null; createItem: (url: string) => void; done: boolean; onItemsStateChange: (done: boolean) => void; trendingItems: IBook[]; } class BooksMenu extends React.Component<IProps> { public render() { const { country, createItem, trendingItems } = this.props; return ( <ItemsMenu {...this.props} createItem={ <CreateMediaItem createItem={createItem} placeholder="Book URL of Rakuten Books or Better World Books" />} doneButtonText="read" todoButtonText="to read" > <TrendingItems itemComponent={SimpleBook} trendingItems={trendingItems} /> {country && <Link href={convertCountryIntoBookStoreUrl(country)}> <NoBoxButton icon={<Search />} onClick={() => undefined} > Search </NoBoxButton> </Link>} </ItemsMenu> ); } } export default connect( ({ books, environment }) => ({ ...books, ...environment }), actionCreators, )(BooksMenu);
Improve style of search books buttons
Improve style of search books buttons
TypeScript
mit
raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d
--- +++ @@ -1,5 +1,6 @@ import { convertCountryIntoBookStoreUrl } from "domain-layer/book"; import * as React from "react"; +import Search = require("react-icons/lib/md/search"); import { connect } from "react-redux"; import { IBook } from "../lib/books"; @@ -7,6 +8,7 @@ import CreateMediaItem from "./CreateMediaItem"; import ItemsMenu from "./ItemsMenu"; import Link from "./Link"; +import NoBoxButton from "./NoBoxButton"; import SimpleBook from "./SimpleBook"; import TrendingItems from "./TrendingItems"; @@ -35,10 +37,13 @@ > <TrendingItems itemComponent={SimpleBook} trendingItems={trendingItems} /> {country && - <Link - href={convertCountryIntoBookStoreUrl(country)} - > - Search online + <Link href={convertCountryIntoBookStoreUrl(country)}> + <NoBoxButton + icon={<Search />} + onClick={() => undefined} + > + Search + </NoBoxButton> </Link>} </ItemsMenu> );
e9f9c54dfff545b601fa66f11e9d5c8968b0edb4
blend/src/container/Fit.ts
blend/src/container/Fit.ts
/// <reference path="../common/Interfaces.ts" /> /// <reference path="../Blend.ts" /> /// <reference path="../dom/Element.ts" /> /// <reference path="../ui/PaddableContainer.ts" /> namespace Blend.container { /** * A container that can 100% fit a child View with possibility * to apply a padding to the container body */ export class Fit extends Blend.ui.PaddableContainer { protected config: FitContainerInterface; protected fittedView: Blend.ui.View; public constructor(config: FitContainerInterface = {}) { super(config); var me = this; me.cssClass = 'fit-container'; me.itemCSSClass = cssPrefix(me.cssClass + '-item'); me.fittedView = null; } protected layoutView() { var me = this; if (me.fittedView) { // first time cleanup me.fittedView.setBounds({ top: null, left: null, width: null, height: null }); me.fittedView.setStyle({ display: null }); } me.performLayoutChildren(); } protected render(): Blend.dom.Element { var me = this; return Blend.dom.Element.create({ children: [me.renderBodyElement()] }); } public addView(item: UIType | Array<UIType>) { var me = this; if (me.items.length === 0) { super.addView.apply(me, arguments); me.fittedView = me.items[0]; } else { throw new Error('Fit container can only have one child view!'); } } } }
/// <reference path="../common/Interfaces.ts" /> /// <reference path="../Blend.ts" /> /// <reference path="../dom/Element.ts" /> /// <reference path="../ui/PaddableContainer.ts" /> namespace Blend.container { /** * A container that can 100% fit a child View with possibility * to apply a padding to the container body */ export class Fit extends Blend.ui.PaddableContainer { protected config: FitContainerInterface; protected fittedView: Blend.ui.View; public constructor(config: FitContainerInterface = {}) { super(config); var me = this; me.cssClass = 'fit-container'; me.itemCSSClass = cssPrefix(me.cssClass + '-item'); me.fittedView = null; } protected layoutView() { var me = this; if (me.fittedView) { // first time cleanup me.fittedView.setBounds(null); me.fittedView.setVisible(true); } me.performLayoutChildren(); } protected render(): Blend.dom.Element { var me = this; return Blend.dom.Element.create({ children: [me.renderBodyElement()] }); } public addView(item: UIType | Array<UIType>) { var me = this; if (me.items.length === 0) { super.addView(item); me.fittedView = me.items[0]; } else { throw new Error('Fit container can only have one child view!'); } } } }
Use new API to set the bounds
Use new API to set the bounds
TypeScript
apache-2.0
blendsdk/material-blend,blendsdk/material-blend,blendsdk/material-blend,blendsdk/material-blend,blendsdk/material-blend
--- +++ @@ -26,8 +26,8 @@ var me = this; if (me.fittedView) { // first time cleanup - me.fittedView.setBounds({ top: null, left: null, width: null, height: null }); - me.fittedView.setStyle({ display: null }); + me.fittedView.setBounds(null); + me.fittedView.setVisible(true); } me.performLayoutChildren(); } @@ -42,7 +42,7 @@ public addView(item: UIType | Array<UIType>) { var me = this; if (me.items.length === 0) { - super.addView.apply(me, arguments); + super.addView(item); me.fittedView = me.items[0]; } else { throw new Error('Fit container can only have one child view!');
c08313842c5decfbc6c76aeefa40df818a069ce6
packages/grafana-ui/.storybook/config.ts
packages/grafana-ui/.storybook/config.ts
import { configure } from '@storybook/react'; import '@grafana/ui/src/components/index.scss'; // automatically import all files ending in *.stories.tsx const req = require.context('../src/components', true, /.story.tsx$/); function loadStories() { req.keys().forEach(req); } configure(loadStories, module);
import { configure } from '@storybook/react'; import '../../../public/sass/grafana.light.scss'; // automatically import all files ending in *.stories.tsx const req = require.context('../src/components', true, /.story.tsx$/); function loadStories() { req.keys().forEach(req); } configure(loadStories, module);
Use light theme in storybook
Use light theme in storybook
TypeScript
agpl-3.0
grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana
--- +++ @@ -1,6 +1,6 @@ import { configure } from '@storybook/react'; -import '@grafana/ui/src/components/index.scss'; +import '../../../public/sass/grafana.light.scss'; // automatically import all files ending in *.stories.tsx const req = require.context('../src/components', true, /.story.tsx$/);
c9a739174b5eee8f25b23836ec98f94b3e7ca30c
client/app/accounts/components/register/register.component.ts
client/app/accounts/components/register/register.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { Account } from '../../models'; import { AccountService } from '../../services'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'] }) export class RegisterComponent { public account = new Account(); public errorMessage: string; constructor(private service: AccountService, private router: Router) { } register() { this.service .register(this.account.email, this.account.password) .then(() => this.router.navigate(['/'])) .catch(error => this.errorMessage = getErrorMessage(error.status)) ; function getErrorMessage(status) { switch (status) { case 409: return 'This account already exists.'; default: return `We're sorry, but an unexpected error occurred.`; } } } }
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { Account } from '../../models'; import { AccountService, CurrentAccountService } from '../../services'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'] }) export class RegisterComponent { public account = new Account(); public errorMessage: string; constructor( private service: AccountService, private currentAccount: CurrentAccountService, private router: Router) { } register() { this.service .register(this.account.email, this.account.password) .then(() => this.service.createToken(this.account.email, this.account.password)) .then(token => { this.currentAccount.set(token); this.router.navigate(['/']); }) .catch(error => this.errorMessage = getErrorMessage(error.status)) ; function getErrorMessage(status) { switch (status) { case 409: return 'This account already exists.'; default: return `We're sorry, but an unexpected error occurred.`; } } } }
Add automatic log in after registration
Add automatic log in after registration
TypeScript
mit
fvilers/angular2-training,fvilers/angular2-training,fvilers/angular2-training
--- +++ @@ -2,7 +2,7 @@ import { Router } from '@angular/router'; import { Account } from '../../models'; -import { AccountService } from '../../services'; +import { AccountService, CurrentAccountService } from '../../services'; @Component({ selector: 'app-register', @@ -13,13 +13,20 @@ public account = new Account(); public errorMessage: string; - constructor(private service: AccountService, private router: Router) { + constructor( + private service: AccountService, + private currentAccount: CurrentAccountService, + private router: Router) { } register() { this.service .register(this.account.email, this.account.password) - .then(() => this.router.navigate(['/'])) + .then(() => this.service.createToken(this.account.email, this.account.password)) + .then(token => { + this.currentAccount.set(token); + this.router.navigate(['/']); + }) .catch(error => this.errorMessage = getErrorMessage(error.status)) ;
5c9e99257f4c0f98f65f2fa46a6c24e9346bf30f
modules/mcagar/src/test/ts/browser/api/TinyLoaderErrorTest.ts
modules/mcagar/src/test/ts/browser/api/TinyLoaderErrorTest.ts
import { UnitTest } from '@ephox/bedrock-client'; import * as TinyLoader from 'ephox/mcagar/api/TinyLoader'; import Theme from 'tinymce/lib/themes/silver/main/ts/Theme'; UnitTest.asynctest('TinyLoader should fail (instead of timeout) when exception is thrown in callback function', (success, failure) => { Theme(); TinyLoader.setup(() => { throw new Error('boo!'); }, { base_url: '/project/tinymce/js/tinymce' }, failure, success); });
import { UnitTest } from '@ephox/bedrock-client'; import * as TinyLoader from 'ephox/mcagar/api/TinyLoader'; UnitTest.asynctest('TinyLoader should fail (instead of timeout) when exception is thrown in callback function', (success, failure) => { TinyLoader.setup(() => { throw new Error('boo!'); }, { base_url: '/project/tinymce/js/tinymce' }, failure, success); });
Remove Theme call to avoid compile error.
Remove Theme call to avoid compile error.
TypeScript
mit
tinymce/tinymce,tinymce/tinymce,TeamupCom/tinymce,FernCreek/tinymce,FernCreek/tinymce,tinymce/tinymce,TeamupCom/tinymce,FernCreek/tinymce
--- +++ @@ -1,10 +1,7 @@ import { UnitTest } from '@ephox/bedrock-client'; import * as TinyLoader from 'ephox/mcagar/api/TinyLoader'; -import Theme from 'tinymce/lib/themes/silver/main/ts/Theme'; UnitTest.asynctest('TinyLoader should fail (instead of timeout) when exception is thrown in callback function', (success, failure) => { - Theme(); - TinyLoader.setup(() => { throw new Error('boo!'); }, { base_url: '/project/tinymce/js/tinymce' }, failure, success);
9a7ada2d0ef9447b26becc666578c887ad223592
packages/lesswrong/lib/executionEnvironment.ts
packages/lesswrong/lib/executionEnvironment.ts
import { Meteor } from 'meteor/meteor'; export const isServer = Meteor.isServer export const isClient = Meteor.isClient export const isDevelopment = Meteor.isDevelopment export const isProduction = Meteor.isProduction export const isAnyTest = Meteor.isTest || Meteor.isAppTest || Meteor.isPackageTest export const isPackageTest = Meteor.isPackageTest export const onStartup = (fn: ()=>void) => { Meteor.startup(fn); } export const getInstanceSettings = () => Meteor.settings; export const getAbsoluteUrl = (maybeRelativeUrl?: string): string => { return Meteor.absoluteUrl(maybeRelativeUrl); } // Like setTimeout, but with fiber handling export const runAfterDelay = Meteor.setTimeout; // Like setTimeout with 0 timeout, possibly different priority, and fiber handling export const deferWithoutDelay = Meteor.delay; export const runAtInterval = Meteor.setInterval; export const wrapAsync = Meteor.wrapAsync ? Meteor.wrapAsync : Meteor._wrapAsync;
import { Meteor } from 'meteor/meteor'; export const isServer = Meteor.isServer export const isClient = Meteor.isClient export const isDevelopment = Meteor.isDevelopment export const isProduction = Meteor.isProduction export const isAnyTest = Meteor.isTest || Meteor.isAppTest || Meteor.isPackageTest export const isPackageTest = Meteor.isPackageTest export const onStartup = (fn: ()=>void) => { Meteor.startup(fn); } export const getInstanceSettings = () => Meteor.settings; export const getAbsoluteUrl = (maybeRelativeUrl?: string): string => { return Meteor.absoluteUrl(maybeRelativeUrl); } // Like setTimeout, but with fiber handling export const runAfterDelay = Meteor.setTimeout; // Like setTimeout with 0 timeout, possibly different priority, and fiber handling export const deferWithoutDelay = Meteor.defer; export const runAtInterval = Meteor.setInterval; export const wrapAsync = Meteor.wrapAsync ? Meteor.wrapAsync : Meteor._wrapAsync;
Fix broken wrapper around Meteor.defer
Fix broken wrapper around Meteor.defer
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -21,7 +21,7 @@ export const runAfterDelay = Meteor.setTimeout; // Like setTimeout with 0 timeout, possibly different priority, and fiber handling -export const deferWithoutDelay = Meteor.delay; +export const deferWithoutDelay = Meteor.defer; export const runAtInterval = Meteor.setInterval;
5d6215f76c0283f5c2ebca3b4f06019ea16bc182
brandings/src/interfaces/node-status.interfaces.ts
brandings/src/interfaces/node-status.interfaces.ts
export enum NodeStatus { RUNNING = 'running', HALTED = 'halted', REBOOTING = 'rebooting', } export interface NodeStatusTime { status: NodeStatus; date: string; } export interface NodeInfo { status: NodeStatus; id: string; serial_number: string; statuses?: NodeStatusTime[]; status_date?: string; last_check?: string; stats?: NodeStatsData[]; } export enum NodeStatsType { CPU = 'machine.CPU.percent', RAM = 'machine.memory.ram.available', NETWORK_OUT = 'network.throughput.incoming', NETWORK_IN = 'network.throughput.outgoing', } export interface NodeStatsData { type: NodeStatsType; data: NodeStatsSeries[]; } export interface NodeStatsSeries { columns: string[]; name: 'node-stats'; tags?: { subtype: string }; values: [ string, number ][]; }
export enum NodeStatus { RUNNING = 'running', HALTED = 'halted', REBOOTING = 'rebooting', } export interface NodeStatusTime { status: NodeStatus; date: string; } export interface NodeInfo { status: NodeStatus; id: string; serial_number: string; statuses?: NodeStatusTime[]; status_date?: string; last_check?: string; stats?: NodeStatsData[]; } export enum NodeStatsType { CPU = 'machine.CPU.percent', RAM = 'machine.memory.ram.available', NETWORK_OUT = 'network.throughput.outgoing', NETWORK_IN = 'network.throughput.incoming', } export interface NodeStatsData { type: NodeStatsType; data: NodeStatsSeries[]; } export interface NodeStatsSeries { columns: string[]; name: 'node-stats'; tags?: { subtype: string }; values: [ string, number ][]; }
Fix swapped incoming / outgoing network stats
fix(node-stats): Fix swapped incoming / outgoing network stats
TypeScript
bsd-3-clause
threefoldfoundation/app_backend,threefoldfoundation/app_backend,threefoldfoundation/app_backend,threefoldfoundation/app_backend
--- +++ @@ -22,8 +22,8 @@ export enum NodeStatsType { CPU = 'machine.CPU.percent', RAM = 'machine.memory.ram.available', - NETWORK_OUT = 'network.throughput.incoming', - NETWORK_IN = 'network.throughput.outgoing', + NETWORK_OUT = 'network.throughput.outgoing', + NETWORK_IN = 'network.throughput.incoming', } export interface NodeStatsData {
13a6fb6bc8a1d6dd2f5b47a32b25f6206d71005d
packages/pretur.sync/src/query.ts
packages/pretur.sync/src/query.ts
export type Ordering = 'NONE' | 'ASC' | 'DESC'; export interface QueryOrder { field: string; ordering: Ordering; chain?: string[]; } export interface QueryFilters { [attribute: string]: any; } export interface QueryPagination { skip?: number; take?: number; } export interface QueryInclude { [alias: string]: SubQuery | boolean; } export interface SubQuery { include?: QueryInclude; filters?: QueryFilters; attributes?: string[]; } export interface Query { queryId?: number; model?: string; byId?: number; count?: boolean; extra?: any; include?: QueryInclude; filters?: QueryFilters; attributes?: string[]; pagination?: QueryPagination; order?: QueryOrder; }
export type Ordering = 'NONE' | 'ASC' | 'DESC'; export interface QueryOrder { field: string; ordering: Ordering; chain?: string[]; } export interface QueryFilters { [attribute: string]: any; } export interface QueryPagination { skip?: number; take?: number; } export interface QueryInclude { [alias: string]: SubQuery | boolean; } export interface SubQuery { include?: QueryInclude; filters?: QueryFilters; attributes?: string[]; required?: boolean; } export interface Query { queryId?: number; model?: string; byId?: number; count?: boolean; extra?: any; include?: QueryInclude; filters?: QueryFilters; attributes?: string[]; pagination?: QueryPagination; order?: QueryOrder; }
Add required to sync subQuery
Add required to sync subQuery
TypeScript
mit
pretur/pretur,pretur/pretur
--- +++ @@ -23,6 +23,7 @@ include?: QueryInclude; filters?: QueryFilters; attributes?: string[]; + required?: boolean; } export interface Query {
cdf0bce0d23d03988b34bec93a9d8eb81a7d4b71
packages/plugin-express/types/bugsnag-express.d.ts
packages/plugin-express/types/bugsnag-express.d.ts
import { Bugsnag } from '@bugsnag/node' declare const bugsnagPluginExpress: Bugsnag.Plugin export default bugsnagPluginExpress
import { Plugin } from '@bugsnag/node' declare const bugsnagPluginExpress: Plugin export default bugsnagPluginExpress
Correct import for plugin type
fix(plugin-express): Correct import for plugin type
TypeScript
mit
bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js
--- +++ @@ -1,3 +1,3 @@ -import { Bugsnag } from '@bugsnag/node' -declare const bugsnagPluginExpress: Bugsnag.Plugin +import { Plugin } from '@bugsnag/node' +declare const bugsnagPluginExpress: Plugin export default bugsnagPluginExpress
f896330b3c0c0d5488ed8475b61b6f4de12da558
app/core/map.service.ts
app/core/map.service.ts
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Map, MapType } from './map'; @Injectable() export class MapService { constructor(private http: Http) { } addMap( title: string = "", height: number, width: number, mapType: MapType, creatorId: number, graphics: string = "" ) { // TODO: compute hash, id, date and return an Observable<Map> } map(id: number) { } maps() { } }
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Map, MapType } from './map'; @Injectable() export class MapService { constructor(private http: Http) { } add( title: string = "", height: number, width: number, mapType: MapType, creatorId: number, graphics: string = "" ) { // TODO: compute hash, id, date and return an Observable<Map> } map(id: number) { } maps() { } delete(id: number) {} }
Add delete function and change add name
Add delete function and change add name
TypeScript
mit
ABAPlan/abaplan-core,ABAPlan/abaplan-core,ABAPlan/abaplan-core
--- +++ @@ -10,7 +10,7 @@ constructor(private http: Http) { } - addMap( + add( title: string = "", height: number, width: number, @@ -29,5 +29,7 @@ } + delete(id: number) {} + }
4b63936fbd99a7c91d686ecada2b42352dd31f20
components/features/Summary/SummaryContainer.tsx
components/features/Summary/SummaryContainer.tsx
import Typography from "@material-ui/core/Typography" import PanelWrapper from "components/panels/PanelWrapper" import Layout from "components/layout/Layout" import GoaPanel from "./Panels/GoaPanel" import { GeneQuery } from "dicty-graphql-schema" import { useRouter } from "next/router" interface SummaryContainerProps { gene: GeneQuery } const SummaryContainer = ({ gene }: SummaryContainerProps) => { const { query } = useRouter() const geneId = query.gene as string return ( <Layout gene={geneId} title={`Gene Summary for ${geneId}`} description={`Gene information for ${geneId}`}> <Typography component="div"> <PanelWrapper title="Latest Gene Ontology Annotations" route={`/gene/${geneId}/goannotations`}> <GoaPanel data={gene} /> </PanelWrapper> </Typography> </Layout> ) } export default SummaryContainer
import Typography from "@material-ui/core/Typography" import PanelWrapper from "components/panels/PanelWrapper" import Layout from "components/layout/Layout" import GoaPanel from "./Panels/GoaPanel" import ReferencesPanel from './Panels/ReferencesPanel' import { GeneQuery } from "dicty-graphql-schema" import { useRouter } from "next/router" interface SummaryContainerProps { gene: GeneQuery } const SummaryContainer = ({ gene }: SummaryContainerProps) => { const { query } = useRouter() const geneId = query.gene as string return ( <Layout gene={geneId} title={`Gene Summary for ${geneId}`} description={`Gene information for ${geneId}`}> <Typography component="div"> <PanelWrapper title="Latest Gene Ontology Annotations" route={`/gene/${geneId}/goannotations`}> <GoaPanel data={gene} /> </PanelWrapper> <PanelWrapper title="Latest References" route={`/gene/${geneId}/references`}> <ReferencesPanel data={gene} /> </PanelWrapper> </Typography> </Layout> ) } export default SummaryContainer
Add Panel Wrapper for References Panel
feat: Add Panel Wrapper for References Panel
TypeScript
bsd-2-clause
dictyBase/genomepage,dictyBase/genomepage,dictyBase/genomepage
--- +++ @@ -2,6 +2,7 @@ import PanelWrapper from "components/panels/PanelWrapper" import Layout from "components/layout/Layout" import GoaPanel from "./Panels/GoaPanel" +import ReferencesPanel from './Panels/ReferencesPanel' import { GeneQuery } from "dicty-graphql-schema" import { useRouter } from "next/router" @@ -24,6 +25,11 @@ route={`/gene/${geneId}/goannotations`}> <GoaPanel data={gene} /> </PanelWrapper> + <PanelWrapper + title="Latest References" + route={`/gene/${geneId}/references`}> + <ReferencesPanel data={gene} /> + </PanelWrapper> </Typography> </Layout> )
4e1063e852c3bd10a8a59b8e9ed89131a261001e
src/expressions/util/iterators.ts
src/expressions/util/iterators.ts
export class IterationResult<T> { public done: boolean; public promise: Promise<void> | undefined; public value: T | undefined | null; constructor(done: boolean, value: T | undefined, promise: Promise<void> | undefined) { this.done = done; this.value = value; this.promise = promise; } } export enum IterationHint { NONE = 0, SKIP_DESCENDANTS = 1 << 0, } export const DONE_TOKEN = new IterationResult(true, undefined, undefined); export function ready<T>(value: T) { return new IterationResult(false, value, undefined); } export interface IIterator<T> { next(hint: IterationHint): IterationResult<T>; }
export class IterationResult<T> { public done: boolean; public value: T | undefined | null; constructor(done: boolean, value: T | undefined) { this.done = done; this.value = value; } } export enum IterationHint { NONE = 0, SKIP_DESCENDANTS = 1 << 0, } export const DONE_TOKEN = new IterationResult(true, undefined); export function ready<T>(value: T) { return new IterationResult(false, value); } export interface IIterator<T> { next(hint: IterationHint): IterationResult<T>; }
Remove dead occurence of asyncness
Remove dead occurence of asyncness
TypeScript
mit
FontoXML/fontoxpath,FontoXML/fontoxpath,FontoXML/fontoxpath
--- +++ @@ -1,11 +1,9 @@ export class IterationResult<T> { public done: boolean; - public promise: Promise<void> | undefined; public value: T | undefined | null; - constructor(done: boolean, value: T | undefined, promise: Promise<void> | undefined) { + constructor(done: boolean, value: T | undefined) { this.done = done; this.value = value; - this.promise = promise; } } @@ -14,9 +12,9 @@ SKIP_DESCENDANTS = 1 << 0, } -export const DONE_TOKEN = new IterationResult(true, undefined, undefined); +export const DONE_TOKEN = new IterationResult(true, undefined); export function ready<T>(value: T) { - return new IterationResult(false, value, undefined); + return new IterationResult(false, value); } export interface IIterator<T> {
5d5e47bc5aa15e8f499bd35b033ec297dabda48b
types/netease-captcha/netease-captcha-tests.ts
types/netease-captcha/netease-captcha-tests.ts
const config: NeteaseCaptcha.Config = { captchaId: 'FAKE ID', element: '#captcha', mode: 'popup', protocol: 'https', width: '200px', lang: 'en', onVerify: (error: any, data?: NeteaseCaptcha.Data) => { console.log(error, data); } }; const onLoad: NeteaseCaptcha.onLoad = (instance: NeteaseCaptcha.Instance) => { instance.refresh(); instance.destroy(); }; function init(initNECaptcha: NeteaseCaptcha.InitFunction): void { initNECaptcha(config, onLoad); }
const config: NeteaseCaptcha.Config = { captchaId: 'FAKE ID', element: '#captcha', mode: 'popup', protocol: 'https', width: '200px', lang: 'en', onVerify: (error: any, data?: NeteaseCaptcha.Data) => { console.log(error, data); } }; const onLoad: NeteaseCaptcha.onLoad = (instance: NeteaseCaptcha.Instance) => { instance.refresh(); instance.destroy(); if (instance.popUp) { instance.popUp(); } }; if (window.initNECaptcha) { window.initNECaptcha(config, onLoad); }
Add test for window attribute
Add test for window attribute
TypeScript
mit
mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,magny/DefinitelyTyped,markogresak/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped
--- +++ @@ -13,8 +13,11 @@ const onLoad: NeteaseCaptcha.onLoad = (instance: NeteaseCaptcha.Instance) => { instance.refresh(); instance.destroy(); + if (instance.popUp) { + instance.popUp(); + } }; -function init(initNECaptcha: NeteaseCaptcha.InitFunction): void { - initNECaptcha(config, onLoad); +if (window.initNECaptcha) { + window.initNECaptcha(config, onLoad); }
477b6ccf4636e061d4af6a73189eee1a9a8735c0
src/graphql/GraphQLEvent.ts
src/graphql/GraphQLEvent.ts
import { GraphQLObjectType, GraphQLList, GraphQLInputObjectType, GraphQLString, GraphQLInt, GraphQLID, GraphQLBoolean, GraphQLNonNull, } from 'graphql' import { GraphQLDateTime } from './GraphQLDateTime' import { Company } from './GraphQLCompany' import { UserType } from './GraphQLUser' const MutableEventFields = { date: { type: GraphQLDateTime }, location: { type: GraphQLString }, publicDescription: { type: GraphQLString }, privateDescription: { type: GraphQLString }, beforeSurvey: { type: GraphQLString }, afterSurvey: { type: GraphQLString }, pictures: { type: new GraphQLList(GraphQLString) }, published: { type: GraphQLBoolean }, } export const EventType: GraphQLObjectType = new GraphQLObjectType({ name: 'Event', fields: () => ({ id: { type: GraphQLID }, ...MutableEventFields, responsible: { type: UserType }, company: { type: Company }, studsYear: { type: GraphQLInt }, }), }) export const EventCreateType = new GraphQLInputObjectType({ name: 'EventCreateType', fields: () => ({ responsibleUserId: { type: GraphQLString }, companyId: { type: new GraphQLNonNull(GraphQLString) }, studsYear: { type: new GraphQLNonNull(GraphQLInt) }, ...MutableEventFields, }), }) // TODO: Make status editable export const EventInputType = new GraphQLInputObjectType({ name: 'EventInput', fields: () => ({ responsibleUserId: {type: GraphQLString}, ...MutableEventFields, }), })
import { GraphQLObjectType, GraphQLList, GraphQLInputObjectType, GraphQLString, GraphQLInt, GraphQLID, GraphQLBoolean, GraphQLNonNull, } from 'graphql' import { GraphQLDateTime } from './GraphQLDateTime' import { Company } from './GraphQLCompany' import { UserType } from './GraphQLUser' const MutableEventFields = { date: { type: GraphQLDateTime }, location: { type: GraphQLString }, publicDescription: { type: GraphQLString }, privateDescription: { type: GraphQLString }, beforeSurvey: { type: GraphQLString }, afterSurvey: { type: GraphQLString }, pictures: { type: new GraphQLList(GraphQLString) }, published: { type: GraphQLBoolean }, } export const EventType: GraphQLObjectType = new GraphQLObjectType({ name: 'Event', fields: () => ({ id: { type: GraphQLID }, ...MutableEventFields, responsible: { type: UserType }, company: { type: Company }, studsYear: { type: GraphQLInt }, }), }) export const EventCreateType = new GraphQLInputObjectType({ name: 'EventCreateType', fields: () => ({ responsibleUserId: { type: GraphQLString }, companyId: { type: new GraphQLNonNull(GraphQLString) }, studsYear: { type: new GraphQLNonNull(GraphQLInt) }, ...MutableEventFields, }), }) // TODO: Make status editable export const EventInputType = new GraphQLInputObjectType({ name: 'EventInput', fields: () => ({ responsibleUserId: {type: GraphQLString}, studsYear: { type: GraphQLInt }, ...MutableEventFields, }), })
Add studsYear is mutable in updateEvent
Add studsYear is mutable in updateEvent
TypeScript
mit
studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord
--- +++ @@ -49,6 +49,7 @@ name: 'EventInput', fields: () => ({ responsibleUserId: {type: GraphQLString}, + studsYear: { type: GraphQLInt }, ...MutableEventFields, }), })
5c6d57ab2cece7ed3fa65f7ef26c944bc33ff57e
lib/services/content-projector.service.ts
lib/services/content-projector.service.ts
'use strict'; import { Injectable, ComponentFactory, ComponentRef, ViewContainerRef } from '@angular/core'; @Injectable() export class ContentProjector { instantiateAndProject<T>(componentFactory: ComponentFactory<T>, parentView:ViewContainerRef, projectedNodesOrComponents: any[]):ComponentRef<T> { let contextInjector = parentView.parentInjector; let projectedNodes = []; let componentRefs:ComponentRef<any>[] = []; for (let i=0; i < projectedNodesOrComponents.length; i++) { let nodeOrCompRef = projectedNodesOrComponents[i]; if (nodeOrCompRef instanceof ComponentRef) { projectedNodes.push(nodeOrCompRef.location.nativeElement); componentRefs.push(nodeOrCompRef); } else { projectedNodes.push(nodeOrCompRef); } } let parentCompRef = parentView.createComponent(componentFactory, null, contextInjector, [projectedNodes]); // using private property to get AppElement instance let appElement = (<any>parentView)._element; appElement.nestedViews = appElement.nestedViews || []; for (let i=0; i < componentRefs.length; i++) { let compRef = componentRefs[i]; appElement.nestedViews.push((<any>compRef.hostView).internalView); // attach appElement to parentView change detector (<any>compRef.hostView).internalView.addToContentChildren(appElement); } return parentCompRef; } }
'use strict'; import { Injectable, ComponentFactory, ComponentRef, ViewContainerRef } from '@angular/core'; @Injectable() export class ContentProjector { instantiateAndProject<T>(componentFactory: ComponentFactory<T>, parentView:ViewContainerRef, projectedNodesOrComponents: any[]):ComponentRef<T> { let contextInjector = parentView.parentInjector; let projectedNodes = []; let componentRefs:ComponentRef<any>[] = []; for (let i=0; i < projectedNodesOrComponents.length; i++) { let nodeOrCompRef = projectedNodesOrComponents[i]; if (nodeOrCompRef instanceof ComponentRef) { projectedNodes.push(nodeOrCompRef.location.nativeElement); componentRefs.push(nodeOrCompRef); } else { projectedNodes.push(nodeOrCompRef); } } let parentCompRef = parentView.createComponent(componentFactory, null, contextInjector, [projectedNodes]); // using private property to get AppElement instance let viewContainer = (<any>parentView)._element; viewContainer.nestedViews = viewContainer.nestedViews || []; for (let i=0; i < componentRefs.length; i++) { let compRef = componentRefs[i]; // attach view to viewContainer change detector viewContainer.nestedViews.push((<any>compRef.hostView).internalView); (<any>compRef.hostView).internalView.viewContainer = viewContainer; } return parentCompRef; } }
Fix content projector after angular2 update
Fix content projector after angular2 update
TypeScript
mit
Rebilly/ReDoc,Rebilly/ReDoc,Rebilly/ReDoc,Rebilly/ReDoc
--- +++ @@ -29,13 +29,13 @@ let parentCompRef = parentView.createComponent(componentFactory, null, contextInjector, [projectedNodes]); // using private property to get AppElement instance - let appElement = (<any>parentView)._element; - appElement.nestedViews = appElement.nestedViews || []; + let viewContainer = (<any>parentView)._element; + viewContainer.nestedViews = viewContainer.nestedViews || []; for (let i=0; i < componentRefs.length; i++) { let compRef = componentRefs[i]; - appElement.nestedViews.push((<any>compRef.hostView).internalView); - // attach appElement to parentView change detector - (<any>compRef.hostView).internalView.addToContentChildren(appElement); + // attach view to viewContainer change detector + viewContainer.nestedViews.push((<any>compRef.hostView).internalView); + (<any>compRef.hostView).internalView.viewContainer = viewContainer; } return parentCompRef; }
542f037a4ece02382e61d8c767432d667c1944d6
src/components/Head.tsx
src/components/Head.tsx
import Head from "next/head"; import largeImage from "../images/hugo_large.jpg"; import ogImage from "../images/hugo_og.jpg"; export default () => ( <div> <Head> <meta charSet="utf-8" /> <meta content="width=device-width, initial-scale=1, viewport-fit=cover" name="viewport" /> <title>Hugo Jobling</title> <meta content="Hugo Jobling. A programmer, writer, and human" name="description" /> {/* Facebook */} <meta content="Hugo Jobling" property="og:title" /> <meta content="Hugo Jobling" property="og:site_name" /> <meta content="https://thisishugo.com" property="og:url" /> <meta content="Hugo Jobling. A programmer, writer, and human" property="og:description" /> <meta content="profile" property="og:type" /> <meta content={ogImage} property="og:image" /> {/* Twitter */} <meta content="summary" name="twitter:card" /> <meta content="@dissimile" name="twitter:site" /> <meta content="Hugo Jobling" name="twitter:title" /> <meta content="Programmer, writer, and human" name="twitter:description" /> <meta content={largeImage} name="twitter:image" /> <link href="/icons/favicon.ico" rel="shortcut icon" /> <link href="/icons/apple-touch-icon.png" rel="apple-touch-icon" /> </Head> </div> );
import Head from "next/head"; import largeImage from "../images/hugo_large.jpg"; import ogImage from "../images/hugo_og.jpg"; export default () => ( <Head> <meta charSet="utf-8" /> <meta content="width=device-width, initial-scale=1, viewport-fit=cover" name="viewport" /> <title>Hugo Jobling</title> <meta content="Hugo Jobling. A programmer, writer, and human" name="description" /> {/* Facebook */} <meta content="Hugo Jobling" property="og:title" /> <meta content="Hugo Jobling" property="og:site_name" /> <meta content="https://thisishugo.com" property="og:url" /> <meta content="Hugo Jobling. A programmer, writer, and human" property="og:description" /> <meta content="profile" property="og:type" /> <meta content={ogImage} property="og:image" /> {/* Twitter */} <meta content="summary" name="twitter:card" /> <meta content="@dissimile" name="twitter:site" /> <meta content="Hugo Jobling" name="twitter:title" /> <meta content="Programmer, writer, and human" name="twitter:description" /> <meta content={largeImage} name="twitter:image" /> <link href="/icons/favicon.ico" rel="shortcut icon" /> <link href="/icons/apple-touch-icon.png" rel="apple-touch-icon" /> </Head> );
Remove unnededed `<div />` wrapper
Remove unnededed `<div />` wrapper
TypeScript
mit
hugo/hugo.github.com,thisishugo/thisishugo.github.com,hugo/hugo.github.com,thisishugo/thisishugo.github.com
--- +++ @@ -4,44 +4,39 @@ import ogImage from "../images/hugo_og.jpg"; export default () => ( - <div> - <Head> - <meta charSet="utf-8" /> - <meta - content="width=device-width, initial-scale=1, viewport-fit=cover" - name="viewport" - /> + <Head> + <meta charSet="utf-8" /> + <meta + content="width=device-width, initial-scale=1, viewport-fit=cover" + name="viewport" + /> - <title>Hugo Jobling</title> + <title>Hugo Jobling</title> - <meta - content="Hugo Jobling. A programmer, writer, and human" - name="description" - /> + <meta + content="Hugo Jobling. A programmer, writer, and human" + name="description" + /> - {/* Facebook */} - <meta content="Hugo Jobling" property="og:title" /> - <meta content="Hugo Jobling" property="og:site_name" /> - <meta content="https://thisishugo.com" property="og:url" /> - <meta - content="Hugo Jobling. A programmer, writer, and human" - property="og:description" - /> - <meta content="profile" property="og:type" /> - <meta content={ogImage} property="og:image" /> + {/* Facebook */} + <meta content="Hugo Jobling" property="og:title" /> + <meta content="Hugo Jobling" property="og:site_name" /> + <meta content="https://thisishugo.com" property="og:url" /> + <meta + content="Hugo Jobling. A programmer, writer, and human" + property="og:description" + /> + <meta content="profile" property="og:type" /> + <meta content={ogImage} property="og:image" /> - {/* Twitter */} - <meta content="summary" name="twitter:card" /> - <meta content="@dissimile" name="twitter:site" /> - <meta content="Hugo Jobling" name="twitter:title" /> - <meta - content="Programmer, writer, and human" - name="twitter:description" - /> - <meta content={largeImage} name="twitter:image" /> + {/* Twitter */} + <meta content="summary" name="twitter:card" /> + <meta content="@dissimile" name="twitter:site" /> + <meta content="Hugo Jobling" name="twitter:title" /> + <meta content="Programmer, writer, and human" name="twitter:description" /> + <meta content={largeImage} name="twitter:image" /> - <link href="/icons/favicon.ico" rel="shortcut icon" /> - <link href="/icons/apple-touch-icon.png" rel="apple-touch-icon" /> - </Head> - </div> + <link href="/icons/favicon.ico" rel="shortcut icon" /> + <link href="/icons/apple-touch-icon.png" rel="apple-touch-icon" /> + </Head> );
a44e5689a3d8d6318d1f62dc26f3255a7f2302fc
SPAWithAngularJS/module5/angularjs-controllers/src/app.module.ts
SPAWithAngularJS/module5/angularjs-controllers/src/app.module.ts
// app.module.ts "use strict"; import { module } from "angular"; import uiRoute from "@uirouter/angularjs"; routingConfig.$inject = ["$stateProvider"]; function routingConfig($stateProvider: angular.ui.IStateProvider) { const message1State: angular.ui.IState = { name: "message1", url: "/message1", template: "<message-1-component></message-1-component>" }; const home: angular.ui.IState = { name: "home", url: "/" }; $stateProvider.state(message1State); $stateProvider.state(home); } const myApp = module("myApp", [uiRoute]) .config(routingConfig); export { myApp };
// app.module.ts "use strict"; import { module } from "angular"; routingConfig.$inject = ["$stateProvider"]; function routingConfig($stateProvider: angular.ui.IStateProvider) { const message1State: angular.ui.IState = { name: "message1", url: "/message1", template: "<message-1-component></message-1-component>" }; const home: angular.ui.IState = { name: "home", url: "/" }; $stateProvider.state(message1State); $stateProvider.state(home); } const myApp = module("myApp", ["ui.router"]) .config(routingConfig); export { myApp };
Delete useless import. Replace uiRoute -> "ui.router"
Delete useless import. Replace uiRoute -> "ui.router"
TypeScript
mit
var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training
--- +++ @@ -3,7 +3,6 @@ "use strict"; import { module } from "angular"; -import uiRoute from "@uirouter/angularjs"; routingConfig.$inject = ["$stateProvider"]; @@ -23,7 +22,7 @@ $stateProvider.state(home); } -const myApp = module("myApp", [uiRoute]) +const myApp = module("myApp", ["ui.router"]) .config(routingConfig); export { myApp };
8b8606f7ca42afad172ef112238c83dc2091c32a
A2/quickstart/src/app/app.component.ts
A2/quickstart/src/app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1> Hello {{name}} </h1> <my-app-custom-component></my-app-custom-component> `, }) export class AppComponent { name = 'Angular'; }
import { Component } from '@angular/core'; @Component({ selector: "my-app", template: `<h1> Hello {{name}} </h1> <my-app-custom-component></my-app-custom-component> `, }) export class AppComponent { name = "Angular"; }
Replace single-quote -> double-quote. Add empty line
Replace single-quote -> double-quote. Add empty line
TypeScript
mit
var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training
--- +++ @@ -1,11 +1,14 @@ import { Component } from '@angular/core'; @Component({ - selector: 'my-app', + selector: "my-app", template: `<h1> Hello {{name}} </h1> <my-app-custom-component></my-app-custom-component> `, }) -export class AppComponent { name = 'Angular'; } + +export class AppComponent { + name = "Angular"; +}
a4a6a327e9bb01a0d4ddb6900ec5fe4b8c0a5e85
angular/src/shared/helpers/SignalRAspNetCoreHelper.ts
angular/src/shared/helpers/SignalRAspNetCoreHelper.ts
import { AppConsts } from '@shared/AppConsts'; import { UtilsService } from '@abp/utils/utils.service'; export class SignalRAspNetCoreHelper { static initSignalR(): void { const encryptedAuthToken = new UtilsService().getCookieValue(AppConsts.authorization.encrptedAuthTokenName); abp.signalr = { autoConnect: true, connect: undefined, hubs: undefined, qs: AppConsts.authorization.encrptedAuthTokenName + '=' + encodeURIComponent(encryptedAuthToken), remoteServiceBaseUrl: AppConsts.remoteServiceBaseUrl, startConnection: undefined, url: '/signalr' }; jQuery.getScript(AppConsts.appBaseUrl + '/assets/abp/abp.signalr-client.js'); } }
import { AppConsts } from '@shared/AppConsts'; import { UtilsService } from '@abp/utils/utils.service'; export class SignalRAspNetCoreHelper { static initSignalR(): void { const encryptedAuthToken = new UtilsService().getCookieValue(AppConsts.authorization.encrptedAuthTokenName); abp.signalr = { autoConnect: true, connect: undefined, hubs: undefined, qs: AppConsts.authorization.encrptedAuthTokenName + '=' + encodeURIComponent(encryptedAuthToken), remoteServiceBaseUrl: AppConsts.remoteServiceBaseUrl, startConnection: undefined, url: '/signalr' }; const script = document.createElement('script'); script.src = AppConsts.appBaseUrl + '/assets/abp/abp.signalr-client.js'; document.head.appendChild(script); } }
Modify the SignalR script loading method.
Modify the SignalR script loading method.
TypeScript
mit
aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template
--- +++ @@ -16,6 +16,8 @@ url: '/signalr' }; - jQuery.getScript(AppConsts.appBaseUrl + '/assets/abp/abp.signalr-client.js'); + const script = document.createElement('script'); + script.src = AppConsts.appBaseUrl + '/assets/abp/abp.signalr-client.js'; + document.head.appendChild(script); } }
8a2f20610a8bb010bd4afb19eb3e9076b40dc4e9
packages/reg-gh-app-front/src/side-effects/fetch-repositories.ts
packages/reg-gh-app-front/src/side-effects/fetch-repositories.ts
import { Observable } from "rxjs"; import { Action, InstallationResAction, RepositoriesResAction, RepositoriesReqAction } from "../actions"; import { ghClient } from "../util/gh-client"; export function fetchRepositories(action$: Observable<Action>) { const installations$ = action$.filter(a => a.type === "installationsRes"); const repoReq$ = installations$ .flatMap((a: InstallationResAction) => Observable.from(a.payload.map(i => i.id))) .map(installationId => ({ type: "repositoriesReq", payload: { installationId, }, } as RepositoriesReqAction)); const repo$ = installations$ .flatMap((a :InstallationResAction) => Observable.from(a.payload.map(i => i.id))) .switchMap(id => ghClient.fetchRepositories(id).then(repositories => { return { type: "repositoriesRes", payload: { installationId: id, repositories, }, } as RepositoriesResAction; })) ; return action$.merge(repoReq$).merge(repo$); }
import { Observable } from "rxjs"; import { Action, InstallationResAction, RepositoriesResAction, RepositoriesReqAction } from "../actions"; import { ghClient } from "../util/gh-client"; export function fetchRepositories(action$: Observable<Action>) { const installations$ = action$.filter(a => a.type === "installationsRes"); const repoReq$ = installations$ .flatMap((a: InstallationResAction) => Observable.from(a.payload.map(i => i.id))) .map(installationId => ({ type: "repositoriesReq", payload: { installationId, }, } as RepositoriesReqAction)); const repo$ = installations$ .flatMap((a :InstallationResAction) => Observable.from(a.payload.map(i => i.id))) .flatMap(id => ghClient.fetchRepositories(id).then(repositories => { return { type: "repositoriesRes", payload: { installationId: id, repositories, }, } as RepositoriesResAction; })) ; return action$.merge(repoReq$).merge(repo$); }
Fix converting stream. should not use switch map!
Fix converting stream. should not use switch map!
TypeScript
mit
reg-viz/reg-suit,reg-viz/reg-suit,reg-viz/reg-suit,reg-viz/reg-suit
--- +++ @@ -14,7 +14,7 @@ } as RepositoriesReqAction)); const repo$ = installations$ .flatMap((a :InstallationResAction) => Observable.from(a.payload.map(i => i.id))) - .switchMap(id => ghClient.fetchRepositories(id).then(repositories => { + .flatMap(id => ghClient.fetchRepositories(id).then(repositories => { return { type: "repositoriesRes", payload: {
e84e8130dffdc79809ab2c933c517947be269511
frontend/src/bundles/status/status.component.ts
frontend/src/bundles/status/status.component.ts
import { Component, OnInit } from '@angular/core'; import { BeamStatsApiService } from "../main/services"; import 'rxjs/add/operator/publishReplay'; import 'rxjs/add/operator/mergeMap'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; @Component({ selector: 'beamstats-status', templateUrl: 'status.component.html', styleUrls: ['status.component.scss'] }) export class StatusComponent implements OnInit { public status$; constructor(private bstatsApi: BeamStatsApiService) { } ngOnInit() { this.status$ = this.bstatsApi.getStats() .do((res: {ingests: any[]}) => res.ingests = res.ingests.sort((a, b) => a['name'].localeCompare(b['name']))) .publishReplay(1) .refCount() } }
import { Component, OnInit } from '@angular/core'; import { BeamStatsApiService } from "../main/services"; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/interval'; import 'rxjs/add/operator/publishReplay'; import 'rxjs/add/operator/mergeMap'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/startWith'; @Component({ selector: 'beamstats-status', templateUrl: 'status.component.html', styleUrls: ['status.component.scss'] }) export class StatusComponent implements OnInit { public status$; constructor(private bstatsApi: BeamStatsApiService) { } ngOnInit() { this.status$ = Observable.interval(20000).startWith(0) .mergeMap(() => this.bstatsApi.getStats()) .do((res: {ingests: any[]}) => res.ingests = res.ingests.sort((a, b) => a['name'].localeCompare(b['name']))) .publishReplay(1) .refCount() } }
Set interval on Status updates
Set interval on Status updates
TypeScript
mit
xCausxn/BeamStats,xCausxn/BeamStats,xCausxn/BeamStats
--- +++ @@ -1,11 +1,14 @@ import { Component, OnInit } from '@angular/core'; import { BeamStatsApiService } from "../main/services"; +import { Observable } from 'rxjs/Observable'; + +import 'rxjs/add/observable/interval'; import 'rxjs/add/operator/publishReplay'; import 'rxjs/add/operator/mergeMap'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; - +import 'rxjs/add/operator/startWith'; @Component({ selector: 'beamstats-status', @@ -19,7 +22,8 @@ } ngOnInit() { - this.status$ = this.bstatsApi.getStats() + this.status$ = Observable.interval(20000).startWith(0) + .mergeMap(() => this.bstatsApi.getStats()) .do((res: {ingests: any[]}) => res.ingests = res.ingests.sort((a, b) => a['name'].localeCompare(b['name']))) .publishReplay(1) .refCount()
ed4cf22f9d95847c173926d7ee7bd1e7e7b9523d
app/src/ui/banners/banner.tsx
app/src/ui/banners/banner.tsx
import * as React from 'react' import { Octicon, OcticonSymbol } from '../octicons' interface IBannerProps { readonly id?: string readonly timeout?: number readonly dismissable?: boolean readonly onDismissed: () => void } export class Banner extends React.Component<IBannerProps, {}> { private timeoutId: NodeJS.Timer | null = null public render() { return ( <div id={this.props.id} className="banner"> <div className="contents">{this.props.children}</div> {this.renderCloseButton()} </div> ) } private renderCloseButton() { const { dismissable } = this.props if (dismissable === undefined || dismissable === false) { return null } return ( <div className="close"> <a onClick={this.props.onDismissed}> <Octicon symbol={OcticonSymbol.x} /> </a> </div> ) } public componentDidMount = () => { if (this.props.timeout !== undefined) { this.timeoutId = setTimeout(() => { this.props.onDismissed() }, this.props.timeout) } } public componentWillUnmount = () => { if (this.props.timeout !== undefined && this.timeoutId !== null) { clearTimeout(this.timeoutId) } } }
import * as React from 'react' import { Octicon, OcticonSymbol } from '../octicons' interface IBannerProps { readonly id?: string readonly timeout?: number readonly dismissable?: boolean readonly onDismissed: () => void } export class Banner extends React.Component<IBannerProps, {}> { private timeoutId: number | null = null public render() { return ( <div id={this.props.id} className="banner"> <div className="contents">{this.props.children}</div> {this.renderCloseButton()} </div> ) } private renderCloseButton() { const { dismissable } = this.props if (dismissable === undefined || dismissable === false) { return null } return ( <div className="close"> <a onClick={this.props.onDismissed}> <Octicon symbol={OcticonSymbol.x} /> </a> </div> ) } public componentDidMount = () => { if (this.props.timeout !== undefined) { this.timeoutId = window.setTimeout(() => { this.props.onDismissed() }, this.props.timeout) } } public componentWillUnmount = () => { if (this.props.timeout !== undefined && this.timeoutId !== null) { window.clearTimeout(this.timeoutId) } } }
Use the Window setTimeout instead of the Node setTimeout
Use the Window setTimeout instead of the Node setTimeout Co-Authored-By: Rafael Oleza <2cf5b502deae2e387c60721eb8244c243cb5c4e1@users.noreply.github.com>
TypeScript
mit
say25/desktop,desktop/desktop,say25/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,say25/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop
--- +++ @@ -9,7 +9,7 @@ } export class Banner extends React.Component<IBannerProps, {}> { - private timeoutId: NodeJS.Timer | null = null + private timeoutId: number | null = null public render() { return ( @@ -37,7 +37,7 @@ public componentDidMount = () => { if (this.props.timeout !== undefined) { - this.timeoutId = setTimeout(() => { + this.timeoutId = window.setTimeout(() => { this.props.onDismissed() }, this.props.timeout) } @@ -45,7 +45,7 @@ public componentWillUnmount = () => { if (this.props.timeout !== undefined && this.timeoutId !== null) { - clearTimeout(this.timeoutId) + window.clearTimeout(this.timeoutId) } } }
65158de44234b0ada4c436847ac2b197f141a27d
mobile/repositories/document-repository.spec.ts
mobile/repositories/document-repository.spec.ts
import { doc } from 'idai-field-core'; import { DocumentRepository } from './document-repository'; import PouchDB = require('pouchdb-node'); describe('DocumentRepository', () => { const project = 'testdb'; let repository: DocumentRepository; beforeEach(async () => { repository = await DocumentRepository.init(project, (name: string) => new PouchDB(name)); }); afterEach(async () => repository.destroy(project)); it('creates document', async () => { const newDoc = await repository.create(doc('Test Document'), 'testuser'); expect(newDoc.resource.shortDescription).toEqual('Test Document'); expect(newDoc.created.user).toEqual('testuser'); expect(newDoc.created.date.getTime()).toBeGreaterThan(Date.now() - 1000); }); });
import { doc } from 'idai-field-core'; import { last } from 'tsfun'; import { DocumentRepository } from './document-repository'; import PouchDB = require('pouchdb-node'); describe('DocumentRepository', () => { const project = 'testdb'; let repository: DocumentRepository; beforeEach(async () => { repository = await DocumentRepository.init(project, (name: string) => new PouchDB(name)); }); afterEach(async () => repository.destroy(project)); it('creates document', async () => { const newDoc = await repository.create(doc('Test Document'), 'testuser'); expect(newDoc.resource.shortDescription).toEqual('Test Document'); expect(newDoc.created.user).toEqual('testuser'); expect(newDoc.created.date.getTime()).toBeGreaterThan(Date.now() - 1000); }); it('fetch document after creation', async () => { const testDoc = await repository.create(doc('Test Document'), 'testuser'); const fetchedDoc = await repository.fetch(testDoc.resource.id); expect(fetchedDoc.resource).toEqual(testDoc.resource); }); it('updates document', async () => { const testDoc = await repository.create(doc('Test Document'), 'testuser1'); testDoc.resource.shortDescription = 'Updated test document'; const updatedDoc = await repository.update(testDoc, 'testuser2'); expect(updatedDoc.resource.shortDescription).toEqual('Updated test document'); expect(last(updatedDoc.modified)?.user).toEqual('testuser2'); expect(last(updatedDoc.modified)?.date.getTime()).toBeGreaterThan(Date.now() - 1000); }); it('removes document', async () => { const testDoc = await repository.create(doc('Test Document'), 'testuser'); await repository.remove(testDoc); return expect(repository.fetch(testDoc.resource.id)).rejects.toBeTruthy(); }); });
Add CRUD tests for DocumentRepository
Add CRUD tests for DocumentRepository
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -1,4 +1,5 @@ import { doc } from 'idai-field-core'; +import { last } from 'tsfun'; import { DocumentRepository } from './document-repository'; import PouchDB = require('pouchdb-node'); @@ -10,6 +11,7 @@ beforeEach(async () => { + repository = await DocumentRepository.init(project, (name: string) => new PouchDB(name)); }); @@ -20,9 +22,40 @@ it('creates document', async () => { const newDoc = await repository.create(doc('Test Document'), 'testuser'); + expect(newDoc.resource.shortDescription).toEqual('Test Document'); expect(newDoc.created.user).toEqual('testuser'); expect(newDoc.created.date.getTime()).toBeGreaterThan(Date.now() - 1000); }); + + it('fetch document after creation', async () => { + + const testDoc = await repository.create(doc('Test Document'), 'testuser'); + const fetchedDoc = await repository.fetch(testDoc.resource.id); + + expect(fetchedDoc.resource).toEqual(testDoc.resource); + }); + + + it('updates document', async () => { + + const testDoc = await repository.create(doc('Test Document'), 'testuser1'); + testDoc.resource.shortDescription = 'Updated test document'; + const updatedDoc = await repository.update(testDoc, 'testuser2'); + + expect(updatedDoc.resource.shortDescription).toEqual('Updated test document'); + expect(last(updatedDoc.modified)?.user).toEqual('testuser2'); + expect(last(updatedDoc.modified)?.date.getTime()).toBeGreaterThan(Date.now() - 1000); + }); + + + it('removes document', async () => { + + const testDoc = await repository.create(doc('Test Document'), 'testuser'); + await repository.remove(testDoc); + + return expect(repository.fetch(testDoc.resource.id)).rejects.toBeTruthy(); + }); + });
77c53b0b3f8dd75e8d42ad3bf26219ef07a8a3f3
web/src/index.tsx
web/src/index.tsx
import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import { App } from "./App"; import reportWebVitals from "./reportWebVitals"; const root = ReactDOM.createRoot( document.getElementById("root") as HTMLElement ); root.render( <React.StrictMode> <App /> </React.StrictMode> ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
import React from "react"; import ReactDOM from "react-dom"; import { App } from "./App"; import "./index.css"; import reportWebVitals from "./reportWebVitals"; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById("root") ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
Revert "refactor(ui): ♻️ use new createRoot"
Revert "refactor(ui): ♻️ use new createRoot" This reverts commit a1f5cfe04fdaaaf88421fdba3619acc27d3183f6.
TypeScript
mit
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
--- +++ @@ -1,16 +1,14 @@ import React from "react"; -import ReactDOM from "react-dom/client"; +import ReactDOM from "react-dom"; +import { App } from "./App"; import "./index.css"; -import { App } from "./App"; import reportWebVitals from "./reportWebVitals"; -const root = ReactDOM.createRoot( - document.getElementById("root") as HTMLElement -); -root.render( +ReactDOM.render( <React.StrictMode> <App /> - </React.StrictMode> + </React.StrictMode>, + document.getElementById("root") ); // If you want to start measuring performance in your app, pass a function
d304e744a7f6257b456caefaed6921beb2584e6a
Signum.React/Scripts/Lines/FormControlReadonly.tsx
Signum.React/Scripts/Lines/FormControlReadonly.tsx
ο»Ώimport * as React from 'react' import { StyleContext, TypeContext } from '../Lines'; import { classes, addClass } from '../Globals'; import "./Lines.css" import { navigatorIsReadOnly } from '../../../../Extensions/Signum.React.Extensions/Authorization/AuthClient'; export interface FormControlReadonlyProps extends React.Props<FormControlReadonly> { ctx: StyleContext; htmlAttributes?: React.HTMLAttributes<any>; className?: string } export class FormControlReadonly extends React.Component<FormControlReadonlyProps> { render() { const ctx = this.props.ctx; var attrs = this.props.htmlAttributes; if (ctx.readonlyAsPlainText) { return ( <p {...attrs} className={classes(ctx.formControlPlainTextClass, attrs && attrs.className, this.props.className)}> {this.props.children} </p> ); } else { return ( <input type="text" style={{ pointerEvents: "none" }} readOnly {...attrs} className={classes(ctx.formControlClass, attrs && attrs.className, this.props.className)} value={React.Children.toArray(this.props.children)[0] as string || ""} /> ); } } }
ο»Ώimport * as React from 'react' import { StyleContext, TypeContext } from '../Lines'; import { classes, addClass } from '../Globals'; import "./Lines.css" export interface FormControlReadonlyProps extends React.Props<FormControlReadonly> { ctx: StyleContext; htmlAttributes?: React.HTMLAttributes<any>; className?: string } export class FormControlReadonly extends React.Component<FormControlReadonlyProps> { render() { const ctx = this.props.ctx; var attrs = this.props.htmlAttributes; if (ctx.readonlyAsPlainText) { return ( <p {...attrs} className={classes(ctx.formControlPlainTextClass, attrs && attrs.className, this.props.className)}> {this.props.children} </p> ); } else { return ( <input type="text" style={{ pointerEvents: "none" }} readOnly {...attrs} className={classes(ctx.formControlClass, attrs && attrs.className, this.props.className)} value={React.Children.toArray(this.props.children)[0] as string || ""} /> ); } } }
Remove not needed import in case of error
Remove not needed import in case of error
TypeScript
mit
signumsoftware/framework,avifatal/framework,avifatal/framework,signumsoftware/framework,AlejandroCano/framework,AlejandroCano/framework
--- +++ @@ -3,7 +3,6 @@ import { classes, addClass } from '../Globals'; import "./Lines.css" -import { navigatorIsReadOnly } from '../../../../Extensions/Signum.React.Extensions/Authorization/AuthClient'; export interface FormControlReadonlyProps extends React.Props<FormControlReadonly> { ctx: StyleContext;
1ae1e5eef475f37a4e315bfa345d141e377d23c1
addons/contexts/src/preview/frameworks/preact.ts
addons/contexts/src/preview/frameworks/preact.ts
import Preact from 'preact'; import { createAddonDecorator, Render } from '../../index'; import { ContextsPreviewAPI } from '../ContextsPreviewAPI'; /** * This is the framework specific bindings for Preact. * '@storybook/preact' expects the returning object from a decorator to be a 'Preact vNode' (vNode). */ export const renderPreact: Render<Preact.VNode> = (contextNodes, propsMap, getStoryVNode) => { const { getRendererFrom } = ContextsPreviewAPI(); return getRendererFrom(Preact.h)(contextNodes, propsMap, getStoryVNode); }; export const withContexts = createAddonDecorator(renderPreact);
import Preact from 'preact'; import { createAddonDecorator, Render } from '../../index'; import { ContextsPreviewAPI } from '../ContextsPreviewAPI'; /** * This is the framework specific bindings for Preact. * '@storybook/preact' expects the returning object from a decorator to be a 'Preact vNode'. */ export const renderPreact: Render<Preact.VNode> = (contextNodes, propsMap, getStoryVNode) => { const { getRendererFrom } = ContextsPreviewAPI(); return getRendererFrom(Preact.h)(contextNodes, propsMap, getStoryVNode); }; export const withContexts = createAddonDecorator(renderPreact);
FIX addon-contexts: correct code comment for Preact integration
FIX addon-contexts: correct code comment for Preact integration
TypeScript
mit
storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,kadirahq/react-storybook
--- +++ @@ -4,7 +4,7 @@ /** * This is the framework specific bindings for Preact. - * '@storybook/preact' expects the returning object from a decorator to be a 'Preact vNode' (vNode). + * '@storybook/preact' expects the returning object from a decorator to be a 'Preact vNode'. */ export const renderPreact: Render<Preact.VNode> = (contextNodes, propsMap, getStoryVNode) => { const { getRendererFrom } = ContextsPreviewAPI();
0f0e28f3f31d467b3e315263f710b6d0d1566710
client/src/configureStore.ts
client/src/configureStore.ts
import { createStore, applyMiddleware } from 'redux'; import 'bootstrap/dist/css/bootstrap.min.css'; import * as _ from 'lodash'; import thunk from 'redux-thunk'; import { createLogger } from 'redux-logger'; import appReducer from './reducers/app'; // import { AppState } from './constants/types'; import { loadState, saveState, setLocalUser } from './localStorage'; import { getToken } from './constants/utils'; import { receiveTokenActionCreator } from './actions/token'; const configureStore = () => { // const persistedState = loadState(); let middleware = [thunk]; let newMiddleware = []; if (process.env.NODE_ENV !== 'production') { setLocalUser(); const loggerMiddleware = createLogger(); newMiddleware = [...middleware, loggerMiddleware]; } else { newMiddleware = middleware; } const store = createStore( appReducer, // persistedState, applyMiddleware(...newMiddleware) ); let token = getToken(); if (token !== null) { store.dispatch(receiveTokenActionCreator(token.user, token)); } store.subscribe(_.throttle(() => { saveState(store.getState()); }, 1000)); return store; }; export default configureStore;
import { createStore, applyMiddleware } from 'redux'; import * as _ from 'lodash'; import thunk from 'redux-thunk'; import { createLogger } from 'redux-logger'; import appReducer from './reducers/app'; // import { AppState } from './constants/types'; import { loadState, saveState, setLocalUser } from './localStorage'; import { getToken } from './constants/utils'; import { receiveTokenActionCreator } from './actions/token'; const configureStore = () => { // const persistedState = loadState(); let middleware = [thunk]; let newMiddleware = []; if (process.env.NODE_ENV !== 'production') { setLocalUser(); const loggerMiddleware = createLogger(); newMiddleware = [...middleware, loggerMiddleware]; } else { newMiddleware = middleware; } const store = createStore( appReducer, // persistedState, applyMiddleware(...newMiddleware) ); let token = getToken(); if (token !== null) { store.dispatch(receiveTokenActionCreator(token.user, token)); } store.subscribe(_.throttle(() => { saveState(store.getState()); }, 1000)); return store; }; export default configureStore;
Remove bootstrap dependency from react store
Remove bootstrap dependency from react store
TypeScript
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
--- +++ @@ -1,5 +1,4 @@ import { createStore, applyMiddleware } from 'redux'; -import 'bootstrap/dist/css/bootstrap.min.css'; import * as _ from 'lodash'; import thunk from 'redux-thunk';
591d00be05a74e23a1182222539aa669be2671e5
src/shared/components/query/filteredSearch/field/ListFormField.tsx
src/shared/components/query/filteredSearch/field/ListFormField.tsx
import { FieldProps } from 'shared/components/query/filteredSearch/field/FilterFormField'; import * as React from 'react'; import { FunctionComponent } from 'react'; import { ISearchClause, Phrase } from 'shared/components/query/SearchClause'; export type ListFilterField = { label: string; input: typeof FilterList; options: string[]; }; export const FilterList: FunctionComponent<FieldProps> = props => { const form = props.filter.form as ListFilterField; return ( <div className="filter-list"> <span>{form.label}</span> <ul> {form.options.map(option => { const update = props.parser.parseSearchQuery(option); const queryPhrases = toUniquePhrases(props.query); return ( <li className="menu-item"> <a tabIndex={-1} onClick={() => props.onChange({ toAdd: update, toRemove: queryPhrases, }) } > {option} </a> </li> ); })} </ul> </div> ); }; function toUniquePhrases(query: ISearchClause[]): Phrase[] { return query.reduce<Phrase[]>((accumulator, clause) => { accumulator.push(...clause.getPhrases()); return [...new Set(accumulator)]; }, []); }
import { FieldProps } from 'shared/components/query/filteredSearch/field/FilterFormField'; import * as React from 'react'; import { FunctionComponent } from 'react'; import { ISearchClause, Phrase } from 'shared/components/query/SearchClause'; export type ListFilterField = { label: string; input: typeof FilterList; options: string[]; }; export const FilterList: FunctionComponent<FieldProps> = props => { const form = props.filter.form as ListFilterField; return ( <div className="filter-list"> <span>{form.label}</span> {form.options.map(option => { const update = props.parser.parseSearchQuery(option); const queryPhrases = toUniquePhrases(props.query); return ( <li className="dropdown-item"> <a style={{ display: 'block', padding: '5px', }} tabIndex={-1} onClick={() => props.onChange({ toAdd: update, toRemove: queryPhrases, }) } > {option} </a> </li> ); })} </div> ); }; function toUniquePhrases(query: ISearchClause[]): Phrase[] { return query.reduce<Phrase[]>((accumulator, clause) => { accumulator.push(...clause.getPhrases()); return [...new Set(accumulator)]; }, []); }
Make list of example queries readable
Make list of example queries readable
TypeScript
agpl-3.0
cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend
--- +++ @@ -15,27 +15,29 @@ return ( <div className="filter-list"> <span>{form.label}</span> - <ul> - {form.options.map(option => { - const update = props.parser.parseSearchQuery(option); - const queryPhrases = toUniquePhrases(props.query); - return ( - <li className="menu-item"> - <a - tabIndex={-1} - onClick={() => - props.onChange({ - toAdd: update, - toRemove: queryPhrases, - }) - } - > - {option} - </a> - </li> - ); - })} - </ul> + {form.options.map(option => { + const update = props.parser.parseSearchQuery(option); + const queryPhrases = toUniquePhrases(props.query); + return ( + <li className="dropdown-item"> + <a + style={{ + display: 'block', + padding: '5px', + }} + tabIndex={-1} + onClick={() => + props.onChange({ + toAdd: update, + toRemove: queryPhrases, + }) + } + > + {option} + </a> + </li> + ); + })} </div> ); };
ecce86fc733e7770bed01dfc31937a1da720d43c
packages/react-day-picker/src/components/Day/Day.tsx
packages/react-day-picker/src/components/Day/Day.tsx
import * as React from 'react'; import { DayProps } from 'types'; import { defaultProps } from '../DayPicker/defaultProps'; import { getDayComponent } from './getDayComponent'; export function Day(props: DayProps): JSX.Element { const { day, dayPickerProps, currentMonth } = props; const locale = dayPickerProps.locale ?? defaultProps.locale; const formatDay = dayPickerProps.formatDay ?? defaultProps.formatDay; const { containerProps, wrapperProps } = getDayComponent( day, currentMonth, dayPickerProps ); return ( <span {...containerProps}> <time {...wrapperProps}>{formatDay(day, { locale })}</time> </span> ); }
import * as React from 'react'; import { DayProps } from 'types'; import { defaultProps } from '../DayPicker/defaultProps'; import { getDayComponent } from './getDayComponent'; export function Day(props: DayProps): JSX.Element { const { day, dayPickerProps, currentMonth } = props; const locale = dayPickerProps.locale ?? defaultProps.locale; const formatDay = dayPickerProps.formatDay ?? defaultProps.formatDay; const { containerProps, wrapperProps, modifiers } = getDayComponent( day, currentMonth, dayPickerProps ); if (modifiers.hidden) { return <span />; } return ( <span {...containerProps}> <time {...wrapperProps}>{formatDay(day, { locale })}</time> </span> ); }
Fix outside day not hidden when required
Fix outside day not hidden when required
TypeScript
mit
gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker
--- +++ @@ -9,11 +9,15 @@ const locale = dayPickerProps.locale ?? defaultProps.locale; const formatDay = dayPickerProps.formatDay ?? defaultProps.formatDay; - const { containerProps, wrapperProps } = getDayComponent( + const { containerProps, wrapperProps, modifiers } = getDayComponent( day, currentMonth, dayPickerProps ); + + if (modifiers.hidden) { + return <span />; + } return ( <span {...containerProps}>
eab88023a996836793461fa3b03951c3876f05d0
trainer/src/services/workout-builder-service.ts
trainer/src/services/workout-builder-service.ts
import {Injectable} from 'angular2/core'; import {WorkoutPlan, Exercise} from './model'; import {WorkoutService} from "./workout-service"; import {ExercisePlan} from "./model"; @Injectable() export class WorkoutBuilderService { buildingWorkout: WorkoutPlan; newWorkout: boolean; firstExercise: boolean = true; constructor(private _workoutService:WorkoutService){} startBuilding(name: string){ if(name){ this.buildingWorkout = this._workoutService.getWorkout(name) this.newWorkout = false; }else{ this.buildingWorkout = new WorkoutPlan("", "", 30, []); this.newWorkout = true; } return this.buildingWorkout; } removeExercise(exercise: ExercisePlan){ var currentIndex = this.buildingWorkout.exercises.map(function(e) { return e.exercise.name; }).indexOf(exercise.exercise.name); this.buildingWorkout.exercises.splice(currentIndex, 1) } addExercise(exercisePlan: ExercisePlan){ if(this.newWorkout && this.firstExercise){ this.buildingWorkout.exercises.splice(0, 1); this.firstExercise = false; } this.buildingWorkout.exercises.push(exercisePlan); } moveExerciseTo(exercise: ExercisePlan, toIndex: number ){ if (toIndex < 0 || toIndex >= this.buildingWorkout.exercises) return; var currentIndex = this.buildingWorkout.exercises.indexOf(exercise); this.buildingWorkout.exercises.splice(toIndex, 0, this.buildingWorkout.exercises.splice(currentIndex, 1)[0]); } }
import {Injectable} from 'angular2/core'; import {WorkoutPlan, Exercise} from './model'; import {WorkoutService} from "./workout-service"; import {ExercisePlan} from "./model"; @Injectable() export class WorkoutBuilderService { buildingWorkout: WorkoutPlan; newWorkout: boolean; constructor(private _workoutService:WorkoutService){} startBuilding(name: string){ if(name){ this.buildingWorkout = this._workoutService.getWorkout(name) this.newWorkout = false; }else{ let exerciseArray : ExercisePlan[] = []; this.buildingWorkout = new WorkoutPlan("", "", 30, exerciseArray); this.newWorkout = true; } return this.buildingWorkout; } removeExercise(exercise: ExercisePlan){ var currentIndex = this.buildingWorkout.exercises.map(function(e) { return e.exercise.name; }).indexOf(exercise.exercise.name); this.buildingWorkout.exercises.splice(currentIndex, 1) } addExercise(exercisePlan: ExercisePlan){ this.buildingWorkout.exercises.push(exercisePlan); } moveExerciseTo(exercise: ExercisePlan, toIndex: number ){ if (toIndex < 0 || toIndex >= this.buildingWorkout.exercises) return; var currentIndex = this.buildingWorkout.exercises.indexOf(exercise); this.buildingWorkout.exercises.splice(toIndex, 0, this.buildingWorkout.exercises.splice(currentIndex, 1)[0]); } }
Fix for empty array when creating new Workout
Fix for empty array when creating new Workout
TypeScript
mit
chandermani/angular2byexample,chandermani/angular2byexample,chandermani/angular2byexample
--- +++ @@ -7,7 +7,6 @@ export class WorkoutBuilderService { buildingWorkout: WorkoutPlan; newWorkout: boolean; - firstExercise: boolean = true; constructor(private _workoutService:WorkoutService){} @@ -16,7 +15,8 @@ this.buildingWorkout = this._workoutService.getWorkout(name) this.newWorkout = false; }else{ - this.buildingWorkout = new WorkoutPlan("", "", 30, []); + let exerciseArray : ExercisePlan[] = []; + this.buildingWorkout = new WorkoutPlan("", "", 30, exerciseArray); this.newWorkout = true; } return this.buildingWorkout; @@ -28,10 +28,6 @@ } addExercise(exercisePlan: ExercisePlan){ - if(this.newWorkout && this.firstExercise){ - this.buildingWorkout.exercises.splice(0, 1); - this.firstExercise = false; - } this.buildingWorkout.exercises.push(exercisePlan); }
55d595c22f0195cee2519dfcc07b28f1e2307ad7
src/resource/ResourcesService.ts
src/resource/ResourcesService.ts
import { get } from '@waldur/core/api'; import { ngInjector } from '@waldur/core/services'; class ResourcesServiceClass { private services; get(resource_type, uuid) { return ngInjector.get('$q').when(this.getInternal(resource_type, uuid)); } async getInternal(resource_type, uuid) { const url = await this.getUrlByType(resource_type); const response = await get(url + uuid); return response.data; } async getUrlByType(resource_type) { if (resource_type === 'JIRA.Issue') { return `/jira-issues/`; } else if (resource_type === 'Support.Offering') { return `/support-offerings/`; } else if (resource_type === 'Rancher.Node') { return `/rancher-nodes/`; } const parts = resource_type.split('.'); const service_type = parts[0]; const type = parts[1]; const services = await this.getServicesList(); const urlParts = services[service_type].resources[type].split('/'); return `/${urlParts[urlParts.length - 2]}/`; } async getServicesList() { if (!this.services) { const response = await get('/service-metadata/'); this.services = response.data; } return this.services; } } export const ResourcesService = new ResourcesServiceClass();
import { get } from '@waldur/core/api'; import { ngInjector } from '@waldur/core/services'; class ResourcesServiceClass { private services; get(resource_type, uuid) { return ngInjector.get('$q').when(this.getInternal(resource_type, uuid)); } async getInternal(resource_type, uuid) { const url = await this.getUrlByType(resource_type); const response = await get(url + uuid + '/'); return response.data; } async getUrlByType(resource_type) { if (resource_type === 'JIRA.Issue') { return `/jira-issues/`; } else if (resource_type === 'Support.Offering') { return `/support-offerings/`; } else if (resource_type === 'Rancher.Node') { return `/rancher-nodes/`; } const parts = resource_type.split('.'); const service_type = parts[0]; const type = parts[1]; const services = await this.getServicesList(); const urlParts = services[service_type].resources[type].split('/'); return `/${urlParts[urlParts.length - 2]}/`; } async getServicesList() { if (!this.services) { const response = await get('/service-metadata/'); this.services = response.data; } return this.services; } } export const ResourcesService = new ResourcesServiceClass();
Add trailing slash to resource URL to avoid redirect.
Add trailing slash to resource URL to avoid redirect.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -10,7 +10,7 @@ async getInternal(resource_type, uuid) { const url = await this.getUrlByType(resource_type); - const response = await get(url + uuid); + const response = await get(url + uuid + '/'); return response.data; }
4737553ba2e78140651378860b3145eaee7d73a0
packages/components/hooks/useWelcomeFlags.ts
packages/components/hooks/useWelcomeFlags.ts
import { useCallback, useState } from 'react'; import { UserSettingsModel } from 'proton-shared/lib/models'; import useCache from './useCache'; export const WELCOME_FLAG_KEY = 'flow'; export interface WelcomeFlagsState { hasDisplayNameStep?: boolean; isWelcomeFlow?: boolean; isWelcomeFlag?: boolean; } const useWelcomeFlags = (): [WelcomeFlagsState, () => void] => { const cache = useCache(); const [state, setState] = useState<WelcomeFlagsState>(() => { // Set from ProtonApp const flow = cache.get(WELCOME_FLAG_KEY); const hasDisplayNameStep = true; // flow === 'signup' || flow === 'welcome-full'; const hasWelcomeModal = flow === 'welcome'; // Assumes that user settings has been pre-loaded. Not using hook to avoid re-renders. const isWelcomeFlag = cache.get(UserSettingsModel.key)?.value?.WelcomeFlag === 0 || hasWelcomeModal; return { hasDisplayNameStep, isWelcomeFlag, isWelcomeFlow: hasDisplayNameStep || isWelcomeFlag, }; }); const setDone = useCallback(() => { cache.delete(WELCOME_FLAG_KEY); setState({}); }, []); return [state, setDone]; }; export default useWelcomeFlags;
import { useCallback, useState } from 'react'; import { UserSettingsModel } from 'proton-shared/lib/models'; import useCache from './useCache'; export const WELCOME_FLAG_KEY = 'flow'; export interface WelcomeFlagsState { hasDisplayNameStep?: boolean; isWelcomeFlow?: boolean; isWelcomeFlag?: boolean; } const useWelcomeFlags = (): [WelcomeFlagsState, () => void] => { const cache = useCache(); const [state, setState] = useState<WelcomeFlagsState>(() => { // Set from ProtonApp const flow = cache.get(WELCOME_FLAG_KEY); const hasDisplayNameStep = flow === 'signup' || flow === 'welcome-full'; const hasWelcomeModal = flow === 'welcome'; // Assumes that user settings has been pre-loaded. Not using hook to avoid re-renders. const isWelcomeFlag = cache.get(UserSettingsModel.key)?.value?.WelcomeFlag === 0 || hasWelcomeModal; return { hasDisplayNameStep, isWelcomeFlag, isWelcomeFlow: hasDisplayNameStep || isWelcomeFlag, }; }); const setDone = useCallback(() => { cache.delete(WELCOME_FLAG_KEY); setState({}); }, []); return [state, setDone]; }; export default useWelcomeFlags;
Remove the hardcoded 'true' development hack again :)
Remove the hardcoded 'true' development hack again :)
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -15,7 +15,7 @@ const [state, setState] = useState<WelcomeFlagsState>(() => { // Set from ProtonApp const flow = cache.get(WELCOME_FLAG_KEY); - const hasDisplayNameStep = true; // flow === 'signup' || flow === 'welcome-full'; + const hasDisplayNameStep = flow === 'signup' || flow === 'welcome-full'; const hasWelcomeModal = flow === 'welcome'; // Assumes that user settings has been pre-loaded. Not using hook to avoid re-renders. const isWelcomeFlag = cache.get(UserSettingsModel.key)?.value?.WelcomeFlag === 0 || hasWelcomeModal;
a247a4bc9eb31fd45182afe9f966e54bbe58f7e9
demo/src/app/components/dialog/dialogdemo.module.ts
demo/src/app/components/dialog/dialogdemo.module.ts
import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { NgModule } from "@angular/core"; import { HighlightJsModule } from 'ngx-highlight-js'; import { InputModule } from 'truly-ui/input'; import { ButtonModule } from 'truly-ui/button'; import { DatatableModule } from 'truly-ui/datatable'; import { DialogDemo } from "./dialogdemo.component"; import { DialogDemoRoutingModule } from "./dialogdemo-routing.module"; @NgModule({ declarations: [ DialogDemo, ], imports:[ ButtonModule, CommonModule, DatatableModule, DialogDemoRoutingModule, FormsModule, HighlightJsModule, InputModule, ], exports: [ DialogDemo, ], }) export class DialogDemoModule { }
import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { NgModule } from "@angular/core"; import { HighlightJsModule } from 'ngx-highlight-js'; import { InputModule } from 'truly-ui/input'; import { ButtonModule } from 'truly-ui/button'; import { DatatableModule } from 'truly-ui/datatable'; import { DialogDemo } from "./dialogdemo.component"; import { DialogDemoRoutingModule } from "./dialogdemo-routing.module"; import { DialogModule } from "../../../../../src/dialog/index"; @NgModule({ declarations: [ DialogDemo, ], imports:[ ButtonModule, CommonModule, DatatableModule, DialogDemoRoutingModule, FormsModule, HighlightJsModule, InputModule, DialogModule ], exports: [ DialogDemo, ], }) export class DialogDemoModule { }
Add DialogModule import to dialogdemo page
docs(showcase): Add DialogModule import to dialogdemo page
TypeScript
mit
TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui
--- +++ @@ -9,6 +9,7 @@ import { DialogDemo } from "./dialogdemo.component"; import { DialogDemoRoutingModule } from "./dialogdemo-routing.module"; +import { DialogModule } from "../../../../../src/dialog/index"; @NgModule({ declarations: [ @@ -22,6 +23,7 @@ FormsModule, HighlightJsModule, InputModule, + DialogModule ], exports: [ DialogDemo,
5d803180343d9a763f2b939099eea615876f5a8e
resources/assets/lib/user-group-badge.tsx
resources/assets/lib/user-group-badge.tsx
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import GroupJson from 'interfaces/group-json'; import * as React from 'react'; interface Props { group?: GroupJson; modifiers?: string[]; } export default function UserGroupBadge({group, modifiers = []}: Props) { if (group == null) { return null; } const style = osu.groupColour(group); if (group.is_probationary) { modifiers.push('probationary'); } const playModes: JSX.Element[] = (group.playmodes ?? []).map((mode) => <i className={`fal fa-extra-mode-${mode}`} key={mode} />); return ( <div className={osu.classWithModifiers('user-group-badge', modifiers)} data-label={group.short_name} style={style} title={group.name} > {playModes.length > 0 && <div className={'user-group-badge__modes'}> {playModes} </div> } </div> ); }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import GroupJson from 'interfaces/group-json'; import * as React from 'react'; interface Props { group?: GroupJson; modifiers?: string[]; } export default function UserGroupBadge({group, modifiers = []}: Props) { if (group == null) { return null; } const style = osu.groupColour(group); const badgeModifiers = [...modifiers]; if (group.is_probationary) { badgeModifiers.push('probationary'); } const playModes: JSX.Element[] = (group.playmodes ?? []).map((mode) => <i className={`fal fa-extra-mode-${mode}`} key={mode} />); return ( <div className={osu.classWithModifiers('user-group-badge', badgeModifiers)} data-label={group.short_name} style={style} title={group.name} > {playModes.length > 0 && <div className={'user-group-badge__modes'}> {playModes} </div> } </div> ); }
Fix modifier leakage on user group badges
Fix modifier leakage on user group badges
TypeScript
agpl-3.0
ppy/osu-web,omkelderman/osu-web,notbakaneko/osu-web,nanaya/osu-web,notbakaneko/osu-web,nanaya/osu-web,ppy/osu-web,nanaya/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,nanaya/osu-web,ppy/osu-web,nanaya/osu-web,LiquidPL/osu-web,LiquidPL/osu-web,ppy/osu-web,omkelderman/osu-web,omkelderman/osu-web,omkelderman/osu-web,LiquidPL/osu-web,ppy/osu-web,LiquidPL/osu-web
--- +++ @@ -16,15 +16,16 @@ const style = osu.groupColour(group); + const badgeModifiers = [...modifiers]; if (group.is_probationary) { - modifiers.push('probationary'); + badgeModifiers.push('probationary'); } const playModes: JSX.Element[] = (group.playmodes ?? []).map((mode) => <i className={`fal fa-extra-mode-${mode}`} key={mode} />); return ( <div - className={osu.classWithModifiers('user-group-badge', modifiers)} + className={osu.classWithModifiers('user-group-badge', badgeModifiers)} data-label={group.short_name} style={style} title={group.name}
c16bd20f2e66c2181b63b27b28d38e818a487102
src/app/components/post-components/post-photo/post-photo.component.ts
src/app/components/post-components/post-photo/post-photo.component.ts
import { Component, Input } from '@angular/core'; import { Photo } from '../../../data.types'; import { FullscreenService } from '../../../shared/fullscreen.service'; @Component({ selector: 'post-photo', template: ` <img switch-target *ngFor="let photo of postPhotos" (click)="fullScreen($event)" src="{{photo.original_size.url}}" sizes="(min-width: 64em) 34vw, (min-width: 48em) 73vw, 95vw" [srcset]="createSrcSet(photo)" [tumblrImage]="photo"> `, styleUrls: ['./post-photo.component.scss'] }) export class PostPhotoComponent { @Input('postPhotos') postPhotos: Photo[]; constructor(private fullscreenService: FullscreenService) { } createSrcSet(photo: Photo): string { if (photo.alt_sizes.length === 0) { return photo.original_size.url; } let srcset = ''; photo.alt_sizes.forEach(picture => { srcset += picture.url + ' ' + picture.width + 'w, '; }); return srcset.substring(0, srcset.lastIndexOf(', ')); } fullScreen(event: any) { const elem = event.currentTarget; this.fullscreenService.requestFullscreen(elem); } }
import { Component, Input } from '@angular/core'; import { Photo } from '../../../data.types'; import { FullscreenService } from '../../../shared/fullscreen.service'; @Component({ selector: 'post-photo', template: ` <img switch-target *ngFor="let photo of postPhotos" (click)="fullScreen($event)" src="{{photo.original_size.url}}" sizes="(min-width: 100em) 26vw, (min-width: 64em) 34vw, (min-width: 48em) 73vw, 95vw" [srcset]="createSrcSet(photo)" [tumblrImage]="photo"> `, styleUrls: ['./post-photo.component.scss'] }) export class PostPhotoComponent { @Input('postPhotos') postPhotos: Photo[]; constructor(private fullscreenService: FullscreenService) { } createSrcSet(photo: Photo): string { if (photo.alt_sizes.length === 0) { return photo.original_size.url; } let srcset = ''; photo.alt_sizes.forEach(picture => { srcset += picture.url + ' ' + picture.width + 'w, '; }); return srcset.substring(0, srcset.lastIndexOf(', ')); } fullScreen(event: any) { const elem = event.currentTarget; this.fullscreenService.requestFullscreen(elem); } }
Improve image handling on 1080p screens
Improve image handling on 1080p screens
TypeScript
mit
zoehneto/tumblr-reader,zoehneto/tumblr-reader,zoehneto/tumblr-reader
--- +++ @@ -6,7 +6,7 @@ selector: 'post-photo', template: ` <img switch-target *ngFor="let photo of postPhotos" (click)="fullScreen($event)" - src="{{photo.original_size.url}}" sizes="(min-width: 64em) 34vw, + src="{{photo.original_size.url}}" sizes="(min-width: 100em) 26vw, (min-width: 64em) 34vw, (min-width: 48em) 73vw, 95vw" [srcset]="createSrcSet(photo)" [tumblrImage]="photo"> `,
809e34b0f4092909e5eaf998c9ade851b9fb96a4
ts/backbone/Conversation.ts
ts/backbone/Conversation.ts
/** * @prettier */ import is from '@sindresorhus/is'; import { Collection as BackboneCollection } from '../types/backbone/Collection'; import { deferredToPromise } from '../../js/modules/deferred_to_promise'; import { Message } from '../types/Message'; export const fetchVisualMediaAttachments = async ({ conversationId, WhisperMessageCollection, }: { conversationId: string; WhisperMessageCollection: BackboneCollection<Message>; }): Promise<Array<Message>> => { if (!is.string(conversationId)) { throw new TypeError("'conversationId' is required"); } if (!is.object(WhisperMessageCollection)) { throw new TypeError("'WhisperMessageCollection' is required"); } const collection = new WhisperMessageCollection(); const lowerReceivedAt = 0; const upperReceivedAt = Number.MAX_VALUE; const hasVisualMediaAttachments = 1; await deferredToPromise( collection.fetch({ index: { // 'hasVisualMediaAttachments' index on // [conversationId, hasVisualMediaAttachments, received_at] name: 'hasVisualMediaAttachments', lower: [conversationId, hasVisualMediaAttachments, lowerReceivedAt], upper: [conversationId, hasVisualMediaAttachments, upperReceivedAt], order: 'desc', }, limit: 10, }) ); return collection.models.map(model => model.toJSON()); };
/** * @prettier */ import is from '@sindresorhus/is'; import { Collection as BackboneCollection } from '../types/backbone/Collection'; import { deferredToPromise } from '../../js/modules/deferred_to_promise'; import { Message } from '../types/Message'; export const fetchVisualMediaAttachments = async ({ conversationId, WhisperMessageCollection, }: { conversationId: string; WhisperMessageCollection: BackboneCollection<Message>; }): Promise<Array<Message>> => { if (!is.string(conversationId)) { throw new TypeError("'conversationId' is required"); } if (!is.object(WhisperMessageCollection)) { throw new TypeError("'WhisperMessageCollection' is required"); } const collection = new WhisperMessageCollection(); const lowerReceivedAt = 0; const upperReceivedAt = Number.MAX_VALUE; const hasVisualMediaAttachments = 1; await deferredToPromise( collection.fetch({ index: { name: 'hasVisualMediaAttachments', lower: [conversationId, hasVisualMediaAttachments, lowerReceivedAt], upper: [conversationId, hasVisualMediaAttachments, upperReceivedAt], order: 'desc', }, limit: 50, }) ); return collection.models.map(model => model.toJSON()); };
Load 50 attachments for media gallery
Load 50 attachments for media gallery
TypeScript
agpl-3.0
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
--- +++ @@ -29,14 +29,12 @@ await deferredToPromise( collection.fetch({ index: { - // 'hasVisualMediaAttachments' index on - // [conversationId, hasVisualMediaAttachments, received_at] name: 'hasVisualMediaAttachments', lower: [conversationId, hasVisualMediaAttachments, lowerReceivedAt], upper: [conversationId, hasVisualMediaAttachments, upperReceivedAt], order: 'desc', }, - limit: 10, + limit: 50, }) );
18a50b2502bebb14e361da167d28ca53dc1f2202
app/src/lib/is-application-bundle.ts
app/src/lib/is-application-bundle.ts
import getFileMetadata from 'file-metadata' /** * Attempts to determine if the provided path is an application bundle or not. * * macOS differs from the other platforms we support in that a directory can * also be an application and therefore executable making it unsafe to open * directories on macOS as we could conceivably end up launching an application. * * This application uses file metadata (the `mdls` tool to be exact) to * determine whether a path is actually an application bundle or otherwise * executable. * * NOTE: This method will always return false when not running on macOS. */ export async function isApplicationBundle(path: string): Promise<boolean> { if (!__DARWIN__) { return false } const metadata = await getFileMetadata(path) if (metadata['contentType'] === 'com.apple.application-bundle') { return true } const contentTypeTree = metadata['contentTypeTree'] if (Array.isArray(contentTypeTree)) { for (const contentType of contentTypeTree) { switch (contentType) { case 'com.apple.application-bundle': case 'com.apple.application': case 'public.executable': return true } } } return false }
import getFileMetadata from 'file-metadata' /** * Attempts to determine if the provided path is an application bundle or not. * * macOS differs from the other platforms we support in that a directory can * also be an application and therefore executable making it unsafe to open * directories on macOS as we could conceivably end up launching an application. * * This application uses file metadata (the `mdls` tool to be exact) to * determine whether a path is actually an application bundle or otherwise * executable. * * NOTE: This method will always return false when not running on macOS. */ export async function isApplicationBundle(path: string): Promise<boolean> { if (process.platform !== 'darwin') { return false } const metadata = await getFileMetadata(path) if (metadata['contentType'] === 'com.apple.application-bundle') { return true } const contentTypeTree = metadata['contentTypeTree'] if (Array.isArray(contentTypeTree)) { for (const contentType of contentTypeTree) { switch (contentType) { case 'com.apple.application-bundle': case 'com.apple.application': case 'public.executable': return true } } } return false }
Make this method not be specific to desktop
Make this method not be specific to desktop
TypeScript
mit
desktop/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,kactus-io/kactus,artivilla/desktop,say25/desktop,say25/desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,say25/desktop,desktop/desktop
--- +++ @@ -14,7 +14,7 @@ * NOTE: This method will always return false when not running on macOS. */ export async function isApplicationBundle(path: string): Promise<boolean> { - if (!__DARWIN__) { + if (process.platform !== 'darwin') { return false }
64af8a3ec212cf1b756a753d3b42cb81c3ea2d94
app/scripts/modules/core/src/search/infrastructure/infrastructure.states.ts
app/scripts/modules/core/src/search/infrastructure/infrastructure.states.ts
import { module } from 'angular'; import { STATE_CONFIG_PROVIDER, StateConfigProvider } from 'core/navigation/state.provider'; import { SETTINGS } from 'core/config/settings'; export const INFRASTRUCTURE_STATES = 'spinnaker.core.search.states'; module(INFRASTRUCTURE_STATES, [ STATE_CONFIG_PROVIDER ]).config((stateConfigProvider: StateConfigProvider) => { 'ngInject'; stateConfigProvider.addToRootState({ name: 'search', url: '/search?q', reloadOnSearch: false, views: { 'main@': { template: ` <infrastructure-search-v1 ng-if="$resolve.version == 1" class="flex-fill"></infrastructure-search-v1> <infrastructure-search-v2 ng-if="$resolve.version == 2" class="flex-fill"></infrastructure-search-v2> `, } }, data: { pageTitleMain: { label: 'Search' } }, resolve: { version: () => SETTINGS.searchVersion || 1, } }); stateConfigProvider.addToRootState({ name: 'infrastructure', url: '/search?q', redirectTo: 'search' }); stateConfigProvider.addRewriteRule('/infrastructure?q', '/search?q'); stateConfigProvider.addRewriteRule('', '/search'); stateConfigProvider.addRewriteRule('/', '/search'); });
import { module } from 'angular'; import { STATE_CONFIG_PROVIDER, StateConfigProvider } from 'core/navigation/state.provider'; import { SETTINGS } from 'core/config/settings'; export const INFRASTRUCTURE_STATES = 'spinnaker.core.search.states'; module(INFRASTRUCTURE_STATES, [ STATE_CONFIG_PROVIDER ]).config((stateConfigProvider: StateConfigProvider) => { 'ngInject'; stateConfigProvider.addToRootState({ name: 'search', url: '/search?q', reloadOnSearch: false, views: { 'main@': { template: ` <infrastructure-search-v1 ng-if="$resolve.version == 1" class="flex-fill"></infrastructure-search-v1> <infrastructure-search-v2 ng-if="$resolve.version == 2" class="flex-fill"></infrastructure-search-v2> `, } }, data: { pageTitleMain: { label: 'Search' } }, resolve: { version: () => SETTINGS.searchVersion || 1, } }); stateConfigProvider.addToRootState({ name: 'infrastructure', url: '/search?q', redirectTo: 'home.search' }); stateConfigProvider.addRewriteRule('/infrastructure?q', '/search?q'); stateConfigProvider.addRewriteRule('', '/search'); stateConfigProvider.addRewriteRule('/', '/search'); });
Fix redirect from 'home.infrastructure' to 'home.search'
fix(core/search): Fix redirect from 'home.infrastructure' to 'home.search'
TypeScript
apache-2.0
spinnaker/deck,duftler/deck,ajordens/deck,ajordens/deck,sgarlick987/deck,duftler/deck,sgarlick987/deck,sgarlick987/deck,duftler/deck,duftler/deck,icfantv/deck,spinnaker/deck,ajordens/deck,icfantv/deck,sgarlick987/deck,icfantv/deck,spinnaker/deck,ajordens/deck,icfantv/deck,spinnaker/deck
--- +++ @@ -31,7 +31,7 @@ } }); - stateConfigProvider.addToRootState({ name: 'infrastructure', url: '/search?q', redirectTo: 'search' }); + stateConfigProvider.addToRootState({ name: 'infrastructure', url: '/search?q', redirectTo: 'home.search' }); stateConfigProvider.addRewriteRule('/infrastructure?q', '/search?q'); stateConfigProvider.addRewriteRule('', '/search'); stateConfigProvider.addRewriteRule('/', '/search');
b0759c2f0ab623df616905545297a14f87ced240
src/app/shared/security/auth.service.ts
src/app/shared/security/auth.service.ts
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Observable, Subject, BehaviorSubject } from 'rxjs/Rx'; import { FirebaseAuth, FirebaseAuthState } from 'angularfire2'; @Injectable() export class AuthService { auth$: BehaviorSubject<FirebaseAuthState> = new BehaviorSubject(null); constructor (private auth: FirebaseAuth, private router: Router) { this.auth.subscribe( data => { this.auth$.next(data); }, err => { this.auth$.error(err); } ); } login(email: string, password: string): Observable<FirebaseAuthState> { return this.fromFirebaseAuthPromise(this.auth.login({ email, password })); } register(email: string, password: string): Observable<FirebaseAuthState> { return this.fromFirebaseAuthPromise(this.auth.createUser({ email, password })); } fromFirebaseAuthPromise(promise): Observable<any> { const subject = new Subject<any>(); promise .then(res => { subject.next(res); subject.complete(); }) .catch(err => { subject.error(err); subject.complete(); }); return subject.asObservable(); } logout() { this.auth.logout(); this.router.navigate(['/home']); } }
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Observable, Subject, BehaviorSubject } from 'rxjs/Rx'; import { FirebaseAuth, FirebaseAuthState } from 'angularfire2'; @Injectable() export class AuthService { auth$: BehaviorSubject<FirebaseAuthState> = new BehaviorSubject(undefined); constructor (private auth: FirebaseAuth, private router: Router) { this.auth.subscribe( data => { this.auth$.next(data); }, err => { this.auth$.error(err); } ); } login(email: string, password: string): Observable<FirebaseAuthState> { return this.fromFirebaseAuthPromise(this.auth.login({ email, password })); } register(email: string, password: string): Observable<FirebaseAuthState> { return this.fromFirebaseAuthPromise(this.auth.createUser({ email, password })); } fromFirebaseAuthPromise(promise): Observable<any> { const subject = new Subject<any>(); promise .then(res => { subject.next(res); subject.complete(); }) .catch(err => { subject.error(err); subject.complete(); }); return subject.asObservable(); } logout() { this.auth.logout(); this.router.navigate(['/home']); } }
Change initial value of `auth$` behavior subject
Change initial value of `auth$` behavior subject That way we can tell if Firebase is still fetching the auth state of the user
TypeScript
mit
michaelgira23/Pear-Tutoring,michaelgira23/Pear-Tutoring,michaelgira23/Pear-Tutoring
--- +++ @@ -6,7 +6,7 @@ @Injectable() export class AuthService { - auth$: BehaviorSubject<FirebaseAuthState> = new BehaviorSubject(null); + auth$: BehaviorSubject<FirebaseAuthState> = new BehaviorSubject(undefined); constructor (private auth: FirebaseAuth, private router: Router) { this.auth.subscribe(
2c49c837d0d2109b29efe3ae3b3dff5f569a1065
src/components/subjectsList/subjectsList.component.ts
src/components/subjectsList/subjectsList.component.ts
import { Component, OnInit } from '@angular/core'; import { Subject } from '../../models/subject'; import { SubjectService } from '../../services/subject.service'; @Component({ templateUrl: './subjectsList.component.html', styleUrls: ['./subjectsList.component.scss'] }) export class SubjectsListComponent implements OnInit { subjects: Subject[] = []; constructor(private subjectService: SubjectService) { } ngOnInit() { this.subjectService.getAll().then(subjects => { this.subjects = subjects; }); } delete(subjectId: string) { return this.subjectService.remove(subjectId) .then(() => { this.subjects = this.subjects.filter(subject => subject._id !== subjectId); }); } }
import { Component, OnInit } from '@angular/core'; import { Subject } from '../../models/subject'; import { SubjectService } from '../../services/subject.service'; import { MdSnackBar } from '@angular/material'; @Component({ templateUrl: './subjectsList.component.html', styleUrls: ['./subjectsList.component.scss'] }) export class SubjectsListComponent implements OnInit { subjects: Subject[] = []; constructor( private subjectService: SubjectService, public snackBar: MdSnackBar ) { } ngOnInit() { this.subjectService.getAll().then(subjects => { this.subjects = subjects; }); } delete(subjectId: string) { return this.subjectService.remove(subjectId) .then(() => { this.subjects = this.subjects.filter(subject => subject._id !== subjectId); this.snackBar.open('ΠŸΡ€Π΅Π΄ΠΌΠ΅Ρ‚ Π²ΠΈΠ΄Π°Π»Π΅Π½ΠΎ!', '', { duration: 3000, }); }); } }
Add snackbar after subject deleting
Add snackbar after subject deleting
TypeScript
mit
ivanna-ostrovets/language-and-literature-admin,ivanna-ostrovets/language-and-literature-admin,ivanna-ostrovets/language-and-literature-admin
--- +++ @@ -3,6 +3,8 @@ import { Subject } from '../../models/subject'; import { SubjectService } from '../../services/subject.service'; + +import { MdSnackBar } from '@angular/material'; @Component({ templateUrl: './subjectsList.component.html', @@ -11,7 +13,10 @@ export class SubjectsListComponent implements OnInit { subjects: Subject[] = []; - constructor(private subjectService: SubjectService) { + constructor( + private subjectService: SubjectService, + public snackBar: MdSnackBar + ) { } ngOnInit() { @@ -24,6 +29,10 @@ return this.subjectService.remove(subjectId) .then(() => { this.subjects = this.subjects.filter(subject => subject._id !== subjectId); + + this.snackBar.open('ΠŸΡ€Π΅Π΄ΠΌΠ΅Ρ‚ Π²ΠΈΠ΄Π°Π»Π΅Π½ΠΎ!', '', { + duration: 3000, + }); }); } }
b518b5a7b633667236e5ccdde7e3e72280fd9abc
packages/core/src/controllers/binders/rest/rest-controller.interface.ts
packages/core/src/controllers/binders/rest/rest-controller.interface.ts
export interface RestController { create?: (data: any, query: object) => Promise<any>; get?: (id: any, query: object) => Promise<any>; getAll?: (query: object) => Promise<any>; update?: (id: any, data: any, query: object) => Promise<any>; patch?: (id: any, data: any, query: object) => Promise<any>; delete?: (id: any, query: object) => Promise<any>; }
import { ObjectType } from '../../interfaces'; export interface RestController { create?: (data: any, query: ObjectType) => Promise<any>; get?: (id: any, query: ObjectType) => Promise<any>; getAll?: (query: ObjectType) => Promise<any>; update?: (id: any, data: any, query: ObjectType) => Promise<any>; patch?: (id: any, data: any, query: ObjectType) => Promise<any>; delete?: (id: any, query: ObjectType) => Promise<any>; }
Replace object by ObjectType in rest-controller.
Replace object by ObjectType in rest-controller.
TypeScript
mit
FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal
--- +++ @@ -1,8 +1,10 @@ +import { ObjectType } from '../../interfaces'; + export interface RestController { - create?: (data: any, query: object) => Promise<any>; - get?: (id: any, query: object) => Promise<any>; - getAll?: (query: object) => Promise<any>; - update?: (id: any, data: any, query: object) => Promise<any>; - patch?: (id: any, data: any, query: object) => Promise<any>; - delete?: (id: any, query: object) => Promise<any>; + create?: (data: any, query: ObjectType) => Promise<any>; + get?: (id: any, query: ObjectType) => Promise<any>; + getAll?: (query: ObjectType) => Promise<any>; + update?: (id: any, data: any, query: ObjectType) => Promise<any>; + patch?: (id: any, data: any, query: ObjectType) => Promise<any>; + delete?: (id: any, query: ObjectType) => Promise<any>; }
05d7d8867f58f41326ce61345700746269048661
src/themes/silver/test/ts/atomic/icons/IconsTest.ts
src/themes/silver/test/ts/atomic/icons/IconsTest.ts
import { UnitTest } from '@ephox/bedrock'; import { IconProvider, get } from '../../../../main/ts/ui/icons/Icons'; import { Assertions, Pipeline, Step } from '@ephox/agar'; import { getAll as getAllOxide } from '@tinymce/oxide-icons-default'; import { TinyLoader } from '../../../../../../../node_modules/@ephox/mcagar'; import Theme from 'tinymce/themes/silver/Theme'; UnitTest.asynctest('IconsTest', (success, failure) => { Theme(); TinyLoader.setup((editor, onSuccess, onFailure) => { const iconIndent = getAllOxide().indent; const iconDefault = getAllOxide()['temporary-placeholder']; const iconProvider = () => editor.ui.registry.getAll().icons; const emptyIconProvider: IconProvider = () => ({ }); const getTest = Step.sync(() => { Assertions.assertEq( 'When an icon exists as a default icon or provided, it should be returned', iconIndent, get('indent', iconProvider) ); Assertions.assertEq( 'When an icon does not exist as a default icon, the temporary placeholder or fallback icon should be returned', iconDefault, get('temp_icon', iconProvider) ); Assertions.assertEq( 'When a default icon or fallback does not exist, !not found! should be returned', '!not found!', get('indent', emptyIconProvider) ); }); Pipeline.async({}, [ getTest, ], onSuccess, onFailure); }, { base_url: '/project/js/tinymce' }, success, failure); });
import { UnitTest } from '@ephox/bedrock'; import { IconProvider, get } from '../../../../main/ts/ui/icons/Icons'; import { Assertions, Pipeline, Step } from '@ephox/agar'; import { getAll as getAllOxide } from '@tinymce/oxide-icons-default'; import { TinyLoader } from '@ephox/mcagar'; import Theme from 'tinymce/themes/silver/Theme'; UnitTest.asynctest('IconsTest', (success, failure) => { Theme(); TinyLoader.setup((editor, onSuccess, onFailure) => { const iconIndent = getAllOxide().indent; const iconDefault = getAllOxide()['temporary-placeholder']; const iconProvider = () => editor.ui.registry.getAll().icons; const emptyIconProvider: IconProvider = () => ({ }); const getTest = Step.sync(() => { Assertions.assertEq( 'When an icon exists as a default icon or provided, it should be returned', iconIndent, get('indent', iconProvider) ); Assertions.assertEq( 'When an icon does not exist as a default icon, the temporary placeholder or fallback icon should be returned', iconDefault, get('temp_icon', iconProvider) ); Assertions.assertEq( 'When a default icon or fallback does not exist, !not found! should be returned', '!not found!', get('indent', emptyIconProvider) ); }); Pipeline.async({}, [ getTest, ], onSuccess, onFailure); }, { base_url: '/project/js/tinymce' }, success, failure); });
Fix accidental relative import from node_modules
Fix accidental relative import from node_modules
TypeScript
mit
tinymce/tinymce,TeamupCom/tinymce,FernCreek/tinymce,FernCreek/tinymce,TeamupCom/tinymce,FernCreek/tinymce,tinymce/tinymce,tinymce/tinymce
--- +++ @@ -2,7 +2,7 @@ import { IconProvider, get } from '../../../../main/ts/ui/icons/Icons'; import { Assertions, Pipeline, Step } from '@ephox/agar'; import { getAll as getAllOxide } from '@tinymce/oxide-icons-default'; -import { TinyLoader } from '../../../../../../../node_modules/@ephox/mcagar'; +import { TinyLoader } from '@ephox/mcagar'; import Theme from 'tinymce/themes/silver/Theme'; UnitTest.asynctest('IconsTest', (success, failure) => {
8e4bcc0ae0da059bfef97b00f19a04f4e8b42bd5
app/scripts/components/customer/create/CustomerCreatePromptContainer.tsx
app/scripts/components/customer/create/CustomerCreatePromptContainer.tsx
import { connect } from 'react-redux'; import { compose } from 'redux'; import { reduxForm, SubmissionError } from 'redux-form'; import { translate, withTranslation } from '@waldur/i18n'; import { closeModalDialog, openModalDialog } from '@waldur/modal/actions'; import { connectAngularComponent } from '@waldur/store/connect'; import * as constants from './constants'; import { CustomerCreatePrompt } from './CustomerCreatePrompt'; import { getOwnerCanRegisterProvider, getOwnerCanRegisterExpert } from './selectors'; const mapStateToProps = state => ({ canRegisterProvider: getOwnerCanRegisterProvider(state), canRegisterExpert: getOwnerCanRegisterExpert(state), }); const mapDispatchToProps = dispatch => ({ closeModal: (): void => dispatch(closeModalDialog), onSubmit: data => { if (!data[constants.FIELD_NAMES.role]) { throw new SubmissionError({ _error: translate('Π‘hoose the role please'), }); } dispatch(closeModalDialog()); dispatch(openModalDialog('customer-create-dialog', { resolve: { role: data[constants.FIELD_NAMES.role], }, size: 'lg', })); }, }); const enhance = compose( connect(mapStateToProps, mapDispatchToProps), reduxForm({ form: constants.CUSTOMER_CHOICE_ROLE_FORM, initialValues: { [constants.FIELD_NAMES.role]: constants.ROLES.customer, }, }), withTranslation, ); export const CustomerCreatePromptContainer = enhance(CustomerCreatePrompt); export default connectAngularComponent(CustomerCreatePromptContainer, ['resolve']);
import { connect } from 'react-redux'; import { compose } from 'redux'; import { reduxForm, SubmissionError } from 'redux-form'; import { translate, withTranslation } from '@waldur/i18n'; import { closeModalDialog, openModalDialog } from '@waldur/modal/actions'; import { connectAngularComponent } from '@waldur/store/connect'; import * as constants from './constants'; import { CustomerCreatePrompt } from './CustomerCreatePrompt'; import { getOwnerCanRegisterProvider, getOwnerCanRegisterExpert } from './selectors'; const mapStateToProps = state => ({ canRegisterProvider: getOwnerCanRegisterProvider(state), canRegisterExpert: getOwnerCanRegisterExpert(state), }); const mapDispatchToProps = dispatch => ({ closeModal: (): void => dispatch(closeModalDialog()), onSubmit: data => { if (!data[constants.FIELD_NAMES.role]) { throw new SubmissionError({ _error: translate('Π‘hoose the role please'), }); } dispatch(closeModalDialog()); dispatch(openModalDialog('customer-create-dialog', { resolve: { role: data[constants.FIELD_NAMES.role], }, size: 'lg', })); }, }); const enhance = compose( connect(mapStateToProps, mapDispatchToProps), reduxForm({ form: constants.CUSTOMER_CHOICE_ROLE_FORM, initialValues: { [constants.FIELD_NAMES.role]: constants.ROLES.customer, }, }), withTranslation, ); export const CustomerCreatePromptContainer = enhance(CustomerCreatePrompt); export default connectAngularComponent(CustomerCreatePromptContainer, ['resolve']);
Fix customer creation dialog closing action.
Fix customer creation dialog closing action.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -16,7 +16,7 @@ }); const mapDispatchToProps = dispatch => ({ - closeModal: (): void => dispatch(closeModalDialog), + closeModal: (): void => dispatch(closeModalDialog()), onSubmit: data => { if (!data[constants.FIELD_NAMES.role]) { throw new SubmissionError({
8f5ebbcbe18e4761f1848b3901154349ce4aa44c
ui/src/kapacitor/components/handlers/Pagerduty2Handler.tsx
ui/src/kapacitor/components/handlers/Pagerduty2Handler.tsx
import React, {SFC} from 'react' import HandlerInput from 'src/kapacitor/components/HandlerInput' import HandlerEmpty from 'src/kapacitor/components/HandlerEmpty' interface Props { selectedHandler: { enabled: boolean } handleModifyHandler: () => void onGoToConfig: () => void validationError: string } const Pagerduty2Handler: SFC<Props> = ({ selectedHandler, handleModifyHandler, onGoToConfig, validationError, }) => selectedHandler.enabled ? ( <div className="endpoint-tab-contents"> <div className="endpoint-tab--parameters"> <h4 className="u-flex u-jc-space-between"> Parameters from Kapacitor Configuration <div className="btn btn-default btn-sm" onClick={onGoToConfig}> <span className="icon cog-thick" /> {validationError ? 'Exit this Rule and Edit Configuration' : 'Save this Rule and Edit Configuration'} </div> </h4> <HandlerInput selectedHandler={selectedHandler} handleModifyHandler={handleModifyHandler} fieldName="routingKey" fieldDisplay="Routing Key:" placeholder="ex: routing_key" redacted={true} fieldColumns="col-md-12" /> </div> </div> ) : ( <HandlerEmpty onGoToConfig={onGoToConfig} validationError={validationError} /> ) export default Pagerduty2Handler
import React, {SFC} from 'react' import HandlerInput from 'src/kapacitor/components/HandlerInput' import HandlerEmpty from 'src/kapacitor/components/HandlerEmpty' interface Props { selectedHandler: { enabled: boolean } handleModifyHandler: () => void onGoToConfig: () => void validationError: string } const Pagerduty2Handler: SFC<Props> = ({ selectedHandler, handleModifyHandler, onGoToConfig, validationError, }) => { if (selectedHandler.enabled) { let goToConfigText if (validationError) { goToConfigText = 'Exit this Rule and Edit Configuration' } else { goToConfigText = 'Save this Rule and Edit Configuration' } return ( <div className="endpoint-tab-contents"> <div className="endpoint-tab--parameters"> <h4 className="u-flex u-jc-space-between"> Parameters from Kapacitor Configuration <div className="btn btn-default btn-sm" onClick={onGoToConfig}> <span className="icon cog-thick" /> {goToConfigText} </div> </h4> <HandlerInput selectedHandler={selectedHandler} handleModifyHandler={handleModifyHandler} fieldName="routingKey" fieldDisplay="Routing Key:" placeholder="ex: routing_key" redacted={true} fieldColumns="col-md-12" /> </div> </div> ) } return ( <HandlerEmpty onGoToConfig={onGoToConfig} validationError={validationError} /> ) } export default Pagerduty2Handler
Remove ternaries from PagerDuty2Handler for ease of debugging
Remove ternaries from PagerDuty2Handler for ease of debugging
TypeScript
mit
nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb,influxdb/influxdb,influxdata/influxdb,li-ang/influxdb,influxdb/influxdb
--- +++ @@ -16,35 +16,44 @@ handleModifyHandler, onGoToConfig, validationError, -}) => - selectedHandler.enabled ? ( - <div className="endpoint-tab-contents"> - <div className="endpoint-tab--parameters"> - <h4 className="u-flex u-jc-space-between"> - Parameters from Kapacitor Configuration - <div className="btn btn-default btn-sm" onClick={onGoToConfig}> - <span className="icon cog-thick" /> - {validationError - ? 'Exit this Rule and Edit Configuration' - : 'Save this Rule and Edit Configuration'} - </div> - </h4> - <HandlerInput - selectedHandler={selectedHandler} - handleModifyHandler={handleModifyHandler} - fieldName="routingKey" - fieldDisplay="Routing Key:" - placeholder="ex: routing_key" - redacted={true} - fieldColumns="col-md-12" - /> +}) => { + if (selectedHandler.enabled) { + let goToConfigText + if (validationError) { + goToConfigText = 'Exit this Rule and Edit Configuration' + } else { + goToConfigText = 'Save this Rule and Edit Configuration' + } + return ( + <div className="endpoint-tab-contents"> + <div className="endpoint-tab--parameters"> + <h4 className="u-flex u-jc-space-between"> + Parameters from Kapacitor Configuration + <div className="btn btn-default btn-sm" onClick={onGoToConfig}> + <span className="icon cog-thick" /> + {goToConfigText} + </div> + </h4> + <HandlerInput + selectedHandler={selectedHandler} + handleModifyHandler={handleModifyHandler} + fieldName="routingKey" + fieldDisplay="Routing Key:" + placeholder="ex: routing_key" + redacted={true} + fieldColumns="col-md-12" + /> + </div> </div> - </div> - ) : ( + ) + } + + return ( <HandlerEmpty onGoToConfig={onGoToConfig} validationError={validationError} /> ) +} export default Pagerduty2Handler
47d25747bcb458d0f11eff85c21d792409ef1695
packages/outputs/src/components/kernel-output-error.tsx
packages/outputs/src/components/kernel-output-error.tsx
import Ansi from "ansi-to-react"; import * as React from "react"; import styled from "styled-components"; interface Props { /** * The name of the exception. This value is returned by the kernel. */ ename: string; /** * The value of the exception. This value is returned by the kernel. */ evalue: string; /** * The output type passed to the Output component. This should be `error` * if you would like to render a KernelOutputError component. */ output_type: "error"; /** * The tracebook of the exception. This value is returned by the kernel. */ traceback: string[]; } const PlainKernelOutputError = (props: Partial<Props>) => { const { ename, evalue, traceback } = props; const joinedTraceback = Array.isArray(traceback) ? traceback.join("\n") : traceback; const kernelOutputError = []; if (joinedTraceback) { kernelOutputError.push(joinedTraceback); } else { if (ename && evalue) { kernelOutputError.push(`${ename}: ${evalue}`); } } return <Ansi linkify={false}>{kernelOutputError.join("\n")}</Ansi>; }; export const KernelOutputError = styled(PlainKernelOutputError)` & code { white-space: pre-wrap; } `; KernelOutputError.defaultProps = { output_type: "error", ename: "", evalue: "", traceback: [] }; KernelOutputError.displayName = "KernelOutputError";
import Ansi from "ansi-to-react"; import * as React from "react"; import styled from "styled-components"; interface Props { /** * The name of the exception. This value is returned by the kernel. */ ename: string; /** * The value of the exception. This value is returned by the kernel. */ evalue: string; /** * The output type passed to the Output component. This should be `error` * if you would like to render a KernelOutputError component. */ output_type: "error"; /** * The tracebook of the exception. This value is returned by the kernel. */ traceback: string[]; } const PlainKernelOutputError = (props: Partial<Props>) => { const { ename, evalue, traceback } = props; const joinedTraceback = Array.isArray(traceback) ? traceback.join("\n") : traceback; const kernelOutputError = []; if (joinedTraceback) { kernelOutputError.push(joinedTraceback); } else { if (ename && evalue) { kernelOutputError.push(`${ename}: ${evalue}`); } } return ( <Ansi className="stacktrace" linkify={false}> {kernelOutputError.join("\n")} </Ansi> ); }; export const KernelOutputError = styled(PlainKernelOutputError)` & .stracktrace { white-space: pre-wrap; } `; KernelOutputError.defaultProps = { output_type: "error", ename: "", evalue: "", traceback: [] }; KernelOutputError.displayName = "KernelOutputError";
Use classname for styled-components styling
Use classname for styled-components styling
TypeScript
bsd-3-clause
nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/composition,nteract/composition,nteract/composition
--- +++ @@ -39,11 +39,15 @@ } } - return <Ansi linkify={false}>{kernelOutputError.join("\n")}</Ansi>; + return ( + <Ansi className="stacktrace" linkify={false}> + {kernelOutputError.join("\n")} + </Ansi> + ); }; export const KernelOutputError = styled(PlainKernelOutputError)` - & code { + & .stracktrace { white-space: pre-wrap; } `;
e8c70e4ca22fdc81963d833f909ee9feb73d4db2
src/app/components/code-input/code-input.component.ts
src/app/components/code-input/code-input.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-code-input', templateUrl: './code-input.component.html', styleUrls: ['./code-input.component.css'] }) export class CodeInputComponent implements OnInit { @Input() code; @Output() codeChange = new EventEmitter(); constructor() { } ngOnInit() { } setCode(code: string) { this.code = code; this.codeChange.emit(code); } }
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-code-input', templateUrl: './code-input.component.html', styleUrls: ['./code-input.component.css'] }) export class CodeInputComponent implements OnInit { @Input() code = "public class Example {\n\n\tpublic final String value;\n\n}"; @Output() codeChange = new EventEmitter(); constructor() { } ngOnInit() { } setCode(code: string) { this.code = code; this.codeChange.emit(code); } }
Move example code to input
Move example code to input
TypeScript
mit
bvkatwijk/code-tools,bvkatwijk/code-tools,bvkatwijk/code-tools
--- +++ @@ -7,19 +7,16 @@ }) export class CodeInputComponent implements OnInit { - @Input() code; + @Input() code = "public class Example {\n\n\tpublic final String value;\n\n}"; @Output() codeChange = new EventEmitter(); constructor() { } - ngOnInit() { - } + ngOnInit() { } setCode(code: string) { this.code = code; this.codeChange.emit(code); } - - }
30241f5126ad58219ca4200e0b5c2c705964c9bc
app/src/lib/dispatcher/validated-repository-path.ts
app/src/lib/dispatcher/validated-repository-path.ts
import * as Path from 'path' import { getGitDir } from '../git' /** * Get the path to the parent of the .git directory or null if the path isn't a * valid repository. */ export async function validatedRepositoryPath(path: string): Promise<string | null> { try { const gitDir = await getGitDir(path) return gitDir ? Path.dirname(gitDir) : null } catch (e) { return null } }
import { getTopLevelWorkingDirectory } from '../git' /** * Get the path to the parent of the .git directory or null if the path isn't a * valid repository. */ export async function validatedRepositoryPath(path: string): Promise<string | null> { try { return await getTopLevelWorkingDirectory(path) } catch (e) { return null } }
Resolve the working directory instead of the git dir
Resolve the working directory instead of the git dir
TypeScript
mit
j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus,kactus-io/kactus,artivilla/desktop,hjobrien/desktop,say25/desktop,desktop/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,gengjiawen/desktop,kactus-io/kactus,j-f1/forked-desktop,gengjiawen/desktop,j-f1/forked-desktop,artivilla/desktop,gengjiawen/desktop,desktop/desktop,desktop/desktop,hjobrien/desktop,hjobrien/desktop,shiftkey/desktop,gengjiawen/desktop,shiftkey/desktop,artivilla/desktop,shiftkey/desktop,say25/desktop,kactus-io/kactus,hjobrien/desktop,say25/desktop,say25/desktop
--- +++ @@ -1,6 +1,4 @@ -import * as Path from 'path' - -import { getGitDir } from '../git' +import { getTopLevelWorkingDirectory } from '../git' /** * Get the path to the parent of the .git directory or null if the path isn't a @@ -8,8 +6,7 @@ */ export async function validatedRepositoryPath(path: string): Promise<string | null> { try { - const gitDir = await getGitDir(path) - return gitDir ? Path.dirname(gitDir) : null + return await getTopLevelWorkingDirectory(path) } catch (e) { return null }
9887e1f7430df576e4d12e80604ddb9b55bb21f6
app/components/classroomLessons/admin/showScriptItem.tsx
app/components/classroomLessons/admin/showScriptItem.tsx
import React, {Component} from 'react' import { connect } from 'react-redux'; class showScriptItem extends Component<any, any> { constructor(props){ super(props); } render() { return ( <div> Script Item </div> ) } } function select(props) { return { classroomLessons: props.classroomLessons }; } export default connect(select)(showScriptItem)
import React, {Component} from 'react' import { connect } from 'react-redux'; import { getClassroomLessonScriptItem } from './helpers'; import * as IntF from '../interfaces'; class showScriptItem extends Component<any, any> { constructor(props){ super(props); } getCurrentScriptItem(): IntF.ScriptItem { const {classroomLessonID, slideID, scriptItemID} = this.props.params; return getClassroomLessonScriptItem(this.props.classroomLessons.data, classroomLessonID, slideID, scriptItemID) } render() { if (this.props.classroomLessons.hasreceiveddata) { return ( <div> {this.getCurrentScriptItem().data.heading} </div> ) } else { return ( <p>Loading...</p> ) } } } function select(props) { return { classroomLessons: props.classroomLessons }; } export default connect(select)(showScriptItem)
Add script item data to page.
Add script item data to page.
TypeScript
agpl-3.0
empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core
--- +++ @@ -1,17 +1,33 @@ import React, {Component} from 'react' import { connect } from 'react-redux'; +import { + getClassroomLessonScriptItem +} from './helpers'; +import * as IntF from '../interfaces'; class showScriptItem extends Component<any, any> { constructor(props){ super(props); } + getCurrentScriptItem(): IntF.ScriptItem { + const {classroomLessonID, slideID, scriptItemID} = this.props.params; + return getClassroomLessonScriptItem(this.props.classroomLessons.data, classroomLessonID, slideID, scriptItemID) + } + render() { - return ( - <div> - Script Item - </div> - ) + if (this.props.classroomLessons.hasreceiveddata) { + return ( + <div> + {this.getCurrentScriptItem().data.heading} + </div> + ) + } else { + return ( + <p>Loading...</p> + ) + } + } }
f88437c324c272e57bff2f997f5ae9f509152b7c
src/app/gallery/album-info.ts
src/app/gallery/album-info.ts
export interface AlbumInfo { albumId: number; title: string; name: string; description: string; imagesInAlbum: number; imagesPerPage: number; totalPages: number; iconUrl: string; }
/** * An interface which can be used by a class to encapsulate album data */ export interface AlbumInfo { /** * The album's unique ID */ albumId: number; /** * The album title, as displayed to the user */ title: string; /** * The short album name, used to refer to the album in URLs */ name: string; /** * The album description */ description: string; /** * The total number of images in the album */ imagesInAlbum: number; /** * The number of images on a page */ imagesPerPage: number; /** * The number of pages that the album has. See also: imagesPerPage */ totalPages: number; /** * The URL to the album icon */ iconUrl: string; }
Add documentation for album info interface
Add documentation for album info interface
TypeScript
apache-2.0
jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog
--- +++ @@ -1,10 +1,44 @@ +/** + * An interface which can be used by a class to encapsulate album data + */ export interface AlbumInfo { + /** + * The album's unique ID + */ albumId: number; + + /** + * The album title, as displayed to the user + */ title: string; + + /** + * The short album name, used to refer to the album in URLs + */ name: string; + + /** + * The album description + */ description: string; + + /** + * The total number of images in the album + */ imagesInAlbum: number; + + /** + * The number of images on a page + */ imagesPerPage: number; + + /** + * The number of pages that the album has. See also: imagesPerPage + */ totalPages: number; + + /** + * The URL to the album icon + */ iconUrl: string; }
d8bff61d0d73f8d3393a2e181ea2df84946ea8b0
src/paths/dataclass/index.ts
src/paths/dataclass/index.ts
import {Endpoint, Parameter, Path, Response} from '../../swagger/path'; import {HTTPVerb} from '../../http-verb'; import {IWakandaDataClass} from '../../'; import {collectionEndpoint} from './collection'; import {createEndpoint} from './create'; export function dataClassPaths(dataClass: IWakandaDataClass): Path[] { const paths: Path[] = []; const basicPath = new Path(`/${dataClass.name}`); basicPath.addEndpoint(HTTPVerb.GET, collectionEndpoint(dataClass)); basicPath.addEndpoint(HTTPVerb.POST, createEndpoint(dataClass)); paths.push(basicPath); //TODO - Add a path for each dataClass method return paths; }
import {Endpoint, Parameter, Path, Response} from '../../swagger/path'; import {HTTPVerb} from '../../http-verb'; import {IWakandaDataClass} from '../../'; import {collectionEndpoint} from './collection'; import {createEndpoint} from './create'; export function dataClassPaths(dataClass: IWakandaDataClass): Path[] { const paths: Path[] = []; const basicPath = new Path(`/${dataClass.name}`); basicPath.addEndpoint(HTTPVerb.GET, collectionEndpoint(dataClass)); basicPath.addEndpoint(HTTPVerb.POST, createEndpoint(dataClass)); paths.push(basicPath); dataClass.methods .filter(x => x.applyTo === 'dataClass') .forEach(method => { const methodPath = new Path(`/${dataClass.name}/_method/${method.name}`); const methodEndpoint = new Endpoint(); methodEndpoint.description = `Call the \`${method.name}\` method on ${dataClass.name} dataClass.`; methodEndpoint.parameters.push(new Parameter({ name: 'body', in: 'body', schema: { type: 'object' } })); methodEndpoint.responses.push(new Response({ id: '200', description: 'Successful response', schema: { type: 'object' } })); methodEndpoint.tags.push(dataClass.name, 'DataClass Method'); methodPath.addEndpoint(HTTPVerb.POST, methodEndpoint); paths.push(methodPath); }); return paths; }
Add dataClass method paths to document
Add dataClass method paths to document
TypeScript
mit
mrblackus/wakanda-swagger
--- +++ @@ -14,7 +14,32 @@ paths.push(basicPath); - //TODO - Add a path for each dataClass method + dataClass.methods + .filter(x => x.applyTo === 'dataClass') + .forEach(method => { + const methodPath = new Path(`/${dataClass.name}/_method/${method.name}`); + const methodEndpoint = new Endpoint(); + + methodEndpoint.description = `Call the \`${method.name}\` method on ${dataClass.name} dataClass.`; + methodEndpoint.parameters.push(new Parameter({ + name: 'body', + in: 'body', + schema: { + type: 'object' + } + })); + methodEndpoint.responses.push(new Response({ + id: '200', + description: 'Successful response', + schema: { + type: 'object' + } + })); + methodEndpoint.tags.push(dataClass.name, 'DataClass Method'); + + methodPath.addEndpoint(HTTPVerb.POST, methodEndpoint); + paths.push(methodPath); + }); return paths; }
71a1a013df2bbce56f44cb06f6fd9ba25c4ec532
src/materials/LineBasicMaterial.d.ts
src/materials/LineBasicMaterial.d.ts
import { Color } from './../math/Color'; import { MaterialParameters, Material } from './Material'; export interface LineBasicMaterialParameters extends MaterialParameters { color?: Color | string | number; linewidth?: number; linecap?: string; linejoin?: string; morphTargets?: boolean; } export class LineBasicMaterial extends Material { constructor( parameters?: LineBasicMaterialParameters ); /** * @default 'LineBasicMaterial' */ type: string; /** * @default 0xffffff */ color: Color | string | number; /** * @default 1 */ linewidth: number; /** * @default 'round' */ linecap: string; /** * @default 'round' */ linejoin: string; /** * @default false */ morphTargets: boolean; setValues( parameters: LineBasicMaterialParameters ): void; }
import { Color } from './../math/Color'; import { MaterialParameters, Material } from './Material'; export interface LineBasicMaterialParameters extends MaterialParameters { color?: Color | string | number; linewidth?: number; linecap?: string; linejoin?: string; morphTargets?: boolean; } export class LineBasicMaterial extends Material { constructor( parameters?: LineBasicMaterialParameters ); /** * @default 'LineBasicMaterial' */ type: string; /** * @default 0xffffff */ color: Color; /** * @default 1 */ linewidth: number; /** * @default 'round' */ linecap: string; /** * @default 'round' */ linejoin: string; /** * @default false */ morphTargets: boolean; setValues( parameters: LineBasicMaterialParameters ): void; }
Fix "color" property type on LineBasicMaterial
Fix "color" property type on LineBasicMaterial
TypeScript
mit
mrdoob/three.js,mrdoob/three.js,06wj/three.js,looeee/three.js,gero3/three.js,looeee/three.js,jpweeks/three.js,greggman/three.js,fyoudine/three.js,kaisalmen/three.js,aardgoose/three.js,donmccurdy/three.js,Liuer/three.js,makc/three.js.fork,fyoudine/three.js,greggman/three.js,Liuer/three.js,kaisalmen/three.js,WestLangley/three.js,gero3/three.js,WestLangley/three.js,06wj/three.js,makc/three.js.fork,jpweeks/three.js,aardgoose/three.js,donmccurdy/three.js
--- +++ @@ -21,7 +21,7 @@ /** * @default 0xffffff */ - color: Color | string | number; + color: Color; /** * @default 1
51a5bb9307562a8faea2f62ccf0778cb8bb00ccc
test/e2e/grid-pager-info.e2e-spec.ts
test/e2e/grid-pager-info.e2e-spec.ts
ο»Ώimport { browser, element, by } from '../../node_modules/protractor/built'; describe('grid pager info', () => { let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'), gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'), pageSizeSelector = element(by.tagName('page-size-selector')).$$('select'), gridSearchInput = element(by.tagName('grid-search')).$$('div').$$('div').$$('input'); beforeEach(() => { browser.get('/'); }); it('should show text in accordance to numbered of filter rows and current results-page',() => { expect(gridPagerInfo.first().getText()).toEqual('Showing 1 to 10 of 53 records'); paginator.get(7).$$('a').click(); pageSizeSelector.$$('option').get(1).click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 21 to 40 of 53 records'); paginator.get(5).$$('a').click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 41 to 60 of 53 records'); }); it('should show count in footer', () => { gridSearchInput.sendKeys('a'); expect(gridPagerInfo.first().getText()).toContain('(Filtered from 53 total records)'); }); });
ο»Ώimport { browser, element, by } from '../../node_modules/protractor/built'; describe('grid pager info', () => { let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'), gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'), pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select'); gridSearchInput = element(by.tagName('grid-search')).$$('div').$$('div').$$('input'); beforeEach(() => { browser.get('/'); pageSizeSelector.$('[value="10"]').click(); }); it('should show text in accordance to numbered of filter rows and current results-page',() => { expect(gridPagerInfo.first().getText()).toEqual('Showing 1 to 10 of 53 records'); paginator.get(7).$$('a').click(); pageSizeSelector.$('[value="20"]').click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 21 to 40 of 53 records'); paginator.get(5).$$('a').click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 41 to 60 of 53 records'); }); it('should show count in footer', () => { gridSearchInput.sendKeys('a'); expect(gridPagerInfo.first().getText()).toContain('(Filtered from 53 total records)'); }); });
Fix issues with e2e testing
Fix issues with e2e testing
TypeScript
mit
unosquare/tubular2,unosquare/tubular2,unosquare/tubular2,unosquare/tubular2
--- +++ @@ -4,17 +4,18 @@ let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'), gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'), - pageSizeSelector = element(by.tagName('page-size-selector')).$$('select'), + pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select'); gridSearchInput = element(by.tagName('grid-search')).$$('div').$$('div').$$('input'); beforeEach(() => { browser.get('/'); + pageSizeSelector.$('[value="10"]').click(); }); it('should show text in accordance to numbered of filter rows and current results-page',() => { expect(gridPagerInfo.first().getText()).toEqual('Showing 1 to 10 of 53 records'); paginator.get(7).$$('a').click(); - pageSizeSelector.$$('option').get(1).click(); + pageSizeSelector.$('[value="20"]').click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 21 to 40 of 53 records'); paginator.get(5).$$('a').click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 41 to 60 of 53 records');
254166807c6f1f5544d521dccce309423be92949
src/communication/constants.ts
src/communication/constants.ts
export const HOST_WILLIAM = '127.0.0.1'// '10.1.38.61' export const HOST_DAVID = '192.168.1.97' export const HOST = WEBPACK_HOST || HOST_WILLIAM export const PORT = 3002 export const IO_SERVER = `http://${HOST}:${PORT}` export const MESSAGE_FROM_CLIENT = 'MESSAGE_FROM_CLIENT' export const MESSAGE_TO_EXTENSION = 'MESSAGE_TO_EXTENSION' export const MESSAGE_FROM_EXTENSION = 'MESSAGE_FROM_EXTENSION' export const MESSAGE_FROM_SERVER = 'MESSAGE_FROM_SERVER'
export const HOST_WILLIAM = '127.0.0.1'// '10.1.38.61' export const HOST_DAVID = '192.168.1.97' export const HOST = WEBPACK_HOST || HOST_WILLIAM export const PORT = process.env.PORT || 3002 export const IO_SERVER = `http://${HOST}:${PORT}` export const MESSAGE_FROM_CLIENT = 'MESSAGE_FROM_CLIENT' export const MESSAGE_TO_EXTENSION = 'MESSAGE_TO_EXTENSION' export const MESSAGE_FROM_EXTENSION = 'MESSAGE_FROM_EXTENSION' export const MESSAGE_FROM_SERVER = 'MESSAGE_FROM_SERVER'
Change port to listen to env variable
Change port to listen to env variable
TypeScript
mit
wdelmas/remote-potato,wdelmas/remote-potato,wdelmas/remote-potato
--- +++ @@ -2,7 +2,7 @@ export const HOST_WILLIAM = '127.0.0.1'// '10.1.38.61' export const HOST_DAVID = '192.168.1.97' export const HOST = WEBPACK_HOST || HOST_WILLIAM -export const PORT = 3002 +export const PORT = process.env.PORT || 3002 export const IO_SERVER = `http://${HOST}:${PORT}` export const MESSAGE_FROM_CLIENT = 'MESSAGE_FROM_CLIENT'
a3fc785a16e52cd32fab7bb92abe59dde82dad54
components/meta/fb-meta-container.ts
components/meta/fb-meta-container.ts
import { MetaContainer } from './meta-container'; export class FbMetaContainer extends MetaContainer { set title( value: string | null ) { this._set( 'og:title', value ); } get title() { return this._get( 'og:title' ); } set description( value: string | null ) { this._set( 'og:description', value ); } get description() { return this._get( 'og:description' ); } set url( value: string | null ) { this._set( 'og:url', value ); } get url() { return this._get( 'og:url' ); } set type( value: string | null ) { this._set( 'og:type', value ); } get type() { return this._get( 'og:type' ); } set image( value: string | null ) { this._set( 'og:type', value ); } get image() { return this._get( 'og:type' ); } set profileId( value: string | null ) { this._set( 'og:profile_id', value ); } get profileId() { return this._get( 'og:profile_id' ); } }
import { MetaContainer } from './meta-container'; export class FbMetaContainer extends MetaContainer { set title( value: string | null ) { this._set( 'og:title', value ); } get title() { return this._get( 'og:title' ); } set description( value: string | null ) { this._set( 'og:description', value ); } get description() { return this._get( 'og:description' ); } set url( value: string | null ) { this._set( 'og:url', value ); } get url() { return this._get( 'og:url' ); } set type( value: string | null ) { this._set( 'og:type', value ); } get type() { return this._get( 'og:type' ); } set image( value: string | null ) { this._set( 'og:image', value ); } get image() { return this._get( 'og:image' ); } set profileId( value: string | null ) { this._set( 'og:profile_id', value ); } get profileId() { return this._get( 'og:profile_id' ); } }
Fix FB image not working in Meta service.
Fix FB image not working in Meta service.
TypeScript
mit
gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib
--- +++ @@ -14,8 +14,8 @@ set type( value: string | null ) { this._set( 'og:type', value ); } get type() { return this._get( 'og:type' ); } - set image( value: string | null ) { this._set( 'og:type', value ); } - get image() { return this._get( 'og:type' ); } + set image( value: string | null ) { this._set( 'og:image', value ); } + get image() { return this._get( 'og:image' ); } set profileId( value: string | null ) { this._set( 'og:profile_id', value ); } get profileId() { return this._get( 'og:profile_id' ); }
e3f61a7d971b3898e3627693d394d8e5bc5f0fbf
client/Library/Components/EncounterLibraryViewModel.tsx
client/Library/Components/EncounterLibraryViewModel.tsx
import * as React from "react"; import { ListingViewModel } from "./Listing"; import { EncounterLibrary } from "../EncounterLibrary"; import { SavedEncounter, SavedCombatant } from "../../Encounter/SavedEncounter"; import { Listing } from "../Listing"; import { TrackerViewModel } from "../../TrackerViewModel"; export type EncounterLibraryViewModelProps = { tracker: TrackerViewModel; library: EncounterLibrary }; export class EncounterLibraryViewModel extends React.Component<EncounterLibraryViewModelProps> { public render() { const listings = this.props.library.Encounters(); const loadSavedEncounter = (listing: Listing<SavedEncounter<SavedCombatant>>) => { listing.GetAsync(savedEncounter => this.props.tracker.Encounter.LoadSavedEncounter(savedEncounter)); }; const deleteListing = (listing: Listing<SavedEncounter<SavedCombatant>>) => { if (confirm(`Delete saved encounter "${listing.CurrentName()}"?`)) { this.props.library.Delete(listing); } }; return ( <ul className = "listings"> {listings.map(l => <ListingViewModel name={l.CurrentName()} onAdd={loadSavedEncounter} onDelete={deleteListing} listing={l} />)} </ul> ); } }
import * as React from "react"; import { ListingViewModel } from "./Listing"; import { EncounterLibrary } from "../EncounterLibrary"; import { SavedEncounter, SavedCombatant } from "../../Encounter/SavedEncounter"; import { Listing } from "../Listing"; import { TrackerViewModel } from "../../TrackerViewModel"; export type EncounterLibraryViewModelProps = { tracker: TrackerViewModel; library: EncounterLibrary }; interface State { listings: Listing<SavedEncounter<SavedCombatant>>[]; } export class LibraryFilter extends React.Component<{}> { } export class EncounterLibraryViewModel extends React.Component<EncounterLibraryViewModelProps, State> { constructor(props) { super(props); this.state = { listings: this.props.library.Encounters() }; } public render() { const loadSavedEncounter = (listing: Listing<SavedEncounter<SavedCombatant>>) => { listing.GetAsync(savedEncounter => this.props.tracker.Encounter.LoadSavedEncounter(savedEncounter)); }; const deleteListing = (listing: Listing<SavedEncounter<SavedCombatant>>) => { if (confirm(`Delete saved encounter "${listing.CurrentName()}"?`)) { this.props.library.Delete(listing); } }; return ([ <LibraryFilter />, <ul className="listings"> {this.state.listings.map(l => <ListingViewModel name={l.CurrentName()} onAdd={loadSavedEncounter} onDelete={deleteListing} listing={l} />)} </ul> ]); } }
Add LibraryFilter, extract listings into state
Add LibraryFilter, extract listings into state
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -9,24 +9,38 @@ tracker: TrackerViewModel; library: EncounterLibrary }; -export class EncounterLibraryViewModel extends React.Component<EncounterLibraryViewModelProps> { + +interface State { + listings: Listing<SavedEncounter<SavedCombatant>>[]; +} + +export class LibraryFilter extends React.Component<{}> { + +} + +export class EncounterLibraryViewModel extends React.Component<EncounterLibraryViewModelProps, State> { + constructor(props) { + super(props); + this.state = { + listings: this.props.library.Encounters() + }; + } public render() { - const listings = this.props.library.Encounters(); - const loadSavedEncounter = (listing: Listing<SavedEncounter<SavedCombatant>>) => { listing.GetAsync(savedEncounter => this.props.tracker.Encounter.LoadSavedEncounter(savedEncounter)); }; const deleteListing = (listing: Listing<SavedEncounter<SavedCombatant>>) => { if (confirm(`Delete saved encounter "${listing.CurrentName()}"?`)) { - this.props.library.Delete(listing); + this.props.library.Delete(listing); } }; - return ( - <ul className = "listings"> - {listings.map(l => <ListingViewModel name={l.CurrentName()} onAdd={loadSavedEncounter} onDelete={deleteListing} listing={l} />)} + return ([ + <LibraryFilter />, + <ul className="listings"> + {this.state.listings.map(l => <ListingViewModel name={l.CurrentName()} onAdd={loadSavedEncounter} onDelete={deleteListing} listing={l} />)} </ul> - ); + ]); } }
bf8678f4edd82df4f3d74f657f7e6ab93568f9bb
src/xrm-mock/controls/iframecontrol/iframecontrol.mock.ts
src/xrm-mock/controls/iframecontrol/iframecontrol.mock.ts
import { ControlMock } from "../control/control.mock"; export class IframeControlMock extends ControlMock implements Xrm.Controls.IframeControl { public setVisible(visible: boolean): void { throw new Error("setVisible not implemented."); } public getObject(): any { throw new Error("getObject not implemented."); } public getContentWindow(): Xrm.Async.PromiseLike<any> { throw new Error("getContentWindow not implemented."); } public getSrc(): string { throw new Error("getSrc not implemented."); } public setSrc(src: string): void { throw new Error("setSrc not implemented."); } public getInitialUrl(): string { throw new Error("getInitialUrl not implemented."); } public getDisabled(): boolean { throw new Error("getDisabled not implemented."); } public setDisabled(value: boolean): void { throw new Error("setDisabled not implemented."); } public setFocus(): void { throw new Error("setFocus not implemented."); } }
import { ControlMock } from "../control/control.mock"; export class IframeControlMock extends ControlMock implements Xrm.Controls.IframeControl { public setVisible(visible: boolean): void { throw new Error("setVisible not implemented."); } public getObject(): any { throw new Error("getObject not implemented."); } public getContentWindow(): Promise<Window> { throw new Error("getContentWindow not implemented."); } public getSrc(): string { throw new Error("getSrc not implemented."); } public setSrc(src: string): void { throw new Error("setSrc not implemented."); } public getInitialUrl(): string { throw new Error("getInitialUrl not implemented."); } public getDisabled(): boolean { throw new Error("getDisabled not implemented."); } public setDisabled(value: boolean): void { throw new Error("setDisabled not implemented."); } public setFocus(): void { throw new Error("setFocus not implemented."); } }
Update to correct return value when implements Xrm.Controls.IframeControl
Update to correct return value when implements Xrm.Controls.IframeControl
TypeScript
mit
camelCaseDave/xrm-mock,camelCaseDave/xrm-mock
--- +++ @@ -7,7 +7,7 @@ public getObject(): any { throw new Error("getObject not implemented."); } - public getContentWindow(): Xrm.Async.PromiseLike<any> { + public getContentWindow(): Promise<Window> { throw new Error("getContentWindow not implemented."); } public getSrc(): string {
0e99b11777055c3e27b431d4b00a20e8b0a37803
src/openstack/openstack-instance/actions/ConsoleAction.ts
src/openstack/openstack-instance/actions/ConsoleAction.ts
import { get } from '@waldur/core/api'; import { format } from '@waldur/core/ErrorMessageFormatter'; import { ENV } from '@waldur/core/services'; import { translate } from '@waldur/i18n'; import { validateState } from '@waldur/resource/actions/base'; import { ResourceAction, ActionContext } from '@waldur/resource/actions/types'; const getConsoleURL = (id: string) => get(`/openstacktenant-instances/${id}/console/`); const validatePermissions = (ctx: ActionContext) => { if (ctx.user.is_staff) { return; } if (!ctx.user.is_support && ENV.plugins.WALDUR_OPENSTACK_TENANT.ALLOW_CUSTOMER_USERS_OPENSTACK_CONSOLE_ACCESS) { return; } return translate('Only staff and organization users are allowed to open console.'); }; export default function createAction(): ResourceAction { return { name: 'console', title: translate('Open console'), type: 'callback', execute: resource => { getConsoleURL(resource.uuid).then(({ url }) => { window.open(url); }).catch(error => { const ctx = {message: format(error)}; const message = translate('Unable to open console. Error message: {message}', ctx); alert(message); }); }, validators: [validateState('OK'), validatePermissions], }; }
import { get } from '@waldur/core/api'; import { format } from '@waldur/core/ErrorMessageFormatter'; import { ENV } from '@waldur/core/services'; import { translate } from '@waldur/i18n'; import { validateState } from '@waldur/resource/actions/base'; import { ResourceAction, ActionContext } from '@waldur/resource/actions/types'; const getConsoleURL = (id: string) => get(`/openstacktenant-instances/${id}/console/`); const validatePermissions = (ctx: ActionContext) => { if (ctx.user.is_staff) { return; } if (!ctx.user.is_support && ENV.plugins.WALDUR_OPENSTACK_TENANT.ALLOW_CUSTOMER_USERS_OPENSTACK_CONSOLE_ACCESS) { return; } return translate('Only staff and organization users are allowed to open console.'); }; export default function createAction(): ResourceAction { return { name: 'console', title: translate('Open console'), type: 'callback', execute: resource => { getConsoleURL(resource.uuid).then(response => { window.open(response.data.url); }).catch(error => { const ctx = {message: format(error)}; const message = translate('Unable to open console. Error message: {message}', ctx); alert(message); }); }, validators: [validateState('OK'), validatePermissions], }; }
Fix open console action for OpenStack instance.
Fix open console action for OpenStack instance.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -24,8 +24,8 @@ title: translate('Open console'), type: 'callback', execute: resource => { - getConsoleURL(resource.uuid).then(({ url }) => { - window.open(url); + getConsoleURL(resource.uuid).then(response => { + window.open(response.data.url); }).catch(error => { const ctx = {message: format(error)}; const message = translate('Unable to open console. Error message: {message}', ctx);
2473ffcaac533a7bd6a5b5fe3a2896a6cff9a726
tests/cases/conformance/jsdoc/jsdocIndexSignature.ts
tests/cases/conformance/jsdoc/jsdocIndexSignature.ts
// @allowJs: true // @checkJs: true // @noEmit: true // @Filename: indices.js /** @type {Object.<string, number>} */ var o1; /** @type {Object.<number, boolean>} */ var o2; /** @type {Object.<boolean, string>} */ var o3;
// @allowJs: true // @checkJs: true // @noEmit: true // @Filename: indices.js /** @type {Object.<string, number>} */ var o1; /** @type {Object.<number, boolean>} */ var o2; /** @type {Object.<boolean, string>} */ var o3; /** @param {Object.<string, boolean>} o */ function f(o) { o.foo = 1; // error o.bar = false; // ok }
Add a better test for jsdoc index signatures.
Add a better test for jsdoc index signatures. The test case shows that the errorenous error no longer appears.
TypeScript
apache-2.0
SaschaNaz/TypeScript,SaschaNaz/TypeScript,minestarks/TypeScript,RyanCavanaugh/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,Microsoft/TypeScript,donaldpipowitch/TypeScript,alexeagle/TypeScript,kpreisser/TypeScript,basarat/TypeScript,Eyas/TypeScript,basarat/TypeScript,alexeagle/TypeScript,donaldpipowitch/TypeScript,Microsoft/TypeScript,minestarks/TypeScript,TukekeSoft/TypeScript,RyanCavanaugh/TypeScript,weswigham/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,Eyas/TypeScript,TukekeSoft/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,basarat/TypeScript,kitsonk/TypeScript,Eyas/TypeScript,weswigham/TypeScript,kpreisser/TypeScript,weswigham/TypeScript,nojvek/TypeScript,nojvek/TypeScript,kpreisser/TypeScript,microsoft/TypeScript,basarat/TypeScript,microsoft/TypeScript,Eyas/TypeScript,SaschaNaz/TypeScript,Microsoft/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,donaldpipowitch/TypeScript,TukekeSoft/TypeScript,SaschaNaz/TypeScript,microsoft/TypeScript
--- +++ @@ -8,3 +8,8 @@ var o2; /** @type {Object.<boolean, string>} */ var o3; +/** @param {Object.<string, boolean>} o */ +function f(o) { + o.foo = 1; // error + o.bar = false; // ok +}
a90081c2e23850fc94d91d0f7136c5e087abf2b1
src/app/public/ts/login.component.ts
src/app/public/ts/login.component.ts
import { Component, OnInit } from '@angular/core'; import { Socket } from '../../../services/socketio.service'; import { User } from '../../../services/user.service'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ templateUrl: '../html/login.component.html' }) export class Login implements OnInit { loginForm: FormGroup; constructor(private socket: Socket, public user: User, private formBuilder: FormBuilder) { this.loginForm = this.formBuilder.group({}); this.socket.socket.on('connection', (data: string) => { if(data) { this.socket.emit('ewAuth', {'token': data}); localStorage.setItem('token', data); } else { localStorage.removeItem('token'); } }); } ngOnInit() { this.loginForm = this.formBuilder.group({ username: '', password: '' }); setInterval(() => { if(this.user.getPropertyNb('mstatus') == 1) { document.location.href="/city"; } }, 1000); } onSubmit(data:object) { this.socket.emit('connection', data); } }
import { Component, OnInit } from '@angular/core'; import { Socket } from '../../../services/socketio.service'; import { User } from '../../../services/user.service'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ templateUrl: '../html/login.component.html' }) export class Login implements OnInit { loginForm: FormGroup; constructor(private socket: Socket, public user: User, private formBuilder: FormBuilder) { this.loginForm = this.formBuilder.group({}); this.socket.socket.on('connection', (data: string) => { if(data) { this.socket.emit('ewAuth', {'token': data}); localStorage.setItem('token', data); } else { localStorage.removeItem('token'); } }); } ngOnInit() { this.loginForm = this.formBuilder.group({ username: '', password: '' }); } onSubmit(data:object) { this.socket.emit('connection', data); } }
Remove crap redirect when connected
Remove crap redirect when connected
TypeScript
agpl-3.0
V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War
--- +++ @@ -30,12 +30,6 @@ username: '', password: '' }); - - setInterval(() => { - if(this.user.getPropertyNb('mstatus') == 1) { - document.location.href="/city"; - } - }, 1000); } onSubmit(data:object) {
69f883f252fb4122b061cdc0b74ef1e79faae644
frontend/site/src/lib/index.ts
frontend/site/src/lib/index.ts
import {Server, Config} from "./server"; /** * Load configuration file given as command line parameter */ let config: Config; if (process.argv.length > 2) { console.info("loading configuration file: " + process.argv[2]); config = require(process.argv[2]); if (process.argv.length > 3) { config.backend = process.argv[3]; } if (process.argv.length > 4){ config.generatedFilesPath = process.argv[4]; } if (process.env.EXTENDEDMIND_URL){ console.info("setting urlOrigin to: " + process.env.EXTENDEDMIND_URL); config.urlOrigin = process.env.EXTENDEDMIND_URL; } }else { console.error("no configuration file provided, exiting..."); process.exit(); }; const server = new Server(config); server.run();
import {Server, Config} from "./server"; /** * Load configuration file given as command line parameter */ let config: Config; if (process.argv.length > 2) { console.info("loading configuration file: " + process.argv[2]); config = require(process.argv[2]); if (process.argv.length > 3) { config.backend = process.argv[3]; } else if (process.env.EXTENDEDMIND_API_URL) { console.info("setting backend to: " + process.env.EXTENDEDMIND_API_URL); config.backend = process.env.EXTENDEDMIND_API_URL; } if (process.env.EXTENDEDMIND_URL){ console.info("setting urlOrigin to: " + process.env.EXTENDEDMIND_URL); config.urlOrigin = process.env.EXTENDEDMIND_URL; } }else { console.error("no configuration file provided, exiting..."); process.exit(); }; const server = new Server(config); server.run();
Add possibility to use EXTENDEDMIND_API_URL for backend address.
Add possibility to use EXTENDEDMIND_API_URL for backend address.
TypeScript
agpl-3.0
extendedmind/extendedmind,extendedmind/extendedmind,extendedmind/extendedmind,extendedmind/extendedmind,extendedmind/extendedmind,extendedmind/extendedmind,extendedmind/extendedmind
--- +++ @@ -9,9 +9,9 @@ config = require(process.argv[2]); if (process.argv.length > 3) { config.backend = process.argv[3]; - } - if (process.argv.length > 4){ - config.generatedFilesPath = process.argv[4]; + } else if (process.env.EXTENDEDMIND_API_URL) { + console.info("setting backend to: " + process.env.EXTENDEDMIND_API_URL); + config.backend = process.env.EXTENDEDMIND_API_URL; } if (process.env.EXTENDEDMIND_URL){ console.info("setting urlOrigin to: " + process.env.EXTENDEDMIND_URL);
36b2deb27edaaaaa8b29135c7fda1ccffd21579f
app/src/ui/notification/new-commits-banner.tsx
app/src/ui/notification/new-commits-banner.tsx
import * as React from 'react' import { ButtonGroup } from '../lib/button-group' import { Button } from '../lib/button' import { Ref } from '../lib/ref' import { Octicon, OcticonSymbol } from '../octicons' import { Branch } from '../../models/branch' interface INewCommitsBannerProps { /** * The number of commits behind `baseBranch` */ readonly commitsBehindBaseBranch: number /** * The target branch that will accept commits * from the current branch */ readonly baseBranch: Branch readonly onCompareClicked: () => void readonly onMergeClicked: () => void } /** * Banner used to notify user that there branch is _commitsBehind_ * commits behind `branch` */ export class NewCommitsBanner extends React.Component< INewCommitsBannerProps, {} > { public render() { return ( <div className="notification-banner diverge-banner"> <div className="notification-banner-content"> <p> Your branch is <strong>{this.props.commitsBehindBaseBranch} commits</strong>{' '} behind <Ref>{this.props.baseBranch.name}</Ref> </p> <a className="close" aria-label="Dismiss banner"> <Octicon symbol={OcticonSymbol.x} /> </a> </div> <ButtonGroup> <Button type="submit" onClick={this.props.onCompareClicked}> Compare </Button> <Button onClick={this.props.onMergeClicked}>Merge...</Button> </ButtonGroup> </div> ) } }
import * as React from 'react' import { ButtonGroup } from '../lib/button-group' import { Button } from '../lib/button' import { Ref } from '../lib/ref' import { Octicon, OcticonSymbol } from '../octicons' import { Branch } from '../../models/branch' interface INewCommitsBannerProps { /** * The number of commits behind `baseBranch` */ readonly commitsBehindBaseBranch: number /** * The target branch that will accept commits * from the current branch */ readonly baseBranch: Branch } /** * Banner used to notify user that there branch is _commitsBehind_ * commits behind `branch` */ export class NewCommitsBanner extends React.Component< INewCommitsBannerProps, {} > { public render() { return ( <div className="notification-banner diverge-banner"> <div className="notification-banner-content"> <p> Your branch is{' '} <strong>{this.props.commitsBehindBaseBranch} commits</strong> behind{' '} <Ref>{this.props.baseBranch.name}</Ref> </p> <a className="close" aria-label="Dismiss banner"> <Octicon symbol={OcticonSymbol.x} /> </a> </div> </div> ) } }
Remove CTA buttons and event handlers
Remove CTA buttons and event handlers
TypeScript
mit
artivilla/desktop,desktop/desktop,say25/desktop,kactus-io/kactus,say25/desktop,artivilla/desktop,kactus-io/kactus,shiftkey/desktop,say25/desktop,artivilla/desktop,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,kactus-io/kactus,j-f1/forked-desktop,j-f1/forked-desktop,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,desktop/desktop
--- +++ @@ -16,8 +16,6 @@ * from the current branch */ readonly baseBranch: Branch - readonly onCompareClicked: () => void - readonly onMergeClicked: () => void } /** @@ -33,22 +31,15 @@ <div className="notification-banner diverge-banner"> <div className="notification-banner-content"> <p> - Your branch is <strong>{this.props.commitsBehindBaseBranch} commits</strong>{' '} - behind <Ref>{this.props.baseBranch.name}</Ref> + Your branch is{' '} + <strong>{this.props.commitsBehindBaseBranch} commits</strong> behind{' '} + <Ref>{this.props.baseBranch.name}</Ref> </p> <a className="close" aria-label="Dismiss banner"> <Octicon symbol={OcticonSymbol.x} /> </a> </div> - - <ButtonGroup> - <Button type="submit" onClick={this.props.onCompareClicked}> - Compare - </Button> - - <Button onClick={this.props.onMergeClicked}>Merge...</Button> - </ButtonGroup> </div> ) }
b5299e3690f8a64a4963851fc92ceff8975014ff
src/vs/workbench/api/browser/mainThreadBulkEdits.ts
src/vs/workbench/api/browser/mainThreadBulkEdits.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IBulkEditService } from 'vs/editor/browser/services/bulkEditService'; import { IWorkspaceEditDto, MainThreadBulkEditsShape, MainContext } from 'vs/workbench/api/common/extHost.protocol'; import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers'; import { reviveWorkspaceEditDto2 } from 'vs/workbench/api/browser/mainThreadEditors'; import { ILogService } from 'vs/platform/log/common/log'; @extHostNamedCustomer(MainContext.MainThreadBulkEdits) export class MainThreadBulkEdits implements MainThreadBulkEditsShape { constructor( _extHostContext: IExtHostContext, @IBulkEditService private readonly _bulkEditService: IBulkEditService, @ILogService private readonly _logService: ILogService, ) { } dispose(): void { } $tryApplyWorkspaceEdit(dto: IWorkspaceEditDto, undoRedoGroupId?: number): Promise<boolean> { const edits = reviveWorkspaceEditDto2(dto); return this._bulkEditService.apply(edits, { undoRedoGroupId, respectAutoSaveConfig: true }).then(() => true, err => { this._logService.warn('IGNORING workspace edit', err); return false; }); } }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IBulkEditService } from 'vs/editor/browser/services/bulkEditService'; import { IWorkspaceEditDto, MainThreadBulkEditsShape, MainContext } from 'vs/workbench/api/common/extHost.protocol'; import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers'; import { reviveWorkspaceEditDto2 } from 'vs/workbench/api/browser/mainThreadEditors'; import { ILogService } from 'vs/platform/log/common/log'; @extHostNamedCustomer(MainContext.MainThreadBulkEdits) export class MainThreadBulkEdits implements MainThreadBulkEditsShape { constructor( _extHostContext: IExtHostContext, @IBulkEditService private readonly _bulkEditService: IBulkEditService, @ILogService private readonly _logService: ILogService, ) { } dispose(): void { } $tryApplyWorkspaceEdit(dto: IWorkspaceEditDto, undoRedoGroupId?: number): Promise<boolean> { const edits = reviveWorkspaceEditDto2(dto); return this._bulkEditService.apply(edits, { undoRedoGroupId }).then(() => true, err => { this._logService.warn('IGNORING workspace edit', err); return false; }); } }
Revert "respect auto save config when using workspace edit API"
Revert "respect auto save config when using workspace edit API" This reverts commit 22c5f41aab0eda67b6829c3a578e5856d2ee8c63.
TypeScript
mit
eamodio/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode
--- +++ @@ -22,7 +22,7 @@ $tryApplyWorkspaceEdit(dto: IWorkspaceEditDto, undoRedoGroupId?: number): Promise<boolean> { const edits = reviveWorkspaceEditDto2(dto); - return this._bulkEditService.apply(edits, { undoRedoGroupId, respectAutoSaveConfig: true }).then(() => true, err => { + return this._bulkEditService.apply(edits, { undoRedoGroupId }).then(() => true, err => { this._logService.warn('IGNORING workspace edit', err); return false; });
1cc4adcbdcf4b47f4b9ee6b89f5c5200bb7a27b7
examples/read-by-chunks-ts.ts
examples/read-by-chunks-ts.ts
import { PromiseReadable } from '../lib/promise-readable' import { createReadStream } from 'fs' type Chunk = Buffer | undefined async function main () { const rstream = new PromiseReadable(createReadStream(process.argv[2] || '/etc/hosts', { highWaterMark: Number(process.argv[3]) || 1024 })) let total = 0 for (let chunk: Chunk; (chunk = await rstream.read());) { console.info(`Read ${chunk.length} bytes chunk`) total += chunk.length } console.info(`Read ${total} bytes in total`) rstream.destroy() } main().catch(console.error)
import { PromiseReadable } from '../lib/promise-readable' import { createReadStream } from 'fs' type Chunk = Buffer | string | undefined async function main () { const rstream = new PromiseReadable(createReadStream(process.argv[2] || '/etc/hosts', { highWaterMark: Number(process.argv[3]) || 1024 })) let total = 0 for (let chunk: Chunk; (chunk = await rstream.read());) { console.info(`Read ${chunk.length} bytes chunk`) total += chunk.length } console.info(`Read ${total} bytes in total`) rstream.destroy() } main().catch(console.error)
Tweak types for example script
Tweak types for example script
TypeScript
mit
dex4er/js-promise-readable,dex4er/js-promise-readable
--- +++ @@ -2,7 +2,7 @@ import { createReadStream } from 'fs' -type Chunk = Buffer | undefined +type Chunk = Buffer | string | undefined async function main () { const rstream = new PromiseReadable(createReadStream(process.argv[2] || '/etc/hosts', {
b463a8c86b84099ef3ef766ccad12055cda0b831
typings/tests/component-type-test.tsx
typings/tests/component-type-test.tsx
import styled from "../.."; declare const A: React.ComponentClass; declare const B: React.StatelessComponent; declare const C: React.ComponentClass | React.StatelessComponent; styled(A); // succeeds styled(B); // succeeds styled(C); // used to fail; see issue trail linked below // https://github.com/mui-org/material-ui/pull/8781#issuecomment-349460247 // https://github.com/mui-org/material-ui/issues/9838 // https://github.com/styled-components/styled-components/pull/1420 // https://github.com/Microsoft/TypeScript/issues/21175 // https://github.com/styled-components/styled-components/pull/1427
import styled from "../.."; declare const A: React.ComponentClass; declare const B: React.StatelessComponent; declare const C: React.ComponentType; styled(A); // succeeds styled(B); // succeeds styled(C); // used to fail; see issue trail linked below // https://github.com/mui-org/material-ui/pull/8781#issuecomment-349460247 // https://github.com/mui-org/material-ui/issues/9838 // https://github.com/styled-components/styled-components/pull/1420 // https://github.com/Microsoft/TypeScript/issues/21175 // https://github.com/styled-components/styled-components/pull/1427
Use React.ComponentType type in test
Use React.ComponentType type in test
TypeScript
mit
styled-components/styled-components,JamieDixon/styled-components,css-components/styled-components,styled-components/styled-components,JamieDixon/styled-components,JamieDixon/styled-components,styled-components/styled-components
--- +++ @@ -2,7 +2,7 @@ declare const A: React.ComponentClass; declare const B: React.StatelessComponent; -declare const C: React.ComponentClass | React.StatelessComponent; +declare const C: React.ComponentType; styled(A); // succeeds styled(B); // succeeds
d7e4fdab026da1dd665dacf2b29ce40873c4b095
docs/src/siteConfig.tsx
docs/src/siteConfig.tsx
// List of projects/orgs using your project for the users page. export const siteConfig = { editUrl: 'https://github.com/formik/formik/edit/master', copyright: `Copyright Β© ${new Date().getFullYear()} Jared Palmer. All Rights Reserved.`, repoUrl: 'https://github.com/formik/formik', algolia: { appId: 'BH4D9OD16A', apiKey: '32fabc38a054677ee9b24e69d699fbd0', indexName: 'formik', // algoliaOptions: { // facetFilters: ['version:VERSION'], // }, }, };
// List of projects/orgs using your project for the users page. export const siteConfig = { editUrl: 'https://github.com/formik/formik/edit/master/docs/src/pages', copyright: `Copyright Β© ${new Date().getFullYear()} Jared Palmer. All Rights Reserved.`, repoUrl: 'https://github.com/formik/formik', algolia: { appId: 'BH4D9OD16A', apiKey: '32fabc38a054677ee9b24e69d699fbd0', indexName: 'formik', // algoliaOptions: { // facetFilters: ['version:VERSION'], // }, }, };
Fix Docs: correct github edit URL
Fix Docs: correct github edit URL
TypeScript
apache-2.0
jaredpalmer/formik,jaredpalmer/formik,jaredpalmer/formik
--- +++ @@ -1,7 +1,7 @@ // List of projects/orgs using your project for the users page. export const siteConfig = { - editUrl: 'https://github.com/formik/formik/edit/master', + editUrl: 'https://github.com/formik/formik/edit/master/docs/src/pages', copyright: `Copyright Β© ${new Date().getFullYear()} Jared Palmer. All Rights Reserved.`, repoUrl: 'https://github.com/formik/formik', algolia: {
e36173ac848fc062ea3dd81fb3f4fe22f4d2753f
src/game/components/PlayerInfo.tsx
src/game/components/PlayerInfo.tsx
import * as React from "react"; import { Small, Text } from "rebass"; import InfoPane from "game/components/InfoPane"; import Player from "models/player"; import { TerritoryAction, TerritoryActionDefinitions, ColourStrings } from "models/values"; type PlayerInfoProps = { player: Player; isActive: boolean; }; const PlayerInfo: React.StatelessComponent<PlayerInfoProps> = ({ player, isActive }) => { return ( <InfoPane> <Text color={ColourStrings[player.data.colour]}> Player {player.data.id} <Small color="black">{isActive ? "(Active)" : ""}</Small> </Text> <Small> <Text> Gold {player.data.gold} (+{player.data.goldProduction + player.territories.map(territory => territory.data.goldProduction).reduce((a, b) => a + b, 0)}) </Text> <Text>{player.data.ready ? "Ready" : "Not Ready"}</Text> </Small> </InfoPane> ); }; export default PlayerInfo;
import * as React from 'react'; import { Small, Text } from 'rebass'; import InfoPane from 'game/components/InfoPane'; import Player from 'models/player'; import { TerritoryAction, TerritoryActionDefinitions, ColourStrings } from 'models/values'; type PlayerInfoProps = { player: Player; isActive: boolean; }; const PlayerInfo: React.StatelessComponent<PlayerInfoProps> = ({ player, isActive }) => { return ( <InfoPane> <Text color={ColourStrings[player.data.colour]}> Player {player.data.id} <Small color="black">{isActive ? '(Active)' : ''}</Small> </Text> <Small> <Text> Gold {player.data.gold} (+{player.data.goldProduction + player.territories.map(territory => territory.data.goldProduction).reduce((a, b) => a + b, 0)}) </Text> <Text>Victory Points {player.victoryPoints}</Text> <Text>{player.data.ready ? 'Ready' : 'Not Ready'}</Text> </Small> </InfoPane> ); }; export default PlayerInfo;
Add victory points to player info
Add victory points to player info
TypeScript
mit
tomwwright/graph-battles,tomwwright/graph-battles,tomwwright/graph-battles
--- +++ @@ -1,8 +1,8 @@ -import * as React from "react"; -import { Small, Text } from "rebass"; -import InfoPane from "game/components/InfoPane"; -import Player from "models/player"; -import { TerritoryAction, TerritoryActionDefinitions, ColourStrings } from "models/values"; +import * as React from 'react'; +import { Small, Text } from 'rebass'; +import InfoPane from 'game/components/InfoPane'; +import Player from 'models/player'; +import { TerritoryAction, TerritoryActionDefinitions, ColourStrings } from 'models/values'; type PlayerInfoProps = { player: Player; @@ -13,14 +13,15 @@ return ( <InfoPane> <Text color={ColourStrings[player.data.colour]}> - Player {player.data.id} <Small color="black">{isActive ? "(Active)" : ""}</Small> + Player {player.data.id} <Small color="black">{isActive ? '(Active)' : ''}</Small> </Text> <Small> <Text> Gold {player.data.gold} (+{player.data.goldProduction + player.territories.map(territory => territory.data.goldProduction).reduce((a, b) => a + b, 0)}) </Text> - <Text>{player.data.ready ? "Ready" : "Not Ready"}</Text> + <Text>Victory Points {player.victoryPoints}</Text> + <Text>{player.data.ready ? 'Ready' : 'Not Ready'}</Text> </Small> </InfoPane> );
42bc9a17621d1a94e939d07c8b76de7340b109f6
functions/src/twitter/twitter-data.ts
functions/src/twitter/twitter-data.ts
import { Optional } from "../optional"; export interface SearchResult { statuses: Tweet[] } export interface Tweet { id_str: string full_text: string created_at: string display_text_range: [number, number] user: User entities: Entities retweeted_status: any in_reply_to_screen_name: Optional<string> } export interface User { id_str: string name: string screen_name: string profile_image_url_https: string } export interface Entities { hashtags: Optional<HashtagsEntity[]> urls: Optional<UrlsEntity[]> media: Optional<MediaEntity[]> user_mentions: Optional<UserMention[]> } export interface HashtagsEntity { text: string indices: [number, number] } export interface UrlsEntity { expanded_url: string display_url: string url: string indices: [number, number] } export interface MediaEntity { id: number id_str: string indices: [number, number] media_url_https: string url: string display_url: string expanded_url: string type: string sizes: { medium: MediaSize thumb: MediaSize large: MediaSize small: MediaSize } } export interface MediaSize { w: number h: number resize: string } export interface UserMention { screen_name: string name: string id: number id_str: string indices: [number, number] }
import { Optional } from "../optional"; export interface SearchResult { statuses: Tweet[] } export interface Tweet { id_str: string full_text: string created_at: string display_text_range: [number, number] user: User entities: Entities retweeted_status: Optional<string> in_reply_to_screen_name: Optional<string> } export interface User { id_str: string name: string screen_name: string profile_image_url_https: string } export interface Entities { hashtags: Optional<HashtagsEntity[]> urls: Optional<UrlsEntity[]> media: Optional<MediaEntity[]> user_mentions: Optional<UserMention[]> } export interface HashtagsEntity { text: string indices: [number, number] } export interface UrlsEntity { expanded_url: string display_url: string url: string indices: [number, number] } export interface MediaEntity { id: number id_str: string indices: [number, number] media_url_https: string url: string display_url: string expanded_url: string type: string sizes: { medium: MediaSize thumb: MediaSize large: MediaSize small: MediaSize } } export interface MediaSize { w: number h: number resize: string } export interface UserMention { screen_name: string name: string id: number id_str: string indices: [number, number] }
Use correct model for retweeted_status
Use correct model for retweeted_status
TypeScript
apache-2.0
squanchy-dev/squanchy-firebase,squanchy-dev/squanchy-firebase
--- +++ @@ -11,7 +11,7 @@ display_text_range: [number, number] user: User entities: Entities - retweeted_status: any + retweeted_status: Optional<string> in_reply_to_screen_name: Optional<string> }
8ab52830debdcb6a3f482001bf756fc23b16ad7e
src/app/config-store/config-store.service.ts
src/app/config-store/config-store.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class ConfigStoreService { _bpm: number; _offset: number; constructor() { this._bpm = 150; this._offset = 0.247; } get bpm(): number { return this._bpm; } set bpm(bpm: number) { this._bpm = bpm; } get offset(): number { return this._offset; } set offset(offset: number) { this._offset = offset; } }
import { Injectable } from '@angular/core'; @Injectable() export class ConfigStoreService { _bpm: number; _offset: number; constructor() { this._bpm = 60; this._offset = 0; } get bpm(): number { return this._bpm; } set bpm(bpm: number) { this._bpm = bpm; } get offset(): number { return this._offset; } set offset(offset: number) { this._offset = offset; } }
Change default bpm and offset
feat: Change default bpm and offset
TypeScript
mit
nb48/chart-hero,nb48/chart-hero,nb48/chart-hero
--- +++ @@ -7,8 +7,8 @@ _offset: number; constructor() { - this._bpm = 150; - this._offset = 0.247; + this._bpm = 60; + this._offset = 0; } get bpm(): number {
dbebb81aa8aefae09ec04c369b2a12bc225a0024
packages/core/src/core/routes/convert-error-to-response.ts
packages/core/src/core/routes/convert-error-to-response.ts
import { renderError } from '../../common'; import { IAppController } from '../app.controller.interface'; import { Config } from '../config'; import { Context, HttpResponse } from '../http'; export async function convertErrorToResponse( error: Error, ctx: Context, appController: IAppController, log = console.error ): Promise<HttpResponse> { if (Config.get('settings.logErrors', 'boolean', true)) { log(error.stack); } if (appController.handleError) { try { return await appController.handleError(error, ctx); } catch (error2) { return renderError(error2, ctx); } } return renderError(error, ctx); }
import { renderError } from '../../common'; import { IAppController } from '../app.controller.interface'; import { Config } from '../config'; import { Context, HttpResponse } from '../http'; export async function convertErrorToResponse( error: Error, ctx: Context, appController: IAppController, log = console.error ): Promise<HttpResponse> { if (Config.get('settings.logErrors', 'boolean', true)) { log(error.stack); } if (appController.handleError) { try { return await appController.handleError(error, ctx); } catch (error2: any) { return renderError(error2, ctx); } } return renderError(error, ctx); }
Fix core to support strict [email protected]
Fix core to support strict [email protected]
TypeScript
mit
FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal
--- +++ @@ -13,7 +13,7 @@ if (appController.handleError) { try { return await appController.handleError(error, ctx); - } catch (error2) { + } catch (error2: any) { return renderError(error2, ctx); } }
59c836c45d89f9d5342b248f47f3deef73369405
apps/portal/prisma/seed-analysis.ts
apps/portal/prisma/seed-analysis.ts
import { PrismaClient } from '@prisma/client'; import { generateAnalysis } from '../src/utils/offers/analysis/analysisGeneration'; const prisma = new PrismaClient(); const seedAnalysis = async () => { console.log('Busy crunching analysis.....'); const profilesWithoutAnalysis = await prisma.offersProfile.findMany({ where: { analysis: { is: null, }, }, }); for (const profile of profilesWithoutAnalysis) { await generateAnalysis({ ctx: { prisma, session: null }, input: { profileId: profile.id }, }); console.log('Analysis generated for profile with id:', profile.id); } }; Promise.all([seedAnalysis()]) .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); console.log('Analysis stopping!'); await prisma.$disconnect(); process.exit(1); }); export {};
import { PrismaClient } from '@prisma/client'; import { generateAnalysis } from '../src/utils/offers/analysis/analysisGeneration'; const prisma = new PrismaClient(); const seedAnalysis = async () => { console.log('Busy crunching analysis.....'); const profilesWithoutAnalysis = await prisma.offersProfile.findMany({ where: { analysis: { is: null, }, }, }); console.log( 'Number of profiles found without analysis:', profilesWithoutAnalysis.length, ); let i = 0; while (i < profilesWithoutAnalysis.length) { const profile = profilesWithoutAnalysis[i]; await generateAnalysis({ ctx: { prisma, session: null }, input: { profileId: profile.id }, }); i++; console.log(i, ': Analysis generated for profile with id', profile.id); } console.log(i, ' analysis generated'); }; Promise.all([seedAnalysis()]) .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); console.log('Analysis stopping!'); await prisma.$disconnect(); process.exit(1); }); export {};
Add logging for seed analysis
[offers][chore] Add logging for seed analysis
TypeScript
mit
yangshun/tech-interview-handbook,yangshun/tech-interview-handbook,yangshun/tech-interview-handbook,yangshun/tech-interview-handbook,yangshun/tech-interview-handbook
--- +++ @@ -14,13 +14,26 @@ }, }); - for (const profile of profilesWithoutAnalysis) { + console.log( + 'Number of profiles found without analysis:', + profilesWithoutAnalysis.length, + ); + + let i = 0; + + while (i < profilesWithoutAnalysis.length) { + const profile = profilesWithoutAnalysis[i]; await generateAnalysis({ ctx: { prisma, session: null }, input: { profileId: profile.id }, }); - console.log('Analysis generated for profile with id:', profile.id); + + i++; + + console.log(i, ': Analysis generated for profile with id', profile.id); } + + console.log(i, ' analysis generated'); }; Promise.all([seedAnalysis()])
ece31c291538f6871dc2291cefab18f6b8594cd4
packages/components/containers/filePreview/helpers.ts
packages/components/containers/filePreview/helpers.ts
import { isSafari, hasPDFSupport } from '@proton/shared/lib/helpers/browser'; export const isSupportedImage = (mimeType: string) => [ 'image/apng', 'image/bmp', 'image/gif', 'image/x-icon', 'image/vnd.microsoft.icon', 'image/jpeg', 'image/png', 'image/svg+xml', !isSafari() && 'image/webp', ] .filter(Boolean) .includes(mimeType); export const isSupportedText = (mimeType: string) => mimeType.startsWith('text/') || ['application/javascript', 'application/typescript'].includes(mimeType); export const isVideo = (mimeType: string) => mimeType.startsWith('video/'); export const isICS = (mimeType: string) => mimeType.startsWith('text/calendar'); export const isPDF = (mimeType: string) => mimeType === 'application/pdf' || mimeType === 'x-pdf'; // Will include more rules in the future export const isPreviewAvailable = (mimeType: string) => isSupportedImage(mimeType) || isSupportedText(mimeType) || (hasPDFSupport() && isPDF(mimeType));
import { hasPDFSupport, getBrowser } from '@proton/shared/lib/helpers/browser'; const isWebpSupported = () => { const { name, version } = getBrowser(); if (name === 'Safari') { /* * The support for WebP image format became available in Safari 14. * It is not possible to support webp images in older Safari versions. * https://developer.apple.com/documentation/safari-release-notes/safari-14-release-notes */ return Number(version?.split('.')[0]) >= 14; } return true; }; export const isSupportedImage = (mimeType: string) => [ 'image/apng', 'image/bmp', 'image/gif', 'image/x-icon', 'image/vnd.microsoft.icon', 'image/jpeg', 'image/png', 'image/svg+xml', isWebpSupported() && 'image/webp', ] .filter(Boolean) .includes(mimeType); export const isSupportedText = (mimeType: string) => mimeType.startsWith('text/') || ['application/javascript', 'application/typescript'].includes(mimeType); export const isVideo = (mimeType: string) => mimeType.startsWith('video/'); export const isICS = (mimeType: string) => mimeType.startsWith('text/calendar'); export const isPDF = (mimeType: string) => mimeType === 'application/pdf' || mimeType === 'x-pdf'; // Will include more rules in the future export const isPreviewAvailable = (mimeType: string) => isSupportedImage(mimeType) || isSupportedText(mimeType) || (hasPDFSupport() && isPDF(mimeType));
Make image thumbnails available in Safari 14
Make image thumbnails available in Safari 14 DRVWEB-1229
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -1,4 +1,19 @@ -import { isSafari, hasPDFSupport } from '@proton/shared/lib/helpers/browser'; +import { hasPDFSupport, getBrowser } from '@proton/shared/lib/helpers/browser'; + +const isWebpSupported = () => { + const { name, version } = getBrowser(); + + if (name === 'Safari') { + /* + * The support for WebP image format became available in Safari 14. + * It is not possible to support webp images in older Safari versions. + * https://developer.apple.com/documentation/safari-release-notes/safari-14-release-notes + */ + return Number(version?.split('.')[0]) >= 14; + } + + return true; +}; export const isSupportedImage = (mimeType: string) => [ @@ -10,7 +25,7 @@ 'image/jpeg', 'image/png', 'image/svg+xml', - !isSafari() && 'image/webp', + isWebpSupported() && 'image/webp', ] .filter(Boolean) .includes(mimeType);
2aa781983bd55f175ca6333ad4e12af98cbf6c40
packages/lesswrong/components/posts/BookmarksList.tsx
packages/lesswrong/components/posts/BookmarksList.tsx
import { registerComponent, Components } from '../../lib/vulcan-lib'; import { useSingle } from '../../lib/crud/withSingle'; import React from 'react'; import { useCurrentUser } from '../common/withUser'; import Users from '../../lib/collections/users/collection'; import withErrorBoundary from '../common/withErrorBoundary'; const BookmarksList = ({limit=50 }) => { const currentUser = useCurrentUser(); const { PostsItem2, Loading } = Components const { document: user, loading } = useSingle({ collection: Users, fragmentName: 'UserBookmarks', fetchPolicy: 'cache-then-network' as any, //FIXME documentId: currentUser!._id, }); let bookmarkedPosts = user?.bookmarkedPosts || [] bookmarkedPosts = bookmarkedPosts.reverse().slice(0, limit) if (loading) return <Loading/> return ( <div> {bookmarkedPosts.map((post) => <PostsItem2 key={post._id} post={post} bookmark/>)} </div> ) } const BookmarksListComponent = registerComponent('BookmarksList', BookmarksList, { hocs: [withErrorBoundary] }); declare global { interface ComponentTypes { BookmarksList: typeof BookmarksListComponent } }
import { registerComponent, Components } from '../../lib/vulcan-lib'; import { useSingle } from '../../lib/crud/withSingle'; import React from 'react'; import { useCurrentUser } from '../common/withUser'; import Users from '../../lib/collections/users/collection'; import withErrorBoundary from '../common/withErrorBoundary'; const BookmarksList = ({limit=50 }) => { const currentUser = useCurrentUser(); const { PostsItem2, Loading } = Components const { document: user, loading } = useSingle({ collection: Users, fragmentName: 'UserBookmarks', fetchPolicy: 'cache-then-network' as any, //FIXME documentId: currentUser!._id, }); let bookmarkedPosts = user?.bookmarkedPosts || [] bookmarkedPosts = [...bookmarkedPosts].reverse().slice(0, limit) if (loading) return <Loading/> return ( <div> {bookmarkedPosts.map((post) => <PostsItem2 key={post._id} post={post} bookmark/>)} </div> ) } const BookmarksListComponent = registerComponent('BookmarksList', BookmarksList, { hocs: [withErrorBoundary] }); declare global { interface ComponentTypes { BookmarksList: typeof BookmarksListComponent } }
Fix bookmarks being broken by sketchy Array.reverse Javascript core-library function
Fix bookmarks being broken by sketchy Array.reverse Javascript core-library function
TypeScript
mit
Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -17,7 +17,7 @@ }); let bookmarkedPosts = user?.bookmarkedPosts || [] - bookmarkedPosts = bookmarkedPosts.reverse().slice(0, limit) + bookmarkedPosts = [...bookmarkedPosts].reverse().slice(0, limit) if (loading) return <Loading/>
f768beacd16403c0f1502cb7957599c31c02a4ce
src/openstack/openstack-security-groups/SecurityGroupsList.tsx
src/openstack/openstack-security-groups/SecurityGroupsList.tsx
import * as React from 'react'; import { NestedListActions } from '@waldur/resource/actions/NestedListActions'; import { ResourceRowActions } from '@waldur/resource/actions/ResourceRowActions'; import { ResourceName } from '@waldur/resource/ResourceName'; import { ResourceState } from '@waldur/resource/state/ResourceState'; import { Table, connectTable, createFetcher } from '@waldur/table-react'; const TableComponent = props => { const { translate } = props; return ( <Table {...props} columns={[ { title: translate('Name'), render: ({ row }) => <ResourceName resource={row} />, }, { title: translate('State'), render: ({ row }) => <ResourceState resource={row} />, }, { title: translate('Actions'), render: ({ row }) => <ResourceRowActions resource={row} />, }, ]} verboseName={translate('security groups')} actions={ <NestedListActions resource={props.resource} tab="security_groups" /> } /> ); }; const TableOptions = { table: 'openstack-security-groups', fetchData: createFetcher('openstack-security-groups'), mapPropsToFilter: props => ({ tenant_uuid: props.resource.uuid, }), }; export const SecurityGroupsList = connectTable(TableOptions)(TableComponent);
import * as React from 'react'; import { NestedListActions } from '@waldur/resource/actions/NestedListActions'; import { ResourceRowActions } from '@waldur/resource/actions/ResourceRowActions'; import { ResourceName } from '@waldur/resource/ResourceName'; import { ResourceState } from '@waldur/resource/state/ResourceState'; import { Table, connectTable, createFetcher } from '@waldur/table-react'; const TableComponent = props => { const { translate } = props; return ( <Table {...props} columns={[ { title: translate('Name'), render: ({ row }) => <ResourceName resource={row} />, }, { title: translate('State'), render: ({ row }) => <ResourceState resource={row} />, className: 'col-sm-2', }, { title: translate('Actions'), render: ({ row }) => <ResourceRowActions resource={row} />, className: 'col-sm-2', }, ]} verboseName={translate('security groups')} actions={ <NestedListActions resource={props.resource} tab="security_groups" /> } /> ); }; const TableOptions = { table: 'openstack-security-groups', fetchData: createFetcher('openstack-security-groups'), mapPropsToFilter: props => ({ tenant_uuid: props.resource.uuid, }), }; export const SecurityGroupsList = connectTable(TableOptions)(TableComponent);
Improve layout of actions in security group tab.
Improve layout of actions in security group tab.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -19,10 +19,12 @@ { title: translate('State'), render: ({ row }) => <ResourceState resource={row} />, + className: 'col-sm-2', }, { title: translate('Actions'), render: ({ row }) => <ResourceRowActions resource={row} />, + className: 'col-sm-2', }, ]} verboseName={translate('security groups')}
8bc92e4a6363804436dba0dc37b33b1d862019bd
tests/cases/fourslash/codeFixAddMissingMember9.ts
tests/cases/fourslash/codeFixAddMissingMember9.ts
/// <reference path='fourslash.ts' /> ////class C { //// z: boolean = true; //// method() { //// const x = 0; //// this.y(x, "a", this.z); //// } ////} verify.codeFixAll({ fixId: "addMissingMember", newFileContent: `class C { y(x: number, arg1: string, z: boolean): any { throw new Error("Method not implemented."); } z: boolean = true; method() { const x = 0; this.y(x, "a", this.z); } }`, });
/// <reference path='fourslash.ts' /> ////class C { //// z: boolean = true; //// method() { //// const x = 0; //// this.y(x, "a", this.z); //// } ////} verify.codeFixAll({ fixId: "addMissingMember", fixAllDescription: "Add all missing members", newFileContent: `class C { z: boolean = true; method() { const x = 0; this.y(x, "a", this.z); } y(x: number, arg1: string, z: boolean): any { throw new Error("Method not implemented."); } }`, });
Update test to reflect new behavior
Update test to reflect new behavior
TypeScript
apache-2.0
kpreisser/TypeScript,RyanCavanaugh/TypeScript,SaschaNaz/TypeScript,weswigham/TypeScript,weswigham/TypeScript,basarat/TypeScript,kpreisser/TypeScript,alexeagle/TypeScript,RyanCavanaugh/TypeScript,basarat/TypeScript,SaschaNaz/TypeScript,alexeagle/TypeScript,minestarks/TypeScript,Microsoft/TypeScript,SaschaNaz/TypeScript,alexeagle/TypeScript,microsoft/TypeScript,nojvek/TypeScript,donaldpipowitch/TypeScript,kitsonk/TypeScript,microsoft/TypeScript,basarat/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,minestarks/TypeScript,kitsonk/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,weswigham/TypeScript,donaldpipowitch/TypeScript,Microsoft/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,microsoft/TypeScript,nojvek/TypeScript,basarat/TypeScript,nojvek/TypeScript,Microsoft/TypeScript
--- +++ @@ -10,15 +10,16 @@ verify.codeFixAll({ fixId: "addMissingMember", + fixAllDescription: "Add all missing members", newFileContent: `class C { - y(x: number, arg1: string, z: boolean): any { - throw new Error("Method not implemented."); - } z: boolean = true; method() { const x = 0; this.y(x, "a", this.z); } + y(x: number, arg1: string, z: boolean): any { + throw new Error("Method not implemented."); + } }`, });
a9a8ca699bf6d33987d375faf04955d80734722a
srcts/react-bootstrap-datatable/TableHead.tsx
srcts/react-bootstrap-datatable/TableHead.tsx
/// <reference path="../../typings/react/react.d.ts"/> /// <reference path="../../typings/react-bootstrap/react-bootstrap.d.ts"/> /// <reference path="../../typings/lodash/lodash.d.ts"/> import * as React from "react"; import {Table} from "react-bootstrap"; export interface IColumnTitles { [columnId: string] : string } interface ITableHeadProps extends React.Props<TableHead> { columnTitles:IColumnTitles; showIdColumn:boolean; idProperty:string; } interface ITableHeadState { } export default class TableHead extends React.Component<ITableHeadProps, ITableHeadState> { constructor(props:ITableHeadProps) { super(props); } render():JSX.Element { var headers:JSX.Element[] = []; var keys:string[] = Object.keys(this.props.columnTitles); if(!this.props.showIdColumn) { keys.splice(keys.indexOf(this.props.idProperty), 1); } headers = keys.map((columnId:string) => { return <th key={columnId}>{this.props.columnTitles[columnId]}</th>; }); return ( <thead className="table-header"> <tr> { headers } </tr> </thead> ); } }
/// <reference path="../../typings/react/react.d.ts"/> /// <reference path="../../typings/react-bootstrap/react-bootstrap.d.ts"/> /// <reference path="../../typings/lodash/lodash.d.ts"/> /// <reference path="../../typings/react-vendor-prefix/react-vendor-prefix.d.ts"/> import * as React from "react"; import {Table} from "react-bootstrap"; import {CSSProperties} from "react"; import * as Prefixer from "react-vendor-prefix"; export interface IColumnTitles { [columnId: string] : string } interface ITableHeadProps extends React.Props<TableHead> { columnTitles:IColumnTitles; showIdColumn:boolean; idProperty:string; } interface ITableHeadState { } const baseStyle:CSSProperties = { userSelect: "none" }; export default class TableHead extends React.Component<ITableHeadProps, ITableHeadState> { constructor(props:ITableHeadProps) { super(props); } render():JSX.Element { var headers:JSX.Element[] = []; var keys:string[] = Object.keys(this.props.columnTitles); if(!this.props.showIdColumn) { keys.splice(keys.indexOf(this.props.idProperty), 1); } headers = keys.map((columnId:string) => { return <th key={columnId}>{this.props.columnTitles[columnId]}</th>; }); return ( <thead className="table-header" style={Prefixer.prefix({styles: baseStyle}).styles} > <tr> { headers } </tr> </thead> ); } }
Fix to make Table Header text not selectable
Fix to make Table Header text not selectable
TypeScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
--- +++ @@ -1,9 +1,12 @@ /// <reference path="../../typings/react/react.d.ts"/> /// <reference path="../../typings/react-bootstrap/react-bootstrap.d.ts"/> /// <reference path="../../typings/lodash/lodash.d.ts"/> +/// <reference path="../../typings/react-vendor-prefix/react-vendor-prefix.d.ts"/> import * as React from "react"; import {Table} from "react-bootstrap"; +import {CSSProperties} from "react"; +import * as Prefixer from "react-vendor-prefix"; export interface IColumnTitles { [columnId: string] : string @@ -18,6 +21,10 @@ interface ITableHeadState { } + +const baseStyle:CSSProperties = { + userSelect: "none" +}; export default class TableHead extends React.Component<ITableHeadProps, ITableHeadState> { @@ -38,7 +45,7 @@ }); return ( - <thead className="table-header"> + <thead className="table-header" style={Prefixer.prefix({styles: baseStyle}).styles} > <tr> { headers
fe6b6b198ff51764d63b6a67e025c163882381a5
app/javascript/retrospring/features/moderation/destroy.ts
app/javascript/retrospring/features/moderation/destroy.ts
import Rails from '@rails/ujs'; import swal from 'sweetalert'; import I18n from 'retrospring/i18n'; import { showNotification, showErrorNotification } from 'utilities/notifications'; export function destroyReportHandler(event: Event): void { const button = event.target as HTMLButtonElement; const id = button.dataset.id; swal({ title: I18n.translate('frontend.destroy_report.confirm.title'), text: I18n.translate('frontend.destroy_report.confirm.text'), type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: I18n.translate('voc.delete'), cancelButtonText: I18n.translate('voc.cancel'), closeOnConfirm: true }, () => { Rails.ajax({ url: '/ajax/mod/destroy_report', type: 'POST', data: new URLSearchParams({ id: id }).toString(), success: (data) => { if (data.success) { document.querySelector(`.moderationbox[data-id="${id}"]`).remove(); } showNotification(data.message, data.success); }, error: (data, status, xhr) => { console.log(data, status, xhr); showErrorNotification(I18n.translate('frontend.error.message')); } }); }); }
import { post } from '@rails/request.js'; import swal from 'sweetalert'; import I18n from 'retrospring/i18n'; import { showNotification, showErrorNotification } from 'utilities/notifications'; export function destroyReportHandler(event: Event): void { const button = event.target as HTMLButtonElement; const id = button.dataset.id; swal({ title: I18n.translate('frontend.destroy_report.confirm.title'), text: I18n.translate('frontend.destroy_report.confirm.text'), type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: I18n.translate('voc.delete'), cancelButtonText: I18n.translate('voc.cancel'), closeOnConfirm: true }, () => { post('/ajax/mod/destroy_report', { body: { id: id }, contentType: 'application/json' }) .then(async response => { const data = await response.json; if (data.success) { document.querySelector(`.moderationbox[data-id="${id}"]`).remove(); } showNotification(data.message, data.success); }) .catch(err => { console.log(err); showErrorNotification(I18n.translate('frontend.error.message')); }); }); }
Refactor report removal to use request.js
Refactor report removal to use request.js
TypeScript
agpl-3.0
Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring
--- +++ @@ -1,4 +1,4 @@ -import Rails from '@rails/ujs'; +import { post } from '@rails/request.js'; import swal from 'sweetalert'; import I18n from 'retrospring/i18n'; @@ -18,22 +18,24 @@ cancelButtonText: I18n.translate('voc.cancel'), closeOnConfirm: true }, () => { - Rails.ajax({ - url: '/ajax/mod/destroy_report', - type: 'POST', - data: new URLSearchParams({ + post('/ajax/mod/destroy_report', { + body: { id: id - }).toString(), - success: (data) => { + }, + contentType: 'application/json' + }) + .then(async response => { + const data = await response.json; + if (data.success) { document.querySelector(`.moderationbox[data-id="${id}"]`).remove(); } + showNotification(data.message, data.success); - }, - error: (data, status, xhr) => { - console.log(data, status, xhr); + }) + .catch(err => { + console.log(err); showErrorNotification(I18n.translate('frontend.error.message')); - } - }); + }); }); }
599b14d9c546e84665ce311a65f763f9f606d687
src/components/contact/list.tsx
src/components/contact/list.tsx
import * as React from "react"; import { Contact } from "models/contact"; import { RemoveContact } from "actions/contacts"; import { Component } from "component"; export interface Props { editable: boolean } export interface State { contacts: Contact[]; } export interface Events { remove: (contactIndex: number) => () => void; } export default Component<Props, State, Events>( state => ({ contacts: state.contacts }), dispatch => ({ remove: (contactIndex: number) => () => { dispatch(RemoveContact(contactIndex)) } }), props => <ul> {props.contacts.map((contact, index) => <li> <p>Name: {contact.name.given} {contact.name.family}</p> <p>Email: {contact.email}</p> <button onClick={props.remove(index)}>Remove</button> </li> )} </ul> );
import * as React from "react"; import { Contact } from "models/contact"; import { RemoveContact } from "actions/contacts"; import { Component } from "component"; export interface Props { editable: boolean } export interface State { contacts: Contact[]; } export interface Events { remove: (contactIndex: number) => () => void; } export default Component<Props, State, Events>( state => ({ contacts: state.contacts }), dispatch => ({ remove: (contactIndex: number) => () => { dispatch(RemoveContact(contactIndex)) } }), props => <ul> { props .contacts // Sort contacts by last name alphabetically .sort( (a, b) => a.name.family < b.name.family ? -1 : a.name.family > b.name.family ? 1 : 0 ) // Render contact .map((contact, index) => <li> <p>Name: {contact.name.given} {contact.name.family}</p> <p>Email: {contact.email}</p> <button onClick={props.remove(index)}>Remove</button> </li> )} </ul> );
Sort contacts alphabetically by last name
Sort contacts alphabetically by last name
TypeScript
mit
luk707/address_book,luk707/address_book
--- +++ @@ -26,12 +26,23 @@ }), props => <ul> - {props.contacts.map((contact, index) => - <li> - <p>Name: {contact.name.given} {contact.name.family}</p> - <p>Email: {contact.email}</p> - <button onClick={props.remove(index)}>Remove</button> - </li> + { + props + .contacts + // Sort contacts by last name alphabetically + .sort( + (a, b) => + a.name.family < b.name.family ? -1 : + a.name.family > b.name.family ? 1 : + 0 + ) + // Render contact + .map((contact, index) => + <li> + <p>Name: {contact.name.given} {contact.name.family}</p> + <p>Email: {contact.email}</p> + <button onClick={props.remove(index)}>Remove</button> + </li> )} </ul> );
d3aee69dec3cb959c9fe9fdc02a22e79cff4aac0
src/app/carousel/components/ngx-agile-slider-item.component.ts
src/app/carousel/components/ngx-agile-slider-item.component.ts
import { AfterViewInit, Component, ElementRef, Input, ViewChild, ViewEncapsulation } from '@angular/core'; /** * This component represents the slide item. */ @Component({ moduleId: module.id, selector: 'ngx-agile-slider-item', template: ` <li #sliderItem class="ngx-agile-slider-item variablewidth"> <ng-content></ng-content> </li> `, encapsulation: ViewEncapsulation.None }) export class SliderItemComponent implements AfterViewInit { /** * additional classes for li */ @Input() additionalClasses: string[]; @ViewChild('sliderItem') sliderItem: ElementRef; /** * Called after the view was initialized. Adds the additional classes */ public ngAfterViewInit() { if (this.additionalClasses) { for (let i = 0; i < this.additionalClasses.length; i++) { this.sliderItem.nativeElement.classList.add(this.additionalClasses[i]); } } } }
import { AfterViewInit, Component, ElementRef, Input, ViewChild, ViewEncapsulation } from '@angular/core'; /** * This component represents the slide item. */ @Component({ moduleId: module.id, selector: 'ngx-agile-slider-item', template: ` <li #sliderItem class="ngx-agile-slider-item variablewidth"> <ng-content></ng-content> </li> `, encapsulation: ViewEncapsulation.None }) export class SliderItemComponent implements AfterViewInit { /** * additional classes for li */ @Input() additionalClasses: string[]; @Input() width: string; @ViewChild('sliderItem') sliderItem: ElementRef; /** * Called after the view was initialized. Adds the additional classes */ public ngAfterViewInit() { if (this.additionalClasses) { for (let i = 0; i < this.additionalClasses.length; i++) { this.sliderItem.nativeElement.classList.add(this.additionalClasses[i]); } } if (this.width) { this.sliderItem.nativeElement.style.width = this.width; } } }
Add width for the item
Add width for the item
TypeScript
mit
anderlin/ngx-agile-slider,anderlin/ngx-agile-slider,anderlin/ngx-agile-slider
--- +++ @@ -18,6 +18,7 @@ * additional classes for li */ @Input() additionalClasses: string[]; + @Input() width: string; @ViewChild('sliderItem') sliderItem: ElementRef; @@ -30,5 +31,9 @@ this.sliderItem.nativeElement.classList.add(this.additionalClasses[i]); } } + + if (this.width) { + this.sliderItem.nativeElement.style.width = this.width; + } } }
90e2d0d72a20b4dd930ee9fadb0bbcda1b179b95
resources/scripts/routers/AuthenticationRouter.tsx
resources/scripts/routers/AuthenticationRouter.tsx
import React from 'react'; import { Route, RouteComponentProps, Switch } from 'react-router-dom'; import LoginContainer from '@/components/auth/LoginContainer'; import ForgotPasswordContainer from '@/components/auth/ForgotPasswordContainer'; import ResetPasswordContainer from '@/components/auth/ResetPasswordContainer'; import LoginCheckpointContainer from '@/components/auth/LoginCheckpointContainer'; import NotFound from '@/components/screens/NotFound'; export default ({ location, history, match }: RouteComponentProps) => ( <div className={'mt-8 xl:mt-32'}> <Switch location={location}> <Route path={`${match.path}/login`} component={LoginContainer} exact/> <Route path={`${match.path}/login/checkpoint`} component={LoginCheckpointContainer}/> <Route path={`${match.path}/password`} component={ForgotPasswordContainer} exact/> <Route path={`${match.path}/password/reset/:token`} component={ResetPasswordContainer}/> <Route path={`${match.path}/checkpoint`}/> <Route path={'*'}> <NotFound onBack={() => history.push('/auth/login')}/> </Route> </Switch> </div> );
import React from 'react'; import { Route, RouteComponentProps, Switch } from 'react-router-dom'; import LoginContainer from '@/components/auth/LoginContainer'; import ForgotPasswordContainer from '@/components/auth/ForgotPasswordContainer'; import ResetPasswordContainer from '@/components/auth/ResetPasswordContainer'; import LoginCheckpointContainer from '@/components/auth/LoginCheckpointContainer'; import NotFound from '@/components/screens/NotFound'; export default ({ location, history, match }: RouteComponentProps) => ( <div className={'pt-8 xl:pt-32'}> <Switch location={location}> <Route path={`${match.path}/login`} component={LoginContainer} exact/> <Route path={`${match.path}/login/checkpoint`} component={LoginCheckpointContainer}/> <Route path={`${match.path}/password`} component={ForgotPasswordContainer} exact/> <Route path={`${match.path}/password/reset/:token`} component={ResetPasswordContainer}/> <Route path={`${match.path}/checkpoint`}/> <Route path={'*'}> <NotFound onBack={() => history.push('/auth/login')}/> </Route> </Switch> </div> );
Fix positioning of the loading bar when logging in
Fix positioning of the loading bar when logging in
TypeScript
mit
Pterodactyl/Panel,Pterodactyl/Panel,Pterodactyl/Panel,Pterodactyl/Panel
--- +++ @@ -7,7 +7,7 @@ import NotFound from '@/components/screens/NotFound'; export default ({ location, history, match }: RouteComponentProps) => ( - <div className={'mt-8 xl:mt-32'}> + <div className={'pt-8 xl:pt-32'}> <Switch location={location}> <Route path={`${match.path}/login`} component={LoginContainer} exact/> <Route path={`${match.path}/login/checkpoint`} component={LoginCheckpointContainer}/>
a213238e5c92e54431df1dcb1907295d8d0989ce
packages/@glimmer/syntax/lib/traversal/path.ts
packages/@glimmer/syntax/lib/traversal/path.ts
import { Node } from '../types/nodes'; export default class Path<N extends Node> { node: N; parent: Path<Node> | null; parentKey: string | null; constructor(node: N, parent: Path<Node> | null = null, parentKey: string | null = null) { this.node = node; this.parent = parent; this.parentKey = parentKey; } get parentNode(): Node | null { return this.parent ? this.parent.node : null; } *parents(): IterableIterator<Path<Node>> { let path: Path<Node> = this; while (path.parent) { path = path.parent; yield path; } } }
import { Node } from '../types/nodes'; export default class Path<N extends Node> { node: N; parent: Path<Node> | null; parentKey: string | null; constructor(node: N, parent: Path<Node> | null = null, parentKey: string | null = null) { this.node = node; this.parent = parent; this.parentKey = parentKey; } get parentNode(): Node | null { return this.parent ? this.parent.node : null; } parents(): PathParentsIterable { return new PathParentsIterable(this); } } class PathParentsIterable implements Iterable<Path<Node>> { path: Path<Node>; constructor(path: Path<Node>) { this.path = path; } [Symbol.iterator]() { let next: () => IteratorResult<Path<Node>, undefined> = () => { if (this.path.parent) { this.path = this.path.parent; return { done: false, value: this.path }; } else { return { done: true, value: undefined }; } }; return { next }; } }
Implement `parents()` method using `Symbol.iterator` instead
syntax/traversal: Implement `parents()` method using `Symbol.iterator` instead
TypeScript
mit
tildeio/glimmer,glimmerjs/glimmer-vm,tildeio/glimmer,glimmerjs/glimmer-vm,tildeio/glimmer,glimmerjs/glimmer-vm
--- +++ @@ -15,11 +15,28 @@ return this.parent ? this.parent.node : null; } - *parents(): IterableIterator<Path<Node>> { - let path: Path<Node> = this; - while (path.parent) { - path = path.parent; - yield path; - } + parents(): PathParentsIterable { + return new PathParentsIterable(this); } } + +class PathParentsIterable implements Iterable<Path<Node>> { + path: Path<Node>; + + constructor(path: Path<Node>) { + this.path = path; + } + + [Symbol.iterator]() { + let next: () => IteratorResult<Path<Node>, undefined> = () => { + if (this.path.parent) { + this.path = this.path.parent; + return { done: false, value: this.path }; + } else { + return { done: true, value: undefined }; + } + }; + + return { next }; + } +}
efc50c7c3f5239dc1603101341a1e76c5dd3e66d
src/harmowatch/ngx-redux-core/decorators/index.ts
src/harmowatch/ngx-redux-core/decorators/index.ts
import { ReduxActionContextDecorator, ReduxActionContextDecoratorConfig, ReduxActionDecorator, ReduxActionDecoratorConfig, ReduxReducerDecorator, ReduxReducerDecoratorConfig, ReduxStateDecorator, ReduxStateDecoratorConfig, } from '@harmowatch/redux-decorators'; import { MethodType } from '@harmowatch/redux-decorators/lib/generic/generic-decorator'; export * from './redux-select.decorator'; export function ReduxAction(config?: ReduxActionDecoratorConfig): MethodType<Function> { return ReduxActionDecorator.forMethod(config); } export function ReduxActionContext(config?: ReduxActionContextDecoratorConfig) { return ReduxActionContextDecorator.forClass(config); } export function ReduxState(config?: ReduxStateDecoratorConfig) { return ReduxStateDecorator.forClass(config); } export function ReduxReducer(config?: ReduxReducerDecoratorConfig) { return ReduxReducerDecorator.forMethod(config); }
import { ReduxActionContextDecorator, ReduxActionDecorator, ReduxReducerDecorator, ReduxStateDecorator, } from '@harmowatch/redux-decorators'; export * from './redux-select.decorator'; export const ReduxAction = ReduxActionDecorator.forMethod; export const ReduxActionContext = ReduxActionContextDecorator.forClass; export const ReduxState = ReduxStateDecorator.forClass; export const ReduxReducer = ReduxReducerDecorator.forMethod;
Revert "try to export alias function to avoid angulars compiler issue "Only initialized variables and constants can be referenced in decorators ...""
Revert "try to export alias function to avoid angulars compiler issue "Only initialized variables and constants can be referenced in decorators ..."" This reverts commit ab01c7c
TypeScript
mit
HarmoWatch/ngx-redux-core,HarmoWatch/ngx-redux-core,HarmoWatch/ngx-redux-core
--- +++ @@ -1,29 +1,13 @@ import { ReduxActionContextDecorator, - ReduxActionContextDecoratorConfig, ReduxActionDecorator, - ReduxActionDecoratorConfig, ReduxReducerDecorator, - ReduxReducerDecoratorConfig, ReduxStateDecorator, - ReduxStateDecoratorConfig, } from '@harmowatch/redux-decorators'; -import { MethodType } from '@harmowatch/redux-decorators/lib/generic/generic-decorator'; export * from './redux-select.decorator'; -export function ReduxAction(config?: ReduxActionDecoratorConfig): MethodType<Function> { - return ReduxActionDecorator.forMethod(config); -} - -export function ReduxActionContext(config?: ReduxActionContextDecoratorConfig) { - return ReduxActionContextDecorator.forClass(config); -} - -export function ReduxState(config?: ReduxStateDecoratorConfig) { - return ReduxStateDecorator.forClass(config); -} - -export function ReduxReducer(config?: ReduxReducerDecoratorConfig) { - return ReduxReducerDecorator.forMethod(config); -} +export const ReduxAction = ReduxActionDecorator.forMethod; +export const ReduxActionContext = ReduxActionContextDecorator.forClass; +export const ReduxState = ReduxStateDecorator.forClass; +export const ReduxReducer = ReduxReducerDecorator.forMethod;
073b7074a5da2b70b4afb83e2bf0f7df93e3bed6
src/browser/settings/settings-dialog/settings-dialog.ts
src/browser/settings/settings-dialog/settings-dialog.ts
import { Injectable } from '@angular/core'; import { Dialog, DialogRef } from '../../ui/dialog'; import { SettingsDialogData } from './settings-dialog-data'; import { SettingsDialogComponent } from './settings-dialog.component'; @Injectable() export class SettingsDialog { constructor(private dialog: Dialog) { } open(data?: SettingsDialogData): DialogRef<SettingsDialogComponent, void> { return this.dialog.open<SettingsDialogComponent, SettingsDialogData, void>( SettingsDialogComponent, { width: '500px', maxHeight: '75vh', disableBackdropClickClose: true, data, }, ); } }
import { Injectable, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; import { Dialog, DialogRef } from '../../ui/dialog'; import { SettingsDialogData } from './settings-dialog-data'; import { SettingsDialogComponent } from './settings-dialog.component'; @Injectable() export class SettingsDialog implements OnDestroy { private dialogRef: DialogRef<SettingsDialogComponent, void> | null = null; private dialogCloseSubscription = Subscription.EMPTY; constructor(private dialog: Dialog) { } ngOnDestroy(): void { this.dialogCloseSubscription.unsubscribe(); } open(data?: SettingsDialogData): DialogRef<SettingsDialogComponent, void> { if (this.dialogRef) { return this.dialogRef; } this.dialogRef = this.dialog.open<SettingsDialogComponent, SettingsDialogData, void>( SettingsDialogComponent, { width: '500px', maxHeight: '75vh', disableBackdropClickClose: true, data, }, ); // If subscription exists, unsubscribe first. if (this.dialogCloseSubscription) { this.dialogCloseSubscription.unsubscribe(); } this.dialogCloseSubscription = this.dialogRef.afterClosed().subscribe(() => { this.dialogRef = null; }); return this.dialogRef; } }
Update only one settings dialog can be opened
Update only one settings dialog can be opened
TypeScript
mit
seokju-na/geeks-diary,seokju-na/geeks-diary,seokju-na/geeks-diary
--- +++ @@ -1,16 +1,28 @@ -import { Injectable } from '@angular/core'; +import { Injectable, OnDestroy } from '@angular/core'; +import { Subscription } from 'rxjs'; import { Dialog, DialogRef } from '../../ui/dialog'; import { SettingsDialogData } from './settings-dialog-data'; import { SettingsDialogComponent } from './settings-dialog.component'; @Injectable() -export class SettingsDialog { +export class SettingsDialog implements OnDestroy { + private dialogRef: DialogRef<SettingsDialogComponent, void> | null = null; + private dialogCloseSubscription = Subscription.EMPTY; + constructor(private dialog: Dialog) { } + ngOnDestroy(): void { + this.dialogCloseSubscription.unsubscribe(); + } + open(data?: SettingsDialogData): DialogRef<SettingsDialogComponent, void> { - return this.dialog.open<SettingsDialogComponent, + if (this.dialogRef) { + return this.dialogRef; + } + + this.dialogRef = this.dialog.open<SettingsDialogComponent, SettingsDialogData, void>( SettingsDialogComponent, @@ -21,5 +33,16 @@ data, }, ); + + // If subscription exists, unsubscribe first. + if (this.dialogCloseSubscription) { + this.dialogCloseSubscription.unsubscribe(); + } + + this.dialogCloseSubscription = this.dialogRef.afterClosed().subscribe(() => { + this.dialogRef = null; + }); + + return this.dialogRef; } }
d0c5709629fe24ae5ae167b336b544abc57b5f2f
packages/Common/src/styledMap.ts
packages/Common/src/styledMap.ts
export const styledMap = (...args) => (props) => { /** Put the styles in the object */ const styles: any = args[args.length - 1] const styleKeys: string[] = Object.keys(styles) /** Check if the first parameter is a string */ if (typeof args[0] === 'string') { /** If it is a string we get the value from it */ const argValue: number = args[0] const value: number = props[argValue] /** * If the value of the string isn't empty * return the value from the declared object */ if (styles[value]) return styles[value] } else { /** * If the first parameter isn't a string * filter the object to match the wanted prop */ const getKeys: string[] = styleKeys.filter(key => props[key]) /** * If a prop is declared return the matching key * or the last one if there are more */ if (getKeys.length) return styles[getKeys.pop()] } /** If a props isn't declared return the 'default' value from the object */ if (styles.hasOwnProperty('default')) { return styles.default } /** * If neither a prop is declared nor the object has the 'default' property * return the last item of the object */ return styles[styleKeys.pop()] }
export const styledMap = (...args) => (props) => { /** Put the styles in the object */ const styles: any = args[args.length - 1] const styleKeys: string[] = Object.keys(styles) /** Check if the first parameter is a string */ if (typeof args[0] === 'string') { /** If it is a string we get the value from it */ const argValue: number = args[0] const value: number = props[argValue] /** * If the value of the string isn't empty * return the value from the declared object */ if (styles[value]) return styles[value] } else { /** * If the first parameter isn't a string * filter the object to match the wanted prop */ const getKeys: string[] = styleKeys.filter(key => props[key]) const possibleKey = getKeys[getKeys.length - 1] /** * If we receive a valuable resolver and it is a function */ if (getKeys.length && typeof styles[possibleKey] == 'function') { return styles[possibleKey](props) } /** * If a prop is declared return the matching key * or the last one if there are more */ if (getKeys.length) return styles[getKeys.pop()] } /** If a props isn't declared return the 'default' value from the object */ if (styles.hasOwnProperty('default')) { return styles.default } /** * If neither a prop is declared nor the object has the 'default' property * return the last item of the object */ return styles[styleKeys.pop()] }
Support functions in the styleMap function
:sparkles: Support functions in the styleMap function
TypeScript
mit
slupjs/slup,slupjs/slup
--- +++ @@ -20,6 +20,14 @@ * filter the object to match the wanted prop */ const getKeys: string[] = styleKeys.filter(key => props[key]) + const possibleKey = getKeys[getKeys.length - 1] + + /** + * If we receive a valuable resolver and it is a function + */ + if (getKeys.length && typeof styles[possibleKey] == 'function') { + return styles[possibleKey](props) + } /** * If a prop is declared return the matching key
e39ce55d819cfab85e544d528b7e0d1ad5d9c53d
source/renderer/app/containers/MenuUpdater/useMenuUpdater.ts
source/renderer/app/containers/MenuUpdater/useMenuUpdater.ts
import { useEffect } from 'react'; import { matchPath } from 'react-router-dom'; import { WalletSettingsStateEnum } from '../../../../common/ipc/api'; import { ROUTES } from '../../routes-config'; import type { UseMenuUpdaterArgs } from './types'; const walletRoutes = Object.values(ROUTES.WALLETS); const useMenuUpdater = ({ stores: { app, profile, router, staking, uiDialogs }, rebuildApplicationMenu, }: UseMenuUpdaterArgs) => { useEffect(() => { let walletSettingsState = WalletSettingsStateEnum.hidden; const walletSettingsOptionVisible = walletRoutes.some( (path) => matchPath(router.location?.pathname, { path, })?.isExact ); if (walletSettingsOptionVisible) { const itIsTheWalletSettingsPage = matchPath(router.location?.pathname, { path: ROUTES.WALLETS.SETTINGS, })?.isExact; const anyDialogOpen = uiDialogs.activeDialog || app.activeDialog || staking.redeemStep; walletSettingsState = anyDialogOpen || itIsTheWalletSettingsPage ? WalletSettingsStateEnum.disabled : WalletSettingsStateEnum.enabled; } rebuildApplicationMenu.send({ isNavigationEnabled: profile.areTermsOfUseAccepted, walletSettingsState, }); }, [ app.activeDialog, profile.areTermsOfUseAccepted, profile.currentLocale, router.location?.pathname, staking.redeemStep, uiDialogs.activeDialog, ]); }; export default useMenuUpdater;
import { useEffect } from 'react'; import { matchPath } from 'react-router-dom'; import { WalletSettingsStateEnum } from '../../../../common/ipc/api'; import { ROUTES } from '../../routes-config'; import type { UseMenuUpdaterArgs } from './types'; import { AnalyticsAcceptanceStatus } from '../../analytics'; const walletRoutes = Object.values(ROUTES.WALLETS); const useMenuUpdater = ({ stores: { app, profile, router, staking, uiDialogs }, rebuildApplicationMenu, }: UseMenuUpdaterArgs) => { useEffect(() => { let walletSettingsState = WalletSettingsStateEnum.hidden; const walletSettingsOptionVisible = walletRoutes.some( (path) => matchPath(router.location?.pathname, { path, })?.isExact ); if (walletSettingsOptionVisible) { const itIsTheWalletSettingsPage = matchPath(router.location?.pathname, { path: ROUTES.WALLETS.SETTINGS, })?.isExact; const anyDialogOpen = uiDialogs.activeDialog || app.activeDialog || staking.redeemStep; walletSettingsState = anyDialogOpen || itIsTheWalletSettingsPage ? WalletSettingsStateEnum.disabled : WalletSettingsStateEnum.enabled; } rebuildApplicationMenu.send({ isNavigationEnabled: profile.areTermsOfUseAccepted && profile.analyticsAcceptanceStatus !== AnalyticsAcceptanceStatus.PENDING, walletSettingsState, }); }, [ app.activeDialog, profile.areTermsOfUseAccepted, profile.currentLocale, router.location?.pathname, staking.redeemStep, uiDialogs.activeDialog, ]); }; export default useMenuUpdater;
Disable menu until analytics accepted/rejected
[DDW-809] Disable menu until analytics accepted/rejected
TypeScript
apache-2.0
input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus
--- +++ @@ -3,6 +3,7 @@ import { WalletSettingsStateEnum } from '../../../../common/ipc/api'; import { ROUTES } from '../../routes-config'; import type { UseMenuUpdaterArgs } from './types'; +import { AnalyticsAcceptanceStatus } from '../../analytics'; const walletRoutes = Object.values(ROUTES.WALLETS); @@ -32,7 +33,9 @@ } rebuildApplicationMenu.send({ - isNavigationEnabled: profile.areTermsOfUseAccepted, + isNavigationEnabled: + profile.areTermsOfUseAccepted && + profile.analyticsAcceptanceStatus !== AnalyticsAcceptanceStatus.PENDING, walletSettingsState, }); }, [
d9002cf55777366ae82793316a70a738080c9cea
ui/test/kapacitor/components/KapacitorRules.test.tsx
ui/test/kapacitor/components/KapacitorRules.test.tsx
import React from 'react' import {shallow} from 'enzyme' import KapacitorRules from 'src/kapacitor/components/KapacitorRules' import {source, kapacitorRules} from 'test/resources' jest.mock('src/shared/apis', () => require('mocks/shared/apis')) const setup = (override = {}) => { const props = { source, rules: kapacitorRules, hasKapacitor: true, loading: false, onDelete: () => {}, onChangeRuleStatus: () => {}, } const wrapper = shallow(<KapacitorRules {...props} />) return { wrapper, props, } } describe('Kapacitor.Containers.KapacitorRules', () => { afterEach(() => { jest.clearAllMocks() }) describe('rendering', () => { it('renders the KapacitorRules', () => { const {wrapper} = setup() expect(wrapper.exists()).toBe(true) }) it('renders two tables', () => { const {wrapper} = setup() expect(wrapper.find('.panel-body').length).toEqual(2) }) }) })
import React from 'react' import {shallow} from 'enzyme' import KapacitorRules from 'src/kapacitor/components/KapacitorRules' import KapacitorRulesTable from 'src/kapacitor/components/KapacitorRulesTable' import TasksTable from 'src/kapacitor/components/TasksTable' import {source, kapacitorRules} from 'test/resources' jest.mock('src/shared/apis', () => require('mocks/shared/apis')) const setup = (override = {}) => { const props = { source, rules: kapacitorRules, hasKapacitor: true, loading: false, onDelete: () => {}, onChangeRuleStatus: () => {} } const wrapper = shallow(<KapacitorRules {...props} />) return { wrapper, props } } describe('Kapacitor.Containers.KapacitorRules', () => { afterEach(() => { jest.clearAllMocks() }) describe('rendering', () => { it('renders the KapacitorRules', () => { const {wrapper} = setup() expect(wrapper.exists()).toBe(true) }) it('renders two tables', () => { const {wrapper} = setup() const kapacitorRulesTable = wrapper.find('KapacitorRulesTable') expect(kapacitorRulesTable.length).toEqual(1) const tasksTable = wrapper.find('TasksTable') expect(tasksTable.length).toEqual(1) }) }) })
Test KapacitorRules to render KapacitorRulesTable & TasksTable
Test KapacitorRules to render KapacitorRulesTable & TasksTable
TypeScript
mit
influxdb/influxdb,li-ang/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb
--- +++ @@ -2,6 +2,8 @@ import {shallow} from 'enzyme' import KapacitorRules from 'src/kapacitor/components/KapacitorRules' +import KapacitorRulesTable from 'src/kapacitor/components/KapacitorRulesTable' +import TasksTable from 'src/kapacitor/components/TasksTable' import {source, kapacitorRules} from 'test/resources' @@ -14,14 +16,14 @@ hasKapacitor: true, loading: false, onDelete: () => {}, - onChangeRuleStatus: () => {}, + onChangeRuleStatus: () => {} } const wrapper = shallow(<KapacitorRules {...props} />) return { wrapper, - props, + props } } @@ -38,7 +40,12 @@ it('renders two tables', () => { const {wrapper} = setup() - expect(wrapper.find('.panel-body').length).toEqual(2) + + const kapacitorRulesTable = wrapper.find('KapacitorRulesTable') + expect(kapacitorRulesTable.length).toEqual(1) + + const tasksTable = wrapper.find('TasksTable') + expect(tasksTable.length).toEqual(1) }) }) })
d14412f4eed7bd0c1701353a279d3b72e78b5ea9
src/app/patient-dashboard/patient-previous-encounter.service.ts
src/app/patient-dashboard/patient-previous-encounter.service.ts
import { Injectable } from '@angular/core'; import { PatientService } from './patient.service'; import * as _ from 'lodash'; import { EncounterResourceService } from '../openmrs-api/encounter-resource.service'; @Injectable() export class PatientPreviousEncounterService { constructor(private patientService: PatientService, private encounterResource: EncounterResourceService) { } public getPreviousEncounter(encounterType: string): Promise<any> { return new Promise((resolve, reject) => { this.patientService.currentlyLoadedPatient.subscribe( (patient) => { if (patient) { let search = _.find(patient.encounters, (e) => { return e.encounterType.uuid === encounterType; }).uuid; this.encounterResource.getEncounterByUuid(search).subscribe((_encounter) => { resolve(_encounter); }, (err) => { reject(err); }); } }); }); } }
import { Injectable } from '@angular/core'; import { PatientService } from './patient.service'; import * as _ from 'lodash'; import { EncounterResourceService } from '../openmrs-api/encounter-resource.service'; @Injectable() export class PatientPreviousEncounterService { constructor(private patientService: PatientService, private encounterResource: EncounterResourceService) { } public getPreviousEncounter(encounterType: string): Promise<any> { return new Promise((resolve, reject) => { this.patientService.currentlyLoadedPatient.subscribe( (patient) => { if (patient) { let search = _.find(patient.encounters, (e) => { return e.encounterType.uuid === encounterType; }); if (search) { this.encounterResource.getEncounterByUuid(search.uuid).subscribe((_encounter) => { resolve(_encounter); }, (err) => { reject(err); }); } else { resolve({}); } } }); }); } }
Resolve empty encounter if patient doesn't have matching encounter type
Resolve empty encounter if patient doesn't have matching encounter type
TypeScript
mit
AMPATH/ng2-amrs,AMPATH/ng2-amrs,AMPATH/ng2-amrs,AMPATH/ng2-amrs
--- +++ @@ -20,13 +20,17 @@ if (patient) { let search = _.find(patient.encounters, (e) => { return e.encounterType.uuid === encounterType; - }).uuid; + }); - this.encounterResource.getEncounterByUuid(search).subscribe((_encounter) => { - resolve(_encounter); - }, (err) => { - reject(err); - }); + if (search) { + this.encounterResource.getEncounterByUuid(search.uuid).subscribe((_encounter) => { + resolve(_encounter); + }, (err) => { + reject(err); + }); + } else { + resolve({}); + } } });
abb2626824fb206661ca2def86e2b4c2d8f5832b
coffee-chats/src/main/webapp/src/components/GroupDeleteDialog.tsx
coffee-chats/src/main/webapp/src/components/GroupDeleteDialog.tsx
import React from "react"; import {Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle} from "@material-ui/core"; import {Group} from "../entity/Group"; import {useHistory} from "react-router-dom"; import {postData} from "../util/fetch"; interface GroupDeleteDialogProps { group: Group; open: boolean; setOpen: (value: boolean) => void; } export function GroupDeleteDialog({group, open, setOpen}: GroupDeleteDialogProps) { const history = useHistory(); const submit = async () => { setOpen(false); const data = new Map(); data.set("id", group.id); await postData("/api/groupDelete", data); history.push("/groups"); }; return ( <Dialog open={open} onClose={() => setOpen(false)}> <DialogTitle>Delete group &ldquo; {group.name} &rdquo;</DialogTitle> <DialogContent> <DialogContentText> Are you sure you want to delete the group? This action cannot be undone. </DialogContentText> </DialogContent> <DialogActions> <Button onClick={() => setOpen(false)}>Cancel</Button> <Button onClick={submit} color="secondary">Delete</Button> </DialogActions> </Dialog> ); }
import React from "react"; import {Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle} from "@material-ui/core"; import {Group} from "../entity/Group"; import {useHistory} from "react-router-dom"; import {postData} from "../util/fetch"; interface GroupDeleteDialogProps { group: Group; open: boolean; setOpen: (value: boolean) => void; } export function GroupDeleteDialog({group, open, setOpen}: GroupDeleteDialogProps) { const history = useHistory(); const submit = async () => { setOpen(false); const data = new Map(); data.set("id", group.id); await postData("/api/groupDelete", data); history.push("/groups"); }; return ( <Dialog open={open} onClose={() => setOpen(false)}> <DialogTitle>Delete group &ldquo;{group.name}&rdquo;</DialogTitle> <DialogContent> <DialogContentText> Are you sure you want to delete the group? This action cannot be undone. </DialogContentText> </DialogContent> <DialogActions> <Button onClick={() => setOpen(false)}>Cancel</Button> <Button onClick={submit} color="secondary">Delete</Button> </DialogActions> </Dialog> ); }
Remove spaces around group name in the delete dialog
Remove spaces around group name in the delete dialog
TypeScript
apache-2.0
googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020
--- +++ @@ -26,7 +26,7 @@ return ( <Dialog open={open} onClose={() => setOpen(false)}> - <DialogTitle>Delete group &ldquo; {group.name} &rdquo;</DialogTitle> + <DialogTitle>Delete group &ldquo;{group.name}&rdquo;</DialogTitle> <DialogContent> <DialogContentText> Are you sure you want to delete the group?
e32a0c71b00a4647ee7a84422f37c8501e65c4a6
frontend/src/app/page/champions/champions.module.ts
frontend/src/app/page/champions/champions.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { ChampionsRoutingModule } from './champions-routing.module'; import { ChampionsNameFilterPipe } from '@pipe/champions-name-filter.pipe'; import { ChampionsTagsFilterPipe } from '@pipe/champions-tags-filter.pipe'; import { ChampionsPage } from './champions.page'; import { TitleService } from '@service/title.service'; import { ChampionsService } from '@service/champions.service'; import { GameMapsService } from '@service/game-maps.service'; @NgModule({ imports: [ CommonModule, FormsModule, ChampionsRoutingModule, ], declarations: [ ChampionsNameFilterPipe, ChampionsTagsFilterPipe, ChampionsPage ], providers: [ TitleService, ChampionsService, GameMapsService ] }) export class ChampionsModule { }
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { ChampionsRoutingModule } from './champions-routing.module'; import { ChampionsNameFilterPipe } from '@pipe/champions-name-filter.pipe'; import { ChampionsTagsFilterPipe } from '@pipe/champions-tags-filter.pipe'; import { ChampionsPage } from './champions.page'; import { TitleService } from '@service/title.service'; import { ChampionsService } from '@service/champions.service'; @NgModule({ imports: [ CommonModule, FormsModule, ChampionsRoutingModule, ], declarations: [ ChampionsNameFilterPipe, ChampionsTagsFilterPipe, ChampionsPage ], providers: [ TitleService, ChampionsService ] }) export class ChampionsModule { }
Remove unused service in ChampionsModule
Remove unused service in ChampionsModule
TypeScript
mit
drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild
--- +++ @@ -10,7 +10,6 @@ import { ChampionsPage } from './champions.page'; import { TitleService } from '@service/title.service'; import { ChampionsService } from '@service/champions.service'; -import { GameMapsService } from '@service/game-maps.service'; @NgModule({ imports: [ @@ -25,8 +24,7 @@ ], providers: [ TitleService, - ChampionsService, - GameMapsService + ChampionsService ] }) export class ChampionsModule { }
4e00f75408e279e8b773932dccad87659afca55e
extensions/typescript-language-features/src/protocol.d.ts
extensions/typescript-language-features/src/protocol.d.ts
import * as Proto from 'typescript/lib/protocol'; export = Proto; declare enum ServerType { Syntax = 'syntax', Semantic = 'semantic', } declare module 'typescript/lib/protocol' { interface Response { readonly _serverType?: ServerType; } interface FileReferencesRequest extends FileRequest { } interface FileReferencesResponseBody { /** * The file locations referencing the symbol. */ refs: readonly ReferencesResponseItem[]; /** * The name of the symbol. */ symbolName: string; } interface FileReferencesResponse extends Response { body?: FileReferencesResponseBody; } }
import * as Proto from 'typescript/lib/protocol'; export = Proto; declare enum ServerType { Syntax = 'syntax', Semantic = 'semantic', } declare module 'typescript/lib/protocol' { interface Response { readonly _serverType?: ServerType; } }
Remove stubs file reference protocol
Remove stubs file reference protocol
TypeScript
mit
Krzysztof-Cieslak/vscode,Microsoft/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode
--- +++ @@ -10,21 +10,5 @@ interface Response { readonly _serverType?: ServerType; } - - interface FileReferencesRequest extends FileRequest { - } - interface FileReferencesResponseBody { - /** - * The file locations referencing the symbol. - */ - refs: readonly ReferencesResponseItem[]; - /** - * The name of the symbol. - */ - symbolName: string; - } - interface FileReferencesResponse extends Response { - body?: FileReferencesResponseBody; - } }
bf32fc69fdbff65c43ad59606ac52dc53c278bbb
jovo-integrations/jovo-platform-alexa/src/core/AlexaSpeechBuilder.ts
jovo-integrations/jovo-platform-alexa/src/core/AlexaSpeechBuilder.ts
import * as _ from 'lodash'; import {SpeechBuilder} from "jovo-core"; import {AlexaSkill} from "./AlexaSkill"; export class AlexaSpeechBuilder extends SpeechBuilder { constructor(alexaSkill: AlexaSkill) { super(alexaSkill); } /** * Adds audio tag to speech * @public * @param {string} url secure url to audio * @param {boolean} condition * @param {number} probability * @return {SpeechBuilder} */ addAudio(url: string | string[], condition?: boolean, probability?: number) { if (_.isArray(url)) { return this.addText('<audio src="' + _.sample(url) + '"/>', condition, probability); } return this.addText('<audio src="' + url + '"/>', condition, probability); } }
import * as _ from 'lodash'; import {SpeechBuilder} from "jovo-core"; import {AlexaSkill} from "./AlexaSkill"; export class AlexaSpeechBuilder extends SpeechBuilder { constructor(alexaSkill: AlexaSkill) { super(alexaSkill); } /** * Adds audio tag to speech * @public * @param {string} url secure url to audio * @param {boolean} condition * @param {number} probability * @return {SpeechBuilder} */ addAudio(url: string | string[], condition?: boolean, probability?: number) { if (_.isArray(url)) { return this.addText('<audio src="' + _.sample(url) + '"/>', condition, probability); } return this.addText('<audio src="' + url + '"/>', condition, probability); } /** * Adds text with language * @param {string} language * @param {string | string[]} text * @param {boolean} condition * @param {number} probability * @returns {SpeechBuilder} */ addLangText(language: string, text: string | string[], condition?: boolean, probability?: number) { if (_.isArray(text)) { return this.addText(`<lang xml:lang="${language}">${text}</lang>`, condition, probability); } return this.addText(`<lang xml:lang="${language}">${text}</lang>`, condition, probability); } /** * Adds text with polly * @param {string} pollyName * @param {string | string[]} text * @param {boolean} condition * @param {number} probability * @returns {SpeechBuilder} */ addTextWithPolly(pollyName: string, text: string | string[], condition?: boolean, probability?: number) { if (_.isArray(text)) { return this.addText(`<voice name="${pollyName}">${text}</voice>`, condition, probability); } return this.addText(`<voice name="${pollyName}">${text}</voice>`, condition, probability); } }
Add polly voices and language tag
:sparkles: Add polly voices and language tag
TypeScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
--- +++ @@ -21,4 +21,34 @@ } return this.addText('<audio src="' + url + '"/>', condition, probability); } + + /** + * Adds text with language + * @param {string} language + * @param {string | string[]} text + * @param {boolean} condition + * @param {number} probability + * @returns {SpeechBuilder} + */ + addLangText(language: string, text: string | string[], condition?: boolean, probability?: number) { + if (_.isArray(text)) { + return this.addText(`<lang xml:lang="${language}">${text}</lang>`, condition, probability); + } + return this.addText(`<lang xml:lang="${language}">${text}</lang>`, condition, probability); + } + + /** + * Adds text with polly + * @param {string} pollyName + * @param {string | string[]} text + * @param {boolean} condition + * @param {number} probability + * @returns {SpeechBuilder} + */ + addTextWithPolly(pollyName: string, text: string | string[], condition?: boolean, probability?: number) { + if (_.isArray(text)) { + return this.addText(`<voice name="${pollyName}">${text}</voice>`, condition, probability); + } + return this.addText(`<voice name="${pollyName}">${text}</voice>`, condition, probability); + } }
0798d13f10b193df0297e301affe761b90a8bfa9
extensions/markdown-language-features/src/slugify.ts
extensions/markdown-language-features/src/slugify.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export class Slug { public constructor( public readonly value: string ) { } public equals(other: Slug): boolean { return this.value === other.value; } } export interface Slugifier { fromHeading(heading: string): Slug; } export const githubSlugifier: Slugifier = new class implements Slugifier { fromHeading(heading: string): Slug { const slugifiedHeading = encodeURI( heading.trim() .toLowerCase() .replace(/\s+/g, '-') // Replace whitespace with - .replace(/[\]\[\!\'\#\$\%\&\'\(\)\*\+\,\.\/\:\;\<\=\>\?\@\\\^\_\{\|\}\~\`γ€‚οΌŒγ€οΌ›οΌšοΌŸοΌβ€¦β€”Β·Λ‰Β¨β€˜β€™β€œβ€γ€…ο½žβ€–βˆΆοΌ‚οΌ‡ο½€ο½œγ€ƒγ€”γ€•γ€ˆγ€‰γ€Šγ€‹γ€Œγ€γ€Žγ€οΌŽγ€–γ€—γ€γ€‘οΌˆοΌ‰οΌ»οΌ½ο½›ο½]/g, '') // Remove known punctuators .replace(/^\-+/, '') // Remove leading - .replace(/\-+$/, '') // Remove trailing - ); return new Slug(slugifiedHeading); } };
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export class Slug { public constructor( public readonly value: string ) { } public equals(other: Slug): boolean { return this.value === other.value; } } export interface Slugifier { fromHeading(heading: string): Slug; } export const githubSlugifier: Slugifier = new class implements Slugifier { fromHeading(heading: string): Slug { const slugifiedHeading = encodeURI( heading.trim() .toLowerCase() .replace(/\s+/g, '-') // Replace whitespace with - .replace(/[\]\[\!\'\#\$\%\&\(\)\*\+\,\.\/\:\;\<\=\>\?\@\\\^\_\{\|\}\~\`γ€‚οΌŒγ€οΌ›οΌšοΌŸοΌβ€¦β€”Β·Λ‰Β¨β€˜β€™β€œβ€γ€…ο½žβ€–βˆΆοΌ‚οΌ‡ο½€ο½œγ€ƒγ€”γ€•γ€ˆγ€‰γ€Šγ€‹γ€Œγ€γ€Žγ€οΌŽγ€–γ€—γ€γ€‘οΌˆοΌ‰οΌ»οΌ½ο½›ο½]/g, '') // Remove known punctuators .replace(/^\-+/, '') // Remove leading - .replace(/\-+$/, '') // Remove trailing - ); return new Slug(slugifiedHeading); } };
Remove duplicate character from regex class
Remove duplicate character from regex class
TypeScript
mit
microsoft/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,the-ress/vscode,the-ress/vscode,landonepps/vscode,Microsoft/vscode,joaomoreno/vscode,the-ress/vscode,mjbvz/vscode,eamodio/vscode,cleidigh/vscode,cleidigh/vscode,joaomoreno/vscode,hoovercj/vscode,hoovercj/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,joaomoreno/vscode,microsoft/vscode,landonepps/vscode,cleidigh/vscode,microsoft/vscode,hoovercj/vscode,microsoft/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,microsoft/vscode,the-ress/vscode,landonepps/vscode,the-ress/vscode,joaomoreno/vscode,cleidigh/vscode,landonepps/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,joaomoreno/vscode,microsoft/vscode,hoovercj/vscode,joaomoreno/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,joaomoreno/vscode,joaomoreno/vscode,landonepps/vscode,microsoft/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,cleidigh/vscode,mjbvz/vscode,eamodio/vscode,the-ress/vscode,mjbvz/vscode,eamodio/vscode,Microsoft/vscode,cleidigh/vscode,the-ress/vscode,mjbvz/vscode,eamodio/vscode,microsoft/vscode,the-ress/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,eamodio/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,mjbvz/vscode,the-ress/vscode,microsoft/vscode,mjbvz/vscode,the-ress/vscode,cleidigh/vscode,the-ress/vscode,the-ress/vscode,eamodio/vscode,mjbvz/vscode,hoovercj/vscode,hoovercj/vscode,joaomoreno/vscode,hoovercj/vscode,landonepps/vscode,cleidigh/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,hoovercj/vscode,landonepps/vscode,hoovercj/vscode,Microsoft/vscode,microsoft/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,cleidigh/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,hoovercj/vscode,mjbvz/vscode,Microsoft/vscode,Microsoft/vscode,mjbvz/vscode,landonepps/vscode,mjbvz/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,mjbvz/vscode,the-ress/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,joaomoreno/vscode,mjbvz/vscode,landonepps/vscode,the-ress/vscode,Microsoft/vscode,hoovercj/vscode,cleidigh/vscode,hoovercj/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,Microsoft/vscode,joaomoreno/vscode,eamodio/vscode,landonepps/vscode,eamodio/vscode,the-ress/vscode,eamodio/vscode,landonepps/vscode,cleidigh/vscode,Microsoft/vscode,joaomoreno/vscode,joaomoreno/vscode,hoovercj/vscode,Microsoft/vscode,cleidigh/vscode,joaomoreno/vscode,cleidigh/vscode,hoovercj/vscode,mjbvz/vscode,hoovercj/vscode,microsoft/vscode,cleidigh/vscode,landonepps/vscode,the-ress/vscode,joaomoreno/vscode
--- +++ @@ -23,7 +23,7 @@ heading.trim() .toLowerCase() .replace(/\s+/g, '-') // Replace whitespace with - - .replace(/[\]\[\!\'\#\$\%\&\'\(\)\*\+\,\.\/\:\;\<\=\>\?\@\\\^\_\{\|\}\~\`γ€‚οΌŒγ€οΌ›οΌšοΌŸοΌβ€¦β€”Β·Λ‰Β¨β€˜β€™β€œβ€γ€…ο½žβ€–βˆΆοΌ‚οΌ‡ο½€ο½œγ€ƒγ€”γ€•γ€ˆγ€‰γ€Šγ€‹γ€Œγ€γ€Žγ€οΌŽγ€–γ€—γ€γ€‘οΌˆοΌ‰οΌ»οΌ½ο½›ο½]/g, '') // Remove known punctuators + .replace(/[\]\[\!\'\#\$\%\&\(\)\*\+\,\.\/\:\;\<\=\>\?\@\\\^\_\{\|\}\~\`γ€‚οΌŒγ€οΌ›οΌšοΌŸοΌβ€¦β€”Β·Λ‰Β¨β€˜β€™β€œβ€γ€…ο½žβ€–βˆΆοΌ‚οΌ‡ο½€ο½œγ€ƒγ€”γ€•γ€ˆγ€‰γ€Šγ€‹γ€Œγ€γ€Žγ€οΌŽγ€–γ€—γ€γ€‘οΌˆοΌ‰οΌ»οΌ½ο½›ο½]/g, '') // Remove known punctuators .replace(/^\-+/, '') // Remove leading - .replace(/\-+$/, '') // Remove trailing - );
432504cd25ab57cbf42596a7fa0d2eb1a42d86a7
src/app/common/services/http-authentication.interceptor.ts
src/app/common/services/http-authentication.interceptor.ts
import { Injectable, Injector, Inject } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable } from 'rxjs'; import { currentUser } from 'src/app/ajs-upgraded-providers'; import API_URL from 'src/app/config/constants/apiURL'; @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor( @Inject(currentUser) private currentUser: any, ) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (request.url.startsWith(API_URL) && this.currentUser.authenticationToken) { request = request.clone({ setHeaders: { Authorization: `Bearer ${this.currentUser.authenticationToken}` }, params: request.params.append('auth_token', this.currentUser.authenticationToken) }); } return next.handle(request); } }
import { Injectable, Injector, Inject } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable } from 'rxjs'; import { currentUser } from 'src/app/ajs-upgraded-providers'; import API_URL from 'src/app/config/constants/apiURL'; @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor( @Inject(currentUser) private currentUser: any, ) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (request.url.startsWith(API_URL) && this.currentUser.authenticationToken) { request = request.clone({ setHeaders: { 'Auth-Token': `Bearer ${this.currentUser.authenticationToken}`, 'Username': `Bearer ${this.currentUser.username}` } }); } return next.handle(request); } }
Add auth tolen and username to header
CONFIG: Add auth tolen and username to header
TypeScript
agpl-3.0
doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web
--- +++ @@ -18,9 +18,9 @@ if (request.url.startsWith(API_URL) && this.currentUser.authenticationToken) { request = request.clone({ setHeaders: { - Authorization: `Bearer ${this.currentUser.authenticationToken}` - }, - params: request.params.append('auth_token', this.currentUser.authenticationToken) + 'Auth-Token': `Bearer ${this.currentUser.authenticationToken}`, + 'Username': `Bearer ${this.currentUser.username}` + } }); } return next.handle(request);
a2333e754b0d8751f438e086741308e876c5f54b
packages/components/containers/recovery/phone/ConfirmRemovePhoneModal.tsx
packages/components/containers/recovery/phone/ConfirmRemovePhoneModal.tsx
import { c } from 'ttag'; import { Alert, Button, ModalProps, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, } from '../../../components'; interface Props extends ModalProps { onConfirm: () => void; } const ConfirmRemovePhoneModal = ({ onConfirm, onClose, ...rest }: Props) => { return ( <Modal onClose={onClose} {...rest}> <ModalHeader title={c('Title').t`Confirm phone number`} /> <ModalContent> <Alert type="warning"> {c('Warning').t`By deleting this phone number, you will no longer be able to recover your account.`} <br /> <br /> {c('Warning').t`Are you sure you want to delete the phone number?`} </Alert> </ModalContent> <ModalFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" onClick={() => { onClose?.(); onConfirm(); }} > {c('Action').t`Confirm`} </Button> </ModalFooter> </Modal> ); }; export default ConfirmRemovePhoneModal;
import { c } from 'ttag'; import { Alert, Button, ModalProps, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, } from '../../../components'; interface Props extends ModalProps { onConfirm: () => void; } const ConfirmRemovePhoneModal = ({ onConfirm, onClose, ...rest }: Props) => { return ( <Modal onClose={onClose} {...rest}> <ModalHeader title={c('Title').t`Confirm phone number`} /> <ModalContent> <Alert type="warning"> {c('Warning').t`By deleting this phone number, you will no longer be able to recover your account.`} <br /> <br /> {c('Warning').t`Are you sure you want to delete the phone number?`} </Alert> </ModalContent> <ModalFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" onClick={() => { onConfirm(); onClose?.(); }} > {c('Action').t`Confirm`} </Button> </ModalFooter> </Modal> ); }; export default ConfirmRemovePhoneModal;
Fix phone recovery switch not turning off when removing recovery phone
Fix phone recovery switch not turning off when removing recovery phone CP-4030
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -30,8 +30,8 @@ <Button color="norm" onClick={() => { + onConfirm(); onClose?.(); - onConfirm(); }} > {c('Action').t`Confirm`}
2c9a11398765c606a26c9b39bbc5e928285572f4
src/plugins/pagination/pager-target/pager-target.component.ts
src/plugins/pagination/pager-target/pager-target.component.ts
import { Component, Optional, OnInit } from '@angular/core'; import { PluginComponent } from '../../plugin.component'; import { RootService } from 'ng2-qgrid/infrastructure/component/root.service'; @Component({ selector: 'q-grid-pager-target', templateUrl: './pager-target.component.html' }) export class PagerTargetComponent extends PluginComponent implements OnInit { constructor(@Optional() root: RootService) { super(root); } private value: any; private target: any; ngOnInit() { this.target = this; this.context = {$implicit: this.target}; } setPage(page: number) { this.model.pagination({current: page - 1}); } handleKeyDown(event: KeyboardEvent) { event.preventDefault(); const isEnter = event.key === 'Enter'; const key = Number.parseInt(event.key) || 0; const total = this.total(); if (isEnter) { this.setPage(this.value); } else if (key <= total && key >= 1) { setTimeout(() => this.value = key); } else { setTimeout(() => this.value = ''); } } total() { const pagination = this.model.pagination(); const count = pagination.count; const size = pagination.size; return count / size; } }
import { Component, Optional, OnInit } from '@angular/core'; import { PluginComponent } from '../../plugin.component'; import { RootService } from 'ng2-qgrid/infrastructure/component/root.service'; @Component({ selector: 'q-grid-pager-target', templateUrl: './pager-target.component.html' }) export class PagerTargetComponent extends PluginComponent implements OnInit { constructor(@Optional() root: RootService) { super(root); } private value: any; private target: any; ngOnInit() { this.target = this; this.context = {$implicit: this.target}; } setPage(page: number) { this.model.pagination({current: page - 1}); } handleKeyDown(event: KeyboardEvent) { event.preventDefault(); const isEnter = event.key === 'Enter'; const key = Number.parseInt(event.key) || 0; const total = this.total(); if (isEnter) { this.setPage(this.value); } else if (key <= total && key >= 1) { setTimeout(() => this.value = key); } else { setTimeout(() => this.value = 1); } } total() { const pagination = this.model.pagination(); const count = pagination.count; const size = pagination.size; return count / size; } }
Set default page to 1
Set default page to 1
TypeScript
mit
qgrid/ng2,azkurban/ng2,qgrid/ng2,azkurban/ng2,qgrid/ng2,azkurban/ng2
--- +++ @@ -36,7 +36,7 @@ } else if (key <= total && key >= 1) { setTimeout(() => this.value = key); } else { - setTimeout(() => this.value = ''); + setTimeout(() => this.value = 1); } }