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
|
---|---|---|---|---|---|---|---|---|---|---|
15d89334a191234cf735a0d783b407aaf76be7eb | app/ctrl/canvas-ctrl.ts | app/ctrl/canvas-ctrl.ts | /**
* Created by gpl on 15/11/30.
*/
module App.Controllers {
import Canvas = App.Services.Canvas;
import Logger = App.Services.Logger;
export class CanvasCtrl {
static $inject = ['Logger', 'Canvas'];
private canvas:Canvas;
private logger:Logger;
constructor(logger:Logger, canvas:Canvas) {
this.canvas = canvas;
this.logger = logger;
this.logger.info('canvas ctrl init');
// create a rectangle object
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'white',
width: 20,
height: 20,
angle: 45
});
this.canvas.add(rect);
}
public startDraw():void {
this.canvas.startDrawing()
}
public stopDraw():void {
this.canvas.stopDrawing();
}
public startPolygon():void {
this.logger.info('start drawing polygon, click first point');
this.canvas.startPolygon();
}
public stopPolygon():void {
this.logger.info('stop drawing polygon');
this.canvas.stopPolygon();
}
}
} | /**
* Created by gpl on 15/11/30.
*/
module App.Controllers {
import Canvas = App.Services.Canvas;
import Logger = App.Services.Logger;
export class CanvasCtrl {
static $inject = ['Logger', 'Canvas'];
private canvas:Canvas;
private logger:Logger;
constructor(logger:Logger, canvas:Canvas) {
this.canvas = canvas;
this.logger = logger;
this.logger.info('canvas ctrl init');
}
public startDraw():void {
this.canvas.startDrawing()
}
public stopDraw():void {
this.canvas.stopDrawing();
}
public startPolygon():void {
this.logger.info('start drawing polygon, click first point');
this.canvas.startPolygon();
}
public stopPolygon():void {
this.logger.info('stop drawing polygon');
this.canvas.stopPolygon();
}
}
} | Remove the init rect when init canvas | Remove the init rect when init canvas
| TypeScript | mit | at15/cadjs,at15/cadjs,at15/cadjs | ---
+++
@@ -14,18 +14,6 @@
this.canvas = canvas;
this.logger = logger;
this.logger.info('canvas ctrl init');
-
- // create a rectangle object
- var rect = new fabric.Rect({
- left: 100,
- top: 100,
- fill: 'white',
- width: 20,
- height: 20,
- angle: 45
- });
-
- this.canvas.add(rect);
}
public startDraw():void { |
76e8a56cee1955f50888e952f88e221932c9a3c1 | src/utils/children.ts | src/utils/children.ts | import * as React from 'react';
const childrenToMap = (children: React.ReactNode): Map<string, React.ReactChild> => {
const childrenArray = React.Children.toArray(children);
const childMap: Map<string, React.ReactChild> = new Map();
childrenArray.forEach((child) => {
childMap.set(child.key, child);
});
return childMap;
};
const compareChildren = (children1: Map<string, React.ReactNode>, children2: Map<string, React.ReactNode>): boolean => {
const keys1 = Array.from(children1.keys());
const keys2 = Array.from(children2.keys());
return keys1 === keys2;
};
export {
childrenToMap,
compareChildren,
} | import * as React from 'react';
const childrenToMap = (children?: any): Map<string, React.ReactElement<any>> => {
const childMap: Map<string, React.ReactElement<any>> = new Map();
if (!children) return childMap;
React.Children.forEach(children, (child) => {
if (React.isValidElement(child)) {
childMap.set(<string>child.key, child)
}
});
return childMap;
};
const compareChildren = (children1: Map<string, React.ReactNode>, children2: Map<string, React.ReactNode>): boolean => {
const keys1 = Array.from(children1.keys());
const keys2 = Array.from(children2.keys());
return keys1 === keys2;
};
export {
childrenToMap,
compareChildren,
} | Change to implement type safety | Change to implement type safety
| TypeScript | mit | bkazi/react-layout-transition,bkazi/react-layout-transition,bkazi/react-layout-transition | ---
+++
@@ -1,11 +1,13 @@
import * as React from 'react';
-const childrenToMap = (children: React.ReactNode): Map<string, React.ReactChild> => {
- const childrenArray = React.Children.toArray(children);
- const childMap: Map<string, React.ReactChild> = new Map();
- childrenArray.forEach((child) => {
- childMap.set(child.key, child);
- });
+const childrenToMap = (children?: any): Map<string, React.ReactElement<any>> => {
+ const childMap: Map<string, React.ReactElement<any>> = new Map();
+ if (!children) return childMap;
+ React.Children.forEach(children, (child) => {
+ if (React.isValidElement(child)) {
+ childMap.set(<string>child.key, child)
+ }
+ });
return childMap;
};
|
950049c94d7f5b8dd62f2522265f132a55c562b4 | app/scripts/components/user/support/utils.ts | app/scripts/components/user/support/utils.ts | import { duration } from 'moment';
import { titleCase } from '@waldur/core/utils';
import { translate } from '@waldur/i18n';
export const formatUserStatus = user => {
if (user.is_staff && !user.is_support) {
return translate('Staff');
} else if (user.is_staff && user.is_support) {
return translate('Staff and Support user');
} else if (!user.is_staff && user.is_support) {
return translate('Support user');
} else {
return translate('Regular user');
}
};
export const formatRegistrationMethod = user => {
if (!user.registration_method) {
return translate('Default');
} else if (user.registration_method === 'openid') {
return translate('Estonian ID');
} else {
return titleCase(user.registration_method);
}
};
export const formatLifetime = input => {
const time = duration(input, 'seconds');
const hours = time.hours();
const minutes = time.minutes();
const seconds = time.seconds();
if (input === null || input === 0) {
return translate('token will not timeout');
}
if (hours === 0 && minutes === 0) {
return `${seconds} sec`;
}
if (hours === 0 && minutes !== 0) {
return `${minutes} min`;
}
if (hours !== 0) {
return minutes !== 0 ? `${hours} h ${minutes} min` : `${hours} h`;
}
};
| import { duration } from 'moment';
import { titleCase } from '@waldur/core/utils';
import { translate } from '@waldur/i18n';
export const formatUserStatus = user => {
if (user.is_staff && !user.is_support) {
return translate('Staff');
} else if (user.is_staff && user.is_support) {
return translate('Staff and Support user');
} else if (!user.is_staff && user.is_support) {
return translate('Support user');
} else {
return translate('Regular user');
}
};
export const formatRegistrationMethod = user => {
if (!user.registration_method) {
return translate('Default');
} else if (user.registration_method === 'openid') {
return translate('Estonian ID');
} else if (user.registration_method === 'saml2') {
return 'SAML2';
} else {
return titleCase(user.registration_method);
}
};
export const formatLifetime = input => {
const time = duration(input, 'seconds');
const hours = time.hours();
const minutes = time.minutes();
const seconds = time.seconds();
if (input === null || input === 0) {
return translate('token will not timeout');
}
if (hours === 0 && minutes === 0) {
return `${seconds} sec`;
}
if (hours === 0 && minutes !== 0) {
return `${minutes} min`;
}
if (hours !== 0) {
return minutes !== 0 ? `${hours} h ${minutes} min` : `${hours} h`;
}
};
| Improve rendering for SAML2 registration method. | Improve rendering for SAML2 registration method.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -20,6 +20,8 @@
return translate('Default');
} else if (user.registration_method === 'openid') {
return translate('Estonian ID');
+ } else if (user.registration_method === 'saml2') {
+ return 'SAML2';
} else {
return titleCase(user.registration_method);
} |
0100bfd848e2f96b3a38c7365a9dc1f78c19bfb7 | lib/components/modification/variants.tsx | lib/components/modification/variants.tsx | import {Checkbox, Heading, Stack} from '@chakra-ui/core'
import message from 'lib/message'
export default function Variants({activeVariants, allVariants, setVariant}) {
return (
<Stack spacing={4}>
<Heading size='md'>{message('variant.activeIn')}</Heading>
<Stack spacing={2}>
{allVariants.map((v, i) => (
<Checkbox
fontWeight='normal'
isChecked={activeVariants[i]}
key={`${i}-${v}`}
name={v}
onChange={(e) => setVariant(i, e.target.checked)}
value={i}
>
{i + 1}. {v}
</Checkbox>
))}
</Stack>
</Stack>
)
}
| import {Checkbox, Heading, Stack} from '@chakra-ui/core'
import message from 'lib/message'
export default function Variants({activeVariants, allVariants, setVariant}) {
return (
<Stack spacing={4}>
<Heading size='md'>{message('variant.activeIn')}</Heading>
<Stack spacing={2}>
{allVariants.map((v, i) => (
<Checkbox
fontWeight='normal'
isChecked={activeVariants[i]}
key={`${i}-${v}`}
name={v}
onChange={(e) => setVariant(i, e.target.checked)}
value={i}
wordBreak='break-all'
>
{i + 1}. {v}
</Checkbox>
))}
</Stack>
</Stack>
)
}
| Break long variant names into new lines | Break long variant names into new lines
| TypeScript | mit | conveyal/analysis-ui,conveyal/analysis-ui,conveyal/analysis-ui | ---
+++
@@ -15,6 +15,7 @@
name={v}
onChange={(e) => setVariant(i, e.target.checked)}
value={i}
+ wordBreak='break-all'
>
{i + 1}. {v}
</Checkbox> |
4240fae07deae852b714b84098b0a9acff573de3 | src/cli.ts | src/cli.ts | // This file is part of cbuild, copyright (c) 2016 BusFaster Ltd.
// Released under the MIT license, see LICENSE.
import * as path from 'path';
import * as cmd from 'commander';
import {build} from './cbuild';
type _ICommand = typeof cmd;
interface ICommand extends _ICommand {
arguments(spec: string): ICommand;
}
((cmd.version(require('../package.json').version) as ICommand)
.arguments('<output-bundle-path>')
.description('SystemJS node module bundling tool')
.option('-p, --package <path>', 'Path to directory with package.json and config.js', process.cwd())
.option('-C, --out-config <path>', 'Path to new config.js to overwrite with path mappings')
.action(handleBundle)
.parse(process.argv)
);
if(process.argv.length < 3) cmd.help();
function handleBundle(targetPath: string, opts: { [key: string]: any }) {
var basePath = path.resolve('.', opts['package']);
build(basePath, targetPath, {
outConfigPath: opts['outConfig']
}).then(() => {
console.log('Build complete!');
}).catch((err) => {
console.log('Build error:');
console.log(err);
});
}
| // This file is part of cbuild, copyright (c) 2016 BusFaster Ltd.
// Released under the MIT license, see LICENSE.
import * as path from 'path';
import * as cmd from 'commander';
import {build} from './cbuild';
type _ICommand = typeof cmd;
interface ICommand extends _ICommand {
arguments(spec: string): ICommand;
}
((cmd.version(require('../package.json').version) as ICommand)
.arguments('<output-bundle-path>')
.description('SystemJS node module bundling tool')
.option('-s, --source <path>', 'main JavaScript source to bundle')
.option('-p, --package <path>', 'directory with package.json and config.js', process.cwd())
.option('-C, --out-config <path>', 'new config.js to overwrite with path mappings')
.action(handleBundle)
.parse(process.argv)
);
if(process.argv.length < 3) cmd.help();
function handleBundle(targetPath: string, opts: { [key: string]: any }) {
var basePath = path.resolve('.', opts['package']);
var sourcePath: string = opts['source'];
if(sourcePath) sourcePath = path.resolve('.', sourcePath);
build(basePath, targetPath, {
sourcePath: sourcePath,
outConfigPath: opts['outConfig']
}).then(() => {
console.log('Build complete!');
}).catch((err) => {
console.log('Build error:');
console.log(err);
});
}
| Allow setting main JavaScript file through a command line parameter. | Allow setting main JavaScript file through a command line parameter.
| TypeScript | mit | charto/cbuild,charto/cbuild | ---
+++
@@ -14,8 +14,9 @@
((cmd.version(require('../package.json').version) as ICommand)
.arguments('<output-bundle-path>')
.description('SystemJS node module bundling tool')
- .option('-p, --package <path>', 'Path to directory with package.json and config.js', process.cwd())
- .option('-C, --out-config <path>', 'Path to new config.js to overwrite with path mappings')
+ .option('-s, --source <path>', 'main JavaScript source to bundle')
+ .option('-p, --package <path>', 'directory with package.json and config.js', process.cwd())
+ .option('-C, --out-config <path>', 'new config.js to overwrite with path mappings')
.action(handleBundle)
.parse(process.argv)
);
@@ -24,8 +25,12 @@
function handleBundle(targetPath: string, opts: { [key: string]: any }) {
var basePath = path.resolve('.', opts['package']);
+ var sourcePath: string = opts['source'];
+
+ if(sourcePath) sourcePath = path.resolve('.', sourcePath);
build(basePath, targetPath, {
+ sourcePath: sourcePath,
outConfigPath: opts['outConfig']
}).then(() => {
console.log('Build complete!'); |
d0195c7a8749f24f7d9a6b370575aced4d524cc2 | typescript/middy.d.ts | typescript/middy.d.ts | import {Callback, Context, Handler, ProxyResult} from 'aws-lambda';
export interface IMiddy {
use: IMiddyUseFunction;
before: IMiddyMiddlewareFunction;
after: IMiddyMiddlewareFunction;
onError: IMiddyMiddlewareFunction;
}
export type IMiddyUseFunction = (config?: object) => IMiddyMiddlewareObject;
export interface IMiddyMiddlewareObject {
before?: IMiddyMiddlewareFunction;
after?: IMiddyMiddlewareFunction;
onError?: IMiddyMiddlewareFunction;
}
type IMiddyMiddlewareFunction = (
handler: IHandlerLambda,
next: IMiddyNextFunction
) => void;
export type IMiddyNextFunction = () => void;
export interface IHandlerLambda {
event: any;
context: Context;
response: ProxyResult | object;
error: Error;
callback: Callback;
}
declare let middy: (handler: Handler) => IMiddy;
export default middy;
| import {Callback, Context, Handler, ProxyResult} from 'aws-lambda';
export interface IMiddy {
use: IMiddyUseFunction;
before: IMiddyMiddlewareFunction;
after: IMiddyMiddlewareFunction;
onError: IMiddyMiddlewareFunction;
}
export type IMiddyUseFunction = (config?: object) => IMiddy;
export interface IMiddyMiddlewareObject {
before?: IMiddyMiddlewareFunction;
after?: IMiddyMiddlewareFunction;
onError?: IMiddyMiddlewareFunction;
}
type IMiddyMiddlewareFunction = (
handler: IHandlerLambda,
next: IMiddyNextFunction
) => void;
export type IMiddyNextFunction = () => void;
export interface IHandlerLambda {
event: any;
context: Context;
response: ProxyResult | object;
error: Error;
callback: Callback;
}
declare let middy: (handler: Handler) => IMiddy;
export default middy;
| Fix wrong type on use function | Fix wrong type on use function
| TypeScript | mit | middyjs/middy,middyjs/middy | ---
+++
@@ -7,7 +7,7 @@
onError: IMiddyMiddlewareFunction;
}
-export type IMiddyUseFunction = (config?: object) => IMiddyMiddlewareObject;
+export type IMiddyUseFunction = (config?: object) => IMiddy;
export interface IMiddyMiddlewareObject {
before?: IMiddyMiddlewareFunction; |
e5d2c6404fe8250bf18381af78d5e3ba5c94c224 | visualization/app/codeCharta/state/store/fileSettings/attributeTypes/attributeTypes.reducer.ts | visualization/app/codeCharta/state/store/fileSettings/attributeTypes/attributeTypes.reducer.ts | import { AttributeTypesAction, AttributeTypesActions, setAttributeTypes, UpdateAttributeTypeAction } from "./attributeTypes.actions"
import { AttributeTypes } from "../../../../codeCharta.model"
const clone = require("rfdc")()
export function attributeTypes(state: AttributeTypes = setAttributeTypes().payload, action: AttributeTypesAction): AttributeTypes {
switch (action.type) {
case AttributeTypesActions.SET_ATTRIBUTE_TYPES:
return clone(action.payload)
case AttributeTypesActions.UPDATE_ATTRIBUTE_TYPE:
return updateAttributeType(state, action)
default:
return state
}
}
function updateAttributeType(state: AttributeTypes, action: UpdateAttributeTypeAction) {
const copy = clone(state)
if (copy[action.payload.category]) {
copy[action.payload.category][action.payload.name] = action.payload.type
}
return copy
}
| import { AttributeTypesAction, AttributeTypesActions, setAttributeTypes, UpdateAttributeTypeAction } from "./attributeTypes.actions"
import { AttributeTypes } from "../../../../codeCharta.model"
const clone = require("rfdc")()
export function attributeTypes(state: AttributeTypes = setAttributeTypes().payload, action: AttributeTypesAction): AttributeTypes {
switch (action.type) {
case AttributeTypesActions.SET_ATTRIBUTE_TYPES:
return clone(action.payload)
case AttributeTypesActions.UPDATE_ATTRIBUTE_TYPE:
return updateAttributeType(state, action)
default:
return state
}
}
function updateAttributeType(state: AttributeTypes, action: UpdateAttributeTypeAction): AttributeTypes {
return { ...state, [action.payload.category]: { ...state[action.payload.category], [action.payload.name]: action.payload.type } }
}
| Refactor use shallow clone instead of deep clone | Refactor use shallow clone instead of deep clone
| TypeScript | bsd-3-clause | MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta | ---
+++
@@ -13,10 +13,6 @@
}
}
-function updateAttributeType(state: AttributeTypes, action: UpdateAttributeTypeAction) {
- const copy = clone(state)
- if (copy[action.payload.category]) {
- copy[action.payload.category][action.payload.name] = action.payload.type
- }
- return copy
+function updateAttributeType(state: AttributeTypes, action: UpdateAttributeTypeAction): AttributeTypes {
+ return { ...state, [action.payload.category]: { ...state[action.payload.category], [action.payload.name]: action.payload.type } }
} |
078a8482c810624c3c0788ea9816677cbf84d038 | resources/assets/lib/shopify-debug.ts | resources/assets/lib/shopify-debug.ts | // 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.
/**
* Dev helpers for looking up Shopify stuff.
* import them somewhere if you need them.
*/
import Shopify from 'shopify-buy';
const options = {
domain: process.env.SHOPIFY_DOMAIN,
storefrontAccessToken: process.env.SHOPIFY_STOREFRONT_TOKEN,
};
const client = Shopify.buildClient(options);
export async function fetchAllProducts(): Promise<any[]> {
return client.product.fetchAll();
}
export async function fetchAllProductIds(): Promise<string[]> {
const products = await fetchAllProducts();
return products.map((x: any) => x.id);
}
export async function fetchAllVariants(): Promise<any[]> {
const products = await fetchAllProducts();
let variants: any[] = [];
for (const product of products) {
variants = variants.concat(product.variants);
}
return variants;
}
export async function fetchAllVariantIds(): Promise<{ }> {
const variants = await fetchAllVariants();
return variants.map((x: any) => ({
gid: x.id,
name: x.title,
}));
}
| // 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.
/**
* Dev helpers for looking up Shopify stuff.
* import them somewhere if you need them.
*/
import Shopify from 'shopify-buy';
const options = {
domain: process.env.SHOPIFY_DOMAIN,
storefrontAccessToken: process.env.SHOPIFY_STOREFRONT_TOKEN,
};
const client = Shopify.buildClient(options);
export function fetchAllProducts(): Promise<any[]> {
return client.product.fetchAll();
}
export async function fetchAllProductIds(): Promise<string[]> {
const products = await fetchAllProducts();
return products.map((x: any) => x.id);
}
export async function fetchAllVariants(): Promise<any[]> {
const products = await fetchAllProducts();
let variants: any[] = [];
for (const product of products) {
variants = variants.concat(product.variants);
}
return variants;
}
export async function fetchAllVariantIds(): Promise<{ }> {
const variants = await fetchAllVariants();
return variants.map((x: any) => ({
gid: x.id,
name: x.title,
}));
}
| Remove async keyword on function without await | Remove async keyword on function without await
| TypeScript | agpl-3.0 | nanaya/osu-web,notbakaneko/osu-web,nanaya/osu-web,LiquidPL/osu-web,ppy/osu-web,LiquidPL/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,nanaya/osu-web,nanaya/osu-web,ppy/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,ppy/osu-web,LiquidPL/osu-web,nanaya/osu-web,ppy/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,ppy/osu-web | ---
+++
@@ -15,7 +15,7 @@
const client = Shopify.buildClient(options);
-export async function fetchAllProducts(): Promise<any[]> {
+export function fetchAllProducts(): Promise<any[]> {
return client.product.fetchAll();
}
|
8ccd95b8a7c9097196c6ea1262cd45aa0101a5dc | src/common/rxjs-extensions.ts | src/common/rxjs-extensions.ts | // Import just the rxjs statics and operators needed for NG2D3
// @credit John Papa"s https://git.io/v14aZ
// Observable class extensions
import "rxjs/add/observable/fromevent";
// Observable operators
import "rxjs/add/operator/debounceTime";
| // Import just the rxjs statics and operators needed for NG2D3
// @credit John Papa"s https://git.io/v14aZ
// Observable class extensions
import "rxjs/add/observable/fromEvent";
// Observable operators
import "rxjs/add/operator/debounceTime";
| Fix Rx module import casing | Fix Rx module import casing
This removes test warnings
| TypeScript | mit | kylebulkley/ngx-charts,Luukschoen/ngx-frozen,kylebulkley/ngx-charts,Luukschoen/ngx-frozen | ---
+++
@@ -2,7 +2,7 @@
// @credit John Papa"s https://git.io/v14aZ
// Observable class extensions
-import "rxjs/add/observable/fromevent";
+import "rxjs/add/observable/fromEvent";
// Observable operators
import "rxjs/add/operator/debounceTime"; |
4e6d6720eebfab561dd17843a95a6c95692add90 | src/ts/worker/senders.ts | src/ts/worker/senders.ts | import { ClearMessage, DisplayMessage } from '../messages'
import { State } from './state'
import { charToCodePoint, stringToUtf8ByteArray } from '../util'
export function sendClear() {
const message: ClearMessage = {
action: 'clear'
}
postMessage(message)
}
export function sendCharacter(input?: string) {
if (input === undefined) {
// TODO sendDone()
return
}
const codePoint = charToCodePoint(input)
const block = getBlock(codePoint)
const bytes = getBytes(input)
const character = input
const name = (State.names) ? State.names[codePoint] || 'Unknown' : 'Loading…'
const message: DisplayMessage = {
action: 'display',
block,
bytes,
character,
codePoint,
name
}
postMessage(message)
}
function getBlock(codePoint: number): string {
if (!State.blocks) return 'Loading…'
for (const block of State.blocks) {
if (codePoint >= Number(block.start) && codePoint <= Number(block.end)) return block.name
}
return 'Unknown'
}
function getBytes(input: string): string {
return stringToUtf8ByteArray(input)
.map(byte => byte.toString(16).toUpperCase())
.map(byte => byte.length < 2 ? '0' + byte : byte)
.join(' ')
}
| import { ClearMessage, DisplayMessage } from '../messages'
import { State } from './state'
import { charToCodePoint, stringToUtf8ByteArray } from '../util'
export function sendClear() {
const message: ClearMessage = {
action: 'clear'
}
postMessage(message)
}
export function sendCharacter(input?: string) {
if (input === undefined) {
// TODO sendDone()
return
}
const codePoint = charToCodePoint(input)
const block = getBlock(codePoint)
const bytes = getBytes(input)
const character = input
const name = (State.names) ? State.names[codePoint] || 'Unknown' : 'Loading…'
const message: DisplayMessage = {
action: 'display',
block: block,
bytes: bytes,
character: character,
codePoint: codePoint,
name: name
}
postMessage(message)
}
function getBlock(codePoint: number): string {
if (!State.blocks) return 'Loading…'
for (const block of State.blocks) {
if (codePoint >= Number(block.start) && codePoint <= Number(block.end)) return block.name
}
return 'Unknown'
}
function getBytes(input: string): string {
return stringToUtf8ByteArray(input)
.map(byte => byte.toString(16).toUpperCase())
.map(byte => byte.length < 2 ? '0' + byte : byte)
.join(' ')
}
| Remove object property shorthand for typescript bug | Remove object property shorthand for typescript bug
https://github.com/rollup/rollup-plugin-typescript/issues/40
| TypeScript | mit | Alexendoo/utf,Alexendoo/utf,Alexendoo/utf,Alexendoo/utf | ---
+++
@@ -24,11 +24,11 @@
const message: DisplayMessage = {
action: 'display',
- block,
- bytes,
- character,
- codePoint,
- name
+ block: block,
+ bytes: bytes,
+ character: character,
+ codePoint: codePoint,
+ name: name
}
postMessage(message) |
360e919fbf0cf532970cbe65ddac74a92e0be03e | src/question_dropdown.ts | src/question_dropdown.ts | // <reference path="question_selectbase.ts" />
/// <reference path="questionfactory.ts" />
/// <reference path="jsonobject.ts" />
module Survey {
<<<<<<< HEAD
export class QuestionDropdownModel extends QuestionSelectBase {
=======
export class QuestionDropdown extends QuestionSelectBase {
>>>>>>> refs/remotes/origin/master
private optionsCaptionValue: string;
constructor(public name: string) {
super(name);
}
public get optionsCaption() { return (this.optionsCaptionValue) ? this.optionsCaptionValue : surveyStrings.optionsCaption; }
public set optionsCaption(newValue: string) { this.optionsCaptionValue = newValue; }
public getType(): string {
return "dropdown";
}
}
<<<<<<< HEAD
JsonObject.metaData.addClass("dropdown", ["optionsCaption"], function () { return new QuestionDropdownModel(""); }, "selectbase");
JsonObject.metaData.setPropertyValues("dropdown", "optionsCaption", null, null,
function (obj: any) { return obj.optionsCaptionValue; });
QuestionFactory.Instance.registerQuestion("dropdown", (name) => { var q = new QuestionDropdownModel(name); q.choices = QuestionFactory.DefaultChoices; return q; });
=======
JsonObject.metaData.addClass("dropdown", ["optionsCaption"], function () { return new QuestionDropdown(""); }, "selectbase");
JsonObject.metaData.setPropertyValues("dropdown", "optionsCaption", null, null,
function (obj: any) { return obj.optionsCaptionValue; });
QuestionFactory.Instance.registerQuestion("dropdown", (name) => { var q = new QuestionDropdown(name); q.choices = QuestionFactory.DefaultChoices; return q; });
>>>>>>> refs/remotes/origin/master
} | // <reference path="question_selectbase.ts" />
/// <reference path="questionfactory.ts" />
/// <reference path="jsonobject.ts" />
module Survey {
export class QuestionDropdownModel extends QuestionSelectBase {
private optionsCaptionValue: string;
constructor(public name: string) {
super(name);
}
public get optionsCaption() { return (this.optionsCaptionValue) ? this.optionsCaptionValue : surveyStrings.optionsCaption; }
public set optionsCaption(newValue: string) { this.optionsCaptionValue = newValue; }
public getType(): string {
return "dropdown";
}
}
JsonObject.metaData.addClass("dropdown", ["optionsCaption"], function () { return new QuestionDropdownModel(""); }, "selectbase");
JsonObject.metaData.setPropertyValues("dropdown", "optionsCaption", null, null,
function (obj: any) { return obj.optionsCaptionValue; });
QuestionFactory.Instance.registerQuestion("dropdown", (name) => { var q = new QuestionDropdownModel(name); q.choices = QuestionFactory.DefaultChoices; return q; });
} | Solve the conflict after merging the branch | Solve the conflict after merging the branch
| TypeScript | mit | mirmdasif/surveyjs,espadana/surveyjs,dmitrykurmanov/surveyjs,surveyjs/surveyjs,espadana/surveyjs,iFacts/surveyjs,andrewtelnov/surveyjs,dmitrykurmanov/surveyjs,surveyjs/surveyjs,surveyjs/surveyjs,andrewtelnov/surveyjs,dmitrykurmanov/surveyjs,iFacts/surveyjs,surveyjs/surveyjs,andrewtelnov/surveyjs,espadana/surveyjs,espadana/surveyjs,mirmdasif/surveyjs,iFacts/surveyjs,dmitrykurmanov/surveyjs,mirmdasif/surveyjs,iFacts/surveyjs | ---
+++
@@ -2,11 +2,7 @@
/// <reference path="questionfactory.ts" />
/// <reference path="jsonobject.ts" />
module Survey {
-<<<<<<< HEAD
export class QuestionDropdownModel extends QuestionSelectBase {
-=======
- export class QuestionDropdown extends QuestionSelectBase {
->>>>>>> refs/remotes/origin/master
private optionsCaptionValue: string;
constructor(public name: string) {
super(name);
@@ -17,17 +13,9 @@
return "dropdown";
}
}
-<<<<<<< HEAD
JsonObject.metaData.addClass("dropdown", ["optionsCaption"], function () { return new QuestionDropdownModel(""); }, "selectbase");
JsonObject.metaData.setPropertyValues("dropdown", "optionsCaption", null, null,
function (obj: any) { return obj.optionsCaptionValue; });
QuestionFactory.Instance.registerQuestion("dropdown", (name) => { var q = new QuestionDropdownModel(name); q.choices = QuestionFactory.DefaultChoices; return q; });
-=======
- JsonObject.metaData.addClass("dropdown", ["optionsCaption"], function () { return new QuestionDropdown(""); }, "selectbase");
- JsonObject.metaData.setPropertyValues("dropdown", "optionsCaption", null, null,
- function (obj: any) { return obj.optionsCaptionValue; });
-
- QuestionFactory.Instance.registerQuestion("dropdown", (name) => { var q = new QuestionDropdown(name); q.choices = QuestionFactory.DefaultChoices; return q; });
->>>>>>> refs/remotes/origin/master
} |
8261e4bdb784da87fe21645b531a3d3fd4356a60 | test/src/tests/SDK.REST/input-args.ts | test/src/tests/SDK.REST/input-args.ts | import { expect } from 'chai';
import { suite, test, slow, timeout, skip, only } from "mocha-typescript";
import FakeRequests from '../common/fakeRequests';
import * as sinon from 'sinon';
@suite
class SdkRestInputArgs extends FakeRequests {
@test
"check that it can take strings"() {
const accountGuid = "SOME-GUID";
let callback = sinon.spy();
SDK.REST.retrieveRecord(accountGuid, "Account", "accountnumber", "primarycontact", callback, () => { expect.fail() });
// Check requests
expect(this.requests.length).to.equal(1);
const req = this.requests[0];
console.log(req);
// Respond
const responseCheck = { name: "it-works" };
req.respond(200, {}, JSON.stringify({ d: responseCheck }));
console.log(req);
sinon.assert.calledWith(callback, responseCheck);
}
@test
"check that it can take null at select and expand"() {
const accountGuid = "SOME-GUID";
let callback = sinon.spy();
SDK.REST.retrieveRecord(accountGuid, "Account", null, null, callback, () => { expect.fail() });
// Check requests
expect(this.requests.length).to.equal(1);
const req = this.requests[0];
console.log(req);
// Respond
const responseCheck = { name: "it-works" };
req.respond(200, {}, JSON.stringify({ d: responseCheck }));
console.log(req);
sinon.assert.calledWith(callback, responseCheck);
}
} | import { expect } from 'chai';
import { suite, test, slow, timeout, skip, only } from "mocha-typescript";
import FakeRequests from '../common/fakeRequests';
import * as sinon from 'sinon';
@suite
class SdkRestInputArgs extends FakeRequests {
@test
"check that it can take strings"() {
const accountGuid = "SOME-GUID";
let callback = sinon.spy();
SDK.REST.retrieveRecord(accountGuid, "Account", "accountnumber", "primarycontact", callback, () => { expect.fail() });
// Check requests
expect(this.requests.length).to.equal(1);
const req = this.requests[0];
// Respond
const responseCheck = { name: "it-works" };
req.respond(200, {}, JSON.stringify({ d: responseCheck }));
sinon.assert.calledWith(callback, responseCheck);
}
@test
"check that it can take null at select and expand"() {
const accountGuid = "SOME-GUID";
let callback = sinon.spy();
SDK.REST.retrieveRecord(accountGuid, "Account", null, null, callback, () => { expect.fail() });
// Check requests
expect(this.requests.length).to.equal(1);
const req = this.requests[0];
// Respond
const responseCheck = { name: "it-works" };
req.respond(200, {}, JSON.stringify({ d: responseCheck }));
sinon.assert.calledWith(callback, responseCheck);
}
} | Remove console.logs in a few tests | Remove console.logs in a few tests
| TypeScript | mit | delegateas/XrmDefinitelyTyped,delegateas/XrmDefinitelyTyped,delegateas/Delegate.XrmDefinitelyTyped,delegateas/Delegate.XrmDefinitelyTyped | ---
+++
@@ -16,13 +16,11 @@
// Check requests
expect(this.requests.length).to.equal(1);
const req = this.requests[0];
- console.log(req);
// Respond
const responseCheck = { name: "it-works" };
req.respond(200, {}, JSON.stringify({ d: responseCheck }));
- console.log(req);
sinon.assert.calledWith(callback, responseCheck);
}
@@ -36,13 +34,11 @@
// Check requests
expect(this.requests.length).to.equal(1);
const req = this.requests[0];
- console.log(req);
// Respond
const responseCheck = { name: "it-works" };
req.respond(200, {}, JSON.stringify({ d: responseCheck }));
- console.log(req);
sinon.assert.calledWith(callback, responseCheck);
}
|
652c31e1c65a4cd6924adcf86ecebfcadc70a79b | packages/components/containers/login/LoginTotpInput.tsx | packages/components/containers/login/LoginTotpInput.tsx | import React from 'react';
import { Input } from '../../components';
interface Props {
totp: string;
setTotp: (totp: string) => void;
id: string;
}
const LoginTotpInput = ({ totp, setTotp, id }: Props) => {
return (
<Input
type="text"
name="twoFa"
autoFocus
autoCapitalize="off"
autoCorrect="off"
id={id}
required
value={totp}
className="w100 mb1"
placeholder="123456"
onChange={({ target: { value } }) => setTotp(value)}
data-cy-login="TOTP"
/>
);
};
export default LoginTotpInput;
| import React from 'react';
import { Input } from '../../components';
interface Props {
totp: string;
setTotp: (totp: string) => void;
id: string;
}
const LoginTotpInput = ({ totp, setTotp, id }: Props) => {
return (
<Input
type="text"
name="twoFa"
autoFocus
autoCapitalize="off"
autoCorrect="off"
id={id}
required
value={totp}
className="w100"
placeholder="123456"
onChange={({ target: { value } }) => setTotp(value)}
data-cy-login="TOTP"
/>
);
};
export default LoginTotpInput;
| Remove mb1 from login totp input | Remove mb1 from login totp input
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -17,7 +17,7 @@
id={id}
required
value={totp}
- className="w100 mb1"
+ className="w100"
placeholder="123456"
onChange={({ target: { value } }) => setTotp(value)}
data-cy-login="TOTP" |
46d90cc4ebeb3a98a7afda6a91c53ef9c8e7d787 | src/images/actions.tsx | src/images/actions.tsx | import * as Axios from "axios";
import { Thunk } from "../redux/interfaces";
import { Point } from "../farm_designer/interfaces";
import { API } from "../api";
import { success, error } from "../ui";
import { t } from "i18next";
const QUERY = { meta: { created_by: "plant-detection" } };
const URL = API.current.pointSearchPath;
export function resetWeedDetection(): Thunk {
return async function (dispatch, getState) {
try {
let { data } = await Axios.post<Point[]>(URL, QUERY);
let ids = data.map(x => x.id);
// If you delete too many points, you will violate the URL length
// limitation of 2,083. Chunking helps fix that.
let chunks = _.chunk(ids, 300).map(function (chunk) {
return Axios.delete(API.current.pointsPath + ids.join(","));
});
Promise.all(chunks)
.then(function () {
dispatch({
type: "DELETE_POINT_OK",
payload: ids
});
success(t("Deleted {{num}} weeds", { num: ids.length }));
})
.catch(function (e) {
console.dir(e);
error(t("Some weeds failed to delete. Please try again."));
});
} catch (e) {
throw e;
}
};
};
| import * as Axios from "axios";
import { Thunk } from "../redux/interfaces";
import { Point } from "../farm_designer/interfaces";
import { API } from "../api";
import { success, error } from "../ui";
import { t } from "i18next";
const QUERY = { meta: { created_by: "plant-detection" } };
const URL = API.current.pointSearchPath;
export function resetWeedDetection(): Thunk {
return async function (dispatch, getState) {
try {
let { data } = await Axios.post<Point[]>(URL, QUERY);
let ids = data.map(x => x.id);
// If you delete too many points, you will violate the URL length
// limitation of 2,083. Chunking helps fix that.
let chunks = _.chunk(ids, 100).map(function (chunk) {
return Axios.delete(API.current.pointsPath + ids.join(","));
});
Promise.all(chunks)
.then(function () {
dispatch({
type: "DELETE_POINT_OK",
payload: ids
});
success(t("Deleted {{num}} weeds", { num: ids.length }));
})
.catch(function (e) {
console.dir(e);
error(t("Some weeds failed to delete. Please try again."));
});
} catch (e) {
throw e;
}
};
};
| Reduce weed deletion chunk size to 100 from 300 to hopefully fix bugs | Reduce weed deletion chunk size to 100 from 300 to hopefully fix bugs
| TypeScript | mit | RickCarlino/farmbot-web-frontend,RickCarlino/farmbot-web-frontend,FarmBot/farmbot-web-frontend,FarmBot/farmbot-web-frontend,MrChristofferson/farmbot-web-frontend,MrChristofferson/farmbot-web-frontend | ---
+++
@@ -15,7 +15,7 @@
let ids = data.map(x => x.id);
// If you delete too many points, you will violate the URL length
// limitation of 2,083. Chunking helps fix that.
- let chunks = _.chunk(ids, 300).map(function (chunk) {
+ let chunks = _.chunk(ids, 100).map(function (chunk) {
return Axios.delete(API.current.pointsPath + ids.join(","));
});
Promise.all(chunks) |
2a09617f8e2ab72e572272fd32107bb9f7e83a99 | helpers/date.ts | helpers/date.ts | import HelperObject from "./object";
export default class HelperDate {
public static getDate(date: Date): Date {
let temp: Date = HelperObject.clone(date);
temp.setHours(0);
temp.setMinutes(0);
temp.setSeconds(0);
temp.setMilliseconds(0);
return temp;
}
}
| import * as moment from "moment";
import HelperObject from "./object";
export default class HelperDate {
public static getDate(date: Date): Date {
let temp: Date = HelperObject.clone(date);
temp.setHours(0);
temp.setMinutes(0);
temp.setSeconds(0);
temp.setMilliseconds(0);
return temp;
}
public static getMonthsBetween(start: Date, end: Date): number[] {
let months: number[] = [];
for (let i: number = start.getMonth(); i <= end.getMonth(); i++) {
months.push(i);
}
return months;
}
public static getWeeksBetween(start: Date, end: Date): {
number: number,
start: Date } [] {
let weeks: { number: number, start: Date }[] = [];
let interval: number = 1000 * 60 * 60 * 24 * 7; // 1 week
for (let i: number = start.getTime(); i <= end.getTime(); i += interval) {
let start: Date = new Date(i);
weeks.push({
number: moment(start).week(),
start: start
});
}
return weeks;
};
}
| Implement duration helpers in HelperDate | Implement duration helpers in HelperDate
| TypeScript | mit | crossroads-education/eta,crossroads-education/eta | ---
+++
@@ -1,3 +1,4 @@
+import * as moment from "moment";
import HelperObject from "./object";
export default class HelperDate {
@@ -9,4 +10,27 @@
temp.setMilliseconds(0);
return temp;
}
+
+ public static getMonthsBetween(start: Date, end: Date): number[] {
+ let months: number[] = [];
+ for (let i: number = start.getMonth(); i <= end.getMonth(); i++) {
+ months.push(i);
+ }
+ return months;
+ }
+
+ public static getWeeksBetween(start: Date, end: Date): {
+ number: number,
+ start: Date } [] {
+ let weeks: { number: number, start: Date }[] = [];
+ let interval: number = 1000 * 60 * 60 * 24 * 7; // 1 week
+ for (let i: number = start.getTime(); i <= end.getTime(); i += interval) {
+ let start: Date = new Date(i);
+ weeks.push({
+ number: moment(start).week(),
+ start: start
+ });
+ }
+ return weeks;
+ };
} |
458a4f444aa05ce1c4e0f816f34b973e5cf67448 | __tests__/main.test.ts | __tests__/main.test.ts | import { Delays, greeter } from '../src/main';
describe('greeter function', () => {
const name = 'John';
let hello: string;
// Act before assertions
beforeAll(async () => {
// Read more about fake timers
// http://facebook.github.io/jest/docs/en/timer-mocks.html#content
jest.useFakeTimers('legacy');
const p: Promise<string> = greeter(name);
jest.runOnlyPendingTimers();
hello = await p;
});
// Assert if setTimeout was called properly
it('delays the greeting by 2 seconds', () => {
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(
expect.any(Function),
Delays.Long,
);
});
// Assert greeter result
it('greets a user with `Hello, {name}` message', () => {
expect(hello).toBe(`Hello, ${name}`);
});
});
| import { Delays, greeter } from '../src/main';
describe('greeter function', () => {
const name = 'John';
let hello: string;
let timeoutSpy: jest.SpyInstance;
// Act before assertions
beforeAll(async () => {
// Read more about fake timers
// http://facebook.github.io/jest/docs/en/timer-mocks.html#content
// Jest 27 now uses "modern" implementation of fake timers
// https://jestjs.io/blog/2021/05/25/jest-27#flipping-defaults
// https://github.com/facebook/jest/pull/5171
jest.useFakeTimers();
timeoutSpy = jest.spyOn(global, 'setTimeout');
const p: Promise<string> = greeter(name);
jest.runOnlyPendingTimers();
hello = await p;
});
// Teardown (cleanup) after assertions
afterAll(() => {
timeoutSpy.mockRestore();
});
// Assert if setTimeout was called properly
it('delays the greeting by 2 seconds', () => {
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(
expect.any(Function),
Delays.Long,
);
});
// Assert greeter result
it('greets a user with `Hello, {name}` message', () => {
expect(hello).toBe(`Hello, ${name}`);
});
});
| Support Jest modern Fake Timers | Support Jest modern Fake Timers
| TypeScript | apache-2.0 | jsynowiec/node-typescript-boilerplate,jsynowiec/node-typescript-boilerplate | ---
+++
@@ -4,15 +4,26 @@
const name = 'John';
let hello: string;
+ let timeoutSpy: jest.SpyInstance;
+
// Act before assertions
beforeAll(async () => {
// Read more about fake timers
// http://facebook.github.io/jest/docs/en/timer-mocks.html#content
- jest.useFakeTimers('legacy');
+ // Jest 27 now uses "modern" implementation of fake timers
+ // https://jestjs.io/blog/2021/05/25/jest-27#flipping-defaults
+ // https://github.com/facebook/jest/pull/5171
+ jest.useFakeTimers();
+ timeoutSpy = jest.spyOn(global, 'setTimeout');
const p: Promise<string> = greeter(name);
jest.runOnlyPendingTimers();
hello = await p;
+ });
+
+ // Teardown (cleanup) after assertions
+ afterAll(() => {
+ timeoutSpy.mockRestore();
});
// Assert if setTimeout was called properly |
62833dffe00fa02fe68af03febaded59fdf2f5d4 | annotator.component.ts | annotator.component.ts | import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'annotator',
templateUrl: './annotator.component.html',
styleUrls: ['./annotator.component.css'],
})
export class AnnotatorComponent {
constructor(
public router: Router,
) { }
actionBack(): void {
this.router.navigate(['./dataview']);
}
getClip(): any {
//return this.alveoService.audioData;
return null;
}
getClipName(): string {
return "";
}
}
| import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AlveoService } from '../alveo/shared/alveo.service';
@Component({
selector: 'annotator',
templateUrl: './annotator.component.html',
styleUrls: ['./annotator.component.css'],
})
export class AnnotatorComponent {
constructor(
public router: Router,
public alveoService: AlveoService,
) { }
actionBack(): void {
this.router.navigate(['./dataview']);
}
getClip(): any {
return this.alveoService.audioData;
}
getClipName(): string {
return "";
}
}
| Call audioData from Alveo module (for now) | Call audioData from Alveo module (for now)
| TypeScript | bsd-3-clause | Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber | ---
+++
@@ -1,5 +1,7 @@
import { Component } from '@angular/core';
import { Router } from '@angular/router';
+
+import { AlveoService } from '../alveo/shared/alveo.service';
@Component({
selector: 'annotator',
@@ -10,6 +12,7 @@
export class AnnotatorComponent {
constructor(
public router: Router,
+ public alveoService: AlveoService,
) { }
actionBack(): void {
@@ -17,8 +20,7 @@
}
getClip(): any {
- //return this.alveoService.audioData;
- return null;
+ return this.alveoService.audioData;
}
getClipName(): string { |
c84f7ff458769620264b379e1694f4132c8aeca7 | tools/env/base.ts | tools/env/base.ts | import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.14.0',
RELEASEVERSION: '0.14.0'
};
export = BaseConfig;
| import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.14.1',
RELEASEVERSION: '0.14.1'
};
export = BaseConfig;
| Update release version to 0.14.1. | Update release version to 0.14.1.
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -3,8 +3,8 @@
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
- RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.14.0',
- RELEASEVERSION: '0.14.0'
+ RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.14.1',
+ RELEASEVERSION: '0.14.1'
};
export = BaseConfig; |
d17175f69f55d5dab22cb27eeb7bc254d994f26b | src/content.ts | src/content.ts | import { Error } from "enonic-fp/lib/common";
import { Either, map } from "fp-ts/lib/Either";
import { pipe } from "fp-ts/lib/pipeable";
import { Content, publish } from "enonic-fp/lib/content";
export function publishFromDraftToMaster(content: Content) : Either<Error, Content> {
return pipe(
publish({
keys: [content._id],
sourceBranch: 'draft',
targetBranch: 'master',
}),
map(() => content)
);
}
export function publishContentByKey<T>(key: string) : (t: T) => Either<Error, T> {
return t => {
return pipe(
publish({
keys: [key],
sourceBranch: 'draft',
targetBranch: 'master',
}),
map(() => t)
);
}
}
| import { Error } from "enonic-fp/lib/common";
import { Either, map, chain } from "fp-ts/lib/Either";
import { pipe } from "fp-ts/lib/pipeable";
import {
Content,
publish,
ModifyContentParams,
create,
CreateContentParams,
DeleteContentParams,
remove,
modify
} from "enonic-fp/lib/content";
import {runInDraftContext} from './context';
export function publishFromDraftToMaster<A>(content: Content<A>) : Either<Error, Content<A>> {
return pipe(
publish({
keys: [content._id],
sourceBranch: 'draft',
targetBranch: 'master',
}),
map(() => content)
);
}
export function publishContentByKey<A>(key: string) : (a: A) => Either<Error, A> {
return a => {
return pipe(
publish({
keys: [key],
sourceBranch: 'draft',
targetBranch: 'master',
}),
map(() => a)
);
}
}
export function applyChangesToData<A>(key: string, changes: any) : ModifyContentParams<A> {
return {
key,
editor: (content: Content<A>) => {
content.data = {
...content.data,
...changes
};
return content;
},
requireValid: true
};
}
export function createAndPublish<A>(params: CreateContentParams<A>) : Either<Error, Content<A>> {
return pipe(
runInDraftContext(create)(params),
chain(publishFromDraftToMaster)
);
}
export function deleteAndPublish(params: DeleteContentParams) : Either<Error, boolean> {
return pipe(
runInDraftContext(remove)(params),
chain(publishContentByKey(params.key))
);
}
export function modifyAndPublish<A>(key: string, changes: any) : Either<Error, Content<A>> {
return pipe(
runInDraftContext(modify)(applyChangesToData<A>(key, changes)),
chain(publishFromDraftToMaster)
);
}
| Add crud operations that also publish | Add crud operations that also publish
Adding pre-baked versions of create, modify, and delete, that also
publishes, since the most common use-case is to use them together.
Closes #7
| TypeScript | mit | ItemConsulting/wizardry | ---
+++
@@ -1,9 +1,19 @@
import { Error } from "enonic-fp/lib/common";
-import { Either, map } from "fp-ts/lib/Either";
+import { Either, map, chain } from "fp-ts/lib/Either";
import { pipe } from "fp-ts/lib/pipeable";
-import { Content, publish } from "enonic-fp/lib/content";
+import {
+ Content,
+ publish,
+ ModifyContentParams,
+ create,
+ CreateContentParams,
+ DeleteContentParams,
+ remove,
+ modify
+} from "enonic-fp/lib/content";
+import {runInDraftContext} from './context';
-export function publishFromDraftToMaster(content: Content) : Either<Error, Content> {
+export function publishFromDraftToMaster<A>(content: Content<A>) : Either<Error, Content<A>> {
return pipe(
publish({
keys: [content._id],
@@ -14,15 +24,51 @@
);
}
-export function publishContentByKey<T>(key: string) : (t: T) => Either<Error, T> {
- return t => {
+export function publishContentByKey<A>(key: string) : (a: A) => Either<Error, A> {
+ return a => {
return pipe(
publish({
keys: [key],
sourceBranch: 'draft',
targetBranch: 'master',
}),
- map(() => t)
+ map(() => a)
);
}
}
+
+export function applyChangesToData<A>(key: string, changes: any) : ModifyContentParams<A> {
+ return {
+ key,
+ editor: (content: Content<A>) => {
+ content.data = {
+ ...content.data,
+ ...changes
+ };
+
+ return content;
+ },
+ requireValid: true
+ };
+}
+
+export function createAndPublish<A>(params: CreateContentParams<A>) : Either<Error, Content<A>> {
+ return pipe(
+ runInDraftContext(create)(params),
+ chain(publishFromDraftToMaster)
+ );
+}
+
+export function deleteAndPublish(params: DeleteContentParams) : Either<Error, boolean> {
+ return pipe(
+ runInDraftContext(remove)(params),
+ chain(publishContentByKey(params.key))
+ );
+}
+
+export function modifyAndPublish<A>(key: string, changes: any) : Either<Error, Content<A>> {
+ return pipe(
+ runInDraftContext(modify)(applyChangesToData<A>(key, changes)),
+ chain(publishFromDraftToMaster)
+ );
+} |
4fabe7f748a315e5ac6c720092aad7c3f43b888f | src/elmMain.ts | src/elmMain.ts | import * as vscode from 'vscode';
import {createDiagnostics} from './elmCheck';
// this method is called when your extension is activated
export function activate(disposables: vscode.Disposable[]) {
vscode.workspace.onDidSaveTextDocument(document => {
createDiagnostics(document);
})
}
| import * as vscode from 'vscode';
import {createDiagnostics} from './elmCheck';
// this method is called when your extension is activated
export function activate(ctx: vscode.ExtensionContext) {
ctx.subscriptions.push(vscode.workspace.onDidSaveTextDocument(document => {
createDiagnostics(document);
}))
}
| Add linting function to extension subsriptions | Add linting function to extension subsriptions
| TypeScript | mit | Krzysztof-Cieslak/vscode-elm,sbrink/vscode-elm | ---
+++
@@ -2,8 +2,8 @@
import {createDiagnostics} from './elmCheck';
// this method is called when your extension is activated
-export function activate(disposables: vscode.Disposable[]) {
- vscode.workspace.onDidSaveTextDocument(document => {
+export function activate(ctx: vscode.ExtensionContext) {
+ ctx.subscriptions.push(vscode.workspace.onDidSaveTextDocument(document => {
createDiagnostics(document);
- })
+ }))
} |
2af048b05e93445097e6535ddf17ab1c31278bda | src/lib/geospatial.ts | src/lib/geospatial.ts | interface LatLng {
lat: number
lng: number
}
const EARTH_RADIUS_IN_METERS = 6371e3
const toRadians = (degrees: number): number => degrees * (Math.PI / 180)
const haversineDistance = (point1: LatLng, point2: LatLng): number => {
const φ1 = toRadians(point1.lat)
const φ2 = toRadians(point2.lat)
const Δφ = toRadians(point2.lat - point1.lat)
const Δλ = toRadians(point2.lng - point1.lng)
const a =
Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2)
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
return EARTH_RADIUS_IN_METERS * c
}
export { haversineDistance as distance }
| interface LatLng {
lat: number
lng: number
}
const EARTH_RADIUS_IN_METERS = 6371e3 // https://en.wikipedia.org/wiki/Earth_radius#Mean_radius
/**
* Convert angular distance from degrees to radians
*
* @param {number} degrees - decimal degrees
* @returns {number} radians
*/
const toRadians = (degrees: number): number => degrees * (Math.PI / 180)
/**
* Calculates the haversine (spherical) distance between two geographic points.
* Arguments are supplied as `LatLng` objects, with coordinates specified
* as `lat` and `lng` properties in decimal degrees.
*
* See:
* https://en.wikipedia.org/wiki/Haversine_formula
* https://www.movable-type.co.uk/scripts/latlong.html
*
* @param {LatLng} point1 - an object with `lat` and `lng` properties
* @param {LatLng} point2 - an object with `lat` and `lng` properties
* @returns {number} Distance between point1 and point2, in meters
*/
const haversineDistance = (point1: LatLng, point2: LatLng): number => {
const φ1 = toRadians(point1.lat)
const φ2 = toRadians(point2.lat)
const Δφ = toRadians(point2.lat - point1.lat)
const Δλ = toRadians(point2.lng - point1.lng)
const a =
Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2)
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
return EARTH_RADIUS_IN_METERS * c
}
export { haversineDistance as distance }
| Add docs to geo lib functions | Add docs to geo lib functions
| TypeScript | mit | artsy/metaphysics,artsy/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1 | ---
+++
@@ -3,10 +3,29 @@
lng: number
}
-const EARTH_RADIUS_IN_METERS = 6371e3
+const EARTH_RADIUS_IN_METERS = 6371e3 // https://en.wikipedia.org/wiki/Earth_radius#Mean_radius
+/**
+ * Convert angular distance from degrees to radians
+ *
+ * @param {number} degrees - decimal degrees
+ * @returns {number} radians
+ */
const toRadians = (degrees: number): number => degrees * (Math.PI / 180)
+/**
+ * Calculates the haversine (spherical) distance between two geographic points.
+ * Arguments are supplied as `LatLng` objects, with coordinates specified
+ * as `lat` and `lng` properties in decimal degrees.
+ *
+ * See:
+ * https://en.wikipedia.org/wiki/Haversine_formula
+ * https://www.movable-type.co.uk/scripts/latlong.html
+ *
+ * @param {LatLng} point1 - an object with `lat` and `lng` properties
+ * @param {LatLng} point2 - an object with `lat` and `lng` properties
+ * @returns {number} Distance between point1 and point2, in meters
+ */
const haversineDistance = (point1: LatLng, point2: LatLng): number => {
const φ1 = toRadians(point1.lat)
const φ2 = toRadians(point2.lat) |
701ab3dd97235080692686b6188ceb1ed510e401 | packages/components/containers/invoices/InvoiceState.tsx | packages/components/containers/invoices/InvoiceState.tsx | import { c } from 'ttag';
import { INVOICE_STATE } from '@proton/shared/lib/constants';
import { Badge } from '../../components';
import { Invoice } from './interface';
const TYPES = {
[INVOICE_STATE.UNPAID]: 'error',
[INVOICE_STATE.PAID]: 'success',
[INVOICE_STATE.VOID]: 'default',
[INVOICE_STATE.BILLED]: 'default',
[INVOICE_STATE.WRITEOFF]: 'default',
} as const;
const getStatesI18N = (invoiceState: INVOICE_STATE) => {
switch (invoiceState) {
case INVOICE_STATE.UNPAID:
return c('Invoice state display as badge').t`Unpaid`;
case INVOICE_STATE.PAID:
return c('Invoice state display as badge').t`Paid`;
case INVOICE_STATE.VOID:
return c('Invoice state display as badge').t`Void`;
case INVOICE_STATE.BILLED:
return c('Invoice state display as badge').t`Billed`;
case INVOICE_STATE.WRITEOFF:
return c('Invoice state display as badge').t`Writeoff`;
default:
return '';
}
};
interface Props {
invoice: Invoice;
}
const InvoiceState = ({ invoice }: Props) => {
return <Badge type={TYPES[invoice.State] || 'default'}>{getStatesI18N(invoice.State)}</Badge>;
};
export default InvoiceState;
| import { c } from 'ttag';
import { INVOICE_STATE } from '@proton/shared/lib/constants';
import { Badge } from '../../components';
import { Invoice } from './interface';
const TYPES = {
[INVOICE_STATE.UNPAID]: 'error',
[INVOICE_STATE.PAID]: 'success',
[INVOICE_STATE.VOID]: 'default',
[INVOICE_STATE.BILLED]: 'default',
[INVOICE_STATE.WRITEOFF]: 'default',
} as const;
const getStatesI18N = (invoiceState: INVOICE_STATE) => {
switch (invoiceState) {
case INVOICE_STATE.UNPAID:
return c('Invoice state display as badge').t`Unpaid`;
case INVOICE_STATE.PAID:
return c('Invoice state display as badge').t`Paid`;
case INVOICE_STATE.VOID:
return c('Invoice state display as badge').t`Void`;
case INVOICE_STATE.BILLED:
return c('Invoice state display as badge').t`Billed`;
case INVOICE_STATE.WRITEOFF:
return c('Invoice state display as badge').t`Cancelled`;
default:
return '';
}
};
interface Props {
invoice: Invoice;
}
const InvoiceState = ({ invoice }: Props) => {
return <Badge type={TYPES[invoice.State] || 'default'}>{getStatesI18N(invoice.State)}</Badge>;
};
export default InvoiceState;
| Change invoice state write-off to cancelled | Change invoice state write-off to cancelled
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -22,7 +22,7 @@
case INVOICE_STATE.BILLED:
return c('Invoice state display as badge').t`Billed`;
case INVOICE_STATE.WRITEOFF:
- return c('Invoice state display as badge').t`Writeoff`;
+ return c('Invoice state display as badge').t`Cancelled`;
default:
return '';
} |
04c3fda4881aadbdf3cf8994d1bfd7c3cea47797 | applications/desktop/src/main/kernel-specs.ts | applications/desktop/src/main/kernel-specs.ts | import { join } from "path";
import { Event, ipcMain as ipc } from "electron";
import { KernelspecInfo, Kernelspecs } from "@nteract/types";
const builtInNodeArgv: string[] = [
process.execPath,
join(__dirname, "..", "node_modules", "ijavascript", "lib", "kernel.js"),
"{connection_file}",
"--protocol=5.0",
"--hide-undefined"
];
const KERNEL_SPECS: Kernelspecs = {
node_nteract: {
name: "node_nteract",
spec: {
argv: builtInNodeArgv,
display_name: "Node.js (nteract)",
language: "javascript",
env: {
ELECTRON_RUN_AS_NODE: "1"
}
}
}
};
export default function initializeKernelSpecs(
kernelSpecs: Kernelspecs
): Kernelspecs {
Object.assign(KERNEL_SPECS, kernelSpecs);
return KERNEL_SPECS;
}
ipc.on("kernel_specs_request", (event: Event) => {
event.sender.send("kernel_specs_reply", KERNEL_SPECS);
});
| import { join } from "path";
import { Event, ipcMain as ipc } from "electron";
import { KernelspecInfo, Kernelspecs } from "@nteract/types";
const builtInNodeArgv: string[] = [
process.execPath,
join(__dirname, "..", "node_modules", "ijavascript", "lib", "kernel.js"),
"{connection_file}",
"--protocol=5.0",
"--hide-undefined"
];
const KERNEL_SPECS: Kernelspecs = {
node_nteract: {
name: "node_nteract",
spec: {
argv: builtInNodeArgv,
display_name: "Node.js (nteract)",
language: "javascript",
env: {
ELECTRON_RUN_AS_NODE: "1",
NODE_PATH: join(__dirname, "..", "node_modules")
}
}
}
};
export default function initializeKernelSpecs(
kernelSpecs: Kernelspecs
): Kernelspecs {
Object.assign(KERNEL_SPECS, kernelSpecs);
return KERNEL_SPECS;
}
ipc.on("kernel_specs_request", (event: Event) => {
event.sender.send("kernel_specs_reply", KERNEL_SPECS);
});
| Add nteract node_modules as NODE_PATH, allowing the bundled Javascript kernel access more modules out of the box | Add nteract node_modules as NODE_PATH, allowing the bundled Javascript kernel access more modules out of the box
| TypeScript | bsd-3-clause | nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract,nteract/composition,nteract/composition | ---
+++
@@ -20,7 +20,8 @@
display_name: "Node.js (nteract)",
language: "javascript",
env: {
- ELECTRON_RUN_AS_NODE: "1"
+ ELECTRON_RUN_AS_NODE: "1",
+ NODE_PATH: join(__dirname, "..", "node_modules")
}
}
} |
23601375eb7a9ecb1074fca43832958124b47f3d | webpack/__tests__/refresh_token_no_test.ts | webpack/__tests__/refresh_token_no_test.ts | jest.mock("axios", () => ({
default: {
interceptors: {
response: { use: jest.fn() },
request: { use: jest.fn() }
},
get() { return Promise.reject("NO"); }
}
}));
jest.mock("../session", () => {
return {
Session: {
clear: jest.fn(),
getBool: jest.fn(),
}
};
});
import { maybeRefreshToken } from "../refresh_token";
import { API } from "../api/index";
import { Session } from "../session";
API.setBaseUrl("http://blah.whatever.party");
describe("maybeRefreshToken()", () => {
it("logs you out when a refresh fails", (done) => {
const t = {
token: {
encoded: "---",
unencoded: {
iat: 123,
jti: "111",
iss: "---",
exp: 456,
mqtt: "---",
os_update_server: "---"
}
}
};
maybeRefreshToken(t).then(() => {
expect(Session.clear).toHaveBeenCalled();
done();
});
});
});
| jest.mock("axios", () => ({
default: {
interceptors: {
response: { use: jest.fn() },
request: { use: jest.fn() }
},
get() { return Promise.reject("NO"); }
}
}));
jest.mock("../session", () => {
return {
Session: {
clear: jest.fn(),
getBool: jest.fn(),
}
};
});
import { maybeRefreshToken } from "../refresh_token";
import { API } from "../api/index";
import { Session } from "../session";
API.setBaseUrl("http://blah.whatever.party");
describe("maybeRefreshToken()", () => {
it("logs you out when a refresh fails", (done) => {
const t = {
token: {
encoded: "---",
unencoded: {
iat: 123,
jti: "111",
iss: "---",
exp: 456,
mqtt: "---",
os_update_server: "---"
}
}
};
maybeRefreshToken(t).then((result) => {
expect(result).toBeUndefined();
done();
});
});
});
| Update failure case test of maybeRefreshToken() | Update failure case test of maybeRefreshToken()
| TypeScript | mit | RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App | ---
+++
@@ -39,8 +39,8 @@
}
}
};
- maybeRefreshToken(t).then(() => {
- expect(Session.clear).toHaveBeenCalled();
+ maybeRefreshToken(t).then((result) => {
+ expect(result).toBeUndefined();
done();
});
}); |
8fa945e35f90d92016ba2029e8e5e4f0897e0d7f | app/server/RtBroker.ts | app/server/RtBroker.ts | import {WeatherService} from './workers/WeatherService';
import {IWeatherUpdate} from '../common/interfaces/WeatherInterfaces';
import {IAccident} from '../common/interfaces/TrafficInterfaces';
import {TrafficService} from './workers/TrafficService';
import * as Rx from '@reactivex/rxjs';
export class RtBroker {
weatherService: WeatherService;
trafficService: TrafficService;
weatherPub: Rx.Subject<IWeatherUpdate>;
accidentPub: Rx.Subject<IAccident>;
constructor(public io:SocketIO.Server) {
this.weatherService = new WeatherService();
this.trafficService = new TrafficService();
this.io.on('connection', function(socket:SocketIO.Socket){
console.log(`Connect from ${socket.client.id}!`);
//console.log('Got a connection.');
});
this.weatherPub = this.weatherService.getWeatherUpdatePub();
this.weatherPub.subscribe(weatherUpdate => this.io.emit('weatherUpdate', weatherUpdate));
this.accidentPub = this.trafficService.getAccidentPub();
this.accidentPub.subscribe(accident => this.io.emit('accident', accident));
}
}
| import {WeatherService} from './workers/WeatherService';
import {IWeatherUpdate} from '../common/interfaces/WeatherInterfaces';
import {IAccident} from '../common/interfaces/TrafficInterfaces';
import {TrafficService} from './workers/TrafficService';
import * as Rx from '@reactivex/rxjs';
export class RtBroker {
weatherService: WeatherService;
trafficService: TrafficService;
weatherPub: Rx.Subject<IWeatherUpdate>;
accidentPub: Rx.Subject<IAccident>;
online:number = 0;
constructor(public io:SocketIO.Server) {
this.weatherService = new WeatherService();
this.trafficService = new TrafficService();
this.io.on('connection', (socket:SocketIO.Socket) => {
console.log(`Connect from ${socket.client.id}!`);
this.online += 1;
console.log(`${this.online} clients online.`);
});
this.io.on('disconnect', (who) => {
console.log(`Disconnect from ${who}.`);
this.online -= 1;
console.log(`${this.online} clients online.`);
});
this.weatherPub = this.weatherService.getWeatherUpdatePub();
this.weatherPub.subscribe(weatherUpdate => this.io.emit('weatherUpdate', weatherUpdate));
this.accidentPub = this.trafficService.getAccidentPub();
this.accidentPub.subscribe(accident => this.io.emit('accident', accident));
}
}
| Put the traffic update time back to once a second | Put the traffic update time back to once a second
| TypeScript | mit | AngularShowcase/angular2-seed-example-mashup,hpinsley/angular-mashup,hpinsley/angular-mashup,AngularShowcase/angular2-seed-example-mashup,AngularShowcase/angular2-seed-example-mashup,hpinsley/angular-mashup | ---
+++
@@ -12,16 +12,25 @@
weatherPub: Rx.Subject<IWeatherUpdate>;
accidentPub: Rx.Subject<IAccident>;
+ online:number = 0;
constructor(public io:SocketIO.Server) {
this.weatherService = new WeatherService();
this.trafficService = new TrafficService();
- this.io.on('connection', function(socket:SocketIO.Socket){
+ this.io.on('connection', (socket:SocketIO.Socket) => {
console.log(`Connect from ${socket.client.id}!`);
- //console.log('Got a connection.');
+ this.online += 1;
+ console.log(`${this.online} clients online.`);
});
+
+ this.io.on('disconnect', (who) => {
+ console.log(`Disconnect from ${who}.`);
+ this.online -= 1;
+ console.log(`${this.online} clients online.`);
+ });
+
this.weatherPub = this.weatherService.getWeatherUpdatePub();
this.weatherPub.subscribe(weatherUpdate => this.io.emit('weatherUpdate', weatherUpdate)); |
6583fec5d8edb6d3663115ab43e03aa61ee07083 | functions/index.ts | functions/index.ts | import axios from "axios";
import { Request, Response } from "express";
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import unfluff = require("unfluff");
import * as amazon from "./amazon";
import { httpsFunction } from "./utils";
admin.initializeApp(functions.config().firebase);
export const article = httpsFunction(async ({ query: { uri } }: Request, response: Response) => {
const { title } = unfluff((await axios.get(uri)).data);
const article = { name: title, uri };
console.log("Article:", article);
response.send(article);
});
export const books = httpsFunction(async (_, response: Response) => {
response.send(await amazon.books());
});
| import axios from "axios";
import { Request, Response } from "express";
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import unfluff = require("unfluff");
import * as amazon from "./amazon";
import { httpsFunction } from "./utils";
admin.initializeApp(functions.config().firebase);
export const article = httpsFunction(async ({ query: { uri } }: Request, response: Response) => {
const { date, favicon, image, text, title } = unfluff((await axios.get(uri)).data);
const article = { date, favicon, image, name: title, text, uri };
console.log("Article:", article);
response.send(article);
});
export const books = httpsFunction(async (_, response: Response) => {
response.send(await amazon.books());
});
| Return details of articles from functions | Return details of articles from functions
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -10,8 +10,8 @@
admin.initializeApp(functions.config().firebase);
export const article = httpsFunction(async ({ query: { uri } }: Request, response: Response) => {
- const { title } = unfluff((await axios.get(uri)).data);
- const article = { name: title, uri };
+ const { date, favicon, image, text, title } = unfluff((await axios.get(uri)).data);
+ const article = { date, favicon, image, name: title, text, uri };
console.log("Article:", article);
|
4e21462e2d5b281f46fad623c955d16ad89f8023 | lib/components/select.tsx | lib/components/select.tsx | import {memo, forwardRef} from 'react'
import Select, {Props} from 'react-select'
import {CB_HEX, CB_RGB} from 'lib/constants'
export const selectStyles = {
option: (styles, state) => ({
...styles,
color: state.isSelected ? '#fff' : styles.color,
backgroundColor: state.isSelected ? CB_HEX : styles.backgroundColor,
'&:hover': {
color: '#fff',
backgroundColor: CB_HEX
}
}),
control: (styles, state) => ({
...styles,
boxShadow: state.isFocused
? `0 0 0 0.2rem rgba(${CB_RGB.r}, ${CB_RGB.g}, ${CB_RGB.b}, 0.25)`
: 0,
borderColor: state.isFocused ? CB_HEX : styles.borderColor,
'&:hover': {
borderColor: state.isFocused ? CB_HEX : styles.borderColor
}
})
}
// NB: React enforces `memo(forwardRef(...))`
export default memo<Props>(
forwardRef((p: Props, ref) => (
<Select innerRef={ref as any} styles={selectStyles} {...p} />
))
)
| import {memo, forwardRef} from 'react'
import Select, {Props} from 'react-select'
import {CB_HEX, CB_RGB} from 'lib/constants'
export const selectStyles = {
option: (styles, state) => ({
...styles,
color: state.isSelected ? '#fff' : styles.color,
backgroundColor: state.isSelected ? CB_HEX : styles.backgroundColor,
'&:hover': {
color: '#fff',
backgroundColor: CB_HEX
}
}),
control: (styles, state) => ({
...styles,
boxShadow: state.isFocused
? `0 0 0 0.2rem rgba(${CB_RGB.r}, ${CB_RGB.g}, ${CB_RGB.b}, 0.25)`
: 0,
borderColor: state.isFocused ? CB_HEX : styles.borderColor,
'&:hover': {
borderColor: state.isFocused ? CB_HEX : styles.borderColor
}
})
}
const SelectWithForwardRef = forwardRef((p: Props, ref) => (
<Select innerRef={ref as any} styles={selectStyles} {...p} />
))
// NB: React enforces `memo(forwardRef(...))`
const MemoedReactSelect = memo<Props>(SelectWithForwardRef)
export default MemoedReactSelect
| Fix bug causing Select not to reload in dev mode | Fix bug causing Select not to reload in dev mode
React Fast-Refresh requires named exports
| TypeScript | mit | conveyal/analysis-ui,conveyal/analysis-ui,conveyal/analysis-ui | ---
+++
@@ -25,9 +25,11 @@
})
}
+const SelectWithForwardRef = forwardRef((p: Props, ref) => (
+ <Select innerRef={ref as any} styles={selectStyles} {...p} />
+))
+
// NB: React enforces `memo(forwardRef(...))`
-export default memo<Props>(
- forwardRef((p: Props, ref) => (
- <Select innerRef={ref as any} styles={selectStyles} {...p} />
- ))
-)
+const MemoedReactSelect = memo<Props>(SelectWithForwardRef)
+
+export default MemoedReactSelect |
55370c18ab9755e5586809054d8a4aed6c781ea3 | lib/base/env.ts | lib/base/env.ts | /// <reference path="../../typings/DefinitelyTyped/node/node.d.ts" />
// env.ts provides functions to query the host Javascript
// environment
// This module has no dependencies to facilitate easier re-use across
// different JS environments
/** Returns true if running in the main browser
* environment with DOM access.
*/
export function isBrowser() {
return typeof window != 'undefined';
}
/** Returns true if running from within NodeJS
* (or a compatible environment)
*/
export function isNodeJS() {
return process && process.version;
}
/** Returns true if running from a Web Worker context
* in a browser (or a compatible environment)
*/
export function isWebWorker() {
return typeof importScripts != 'undefined';
}
/** Returns true if running as a page script
* in a Firefox Jetpack add-on
*/
export function isFirefoxAddon() {
return isBrowser() && window.location.protocol == 'resource:';
}
/** Returns true if running as a content or
* background script in a Google Chrome extension
*/
export function isChromeExtension() {
return isBrowser() && typeof chrome != 'undefined';
}
| /// <reference path="../../typings/DefinitelyTyped/node/node.d.ts" />
// env.ts provides functions to query the host Javascript
// environment
// This module has no dependencies to facilitate easier re-use across
// different JS environments
/** Returns true if running in the main browser
* environment with DOM access.
*/
export function isBrowser() {
return typeof window != 'undefined';
}
/** Returns true if running from within NodeJS
* (or a compatible environment)
*/
export function isNodeJS() {
return process && process.version;
}
/** Returns true if running from a Web Worker context
* in a browser (or a compatible environment)
*/
export function isWebWorker() {
return typeof importScripts != 'undefined';
}
/** Returns true if running as a page script
* in a Firefox Jetpack add-on
*/
export function isFirefoxAddon() {
return isBrowser() && window.location.protocol == 'resource:';
}
/** Returns true if running as a content or
* background script in a Google Chrome extension
*/
export function isChromeExtension() {
return isBrowser() &&
typeof chrome !== 'undefined' &&
typeof chrome.extension !== 'undefined';
}
| Fix web app failing to display items in Chrome | Fix web app failing to display items in Chrome
The web app was detecting its environment as a Chrome
extension when run in Chrome and trying to use the Chrome Extension
Dropbox auth driver.
Make the test for the Chrome extension environment stricter
by testing for window.chrome.extension
| TypeScript | bsd-3-clause | robertknight/passcards,robertknight/passcards,robertknight/passcards,robertknight/passcards | ---
+++
@@ -38,6 +38,8 @@
* background script in a Google Chrome extension
*/
export function isChromeExtension() {
- return isBrowser() && typeof chrome != 'undefined';
+ return isBrowser() &&
+ typeof chrome !== 'undefined' &&
+ typeof chrome.extension !== 'undefined';
}
|
0af8403c8afdcc1e851f0eed377fc53ffb94f250 | src/main/index.ts | src/main/index.ts | import { ipcMain, app, Menu } from 'electron';
import { resolve } from 'path';
import { platform, homedir } from 'os';
import { AppWindow } from './app-window';
ipcMain.setMaxListeners(0);
app.setPath('userData', resolve(homedir(), '.wexond'));
export const appWindow = new AppWindow();
app.on('ready', () => {
// Create our menu entries so that we can use macOS shortcuts
Menu.setApplicationMenu(
Menu.buildFromTemplate([
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'pasteandmatchstyle' },
{ role: 'delete' },
{ role: 'selectall' },
{ role: 'quit' },
],
},
]),
);
appWindow.createWindow();
});
app.on('window-all-closed', () => {
if (platform() !== 'darwin') {
app.quit();
}
});
| import { ipcMain, app, Menu, session } from 'electron';
import { resolve } from 'path';
import { platform, homedir } from 'os';
import { AppWindow } from './app-window';
ipcMain.setMaxListeners(0);
app.setPath('userData', resolve(homedir(), '.wexond'));
export const appWindow = new AppWindow();
session.defaultSession.setPermissionRequestHandler(
(webContents, permission, callback) => {
if (permission === 'notifications' || permission === 'fullscreen') {
callback(true);
} else {
callback(false);
}
},
);
app.on('ready', () => {
// Create our menu entries so that we can use macOS shortcuts
Menu.setApplicationMenu(
Menu.buildFromTemplate([
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'pasteandmatchstyle' },
{ role: 'delete' },
{ role: 'selectall' },
{ role: 'quit' },
],
},
]),
);
appWindow.createWindow();
});
app.on('window-all-closed', () => {
if (platform() !== 'darwin') {
app.quit();
}
});
| Disable all permissions requests by default | Disable all permissions requests by default
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -1,4 +1,4 @@
-import { ipcMain, app, Menu } from 'electron';
+import { ipcMain, app, Menu, session } from 'electron';
import { resolve } from 'path';
import { platform, homedir } from 'os';
import { AppWindow } from './app-window';
@@ -8,6 +8,16 @@
app.setPath('userData', resolve(homedir(), '.wexond'));
export const appWindow = new AppWindow();
+
+session.defaultSession.setPermissionRequestHandler(
+ (webContents, permission, callback) => {
+ if (permission === 'notifications' || permission === 'fullscreen') {
+ callback(true);
+ } else {
+ callback(false);
+ }
+ },
+);
app.on('ready', () => {
// Create our menu entries so that we can use macOS shortcuts |
c51b74377aa7439f9f65974e0b10a06b0e3d7a93 | tools/env/base.ts | tools/env/base.ts | import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.4.0',
RELEASEVERSION: '0.4.0'
};
export = BaseConfig;
| import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.5.0',
RELEASEVERSION: '0.5.0'
};
export = BaseConfig;
| Update release version to 0.5.0. | Update release version to 0.5.0.
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -3,8 +3,8 @@
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
- RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.4.0',
- RELEASEVERSION: '0.4.0'
+ RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.5.0',
+ RELEASEVERSION: '0.5.0'
};
export = BaseConfig; |
842fd10982f039dbbaed6658754e034c0a756364 | src/index.ts | src/index.ts | import * as Hapi from 'hapi';
import Logger from './helper/logger';
import * as Router from './router';
import Plugins from './plugins';
class Server {
public static init() : void {
try {
const server = new Hapi.Server();
server.connection({
host: process.env.HOST,
port: process.env.PORT
});
if (process.env.NODE_ENV === 'development') {
Plugins.status(server);
Plugins.swagger(server);
}
Router.register(server);
await server.start();
Logger.info('Server is up and running!');
} catch(error) {
Logger.info(`There was something wrong: ${error}`);
}
}
}
export default Server.init();
| import * as Hapi from 'hapi';
import Logger from './helper/logger';
import * as Router from './router';
import Plugins from './plugins';
class Server {
static async init() : Promise<any> {
try {
const server = new Hapi.Server();
server.connection({
host: process.env.HOST,
port: process.env.PORT
});
if (process.env.NODE_ENV === 'development') {
Plugins.status(server);
Plugins.swagger(server);
}
Router.register(server);
await server.start();
Logger.info('Server is up and running!');
} catch(error) {
Logger.info(`There was something wrong: ${error}`);
}
}
}
export default Server.init();
| Fix issue with wrong async/await declaration | Fix issue with wrong async/await declaration
| TypeScript | mit | BlackBoxVision/typescript-hapi-starter,BlackBoxVision/typescript-hapi-starter,BlackBoxVision/typescript-hapi-starter | ---
+++
@@ -5,7 +5,7 @@
import Plugins from './plugins';
class Server {
- public static init() : void {
+ static async init() : Promise<any> {
try {
const server = new Hapi.Server();
|
f5358b19d23459fb0f9e8aad5c4126474535c1b4 | src/index.ts | src/index.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
ILayoutRestorer,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { ILauncher } from '@jupyterlab/launcher';
import { Debugger } from './debugger';
import { IDebugger } from './tokens';
/**
* The command IDs used by the debugger plugin.
*/
namespace CommandIDs {
export const open = 'debugger:open';
}
/**
* A plugin providing a UI for code debugging and environment inspection.
*/
const plugin: JupyterFrontEndPlugin<IDebugger> = {
id: '@jupyterlab/debugger:plugin',
optional: [ILauncher, ILayoutRestorer],
provides: IDebugger,
autoStart: true,
activate: (
app: JupyterFrontEnd,
launcher: ILauncher | null,
restorer: ILayoutRestorer | null
): IDebugger => {
console.log(plugin.id, 'Hello, world.');
const { shell } = app;
const command = CommandIDs.open;
const label = 'Environment';
const widget = new Debugger();
widget.id = 'jp-debugger';
widget.title.label = label;
shell.add(widget, 'right', { activate: false });
if (launcher) {
launcher.add({ command, args: { isLauncher: true } });
}
if (restorer) {
restorer.add(widget, widget.id);
}
return widget;
}
};
/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [plugin];
export default plugins;
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
ILayoutRestorer,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { Debugger } from './debugger';
import { IDebugger } from './tokens';
/**
* A plugin providing a UI for code debugging and environment inspection.
*/
const plugin: JupyterFrontEndPlugin<IDebugger> = {
id: '@jupyterlab/debugger:plugin',
optional: [ILayoutRestorer],
provides: IDebugger,
autoStart: true,
activate: (
app: JupyterFrontEnd,
restorer: ILayoutRestorer | null
): IDebugger => {
console.log(plugin.id, 'Hello, world.');
const { shell } = app;
const label = 'Environment';
const widget = new Debugger();
widget.id = 'jp-debugger';
widget.title.label = label;
shell.add(widget, 'right', { activate: false });
if (restorer) {
restorer.add(widget, widget.id);
}
return widget;
}
};
/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [plugin];
export default plugins;
| Remove launcher item for now as well. It may be unnecessary. | Remove launcher item for now as well. It may be unnecessary.
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -7,45 +7,30 @@
JupyterFrontEndPlugin
} from '@jupyterlab/application';
-import { ILauncher } from '@jupyterlab/launcher';
-
import { Debugger } from './debugger';
import { IDebugger } from './tokens';
-
-/**
- * The command IDs used by the debugger plugin.
- */
-namespace CommandIDs {
- export const open = 'debugger:open';
-}
/**
* A plugin providing a UI for code debugging and environment inspection.
*/
const plugin: JupyterFrontEndPlugin<IDebugger> = {
id: '@jupyterlab/debugger:plugin',
- optional: [ILauncher, ILayoutRestorer],
+ optional: [ILayoutRestorer],
provides: IDebugger,
autoStart: true,
activate: (
app: JupyterFrontEnd,
- launcher: ILauncher | null,
restorer: ILayoutRestorer | null
): IDebugger => {
console.log(plugin.id, 'Hello, world.');
const { shell } = app;
- const command = CommandIDs.open;
const label = 'Environment';
const widget = new Debugger();
widget.id = 'jp-debugger';
widget.title.label = label;
shell.add(widget, 'right', { activate: false });
-
- if (launcher) {
- launcher.add({ command, args: { isLauncher: true } });
- }
if (restorer) {
restorer.add(widget, widget.id); |
7a68bc1d5cd368f33a0da3d56096ef1ee47cb579 | src/machine/stella/tia/LatchedInput.ts | src/machine/stella/tia/LatchedInput.ts | import SwitchInterface from '../../io/SwitchInterface';
export default class LatchedInput {
constructor(private _switch: SwitchInterface) {
this.reset();
this._switch.stateChanged.addHandler((state: boolean) => {
if (this._modeLatched && !state) {
this._latchedValue = 0x80;
}
});
}
reset(): void {
this._modeLatched = false;
this._latchedValue = 0;
}
vblank(value: number): void {
if ((value & 0x40) > 0) {
if (!this._modeLatched) {
this._modeLatched = true;
this._latchedValue = 0;
}
} else {
this._modeLatched = false;
}
}
inpt(): number {
if (this._modeLatched) {
return this._latchedValue;
} else {
return this._switch.read() ? 0 : 0x80;
}
}
private _modeLatched = false;
private _latchedValue = 0;
}
| import SwitchInterface from '../../io/SwitchInterface';
export default class LatchedInput {
constructor(private _switch: SwitchInterface) {
this.reset();
}
reset(): void {
this._modeLatched = false;
this._latchedValue = 0;
}
vblank(value: number): void {
if ((value & 0x40) > 0) {
this._modeLatched = true;
} else {
this._modeLatched = false;
this._latchedValue = 0x80;
}
}
inpt(): number {
let value = this._switch.read() ? 0 : 0x80;
if (this._modeLatched) {
this._latchedValue &= value;
value = this._latchedValue;
}
return value;
}
private _modeLatched = false;
private _latchedValue = 0;
}
| Change latched input to match spec -> golf works. Who would have thought that the spec meant THAT? | Change latched input to match spec -> golf works. Who would have thought that the spec meant THAT?
| TypeScript | mit | 6502ts/6502.ts,DirtyHairy/6502.ts,DirtyHairy/6502.ts,6502ts/6502.ts,DirtyHairy/6502.ts,6502ts/6502.ts,6502ts/6502.ts,6502ts/6502.ts,DirtyHairy/6502.ts | ---
+++
@@ -4,12 +4,6 @@
constructor(private _switch: SwitchInterface) {
this.reset();
-
- this._switch.stateChanged.addHandler((state: boolean) => {
- if (this._modeLatched && !state) {
- this._latchedValue = 0x80;
- }
- });
}
reset(): void {
@@ -19,21 +13,22 @@
vblank(value: number): void {
if ((value & 0x40) > 0) {
- if (!this._modeLatched) {
- this._modeLatched = true;
- this._latchedValue = 0;
- }
+ this._modeLatched = true;
} else {
this._modeLatched = false;
+ this._latchedValue = 0x80;
}
}
inpt(): number {
+ let value = this._switch.read() ? 0 : 0x80;
+
if (this._modeLatched) {
- return this._latchedValue;
- } else {
- return this._switch.read() ? 0 : 0x80;
+ this._latchedValue &= value;
+ value = this._latchedValue;
}
+
+ return value;
}
private _modeLatched = false; |
46293ba938a5ceae786a8c777651d33f3969721a | addon/element-remove.ts | addon/element-remove.ts | // Polyfill Element.remove on IE11
// from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
(function(arr) {
arr.forEach(function(item) {
if (Object.prototype.hasOwnProperty.call(item, 'remove')) {
return;
}
Object.defineProperty(item, 'remove', {
configurable: true,
enumerable: true,
writable: true,
value: function remove() {
this.parentNode.removeChild(this);
},
});
});
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
| // Polyfill Element.remove on IE11
// from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
const classPrototypes =
[window.Element, window.CharacterData,window.DocumentType]
.filter( (klass) => klass )
.map( (klass) => klass.prototype );
(function(arr) {
arr.forEach(function(item) {
if (Object.prototype.hasOwnProperty.call(item, 'remove')) {
return;
}
Object.defineProperty(item, 'remove', {
configurable: true,
enumerable: true,
writable: true,
value: function remove() {
this.parentNode.removeChild(this);
},
});
});
})(classPrototypes);
| Fix for running in Fastboot | Fix for running in Fastboot
Fastboot does not have the concept of Element, CharacterData and
presumably DocumentType. Inclusion of this polyfill thus makes
Fastboot crash early.
Implementation may well be changed to check for IE11 instead of
checking if the entities exist. I opted for the latter as the
polyfill might support other cases now, or in the future.
Further, I based myself on fetching these entities from window as
TypeScript gave errors if I chose not to.
| TypeScript | mit | ember-animation/ember-animated,ember-animation/ember-animated,ember-animation/ember-animated | ---
+++
@@ -1,5 +1,11 @@
// Polyfill Element.remove on IE11
// from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
+
+const classPrototypes =
+ [window.Element, window.CharacterData,window.DocumentType]
+ .filter( (klass) => klass )
+ .map( (klass) => klass.prototype );
+
(function(arr) {
arr.forEach(function(item) {
if (Object.prototype.hasOwnProperty.call(item, 'remove')) {
@@ -14,4 +20,4 @@
},
});
});
-})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+})(classPrototypes); |
21dc1e5e263932fa869418e6cf223b27d09ef669 | modules/tinymce/src/plugins/autosave/main/ts/api/Api.ts | modules/tinymce/src/plugins/autosave/main/ts/api/Api.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import * as Storage from '../core/Storage';
import { Fun } from '@ephox/katamari';
const get = function (editor) {
return {
hasDraft: Fun.curry(Storage.hasDraft, editor),
storeDraft: Fun.curry(Storage.storeDraft, editor),
restoreDraft: Fun.curry(Storage.restoreDraft, editor),
removeDraft: Fun.curry(Storage.removeDraft, editor),
isEmpty: Fun.curry(Storage.isEmpty, editor)
};
};
export {
get
};
| /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import * as Storage from '../core/Storage';
const get = (editor) => ({
hasDraft: () => Storage.hasDraft(editor),
storeDraft: () => Storage.storeDraft(editor),
restoreDraft: () => Storage.restoreDraft(editor),
removeDraft: (fire?: boolean) => Storage.removeDraft(editor, fire),
isEmpty: (html?: string) => Storage.isEmpty(editor, html)
});
export {
get
};
| Remove Fun.curry calls to reduce code output size, and preserve parameter optionality | Remove Fun.curry calls to reduce code output size, and preserve parameter optionality
| TypeScript | mit | tinymce/tinymce,TeamupCom/tinymce,tinymce/tinymce,FernCreek/tinymce,FernCreek/tinymce,tinymce/tinymce,TeamupCom/tinymce,FernCreek/tinymce | ---
+++
@@ -6,17 +6,14 @@
*/
import * as Storage from '../core/Storage';
-import { Fun } from '@ephox/katamari';
-const get = function (editor) {
- return {
- hasDraft: Fun.curry(Storage.hasDraft, editor),
- storeDraft: Fun.curry(Storage.storeDraft, editor),
- restoreDraft: Fun.curry(Storage.restoreDraft, editor),
- removeDraft: Fun.curry(Storage.removeDraft, editor),
- isEmpty: Fun.curry(Storage.isEmpty, editor)
- };
-};
+const get = (editor) => ({
+ hasDraft: () => Storage.hasDraft(editor),
+ storeDraft: () => Storage.storeDraft(editor),
+ restoreDraft: () => Storage.restoreDraft(editor),
+ removeDraft: (fire?: boolean) => Storage.removeDraft(editor, fire),
+ isEmpty: (html?: string) => Storage.isEmpty(editor, html)
+});
export {
get |
de244f9ea30381d3af9187ec5467e149a3872ab0 | src/Apps/Artist/Routes/Overview/Components/Genes.tsx | src/Apps/Artist/Routes/Overview/Components/Genes.tsx | import { Sans, Serif, Spacer } from "@artsy/palette"
import { Genes_artist } from "__generated__/Genes_artist.graphql"
import React, { Component } from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { data as sd } from "sharify"
import styled from "styled-components"
import { space } from "styled-system"
const GeneFamily = styled.div``
const GeneLink = styled.a`
display: inline-block;
${space};
`
interface Props {
artist: Genes_artist
}
export class Genes extends Component<Props> {
render() {
const { related } = this.props.artist
const { genes } = related
if (genes.edges.length === 0) {
return null
}
return (
<GeneFamily>
<Sans size="2" weight="medium">
Related Categories
</Sans>
<Spacer mb={1} />
{genes.edges.map(({ node: gene }, index, list) => {
const geneDivider = index < list.length - 1 ? "," : ""
const href = sd.APP_URL + gene.href
return (
<Serif size="3t" display="inline-block" key={index} mr={0.5}>
<GeneLink href={href} className="noUnderline">
{gene.name}
{geneDivider}
</GeneLink>
</Serif>
)
})}
</GeneFamily>
)
}
}
export const GenesFragmentContainer = createFragmentContainer(Genes, {
artist: graphql`
fragment Genes_artist on Artist {
related {
genes {
edges {
node {
href
name
}
}
}
}
}
`,
})
| import { Sans, Spacer, Tags } from "@artsy/palette"
import { Genes_artist } from "__generated__/Genes_artist.graphql"
import React, { Component } from "react"
import { createFragmentContainer, graphql } from "react-relay"
import styled from "styled-components"
const GeneFamily = styled.div``
interface Props {
artist: Genes_artist
}
export class Genes extends Component<Props> {
render() {
const { related } = this.props.artist
const { genes } = related
if (genes.edges.length === 0) {
return null
}
const tags = genes.edges.map(edge => edge.node)
return (
<GeneFamily>
<Sans size="2" weight="medium">
Related Categories
</Sans>
<Spacer mb={1} />
<Tags tags={tags} displayNum={8} />
</GeneFamily>
)
}
}
export const GenesFragmentContainer = createFragmentContainer(Genes, {
artist: graphql`
fragment Genes_artist on Artist {
related {
genes {
edges {
node {
href
name
}
}
}
}
}
`,
})
| Use `<Tags />` for artist genes | Use `<Tags />` for artist genes
| TypeScript | mit | artsy/reaction,artsy/reaction-force,artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction | ---
+++
@@ -1,16 +1,10 @@
-import { Sans, Serif, Spacer } from "@artsy/palette"
+import { Sans, Spacer, Tags } from "@artsy/palette"
import { Genes_artist } from "__generated__/Genes_artist.graphql"
import React, { Component } from "react"
import { createFragmentContainer, graphql } from "react-relay"
-import { data as sd } from "sharify"
import styled from "styled-components"
-import { space } from "styled-system"
const GeneFamily = styled.div``
-const GeneLink = styled.a`
- display: inline-block;
- ${space};
-`
interface Props {
artist: Genes_artist
@@ -23,24 +17,14 @@
if (genes.edges.length === 0) {
return null
}
+ const tags = genes.edges.map(edge => edge.node)
return (
<GeneFamily>
<Sans size="2" weight="medium">
Related Categories
</Sans>
<Spacer mb={1} />
- {genes.edges.map(({ node: gene }, index, list) => {
- const geneDivider = index < list.length - 1 ? "," : ""
- const href = sd.APP_URL + gene.href
- return (
- <Serif size="3t" display="inline-block" key={index} mr={0.5}>
- <GeneLink href={href} className="noUnderline">
- {gene.name}
- {geneDivider}
- </GeneLink>
- </Serif>
- )
- })}
+ <Tags tags={tags} displayNum={8} />
</GeneFamily>
)
} |
843e7634109766aab8d719ed62f1c45194204ce7 | src/components/shared/link.tsx | src/components/shared/link.tsx | import * as _ from 'lodash';
import * as Reflux from 'reflux';
import * as React from 'react';
import { RouteStore } from '../../stores/route-store';
import { ActiveLinkProps } from './props';
const Route = require('react-router');
export const ActiveLink = React.createClass<ActiveLinkProps, any>({
mixins: [Reflux.connect(RouteStore, 'route')],
render: function(){
var path:string = _.get(this.state.route, 'location.pathname', '');
var active:string = path === this.props.to ? 'active' : '';
return (
<Route.Link className={`item ${active}`} to={this.props.to}>
{this.props.children}
</Route.Link>
);
}
});
| import * as _ from 'lodash';
import * as React from 'react';
import { connect } from 'react-redux';
import { ActiveLinkProps } from './props';
const Route = require('react-router');
export const ActiveLink = connect(state => ({router: state.router}))(React.createClass<ActiveLinkProps, any>({
render: function(){
var path:string = _.get(this.props.router, 'location.pathname', '');
var active:string = path === this.props.to ? 'active' : '';
return (
<Route.Link className={`item ${active}`} to={this.props.to}>
{this.props.children}
</Route.Link>
);
}
}));
| Update ActiveLink to use redux | Update ActiveLink to use redux
| TypeScript | apache-2.0 | lawrence0819/neptune-front,lawrence0819/neptune-front | ---
+++
@@ -1,15 +1,13 @@
import * as _ from 'lodash';
-import * as Reflux from 'reflux';
import * as React from 'react';
-import { RouteStore } from '../../stores/route-store';
+import { connect } from 'react-redux';
import { ActiveLinkProps } from './props';
const Route = require('react-router');
-export const ActiveLink = React.createClass<ActiveLinkProps, any>({
- mixins: [Reflux.connect(RouteStore, 'route')],
+export const ActiveLink = connect(state => ({router: state.router}))(React.createClass<ActiveLinkProps, any>({
render: function(){
- var path:string = _.get(this.state.route, 'location.pathname', '');
+ var path:string = _.get(this.props.router, 'location.pathname', '');
var active:string = path === this.props.to ? 'active' : '';
return (
<Route.Link className={`item ${active}`} to={this.props.to}>
@@ -17,4 +15,4 @@
</Route.Link>
);
}
-});
+})); |
275324fe3a1f12f4eacc77a6149b17d2b1172e29 | src/app/components/app.component.spec.ts | src/app/components/app.component.spec.ts | import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports: [
RouterTestingModule
]
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'mathDruck'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('mathDruck');
}));
it('should render title in a header tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('header').textContent).toContain('mathDruck');
}));
});
| import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports: [
RouterTestingModule
]
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'Mathdruck'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('Mathdruck');
}));
});
| Remove root component unit test | Remove root component unit test
Unit test fails as title variable appears in hyperlink now rather than a
title element.
This unit test isn't so important (can always add back later).
| TypeScript | mit | family-guy/mathdruck-ng1,family-guy/mathdruck-ng1,family-guy/mathdruck-ng1 | ---
+++
@@ -21,16 +21,9 @@
expect(app).toBeTruthy();
}));
- it(`should have as title 'mathDruck'`, async(() => {
+ it(`should have as title 'Mathdruck'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
- expect(app.title).toEqual('mathDruck');
- }));
-
- it('should render title in a header tag', async(() => {
- const fixture = TestBed.createComponent(AppComponent);
- fixture.detectChanges();
- const compiled = fixture.debugElement.nativeElement;
- expect(compiled.querySelector('header').textContent).toContain('mathDruck');
+ expect(app.title).toEqual('Mathdruck');
}));
}); |
18741033ac03a72aa3feec8014c861143581e8c6 | src/lib/package-manager/npm.ts | src/lib/package-manager/npm.ts | import { NodeManager } from './node-manager';
export class Npm extends NodeManager {
constructor(cwd: string) {
super(cwd, 'npm');
}
install(packageName: string, cwd?: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('install', [packageName, '--save'], cwd, stream);
}
installDev(packageName: string, cwd?: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('install', [packageName, '--save-dev'], cwd, stream);
}
uninstall(packageName: string, cwd?: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('uninstall', [packageName, '--save'], cwd, stream);
}
upgrade(packageName: string, cwd?: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('upgrade', [packageName, '--save'], cwd, stream);
}
runScript(scriptName: string, cwd: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('run-script', [scriptName], cwd, stream);
}
runScriptInBackground(scriptName: string, cwd?: string) {
return this._execInBackground('run-script', [scriptName], cwd);
}
getExecutable(): Promise<string> {
return this._getManagerExecutable('npm');
}
} | import { NodeManager } from './node-manager';
export class Npm extends NodeManager {
constructor(cwd: string) {
super(cwd, 'npm');
}
install(packageName: string, cwd?: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('install', [packageName, '--save'], cwd, stream);
}
installDev(packageName: string, cwd?: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('install', [packageName, '--save-dev'], cwd, stream);
}
uninstall(packageName: string, cwd?: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('uninstall', [packageName, '--save'], cwd, stream);
}
upgrade(packageName: string, cwd?: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('install', [packageName, '--save'], cwd, stream);
}
runScript(scriptName: string, cwd: string, stream?: (data: any, error?: boolean) => void) {
return this._exec('run-script', [scriptName], cwd, stream);
}
runScriptInBackground(scriptName: string, cwd?: string) {
return this._execInBackground('run-script', [scriptName], cwd);
}
getExecutable(): Promise<string> {
return this._getManagerExecutable('npm');
}
} | Upgrade properly to the latest version | fix(Npm): Upgrade properly to the latest version
| TypeScript | apache-2.0 | webshell/materia-server,webshell/materia-server,webshell/materia-server,webshell/materia-server | ---
+++
@@ -19,7 +19,7 @@
}
upgrade(packageName: string, cwd?: string, stream?: (data: any, error?: boolean) => void) {
- return this._exec('upgrade', [packageName, '--save'], cwd, stream);
+ return this._exec('install', [packageName, '--save'], cwd, stream);
}
runScript(scriptName: string, cwd: string, stream?: (data: any, error?: boolean) => void) { |
8e015966f959d04a6254fd9b5cd34826086be6f7 | packages/components/components/version/ChangelogModal.tsx | packages/components/components/version/ChangelogModal.tsx | import React, { useState } from 'react';
import { c } from 'ttag';
import markdownit from 'markdown-it';
import { FormModal } from '../modal';
import './ChangeLogModal.scss';
import { getAppVersion } from '../../helpers';
const md = markdownit('default', {
breaks: true,
linkify: true,
});
interface Props {
changelog?: string;
}
const ChangelogModal = ({ changelog = '', ...rest }: Props) => {
const [html] = useState(() => {
const modifiedChangelog = changelog.replace(/\[(\d+\.\d+\.\d+[^\]]*)]/g, (match, capture) => {
return `[${getAppVersion(capture)}]`;
});
return {
__html: md.render(modifiedChangelog),
};
});
return (
<FormModal title={c('Title').t`Release notes`} close={c('Action').t`Close`} submit={null} {...rest}>
<div className="modal-content-inner-changelog" dangerouslySetInnerHTML={html} />
</FormModal>
);
};
export default ChangelogModal;
| import React, { useState } from 'react';
import { c } from 'ttag';
import markdownit from 'markdown-it';
import { FormModal } from '../modal';
import './ChangeLogModal.scss';
import { getAppVersion } from '../../helpers';
const md = markdownit('default', {
breaks: true,
linkify: true,
});
interface Props {
changelog?: string;
}
const ChangelogModal = ({ changelog = '', ...rest }: Props) => {
const [html] = useState(() => {
const modifiedChangelog = changelog.replace(/\[(\d+\.\d+\.\d+[^\]]*)]/g, (match, capture) => {
return `[${getAppVersion(capture)}]`;
});
return {
__html: md.render(modifiedChangelog),
};
});
return (
<FormModal title={c('Title').t`Release notes`} close={c('Action').t`Close`} submit={null} {...rest}>
<div className="modal-content-inner-changelog" dangerouslySetInnerHTML={html} lang="en" />
</FormModal>
);
};
export default ChangelogModal;
| Fix - lang for release notes block | Fix - lang for release notes block
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -27,7 +27,7 @@
return (
<FormModal title={c('Title').t`Release notes`} close={c('Action').t`Close`} submit={null} {...rest}>
- <div className="modal-content-inner-changelog" dangerouslySetInnerHTML={html} />
+ <div className="modal-content-inner-changelog" dangerouslySetInnerHTML={html} lang="en" />
</FormModal>
);
}; |
935c35298bf5f83a06fae43785bf6f0e9ec97e0e | build/release.ts | build/release.ts | import { getWorkspaces } from 'bolt';
import * as path from 'path';
import exec from './lib/exec';
import build from './build';
function need(val, msg) {
if (!val) {
throw new Error(msg);
}
}
export default async function release({ packages, type }) {
need(packages, 'Please specify at least one package.');
need(type, 'Please specify a release type (or version number).');
await exec('bolt', ['build']);
const ws = await getWorkspaces();
for (const pkg of packages.split(',')) {
await build({ pkg });
const name = pkg.trim();
const w = ws.filter(w => w.name === name)[0];
if (!w) continue;
const cwd = w.dir;
await exec('npm', ['--no-git-tag-version', 'version', type], { cwd });
const ver = require(path.join(cwd, 'package.json')).version;
const tag = `${name}-${ver}`;
await exec('git', ['commit', '-am', tag], { cwd });
await exec('git', ['tag', '-a', tag, '-m', tag], { cwd });
await exec('npm', ['publish'], { cwd });
}
await exec('git', ['push', '--follow-tags']);
}
| import { getWorkspaces } from 'bolt';
import * as path from 'path';
import exec from './lib/exec';
import build from './build';
function need(val, msg) {
if (!val) {
throw new Error(msg);
}
}
export default async function release({ packages, type }) {
need(packages, 'Please specify at least one package.');
need(type, 'Please specify a release type (or version number).');
await exec('bolt', ['build']);
const ws = await getWorkspaces();
for (const pkg of packages.split(',')) {
await build({ pkg });
const name = pkg.trim();
const w = ws.filter(w => w.name === name)[0];
if (!w) continue;
const cwd = w.dir;
await exec(
'npm',
['--allow-same-version', '--no-git-tag-version', 'version', type],
{ cwd }
);
const ver = require(path.join(cwd, 'package.json')).version;
const tag = `${name}-${ver}`;
await exec('git', ['commit', '-am', tag], { cwd });
await exec('git', ['tag', '-a', tag, '-m', tag], { cwd });
await exec('npm', ['publish'], { cwd });
}
await exec('git', ['push', '--follow-tags']);
}
| Allow same version when versioning. | Allow same version when versioning.
| TypeScript | mit | skatejs/skatejs,skatejs/skatejs,skatejs/skatejs | ---
+++
@@ -20,7 +20,11 @@
const w = ws.filter(w => w.name === name)[0];
if (!w) continue;
const cwd = w.dir;
- await exec('npm', ['--no-git-tag-version', 'version', type], { cwd });
+ await exec(
+ 'npm',
+ ['--allow-same-version', '--no-git-tag-version', 'version', type],
+ { cwd }
+ );
const ver = require(path.join(cwd, 'package.json')).version;
const tag = `${name}-${ver}`;
await exec('git', ['commit', '-am', tag], { cwd }); |
4816c933504541fd40c33c11cd459951606afceb | MonitoredSocket.ts | MonitoredSocket.ts | import net = require("net");
/**
* Represents a given host and port. Handles checking whether a host
* is up or not, as well as if it is accessible on the given port.
*/
class MonitoredSocket {
/**
* Returns whether the host can be accessed on its port.
*/
public isUp: boolean;
private socket: net.Socket;
constructor(
public endpoint: string,
public port: number
) {
this.socket = new net.Socket();
}
connect(successCallback: { (sock: MonitoredSocket, conn?: any): void },
failCallback: { (sock: MonitoredSocket, conn?: any): void }, conn?: any): void {
this.socket.connect(
this.port,
this.endpoint,
this.onConnectSuccess.bind(this, successCallback, conn)
);
this.socket.on("error", this.onConnectFailure.bind(this, failCallback, conn));
}
onConnectSuccess(callback: { (sock: MonitoredSocket, conn?: any): void }, conn?: any) {
this.isUp = true;
// We're good! Close the socket
this.socket.end();
callback(this, conn);
}
onConnectFailure(callback: { (sock: MonitoredSocket, conn?: any): void }, conn?: any) {
this.isUp = false;
// Cleanup
this.socket.destroy();
callback(this, conn);
}
toString(): string {
return this.endpoint + ":" + this.port;
}
serialize(): string {
return JSON.stringify(this);
}
}
export = MonitoredSocket; | import net = require("net");
/**
* Represents a given host and port. Handles checking whether a host
* is up or not, as well as if it is accessible on the given port.
*/
class MonitoredSocket {
/**
* Returns whether the host can be accessed on its port.
*/
public isUp: boolean;
private socket: net.Socket;
constructor(
public endpoint: string,
public port: number
) {
this.socket = new net.Socket();
}
connect(successCallback: { (sock: MonitoredSocket, conn?: any): void },
failCallback: { (sock: MonitoredSocket, conn?: any): void }, conn?: any): void {
this.socket.connect(
this.port,
this.endpoint,
this.onConnectSuccess.bind(this, successCallback, conn)
);
this.socket.on("error", this.onConnectFailure.bind(this, failCallback, conn));
}
onConnectSuccess(callback: { (sock: MonitoredSocket, conn?: any): void }, conn?: any) {
this.isUp = true;
// We're good! Close the socket
this.socket.end();
callback(this, conn);
}
onConnectFailure(callback: { (sock: MonitoredSocket, conn?: any): void }, conn?: any) {
this.isUp = false;
// Cleanup
this.socket.destroy();
callback(this, conn);
}
toString(): string {
return this.endpoint + ":" + this.port;
}
serialize(): Object {
return {
"socket": this.endpoint + ":" + this.port,
"status": this.isUp
};
}
}
export = MonitoredSocket; | Return object instead in serialize() | Return object instead in serialize()
| TypeScript | mit | OzuYatamutsu/is-my-server-up,OzuYatamutsu/is-my-server-up,OzuYatamutsu/is-my-server-up | ---
+++
@@ -51,8 +51,11 @@
return this.endpoint + ":" + this.port;
}
- serialize(): string {
- return JSON.stringify(this);
+ serialize(): Object {
+ return {
+ "socket": this.endpoint + ":" + this.port,
+ "status": this.isUp
+ };
}
}
|
42ba95e8bcf0ee802f432340b2a610479fef78b7 | packages/core/src/auth/login-optional.hook.ts | packages/core/src/auth/login-optional.hook.ts | import { HookDecorator } from '../core';
import { Login } from './login.hook';
export function LoginOptional(
options: { redirect?: string, user: (id: number|string) => Promise<any> }): HookDecorator {
return Login(false, options);
}
| import { HookDecorator } from '../core';
import { Login } from './login.hook';
export function LoginOptional(options: { user: (id: number|string) => Promise<any> }): HookDecorator {
return Login(false, options);
}
| Remove the redirect option from LoginOptional | Remove the redirect option from LoginOptional
| TypeScript | mit | FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal | ---
+++
@@ -1,7 +1,6 @@
import { HookDecorator } from '../core';
import { Login } from './login.hook';
-export function LoginOptional(
- options: { redirect?: string, user: (id: number|string) => Promise<any> }): HookDecorator {
+export function LoginOptional(options: { user: (id: number|string) => Promise<any> }): HookDecorator {
return Login(false, options);
} |
ec77b80284577234fe4a4e4a8c70a67676c22c22 | packages/react-input-feedback/src/index.ts | packages/react-input-feedback/src/index.ts | export default function Input() {
return null
}
| import { ComponentClass, createElement as r, SFC } from 'react'
import { WrappedFieldProps } from 'redux-form'
export type Component<P> = string | ComponentClass<P> | SFC<P>
export interface IInputProps extends WrappedFieldProps {
components: {
error: Component<any>
input: Component<any>
wrapper: Component<any>
}
}
export default function Input({
components,
input,
meta,
...props,
}: IInputProps) {
const { error, touched } = meta
const showError = touched && !!error
return r(
components.wrapper,
{},
r(components.input, { ...props, ...input }),
showError && r(components.error),
)
}
| Add typings and preliminary output | Add typings and preliminary output
| TypeScript | mit | thirdhand/components,thirdhand/components | ---
+++
@@ -1,3 +1,28 @@
-export default function Input() {
- return null
+import { ComponentClass, createElement as r, SFC } from 'react'
+import { WrappedFieldProps } from 'redux-form'
+
+export type Component<P> = string | ComponentClass<P> | SFC<P>
+
+export interface IInputProps extends WrappedFieldProps {
+ components: {
+ error: Component<any>
+ input: Component<any>
+ wrapper: Component<any>
+ }
}
+
+export default function Input({
+ components,
+ input,
+ meta,
+ ...props,
+}: IInputProps) {
+ const { error, touched } = meta
+ const showError = touched && !!error
+ return r(
+ components.wrapper,
+ {},
+ r(components.input, { ...props, ...input }),
+ showError && r(components.error),
+ )
+} |
c3e6c4dfa125198fddd50e84704026d73995846b | src/isaac-generator.ts | src/isaac-generator.ts | import { SeedProvider } from './seed-provider';
export class IsaacGenerator {
private _count: number;
private _memory: any;
constructor(seed: Array<number>) {
this._count = 0;
this._memory = SeedProvider.getMemory(seed);
}
public getValue(): number {
if (this._count <= 0) {
this._randomise();
}
return 0;
}
private _randomise(): void {
}
}
| import { SeedProvider } from './seed-provider';
export class IsaacGenerator {
private _count: number;
private _accumulatorShifts: Array<(x: number) => number>;
private _memory: any;
constructor(seed: Array<number>) {
this._count = 0;
this._accumulatorShifts = [
(x: number) => x << 13,
(x: number) => x >>> 6,
(x: number) => x << 2,
(x: number) => x >>> 16
];
this._memory = SeedProvider.getMemory(seed);
}
public getValue(): number {
if (this._count <= 0) {
this._randomise();
}
return 0;
}
private _randomise(): void {
}
}
| Store required accumulator shifts (in order) | Store required accumulator shifts (in order)
| TypeScript | mit | Jameskmonger/isaac-crypto | ---
+++
@@ -2,10 +2,18 @@
export class IsaacGenerator {
private _count: number;
+ private _accumulatorShifts: Array<(x: number) => number>;
private _memory: any;
constructor(seed: Array<number>) {
this._count = 0;
+
+ this._accumulatorShifts = [
+ (x: number) => x << 13,
+ (x: number) => x >>> 6,
+ (x: number) => x << 2,
+ (x: number) => x >>> 16
+ ];
this._memory = SeedProvider.getMemory(seed);
} |
6840e7d1491902a40faa1fb65e2039427861b274 | src/lib/util/regexp.ts | src/lib/util/regexp.ts | const EOL = `(?:$|"|'|,| |;|\\)|\\r|\\n|\})`;
const DOT_VALUE = `(?:\\.\\d+)`; // ['.x', '']
const ALPHA = `(?:1(:?\\.0+)?|0${DOT_VALUE}?|${DOT_VALUE})`; // ['0', '1', '0.x', '1.0', '.x']
const HEXA_VALUE = '[\\da-f]'; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']
export { EOL, ALPHA, DOT_VALUE, HEXA_VALUE };
| const EOL = `(?:$|"|'|,| |;|\\)|\\r|\\n|\}|<)`;
const DOT_VALUE = `(?:\\.\\d+)`; // ['.x', '']
const ALPHA = `(?:1(:?\\.0+)?|0${DOT_VALUE}?|${DOT_VALUE})`; // ['0', '1', '0.x', '1.0', '.x']
const HEXA_VALUE = '[\\da-f]'; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']
export { EOL, ALPHA, DOT_VALUE, HEXA_VALUE };
| Add `<`as end of colors | feat: Add `<`as end of colors
| TypeScript | apache-2.0 | KamiKillertO/vscode-colorize,KamiKillertO/vscode-colorize | ---
+++
@@ -1,4 +1,4 @@
-const EOL = `(?:$|"|'|,| |;|\\)|\\r|\\n|\})`;
+const EOL = `(?:$|"|'|,| |;|\\)|\\r|\\n|\}|<)`;
const DOT_VALUE = `(?:\\.\\d+)`; // ['.x', '']
const ALPHA = `(?:1(:?\\.0+)?|0${DOT_VALUE}?|${DOT_VALUE})`; // ['0', '1', '0.x', '1.0', '.x'] |
9121d7ec97f489f8aca490421424ad4f5b53af52 | problems/complementary-colours/tests.ts | problems/complementary-colours/tests.ts | export class Tests {
public static tests: any[] = [
{
input: "#ffffff",
output: "#000000"
},
{
input: "#abcdef",
output: "#543210"
},
{
input: "#badcab",
output: "#452354"
},
{
input: "#133742",
output: "#ecc8bd"
},
{
input: "#a1b2c3",
output: "#5e4d3c"
},
{
input: "#7f7f80",
output: "#80807f"
}
];
}
| import {ITestSuite} from '../testsuite.interface';
import {ITest} from '../test.interface';
export class Tests implements ITestSuite<string, string> {
public getTests(): Array<ITest<string, string>> {
return [
{
input: "#ffffff",
output: "#000000"
},
{
input: "#abcdef",
output: "#543210"
},
{
input: "#badcab",
output: "#452354"
},
{
input: "#133742",
output: "#ecc8bd"
},
{
input: "#a1b2c3",
output: "#5e4d3c"
},
{
input: "#7f7f80",
output: "#80807f"
}
];
}
}
| Add more robust test suite architecture for complementary-colours | Add more robust test suite architecture for complementary-colours
| TypeScript | unlicense | Jameskmonger/challenges | ---
+++
@@ -1,28 +1,33 @@
-export class Tests {
- public static tests: any[] = [
- {
- input: "#ffffff",
- output: "#000000"
- },
- {
- input: "#abcdef",
- output: "#543210"
- },
- {
- input: "#badcab",
- output: "#452354"
- },
- {
- input: "#133742",
- output: "#ecc8bd"
- },
- {
- input: "#a1b2c3",
- output: "#5e4d3c"
- },
- {
- input: "#7f7f80",
- output: "#80807f"
- }
- ];
+import {ITestSuite} from '../testsuite.interface';
+import {ITest} from '../test.interface';
+
+export class Tests implements ITestSuite<string, string> {
+ public getTests(): Array<ITest<string, string>> {
+ return [
+ {
+ input: "#ffffff",
+ output: "#000000"
+ },
+ {
+ input: "#abcdef",
+ output: "#543210"
+ },
+ {
+ input: "#badcab",
+ output: "#452354"
+ },
+ {
+ input: "#133742",
+ output: "#ecc8bd"
+ },
+ {
+ input: "#a1b2c3",
+ output: "#5e4d3c"
+ },
+ {
+ input: "#7f7f80",
+ output: "#80807f"
+ }
+ ];
+ }
} |
d14849be1bb825106a17a6e4ea4c0e9b6ae5a56c | src/AwaitLock.ts | src/AwaitLock.ts | import assert from 'assert';
/**
* A mutex lock for coordination across async functions
*/
export default class AwaitLock {
private _acquired: boolean = false;
private _waitingResolvers: (() => void)[] = [];
/**
* Acquires the lock, waiting if necessary for it to become free if it is already locked. The
* returned promise is fulfilled once the lock is acquired.
*
* After acquiring the lock, you **must** call `release` when you are done with it.
*/
acquireAsync(): Promise<void> {
if (!this._acquired) {
this._acquired = true;
return Promise.resolve();
}
return new Promise(resolve => {
this._waitingResolvers.push(resolve);
});
}
/**
* Acquires the lock if it is free and otherwise returns immediately without waiting. Returns
* `true` if the lock was free and is now acquired, and `false` otherwise,
*/
tryAcquire(): boolean {
if (!this._acquired) {
this._acquired = true;
return true;
}
return false;
}
/**
* Releases the lock and gives it to the next waiting acquirer, if there is one. Each acquirer
* must release the lock exactly once.
*/
release(): void {
assert(this._acquired, 'Trying to release an unacquired lock');
if (this._waitingResolvers.length > 0) {
let resolve = this._waitingResolvers.shift()!;
resolve();
} else {
this._acquired = false;
}
}
}
| /**
* A mutex lock for coordination across async functions
*/
export default class AwaitLock {
private _acquired: boolean = false;
private _waitingResolvers: (() => void)[] = [];
/**
* Acquires the lock, waiting if necessary for it to become free if it is already locked. The
* returned promise is fulfilled once the lock is acquired.
*
* After acquiring the lock, you **must** call `release` when you are done with it.
*/
acquireAsync(): Promise<void> {
if (!this._acquired) {
this._acquired = true;
return Promise.resolve();
}
return new Promise(resolve => {
this._waitingResolvers.push(resolve);
});
}
/**
* Acquires the lock if it is free and otherwise returns immediately without waiting. Returns
* `true` if the lock was free and is now acquired, and `false` otherwise,
*/
tryAcquire(): boolean {
if (!this._acquired) {
this._acquired = true;
return true;
}
return false;
}
/**
* Releases the lock and gives it to the next waiting acquirer, if there is one. Each acquirer
* must release the lock exactly once.
*/
release(): void {
if (!this._acquired) {
throw new Error(`Cannot release an unacquired lock`);
}
if (this._waitingResolvers.length > 0) {
let resolve = this._waitingResolvers.shift()!;
resolve();
} else {
this._acquired = false;
}
}
}
| Remove "assert" dep for easier web compatibility | Remove "assert" dep for easier web compatibility
See https://github.com/ide/await-lock/issues/6
| TypeScript | mit | ide/await-lock,ide/await-lock | ---
+++
@@ -1,5 +1,3 @@
-import assert from 'assert';
-
/**
* A mutex lock for coordination across async functions
*/
@@ -42,7 +40,10 @@
* must release the lock exactly once.
*/
release(): void {
- assert(this._acquired, 'Trying to release an unacquired lock');
+ if (!this._acquired) {
+ throw new Error(`Cannot release an unacquired lock`);
+ }
+
if (this._waitingResolvers.length > 0) {
let resolve = this._waitingResolvers.shift()!;
resolve(); |
8ee39038c058eb53eda071196e957998de2ec3c1 | src/extension.ts | src/extension.ts | 'use strict';
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
console.log('Dart-Code activated!');
}
export function deactivate() {
console.log('Dart-Code deactivated!');
} | "use strict";
import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
const configName = "dart";
const configSdkPath = "sdkPath";
let dartSdkRoot: string;
export function activate(context: vscode.ExtensionContext) {
console.log("Dart-Code activated!");
dartSdkRoot = findDartSdk();
if (dartSdkRoot != null) {
vscode.window.showErrorMessage("Dart-Code: Could not find a Dart SDK to use. Please add it to your PATH or set it in the extensions settings and reload");
return; // Don't set anything else up; we can't work like this!
}
}
export function deactivate() {
console.log("Dart-Code deactivated!");
}
function findDartSdk(): string {
let config = vscode.workspace.getConfiguration(configName);
let paths = (<string>process.env.PATH).split(";");
// We don't expect the user to add .\bin in config, but it would be in the PATHs
if (config.has(configSdkPath))
paths.unshift(path.join(config.get<string>(configSdkPath), 'bin'));
let sdkPath = paths.find(isValidDartSdk);
if (sdkPath)
return path.join(sdkPath, ".."); // Take .\bin back off.
return null;
}
function isValidDartSdk(pathToTest: string): boolean {
// To check for a Dart SDK, we check for .\dart or .\dart.exe
let dartLinux = path.join(pathToTest, "dart");
let dartWindows = path.join(pathToTest, "dart.exe");
// Apparently this is the "correct" way to check files exist synchronously in Node :'(
try {
fs.accessSync(dartLinux, fs.X_OK);
return true; // If no error, we found a match!
}
catch (e) { }
try {
fs.accessSync(dartWindows, fs.X_OK);
return true; // If no error, we found a match!
}
catch (e) { }
return false; // Neither one worked, so this must be an invalid path.
} | Add code to detect SDK and alert the user if not found. | Add code to detect SDK and alert the user if not found.
| TypeScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -1,10 +1,58 @@
-'use strict';
-import * as vscode from 'vscode';
+"use strict";
+import * as vscode from "vscode";
+import * as fs from "fs";
+import * as path from "path";
+
+const configName = "dart";
+const configSdkPath = "sdkPath";
+
+let dartSdkRoot: string;
export function activate(context: vscode.ExtensionContext) {
- console.log('Dart-Code activated!');
+ console.log("Dart-Code activated!");
+
+ dartSdkRoot = findDartSdk();
+ if (dartSdkRoot != null) {
+ vscode.window.showErrorMessage("Dart-Code: Could not find a Dart SDK to use. Please add it to your PATH or set it in the extensions settings and reload");
+ return; // Don't set anything else up; we can't work like this!
+ }
}
export function deactivate() {
- console.log('Dart-Code deactivated!');
+ console.log("Dart-Code deactivated!");
}
+
+function findDartSdk(): string {
+ let config = vscode.workspace.getConfiguration(configName);
+ let paths = (<string>process.env.PATH).split(";");
+
+ // We don't expect the user to add .\bin in config, but it would be in the PATHs
+ if (config.has(configSdkPath))
+ paths.unshift(path.join(config.get<string>(configSdkPath), 'bin'));
+
+ let sdkPath = paths.find(isValidDartSdk);
+ if (sdkPath)
+ return path.join(sdkPath, ".."); // Take .\bin back off.
+
+ return null;
+}
+
+function isValidDartSdk(pathToTest: string): boolean {
+ // To check for a Dart SDK, we check for .\dart or .\dart.exe
+ let dartLinux = path.join(pathToTest, "dart");
+ let dartWindows = path.join(pathToTest, "dart.exe");
+
+ // Apparently this is the "correct" way to check files exist synchronously in Node :'(
+ try {
+ fs.accessSync(dartLinux, fs.X_OK);
+ return true; // If no error, we found a match!
+ }
+ catch (e) { }
+ try {
+ fs.accessSync(dartWindows, fs.X_OK);
+ return true; // If no error, we found a match!
+ }
+ catch (e) { }
+
+ return false; // Neither one worked, so this must be an invalid path.
+} |
4c404bad9fb071b2d72e7051601394cf750961cb | lib/ui/src/components/sidebar/Heading.tsx | lib/ui/src/components/sidebar/Heading.tsx | import React, { FunctionComponent, ComponentProps } from 'react';
import { styled } from '@storybook/theming';
import { Brand } from './Brand';
import { SidebarMenu, MenuList } from './Menu';
export interface HeadingProps {
menuHighlighted?: boolean;
menu: MenuList;
}
const BrandArea = styled.div(({ theme }) => ({
fontSize: theme.typography.size.s2,
fontWeight: theme.typography.weight.bold,
color: theme.color.defaultText,
marginRight: 40,
display: 'flex',
width: '100%',
alignItems: 'center',
minHeight: 22,
'& > *': {
maxWidth: '100%',
height: 'auto',
width: 'auto',
display: 'block',
},
}));
const HeadingWrapper = styled.div({
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
position: 'relative',
});
export const Heading: FunctionComponent<HeadingProps & ComponentProps<typeof HeadingWrapper>> = ({
menuHighlighted = false,
menu,
...props
}) => {
return (
<HeadingWrapper {...props}>
<BrandArea>
<Brand />
</BrandArea>
<SidebarMenu menu={menu} isHighlighted={menuHighlighted} />
</HeadingWrapper>
);
};
| import React, { FunctionComponent, ComponentProps } from 'react';
import { styled } from '@storybook/theming';
import { Brand } from './Brand';
import { SidebarMenu, MenuList } from './Menu';
export interface HeadingProps {
menuHighlighted?: boolean;
menu: MenuList;
}
const BrandArea = styled.div(({ theme }) => ({
fontSize: theme.typography.size.s2,
fontWeight: theme.typography.weight.bold,
color: theme.color.defaultText,
marginRight: 40,
display: 'flex',
width: '100%',
alignItems: 'center',
minHeight: 22,
'& > *': {
maxWidth: '100%',
height: 'auto',
display: 'block',
flex: '1 1 auto',
},
}));
const HeadingWrapper = styled.div({
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
position: 'relative',
});
export const Heading: FunctionComponent<HeadingProps & ComponentProps<typeof HeadingWrapper>> = ({
menuHighlighted = false,
menu,
...props
}) => {
return (
<HeadingWrapper {...props}>
<BrandArea>
<Brand />
</BrandArea>
<SidebarMenu menu={menu} isHighlighted={menuHighlighted} />
</HeadingWrapper>
);
};
| Fix display of sidebar logo | UI: Fix display of sidebar logo | TypeScript | mit | kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -22,8 +22,8 @@
'& > *': {
maxWidth: '100%',
height: 'auto',
- width: 'auto',
display: 'block',
+ flex: '1 1 auto',
},
}));
|
7b88c453797dbb5f64ac052982c6162498ace2ae | src/emitter/functions.ts | src/emitter/functions.ts | import { FunctionLikeDeclaration, Identifier, TypeReferenceNode } from 'typescript';
import { Context } from '../contexts';
import { EmitResult, emit } from './';
const emitFunctionDeclaration = (node: FunctionLikeDeclaration, context: Context): string => {
const return_type = emit(node.type, context).emitted_string;
const function_name = emit(node.name, context).emitted_string;
const parameters =
node.parameters
.map(p => ({ name: emit(p.name, context).emitted_string, type: emit(p.type, context).emitted_string}))
.map(({ name, type }) => `${type} ${name}`)
.join(', ');
const body = '';
const declaration = `${return_type} ${function_name}(${parameters}) {\n${body}\n}`;
return declaration;
};
export const emitFunctionLikeDeclaration = (node: FunctionLikeDeclaration, context: Context): EmitResult => {
return {
context,
emitted_string: emitFunctionDeclaration(node, context)
};
}
| import { FunctionLikeDeclaration, Identifier, TypeReferenceNode } from 'typescript';
import { Context } from '../contexts';
import { EmitResult, emit } from './';
const emitFunctionDeclaration = (node: FunctionLikeDeclaration, context: Context): string => {
const return_type = emit(node.type, context).emitted_string;
const function_name = emit(node.name, context).emitted_string;
const parameters =
node.parameters
.map(p => ({ name: emit(p.name, context).emitted_string, type: emit(p.type, context).emitted_string}))
.map(({ name, type }) => `${type} ${name}`)
.join(', ');
const body = emit(node.body, context).emitted_string;
const declaration = `${return_type} ${function_name}(${parameters}) ${body}`;
return declaration;
};
export const emitFunctionLikeDeclaration = (node: FunctionLikeDeclaration, context: Context): EmitResult => {
return {
context,
emitted_string: emitFunctionDeclaration(node, context)
};
}
| Use emit result of function body | Use emit result of function body
| TypeScript | mit | AmnisIO/typewriter,AmnisIO/typewriter,AmnisIO/typewriter | ---
+++
@@ -10,8 +10,8 @@
.map(p => ({ name: emit(p.name, context).emitted_string, type: emit(p.type, context).emitted_string}))
.map(({ name, type }) => `${type} ${name}`)
.join(', ');
- const body = '';
- const declaration = `${return_type} ${function_name}(${parameters}) {\n${body}\n}`;
+ const body = emit(node.body, context).emitted_string;
+ const declaration = `${return_type} ${function_name}(${parameters}) ${body}`;
return declaration;
};
|
e8fa6808a5d0b2204173cf78537b9349048aa814 | src/form/elements/index.ts | src/form/elements/index.ts | /**
* Created by Samuel Gratzl on 08.03.2017.
*/
import {IForm, IFormElementDesc,IFormElement} from '../interfaces';
import {list, IPluginDesc} from 'phovea_core/src/plugin';
import {FORM_EXTENSION_POINT} from '..';
/**
* Factory method to create form elements for the phovea extension type `tdpFormElement`.
* An element is found when `desc.type` is matching the extension id.
*
* @param form the form to which the element will be appended
* @param $parent parent D3 selection element
* @param desc form element description
*/
export function create(form: IForm, $parent: d3.Selection<any>, desc: IFormElementDesc): Promise<IFormElement> {
const plugins = list((pluginDesc: IPluginDesc) => {
return pluginDesc.type === FORM_EXTENSION_POINT && pluginDesc.id === desc.type;
});
if(plugins.length === 0) {
throw new Error('unknown form element type: ' + desc.type);
}
return plugins[0].load().then((p) => {
// selection is used in SELECT2 and SELECT3
if(p.desc.selection) {
return p.factory(form, $parent, <any>desc, p.desc.selection);
}
return p.factory(form, $parent, <any>desc);
});
}
| /**
* Created by Samuel Gratzl on 08.03.2017.
*/
import {IForm, IFormElementDesc,IFormElement} from '../interfaces';
import {get} from 'phovea_core/src/plugin';
import {FORM_EXTENSION_POINT} from '..';
/**
* Factory method to create form elements for the phovea extension type `tdpFormElement`.
* An element is found when `desc.type` is matching the extension id.
*
* @param form the form to which the element will be appended
* @param $parent parent D3 selection element
* @param desc form element description
*/
export function create(form: IForm, $parent: d3.Selection<any>, desc: IFormElementDesc): Promise<IFormElement> {
const plugin = get(FORM_EXTENSION_POINT, desc.type);
if(!plugin) {
throw new Error('unknown form element type: ' + desc.type);
}
return plugin.load().then((p) => {
// selection is used in SELECT2 and SELECT3
if(p.desc.selection) {
return p.factory(form, $parent, <any>desc, p.desc.selection);
}
return p.factory(form, $parent, <any>desc);
});
}
| Use `plugin.get` in form element `create` function | Use `plugin.get` in form element `create` function
#185
| TypeScript | bsd-3-clause | datavisyn/tdp_core,datavisyn/tdp_core,datavisyn/tdp_core,datavisyn/tdp_core | ---
+++
@@ -2,7 +2,7 @@
* Created by Samuel Gratzl on 08.03.2017.
*/
import {IForm, IFormElementDesc,IFormElement} from '../interfaces';
-import {list, IPluginDesc} from 'phovea_core/src/plugin';
+import {get} from 'phovea_core/src/plugin';
import {FORM_EXTENSION_POINT} from '..';
/**
@@ -14,13 +14,11 @@
* @param desc form element description
*/
export function create(form: IForm, $parent: d3.Selection<any>, desc: IFormElementDesc): Promise<IFormElement> {
- const plugins = list((pluginDesc: IPluginDesc) => {
- return pluginDesc.type === FORM_EXTENSION_POINT && pluginDesc.id === desc.type;
- });
- if(plugins.length === 0) {
+ const plugin = get(FORM_EXTENSION_POINT, desc.type);
+ if(!plugin) {
throw new Error('unknown form element type: ' + desc.type);
}
- return plugins[0].load().then((p) => {
+ return plugin.load().then((p) => {
// selection is used in SELECT2 and SELECT3
if(p.desc.selection) {
return p.factory(form, $parent, <any>desc, p.desc.selection); |
53202341e81a6011e1b8de2197336b46a2b5550f | test-errors/classes.ts | test-errors/classes.ts | class A {
x: number = 42 // TS9209 - field initializers
}
class B extends A { } // TS9228 - inheritence
interface C { } // Probably should emit some sort of error, just skips it at the moment
class D implements C { } // TS9228
class G<T> { } // Generics now supported
class S {
public static x: number
public static m() { }
}
S.x = 42 // TS9247 - can be removed if static field support is added
S.m() // TS9235 - can be removed if static method support is added
| class A {
x: number = 42 // TS9209 - field initializers
}
class B extends A { } // TS9228 - inheritence
interface C { } // Probably should emit some sort of error, just skips it at the moment
class D implements C { } // TS9228
class G<T> { } // Generics now supported
class S {
public static x: number
public static m() { }
}
S.x = 42
S.m()
| Fix testsuite (static now supported) | Fix testsuite (static now supported)
| TypeScript | mit | switch-education/pxt,Microsoft/pxt,Microsoft/pxt,playi/pxt,Microsoft/pxt,switchinnovations/pxt,switchinnovations/pxt,Microsoft/pxt,switchinnovations/pxt,switch-education/pxt,switch-education/pxt,switch-education/pxt,Microsoft/pxt,playi/pxt,playi/pxt,switchinnovations/pxt,switch-education/pxt,playi/pxt | ---
+++
@@ -9,5 +9,5 @@
public static x: number
public static m() { }
}
-S.x = 42 // TS9247 - can be removed if static field support is added
-S.m() // TS9235 - can be removed if static method support is added
+S.x = 42
+S.m() |
de637662069f398318c07a07140704909b2749d7 | src/app/config/constants/apiURL.prod.ts | src/app/config/constants/apiURL.prod.ts | let API_URL: string;
API_URL = `https://${window.location.host}/api`;
export default API_URL;
| let API_URL: string;
API_URL = `${window.location.origin}/api`;
export default API_URL;
| Switch api url to use origin | CONFIG: Switch api url to use origin
| TypeScript | agpl-3.0 | doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web | ---
+++
@@ -1,4 +1,4 @@
let API_URL: string;
-API_URL = `https://${window.location.host}/api`;
+API_URL = `${window.location.origin}/api`;
export default API_URL; |
c2783efb6d05f6d6759aeda57047e7b12d9107fa | src/telemetry.ts | src/telemetry.ts | 'use strict';
import { RestClientSettings } from './models/configurationSettings';
import * as Constants from './constants';
import * as appInsights from "applicationinsights";
appInsights.setup(Constants.AiKey)
.setAutoCollectPerformance(false)
.start();
export class Telemetry {
private static readonly restClientSettings: RestClientSettings = new RestClientSettings();
public static sendEvent(eventName: string, properties?: { [key: string]: string }) {
try {
if (Telemetry.restClientSettings.enableTelemetry) {
appInsights.defaultClient.trackEvent({name: eventName, properties});
}
} catch {
}
}
} | 'use strict';
import { RestClientSettings } from './models/configurationSettings';
import * as Constants from './constants';
import * as appInsights from "applicationinsights";
appInsights.setup(Constants.AiKey)
.setAutoCollectDependencies(false)
.setAutoCollectPerformance(false)
.setAutoCollectRequests(false)
.setAutoDependencyCorrelation(false)
.start();
export class Telemetry {
private static readonly restClientSettings: RestClientSettings = new RestClientSettings();
public static sendEvent(eventName: string, properties?: { [key: string]: string }) {
try {
if (Telemetry.restClientSettings.enableTelemetry) {
appInsights.defaultClient.trackEvent({name: eventName, properties});
}
} catch {
}
}
} | Disable some auto collected metrics | Disable some auto collected metrics
| TypeScript | mit | Huachao/vscode-restclient,Huachao/vscode-restclient | ---
+++
@@ -5,7 +5,10 @@
import * as appInsights from "applicationinsights";
appInsights.setup(Constants.AiKey)
+ .setAutoCollectDependencies(false)
.setAutoCollectPerformance(false)
+ .setAutoCollectRequests(false)
+ .setAutoDependencyCorrelation(false)
.start();
export class Telemetry { |
7666047927cac50b9da1196bd282f973ec945988 | modern/src/runtime/Text.ts | modern/src/runtime/Text.ts | import GuiObject from "./GuiObject";
import { unimplementedWarning } from "../utils";
class Text extends GuiObject {
/**
* getclassname()
*
* Returns the class name for the object.
* @ret The class name.
*/
getclassname() {
return "Text";
}
setalternatetext(txt: string) {
unimplementedWarning("setalternatetext");
}
settext(txt: string) {
unimplementedWarning("settext");
return;
}
gettext() {
unimplementedWarning("gettext");
return;
}
gettextwidth() {
unimplementedWarning("gettextwidth");
return;
}
ontextchanged(newtxt: string): void {
this.js_trigger("onTextChanged", newtxt);
}
}
export default Text;
| import GuiObject from "./GuiObject";
import { unimplementedWarning } from "../utils";
class Text extends GuiObject {
/**
* getclassname()
*
* Returns the class name for the object.
* @ret The class name.
*/
getclassname() {
return "Text";
}
setalternatetext(txt: string) {
unimplementedWarning("setalternatetext");
}
settext(txt: string) {
unimplementedWarning("settext");
return;
}
gettext() {
unimplementedWarning("gettext");
return "";
}
gettextwidth() {
unimplementedWarning("gettextwidth");
return;
}
ontextchanged(newtxt: string): void {
this.js_trigger("onTextChanged", newtxt);
}
}
export default Text;
| Return a string so other methods don't crash | Return a string so other methods don't crash
| TypeScript | mit | captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js | ---
+++
@@ -23,7 +23,7 @@
gettext() {
unimplementedWarning("gettext");
- return;
+ return "";
}
gettextwidth() { |
fcdff55b266f027cd3c361aaf2a391c88f1ea672 | lib/tasks/CopyIndex.ts | lib/tasks/CopyIndex.ts | import {buildHelper as helper, taskRunner} from "../Container";
const gulp = require("gulp");
const embedlr = require("gulp-embedlr");
export default function CopyIndex() {
let stream = gulp.src('index.html');
if (helper.isWatching())
stream = stream.pipe(embedlr());
return stream.pipe(gulp.dest(helper.getTempFolder()));
} | import {buildHelper as helper, taskRunner} from "../Container";
const gulp = require("gulp");
const embedlr = require("gulp-embedlr");
export default function CopyIndex() {
let stream = gulp.src('index.html');
if (helper.isWatching())
stream = stream.pipe(embedlr({ port: helper.getSettings().liveReloadPort}));
return stream.pipe(gulp.dest(helper.getTempFolder()));
} | Add live reload port to embedlr | Add live reload port to embedlr
| TypeScript | mit | mtfranchetto/smild,mtfranchetto/smild,mtfranchetto/smild | ---
+++
@@ -5,6 +5,6 @@
export default function CopyIndex() {
let stream = gulp.src('index.html');
if (helper.isWatching())
- stream = stream.pipe(embedlr());
+ stream = stream.pipe(embedlr({ port: helper.getSettings().liveReloadPort}));
return stream.pipe(gulp.dest(helper.getTempFolder()));
} |
e77e31f352a41fc54a75af4c19a329025915848a | app/src/lib/gravatar.ts | app/src/lib/gravatar.ts | import * as crypto from 'crypto'
import { getDotComAPIEndpoint } from './api'
/**
* Convert an email address to a Gravatar URL format
*
* @param email The email address associated with a user
* @param size The size (in pixels) of the avatar to render
*/
export function generateGravatarUrl(email: string, size: number = 200): string {
const input = email.trim().toLowerCase()
const hash = crypto
.createHash('md5')
.update(input)
.digest('hex')
return `https://www.gravatar.com/avatar/${hash}?s=${size}`
}
/**
* Retrieve the avatar for the given author, based on the
* endpoint associated with an account.
*
* This is a workaround for a current limitation with
* GitHub Enterprise, where avatar URLs are inaccessible
* in some scenarios.
*
* @param avatar_url The canonical avatar to use
* @param email The email address to use as a fallback
* @param endpoint The API endpoint for the account
*/
export function getAvatarWithEnterpriseFallback(
avatar_url: string,
email: string,
endpoint: string
): string {
if (endpoint === getDotComAPIEndpoint()) {
return avatar_url
}
return generateGravatarUrl(email)
}
| import * as crypto from 'crypto'
import { getDotComAPIEndpoint } from './api'
/**
* Convert an email address to a Gravatar URL format
*
* @param email The email address associated with a user
* @param size The size (in pixels) of the avatar to render
*/
export function generateGravatarUrl(email: string, size: number = 200): string {
const input = email.trim().toLowerCase()
const hash = crypto
.createHash('md5')
.update(input)
.digest('hex')
return `https://www.gravatar.com/avatar/${hash}?s=${size}`
}
/**
* Retrieve the avatar for the given author, based on the
* endpoint associated with an account.
*
* This is a workaround for a current limitation with
* GitHub Enterprise, where avatar URLs are inaccessible
* in some scenarios.
*
* @param avatar_url The canonical avatar to use
* @param email The email address to use as a fallback
* @param endpoint The API endpoint for the account
*/
export function getAvatarWithEnterpriseFallback(
avatar_url: string,
email: string | null,
endpoint: string
): string {
if (endpoint === getDotComAPIEndpoint() || email === null) {
return avatar_url
}
return generateGravatarUrl(email)
}
| Allow null emails in getAvatarWithEnterpriseFallback | Allow null emails in getAvatarWithEnterpriseFallback
| TypeScript | mit | j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,say25/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,artivilla/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,j-f1/forked-desktop,artivilla/desktop,say25/desktop,j-f1/forked-desktop | ---
+++
@@ -32,10 +32,10 @@
*/
export function getAvatarWithEnterpriseFallback(
avatar_url: string,
- email: string,
+ email: string | null,
endpoint: string
): string {
- if (endpoint === getDotComAPIEndpoint()) {
+ if (endpoint === getDotComAPIEndpoint() || email === null) {
return avatar_url
}
|
ee9f34c2932dd2a8a34d7cbfc04ffc48b264574c | packages/documentation/src/components/Layout/ToggleRTL.tsx | packages/documentation/src/components/Layout/ToggleRTL.tsx | import type { ReactElement } from "react";
import { AppBarAction } from "@react-md/app-bar";
import {
FormatAlignLeftSVGIcon,
FormatAlignRightSVGIcon,
} from "@react-md/material-icons";
import { MenuItem } from "@react-md/menu";
import { Tooltip, useTooltip } from "@react-md/tooltip";
import { useDir } from "@react-md/utils";
export interface ToggleRTLProps {
as: "action" | "menuitem";
}
export default function ToggleRTL({ as }: ToggleRTLProps): ReactElement {
const { dir, toggleDir } = useDir();
const isRTL = dir === "rtl";
let icon = <FormatAlignLeftSVGIcon />;
if (isRTL) {
icon = <FormatAlignRightSVGIcon />;
}
const { elementProps, tooltipProps } = useTooltip({
baseId: "toggle-rtl",
onClick: toggleDir,
});
if (as === "menuitem") {
return (
<MenuItem
id="toggle-rtl"
onClick={toggleDir}
leftAddon={icon}
secondaryText={`Current orientation: ${isRTL ? "RTL" : "LTR"}`}
>
Toggle RTL
</MenuItem>
);
}
return (
<>
<AppBarAction
{...elementProps}
last
aria-label="Right to left layout"
aria-pressed={isRTL}
>
{icon}
</AppBarAction>
<Tooltip {...tooltipProps}>TOggle right to left</Tooltip>
</>
);
}
| import type { ReactElement } from "react";
import { AppBarAction } from "@react-md/app-bar";
import {
FormatAlignLeftSVGIcon,
FormatAlignRightSVGIcon,
} from "@react-md/material-icons";
import { MenuItem } from "@react-md/menu";
import { Tooltip, useTooltip } from "@react-md/tooltip";
import { useDir } from "@react-md/utils";
export interface ToggleRTLProps {
as: "action" | "menuitem";
}
export default function ToggleRTL({ as }: ToggleRTLProps): ReactElement {
const { dir, toggleDir } = useDir();
const isRTL = dir === "rtl";
let icon = <FormatAlignLeftSVGIcon />;
if (isRTL) {
icon = <FormatAlignRightSVGIcon />;
}
const { elementProps, tooltipProps } = useTooltip({
baseId: "toggle-rtl",
onClick: toggleDir,
});
if (as === "menuitem") {
return (
<MenuItem
id="toggle-rtl"
onClick={toggleDir}
leftAddon={icon}
secondaryText={`Current orientation: ${isRTL ? "RTL" : "LTR"}`}
>
Toggle RTL
</MenuItem>
);
}
return (
<>
<AppBarAction
{...elementProps}
last
aria-label="Right to left layout"
aria-pressed={isRTL}
>
{icon}
</AppBarAction>
<Tooltip {...tooltipProps}>Toggle right to left</Tooltip>
</>
);
}
| Fix typo for RTL tooltip | chore(website): Fix typo for RTL tooltip
| TypeScript | mit | mlaursen/react-md,mlaursen/react-md,mlaursen/react-md | ---
+++
@@ -48,7 +48,7 @@
>
{icon}
</AppBarAction>
- <Tooltip {...tooltipProps}>TOggle right to left</Tooltip>
+ <Tooltip {...tooltipProps}>Toggle right to left</Tooltip>
</>
);
} |
bf1fc44356ac654f48e019c343bac08a446b4922 | data/static/codefixes/loginJimChallenge_3.ts | data/static/codefixes/loginJimChallenge_3.ts | module.exports = function login () {
function afterLogin (user, res, next) {
models.Basket.findOrCreate({ where: { UserId: user.data.id }, defaults: {} })
.then(([basket]) => {
const token = security.authorize(user)
user.bid = basket.id // keep track of original basket
security.authenticatedUsers.put(token, user)
res.json({ authentication: { token, bid: basket.id, umail: user.data.email } })
}).catch(error => {
next(error)
})
}
return (req, res, next) => {
models.sequelize.query(`SELECT * FROM Users WHERE email = ? AND password = ? AND deletedAt IS NULL`,
{ replacements: [ req.body.email, security.hash(req.body.password) ], model: models.User, plain: true })
.then((authenticatedUser) => {
const user = utils.queryResultToJson(authenticatedUser)
if (user.data?.id && user.data.totpSecret !== '') {
res.status(401).json({
status: 'totp_token_required',
data: {
tmpToken: security.authorize({
userId: user.data.id,
type: 'password_valid_needs_second_factor_token'
})
}
})
} else if (user.data?.id) {
afterLogin(user, res, next)
} else {
res.status(401).send(res.__('Invalid email or password.'))
}
}).catch(error => {
next(error)
})
} | module.exports = function login () {
function afterLogin (user, res, next) {
models.Basket.findOrCreate({ where: { UserId: user.data.id }, defaults: {} })
.then(([basket]) => {
const token = security.authorize(user)
user.bid = basket.id // keep track of original basket
security.authenticatedUsers.put(token, user)
res.json({ authentication: { token, bid: basket.id, umail: user.data.email } })
}).catch(error => {
next(error)
})
}
return (req, res, next) => {
models.sequelize.query(`SELECT * FROM Users WHERE email = ? AND password = ? AND deletedAt IS NULL`,
{ replacements: [ req.body.email, req.body.password ], model: models.User, plain: true })
.then((authenticatedUser) => {
const user = utils.queryResultToJson(authenticatedUser)
if (user.data?.id && user.data.totpSecret !== '') {
res.status(401).json({
status: 'totp_token_required',
data: {
tmpToken: security.authorize({
userId: user.data.id,
type: 'password_valid_needs_second_factor_token'
})
}
})
} else if (user.data?.id) {
afterLogin(user, res, next)
} else {
res.status(401).send(res.__('Invalid email or password.'))
}
}).catch(error => {
next(error)
})
} | Change supposedly wrong fix option into actually being wrong | Change supposedly wrong fix option into actually being wrong
| TypeScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -13,7 +13,7 @@
return (req, res, next) => {
models.sequelize.query(`SELECT * FROM Users WHERE email = ? AND password = ? AND deletedAt IS NULL`,
- { replacements: [ req.body.email, security.hash(req.body.password) ], model: models.User, plain: true })
+ { replacements: [ req.body.email, req.body.password ], model: models.User, plain: true })
.then((authenticatedUser) => {
const user = utils.queryResultToJson(authenticatedUser)
if (user.data?.id && user.data.totpSecret !== '') { |
12e87b7b353876e27a50acb452e0ebdfbc651087 | src/cli/TypeSource.ts | src/cli/TypeSource.ts | import { Readable } from "readable-stream";
import { JSONSourceData, JSONSchemaSourceData } from "quicktype-core";
import { GraphQLSourceData } from "../quicktype-graphql-input";
export interface JSONTypeSource extends JSONSourceData<Readable> {
kind: "json";
}
export interface SchemaTypeSource extends JSONSchemaSourceData {
kind: "schema";
}
export interface GraphQLTypeSource extends GraphQLSourceData {
kind: "graphql";
}
export type TypeSource = GraphQLTypeSource | JSONTypeSource | SchemaTypeSource;
| import { Readable } from "readable-stream";
import { JSONSourceData, JSONSchemaSourceData } from "../quicktype-core";
import { GraphQLSourceData } from "../quicktype-graphql-input";
export interface JSONTypeSource extends JSONSourceData<Readable> {
kind: "json";
}
export interface SchemaTypeSource extends JSONSchemaSourceData {
kind: "schema";
}
export interface GraphQLTypeSource extends GraphQLSourceData {
kind: "graphql";
}
export type TypeSource = GraphQLTypeSource | JSONTypeSource | SchemaTypeSource;
| Fix for import reference module path | Fix for import reference module path
Fixed the correct relative module path reference for import from quicktype-core | TypeScript | apache-2.0 | quicktype/quicktype,quicktype/quicktype,quicktype/quicktype,quicktype/quicktype,quicktype/quicktype | ---
+++
@@ -1,6 +1,6 @@
import { Readable } from "readable-stream";
-import { JSONSourceData, JSONSchemaSourceData } from "quicktype-core";
+import { JSONSourceData, JSONSchemaSourceData } from "../quicktype-core";
import { GraphQLSourceData } from "../quicktype-graphql-input";
export interface JSONTypeSource extends JSONSourceData<Readable> { |
41fe5b071e5728c1111d9029e59099b43945b03f | addons/toolbars/src/components/MenuToolbar.tsx | addons/toolbars/src/components/MenuToolbar.tsx | import React, { FC } from 'react';
import { useGlobals } from '@storybook/api';
import { Icons, IconButton, WithTooltip, TooltipLinkList, TabButton } from '@storybook/components';
import { NormalizedToolbarArgType } from '../types';
export type MenuToolbarProps = NormalizedToolbarArgType & { id: string };
export const MenuToolbar: FC<MenuToolbarProps> = ({
id,
name,
description,
toolbar: { icon, items, showName },
}) => {
const [globals, updateGlobals] = useGlobals();
const selectedValue = globals[id];
const active = selectedValue != null;
const selectedItem = active && items.find((item) => item.value === selectedValue);
const selectedIcon = (selectedItem && selectedItem.icon) || icon;
return (
<WithTooltip
placement="top"
trigger="click"
tooltip={({ onHide }) => {
const links = items.map((item) => {
const { value, left, title, right } = item;
return {
id: value,
left,
title,
right,
active: selectedValue === value,
onClick: () => {
updateGlobals({ [id]: value });
onHide();
},
};
});
return <TooltipLinkList links={links} />;
}}
closeOnClick
>
{selectedIcon ? (
<IconButton key={name} active={active} title={description}>
<Icons icon={selectedIcon} />
{showName ? `\xa0${name}` : ``}
</IconButton>
) : (
<TabButton active={active}>{name}</TabButton>
)}
</WithTooltip>
);
};
| import React, { FC } from 'react';
import { useGlobals } from '@storybook/api';
import { Icons, IconButton, WithTooltip, TooltipLinkList, TabButton } from '@storybook/components';
import { NormalizedToolbarArgType } from '../types';
export type MenuToolbarProps = NormalizedToolbarArgType & { id: string };
export const MenuToolbar: FC<MenuToolbarProps> = ({
id,
name,
description,
toolbar: { icon, items, showName },
}) => {
const [globals, updateGlobals] = useGlobals();
const selectedValue = globals[id];
const active = selectedValue != null;
const selectedItem = active && items.find((item) => item.value === selectedValue);
const selectedIcon = (selectedItem && selectedItem.icon) || icon;
return (
<WithTooltip
placement="top"
trigger="click"
tooltip={({ onHide }) => {
const links = items.map((item) => {
const { value, left, title, right } = item;
return {
id: value,
left,
title,
right,
active: selectedValue === value,
onClick: () => {
updateGlobals({ [id]: value });
onHide();
},
};
});
return <TooltipLinkList links={links} />;
}}
closeOnClick
>
{selectedIcon ? (
<IconButton key={name} active={active} title={description}>
<Icons icon={selectedIcon} />
{showName ? `\xa0${name}` : null}
</IconButton>
) : (
<TabButton active={active}>{name}</TabButton>
)}
</WithTooltip>
);
};
| Update label display to return null if the showName is not set to true | Update label display to return null if the showName is not set to true | TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -43,7 +43,7 @@
{selectedIcon ? (
<IconButton key={name} active={active} title={description}>
<Icons icon={selectedIcon} />
- {showName ? `\xa0${name}` : ``}
+ {showName ? `\xa0${name}` : null}
</IconButton>
) : (
<TabButton active={active}>{name}</TabButton> |
a8d851cc62788206852bd690bf577f51584a7cea | app/index.ts | app/index.ts | import './styles.css'
import {
run,
// DEV
logFns,
mergeStates,
} from 'fractal-core'
import { viewHandler } from 'fractal-core/interfaces/view'
import { styleHandler } from 'fractal-core/groups/style'
import * as root from './Root'
declare const ENV: any
let DEV = ENV === 'development'
const app = run({
root,
groups: {
style: styleHandler('', DEV),
},
interfaces: {
view: viewHandler('#app'),
},
...DEV ? logFns : {},
})
// Hot reload - DEV ONLY
if (module.hot) {
module.hot.accept('./Root', () => {
let m = <any> require('./Root')
app.moduleAPI.reattach(m, mergeStates)
})
}
| import './styles.css'
import {
run,
// DEV
logFns,
mergeStates,
} from 'fractal-core'
import { viewHandler } from 'fractal-core/interfaces/view'
import { styleHandler } from 'fractal-core/groups/style'
import * as root from './Root'
declare const ENV: any
let DEV = ENV === 'development'
const app = run({
root,
groups: {
style: styleHandler('', DEV),
},
interfaces: {
view: viewHandler('#app'),
},
...DEV ? logFns : {},
})
// Hot reload - DEV ONLY
if (module.hot) {
module.hot.accept('./Root', () => {
let m = <any> require('./Root')
app.moduleAPI.reattach(m, mergeStates)
})
}
| Add new line for fixing code style | Add new line for fixing code style
| TypeScript | mit | FractalBlocks/Fractal-quickstart,FractalBlocks/Fractal-quickstart,FractalBlocks/Fractal-quickstart | ---
+++
@@ -7,6 +7,7 @@
} from 'fractal-core'
import { viewHandler } from 'fractal-core/interfaces/view'
import { styleHandler } from 'fractal-core/groups/style'
+
import * as root from './Root'
declare const ENV: any |
704d5d065808d9181a1054a901d7a3b4e13e2407 | src/main/index.tsx | src/main/index.tsx | import 'babel-polyfill'
import React, { Component } from 'react'
import { render } from 'react-dom'
import { App } from './App'
import { AppContainer } from 'react-hot-loader'
const domElement = document.getElementById('root')
const renderApp = (RootComponent: Component) => {
render(
<AppContainer>
<RootComponent />
</AppContainer>,
domElement
)
}
if (module.hot) {
module.hot.accept('./App', () => renderApp(App))
}
renderApp(App)
| import 'babel-polyfill'
import React, { Component } from 'react'
import { render } from 'react-dom'
import { App } from './App'
import { AppContainer } from 'react-hot-loader'
const domElement = document.getElementById('root')
const renderApp = (RootComponent: new () => Component<any, any>) => {
render(
<AppContainer>
<RootComponent />
</AppContainer>,
domElement
)
}
if (module.hot) {
module.hot.accept('./App', () => renderApp(App))
}
renderApp(App)
| Fix Typescript Component class parameter declaration | Fix Typescript Component class parameter declaration
| TypeScript | mit | olegstepura/awesome-typescript-loader-test,olegstepura/awesome-typescript-loader-test,olegstepura/awesome-typescript-loader-test,olegstepura/awesome-typescript-loader-test | ---
+++
@@ -5,7 +5,7 @@
import { AppContainer } from 'react-hot-loader'
const domElement = document.getElementById('root')
-const renderApp = (RootComponent: Component) => {
+const renderApp = (RootComponent: new () => Component<any, any>) => {
render(
<AppContainer>
<RootComponent /> |
e89539684ae48237c82b67938fcc18298308133c | src/markdown-preview/insert-menu-entries.ts | src/markdown-preview/insert-menu-entries.ts | import { normalizeUrl } from '@worldbrain/memex-url-utils'
import { isLoggable } from 'src/activity-logger'
import { extractIdFromUrl, isUrlYTVideo } from 'src/util/youtube-url'
import { MenuItemProps } from './types'
export const annotationMenuItems: MenuItemProps[] = [
{
name: 'YouTube Timestamp',
isDisabled: !isUrlYTVideo(document.location.href),
getTextToInsert() {
const videoEl = document.querySelector<HTMLVideoElement>(
'.video-stream',
)
const timestampSecs = Math.trunc(videoEl?.currentTime ?? 0)
const humanTimestamp = `${Math.floor(timestampSecs / 60)}:${(
timestampSecs % 60
)
.toString()
.padStart(2, '0')}`
const videoId = extractIdFromUrl(document.location.href)
return `[${humanTimestamp}](https://youtu.be/${videoId}?t=${timestampSecs})`
},
},
{
name: 'Link',
isDisabled: !isLoggable({ url: document.location.href }),
getTextToInsert() {
return `[${normalizeUrl(document.location.href)}](${
document.location.href
})`
},
},
]
| import { extractIdFromUrl, isUrlYTVideo } from 'src/util/youtube-url'
import { MenuItemProps } from './types'
export const annotationMenuItems: MenuItemProps[] = [
{
name: 'YouTube Timestamp',
isDisabled: !isUrlYTVideo(document.location.href),
getTextToInsert() {
const videoEl = document.querySelector<HTMLVideoElement>(
'.video-stream',
)
const timestampSecs = Math.trunc(videoEl?.currentTime ?? 0)
const humanTimestamp = `${Math.floor(timestampSecs / 60)}:${(
timestampSecs % 60
)
.toString()
.padStart(2, '0')}`
const videoId = extractIdFromUrl(document.location.href)
return `[${humanTimestamp}](https://youtu.be/${videoId}?t=${timestampSecs})`
},
},
{
name: 'Link',
getTextToInsert() {
return '[LinkText](url)'
},
},
]
| Make 'Link' insert menu item insert MD placeholder | Make 'Link' insert menu item insert MD placeholder
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -1,6 +1,3 @@
-import { normalizeUrl } from '@worldbrain/memex-url-utils'
-
-import { isLoggable } from 'src/activity-logger'
import { extractIdFromUrl, isUrlYTVideo } from 'src/util/youtube-url'
import { MenuItemProps } from './types'
@@ -27,11 +24,8 @@
},
{
name: 'Link',
- isDisabled: !isLoggable({ url: document.location.href }),
getTextToInsert() {
- return `[${normalizeUrl(document.location.href)}](${
- document.location.href
- })`
+ return '[LinkText](url)'
},
},
] |
3452284971165e383bb745c4c5743f9826bdeae5 | packages/components/components/contacts/ContactImageField.tsx | packages/components/components/contacts/ContactImageField.tsx | import React from 'react';
import { c } from 'ttag';
import { Button } from '../button';
interface Props {
value: string;
onChange: () => void;
}
const ContactImageField = ({ value, onChange }: Props) => {
return (
<div>
{value ? (
<img className="max-w13e" src={value} referrerPolicy="no-referrer" />
) : (
<Button onClick={onChange}>{c('Action').t`Upload picture`}</Button>
)}
</div>
);
};
export default ContactImageField;
| import React from 'react';
import { c } from 'ttag';
import { formatImage } from 'proton-shared/lib/helpers/image';
import { Button } from '../button';
interface Props {
value: string;
onChange: () => void;
}
const ContactImageField = ({ value, onChange }: Props) => {
return (
<div>
{value ? (
<img className="max-w13e" src={formatImage(value)} referrerPolicy="no-referrer" />
) : (
<Button onClick={onChange}>{c('Action').t`Upload picture`}</Button>
)}
</div>
);
};
export default ContactImageField;
| Format image in contact editor | Format image in contact editor
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,5 +1,6 @@
import React from 'react';
import { c } from 'ttag';
+import { formatImage } from 'proton-shared/lib/helpers/image';
import { Button } from '../button';
@@ -12,7 +13,7 @@
return (
<div>
{value ? (
- <img className="max-w13e" src={value} referrerPolicy="no-referrer" />
+ <img className="max-w13e" src={formatImage(value)} referrerPolicy="no-referrer" />
) : (
<Button onClick={onChange}>{c('Action').t`Upload picture`}</Button>
)} |
ff53e2d9accc9d9d7b3abc272b2c12e7a11a23fc | src/polyfills/index.ts | src/polyfills/index.ts | /*eslint-disable */
import 'core-js/fn/reflect/own-keys'
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (search, pos) {
return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search
}
}
if (!Array.prototype.includes) {
Array.prototype.includes = function (searchElement, ...args) {
let O = Object(this)
let len = parseInt(O.length, 10) || 0
if (len === 0) {
return false
}
let n = (args as any)[1] || 0
let k
if (n >= 0) {
k = n
} else {
k = len + n
if (k < 0) {
k = 0
}
}
let currentElement
while (k < len) {
currentElement = O[k]
if (searchElement === currentElement || (searchElement !== searchElement && currentElement !== currentElement)) {
return true
}
k++
}
return false
}
}
if (!Object.values || !Object.entries || !Object.assign) {
const reduce = Function.bind.call(Function.call as any, Array.prototype.reduce)
const isEnumerable = Function.bind.call(Function.call as any, Object.prototype.propertyIsEnumerable)
const concat = Function.bind.call(Function.call as any, Array.prototype.concat)
const keys = Reflect.ownKeys
if (!Object.values) {
(Object.values as any) = function values (O: any) {
return reduce(keys(O), (v: any, k: any) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), [])
}
}
if (!Object.entries) {
(Object.entries as any) = function entries (O: any) {
return reduce(keys(O), (e: any, k: any) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [[k, O[k]]] : []), [])
}
}
if (!Object.assign) {
(Object.assign as any) = function assign (target: any, _varArgs: any) {
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object')
}
const to = Object(target)
for (let index = 1; index < arguments.length; index++) {
const nextSource = arguments[index]
if (nextSource != null) {
for (const nextKey in nextSource) {
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey]
}
}
}
}
return to
}
}
}
| /*eslint-disable */
import 'core-js/fn/array/includes'
import 'core-js/fn/object/assign'
import 'core-js/fn/object/entries'
import 'core-js/fn/object/values'
import 'core-js/fn/string/starts-with'
| Use core-js for all of the polyfills | Use core-js for all of the polyfills
| TypeScript | mit | revolver-app/vuex-orm,revolver-app/vuex-orm | ---
+++
@@ -1,89 +1,7 @@
/*eslint-disable */
-import 'core-js/fn/reflect/own-keys'
-
-if (!String.prototype.startsWith) {
- String.prototype.startsWith = function (search, pos) {
- return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search
- }
-}
-
-if (!Array.prototype.includes) {
- Array.prototype.includes = function (searchElement, ...args) {
- let O = Object(this)
- let len = parseInt(O.length, 10) || 0
-
- if (len === 0) {
- return false
- }
-
- let n = (args as any)[1] || 0
- let k
-
- if (n >= 0) {
- k = n
- } else {
- k = len + n
-
- if (k < 0) {
- k = 0
- }
- }
-
- let currentElement
-
- while (k < len) {
- currentElement = O[k]
-
- if (searchElement === currentElement || (searchElement !== searchElement && currentElement !== currentElement)) {
- return true
- }
-
- k++
- }
-
- return false
- }
-}
-
-if (!Object.values || !Object.entries || !Object.assign) {
- const reduce = Function.bind.call(Function.call as any, Array.prototype.reduce)
- const isEnumerable = Function.bind.call(Function.call as any, Object.prototype.propertyIsEnumerable)
- const concat = Function.bind.call(Function.call as any, Array.prototype.concat)
- const keys = Reflect.ownKeys
-
- if (!Object.values) {
- (Object.values as any) = function values (O: any) {
- return reduce(keys(O), (v: any, k: any) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), [])
- }
- }
-
- if (!Object.entries) {
- (Object.entries as any) = function entries (O: any) {
- return reduce(keys(O), (e: any, k: any) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [[k, O[k]]] : []), [])
- }
- }
-
- if (!Object.assign) {
- (Object.assign as any) = function assign (target: any, _varArgs: any) {
- if (target == null) {
- throw new TypeError('Cannot convert undefined or null to object')
- }
-
- const to = Object(target)
-
- for (let index = 1; index < arguments.length; index++) {
- const nextSource = arguments[index]
-
- if (nextSource != null) {
- for (const nextKey in nextSource) {
- if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
- to[nextKey] = nextSource[nextKey]
- }
- }
- }
- }
- return to
- }
- }
-}
+import 'core-js/fn/array/includes'
+import 'core-js/fn/object/assign'
+import 'core-js/fn/object/entries'
+import 'core-js/fn/object/values'
+import 'core-js/fn/string/starts-with' |
6e5b7f030d13022ee3c0b26943bd9cd9f7a1e98f | packages/jupyterlab-manager/src/semvercache.ts | packages/jupyterlab-manager/src/semvercache.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
maxSatisfying
} from 'semver';
/**
* A cache using semver ranges to retrieve values.
*/
export
class SemVerCache<T> {
set(key: string, version: string, object: T) {
if (!(key in this._cache)) {
this._cache[key] = Object.create(null);
}
if (!(version in this._cache[key])) {
this._cache[key][version] = object;
}
}
get(key: string, semver: string): T {
if (key in this._cache) {
let versions = this._cache[key];
let best = maxSatisfying(Object.keys(versions), semver);
return versions[best];
}
}
private _cache: { [key: string]: {[version: string]: T} } = Object.create(null);
} | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
maxSatisfying
} from 'semver';
/**
* A cache using semver ranges to retrieve values.
*/
export
class SemVerCache<T> {
set(key: string, version: string, object: T) {
if (!(key in this._cache)) {
this._cache[key] = Object.create(null);
}
if (!(version in this._cache[key])) {
this._cache[key][version] = object;
} else {
throw `Version ${version} of key ${key} already registered.`;
}
}
get(key: string, semver: string): T {
if (key in this._cache) {
let versions = this._cache[key];
let best = maxSatisfying(Object.keys(versions), semver);
return versions[best];
}
}
private _cache: { [key: string]: {[version: string]: T} } = Object.create(null);
}
| Throw an error if trying to register a widget version that we’ve already registered. | Throw an error if trying to register a widget version that we’ve already registered. | TypeScript | bsd-3-clause | ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets | ---
+++
@@ -17,6 +17,8 @@
}
if (!(version in this._cache[key])) {
this._cache[key][version] = object;
+ } else {
+ throw `Version ${version} of key ${key} already registered.`;
}
}
|
fd9c7a336f946a8847e9eef89dc4839643b04b15 | src/app/app.ts | src/app/app.ts | require('angular');
require('angular-ui-router');
require('angular-material');
require('angular-material/angular-material.scss');
const appModule = angular.module('materialSample', ['ui.router', 'ngMaterial']);
const serviceModules = <Function>require('./common/services');
const featureModules = <Function>require('./features');
featureModules(appModule);
serviceModules(appModule);
appModule
.config(setupDefaultRoute);
setupDefaultRoute.$inject = ['$urlRouterProvider'];
function setupDefaultRoute ($urlRouterProvider:ng.ui.IUrlRouterProvider) {
$urlRouterProvider.otherwise('/login');
} | import 'angular';
import 'angular-ui-router';
import 'angular-material';
import 'angular-material/angular-material.scss';
const appModule = angular.module('materialSample', ['ui.router', 'ngMaterial']);
const serviceModules = <Function>require('./common/services');
const featureModules = <Function>require('./features');
featureModules(appModule);
serviceModules(appModule);
appModule
.config(setupDefaultRoute);
setupDefaultRoute.$inject = ['$urlRouterProvider'];
function setupDefaultRoute ($urlRouterProvider:ng.ui.IUrlRouterProvider) {
$urlRouterProvider.otherwise('/login');
} | Update to import using ES6 syntax | Update to import using ES6 syntax
| TypeScript | mit | locnguyen/webpack-angular-typescript,locnguyen/webpack-angular-typescript,locnguyen/webpack-angular-typescript | ---
+++
@@ -1,7 +1,7 @@
-require('angular');
-require('angular-ui-router');
-require('angular-material');
-require('angular-material/angular-material.scss');
+import 'angular';
+import 'angular-ui-router';
+import 'angular-material';
+import 'angular-material/angular-material.scss';
const appModule = angular.module('materialSample', ['ui.router', 'ngMaterial']);
const serviceModules = <Function>require('./common/services'); |
7bf11a1b561fd19de14639bbcd657c4bd7bca5af | src/aws-token-helper/aws-token-helper.ts | src/aws-token-helper/aws-token-helper.ts | // tslint:disable-next-line:no-require-imports
import open = require("open");
const generateQuery = (params: { [key: string]: string }) =>
Object.keys(params)
.map((key: string) => key + "=" + params[key])
.join("&");
function prompt(question: string): Promise<string> {
return new Promise((resolve, reject) => {
const stdin = process.stdin;
const stdout = process.stdout;
stdin.resume();
stdout.write(question + " ");
stdin.once("data", data => {
resolve(data.toString().trim());
});
});
}
prompt("Client ID?").then(clientId => {
prompt("Product Id?").then(productId => {
prompt("Redirect URI (allowed return URL)?").then(redirectURI => {
const deviceSerialNumber = 123; // can be anything
const scopeData = {
"alexa:all": {
productID: productId,
productInstanceAttributes: {
deviceSerialNumber: deviceSerialNumber,
},
},
};
const getParams = generateQuery({
client_id: clientId,
scope: "alexa:all",
scope_data: JSON.stringify(scopeData),
response_type: "code",
redirect_uri: redirectURI,
});
const authUrl = `https://www.amazon.com/ap/oa?${getParams}`;
open(authUrl);
process.exit();
});
});
});
| // tslint:disable-next-line:no-require-imports
import open = require("open");
const generateQuery = (params: { [key: string]: string }) =>
Object.keys(params)
.map((key: string) => key + "=" + params[key])
.join("&");
function prompt(question: string): Promise<string> {
return new Promise((resolve, reject) => {
const stdin = process.stdin;
const stdout = process.stdout;
stdin.resume();
stdout.write(question + " ");
stdin.once("data", data => {
resolve(data.toString().trim());
});
});
}
prompt("Client ID?").then(clientId => {
prompt("Product Id?").then(productId => {
prompt("Redirect URI (allowed return URL)?").then(redirectURI => {
const scopeData = {
"alexa:all": {
productID: productId,
productInstanceAttributes: {
deviceSerialNumber: 123, // can be anything
},
},
};
const getParams = generateQuery({
client_id: clientId,
scope: "alexa:all",
scope_data: JSON.stringify(scopeData),
response_type: "code",
redirect_uri: redirectURI,
});
const authUrl = `https://www.amazon.com/ap/oa?${getParams}`;
open(authUrl);
process.exit();
});
});
});
| Remove variable which is not needed | Remove variable which is not needed
| TypeScript | mit | dolanmiu/MMM-awesome-alexa,dolanmiu/MMM-awesome-alexa | ---
+++
@@ -23,12 +23,11 @@
prompt("Client ID?").then(clientId => {
prompt("Product Id?").then(productId => {
prompt("Redirect URI (allowed return URL)?").then(redirectURI => {
- const deviceSerialNumber = 123; // can be anything
const scopeData = {
"alexa:all": {
productID: productId,
productInstanceAttributes: {
- deviceSerialNumber: deviceSerialNumber,
+ deviceSerialNumber: 123, // can be anything
},
},
}; |
c8ac045842e414d7b48fa02961f1da7b4b5da7df | src/Components/select-item.component.ts | src/Components/select-item.component.ts | import { Component, Input, Output, EventEmitter } from '@angular/core';
import { SelectableItem } from '../selectable-item';
import { SelectService } from '../Services/select.service';
@Component({
selector: 'cra-select-item',
template: `
<div class="ui-select-choices-row"
[class.active]="item.selected"
(click)="select($event)">
<a href="javascript:void(0)" class="dropdown-item">
<div>{{item.text}}</div>
</a>
<ul *ngIf="haveChildren"
class="ui-select-choices"
role="menu">
<li *ngFor="let o of item.children" role="menuitem">
<cra-select-item [item]="o" (selected)="itemSelected()"></cra-select-item>
</li>
</ul>
</div>
`
})
export class TreeSelectItemComponent {
@Input()
public item: SelectableItem;
public constructor(
private svc: SelectService
) {}
public get haveChildren(): boolean {
return this.item && this.item.children && this.item.children.length > 0;
}
public select($event: any): void {
this.svc.toggleItemSelection(this.item);
}
}
| import { Component, Input, Output, EventEmitter } from '@angular/core';
import { SelectableItem } from '../selectable-item';
import { SelectService } from '../Services/select.service';
@Component({
selector: 'cra-select-item',
template: `
<div class="ui-select-choices-row"
[class.active]="item.selected"
(click)="select($event)">
<a href="javascript:void(0)" class="dropdown-item">
<div><input type="checkbox" *ngIf="needCheckBox" [checked]="item.selected" /> {{item.text}}</div>
</a>
<ul *ngIf="haveChildren"
class="ui-select-choices"
role="menu">
<li *ngFor="let o of item.children" role="menuitem">
<cra-select-item [item]="o" (selected)="itemSelected()"></cra-select-item>
</li>
</ul>
</div>
`
})
export class TreeSelectItemComponent {
@Input()
public item: SelectableItem;
public constructor(
private svc: SelectService
) {}
get needCheckBox(): boolean {
return this.svc.Configuration.isHierarchy() && this.svc.Configuration.allowMultiple;
}
public get haveChildren(): boolean {
return this.item && this.item.children && this.item.children.length > 0;
}
public select($event: any): void {
if (this.svc.Configuration.allowMultiple || !this.haveChildren) {
this.svc.toggleItemSelection(this.item);
}
}
}
| Add checkbox on tree with allow multiple | Add checkbox on tree with allow multiple
| TypeScript | mit | Crazyht/ngx-tree-select,Crazyht/crazy-select,Crazyht/ngx-tree-select,Crazyht/ngx-tree-select,Crazyht/crazy-select,Crazyht/crazy-select | ---
+++
@@ -9,7 +9,7 @@
[class.active]="item.selected"
(click)="select($event)">
<a href="javascript:void(0)" class="dropdown-item">
- <div>{{item.text}}</div>
+ <div><input type="checkbox" *ngIf="needCheckBox" [checked]="item.selected" /> {{item.text}}</div>
</a>
<ul *ngIf="haveChildren"
class="ui-select-choices"
@@ -29,11 +29,17 @@
private svc: SelectService
) {}
+ get needCheckBox(): boolean {
+ return this.svc.Configuration.isHierarchy() && this.svc.Configuration.allowMultiple;
+ }
+
public get haveChildren(): boolean {
return this.item && this.item.children && this.item.children.length > 0;
}
public select($event: any): void {
- this.svc.toggleItemSelection(this.item);
+ if (this.svc.Configuration.allowMultiple || !this.haveChildren) {
+ this.svc.toggleItemSelection(this.item);
+ }
}
} |
8bb822ebc414aeba7d975b5bba538c2d496796dd | functions/src/main.ts | functions/src/main.ts | import { https, config } from 'firebase-functions'
import { initializeApp } from 'firebase-admin'
import { migrateToFirestore } from './migrateToFirestore'
import { generateSchedule } from './schedule-view/generate-schedule'
import { fetchTwitter } from './twitter/fetch-twitter';
import fetch from "node-fetch";
const firebaseConf = config().firebase
const firebaseApp = initializeApp(firebaseConf)
export = {
migrateToFirestore: https.onRequest(migrateToFirestore(firebaseApp)),
generateSchedule: https.onRequest(generateSchedule(firebaseApp)),
fetchTwitter: https.onRequest(fetchTwitter(firebaseApp, fetch, config().twitter))
}
| import { https, config } from 'firebase-functions'
import { initializeApp } from 'firebase-admin'
import { migrateToFirestore } from './migrateToFirestore'
import { generateSchedule } from './schedule-view/generate-schedule'
import { fetchTwitter } from './twitter/fetch-twitter';
import fetch from "node-fetch";
import { generateSpeakers } from './speakers-view/generate-speakers';
const firebaseConf = config().firebase
const firebaseApp = initializeApp(firebaseConf)
export = {
migrateToFirestore: https.onRequest(migrateToFirestore(firebaseApp)),
generateSchedule: https.onRequest(generateSchedule(firebaseApp)),
generateSpeakers: https.onRequest(generateSpeakers(firebaseApp)),
fetchTwitter: https.onRequest(fetchTwitter(firebaseApp, fetch, config().twitter)),
}
| Add speakers generator to functions | Add speakers generator to functions
| TypeScript | apache-2.0 | squanchy-dev/squanchy-firebase,squanchy-dev/squanchy-firebase | ---
+++
@@ -4,6 +4,7 @@
import { generateSchedule } from './schedule-view/generate-schedule'
import { fetchTwitter } from './twitter/fetch-twitter';
import fetch from "node-fetch";
+import { generateSpeakers } from './speakers-view/generate-speakers';
const firebaseConf = config().firebase
const firebaseApp = initializeApp(firebaseConf)
@@ -11,5 +12,6 @@
export = {
migrateToFirestore: https.onRequest(migrateToFirestore(firebaseApp)),
generateSchedule: https.onRequest(generateSchedule(firebaseApp)),
- fetchTwitter: https.onRequest(fetchTwitter(firebaseApp, fetch, config().twitter))
+ generateSpeakers: https.onRequest(generateSpeakers(firebaseApp)),
+ fetchTwitter: https.onRequest(fetchTwitter(firebaseApp, fetch, config().twitter)),
} |
e75841d5872eb5d1d53bd10f32caed2a09ba7fde | src/pokeLCG.ts | src/pokeLCG.ts | /// <reference path="../node_modules/typescript/lib/lib.es6.d.ts" />
'use strict';
export const GEN3_ARG: LCGArg = Object.freeze({multiplier: 0x41C64E6D, increment: 0x6073});
export const GEN4_ARG: LCGArg = Object.freeze({multiplier: 0x41C64E6D, increment: 0x6073});
export const GEN4_ALTERNATIVE_ARG: LCGArg = Object.freeze({multiplier: 0x41C64E6D, increment: 0x6073});
export function* generator(lcgArg: LCGArg, initialSeed: number, maxFrame?: number): Iterable<number> {
yield 0;
}
export interface LCGArg {
multiplier: number;
increment: number;
} | /// <reference path="../node_modules/typescript/lib/lib.es6.d.ts" />
'use strict';
export const GEN3_ARG: LCGArg = Object.freeze({multiplier: 0x41C64E6D, increment: 0x6073});
export const GEN4_ARG: LCGArg = Object.freeze({multiplier: 0x41C64E6D, increment: 0x6073});
export const GEN4_ALTERNATIVE_ARG: LCGArg = Object.freeze({multiplier: 0x41C64E6D, increment: 0x6073});
export function* generator(lcgArg: LCGArg, initialSeed: number, maxFrame?: number): IterableIterator<number> {
yield 0;
}
export interface LCGArg {
multiplier: number;
increment: number;
} | Fix the type of generator | Fix the type of generator
| TypeScript | mit | mizdra/poke-lcg,mizdra/poke-lcg | ---
+++
@@ -6,7 +6,7 @@
export const GEN4_ARG: LCGArg = Object.freeze({multiplier: 0x41C64E6D, increment: 0x6073});
export const GEN4_ALTERNATIVE_ARG: LCGArg = Object.freeze({multiplier: 0x41C64E6D, increment: 0x6073});
-export function* generator(lcgArg: LCGArg, initialSeed: number, maxFrame?: number): Iterable<number> {
+export function* generator(lcgArg: LCGArg, initialSeed: number, maxFrame?: number): IterableIterator<number> {
yield 0;
}
|
a31457505ed790ee4e32763eb15552f860898dea | src/app/journal/journalEntries.service.spec.ts | src/app/journal/journalEntries.service.spec.ts | import { JournalEntriesService } from './journalEntries.service';
describe('JournalEntriesService', () => {
let service: JournalEntriesService;
let firebaseService: any;
beforeEach(() => {
service = new JournalEntriesService(firebaseService);
});
it('should create JournalEntriesService', () => {
expect(service).toBeTruthy();
});
});
| import { JournalEntriesService } from './journalEntries.service';
import {JournalEntry, JournalEntryFirebase} from './journalEntry';
import {Observable} from 'rxjs';
class FirebaseServiceStub {
getList(url) {
let journalEntries = [];
journalEntries.push(new JournalEntry());
journalEntries.push(new JournalEntry());
return Observable.of(journalEntries);
}
addItem(url, journalEntry) { }
deleteItem(url, id) { }
updateItem(url, id, journalEntry) { }
}
describe('JournalEntriesService', () => {
let service: JournalEntriesService;
let firebaseService: any = new FirebaseServiceStub();
let journalEntry = new JournalEntry();
journalEntry.$key = 'j1';
journalEntry.date = new Date('2017-03-15');
journalEntry.editable = false;
journalEntry.foodID = 1;
journalEntry.quantity = 100;
journalEntry.unit = 'mg';
journalEntry.userId = 'user1';
let firebaseJournalEntry = new JournalEntryFirebase();
firebaseJournalEntry.date = journalEntry.date.toString();
firebaseJournalEntry.editable = journalEntry.editable;
firebaseJournalEntry.foodID = journalEntry.foodID;
firebaseJournalEntry.name = journalEntry.name;
firebaseJournalEntry.quantity = journalEntry.quantity;
firebaseJournalEntry.unit = journalEntry.unit;
firebaseJournalEntry.userId = journalEntry.userId;
let url = 'journalEntries/user1/2017315';
beforeEach(() => {
service = new JournalEntriesService(firebaseService);
});
it('should create JournalEntriesService', () => {
expect(service).toBeTruthy();
});
it('should get journal entries', () => {
let userId = 'user1';
let date = new Date('2017-03-15');
spyOn(firebaseService, 'getList');
service.getJournalEntries(date, userId);
expect(firebaseService.getList).toHaveBeenCalledWith(url);
});
it('should add journal entry', () => {
spyOn(firebaseService, 'addItem');
service.addEntry(journalEntry);
expect(firebaseService.addItem).toHaveBeenCalledWith(url, firebaseJournalEntry);
});
it('should delete journal entry', () => {
spyOn(firebaseService, 'deleteItem');
service.deleteEntry(journalEntry);
expect(firebaseService.deleteItem).toHaveBeenCalledWith(url, journalEntry.$key);
});
it('should update journal entry', () => {
spyOn(firebaseService, 'updateItem');
service.updateEntry(journalEntry);
expect(firebaseService.updateItem).toHaveBeenCalledWith(url, journalEntry.$key, firebaseJournalEntry);
});
});
| Write tests for the journal entry service | Write tests for the journal entry service
| TypeScript | mit | stefanamport/nuba,stefanamport/nuba,stefanamport/nuba | ---
+++
@@ -1,8 +1,46 @@
import { JournalEntriesService } from './journalEntries.service';
+import {JournalEntry, JournalEntryFirebase} from './journalEntry';
+import {Observable} from 'rxjs';
+
+class FirebaseServiceStub {
+ getList(url) {
+ let journalEntries = [];
+ journalEntries.push(new JournalEntry());
+ journalEntries.push(new JournalEntry());
+
+ return Observable.of(journalEntries);
+ }
+
+ addItem(url, journalEntry) { }
+
+ deleteItem(url, id) { }
+
+ updateItem(url, id, journalEntry) { }
+}
describe('JournalEntriesService', () => {
let service: JournalEntriesService;
- let firebaseService: any;
+ let firebaseService: any = new FirebaseServiceStub();
+
+ let journalEntry = new JournalEntry();
+ journalEntry.$key = 'j1';
+ journalEntry.date = new Date('2017-03-15');
+ journalEntry.editable = false;
+ journalEntry.foodID = 1;
+ journalEntry.quantity = 100;
+ journalEntry.unit = 'mg';
+ journalEntry.userId = 'user1';
+
+ let firebaseJournalEntry = new JournalEntryFirebase();
+ firebaseJournalEntry.date = journalEntry.date.toString();
+ firebaseJournalEntry.editable = journalEntry.editable;
+ firebaseJournalEntry.foodID = journalEntry.foodID;
+ firebaseJournalEntry.name = journalEntry.name;
+ firebaseJournalEntry.quantity = journalEntry.quantity;
+ firebaseJournalEntry.unit = journalEntry.unit;
+ firebaseJournalEntry.userId = journalEntry.userId;
+
+ let url = 'journalEntries/user1/2017315';
beforeEach(() => {
service = new JournalEntriesService(firebaseService);
@@ -11,4 +49,38 @@
it('should create JournalEntriesService', () => {
expect(service).toBeTruthy();
});
+
+ it('should get journal entries', () => {
+ let userId = 'user1';
+ let date = new Date('2017-03-15');
+ spyOn(firebaseService, 'getList');
+
+ service.getJournalEntries(date, userId);
+
+ expect(firebaseService.getList).toHaveBeenCalledWith(url);
+ });
+
+ it('should add journal entry', () => {
+ spyOn(firebaseService, 'addItem');
+
+ service.addEntry(journalEntry);
+
+ expect(firebaseService.addItem).toHaveBeenCalledWith(url, firebaseJournalEntry);
+ });
+
+ it('should delete journal entry', () => {
+ spyOn(firebaseService, 'deleteItem');
+
+ service.deleteEntry(journalEntry);
+
+ expect(firebaseService.deleteItem).toHaveBeenCalledWith(url, journalEntry.$key);
+ });
+
+ it('should update journal entry', () => {
+ spyOn(firebaseService, 'updateItem');
+
+ service.updateEntry(journalEntry);
+
+ expect(firebaseService.updateItem).toHaveBeenCalledWith(url, journalEntry.$key, firebaseJournalEntry);
+ });
}); |
48f00daf9105f6e513f269a13662db521ec4c969 | src/observers/BaseStatusBarItemObserver.ts | src/observers/BaseStatusBarItemObserver.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { StatusBarItem } from '../vscodeAdapter';
import { BaseEvent } from '../omnisharp/loggingEvents';
export abstract class BaseStatusBarItemObserver {
constructor(private statusBarItem: StatusBarItem) {
}
public SetAndShowStatusBar(text: string, command: string, color?: string, tooltip?: string) {
this.statusBarItem.text = text;
this.statusBarItem.command = command;
this.statusBarItem.color = color;
this.statusBarItem.tooltip = tooltip;
this.statusBarItem.show();
}
public ResetAndHideStatusBar() {
this.statusBarItem.text = undefined;
this.statusBarItem.command = undefined;
this.statusBarItem.color = undefined;
this.statusBarItem.tooltip = undefined;
this.statusBarItem.hide();
}
abstract post: (event: BaseEvent) => void;
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { StatusBarItem } from '../vscodeAdapter';
import { BaseEvent } from '../omnisharp/loggingEvents';
export abstract class BaseStatusBarItemObserver {
constructor(private statusBarItem: StatusBarItem) {
}
public SetAndShowStatusBar(text: string, command: string, color?: string, tooltip?: string) {
this.statusBarItem.text = text;
this.statusBarItem.command = command;
this.statusBarItem.color = color;
this.statusBarItem.tooltip = tooltip;
this.statusBarItem.show();
}
public ResetAndHideStatusBar() {
this.statusBarItem.text = '';
this.statusBarItem.command = undefined;
this.statusBarItem.color = undefined;
this.statusBarItem.tooltip = undefined;
this.statusBarItem.hide();
}
abstract post: (event: BaseEvent) => void;
}
| Set text to an empty string | Set text to an empty string
| TypeScript | mit | OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode | ---
+++
@@ -20,7 +20,7 @@
}
public ResetAndHideStatusBar() {
- this.statusBarItem.text = undefined;
+ this.statusBarItem.text = '';
this.statusBarItem.command = undefined;
this.statusBarItem.color = undefined;
this.statusBarItem.tooltip = undefined; |
915886c1c393ce3e0187d1471e81cccf96fc3e18 | ts/src/model/response/TransactionStatus.ts | ts/src/model/response/TransactionStatus.ts | import {CardResponse} from './CardResponse';
import {Status} from './Status';
import {Acquirer} from './Acquirer';
import {Revert} from './Revert';
import {Customer} from './Customer';
import {Splitting} from '../Splitting';
export interface TransactionStatus {
id: string;
acquirer: Acquirer;
type: string;
amount: number;
current_amount: number;
currency: string;
timestamp: string;
modified: string;
filing_code: string;
authorization_code?: string;
token?: string;
status: Status;
card: CardResponse;
reverts?: Revert[];
customer?: Customer;
cardholder_authentication: string;
order?: string;
committed: boolean;
committed_amount?: string;
recurring: boolean;
splitting: Splitting;
reference_number?: string;
}
| import {CardResponse} from './CardResponse';
import {Status} from './Status';
import {Acquirer} from './Acquirer';
import {Revert} from './Revert';
import {Customer} from './Customer';
import {Splitting} from '../Splitting';
export interface TransactionStatus {
id: string;
acquirer: Acquirer;
type: string;
amount: number;
current_amount: number;
currency: string;
timestamp: string;
modified: string;
filing_code: string;
authorization_code?: string;
token?: string;
status: Status;
card: CardResponse;
reverts?: Revert[];
customer?: Customer;
cardholder_authentication: string;
order?: string;
committed: boolean;
committed_amount?: string;
recurring: boolean;
splitting?: Splitting;
reference_number?: string;
}
| Mark splitting as optional in transaction status | Mark splitting as optional in transaction status
| TypeScript | mit | solinor/paymenthighway-javascript-lib | ---
+++
@@ -26,6 +26,6 @@
committed: boolean;
committed_amount?: string;
recurring: boolean;
- splitting: Splitting;
+ splitting?: Splitting;
reference_number?: string;
} |
58e3fcf39298089b70333a664fdbd73f8cebd21a | src/app/views/sessions/sessions.controller.ts | src/app/views/sessions/sessions.controller.ts | /// <reference path="../../references/references.d.ts" />
module flexportal {
'use strict';
class Session extends FlexSearch.DuplicateDetection.Session {
JobStartTimeString: string
JobEndTimeString: string
}
interface ISessionsProperties extends ng.IScope {
Sessions: Session[]
Limit: number
Page: number
Total: number
goToSession(sessionId: string): void
}
export class SessionsController {
/* @ngInject */
constructor($scope: ISessionsProperties, $state: any, $http: ng.IHttpService) {
$http.get(DuplicatesUrl + "/search?c=*&q=type+=+'session'").then((response: any) => {
$scope.goToSession = function(sessionId) {
$state.go('session', {id: sessionId});
};
var toDateStr = function(dateStr: any) {
var date = new Date(dateStr);
return date.toLocaleDateString() + ", " + date.toLocaleTimeString();
}
var results = <FlexSearch.Core.SearchResults>response.data.Data;
$scope.Sessions = results.Documents
.map(d => <Session>JSON.parse(d.Fields["sessionproperties"]))
.map(s => {
s.JobStartTimeString = toDateStr(s.JobStartTime);
s.JobEndTimeString = toDateStr(s.JobEndTime);
return s;
});
$scope.Limit = 10;
$scope.Page = 1;
$scope.Total = results.TotalAvailable;
});
}
}
}
| /// <reference path="../../references/references.d.ts" />
module flexportal {
'use strict';
class Session extends FlexSearch.DuplicateDetection.Session {
JobStartTimeString: string
JobEndTimeString: string
}
interface ISessionsProperties extends ng.IScope {
Sessions: Session[]
Limit: number
Page: number
Total: number
goToSession(sessionId: string): void
}
export class SessionsController {
/* @ngInject */
constructor($scope: ISessionsProperties, $state: any, $http: ng.IHttpService) {
$http.get(DuplicatesUrl + "/search?c=*&q=type+=+'session'").then((response: any) => {
$scope.goToSession = function(sessionId) {
$state.go('session', {sessionId: sessionId});
};
var toDateStr = function(dateStr: any) {
var date = new Date(dateStr);
return date.toLocaleDateString() + ", " + date.toLocaleTimeString();
}
var results = <FlexSearch.Core.SearchResults>response.data.Data;
$scope.Sessions = results.Documents
.map(d => <Session>JSON.parse(d.Fields["sessionproperties"]))
.map(s => {
s.JobStartTimeString = toDateStr(s.JobStartTime);
s.JobEndTimeString = toDateStr(s.JobEndTime);
return s;
});
$scope.Limit = 10;
$scope.Page = 1;
$scope.Total = results.TotalAvailable;
});
}
}
}
| Fix link between Sessions and Session page | feat(portal): Fix link between Sessions and Session page
| TypeScript | apache-2.0 | FlexSearch/FlexSearch,FlexSearch/FlexSearch,FlexSearch/FlexSearch,FlexSearch/FlexSearch | ---
+++
@@ -21,7 +21,7 @@
constructor($scope: ISessionsProperties, $state: any, $http: ng.IHttpService) {
$http.get(DuplicatesUrl + "/search?c=*&q=type+=+'session'").then((response: any) => {
$scope.goToSession = function(sessionId) {
- $state.go('session', {id: sessionId});
+ $state.go('session', {sessionId: sessionId});
};
var toDateStr = function(dateStr: any) { |
3522ec72314e02d973cd358b8ab5a7ebaccd03e5 | angular/src/tests/attribute-tests.ts | angular/src/tests/attribute-tests.ts | import {Order} from "../app/lod/Order";
import { Observable } from 'rxjs/Observable';
import {Product} from "../app/lod/Product";
describe('Attributes', function() {
it( "should be flagged as created", function() {
let newOrder = new Order();
let now = new Date();
newOrder.Order.create( { OrderDate: now });
expect( newOrder.Order$.OrderDate.getTime()).toBe( now.getTime() );
expect( newOrder.Order$.updated).toBeTruthy();
newOrder.Order$.ShipName = "John Smith";
newOrder.Order$.OrderDetail.create( { Quantity: 10 }, { position: Position.Last } );
});
});
| import {Order} from "../app/lod/Order";
import { Observable } from 'rxjs/Observable';
import {Product} from "../app/lod/Product";
describe('Attributes', function() {
it( "should be flagged as created", function() {
let newOrder = new Order();
let now = new Date();
newOrder.Order.create( { OrderDate: now });
expect( newOrder.Order$.OrderDate.getTime()).toBe( now.getTime() );
expect( newOrder.Order$.updated).toBeTruthy();
newOrder.Order$.ShipName = "John Smith";
// newOrder.Order$.OrderDetail.create( { Quantity: 10 }, { position: Position.Last } );
});
});
| Update tests to check for date | Update tests to check for date
| TypeScript | apache-2.0 | DeegC/Zeidon-Northwind,DeegC/Zeidon-Northwind,DeegC/Zeidon-Northwind,DeegC/Zeidon-Northwind,DeegC/Zeidon-Northwind,DeegC/Zeidon-Northwind | ---
+++
@@ -10,6 +10,6 @@
expect( newOrder.Order$.OrderDate.getTime()).toBe( now.getTime() );
expect( newOrder.Order$.updated).toBeTruthy();
newOrder.Order$.ShipName = "John Smith";
- newOrder.Order$.OrderDetail.create( { Quantity: 10 }, { position: Position.Last } );
+ // newOrder.Order$.OrderDetail.create( { Quantity: 10 }, { position: Position.Last } );
});
}); |
8ee4ac5239519218a1c1f47bca8fe91474c894d6 | app/test/globals.ts | app/test/globals.ts | /// <reference path="../../node_modules/@types/node/index.d.ts" />
import 'mocha'
import 'chai-datetime'
// These constants are defined by Webpack at build time, but since tests aren't
// built with Webpack we need to make sure these exist at runtime.
const g: any = global
g['__WIN32__'] = process.platform === 'win32'
g['__DARWIN__'] = process.platform === 'darwin'
g['__RELEASE_ENV__'] = 'development'
| // This shouldn't be necessary, but without this CI fails on Windows. Seems to
// be a bug in TS itself or ts-node.
/// <reference path="../../node_modules/@types/node/index.d.ts" />
import 'mocha'
import 'chai-datetime'
// These constants are defined by Webpack at build time, but since tests aren't
// built with Webpack we need to make sure these exist at runtime.
const g: any = global
g['__WIN32__'] = process.platform === 'win32'
g['__DARWIN__'] = process.platform === 'darwin'
g['__RELEASE_ENV__'] = 'development'
| Document why we're doing this | Document why we're doing this
| TypeScript | mit | shiftkey/desktop,desktop/desktop,artivilla/desktop,gengjiawen/desktop,hjobrien/desktop,kactus-io/kactus,say25/desktop,shiftkey/desktop,hjobrien/desktop,desktop/desktop,gengjiawen/desktop,say25/desktop,artivilla/desktop,artivilla/desktop,hjobrien/desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,BugTesterTest/desktops,say25/desktop,say25/desktop,gengjiawen/desktop,hjobrien/desktop,BugTesterTest/desktops,j-f1/forked-desktop,shiftkey/desktop,gengjiawen/desktop,BugTesterTest/desktops,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,BugTesterTest/desktops,kactus-io/kactus,desktop/desktop | ---
+++
@@ -1,3 +1,5 @@
+// This shouldn't be necessary, but without this CI fails on Windows. Seems to
+// be a bug in TS itself or ts-node.
/// <reference path="../../node_modules/@types/node/index.d.ts" />
import 'mocha' |
4e73d864bb2472e5c19fe8afb63c90b1ec8d6b73 | src/client/app/statisch/werkliste-unselbst.component.ts | src/client/app/statisch/werkliste-unselbst.component.ts | /**
* Created by Roberta Padlina ([email protected]) on 27/10/17.
*/
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'rae-werkliste-unselbst',
templateUrl: 'werkliste-unselbst.component.html'
})
export class WerklisteUnselbstComponent {
title = 'Unselbständige Publikationen';
}
| /**
* Created by Roberta Padlina ([email protected]) on 27/10/17.
*/
import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { globalSearchVariableService } from '../suche/globalSearchVariablesService';
@Component({
moduleId: module.id,
selector: 'rae-werkliste-unselbst',
templateUrl: 'werkliste-unselbst.component.html'
})
export class WerklisteUnselbstComponent {
title = 'Unselbständige Publikationen';
poemIRI: string;
poemLink: string;
constructor(private http: Http) {
}
fromPoemTitleToPoemIRI(poemTitle: string) {
return this.http.get
(
globalSearchVariableService.API_URL +
globalSearchVariableService.extendedSearch +
'http%3A%2F%2Fwww.knora.org%2Fontology%2Fkuno-raeber-gui%23Poem' +
'&property_id=http%3A%2F%2Fwww.knora.org%2Fontology%2Fkuno-raeber-gui%23hasConvoluteTitle' +
'&compop=EQ' +
'&searchval=Verstreutes' +
'&property_id=http%3A%2F%2Fwww.knora.org%2Fontology%2Fkuno-raeber-gui%23hasPoemTitle' +
'&compop=EQ' +
'&searchval=' +
poemTitle +
'&property_id=http%3A%2F%2Fwww.knora.org%2Fontology%2Fkuno-raeber-gui%23hasPoemIRI' +
'&compop=EXISTS' +
'&searchval='
)
.map(
(lambda: Response) => {
const data = lambda.json();
this.poemIRI = data.subjects.value[2];
}
)
.subscribe(res => this.poemLink = '/Verstreutes/' + poemTitle + '---' + this.poemIRI);
}
}
| Work on a function to get the poem IRI from the poem title (first step). | Work on a function to get the poem IRI from the poem title (first step).
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -3,12 +3,48 @@
*/
import { Component } from '@angular/core';
+import { Http, Response } from '@angular/http';
+import { globalSearchVariableService } from '../suche/globalSearchVariablesService';
@Component({
moduleId: module.id,
selector: 'rae-werkliste-unselbst',
templateUrl: 'werkliste-unselbst.component.html'
})
+
export class WerklisteUnselbstComponent {
title = 'Unselbständige Publikationen';
+ poemIRI: string;
+ poemLink: string;
+
+ constructor(private http: Http) {
+ }
+
+ fromPoemTitleToPoemIRI(poemTitle: string) {
+
+ return this.http.get
+ (
+ globalSearchVariableService.API_URL +
+ globalSearchVariableService.extendedSearch +
+ 'http%3A%2F%2Fwww.knora.org%2Fontology%2Fkuno-raeber-gui%23Poem' +
+ '&property_id=http%3A%2F%2Fwww.knora.org%2Fontology%2Fkuno-raeber-gui%23hasConvoluteTitle' +
+ '&compop=EQ' +
+ '&searchval=Verstreutes' +
+ '&property_id=http%3A%2F%2Fwww.knora.org%2Fontology%2Fkuno-raeber-gui%23hasPoemTitle' +
+ '&compop=EQ' +
+ '&searchval=' +
+ poemTitle +
+ '&property_id=http%3A%2F%2Fwww.knora.org%2Fontology%2Fkuno-raeber-gui%23hasPoemIRI' +
+ '&compop=EXISTS' +
+ '&searchval='
+ )
+ .map(
+ (lambda: Response) => {
+ const data = lambda.json();
+ this.poemIRI = data.subjects.value[2];
+ }
+ )
+ .subscribe(res => this.poemLink = '/Verstreutes/' + poemTitle + '---' + this.poemIRI);
+ }
+
} |
e437967f6b28b9142fb578a2f6963483e3bb2a50 | spec/templates/template.spec.ts | spec/templates/template.spec.ts | /// <reference path="../../typings/jasmine/jasmine.d.ts" />
import { Template } from '../../src/templates/template';
describe('Template', () => {
describe('getOpeningEscape', () => {
it('should return "{{"', () => {
let tmp = new Template('');
expect(tmp.getOpeningEscape()).toBe("{{");
});
});
describe('getClosingEscape', () => {
it('should return "}}"', () => {
let tmp = new Template('');
expect(tmp.getClosingEscape()).toBe("}}");
});
});
describe('getContents', () => {
let testCases = ['', 'asjdaidja', 'the quick brown dog jumps over the lazy white parrot'];
function should_return(index, output) {
it('should return "' + output + '" [test case ' + index + ']', () => {
let tmp = new Template(output);
expect(tmp.getContents()).toBe(output);
});
}
for (let t in testCases) {
should_return(t, testCases[t]);
}
});
})
| /// <reference path="../../typings/jasmine/jasmine.d.ts" />
import { Template } from '../../src/templates/template';
describe('Template', () => {
describe('getOpeningEscape', () => {
it('should return "{{"', () => {
let tmp = new Template('');
expect(tmp.getOpeningEscape()).toBe("{{");
});
});
describe('getClosingEscape', () => {
it('should return "}}"', () => {
let tmp = new Template('');
expect(tmp.getClosingEscape()).toBe("}}");
});
});
describe('getContents (no bindings)', () => {
let testCases = ['', 'asjdaidja', 'the quick brown dog jumps over the lazy white parrot'];
function should_return(index, output) {
it('should return "' + output + '" [test case ' + index + ']', () => {
let tmp = new Template(output);
expect(tmp.getContents()).toBe(output);
});
}
for (let t in testCases) {
should_return(t, testCases[t]);
}
});
describe('getContents (with bindings)', () => {
let testCases = ['{{dependencies}}', 'hello, my name is {{name}}', '## {{dependencyName}}'];
function should_return(index, output) {
it('should return "' + output + '" [test case ' + index + ']', () => {
let tmp = new Template(output);
expect(tmp.getContents()).toBe(output);
});
}
for (let t in testCases) {
should_return(t, testCases[t]);
}
});
})
| Test that getContents doesn't bind values | Test that getContents doesn't bind values
| TypeScript | unlicense | dependument/dependument,dependument/dependument,Jameskmonger/dependument,Jameskmonger/dependument | ---
+++
@@ -19,7 +19,7 @@
});
});
- describe('getContents', () => {
+ describe('getContents (no bindings)', () => {
let testCases = ['', 'asjdaidja', 'the quick brown dog jumps over the lazy white parrot'];
function should_return(index, output) {
@@ -34,4 +34,20 @@
should_return(t, testCases[t]);
}
});
+
+ describe('getContents (with bindings)', () => {
+ let testCases = ['{{dependencies}}', 'hello, my name is {{name}}', '## {{dependencyName}}'];
+
+ function should_return(index, output) {
+ it('should return "' + output + '" [test case ' + index + ']', () => {
+ let tmp = new Template(output);
+
+ expect(tmp.getContents()).toBe(output);
+ });
+ }
+
+ for (let t in testCases) {
+ should_return(t, testCases[t]);
+ }
+ });
}) |
816a48e17dda23af8cafd2b79453f7812ac5969e | src/main/SideNavigator.tsx | src/main/SideNavigator.tsx | import * as React from 'react'
import { inject } from 'mobx-react'
import DataStore from './stores/DataStore'
type SideNavigatorProps = {
data?: DataStore
}
@inject('data')
export default class SideNavigator extends React.Component<SideNavigatorProps> {
render () {
const storageEntries = [...this.props.data.storageMap.entries()]
return <div>SideNav
<ul>
{storageEntries.map(([name]) => (
<li>{name}</li>
))}
</ul>
{storageEntries.length === 0 &&
<p>No storages</p>
}
</div>
}
}
| import * as React from 'react'
import { inject, observer } from 'mobx-react'
import DataStore from './stores/DataStore'
type SideNavigatorProps = {
data?: DataStore
}
@inject('data')
@observer
export default class SideNavigator extends React.Component<SideNavigatorProps> {
render () {
const storageEntries = [...this.props.data.storageMap.entries()]
return <nav>SideNav
<ul>
{storageEntries.map(([name]) => (
<li key={name}>{name}</li>
))}
</ul>
{storageEntries.length === 0 &&
<p>No storages</p>
}
</nav>
}
}
| Set key to list item | Set key to list item
| TypeScript | mit | Sarah-Seo/Inpad,Sarah-Seo/Inpad | ---
+++
@@ -1,5 +1,5 @@
import * as React from 'react'
-import { inject } from 'mobx-react'
+import { inject, observer } from 'mobx-react'
import DataStore from './stores/DataStore'
type SideNavigatorProps = {
@@ -7,18 +7,19 @@
}
@inject('data')
+@observer
export default class SideNavigator extends React.Component<SideNavigatorProps> {
render () {
const storageEntries = [...this.props.data.storageMap.entries()]
- return <div>SideNav
+ return <nav>SideNav
<ul>
{storageEntries.map(([name]) => (
- <li>{name}</li>
+ <li key={name}>{name}</li>
))}
</ul>
{storageEntries.length === 0 &&
<p>No storages</p>
}
- </div>
+ </nav>
}
} |
5a6b0ba71060e127b7980e13b95334c253f63ad5 | src/utils/badges.ts | src/utils/badges.ts | import { HitStatus } from '../types';
import { BadgeDescriptor } from '@shopify/polaris/types/components/ResourceList/Item';
import { Status } from '@shopify/polaris/types/components/Badge/Badge';
// import { BadgeProps } from '@shopify/polaris';
const noTOBadge: BadgeDescriptor = {
content: 'No T.O.',
status: '' as Status
};
export const generateTOpticonBadge = (
averageScore: number | null
): BadgeDescriptor[] => {
if (!averageScore) {
return [noTOBadge];
}
const status = assignScoreColor(averageScore) as Status;
const content = generateContentString(averageScore);
return [
{
status,
content
}
];
};
const generateContentString = (average: number | null) => {
return !average ? 'No T.O.' : `${average.toFixed(2)} T.O.`;
};
const assignScoreColor = (score: number | null): Status | null => {
if (!score) {
return null;
}
if (score < 2) {
return 'warning';
} else if (score < 3) {
return 'attention';
} else if (score < 4) {
return 'info';
} else {
return 'success';
}
};
export const generateHitStatusBadge = (status: HitStatus): BadgeDescriptor => {
switch (status) {
case 'Paid':
return { content: 'Paid', status: 'success' };
case 'Approved':
case 'Pending Payment':
return { content: 'Approved', status: 'success' };
case 'Rejected':
return { content: 'Rejected', status: 'warning' };
case 'Submitted':
case 'Pending Approval':
return { content: 'Pending', status: 'info' };
default:
return { content: 'Pending', status: 'info' };
}
};
| import { HitStatus } from '../types';
import { Status } from '@shopify/polaris/types/components/Badge/Badge';
export const assignScoreColor = (score: number): Status => {
if (score < 2) {
return 'warning';
} else if (score < 3) {
return 'attention';
} else if (score < 4) {
return 'info';
} else {
return 'success';
}
};
export const generateHitStatusBadge = (status: HitStatus): Status => {
switch (status) {
case 'Paid':
return 'success';
case 'Approved':
case 'Pending Payment':
return 'success';
case 'Rejected':
return 'warning';
case 'Submitted':
case 'Pending Approval':
return 'info';
default:
return 'info';
}
};
| Update badge utility functions to use Polaris 2.0 Badge API. | Update badge utility functions to use Polaris 2.0 Badge API.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -1,40 +1,7 @@
import { HitStatus } from '../types';
-import { BadgeDescriptor } from '@shopify/polaris/types/components/ResourceList/Item';
import { Status } from '@shopify/polaris/types/components/Badge/Badge';
-// import { BadgeProps } from '@shopify/polaris';
-const noTOBadge: BadgeDescriptor = {
- content: 'No T.O.',
- status: '' as Status
-};
-
-export const generateTOpticonBadge = (
- averageScore: number | null
-): BadgeDescriptor[] => {
- if (!averageScore) {
- return [noTOBadge];
- }
-
- const status = assignScoreColor(averageScore) as Status;
- const content = generateContentString(averageScore);
-
- return [
- {
- status,
- content
- }
- ];
-};
-
-const generateContentString = (average: number | null) => {
- return !average ? 'No T.O.' : `${average.toFixed(2)} T.O.`;
-};
-
-const assignScoreColor = (score: number | null): Status | null => {
- if (!score) {
- return null;
- }
-
+export const assignScoreColor = (score: number): Status => {
if (score < 2) {
return 'warning';
} else if (score < 3) {
@@ -46,19 +13,19 @@
}
};
-export const generateHitStatusBadge = (status: HitStatus): BadgeDescriptor => {
+export const generateHitStatusBadge = (status: HitStatus): Status => {
switch (status) {
case 'Paid':
- return { content: 'Paid', status: 'success' };
+ return 'success';
case 'Approved':
case 'Pending Payment':
- return { content: 'Approved', status: 'success' };
+ return 'success';
case 'Rejected':
- return { content: 'Rejected', status: 'warning' };
+ return 'warning';
case 'Submitted':
case 'Pending Approval':
- return { content: 'Pending', status: 'info' };
+ return 'info';
default:
- return { content: 'Pending', status: 'info' };
+ return 'info';
}
}; |
d5c6a5d36899f03f3c9b52eefde5d0147d274adf | resources/assets/lib/turbolinks-reload.ts | resources/assets/lib/turbolinks-reload.ts | // 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.
export default class TurbolinksReload {
private loaded = new Set<string>();
private loading = new Map<string, JQuery.jqXHR<void>>();
constructor() {
$(document).on('turbolinks:before-cache', this.abortLoading);
}
abortLoading = () => {
for (const xhr of this.loading.values()) {
xhr.abort();
}
};
forget = (src: string) => {
this.loaded.delete(src);
this.loading.get(src)?.abort();
};
load(src: string) {
if (this.loaded.has(src) || this.loading.has(src)) return;
const xhr = $.ajax(src, { cache: true, dataType: 'script' }) as JQuery.jqXHR<void>;
this.loading.set(src, xhr);
void xhr
.done(() => this.loaded.add(src))
.always(() => this.loading.delete(src));
return xhr;
}
}
| // 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.
export default class TurbolinksReload {
private loaded = new Set<string>();
private loading = new Map<string, JQuery.jqXHR<void>>();
constructor() {
$(document).on('turbolinks:before-cache', this.abortLoading);
}
abortLoading = () => {
for (const xhr of this.loading.values()) {
xhr.abort();
}
};
forget = (src: string) => {
this.loaded.delete(src);
this.loading.get(src)?.abort();
};
load(src: string) {
if (this.loaded.has(src) || this.loading.has(src)) {
return this.loading.get(src);
}
const xhr = $.ajax(src, { cache: true, dataType: 'script' }) as JQuery.jqXHR<void>;
this.loading.set(src, xhr);
void xhr
.done(() => this.loaded.add(src))
.always(() => this.loading.delete(src));
return xhr;
}
}
| Return existing xhr if any | Return existing xhr if any
| TypeScript | agpl-3.0 | ppy/osu-web,nanaya/osu-web,nanaya/osu-web,LiquidPL/osu-web,nanaya/osu-web,ppy/osu-web,notbakaneko/osu-web,ppy/osu-web,nanaya/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,ppy/osu-web,nanaya/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,ppy/osu-web,LiquidPL/osu-web,LiquidPL/osu-web | ---
+++
@@ -21,7 +21,9 @@
};
load(src: string) {
- if (this.loaded.has(src) || this.loading.has(src)) return;
+ if (this.loaded.has(src) || this.loading.has(src)) {
+ return this.loading.get(src);
+ }
const xhr = $.ajax(src, { cache: true, dataType: 'script' }) as JQuery.jqXHR<void>;
|
98ae99347a60bbccd2bb61c05c56dbd81517edda | marked/marked-tests.ts | marked/marked-tests.ts | /// <reference path="marked.d.ts" />
import marked = require('marked');
var options: MarkedOptions = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
silent: false,
highlight: function (code: string, lang: string) {
return '';
},
langPrefix: 'lang-',
smartypants: false,
renderer: new marked.Renderer()
};
function callback() {
console.log('callback called');
}
marked.setOptions(options);
console.log(marked('i am using __markdown__.'));
console.log(marked('i am using __markdown__.', options));
console.log(marked('i am using __markdown__.', callback));
console.log(marked('i am using __markdown__.', options, callback));
console.log(marked.parse('i am using __markdown__.'));
console.log(marked.parse('i am using __markdown__.', options));
console.log(marked.parse('i am using __markdown__.', callback));
console.log(marked.parse('i am using __markdown__.', options, callback));
var text = 'something';
var tokens = marked.lexer(text, options);
console.log(marked.parser(tokens));
var renderer = new marked.Renderer();
renderer.heading = function(text, level, raw) {
return text + level.toString() + raw;
};
| /// <reference path="marked.d.ts" />
import * as marked from 'marked';
var options: MarkedOptions = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
silent: false,
highlight: function (code: string, lang: string) {
return '';
},
langPrefix: 'lang-',
smartypants: false,
renderer: new marked.Renderer()
};
function callback() {
console.log('callback called');
}
marked.setOptions(options);
console.log(marked('i am using __markdown__.'));
console.log(marked('i am using __markdown__.', options));
console.log(marked('i am using __markdown__.', callback));
console.log(marked('i am using __markdown__.', options, callback));
console.log(marked.parse('i am using __markdown__.'));
console.log(marked.parse('i am using __markdown__.', options));
console.log(marked.parse('i am using __markdown__.', callback));
console.log(marked.parse('i am using __markdown__.', options, callback));
var text = 'something';
var tokens = marked.lexer(text, options);
console.log(marked.parser(tokens));
var renderer = new marked.Renderer();
renderer.heading = function(text, level, raw) {
return text + level.toString() + raw;
};
| Fix TS1202 for --target es6 | marked.d.ts: Fix TS1202 for --target es6
| TypeScript | mit | abbasmhd/DefinitelyTyped,georgemarshall/DefinitelyTyped,martinduparc/DefinitelyTyped,pocesar/DefinitelyTyped,danfma/DefinitelyTyped,isman-usoh/DefinitelyTyped,alvarorahul/DefinitelyTyped,schmuli/DefinitelyTyped,donnut/DefinitelyTyped,arusakov/DefinitelyTyped,donnut/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,newclear/DefinitelyTyped,YousefED/DefinitelyTyped,jimthedev/DefinitelyTyped,arma-gast/DefinitelyTyped,borisyankov/DefinitelyTyped,amanmahajan7/DefinitelyTyped,hellopao/DefinitelyTyped,florentpoujol/DefinitelyTyped,abbasmhd/DefinitelyTyped,HPFOD/DefinitelyTyped,HPFOD/DefinitelyTyped,mcliment/DefinitelyTyped,YousefED/DefinitelyTyped,mareek/DefinitelyTyped,zuzusik/DefinitelyTyped,nainslie/DefinitelyTyped,chrismbarr/DefinitelyTyped,newclear/DefinitelyTyped,markogresak/DefinitelyTyped,johan-gorter/DefinitelyTyped,syuilo/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,florentpoujol/DefinitelyTyped,greglo/DefinitelyTyped,rolandzwaga/DefinitelyTyped,ashwinr/DefinitelyTyped,hellopao/DefinitelyTyped,arusakov/DefinitelyTyped,mattblang/DefinitelyTyped,damianog/DefinitelyTyped,benishouga/DefinitelyTyped,paulmorphy/DefinitelyTyped,rcchen/DefinitelyTyped,mhegazy/DefinitelyTyped,isman-usoh/DefinitelyTyped,dsebastien/DefinitelyTyped,QuatroCode/DefinitelyTyped,QuatroCode/DefinitelyTyped,stacktracejs/DefinitelyTyped,aciccarello/DefinitelyTyped,use-strict/DefinitelyTyped,psnider/DefinitelyTyped,abner/DefinitelyTyped,mhegazy/DefinitelyTyped,benishouga/DefinitelyTyped,rcchen/DefinitelyTyped,smrq/DefinitelyTyped,raijinsetsu/DefinitelyTyped,reppners/DefinitelyTyped,Ptival/DefinitelyTyped,use-strict/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,mareek/DefinitelyTyped,gandjustas/DefinitelyTyped,arma-gast/DefinitelyTyped,xStrom/DefinitelyTyped,progre/DefinitelyTyped,mcrawshaw/DefinitelyTyped,pwelter34/DefinitelyTyped,benliddicott/DefinitelyTyped,hellopao/DefinitelyTyped,Pro/DefinitelyTyped,chrootsu/DefinitelyTyped,daptiv/DefinitelyTyped,Litee/DefinitelyTyped,benishouga/DefinitelyTyped,Pro/DefinitelyTyped,danfma/DefinitelyTyped,tan9/DefinitelyTyped,EnableSoftware/DefinitelyTyped,chrismbarr/DefinitelyTyped,martinduparc/DefinitelyTyped,damianog/DefinitelyTyped,mattblang/DefinitelyTyped,frogcjn/DefinitelyTyped,jimthedev/DefinitelyTyped,jimthedev/DefinitelyTyped,Penryn/DefinitelyTyped,alexdresko/DefinitelyTyped,abner/DefinitelyTyped,schmuli/DefinitelyTyped,mcrawshaw/DefinitelyTyped,aciccarello/DefinitelyTyped,martinduparc/DefinitelyTyped,georgemarshall/DefinitelyTyped,stephenjelfs/DefinitelyTyped,Penryn/DefinitelyTyped,ryan10132/DefinitelyTyped,minodisk/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,smrq/DefinitelyTyped,progre/DefinitelyTyped,stephenjelfs/DefinitelyTyped,raijinsetsu/DefinitelyTyped,pocesar/DefinitelyTyped,scriby/DefinitelyTyped,gcastre/DefinitelyTyped,magny/DefinitelyTyped,reppners/DefinitelyTyped,sledorze/DefinitelyTyped,Zzzen/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,subash-a/DefinitelyTyped,scriby/DefinitelyTyped,shlomiassaf/DefinitelyTyped,philippstucki/DefinitelyTyped,ashwinr/DefinitelyTyped,gcastre/DefinitelyTyped,zuzusik/DefinitelyTyped,amanmahajan7/DefinitelyTyped,micurs/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,georgemarshall/DefinitelyTyped,gandjustas/DefinitelyTyped,Ptival/DefinitelyTyped,AgentME/DefinitelyTyped,jraymakers/DefinitelyTyped,emanuelhp/DefinitelyTyped,johan-gorter/DefinitelyTyped,frogcjn/DefinitelyTyped,chbrown/DefinitelyTyped,yuit/DefinitelyTyped,nainslie/DefinitelyTyped,rolandzwaga/DefinitelyTyped,arusakov/DefinitelyTyped,alexdresko/DefinitelyTyped,magny/DefinitelyTyped,one-pieces/DefinitelyTyped,xStrom/DefinitelyTyped,yuit/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,AgentME/DefinitelyTyped,nobuoka/DefinitelyTyped,shlomiassaf/DefinitelyTyped,georgemarshall/DefinitelyTyped,stacktracejs/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,pocesar/DefinitelyTyped,musicist288/DefinitelyTyped,alvarorahul/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,philippstucki/DefinitelyTyped,paulmorphy/DefinitelyTyped,nycdotnet/DefinitelyTyped,sledorze/DefinitelyTyped,amir-arad/DefinitelyTyped,nfriend/DefinitelyTyped,nycdotnet/DefinitelyTyped,aciccarello/DefinitelyTyped,psnider/DefinitelyTyped,nobuoka/DefinitelyTyped,syuilo/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,Zzzen/DefinitelyTyped,minodisk/DefinitelyTyped,Litee/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,pwelter34/DefinitelyTyped,AgentME/DefinitelyTyped,emanuelhp/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,greglo/DefinitelyTyped,borisyankov/DefinitelyTyped,zuzusik/DefinitelyTyped,axelcostaspena/DefinitelyTyped,chrootsu/DefinitelyTyped,psnider/DefinitelyTyped,dsebastien/DefinitelyTyped,tan9/DefinitelyTyped,AgentME/DefinitelyTyped,jraymakers/DefinitelyTyped,EnableSoftware/DefinitelyTyped,schmuli/DefinitelyTyped,subash-a/DefinitelyTyped | ---
+++
@@ -1,6 +1,6 @@
/// <reference path="marked.d.ts" />
-import marked = require('marked');
+import * as marked from 'marked';
var options: MarkedOptions = {
gfm: true, |
55fe9aee5b3fdd02b4c5af084e87f07e71b3cd4d | src/picturepark-sdk-v1-angular/src/tests/share-service.spec.ts | src/picturepark-sdk-v1-angular/src/tests/share-service.spec.ts | import { } from 'jasmine';
import { async, inject } from '@angular/core/testing';
import {
ContentService, ContentSearchRequest,
ShareContent, ShareBasicCreateRequest, ShareService, OutputAccess
} from '@picturepark/sdk-v1-angular';
import { configureTest } from './config';
describe('ShareService', () => {
beforeEach(configureTest);
it('should create embed share', async(inject([ContentService, ShareService],
async (contentService: ContentService, shareService: ShareService) => {
// arrange
const request = new ContentSearchRequest();
request.searchString = 'm';
const response = await contentService.search(request).toPromise();
// act
const contents = response.results.map(i => new ShareContent({
contentId: i.id,
outputFormatIds: ['Original']
}));
const result = await shareService.create(new ShareBasicCreateRequest({
name: 'Share',
languageCode: 'en',
contents: contents,
outputAccess: OutputAccess.Full
})).toPromise();
const share = await shareService.get(result.shareId!).toPromise();
// assert
expect(result.shareId).not.toBeNull();
expect(share.id).toEqual(result.shareId!);
})));
});
| import { } from 'jasmine';
import { async, inject } from '@angular/core/testing';
import {
ContentService, ContentSearchRequest,
ShareContent, ShareBasicCreateRequest, ShareService, OutputAccess
} from '@picturepark/sdk-v1-angular';
import { configureTest } from './config';
describe('ShareService', () => {
beforeEach(configureTest);
it('should create embed share', async(inject([ContentService, ShareService],
async (contentService: ContentService, shareService: ShareService) => {
// arrange
const request = new ContentSearchRequest();
request.searchString = 'm';
const response = await contentService.search(request).toPromise();
// act
const contents = response.results.map(i => new ShareContent({
contentId: i.id,
outputFormatIds: ['Original']
}));
const result = await shareService.create( null, new ShareBasicCreateRequest({
name: 'Share',
languageCode: 'en',
contents: contents,
outputAccess: OutputAccess.Full,
suppressNotifications: false
})).toPromise();
const share = await shareService.get(result.shareId!).toPromise();
// assert
expect(result.shareId).not.toBeNull();
expect(share.id).toEqual(result.shareId!);
})));
});
| Fix testing services after api breaks | Fix testing services after api breaks
| TypeScript | mit | Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript | ---
+++
@@ -24,11 +24,12 @@
outputFormatIds: ['Original']
}));
- const result = await shareService.create(new ShareBasicCreateRequest({
+ const result = await shareService.create( null, new ShareBasicCreateRequest({
name: 'Share',
languageCode: 'en',
contents: contents,
- outputAccess: OutputAccess.Full
+ outputAccess: OutputAccess.Full,
+ suppressNotifications: false
})).toPromise();
const share = await shareService.get(result.shareId!).toPromise(); |
72d96423109937690f6189aa912cfbbfb472fd1e | frontend/vite.config.ts | frontend/vite.config.ts | import { fileURLToPath, URL } from 'url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
| import { fileURLToPath, URL } from 'url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
watch: {
usePolling: true
}
}
})
| Use polling for HMR because SSHFS does not send iNotify events | Use polling for HMR because SSHFS does not send iNotify events
Signed-off-by: Aurélien Bompard <[email protected]>
| TypeScript | lgpl-2.1 | fedora-infra/fmn,fedora-infra/fmn,fedora-infra/fmn,fedora-infra/fmn,fedora-infra/fmn | ---
+++
@@ -10,5 +10,10 @@
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
+ },
+ server: {
+ watch: {
+ usePolling: true
+ }
}
}) |
a9ac439c6add02096ffa56302eaec67bdd8d7dc0 | src/application/index.ts | src/application/index.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Application
} from 'phosphor/lib/ui/application';
import {
ApplicationShell
} from './shell';
export
class JupyterLab extends Application<ApplicationShell> {
/**
* Create the application shell for the JupyterLab application.
*/
protected createShell(): ApplicationShell {
return new ApplicationShell();
}
}
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Application
} from 'phosphor/lib/ui/application';
import {
ApplicationShell
} from './shell';
/**
* The type for all JupyterLab plugins.
*/
export
type JupyterLabPlugin<T> = Application.IPlugin<JupyterLab, T>;
/**
* JupyterLab is the main application class. It is instantiated once and shared.
*/
export
class JupyterLab extends Application<ApplicationShell> {
/**
* Create the application shell for the JupyterLab application.
*/
protected createShell(): ApplicationShell {
return new ApplicationShell();
}
}
| Add JupyterLabPlugin type and some docs. | Add JupyterLabPlugin type and some docs.
| TypeScript | bsd-3-clause | TypeFox/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,TypeFox/jupyterlab,TypeFox/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,TypeFox/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab | ---
+++
@@ -9,6 +9,17 @@
ApplicationShell
} from './shell';
+
+/**
+ * The type for all JupyterLab plugins.
+ */
+export
+type JupyterLabPlugin<T> = Application.IPlugin<JupyterLab, T>;
+
+
+/**
+ * JupyterLab is the main application class. It is instantiated once and shared.
+ */
export
class JupyterLab extends Application<ApplicationShell> {
/** |
2df8324ca6bdbacd543d4cb5adab6b706fb3acad | examples/tscDemo.ts | examples/tscDemo.ts | ///<reference path="../lib/d3.d.ts" />
///<reference path="../src/table.ts" />
///<reference path="../src/renderer.ts" />
///<reference path="../src/interaction.ts" />
///<reference path="../src/labelComponent.ts" />
///<reference path="../src/axis.ts" />
///<reference path="../src/scale.ts" />
///<reference path="exampleUtil.ts" />
if ((<any> window).demoName === "tsc-demo") {
var yScale = new LinearScale();
var xScale = new LinearScale();
var left = new YAxis(yScale, "left");
var data = makeRandomData(1000, 200);
var renderer = new LineRenderer(data, xScale, yScale);
var bottomAxis = new XAxis(xScale, "bottom");
var chart = new Table([[left, renderer]
,[null, bottomAxis]]);
var outerTable = new Table([ [new TitleLabel("A Chart")],
[chart] ])
outerTable.xMargin = 10;
outerTable.yMargin = 10;
var svg = d3.select("#table");
outerTable.anchor(svg);
outerTable.computeLayout();
outerTable.render();
}
| ///<reference path="../lib/d3.d.ts" />
///<reference path="../src/table.ts" />
///<reference path="../src/renderer.ts" />
///<reference path="../src/interaction.ts" />
///<reference path="../src/labelComponent.ts" />
///<reference path="../src/axis.ts" />
///<reference path="../src/scale.ts" />
///<reference path="exampleUtil.ts" />
if ((<any> window).demoName === "tsc-demo") {
var yScale = new LinearScale();
var xScale = new LinearScale();
var left = new YAxis(yScale, "left");
var data = makeRandomData(1000, 200);
var lineRenderer = new LineRenderer(data, xScale, yScale);
var bottomAxis = new XAxis(xScale, "bottom");
var chart = new Table([[left, lineRenderer]
,[null, bottomAxis]]);
var outerTable = new Table([ [new TitleLabel("A Chart")],
[chart] ])
outerTable.xMargin = 10;
outerTable.yMargin = 10;
var svg = d3.select("#table");
outerTable.anchor(svg);
outerTable.computeLayout();
outerTable.render();
}
| Fix temporary naming collision in example files | Fix temporary naming collision in example files
| TypeScript | mit | alyssaq/plottable,gdseller/plottable,danmane/plottable,iobeam/plottable,palantir/plottable,jacqt/plottable,jacqt/plottable,alyssaq/plottable,onaio/plottable,softwords/plottable,palantir/plottable,iobeam/plottable,NextTuesday/plottable,alyssaq/plottable,jacqt/plottable,softwords/plottable,gdseller/plottable,NextTuesday/plottable,palantir/plottable,RobertoMalatesta/plottable,iobeam/plottable,onaio/plottable,RobertoMalatesta/plottable,danmane/plottable,danmane/plottable,gdseller/plottable,RobertoMalatesta/plottable,palantir/plottable,onaio/plottable,NextTuesday/plottable,softwords/plottable | ---
+++
@@ -14,10 +14,10 @@
var xScale = new LinearScale();
var left = new YAxis(yScale, "left");
var data = makeRandomData(1000, 200);
-var renderer = new LineRenderer(data, xScale, yScale);
+var lineRenderer = new LineRenderer(data, xScale, yScale);
var bottomAxis = new XAxis(xScale, "bottom");
-var chart = new Table([[left, renderer]
+var chart = new Table([[left, lineRenderer]
,[null, bottomAxis]]);
var outerTable = new Table([ [new TitleLabel("A Chart")], |
f49e20e47d22aa5f90becbfc94225f0c32f79ab6 | ee_tests/src/functional/screenshot.spec.ts | ee_tests/src/functional/screenshot.spec.ts | import { browser } from 'protractor';
import * as support from '../specs/support';
import { LandingPage } from '../specs/page_objects';
describe('Landing Page', () => {
beforeEach( async () => {
await support.desktopTestSetup();
let landingPage = new LandingPage();
await landingPage.open();
});
fit('writes the screenshot of landing page', async () => {
await expect(await browser.getTitle()).toEqual('OpenShift.io');
await support.writeScreenshot('page.png');
});
});
| import { browser } from 'protractor';
import * as support from '../specs/support';
import { LandingPage } from '../specs/page_objects';
describe('Landing Page', () => {
beforeEach( async () => {
await support.desktopTestSetup();
let landingPage = new LandingPage();
await landingPage.open();
});
it('writes the screenshot of landing page', async () => {
await expect(await browser.getTitle()).toEqual('OpenShift.io');
await support.writeScreenshot('page.png');
});
});
| Rename fit -> it in functional tests | Rename fit -> it in functional tests
| TypeScript | apache-2.0 | ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test | ---
+++
@@ -11,7 +11,7 @@
await landingPage.open();
});
- fit('writes the screenshot of landing page', async () => {
+ it('writes the screenshot of landing page', async () => {
await expect(await browser.getTitle()).toEqual('OpenShift.io');
await support.writeScreenshot('page.png');
}); |
00a45903a7a37e000c95461f5cb753ac1d546a91 | src/app/connections/list/list.component.spec.ts | src/app/connections/list/list.component.spec.ts | /* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { IPaaSCommonModule } from '../../common/common.module';
import { ConnectionsListComponent } from './list.component';
describe('ConnectionsListComponent', () => {
let component: ConnectionsListComponent;
let fixture: ComponentFixture<ConnectionsListComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [IPaaSCommonModule, RouterTestingModule.withRoutes([])],
declarations: [ConnectionsListComponent],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ConnectionsListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| /* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { ModalModule } from 'ng2-bootstrap/modal';
import { ToasterModule } from 'angular2-toaster';
import { IPaaSCommonModule } from '../../common/common.module';
import { ConnectionsListComponent } from './list.component';
describe('ConnectionsListComponent', () => {
let component: ConnectionsListComponent;
let fixture: ComponentFixture<ConnectionsListComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
IPaaSCommonModule,
RouterTestingModule.withRoutes([]),
ModalModule,
ToasterModule,
],
declarations: [ConnectionsListComponent],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ConnectionsListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| Fix tests for connection list | Fix tests for connection list
| TypeScript | apache-2.0 | kahboom/ipaas-client,kahboom/ipaas-client,kahboom/ipaas-client,kahboom/ipaas-client | ---
+++
@@ -3,6 +3,9 @@
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
+
+import { ModalModule } from 'ng2-bootstrap/modal';
+import { ToasterModule } from 'angular2-toaster';
import { IPaaSCommonModule } from '../../common/common.module';
import { ConnectionsListComponent } from './list.component';
@@ -13,7 +16,12 @@
beforeEach(async(() => {
TestBed.configureTestingModule({
- imports: [IPaaSCommonModule, RouterTestingModule.withRoutes([])],
+ imports: [
+ IPaaSCommonModule,
+ RouterTestingModule.withRoutes([]),
+ ModalModule,
+ ToasterModule,
+ ],
declarations: [ConnectionsListComponent],
})
.compileComponents(); |
7fd5d324925c8164757ff60b2dda60c45f5c77e6 | projects/ngx-progressbar/src/lib/ng-progress.component.spec.ts | projects/ngx-progressbar/src/lib/ng-progress.component.spec.ts | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { NgProgressComponent } from './ng-progress.component';
import { NgProgress } from './ng-progress.service';
class NgProgressStub {
config = {};
ref() {
return {
state: of(
{
active: true,
value: 5
}
)
};
}
}
describe('NgProgressComponent', () => {
let component: NgProgressComponent;
let fixture: ComponentFixture<NgProgressComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [NgProgressComponent],
imports: [
RouterTestingModule
],
providers: [
{ provide: NgProgress, useClass: NgProgressStub }
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(NgProgressComponent);
component = fixture.componentInstance;
});
it('should create a progress bar', () => {
expect(component).toBeDefined();
});
// it('should destroy component without errors', () => {
// const ngOnDestroySpy = spyOn(component, 'ngOnDestroy');
// fixture.destroy();
// component.ngOnDestroy();
// expect(ngOnDestroySpy).toHaveBeenCalled();
// });
});
| import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { of } from 'rxjs';
import { NgProgress, NgProgressComponent, NgProgressModule } from 'ngx-progressbar';
describe('NgProgress Component', () => {
let component: NgProgressComponent;
let ngProgress: NgProgress;
let fixture: ComponentFixture<NgProgressComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [NgProgressModule]
});
ngProgress = TestBed.inject(NgProgress);
});
beforeEach(() => {
fixture = TestBed.createComponent(NgProgressComponent);
component = fixture.componentInstance;
});
it('should create a progress bar', () => {
expect(component).toBeDefined();
});
it('should start/complete the progress using the start/complete functions', (done: DoneFn) => {
const progressRef = ngProgress.ref();
spyOn(progressRef, 'start');
spyOn(progressRef, 'complete');
component.ngOnInit();
component.start();
expect(progressRef.start).toHaveBeenCalled();
setTimeout(() => {
component.complete();
expect(progressRef.complete).toHaveBeenCalled();
done();
}, 200);
});
it('should get true on isStarted when progress is started', (done: DoneFn) => {
component.ngOnInit();
component.start();
setTimeout(() => {
expect(component.isStarted).toBeTrue();
done();
});
});
});
| Add more tests for the progress bar component | enhance: Add more tests for the progress bar component
| TypeScript | mit | MurhafSousli/ngx-progressbar,MurhafSousli/ngx-progressbar,MurhafSousli/ngx-progressbar | ---
+++
@@ -1,39 +1,19 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
-import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
-import { NgProgressComponent } from './ng-progress.component';
-import { NgProgress } from './ng-progress.service';
+import { NgProgress, NgProgressComponent, NgProgressModule } from 'ngx-progressbar';
-class NgProgressStub {
- config = {};
-
- ref() {
- return {
- state: of(
- {
- active: true,
- value: 5
- }
- )
- };
- }
-}
-
-describe('NgProgressComponent', () => {
+describe('NgProgress Component', () => {
let component: NgProgressComponent;
+ let ngProgress: NgProgress;
let fixture: ComponentFixture<NgProgressComponent>;
- beforeEach(waitForAsync(() => {
+ beforeEach(() => {
TestBed.configureTestingModule({
- declarations: [NgProgressComponent],
- imports: [
- RouterTestingModule
- ],
- providers: [
- { provide: NgProgress, useClass: NgProgressStub }
- ]
- }).compileComponents();
- }));
+ imports: [NgProgressModule]
+ });
+
+ ngProgress = TestBed.inject(NgProgress);
+ });
beforeEach(() => {
fixture = TestBed.createComponent(NgProgressComponent);
@@ -44,10 +24,29 @@
expect(component).toBeDefined();
});
- // it('should destroy component without errors', () => {
- // const ngOnDestroySpy = spyOn(component, 'ngOnDestroy');
- // fixture.destroy();
- // component.ngOnDestroy();
- // expect(ngOnDestroySpy).toHaveBeenCalled();
- // });
+ it('should start/complete the progress using the start/complete functions', (done: DoneFn) => {
+ const progressRef = ngProgress.ref();
+ spyOn(progressRef, 'start');
+ spyOn(progressRef, 'complete');
+ component.ngOnInit();
+
+ component.start();
+ expect(progressRef.start).toHaveBeenCalled();
+
+ setTimeout(() => {
+ component.complete();
+ expect(progressRef.complete).toHaveBeenCalled();
+ done();
+ }, 200);
+ });
+
+ it('should get true on isStarted when progress is started', (done: DoneFn) => {
+ component.ngOnInit();
+ component.start();
+
+ setTimeout(() => {
+ expect(component.isStarted).toBeTrue();
+ done();
+ });
+ });
}); |
7877c80a9b35c58cb63cb95789f731b31428278d | src/helper/property.ts | src/helper/property.ts | /**
* Assign value to an object property
*
* @param value: What you are assigning
* @param target: Target to assign value to
* @param propertyPath Where to assign value to on target (path to assign. ie: "baseTexture" or "mesh.material")
*
*/
export function assignProperty(value: any, target: any, propertyPath: string) {
const propsList: string[] = propertyPath.split('.');
propsList.forEach((prop: string, index: number) => {
if (target[prop] === undefined) {
// create property if it doesn't exist.
console.warn(`Created property ${prop} on: (from ${propsList})`, target)
target[prop] = {}
}
if (index === propsList.length - 1) {
target[prop] = value;
} else {
target = target[prop]
}
})
}
| /**
* Assign value to an object property
*
* @param value: What you are assigning
* @param target: Target to assign value to
* @param propertyPath Where to assign value to on target (path to assign. ie: "baseTexture" or "mesh.material")
*
*/
export function assignProperty(value: any, target: any, propertyPath: string) {
const propsList: string[] = propertyPath.split('.');
propsList.forEach((prop: string, index: number) => {
// for assigning to arrays (ie: Texture to model -> meshes[1].material.albedoTexture)
const arrayRegex = /(?<arrayName>.*)\[(?<arrayIndexString>\d+)\]$/;
const match = prop.match(arrayRegex);
if (match && (match as any).groups) {
const { arrayName, arrayIndexString} = (match as any).groups;
const arrayIndex = parseInt(arrayIndexString);
const arrayProp = target[arrayName];
if (arrayProp === undefined || !Array.isArray(arrayProp) || arrayIndex >= arrayProp.length ) {
console.error(`Array not found or missing index (skipping) for property assignment: '${arrayName}[${arrayIndex}]'`, target);
} else {
if (index === propsList.length - 1) {
arrayProp[arrayIndex] = value;
} else {
target = arrayProp[arrayIndex];
}
}
} else {
if (target[prop] === undefined) {
// create property if it doesn't exist.
console.warn(`Created property ${prop} on: (from ${propsList})`, target)
target[prop] = {}
}
if (index === propsList.length - 1) {
target[prop] = value;
} else {
target = target[prop]
}
}
})
}
| Support to assign in arrays. ie: for model textures: assignTo={'meshes[0].material.albedoTexture'} | add: Support to assign in arrays. ie: for model textures: assignTo={'meshes[0].material.albedoTexture'}
| TypeScript | mit | brianzinn/react-babylonJS,brianzinn/react-babylonJS | ---
+++
@@ -10,16 +10,35 @@
const propsList: string[] = propertyPath.split('.');
propsList.forEach((prop: string, index: number) => {
- if (target[prop] === undefined) {
- // create property if it doesn't exist.
- console.warn(`Created property ${prop} on: (from ${propsList})`, target)
- target[prop] = {}
- }
+ // for assigning to arrays (ie: Texture to model -> meshes[1].material.albedoTexture)
+ const arrayRegex = /(?<arrayName>.*)\[(?<arrayIndexString>\d+)\]$/;
+ const match = prop.match(arrayRegex);
- if (index === propsList.length - 1) {
- target[prop] = value;
+ if (match && (match as any).groups) {
+ const { arrayName, arrayIndexString} = (match as any).groups;
+ const arrayIndex = parseInt(arrayIndexString);
+ const arrayProp = target[arrayName];
+ if (arrayProp === undefined || !Array.isArray(arrayProp) || arrayIndex >= arrayProp.length ) {
+ console.error(`Array not found or missing index (skipping) for property assignment: '${arrayName}[${arrayIndex}]'`, target);
+ } else {
+ if (index === propsList.length - 1) {
+ arrayProp[arrayIndex] = value;
+ } else {
+ target = arrayProp[arrayIndex];
+ }
+ }
} else {
- target = target[prop]
+ if (target[prop] === undefined) {
+ // create property if it doesn't exist.
+ console.warn(`Created property ${prop} on: (from ${propsList})`, target)
+ target[prop] = {}
+ }
+
+ if (index === propsList.length - 1) {
+ target[prop] = value;
+ } else {
+ target = target[prop]
+ }
}
})
} |
7858ac4af12995bc973867661e01d8854d43daf0 | packages/pipeline/src/Context.ts | packages/pipeline/src/Context.ts | import { isObject } from '@boost/common';
interface Cloneable {
clone?: () => unknown;
}
export default class Context {
/**
* Create a new instance of the current context and shallow clone all properties.
*/
clone(...args: any[]): this {
// @ts-expect-error
const context = new this.constructor(...args);
// Copy enumerable properties
Object.keys(this).forEach((key) => {
const prop = key as keyof this;
let value: unknown = this[prop];
if (Array.isArray(value)) {
value = [...value];
} else if (value instanceof Map) {
value = new Map(value);
} else if (value instanceof Set) {
value = new Set(value);
} else if (value instanceof Date) {
value = new Date(value.getTime());
} else if (isObject<Cloneable>(value)) {
if (typeof value.clone === 'function') {
value = value.clone();
// Dont dereference instances, only plain objects
} else if (value.constructor === Object) {
value = { ...value };
}
}
context[prop] = value;
});
return context;
}
}
| import { isObject, isPlainObject } from '@boost/common';
interface Cloneable {
clone?: () => unknown;
}
export default class Context {
/**
* Create a new instance of the current context and shallow clone all properties.
*/
clone(...args: any[]): this {
// @ts-expect-error
const context = new this.constructor(...args);
// Copy enumerable properties
Object.keys(this).forEach((key) => {
const prop = key as keyof this;
let value: unknown = this[prop];
if (Array.isArray(value)) {
value = [...value];
} else if (value instanceof Map) {
value = new Map(value);
} else if (value instanceof Set) {
value = new Set(value);
} else if (value instanceof Date) {
value = new Date(value.getTime());
} else if (isObject<Cloneable>(value)) {
if (typeof value.clone === 'function') {
value = value.clone();
// Dont dereference instances, only plain objects
} else if (isPlainObject(value)) {
value = { ...value };
}
}
context[prop] = value;
});
return context;
}
}
| Update to check for plain objects. | fix: Update to check for plain objects.
| TypeScript | mit | milesj/boost,milesj/boost | ---
+++
@@ -1,4 +1,4 @@
-import { isObject } from '@boost/common';
+import { isObject, isPlainObject } from '@boost/common';
interface Cloneable {
clone?: () => unknown;
@@ -29,7 +29,7 @@
if (typeof value.clone === 'function') {
value = value.clone();
// Dont dereference instances, only plain objects
- } else if (value.constructor === Object) {
+ } else if (isPlainObject(value)) {
value = { ...value };
}
} |
0fe933cf362ad3f674c12ef5c67934873280dd3c | src/custom-linter.ts | src/custom-linter.ts | import * as ts from 'typescript';
import { ILinterOptions, LintResult } from 'tslint';
import { typescriptService } from './typescript-service';
const { Linter: TSLintLinter } = require('tslint');
export class CustomLinter extends TSLintLinter {
constructor(options: ILinterOptions, program?: ts.Program | undefined) {
super(options, program);
}
getResult(): LintResult {
return super.getResult();
}
getSourceFile(fileName: string, source: string) {
if (this.program === undefined) {
return super.getSourceFile(fileName, source);
}
const service = typescriptService();
return service.getSourceFile(fileName, source);
}
}
| import * as ts from 'typescript';
import { ILinterOptions, LintResult } from 'tslint';
import { typescriptService } from './typescript-service';
const { Linter: TSLintLinter } = require('tslint');
export class CustomLinter extends TSLintLinter {
constructor(options: ILinterOptions, program?: ts.Program | undefined) {
super(options, program);
}
getResult(): LintResult {
return super.getResult();
}
getSourceFile(fileName: string, source: string) {
if (this.program === undefined) {
return super.getSourceFile(fileName, source);
}
const service = typescriptService();
const result = service.getSourceFile(fileName, source);
this.program = service.getProgram();
return result;
}
}
| Update program when sourceFile was updated | fix: Update program when sourceFile was updated
| TypeScript | mit | JamesHenry/eslint-plugin-tslint,JamesHenry/eslint-plugin-tslint | ---
+++
@@ -18,6 +18,8 @@
return super.getSourceFile(fileName, source);
}
const service = typescriptService();
- return service.getSourceFile(fileName, source);
+ const result = service.getSourceFile(fileName, source);
+ this.program = service.getProgram();
+ return result;
}
} |
62a97727d29a64a6aeba61c4acc6c84302734770 | src/app/pages/tabs/tabs.component.spec.ts | src/app/pages/tabs/tabs.component.spec.ts | import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TabsPage } from './tabs.page';
describe('TabsPage', () => {
let component: TabsPage;
let fixture: ComponentFixture<TabsPage>;
beforeEach(async () => {
TestBed.configureTestingModule({
declarations: [TabsPage],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TabsPage);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Tabs } from './tabs.component';
describe('Tabs', () => {
let component: Tabs;
let fixture: ComponentFixture<Tabs>;
beforeEach(async () => {
TestBed.configureTestingModule({
declarations: [Tabs],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(Tabs);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| Fix base test for Tabs | Fix base test for Tabs
| TypeScript | apache-2.0 | openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile | ---
+++
@@ -1,21 +1,21 @@
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
-import { TabsPage } from './tabs.page';
+import { Tabs } from './tabs.component';
-describe('TabsPage', () => {
- let component: TabsPage;
- let fixture: ComponentFixture<TabsPage>;
+describe('Tabs', () => {
+ let component: Tabs;
+ let fixture: ComponentFixture<Tabs>;
beforeEach(async () => {
TestBed.configureTestingModule({
- declarations: [TabsPage],
+ declarations: [Tabs],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
});
beforeEach(() => {
- fixture = TestBed.createComponent(TabsPage);
+ fixture = TestBed.createComponent(Tabs);
component = fixture.componentInstance;
fixture.detectChanges();
}); |
940d5f373f84cc93505aa3680fdd9d2258827afe | hawtio-web/src/main/webapp/app/ui/js/editablePropertyDirective.ts | hawtio-web/src/main/webapp/app/ui/js/editablePropertyDirective.ts | module UI {
export class EditableProperty {
public restrict = 'E';
public scope = true;
public templateUrl = UI.templatePath + 'editableProperty.html';
public require = 'ngModel';
public link = null;
constructor(private $parse) {
this.link = (scope, element, attrs, ngModel) => {
scope.editing = false;
$(element.find(".icon-pencil")[0]).hide();
ngModel.$render = function () {
var propertyName = $parse(attrs['property'])(scope);
scope.text = ngModel.$viewValue[propertyName];
};
scope.showEdit = function () {
$(element.find(".icon-pencil")[0]).show();
};
scope.hideEdit = function () {
$(element.find(".icon-pencil")[0]).hide();
};
scope.doEdit = function () {
scope.editing = true;
};
scope.stopEdit = function () {
scope.editing = false;
};
scope.saveEdit = function () {
var value = $(element.find(":input[type=text]")[0]).val();
var obj = ngModel.$viewValue;
obj[$parse(attrs['property'])(scope)] = value;
ngModel.$setViewValue(obj);
ngModel.$render();
scope.editing = false;
scope.$parent.$eval(attrs['onSave']);
};
};
}
}
}
| module UI {
export class EditableProperty {
public restrict = 'E';
public scope = true;
public templateUrl = UI.templatePath + 'editableProperty.html';
public require = 'ngModel';
public link = null;
constructor(private $parse) {
this.link = (scope, element, attrs, ngModel) => {
scope.editing = false;
$(element.find(".icon-pencil")[0]).hide();
scope.getPropertyName = () => {
var propertyName = $parse(attrs['property'])(scope);
if (!propertyName && propertyName !== 0) {
propertyName = attrs['property'];
}
return propertyName;
}
scope.propertyName = scope.getPropertyName();
ngModel.$render = function () {
if (!ngModel.$viewValue) {
return;
}
scope.text = ngModel.$viewValue[scope.propertyName];
};
scope.showEdit = function () {
$(element.find(".icon-pencil")[0]).show();
};
scope.hideEdit = function () {
$(element.find(".icon-pencil")[0]).hide();
};
scope.doEdit = function () {
scope.editing = true;
};
scope.stopEdit = function () {
scope.editing = false;
};
scope.saveEdit = function () {
var value = $(element.find(":input[type=text]")[0]).val();
var obj = ngModel.$viewValue;
obj[scope.propertyName] = value;
ngModel.$setViewValue(obj);
ngModel.$render();
scope.editing = false;
scope.$parent.$eval(attrs['onSave']);
};
};
}
}
}
| Fix editable property parsing of property attribute | Fix editable property parsing of property attribute
| TypeScript | apache-2.0 | telefunken/hawtio,skarsaune/hawtio,andytaylor/hawtio,padmaragl/hawtio,jfbreault/hawtio,rajdavies/hawtio,rajdavies/hawtio,hawtio/hawtio,padmaragl/hawtio,skarsaune/hawtio,hawtio/hawtio,andytaylor/hawtio,tadayosi/hawtio,padmaragl/hawtio,hawtio/hawtio,uguy/hawtio,padmaragl/hawtio,rajdavies/hawtio,tadayosi/hawtio,andytaylor/hawtio,voipme2/hawtio,hawtio/hawtio,skarsaune/hawtio,fortyrunner/hawtio,Fatze/hawtio,Fatze/hawtio,telefunken/hawtio,fortyrunner/hawtio,jfbreault/hawtio,rajdavies/hawtio,samkeeleyong/hawtio,mposolda/hawtio,grgrzybek/hawtio,grgrzybek/hawtio,mposolda/hawtio,skarsaune/hawtio,andytaylor/hawtio,telefunken/hawtio,uguy/hawtio,tadayosi/hawtio,voipme2/hawtio,stalet/hawtio,jfbreault/hawtio,voipme2/hawtio,skarsaune/hawtio,mposolda/hawtio,stalet/hawtio,Fatze/hawtio,mposolda/hawtio,telefunken/hawtio,samkeeleyong/hawtio,Fatze/hawtio,Fatze/hawtio,rajdavies/hawtio,samkeeleyong/hawtio,uguy/hawtio,voipme2/hawtio,grgrzybek/hawtio,jfbreault/hawtio,mposolda/hawtio,voipme2/hawtio,telefunken/hawtio,stalet/hawtio,tadayosi/hawtio,fortyrunner/hawtio,stalet/hawtio,fortyrunner/hawtio,samkeeleyong/hawtio,uguy/hawtio,stalet/hawtio,hawtio/hawtio,padmaragl/hawtio,tadayosi/hawtio,grgrzybek/hawtio,jfbreault/hawtio,samkeeleyong/hawtio,uguy/hawtio,grgrzybek/hawtio,andytaylor/hawtio | ---
+++
@@ -14,9 +14,21 @@
scope.editing = false;
$(element.find(".icon-pencil")[0]).hide();
+ scope.getPropertyName = () => {
+ var propertyName = $parse(attrs['property'])(scope);
+ if (!propertyName && propertyName !== 0) {
+ propertyName = attrs['property'];
+ }
+ return propertyName;
+ }
+
+ scope.propertyName = scope.getPropertyName();
+
ngModel.$render = function () {
- var propertyName = $parse(attrs['property'])(scope);
- scope.text = ngModel.$viewValue[propertyName];
+ if (!ngModel.$viewValue) {
+ return;
+ }
+ scope.text = ngModel.$viewValue[scope.propertyName];
};
scope.showEdit = function () {
@@ -39,7 +51,7 @@
var value = $(element.find(":input[type=text]")[0]).val();
var obj = ngModel.$viewValue;
- obj[$parse(attrs['property'])(scope)] = value;
+ obj[scope.propertyName] = value;
ngModel.$setViewValue(obj);
ngModel.$render(); |
f011818c12ffc5d4b1cd45e2147ffa0f1f8d4846 | packages/skin-database/tasks/screenshotSkin.ts | packages/skin-database/tasks/screenshotSkin.ts | // eslint-disable-next-line
import _temp from "temp";
import fs from "fs";
import fetch from "node-fetch";
import md5Buffer from "md5";
import * as S3 from "../s3";
import * as Skins from "../data/skins";
const Shooter = require("../shooter");
const temp = _temp.track();
export async function screenshot(md5: string, shooter: typeof Shooter) {
const url = Skins.getSkinUrl(md5);
const response = await fetch(url);
if (!response.ok) {
await Skins.recordScreenshotUpdate(md5, `Failed to download from ${url}.`);
console.error(`Failed to download skin from "${url}".`);
return;
}
const buffer = await response.buffer();
const actualMd5 = md5Buffer(buffer);
if (md5 !== actualMd5) {
throw new Error("Downloaded skin had a different md5.");
}
const tempFile = temp.path({ suffix: ".wsz" });
const tempScreenshotPath = temp.path({ suffix: ".png" });
fs.writeFileSync(tempFile, buffer);
console.log("Starting screenshot");
const success = await shooter.takeScreenshot(tempFile, tempScreenshotPath, {
minify: true,
md5,
});
if (success) {
console.log("Completed screenshot");
await S3.putScreenshot(md5, fs.readFileSync(tempScreenshotPath));
} else {
console.log(`Screenshot failed ${md5}`);
}
}
| // eslint-disable-next-line
import _temp from "temp";
import fs from "fs";
import fetch from "node-fetch";
import md5Buffer from "md5";
import * as S3 from "../s3";
import * as Skins from "../data/skins";
import * as CloudFlare from "../CloudFlare";
const Shooter = require("../shooter");
const temp = _temp.track();
export async function screenshot(md5: string, shooter: typeof Shooter) {
const url = Skins.getSkinUrl(md5);
const response = await fetch(url);
if (!response.ok) {
await Skins.recordScreenshotUpdate(md5, `Failed to download from ${url}.`);
console.error(`Failed to download skin from "${url}".`);
return;
}
const buffer = await response.buffer();
const actualMd5 = md5Buffer(buffer);
if (md5 !== actualMd5) {
throw new Error("Downloaded skin had a different md5.");
}
const tempFile = temp.path({ suffix: ".wsz" });
const tempScreenshotPath = temp.path({ suffix: ".png" });
fs.writeFileSync(tempFile, buffer);
console.log("Starting screenshot");
const success = await shooter.takeScreenshot(tempFile, tempScreenshotPath, {
minify: true,
md5,
});
if (success) {
console.log("Completed screenshot");
await S3.putScreenshot(md5, fs.readFileSync(tempScreenshotPath));
await CloudFlare.purgeFiles([Skins.getScreenshotUrl(actualMd5)]);
} else {
console.log(`Screenshot failed ${md5}`);
}
}
| Clear screenshot CDN cache after reuploading | Clear screenshot CDN cache after reuploading
| TypeScript | mit | captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js | ---
+++
@@ -5,6 +5,7 @@
import md5Buffer from "md5";
import * as S3 from "../s3";
import * as Skins from "../data/skins";
+import * as CloudFlare from "../CloudFlare";
const Shooter = require("../shooter");
const temp = _temp.track();
@@ -36,6 +37,7 @@
if (success) {
console.log("Completed screenshot");
await S3.putScreenshot(md5, fs.readFileSync(tempScreenshotPath));
+ await CloudFlare.purgeFiles([Skins.getScreenshotUrl(actualMd5)]);
} else {
console.log(`Screenshot failed ${md5}`);
} |
c4249ef30e8dadc3948fe4503f2fc20a29b467f6 | packages/shared/lib/helpers/blackfriday.ts | packages/shared/lib/helpers/blackfriday.ts | import { isWithinInterval } from 'date-fns';
import { BLACK_FRIDAY, PRODUCT_PAYER } from '../constants';
import { Subscription } from '../interfaces';
import { hasMailPlus, hasMailProfessional, hasVpnBasic, hasVpnPlus, hasAddons } from './subscription';
export const isBlackFridayPeriod = () => {
return isWithinInterval(new Date(), { start: BLACK_FRIDAY.START, end: BLACK_FRIDAY.END });
};
export const isCyberMonday = () => {
return isWithinInterval(new Date(), { start: BLACK_FRIDAY.CYBER_START, end: BLACK_FRIDAY.CYBER_END });
};
export const isProductPayerPeriod = () => {
return isWithinInterval(new Date(), { start: PRODUCT_PAYER.START, end: PRODUCT_PAYER.END });
};
export const isProductPayer = (subscription: Subscription) => {
if (!subscription) {
return false;
}
const couponCode = subscription?.CouponCode || '';
const isPaying = hasMailPlus(subscription) || hasVpnBasic(subscription) || hasVpnPlus(subscription);
const noPro = !hasMailProfessional(subscription);
const noBundle = !(hasMailPlus(subscription) && hasVpnPlus(subscription));
const noBFCoupon = ![BLACK_FRIDAY.COUPON_CODE].includes(couponCode);
const noAddons = !hasAddons(subscription);
return isPaying && noPro && noBundle && noBFCoupon && noAddons;
};
| import { isWithinInterval, isAfter } from 'date-fns';
import { BLACK_FRIDAY, PRODUCT_PAYER } from '../constants';
import { Subscription } from '../interfaces';
import { hasMailPlus, hasMailProfessional, hasVpnBasic, hasVpnPlus, hasAddons } from './subscription';
export const isBlackFridayPeriod = () => {
return isWithinInterval(new Date(), { start: BLACK_FRIDAY.START, end: BLACK_FRIDAY.END });
};
export const isCyberMonday = () => {
return isWithinInterval(new Date(), { start: BLACK_FRIDAY.CYBER_START, end: BLACK_FRIDAY.CYBER_END });
};
export const isProductPayerPeriod = () => {
return isAfter(new Date(), PRODUCT_PAYER.START);
};
export const isProductPayer = (subscription: Subscription) => {
if (!subscription) {
return false;
}
const couponCode = subscription?.CouponCode || '';
const isPaying = hasMailPlus(subscription) || hasVpnBasic(subscription) || hasVpnPlus(subscription);
const noPro = !hasMailProfessional(subscription);
const noBundle = !(hasMailPlus(subscription) && hasVpnPlus(subscription));
const noBFCoupon = ![BLACK_FRIDAY.COUPON_CODE].includes(couponCode);
const noAddons = !hasAddons(subscription);
return isPaying && noPro && noBundle && noBFCoupon && noAddons;
};
| Remove end limit for product payer promo | Remove end limit for product payer promo
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,4 +1,4 @@
-import { isWithinInterval } from 'date-fns';
+import { isWithinInterval, isAfter } from 'date-fns';
import { BLACK_FRIDAY, PRODUCT_PAYER } from '../constants';
import { Subscription } from '../interfaces';
@@ -13,7 +13,7 @@
};
export const isProductPayerPeriod = () => {
- return isWithinInterval(new Date(), { start: PRODUCT_PAYER.START, end: PRODUCT_PAYER.END });
+ return isAfter(new Date(), PRODUCT_PAYER.START);
};
export const isProductPayer = (subscription: Subscription) => { |
7eea6ea0fea136bbd48bb9f60cb9015aed1df37e | src/js/Filter/Filter.ts | src/js/Filter/Filter.ts | ///<reference path="./Interfaces/IFilter.ts" />
///<reference path="./Interfaces/IFilterFunction.ts" />
import * as clone from 'lodash/clone';
class Filter<T> implements IFilter<T>
{
private filterFunctions: IFilterFunction<T>[] = [];
private originalDataSet: T[] = [];
private filteredDataSet: T[] = [];
private ruleSet: any = {};
constructor(dataSet: T[], ruleSet: any)
{
this.originalDataSet = dataSet;
this.ruleSet = ruleSet;
}
public addFilterFunction = (filterFunc: IFilterFunction<T>): IFilter<T> =>
{
this.filterFunctions.push(filterFunc);
return this;
}
public addFilterFunctions = (filterFunctions: IFilterFunction<T>[]): IFilter<T> =>
{
filterFunctions.forEach(f => this.filterFunctions.push(f));
return this;
}
public filter = (): T[] =>
{
this.filteredDataSet = clone(this.originalDataSet);
for (var i = 0; i < this.filterFunctions.length; i ++) {
let func = this.filterFunctions[i];
this.filteredDataSet = func(this.filteredDataSet, this.ruleSet);
}
return this.originalDataSet;
}
};
| ///<reference path="./Interfaces/IFilter.ts" />
///<reference path="./Interfaces/IFilterFunction.ts" />
import * as clone from 'lodash/clone';
class Filter<T> implements IFilter<T>
{
private filterFunctions: IFilterFunction<T>[] = [];
private originalDataSet: T[] = [];
private filteredDataSet: T[] = [];
private ruleSet: any = {};
constructor(dataSet: T[], ruleSet: any)
{
this.originalDataSet = dataSet;
this.ruleSet = ruleSet;
}
public addFilterFunction = (filterFunc: IFilterFunction<T>): IFilter<T> =>
{
this.filterFunctions.push(filterFunc);
return this;
}
public addFilterFunctions = (filterFunctions: IFilterFunction<T>[]): IFilter<T> =>
{
filterFunctions.forEach(f => this.filterFunctions.push(f));
return this;
}
public filter = (): T[] =>
{
this.filteredDataSet = clone(this.originalDataSet);
for (var i = 0; i < this.filterFunctions.length; i++) {
let func = this.filterFunctions[i];
this.filteredDataSet = func(this.filteredDataSet, this.ruleSet);
}
return this.filteredDataSet;
}
};
export default Filter; | Fix filter to return the filtered data set lol | Fix filter to return the filtered data set lol
| TypeScript | mit | harksys/HawkEye,harksys/HawkEye,harksys/HawkEye | ---
+++
@@ -36,13 +36,15 @@
public filter = (): T[] =>
{
this.filteredDataSet = clone(this.originalDataSet);
- for (var i = 0; i < this.filterFunctions.length; i ++) {
+ for (var i = 0; i < this.filterFunctions.length; i++) {
let func = this.filterFunctions[i];
this.filteredDataSet = func(this.filteredDataSet, this.ruleSet);
}
- return this.originalDataSet;
+ return this.filteredDataSet;
}
};
+
+export default Filter; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.