blob_id
large_stringlengths 40
40
| language
large_stringclasses 1
value | repo_name
large_stringlengths 5
119
| path
large_stringlengths 4
271
| score
float64 2.52
4.84
| int_score
int64 3
5
| text
stringlengths 26
4.09M
|
|---|---|---|---|---|---|---|
a50260b604133f94a9018129adacba926844054d
|
TypeScript
|
JLL32/js-algorithms-data-structures
|
/src/data-structures/linked-lists/double-linked-list.ts
| 4.0625
| 4
|
class Node<T> {
constructor(
public value: T,
public next: Node<T> | null = null,
public previous: Node<T> | null = null) { }
}
class LinkedList<T> {
head: Node<T>;
tail: Node<T>;
length: number;
constructor(value: T) {
this.head = {
value: value,
next: null,
previous: null,
};
this.tail = this.head;
this.length = 1;
}
append(value: T) {
let newNode = new Node<T>(value);
newNode.previous = this.tail;
this.tail.next = newNode;
this.tail = newNode;
this.length++;
}
prepend(value: T) {
let newNode = new Node<T>(value);
newNode.next = this.head;
this.head.previous = newNode;
this.head =newNode;
this.length++;
}
insert(index: number, value: T) {
if (index >= this.length) {
return this.append(value);
} else if (index <= 0) {
return this.prepend(value);
}
let newNode = new Node<T>(value);
let follower = this.traverseToIndex(index);
let leader = follower.previous;
if (leader && leader.next) {
newNode.next = follower;
follower.previous = newNode;
leader.next = newNode;
newNode.previous = leader;
}
this.length++;
}
remove(index: number) {
let toRemove = this.traverseToIndex(index);
let leader = this.traverseToIndex(index - 1);
let follower = this.traverseToIndex(index + 1)
leader.next = follower;
follower.previous = leader;
toRemove.next = null;
toRemove.previous = null;
this.length--;
}
toArray(): T[] {
let nodeArray = new Array();
let currentNode: Node<T> = this.head;
while (currentNode) {
nodeArray.push(currentNode.value);
if (currentNode.next) {
currentNode = currentNode.next;
} else {
break;
}
}
return nodeArray;
}
traverseToIndex(index: number): Node<T> {
if (index <= 0) { return this.head; }
let currentNode: Node<T> = this.head;
while (currentNode && index--) {
if (currentNode.next) { currentNode = currentNode.next; }
}
return currentNode;
}
}
let myLinkedList = new LinkedList<number>(10);
myLinkedList.append(599);
myLinkedList.prepend(0);
myLinkedList.insert(2, 55);
myLinkedList.remove(1);
console.log(myLinkedList.toArray());
console.log(myLinkedList);
export { };
|
f565c24e8e62ae6ad12bda9af019f2452c536e29
|
TypeScript
|
Augani/hire-me
|
/src/utils/utils.ts
| 2.5625
| 3
|
export async function Http(
request: RequestInfo,
options?: any
): Promise<any> {
const response = await fetch(request, options);
const body = await response.json();
return body;
}
interface ITokens {
accessToken: string;
groupId: string;
institutionId: string;
}
const Tokens: ITokens = {
accessToken: "234ffdb8-0889-4be3-b096-97ab1679752c",
groupId: '11fc220c-ebba-4e55-9346-cd1eed714620',
institutionId: 'fb6c8114-387e-4051-8cf7-4e388a77b673'
}
const MainUrl:string = "https://tryfamly.co/api/daycare/tablet/group"
const CheckInUrl:string = "https://tryfamly.co/api/v2/children/"
export const Fetch = (type: 'getChildren' | 'checkInChild' | 'checkOutChild', id?:string, time?:string)=>{
switch(type){
case 'getChildren':
return Http(MainUrl + `?accessToken=${Tokens.accessToken}&groupId=${Tokens.groupId}&institutionId=${Tokens.institutionId}`);
case 'checkInChild':
let formData = new FormData();
if(!time)return null;
formData.append('pickupTime', time);
formData.append('accessToken', Tokens.accessToken);
const paramsIn = {
method: "post",
body: formData
}
return Http(CheckInUrl+`${id}/checkins`, paramsIn)
case "checkOutChild":
let formDataOut = new FormData();
formDataOut.append('accessToken', Tokens.accessToken);
const paramsOut = {
method: "post",
body: formDataOut
}
return Http(CheckInUrl+`${id}/checkout`, paramsOut)
default:
return null;
}
}
|
d576c1b2a1119979bb2a4618c5e013ca108310f6
|
TypeScript
|
appliedblockchain/parser-combinators
|
/then.ts
| 2.671875
| 3
|
import type { Parser as P } from './types/parser.js'
export const then =
<A, B>(a: P<A>, f: (_: A) => P<B>): P<B> =>
input => {
const [ s, r ] = a(input)
return f(r)(s)
}
export default then
|
310f11ec2d4bdc7742eef8287307e2610c918fe9
|
TypeScript
|
daxingyou/Mafia
|
/client20689/client514/PalaceWar/src/core/component/RewardFly.ts
| 2.578125
| 3
|
/**
* 奖励物品icon、文字飘动动画
* author dmj
* date 2017/9/27
* @class RewardFly
*/
class RewardFly extends BaseDisplayObjectContainer
{
private _tw:egret.Tween;
private _temScale:number = 0.6;
public constructor()
{
super();
}
public init(icon:string,message:string,itemtype:number=0):void
{
SoundManager.playEffect(SoundConst.EFFECT_SHOWTIP);
let container:BaseDisplayObjectContainer = new BaseDisplayObjectContainer();
this.addChild(container);
let temX:number = 0;
let temY:number = 0;
let iconBt:BaseBitmap=null;
let bgPic = "public_itemtipbg2";
if(icon){
bgPic = "public_itemtipbg";
}
let numBg = BaseBitmap.create(bgPic);
// numBg.width = 300;
// numBg.setScale(this._temScale);
container.addChild(numBg);
// temX = numBg.width * this._temScale;
// temY = numBg.height * this._temScale/2;
if(icon)
{
let iconBg = BaseBitmap.create("public_tipiconbg");
// iconBg.setScale(this._temScale);
container.addChild(iconBg);
let rect:egret.Rectangle=egret.Rectangle.create();
rect.setTo(0,0,100,100);
iconBt = BaseLoadBitmap.create(icon,rect);
iconBt.setScale(this._temScale);
if(itemtype==10||itemtype==8)
{
iconBt.scaleX =iconBt.scaleY =0.5;
}
container.addChild(iconBt);
// temX = iconBt.width * this._temScale;
// temY = iconBt.height * this._temScale/2;
// iconBt.setScale(0.7);
numBg.x = 40;
numBg.y = iconBt.y + iconBt.height*0.7/2 - numBg.height/2 - 5;
}
let msgTF:BaseBitmapText = ComponentManager.getBitmapText(message,TextFieldConst.FONTNAME_ITEMTIP);
if(iconBt)
{
temX = iconBt.width * iconBt.scaleX;
temY = iconBt.height * iconBt.scaleY/2;
}
msgTF.x = temX;
msgTF.y = temY - msgTF.height/2;
numBg.width = msgTF.width + 50;
msgTF.x = temX;
if(iconBt)
{
msgTF.y = iconBt.y + iconBt.height*0.7/2 - msgTF.height/2;
msgTF.y = numBg.y + numBg.height/2 - msgTF.height/2;
}
else
{
msgTF.x=numBg.x+(numBg.width-msgTF.width)/2;
msgTF.y = numBg.y + numBg.height/2 - msgTF.height/2;
}
container.addChild(msgTF);
// if(message)
// {
// let msgTF:BaseTextField = ComponentManager.getTextField(message,30);
// if(iconBt)
// {
// temX = iconBt.width * iconBt.scaleX;
// temY = iconBt.height * iconBt.scaleY/2;
// }
// msgTF.x = temX;
// if(iconBt)
// {
// msgTF.y = iconBt.y + iconBt.height*0.7/2 - msgTF.height/2;
// }
// else
// {
// msgTF.x=numBg.x+(numBg.width-msgTF.width)/2;
// msgTF.y = numBg.y + numBg.height/2 - msgTF.height/2;
// }
// container.addChild(msgTF);
// if(msgTF.width+30>numBg.width)
// {
// numBg.width = msgTF.width + 30;
// }
// }
container.x = -container.width/2;
this._tw = egret.Tween.get(container);
this._tw.to({y:-80},1500).call(this.onComplete,this);
}
private onComplete():void
{
if(this._tw)
{
egret.Tween.removeTweens(this._tw);
this._tw = null;
}
this.dispose();
}
public dispose():void
{
if(this._tw)
{
egret.Tween.removeTweens(this._tw);
this._tw = null;
}
this._temScale = 0.6;
super.dispose();
}
}
|
6fca8b20614f52b8591200832a911869ed641224
|
TypeScript
|
ivaylopivanov/wamp-server
|
/test/all/message.ts
| 2.671875
| 3
|
import { expect } from 'chai';
import { SocketMessageInterface } from '../../src/interfaces';
import Message from '../../src/message';
describe('Message', () => {
it('Should get parsed message', () => {
const ar: any[] = [
1,
'com.some.realm',
{},
];
const msg: string = JSON.stringify(ar);
const message: SocketMessageInterface = new Message(msg).getMessage();
expect(message).to.be.a('object');
expect(message).to.has.property('type');
expect(message).to.has.property('id');
expect(message).to.has.property('incoming');
expect(message.incoming).to.be.a('array');
});
it('Should not fail if the Message is init. with an empty string', () => {
const message: SocketMessageInterface = new Message('').getMessage();
expect(message).to.be.a('object');
expect(message).to.has.property('type');
expect(message).to.has.property('id');
expect(message).to.has.property('incoming');
expect(message.incoming).to.be.a('array');
});
});
|
ba33dbb7306090615f96cceb9e0791b07042af0d
|
TypeScript
|
HajoAhoMantila/io-ts-builder
|
/tests/IoTsBuilder.test.ts
| 3.09375
| 3
|
import * as t from 'io-ts'
import { IoTsBuilder } from '../src'
const Order = t.type({
description: t.string,
id: t.number
})
type IOrder = t.TypeOf<typeof Order>
describe('io-ts-builder', () => {
it('should build a valid object', () => {
const order: IOrder = IoTsBuilder(Order)
.id(4)
.description('foo')
.build()
expect(() => Order.decode(order)).not.toThrow()
expect(order).toEqual({ id: 4, description: 'foo' })
})
it('should throw error when trying to build an invalid object', () => {
const builder = IoTsBuilder(Order).id(4)
expect(builder.build).toThrow('description')
})
describe('with template object', () => {
it('should create a copy of the template object', () => {
const template: IOrder = { description: 'foo', id: 42 }
const order: IOrder = IoTsBuilder(Order, template).build()
expect(order).toEqual(template)
})
it('should build a modified template object', () => {
const template: IOrder = { description: 'foo', id: 42 }
const order: IOrder = IoTsBuilder(Order, template)
.id(19)
.build()
expect(order).toEqual({ description: 'foo', id: 19 })
})
it('should not modify the template object', () => {
const template: IOrder = { description: 'foo', id: 42 }
const order: IOrder = IoTsBuilder(Order, template)
.id(19)
.build()
expect(order.id).toEqual(19)
expect(template.id).toEqual(42)
})
it('should reject an invalid template object', () => {
const template: IOrder = { description: 'foo' } as IOrder
expect(() => IoTsBuilder(Order, template)).toThrow('id')
})
})
})
|
ef9c294542b66ac3d31571502bbd9ed72a02749f
|
TypeScript
|
NGromann/Preproc
|
/src/lib/ExpressionParser.ts
| 3.0625
| 3
|
import { Expression, ExpressionType } from './Expression';
const openingExpr = /\{\{/g;
const closingExpr = /\}\}/g;
const quoteExpr = /(?<!\\)\"/g;
const expressionFilterTypeMap: { [regex: string]: number } = {
"^\\s*else if ([\\s\\S]*)\\s*$" : ExpressionType.ElseCondition, // [\\s\\S] workaround for missing dot-all flag
"^\\s*if ([\\s\\S]*)\\s*$" : ExpressionType.Condition,
"^\\s*else\\s*$" : ExpressionType.Else,
"^\\s*end\\s*$" : ExpressionType.BlockEnd,
"^\\s*\\=([\\s\\S]*)\\s*$" : ExpressionType.Assignment,
"^\\s*\\:([\\s\\S]*)\\s*$" : ExpressionType.Execution,
};
const logMatch = (match: RegExpMatchArray) => console.log(`Found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`);
export function findExpressionsInText(content: string) {
let openingMatches = Array.from(content.matchAll(openingExpr));
let closingMatches = Array.from(content.matchAll(closingExpr));
let quoteMatches = Array.from(content.matchAll(quoteExpr));
if (quoteMatches.length % 2 > 0) {
throw Error("Closing quote expected.");
}
// Iterate through the quote pairs
for (let i = 0; i < quoteMatches.length; i += 2) {
const openingQuoteMatch = quoteMatches[i];
const closingQuoteMatch = quoteMatches[i+1];
openingMatches = openingMatches.filter(x => x.index < openingQuoteMatch.index || x.index > closingQuoteMatch.index);
closingMatches = closingMatches.filter(x => x.index < openingQuoteMatch.index || x.index > closingQuoteMatch.index);
}
let expressions = [];
for (const openingMatch of openingMatches) {
// Find the next closingExpression
const closingMatch = closingMatches.find(x => x.index > openingMatch.index);
if (!closingMatch) {
throw Error("Expected }}");
}
const expressionStart = openingMatch.index;
const expressionEnd = closingMatch.index + closingMatch[0].length;
const expressionContentStart = openingMatch.index + openingMatch[0].length;
const expressionContentEnd = closingMatch.index;
const expressionText = content.substring(expressionContentStart, expressionContentEnd).trim();
let expressionType = null;
let expressionContent = null;
for (const expressionFilter of Object.keys(expressionFilterTypeMap)) {
const match = new RegExp(expressionFilter).exec(expressionText);
if (match != null) {
expressionType = expressionFilterTypeMap[expressionFilter];
if (match.length >= 2) {
expressionContent = match[1].trim();
}
break;
}
}
if (expressionType == null) {
throw Error(`Operator expected in ${expressionText}`);
}
expressions.push(new Expression(expressionText, expressionType, expressionContent, expressionStart, expressionEnd));
}
return expressions;
}
|
758a2731dffb20aac6672569ef4f6a8d644afcb1
|
TypeScript
|
Spiffo/frontend-1
|
/src/tools/filter-repositories-by-input.ts
| 2.640625
| 3
|
import { Repository } from "../data/common";
export function filterRepositoriesByInput(
repositories: Repository[],
filter: string
): Repository[] {
const _lowcaseFilter = stringify(filter);
return repositories.filter(
(_repo) =>
stringify(_repo.name)?.includes(_lowcaseFilter) ||
stringify(_repo.description)?.includes(_lowcaseFilter) ||
stringify(_repo.category)?.includes(_lowcaseFilter) ||
stringify(_repo.full_name)?.includes(_lowcaseFilter) ||
stringify(_repo.authors)?.includes(_lowcaseFilter) ||
stringify(_repo.domain)?.includes(_lowcaseFilter)
);
}
const stringify = (str: any): string => {
return String(str).toLocaleLowerCase().replace(/-|_| /g, "");
};
|
41a67c0e12769404af4587a31644a95638ba8b69
|
TypeScript
|
djr-taureau/angular8-ngrx-monorepo
|
/libs/shared/src/lib/models/state/utilities.ts
| 3
| 3
|
import { Observable, combineLatest } from 'rxjs';
import { map as rxMap } from 'rxjs/operators'
import { assoc, assocPath, pipe, values } from 'ramda';
import { LoadDataStatus, DataState } from './entity-state';
import { indexByProp } from '../../utility/object';
/**
* Helper method to set the status in State;
*/
const updateDataStatus = (status: string) => assoc('status', status);
/**
* Sets the status in State to "loading"
*/
export const setLoadingState = updateDataStatus(LoadDataStatus.loading);
/**
* Sets the status in State to "loaded"
*/
export const setLoadedState = updateDataStatus(LoadDataStatus.loaded);
/**
* Updates all Entities in State
*/
export const setEntities = <T, S>(entities: Array<T>, state: S) =>
assoc('entities', indexByProp('guid', entities), state) as S;
/**
* Updates a property of an Entity in state
*/
export const setEntityProp = (...props: string[]) => <V, S>(
id: string,
value: V,
state: S
) => assocPath<V, S>(['entities', id, ...props], value, state) as S;
/**
* Updates an Entity in state
*/
export const setEntity = <V, S>(id: string, value: V, state: S) =>
assocPath<V, S>(['entities', id], value, state) as S;
/**
* function signature for `setDataState`
*/
type SetDataStateFn = <P, T>(payload: Array<P>, state: T) => T;
/**
* Updates Entities in state and set the status to loaded
*/
export const setDataState = <SetDataStateFn>pipe(setEntities, setLoadedState);
/**
* Calculates the State of the requested dataset from state
*/
const calculateDataState = ([loaded, count]: [boolean, number]): DataState => {
if (!loaded) {
return LoadDataStatus.loading;
} else if (loaded && count > 0) {
return LoadDataStatus.loaded;
} else if (loaded && count < 1) {
return LoadDataStatus.empty;
}
return LoadDataStatus.error;
};
/**
* Calculates the State of the requested dataset from the count and loadStatus
*/
export const getDatasetState = (loaded$: Observable<boolean>, count$: Observable<number>) => {
return combineLatest(
loaded$,
count$
).pipe(rxMap(calculateDataState));
}
|
0607b65c34a3ede305f78188e1c5931853acc610
|
TypeScript
|
hanFengSan/eHunter
|
/src/platform/eh/parser/IntroHtmlParser.ts
| 2.71875
| 3
|
import { ImgPageInfo } from '../../../../core/bean/ImgPageInfo'
import { ThumbInfo, ThumbMode } from '../../../../core/bean/ThumbInfo'
// a parser for album's intro page
export class IntroHtmlParser {
private html: HTMLElement;
private reqUrl: string;
constructor(html, reqUrl) {
this.html = document.createElement('html');
this.reqUrl = reqUrl; // the request url. It's maybe different with introUrl in more thumbs mode
this.html.innerHTML = html.replace(/src=/g, 'x-src='); // avoid load assets
// this.document = this.html.ownerDocument!;
}
getImgUrls(): Array<ImgPageInfo> {
if (this._isValidIntroPage()) {
return Array.prototype.slice.call(this.html.getElementsByClassName('gdtm'), 0).map(item => {
item.children[0].getAttribute('style').match(/width:(.*?)px; height:(.*?)px;/g);
const thumbHeight = Number(RegExp.$2);
const thumbWidth = Number(RegExp.$1);
let pageUrl = item.getElementsByTagName('a')[0].getAttribute('href').match(/\/s.*$/) + '';
return {
id: pageUrl,
index: 0,
pageUrl,
src: '',
thumbHeight,
thumbWidth,
heightOfWidth: thumbHeight / thumbWidth
};
})
} else {
return [];
}
}
getThumbObjList(sumOfPage, albumId): Array<ThumbInfo> {
return this._computeThumbList(this._getThumbImgList(albumId, sumOfPage), sumOfPage);
}
_getThumbKeyId() {
let tmp = this.html.getElementsByClassName('gdtm')![0].children![0].getAttribute('style')!.match(/m\/.*?\//);
return (tmp + '').replace(/(m|\/)/g, '');
}
_getThumbPageCount(sumOfPage) {
// 20 is the img sum per spirit in small thumb model
if (sumOfPage < 20) {
return 1;
}
let reminder = sumOfPage % 20;
if (reminder > 1) {
return (sumOfPage - reminder) / 20 + 1;
} else {
return sumOfPage / 20;
}
}
_getThumbImgList(albumId, sumOfPage): string[] {
let thumbKeyId = this._getThumbKeyId();
let imgList: string[] = [];
for (let i = 0; i < this._getThumbPageCount(sumOfPage); i++) {
if (window.location.hostname === 'e-hentai.org') {
imgList.push(`https://ehgt.org/m/${thumbKeyId}/${albumId}-${i < 10 ? '0' + i : i}.jpg`);
} else {
imgList.push(`https://s.exhentai.org/m/${thumbKeyId}/${albumId}-${i < 10 ? '0' + i : i}.jpg`);
}
}
return imgList;
}
_getTruePageIndex() {
return Number(this.html.getElementsByClassName('ptds')[0].textContent) - 1;
}
_isValidIntroPage() {
// In more thumbs mode, it will have many repeated intro page requests because the error of count of intro pages.
// For the speed first, I don't fix the bug of the error, but discard the repeated intro page requests by validating
// index.
if (this.reqUrl && this.reqUrl.includes('?p=')) {
let reqIndex = Number(this.reqUrl!.match(/\?p=[0-9]+/g)![0].replace('?p=', ''));
if (this._getTruePageIndex() !== reqIndex) {
return false;
}
}
return true;
}
_computeThumbList(imgList, sumOfPage): Array<ThumbInfo> {
let thumbObjList: Array<ThumbInfo> = [];
for (let i = 0; i < imgList.length; i++) {
for (let t = 0; t < 20; t++) {
if (i !== imgList.length - 1 ||
(t < (sumOfPage % 20 || 20))
) {
thumbObjList.push({
id: imgList[i] + t,
src: imgList[i],
mode: ThumbMode.SPIRIT,
offset: t * 100
})
}
}
}
return thumbObjList;
}
}
|
b35f2207bc468e8b18a54bfb5c6436356756bd0f
|
TypeScript
|
shamirshahul/user-interfaces
|
/libs/organisation/src/lib/desk.class.ts
| 2.734375
| 3
|
export class Desk {
/** ID of the desk also map_id */
public readonly id: string;
/** Name of the desk */
public readonly name: string;
/** Whether desk is available / bookable */
public readonly bookable: boolean;
/** Zone/Level of the desk */
public readonly zone: any;
/** Group/Department allocated to the desk */
public readonly groups: string[];
constructor(data) {
this.id = data.id;
this.name = data.name;
this.bookable = data.bookable;
this.zone = data.zone;
this.groups = data.groups || [];
}
public format() {
const { id, name, bookable, groups } = this;
return {
id,
name,
bookable,
groups,
};
}
}
|
159f209bc6515b6703641f994df53d36eb401e06
|
TypeScript
|
MehdiSaeedifar/ag-grid
|
/charts-packages/ag-charts-community/src/chart/markerLabel.ts
| 2.5625
| 3
|
import { Group } from "../scene/group";
import { Text, FontStyle, FontWeight } from "../scene/shape/text";
import { Square } from "./marker/square";
import { Marker } from "./marker/marker";
import { HdpiCanvas } from "../canvas/hdpiCanvas";
export class MarkerLabel extends Group {
static className = 'MarkerLabel';
private label = new Text();
constructor() {
super();
const label = this.label;
label.textBaseline = 'middle';
label.fontSize = 12;
label.fontFamily = 'Verdana, sans-serif';
label.fill = 'black';
// For better looking vertical alignment of labels to markers.
label.y = HdpiCanvas.has.textMetrics ? 1 : 0;
this.append([this.marker, label]);
this.update();
}
set text(value: string) {
this.label.text = value;
}
get text(): string {
return this.label.text;
}
set fontStyle(value: FontStyle | undefined) {
this.label.fontStyle = value;
}
get fontStyle(): FontStyle | undefined {
return this.label.fontStyle;
}
set fontWeight(value: FontWeight | undefined) {
this.label.fontWeight = value;
}
get fontWeight(): FontWeight | undefined {
return this.label.fontWeight;
}
set fontSize(value: number) {
this.label.fontSize = value;
}
get fontSize(): number {
return this.label.fontSize;
}
set fontFamily(value: string) {
this.label.fontFamily = value;
}
get fontFamily(): string {
return this.label.fontFamily;
}
set color(value: string | undefined) {
this.label.fill = value;
}
get color(): string | undefined {
return this.label.fill;
}
private _marker: Marker = new Square();
set marker(value: Marker) {
if (this._marker !== value) {
this.removeChild(this._marker);
this._marker = value;
this.appendChild(value);
this.update();
}
}
get marker(): Marker {
return this._marker;
}
private _markerSize: number = 15;
set markerSize(value: number) {
if (this._markerSize !== value) {
this._markerSize = value;
this.update();
}
}
get markerSize(): number {
return this._markerSize;
}
set markerFill(value: string | undefined) {
this.marker.fill = value;
}
get markerFill(): string | undefined {
return this.marker.fill;
}
set markerStroke(value: string | undefined) {
this.marker.stroke = value;
}
get markerStroke(): string | undefined {
return this.marker.stroke;
}
set markerStrokeWidth(value: number) {
this.marker.strokeWidth = value;
}
get markerStrokeWidth(): number {
return this.marker.strokeWidth;
}
set markerFillOpacity(value: number) {
this.marker.fillOpacity = value;
}
get markerFillOpacity(): number {
return this.marker.fillOpacity;
}
set markerStrokeOpacity(value: number) {
this.marker.strokeOpacity = value;
}
get markerStrokeOpacity(): number {
return this.marker.strokeOpacity;
}
set opacity(value: number) {
this.marker.opacity = value;
this.label.opacity = value;
}
get opacity(): number {
return this.marker.opacity;
}
private _spacing: number = 8;
set spacing(value: number) {
if (this._spacing !== value) {
this._spacing = value;
this.update();
}
}
get spacing(): number {
return this._spacing;
}
private update() {
const marker = this.marker;
const markerSize = this.markerSize;
marker.size = markerSize;
this.label.x = markerSize / 2 + this.spacing;
}
}
|
fa2be950bb998c99d3e7757c1ec4a5903b3ff43f
|
TypeScript
|
wswebcreation/webdriver-image-comparison
|
/lib/clientSideScripts/getElementPositionTopScreenNativeMobile.ts
| 3
| 3
|
import { ElementPosition } from './elementPosition.interfaces';
/**
* Get the element position to the top of the screen of the device, not the top of the webview
* This method is used for Android native and iOS screenshots
*/
export function getElementPositionTopScreenNativeMobile(
element: HTMLElement,
{
isLandscape,
safeArea,
screenHeight,
screenWidth,
sideBarWidth,
statusBarAddressBarHeight,
}: {
isLandscape: boolean;
safeArea: number;
screenHeight: number;
screenWidth: number;
sideBarWidth: number;
statusBarAddressBarHeight: number;
},
): ElementPosition {
// Get some heights and widths
const { innerHeight } = window;
// Determine element position
const elementPosition = element.getBoundingClientRect();
let y;
if (screenHeight === innerHeight || screenWidth === innerHeight) {
/* an app with a transparent statusbar */
y = elementPosition.top;
} else {
y = statusBarAddressBarHeight + elementPosition.top;
}
return {
height: elementPosition.height,
width: elementPosition.width,
x: elementPosition.left + (isLandscape ? safeArea : 0) + sideBarWidth,
y: y,
};
}
|
1bc1561fd2cff4a26c17ce63b803e343c09b9223
|
TypeScript
|
EdgarGGamartgo/js-nodejs-concepts
|
/src/services/Recursiveness/company.ts
| 3.0625
| 3
|
export const myCompany = {
sales: [{ name: "Allie", salary: 1000 }, { name: "Allie", salary: 1000 }],
development: {
sites: [{ name: "Jeff", salary: 1000 }, { name: "Mike", salary: 1000 }],
marketing: [{ name: "Sophie", salary: 1000 }, { name: "Edgar", salary: 1000 }],
maintanance: {
legacy: [{ name: "Sophie", salary: 1000 }, { name: "Edgar", salary: 1000 }],
sporadic: [{ name: "Sophie", salary: 1000 }, { name: "Edgar", salary: 1000 }]
}
}
}
export const myOtherCompany = [{ name: "Allie", salary: 1000 }, { name: "Allie", salary: 1000 }]
export const sumSalaries = (company: any) => {
if (Array.isArray(company)) {
return company.reduce((prevValue, current) => prevValue + current.salary, 0);
} else {
let sum = 0;
for (const e of Object.values(company)) {
sum += sumSalaries(e)
}
return sum
}
}
|
de74babc28a75f26496525eb117cd75bbd6ffed1
|
TypeScript
|
TrySpace/babylonjs-typescript-webpack-starter
|
/src/shark.ts
| 2.703125
| 3
|
import { AbstractMesh, WaterMaterial } from "babylonjs";
import { SceneInstance } from './SceneInstance';
import { BehaviorSubject } from 'rxjs';
import { SharkMesh } from "./Meshes";
export class Shark {
private _sharkMesh: AbstractMesh;
private _waterMaterial: WaterMaterial;
public swimming: BehaviorSubject<boolean>;
public sharkAnimationTime = 0;
public firstVertex: any;
constructor (sceneInstance: SceneInstance, waterMaterial: WaterMaterial) {
this.swimming = new BehaviorSubject(false);
sceneInstance.scene.registerBeforeRender(() => {
let deltaTime: number = (1 / sceneInstance.renderCanvas.engine.getFps());
this.debugFirstMeshCoordinate(this._sharkMesh as BABYLON.Mesh);
this.animateShark(deltaTime);
});
this._waterMaterial = waterMaterial;
this.createTheShark(sceneInstance);
}
createTheShark (sceneInstance: SceneInstance) {
// create a shark mesh from an obj file
new SharkMesh(sceneInstance.scene).getObservableMesh()
.subscribe(sharkMesh => {
this._sharkMesh = sharkMesh;
this._sharkMesh.getChildren().forEach(
mesh => {
this._waterMaterial.addToRenderList(mesh);
}
);
});
}
animateShark(deltaTime: number): void {
// console.log(this.swimming.getValue());
if (this._sharkMesh && this.swimming.getValue()) {
this.sharkAnimationTime += 0.01;
this._sharkMesh.getChildren().forEach(
mesh => {
let realMesh = <BABYLON.Mesh> mesh;
let vertexData = BABYLON.VertexData.ExtractFromMesh(realMesh);
let positions = vertexData.positions;
let numberOfPoints = positions.length / 3;
for (let i = 0; i < numberOfPoints; i++) {
let vertex = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
vertex.x += (Math.sin(0.15 * vertex.z + this.sharkAnimationTime * 4 - 1.6) * 0.05);
positions[i * 3] = vertex.x;
}
vertexData.applyToMesh(mesh as BABYLON.Mesh);
}
);
}
}
/**
* Sets the coordinates of the first vertex of mesh
*/
public debugFirstMeshCoordinate(mesh: BABYLON.Mesh) {
if(!mesh || !mesh.getChildren()) {
return;
}
let firstMesh = (mesh.getChildren()[0] as BABYLON.Mesh)
let vertexData = BABYLON.VertexData.ExtractFromMesh(firstMesh);
let positions = vertexData.positions;
this.firstVertex = new BABYLON.Vector3(positions[0], positions[1], positions[3]);
}
}
|
ab0403c38fda9cbe70a207e1a864b03e5a71585f
|
TypeScript
|
VEuPathDB/WDKClient
|
/Client/src/StoreModules/UserPasswordChangeStoreModule.ts
| 2.78125
| 3
|
import { Action } from 'wdk-client/Actions';
import {
PASSWORD_FORM_UPDATE,
PASSWORD_FORM_SUBMISSION_STATUS
} from 'wdk-client/Actions/UserActions';
export const key = 'passwordChange';
export type State = {
formStatus: 'new' | 'modified' | 'pending' | 'success' | 'error';
errorMessage?: string;
passwordForm: {
oldPassword: string;
newPassword: string;
confirmPassword: string;
}
}
const defaultState: State = {
passwordForm: getEmptyForm(),
formStatus: 'new', // Values: [ 'new', 'modified', 'pending', 'success', 'error' ]
errorMessage: undefined
};
export function reduce(state: State = defaultState, action: Action): State {
switch (action.type) {
case PASSWORD_FORM_UPDATE:
return {
...state,
passwordForm: action.payload,
formStatus: 'modified'
};
case PASSWORD_FORM_SUBMISSION_STATUS:
return {
...state,
// in all status update cases, we should clear passwords
passwordForm: getEmptyForm(),
formStatus: action.payload.formStatus,
errorMessage: action.payload.errorMessage,
};
default:
return state;
}
}
function getEmptyForm() {
return {
oldPassword: '',
newPassword: '',
confirmPassword: ''
};
}
|
1e5c8ac3ac06c0d0ddd4c06c347b8ea860de33a3
|
TypeScript
|
nkohari/nate.io
|
/src/util/search.ts
| 2.921875
| 3
|
import escapeStringForRegexp from 'escape-string-regexp';
import {Article} from '@nkohari/apocrypha';
import {Metadata} from 'src/types';
export const search = (
articles: Article<Metadata>[],
query: string | null,
): Article<Metadata>[] => {
const isMatch = (article: Article<Metadata>) => {
// Never match page or music articles.
if (article.metadata.type === 'page' || article.metadata.type === 'music') return false;
// If a query string was provided, use it to match.
if (query && query.length > 0) {
const regexp = new RegExp(escapeStringForRegexp(query), 'i');
const fields = [
article.metadata.title,
article.metadata.subtitle,
article.metadata.category,
article.metadata.excerpt,
];
return fields.some((field) => field?.match(regexp));
}
return true;
};
return articles
.filter(isMatch)
.sort((a, b) => b.metadata.date!.valueOf() - a.metadata.date!.valueOf());
};
|
06a7b580ce46df5da41a97cc02ff9064de4bbd4a
|
TypeScript
|
david-driscoll/IxJS
|
/src/add/iterable-operators/buffer.ts
| 2.71875
| 3
|
import { Iterable } from '../../iterable';
import { buffer } from '../../iterable/buffer';
Iterable.prototype.buffer = function<T>(count: number, skip?: number): Iterable<T[]> {
return buffer<T>(this, count, skip);
};
declare module '../../Iterable' {
interface Iterable<T> {
buffer(count: number, skip?: number): Iterable<T[]>
}
}
|
086987f4fa36b4378b0d6ad2429a953b30f2c20e
|
TypeScript
|
kcvgan/acmevalue
|
/src/domain/contracts/hooks/useGetContract.ts
| 2.625
| 3
|
import { useEffect, useState } from 'react';
import { Contract } from '../types/Contract';
import contractsService from '../api/contractsService';
export const useGetContract = (initialId?: string) => {
const [contract, setContract] = useState<Contract | undefined>();
const fetchContract = async (id: string) => {
const fetchedContract = await contractsService.getContract(id);
setContract(fetchedContract);
};
useEffect(() => {
if (initialId) {
fetchContract(initialId);
}
}, [initialId]);
return {
fetchContract,
contract,
};
};
|
5ff0201ebe5ab73dd3aac6a266bcc1c2d98ad2d3
|
TypeScript
|
frantoribio/Programacion-02-Ejercicios-2021-2022
|
/typescript/src/mod/mod-05-09-MSPinzon.ts
| 3.1875
| 3
|
export default {numeroCifras};
/**
* Función que calcula el número de cifras de un número.
* @param numero El número del que hay que hallar el número de cifras.
* @returns El número de cifras que tiene.
*/
function numeroCifras (numero : number) : number{
let contadorCifras : number = 0;
while(Math.floor(numero)!=0){
numero = numero/10;
contadorCifras++;
}
return contadorCifras;
}
|
fdb7546bf64de9ff6fba343de0395e3937207e6b
|
TypeScript
|
Spinnafre/EstudoTypescript
|
/src/types_annotation/Object.ts
| 3.265625
| 3
|
const objectA : { readonly name:string,age:number,sex?:string,[key:string]:unknown}={
name:'Davi',
age:19
}
console.log(objectA)
type MyType={
id:number,
name:string,
age:number
}
const peoples:MyType[]=[{id:0,name:"Davi Silva da Penha",age:19},{id:1,name:"Mr X",age:9}]
|
b443504098e4086cc9a609b3c939a55150393f39
|
TypeScript
|
paulstanyer/propertydemo
|
/client/src/core/paginationViewModel.ts
| 2.71875
| 3
|
import { makeObservable, observable } from "mobx";
export interface IPaginationViewModel<TResultItem> {
page: number;
itemsPerPage: number;
totalResults: number;
withPagination(results: TResultItem[]): TResultItem[];
}
export abstract class AbstractPaginationViewModel {
@observable page: number;
@observable itemsPerPage: number = 0;
@observable totalResults: number = 0;
constructor(page: number, itemsPerPage: number, totalResults: number) {
this.page = page;
this.itemsPerPage = itemsPerPage;
this.totalResults = totalResults;
makeObservable(this);
}
}
export class InMemoryPaginator<TResultItem>
extends AbstractPaginationViewModel
implements IPaginationViewModel<TResultItem> {
withPagination(results: TResultItem[]): TResultItem[] {
return results.slice(0);
}
}
export class SQLPaginator<TResultItem>
extends AbstractPaginationViewModel
implements IPaginationViewModel<TResultItem> {
withPagination(results: TResultItem[]): TResultItem[] {
return results;
}
}
|
5c44b235196e68aeac5a6b822b955e8b15348642
|
TypeScript
|
Meduzjam/portal.atm-servis.ru
|
/static/ng2/src/plan/components/department/detail.ts
| 2.65625
| 3
|
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Department } from '../../models';
export type DepartmentInput = Department;
export type SelectOutput = Department;
export type DeleteOutput = Department;
@Component({
selector: 'department-detail',
styles: [`
.selected {
background-color: #CFD8DC !important;
color: white;
}
`],
template: `
<div *ngIf="department">
<button
(click)="select.emit(department)"
[class.selected]="selected"
>{{ id }} - {{ name }} - {{ code }}</button>
<button (click)="delete.emit(department)">Удалить</button>
</div>
`
})
export class DepartmentDetailComponent {
@Input() department: DepartmentInput;
@Input() selected: boolean;
@Output() select = new EventEmitter<SelectOutput>();
@Output() delete = new EventEmitter<DeleteOutput>();
get id() {
return this.department.id;
}
get name() {
return this.department.name;
}
get code() {
return this.department.code;
}
}
|
f0a8042733ef4b81c3ed38a700a7ea569fd4b830
|
TypeScript
|
episodehunter/show-update
|
/src/red-keep/gql.ts
| 2.53125
| 3
|
export function gql(strings, ...keys): string {
const lastIndex = strings.length - 1;
return strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], '') + strings[lastIndex];
}
|
fc94382671f52c5eaa5441bbe5f9c15a25afbb32
|
TypeScript
|
anasjaber/Angular-QueryBuilder
|
/projects/angular2-query-builder/src/lib/query-builder/query-builder-expression.pipe.ts
| 2.828125
| 3
|
import {Pipe, PipeTransform, Query} from '@angular/core';
import {QueryBuilderConfig} from "./query-builder.interfaces";
@Pipe({name: 'expressionFormat', pure: false})
export class QueryBuilderExpressionPipe implements PipeTransform {
transform(query: Query, queryConfig: QueryBuilderConfig): string {
return this.computed(query, queryConfig);
}
defineCondition(rule){
return rule.condition ? rule.condition : rule.operator;
}
getInputType(config : QueryBuilderConfig, field: string, operator: string): string {
if (config.getInputType) {
return config.getInputType(field, operator);
}
if (!config.fields[field]) {
throw new Error(`No configuration for field '${field}' could be found! Please add it to config.fields.`);
}
const type = config.fields[field].type;
switch (operator) {
case 'is null':
case 'is not null':
return null; // No displayed component
case 'in':
case 'not in':
return type === 'category' || type === 'boolean' ? 'multiselect' : type;
default:
return type;
}
}
defineMultiselect(rule){
let value = rule.value || [];
return JSON.stringify(value);
}
defineString(rule){
let value = rule.value || "";
return JSON.stringify(value);
}
private defineDate(rule) {
let value = rule.value || "";
return JSON.stringify(value);
}
private defineNumber(rule) {
if (typeof rule.value === 'undefined'){
return "?";
}
return rule.value;
}
private defineBoolean(rule) {
let value = rule.value ? true : false;
return JSON.stringify(value);
}
defineValue(rule, queryConfig : QueryBuilderConfig){
let format = this.getInputType(queryConfig, rule.field, rule.operator);
if (!format){
return '';
}
switch (format){
case 'number' : return this.defineNumber(rule)
case 'boolean' : return this.defineBoolean(rule);
case 'string' : return this.defineString(rule)
case 'category' : return this.defineString(rule);
case 'multiselect' : return this.defineMultiselect(rule);
case 'date' : return this.defineDate(rule);
default : return this.defineString(rule)
}
}
computed = function (group, queryConfig) {
let str = "";
if (!group) {
return str;
}
str += " (";
let myMap = group.rules.map((rule) => {
let newStr = "";
if (rule.condition && rule.rules) {
newStr = this.computed(rule, queryConfig);
} else {
newStr = [rule.field,this.defineCondition(rule), this.defineValue(rule, queryConfig)].join(" ");
}
return newStr;
});
str += myMap.join(" " +group.condition.toUpperCase()+ " ");
str += ")";
return str;
};
}
|
f85634f81de1f7a4bd23967ff3b0e416bcc8b955
|
TypeScript
|
Litvinov1618/place-me
|
/src/modules/calculateDefaultPaidDays.ts
| 2.96875
| 3
|
import CustomDateRange from '../interfaces/CustomDateRange'
import FiniteDateRange from '../interfaces/FiniteDateRange'
const calculateDefaultPaidDays = (dateRange: CustomDateRange) => {
if (dateRange?.endDate) {
return dateRange as FiniteDateRange
}
const date = dateRange.startDate
const lastDayOfMonth = (year: number, month: number) => new Date(year, month + 1, 0)
const lastDayOfNextMonth = lastDayOfMonth(date.getFullYear(), date.getMonth() + 1)
if (
lastDayOfMonth(date.getFullYear(), date.getMonth()).getDate() === date.getDate() ||
date.getDate() > lastDayOfNextMonth.getDate()
) return { startDate: dateRange.startDate, endDate: lastDayOfNextMonth }
else {
const endDate = new Date(date.getFullYear(), date.getMonth() + 1, date.getDate())
return { startDate: dateRange.startDate, endDate }
}
}
export default calculateDefaultPaidDays
|
2915495fe54662208265fe655553f8dd766f5c9e
|
TypeScript
|
atahanyorganci/jukebox
|
/src/commands/resume.ts
| 2.78125
| 3
|
import { Command, CommandContext } from "~/commands/index.js";
import JukeBox from "~/music/jukebox.js";
export class ResumeCommand extends Command {
constructor() {
super({
name: "resume",
description: "Resumes the current song.",
});
}
async run({ message, member, guild }: CommandContext, args: string[]): Promise<void> {
if (args.length !== 0) {
await message.channel.send("Resume command doesn't require arguments!");
}
const player = JukeBox.the().getPlayer(guild.id);
if (!player) {
await message.channel.send("Bot is not currently playing in any voice channel!");
return;
}
if (player.isPlaying) {
await message.channel.send("Bot is already playing!");
return;
}
// User should be in the same channel with the bot
if (player.channelId !== member.voice.channel?.id) {
await message.channel.send(
"You need to be in the same voice channel with the bot to resume!"
);
return;
}
player.resume();
await message.channel.send("Streaming resumed.");
}
}
|
8eed3c6596b0994d28046e366c690c4b485c1cd7
|
TypeScript
|
lnatus/larsnatus.fit
|
/src/scripts/app/model/training-result.ts
| 2.671875
| 3
|
namespace LNF {
export namespace Model {
export class TrainingResult {
public restDays: number
public trainDays: number
public doCardio: boolean
public time: number
public isBusy() : boolean {
return (7 - this.restDays > this.time)
}
constructor(restDays: number, doCardio: boolean, time: number) {
this.restDays = restDays
this.trainDays = 7 - restDays
this.doCardio = doCardio
this.time = time
}
}
}
}
|
b7764833f9442a71b5b1a64a99b33eaa3ad6ed2a
|
TypeScript
|
JLRiiot/carrete
|
/src/Util/index.ts
| 3
| 3
|
const addItemToArray = <T>(item: T, original: T[]): T[] => {
let newArray = original.slice();
newArray.splice(newArray.length - 1, 0, item);
return newArray;
};
const removeItemFromArray = <T>(
item: T,
originalArray: T[],
matchFunction: (value: T, index?: number, array?: T[]) => boolean
): T[] => {
return originalArray.filter(matchFunction);
};
export { addItemToArray, removeItemFromArray };
|
f9c3f043d73a21a346c72f943b5317bad2130d13
|
TypeScript
|
ShellWolf/Typescript-Learn-Practice
|
/src/advanceType/index.ts
| 3.984375
| 4
|
// 利用 strictNullChecks: true 监控返回值为undefined时,报错提示
interface Square {
kind: "square", // 这个就是具有辨识性的属性
size: number,
}
interface Rectangle {
kind: "rectangle",
height: number,
width: number,
}
interface Circle {
kind: "circle",
radius: number,
}
interface Triangle {
kind: "triangle",
bottom: number,
height: number,
}
type Shape = Square | Rectangle | Circle | Triangle // 组成一个可联合标识
function getArea(s: Shape): number {
switch (s.kind) {
case 'square':
return s.size * s.size;
case 'rectangle':
return s.height * s.width;
case 'circle':
return Math.PI * s.radius ** 2; // ** 是求幂运算
case 'triangle':
return s.bottom * s.height / 2;
default:
return assertNever(s)
}
}
// 使用never 类型, 主动捕捉,运行时报错
function assertNever (value: never): never {
throw new Error('unexpected object: ' + value)
}
|
5657ed0e8ab2ccf33876176ed7d9942df78bdbf1
|
TypeScript
|
joeelliott/dotproduct
|
/ts/model/projectile/Projectile.ts
| 3.140625
| 3
|
import Entity from 'model/Entity';
import Player from 'model/player/Player';
import Listener from 'Listener';
import Repel from 'model/projectile/Repel';
import Simulation from 'model/Simulation';
abstract class Projectile extends Entity {
protected owner_ : Player;
private level_ : number;
protected lifetime_ : number;
protected damage_ : number;
private bounceCount_ : number;
constructor(simulation : Simulation, owner : Player, level : number, lifetime : number, damage : number, bounceCount : number) {
super(simulation);
this.owner_ = owner;
this.level_ = level;
this.lifetime_ = lifetime;
this.damage_ = damage;
this.bounceCount_ = bounceCount;
}
/**
* Returns the level of this projectile. The values vary for each type of
* projectile, but the weakest level is 0.
*/
public getLevel() : number {
return this.level_;
}
/** This function returns true if the projectile is bouncy, false otherwise. */
public isBouncing() : boolean {
return this.bounceCount_ != 0;
}
protected abstract checkPlayerCollision_(player : Player) : boolean;
/** |player| specifies the player who was directly hit or null if there was no direct hit. */
protected explode_(player : Player | null) {
Listener.fire(this, 'explode', player);
}
public advanceTime() {
if (--this.lifetime_ <= 0) {
this.invalidate();
return;
}
this.updatePosition_();
this.simulation_.playerList.some(this.checkPlayerCollision_.bind(this));
}
/** This function is called when a repel may affect the projectile. */
public onRepelled(repel : Repel) {
this.velocity_ = repel.apply(this.position_, this.velocity_);
}
protected bounce_() {
if (this.bounceCount_ == 0) {
this.explode_(null);
} else if (this.bounceCount_ > 0) {
--this.bounceCount_;
}
}
}
namespace Projectile {
type Event = 'explode';
}
export default Projectile;
|
b04615baa47bf71dd1b61616dea53a5678755810
|
TypeScript
|
bitblit/Epsilon
|
/src/config/inter-api/inter-api-process-mapping.ts
| 2.5625
| 3
|
/**
* When an event matching the source and type is received, the listed background types will be
* enqueued with the data from the inter-api block being treated as the data block of the background
* task
*/
export interface InterApiProcessMapping {
sourceRegex: string;
typeRegex: string;
disabled: boolean;
backgroundProcessTypes: string[];
}
|
a98a9aea6b7b26941d8b90b6314897a961434b85
|
TypeScript
|
AnimeshTimsina/animeshtimsina.github.io
|
/src/database/services.data.ts
| 2.609375
| 3
|
import { ReactComponent as DjangoLogo } from "images/Django.svg"
import { ReactComponent as EthereumLogo } from "images/Ethereum.svg"
import { ReactComponent as GraphQLLogo } from "images/GraphQL.svg"
import { ReactComponent as ReactLogo } from "images/React.svg"
import { ReactComponent as FlutterLogo } from "images/flutter.svg"
export const ServiceData = [
{
id: "1",
image: ReactLogo,
title: "Frontend React",
content:
"If you ever want a web application for your business or personal need, I got you covered. You can always provide me your wildest designs and I will build it exactly how you want it. Dynamic themes, complex animations, offline working....you name it.",
},
{
id: "2",
image: DjangoLogo,
title: "Backend",
content:
"Want a solid backend for your project to make it run in any device that you can think of. I got you covered. Database design, authentication, push notifications, server side rendering...",
},
{
id: "3",
image: GraphQLLogo,
title: "GraphQL (coz' REST sucks)",
content:
"Gone are the days of over-fetching data from REST API calls! GraphQL is efficient, flexible, solves overfetching and works well with Typescript.",
},
{
id: "4",
image: FlutterLogo,
title: "Mobile",
content:
"Want a high performant, modern-looking native mobile application for your business? You have come to the right place. And also, don't worry about iOS or Android cuz I use Flutter! ",
},
{
id: "5",
image: EthereumLogo,
title: "Blockchain Programming",
content:
"Building decentralized applications and smart contracts based on Ethereum Blockchain have always intrigued me. Fault tolerant and censorship resistant system with no single point of failure is the future!",
},
]
|
d3510449435ff16d8c6ca2b9cda0727ecd57445f
|
TypeScript
|
fromfeizhou/egretPro
|
/game/src/app/com_main/src/proxy/TankProxy.ts
| 2.625
| 3
|
// class TankProxy extends BaseProxy {
// public static tag_resp_open_info_view = false;
// /**购买请求ID */
// public static temp_request_buy: number;
// /**使用请求ID */
// public static temp_request_use: number;
// /**强化请求类型 */
// public static temp_request_strengthen: number;
// public constructor() {
// super();
// }
// protected listenerProtoNotifications(): any[] {
// return [
// [ProtoDef.TANK_INFO, this, 'TankInfoReq', 'TankInfoResp'],//获取战车信息
// [ProtoDef.TANK_STRENGTHEN, this, 'TankStrengthenReq', 'TankStrengthenResp'],//战车强化
// [ProtoDef.TANK_USE, this, 'TankUseReq', 'TankUseResp'],//使用战车
// [ProtoDef.TANK_BUY, this, 'TankBuyReq', 'TankBuyResp'],//购买战车
// ];
// }
// public execute(notification: AGame.INotification) {
// let protocol: number = Number(notification.getName());
// let body = notification.getBody();
// switch (protocol) {
// case ProtoDef.TANK_INFO: {
// TankModel.setTankInfo(body);
// if (TankProxy.tag_resp_open_info_view)
// AGame.R.notifyView(TASK_UI.POP_TANK_OPEN);
// break;
// }
// case ProtoDef.TANK_STRENGTHEN: {
// let vo = TankModel.getTankVo();
// let addExp = body.tankExp - vo.tankExp;
// let addExpFixed = vo.getStrengthenAddExp(TankProxy.temp_request_strengthen);
// if (addExp > addExpFixed) {
// //FIX ME
// EffectUtils.showTips("暴击", 1, false);
// }
// TankModel.updateTankInfo(body);
// break;
// }
// case ProtoDef.TANK_USE: {
// let vo = TankModel.getTankVo();
// vo.tankSkinId = TankProxy.temp_request_use;
// break;
// }
// case ProtoDef.TANK_BUY: {
// TankProxy.send_TANK_INFO();
// break;
// }
// default:
// break;
// }
// AGame.ServiceBuilder.notifyView(notification);
// }
// /////////////////////////////////////////////////////////////////////
// /**
// * 获取战车信息
// */
// public static send_TANK_INFO(open: boolean = false) {
// debug("RankProxy:send_TANK_INFO--->>");
// TankProxy.tag_resp_open_info_view = open;
// let data = AGame.ServiceBuilder.newClazz(ProtoDef.TANK_INFO);
// AGame.ServiceBuilder.sendMessage(data);
// }
// /**
// * 战车强化
// */
// public static send_TANK_STRENGTHEN(consumeType) {
// debug("RankProxy:send_TANK_STRENGTHEN--->>");
// TankProxy.temp_request_strengthen = consumeType;
// let data = AGame.ServiceBuilder.newClazz(ProtoDef.TANK_STRENGTHEN);
// data.type = consumeType;
// AGame.ServiceBuilder.sendMessage(data);
// }
// /**
// * 使用战车
// */
// public static send_TANK_USE(skinId) {
// debug("RankProxy:send_TANK_USE--->>");
// TankProxy.temp_request_use = skinId;
// let data = AGame.ServiceBuilder.newClazz(ProtoDef.TANK_USE);
// data.tankSkinId = skinId;
// AGame.ServiceBuilder.sendMessage(data);
// }
// /**
// * 购买战车
// */
// public static send_TANK_BUY(skinId) {
// debug("RankProxy:send_TANK_BUY--->>");
// TankProxy.temp_request_buy = skinId;
// let data = AGame.ServiceBuilder.newClazz(ProtoDef.TANK_BUY);
// data.tankSkinId = skinId;
// AGame.ServiceBuilder.sendMessage(data);
// }
// }
|
11c924d23ef495eee036611bb8e9f910d8e985e3
|
TypeScript
|
cunningt/teiid-komodo
|
/ui/beetle-lib/src/connections/shared/schema-node.model.spec.ts
| 2.625
| 3
|
import { SchemaNode } from "./schema-node.model";
describe("SchemaNode", () => {
let schemaNode: SchemaNode;
beforeEach(() => {
schemaNode = null;
});
it("should create, root only", () => {
console.log("========== [SchemaNode] should create, root only");
schemaNode = SchemaNode.create(
{
"name": "restaurants",
"type": "collection",
"path": "collection=restaurants",
"connectionName": "conn1",
"queryable": true,
"children": [
],
});
expect(schemaNode.getName()).toEqual("restaurants");
expect(schemaNode.getType()).toEqual("collection");
expect(schemaNode.getPath()).toEqual("collection=restaurants");
expect(schemaNode.getConnectionName()).toEqual("conn1");
expect(schemaNode.isQueryable()).toEqual(true);
expect(schemaNode.getMaxLevels()).toEqual(1);
});
it("should create, root with 2 children", () => {
console.log("========== [SchemaNode] should create, root with 2 children");
schemaNode = SchemaNode.create(
{
"name": "restaurants",
"type": "collection",
"path": "collection=restaurants",
"connectionName": "conn1",
"queryable": true,
"children": [
{
"name": "grades",
"type": "embedded",
"path": "collection=restaurants/embedded=grades",
"connectionName": "conn1",
"queryable": true,
"children": []
},
{
"name": "address",
"type": "embedded",
"path": "collection=restaurants/embedded=address",
"connectionName": "conn1",
"queryable": true,
"children": []
},
],
});
expect(schemaNode.getName()).toEqual("restaurants");
expect(schemaNode.getType()).toEqual("collection");
expect(schemaNode.getPath()).toEqual("collection=restaurants");
expect(schemaNode.getConnectionName()).toEqual("conn1");
expect(schemaNode.isQueryable()).toEqual(true);
expect(schemaNode.getMaxLevels()).toEqual(2);
expect(schemaNode.getChildren().length).toEqual(2);
expect(schemaNode.getChildren()[0].getName()).toEqual("grades");
expect(schemaNode.getChildren()[0].getType()).toEqual("embedded");
expect(schemaNode.getChildren()[0].getPath()).toEqual("collection=restaurants/embedded=grades");
expect(schemaNode.getChildren()[0].getConnectionName()).toEqual("conn1");
expect(schemaNode.getChildren()[0].isQueryable()).toEqual(true);
expect(schemaNode.getChildren()[0].getMaxLevels()).toEqual(1);
expect(schemaNode.getChildren()[0].getChildren().length).toEqual(0);
expect(schemaNode.getChildren()[1].getName()).toEqual("address");
expect(schemaNode.getChildren()[1].getType()).toEqual("embedded");
expect(schemaNode.getChildren()[1].getPath()).toEqual("collection=restaurants/embedded=address");
expect(schemaNode.getChildren()[1].getConnectionName()).toEqual("conn1");
expect(schemaNode.getChildren()[1].isQueryable()).toEqual(true);
expect(schemaNode.getChildren()[1].getMaxLevels()).toEqual(1);
expect(schemaNode.getChildren()[1].getChildren().length).toEqual(0);
});
it("should create, root with 3 levels", () => {
console.log("========== [SchemaNode] should create, root with 3 levels");
schemaNode = SchemaNode.create(
{
"name": "myCatalog",
"type": "catalog",
"path": "catalog=myCatalog",
"connectionName": "conn1",
"queryable": false,
"children": [
{
"name": "mySchema1",
"type": "schema",
"path": "catalog=myCatalog/schema=mySchema1",
"connectionName": "conn1",
"queryable": false,
"children": [
{
"name": "myTable1",
"type": "table",
"path": "catalog=myCatalog/schema=mySchema1/table=myTable1",
"connectionName": "conn1",
"queryable": true,
"children": []
},
{
"name": "myTable2",
"type": "table",
"path": "catalog=myCatalog/schema=mySchema1/table=myTable2",
"connectionName": "conn1",
"queryable": true,
"children": []
}
]
},
{
"name": "mySchema2",
"type": "schema",
"path": "catalog=myCatalog/schema=mySchema2",
"connectionName": "conn1",
"queryable": false,
"children": [
{
"name": "myTableA",
"type": "table",
"path": "catalog=myCatalog/schema=mySchema2/table=myTableA",
"connectionName": "conn1",
"queryable": true,
"children": []
},
{
"name": "myTableB",
"type": "table",
"path": "catalog=myCatalog/schema=mySchema2/table=myTableB",
"connectionName": "conn1",
"queryable": true,
"children": []
},
{
"name": "myTableC",
"type": "table",
"path": "catalog=myCatalog/schema=mySchema2/table=myTableC",
"connectionName": "conn1",
"queryable": true,
"children": []
}
]
},
],
});
// Root Node (myCatalog)
expect(schemaNode.getName()).toEqual("myCatalog");
expect(schemaNode.getType()).toEqual("catalog");
expect(schemaNode.getPath()).toEqual("catalog=myCatalog");
expect(schemaNode.getConnectionName()).toEqual("conn1");
expect(schemaNode.isQueryable()).toEqual(false);
expect(schemaNode.getMaxLevels()).toEqual(3);
expect(schemaNode.getChildren().length).toEqual(2);
// Root Child 1 (mySchema1)
const schema1: SchemaNode = schemaNode.getChildren()[0];
expect(schema1.getName()).toEqual("mySchema1");
expect(schema1.getType()).toEqual("schema");
expect(schema1.getPath()).toEqual("catalog=myCatalog/schema=mySchema1");
expect(schema1.getConnectionName()).toEqual("conn1");
expect(schema1.isQueryable()).toEqual(false);
expect(schema1.getMaxLevels()).toEqual(2);
expect(schema1.getChildren().length).toEqual(2);
// Root Child 2 (mySchema2)
const schema2: SchemaNode = schemaNode.getChildren()[1];
expect(schema2.getName()).toEqual("mySchema2");
expect(schema2.getType()).toEqual("schema");
expect(schema2.getPath()).toEqual("catalog=myCatalog/schema=mySchema2");
expect(schema2.getConnectionName()).toEqual("conn1");
expect(schema2.isQueryable()).toEqual(false);
expect(schema2.getMaxLevels()).toEqual(2);
expect(schema2.getChildren().length).toEqual(3);
// mySchema2 children
const tableA: SchemaNode = schema2.getChildren()[0];
const tableB: SchemaNode = schema2.getChildren()[1];
const tableC: SchemaNode = schema2.getChildren()[2];
expect(tableA.getName()).toEqual("myTableA");
expect(tableA.getType()).toEqual("table");
expect(tableA.getPath()).toEqual("catalog=myCatalog/schema=mySchema2/table=myTableA");
expect(tableA.getConnectionName()).toEqual("conn1");
expect(tableA.isQueryable()).toEqual(true);
expect(tableA.getMaxLevels()).toEqual(1);
expect(tableA.getChildren().length).toEqual(0);
expect(tableB.getName()).toEqual("myTableB");
expect(tableB.getType()).toEqual("table");
expect(tableB.getPath()).toEqual("catalog=myCatalog/schema=mySchema2/table=myTableB");
expect(tableB.getConnectionName()).toEqual("conn1");
expect(tableB.isQueryable()).toEqual(true);
expect(tableB.getMaxLevels()).toEqual(1);
expect(tableB.getChildren().length).toEqual(0);
expect(tableC.getName()).toEqual("myTableC");
expect(tableC.getType()).toEqual("table");
expect(tableC.getPath()).toEqual("catalog=myCatalog/schema=mySchema2/table=myTableC");
expect(tableC.getConnectionName()).toEqual("conn1");
expect(tableC.isQueryable()).toEqual(true);
expect(tableC.getMaxLevels()).toEqual(1);
expect(tableC.getChildren().length).toEqual(0);
});
});
|
69ae65c1fa0d4fa68d739bec0302eac1d5e95c4b
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/uint48be/index.d.ts
| 3.328125
| 3
|
// Type definitions for uint48be 2.0
// Project: https://github.com/mafintosh/uint48be
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
/**
* Encode a number as a big endian 48 bit unsigned integer.
*
* @param number The number to encode.
* @param buffer The buffer to encode the `number` into.
* @param [offset=0] The offset at which to write the encoded `number`.
*
* @example
* import * as uint48be from 'uint48be'
*
* uint48be.encode(42) // returns a 6 byte buffer with 42 encoded
*/
export function encode(number: number, buffer?: Buffer, offset?: number): Buffer;
export namespace encode {
/**
* Number of bytes after encoding a number. Always returns `6`.
*/
const bytes: 6;
}
/**
* Decode a number from a buffer.
*
* @param buffer The buffer with the encoded number.
* @param [offset=0] The offset at which to start decoding.
*
* @example
* import * as uint48be from 'uint48be'
*
* const buffer = uint48be.encode(42)
* console.log(uint48be.decode(buffer)) // returns 42
*/
export function decode(buffer: Buffer, offset?: number): number;
export namespace decode {
/**
* Number of bytes after decoding a number. Always returns `6`.
*/
const bytes: 6;
}
/**
* Always returns `6`.
*/
export function encodingLength(number: number): 6;
|
fabe19e153177361fd7437faef85a4a945cdf588
|
TypeScript
|
brunoparga/cicero
|
/src/store/sliceReducers/pageReducer.test.ts
| 2.921875
| 3
|
import { PageState } from "../../types";
import { pageReducer } from "./pageReducer";
const basePage = {
status: "frontPage",
currentWordIndex: 4,
resultsSaved: false,
guess: { wrongGuess: false, rightGuess: true },
passiveSelected: false,
pluralSelected: false,
revealAnswer: false,
} as PageState;
it("resets the word counter when getting a new batch of words", () => {
const page = JSON.parse(JSON.stringify(basePage));
const action = { type: "SET_WORDS" };
const expectation = { ...page, currentWordIndex: -1 } as PageState;
expect(pageReducer(page, action)).toEqual(expectation);
});
it("reacts to the back-end saving study session results to the DB", () => {
const page = JSON.parse(JSON.stringify(basePage));
const action = { type: "RESULTS_SAVED" };
const expectation = { ...page, resultsSaved: true } as PageState;
expect(pageReducer(page, action)).toEqual(expectation);
});
it("sets a wrong guess", () => {
const page = JSON.parse(JSON.stringify(basePage));
const action = {
type: "SET_GUESS",
payload: { property: "rightGuess", value: false },
};
const expectation = {
...page,
guess: { ...page.guess, rightGuess: false },
} as PageState;
expect(pageReducer(page, action)).toEqual(expectation);
});
it("sets a right guess that makes all the guesses right", () => {
const page = JSON.parse(JSON.stringify(basePage));
const action = {
type: "SET_GUESS",
payload: { property: "wrongGuess", value: true },
};
const expectation = {
...page,
guess: { ...page.guess, wrongGuess: true },
revealAnswer: true,
} as PageState;
expect(pageReducer(page, action)).toEqual(expectation);
});
it("sets another kind of right guess", () => {
const page = JSON.parse(JSON.stringify(basePage));
const newPage = { ...page, guess: { ...page.guess, thirdGuess: false } };
const action = {
type: "SET_GUESS",
payload: { property: "thirdGuess", value: true },
};
const expectation = {
...newPage,
guess: { ...newPage.guess, thirdGuess: true },
} as PageState;
expect(pageReducer(page, action)).toEqual(expectation);
});
it("sets which main page component should load", () => {
const page = JSON.parse(JSON.stringify(basePage));
const action = { type: "SET_STATUS", payload: "done" };
const expectation = { ...page, status: "done" } as PageState;
expect(pageReducer(page, action)).toEqual(expectation);
});
it("toggles whether the verb suffixes shown are active or passive (deponent verbs)", () => {
const page = JSON.parse(JSON.stringify(basePage));
const action = { type: "TOGGLE_DEPONENT" };
const expectation = { ...page, passiveSelected: true } as PageState;
expect(pageReducer(page, action)).toEqual(expectation);
});
it("toggles whether the noun suffixes shown are singular or plural", () => {
const page = JSON.parse(JSON.stringify(basePage));
const action = { type: "TOGGLE_PLURAL" };
const expectation = { ...page, pluralSelected: true } as PageState;
expect(pageReducer(page, action)).toEqual(expectation);
});
it("does nothing with any other action", () => {
const page = JSON.parse(JSON.stringify(basePage));
const action = { type: "SOME_ACTION" };
expect(pageReducer(page, action)).toEqual(page);
});
|
88e3b2b846d167beccd794c48378fc2fe0f63373
|
TypeScript
|
jcowman2/react-ensemble
|
/packages/react-ensemble/src/utils/TrackUtils/helpers.ts
| 3.03125
| 3
|
export const clampString = (str: string, len = 30) => {
if (str.length <= len) {
return str;
}
return str.substr(0, len - 3) + "...";
};
export const newId = (kind: string): string => {
const str = Math.random().toString(36);
return `${kind}_${str.substr(2, 8)}`;
};
export const isFunction = (f: unknown): f is Function =>
f && typeof f === "function";
export const isNumber = (n: unknown): n is number => typeof n === "number";
export const isArray = (n: unknown): n is any[] =>
n && (n as any).length !== undefined;
|
07cf5d5651b084cf82e5d74b0fd29acc16007039
|
TypeScript
|
kahummer/opensrp-web
|
/clients/core/src/store/ducks/locations.ts
| 3.046875
| 3
|
import { AnyAction, Store } from 'redux';
import SeamlessImmutable from 'seamless-immutable';
/** The reducer name */
export const reducerName = 'locations';
/** Inteface for Location */
export interface Location {
id: string;
label: string;
parent?: string;
node: {
locationId: string;
name: string;
parentLocation?: ParentLocation;
tags: string[];
voided: boolean;
};
children?: LocationNode;
}
/** interface for the parent location. */
export interface ParentLocation {
locationId: string;
name: string;
voided: boolean;
parentLocation?: ParentLocation;
}
/** A single node for location hierarchy */
export interface LocationNode {
[key: string]: Location;
}
/** Interface for location object */
export interface LocationHierarchy {
locationsHierarchy: {
map: LocationNode;
parentChildren: {
[key: string]: string[];
};
};
}
/** SET_LOCATION action type */
export const SET_LOCATIONS = 'opensrp/reducer/locations/SET_LOCATIONS';
/** Interface for setLocationAction */
interface SetLocationAction extends AnyAction {
locations: LocationHierarchy;
type: typeof SET_LOCATIONS;
}
/** Create type for location reducer actions */
export type LocationActionTypes = SetLocationAction | AnyAction;
/** setLocation action */
export const setLocations = (locations: LocationHierarchy | null): SetLocationAction => ({
locations,
type: SET_LOCATIONS,
});
/** interface for location state in redux store */
interface LocationState {
locations: {
[key: string]: LocationHierarchy;
};
}
/** Create an immutable location state */
export type ImmutableLocationsState = LocationState & SeamlessImmutable.ImmutableObject<LocationState>;
/** initial locations-state */
const initialState: ImmutableLocationsState = SeamlessImmutable({
locations: {},
});
/** the locations reducer function */
export default function reducer(
state: ImmutableLocationsState = initialState,
action: LocationActionTypes,
): ImmutableLocationsState {
switch (action.type) {
case SET_LOCATIONS:
return SeamlessImmutable({
locations: action.locations,
});
default:
return state;
}
}
/** get location hierarchy
* @param {Partial<Store>} state - the redux store
* @return {Household | null} a household obj if the id is found else null
*/
export function getLocationHierarchy(state: Partial<Store>): LocationHierarchy | null {
return (state as any)[reducerName].locations;
}
|
9f865e1b0b04963bf30fd3b1e8db28b0987be5b4
|
TypeScript
|
Zcating/power-ui
|
/components/cdk/accordion/accordion-dispatcher.ts
| 2.515625
| 3
|
import { inject, InjectionKey, onUnmounted, provide, watch } from 'vue';
import { AccordionItemState as AccordionItemState } from './types';
/**
* @description
*
* @date 2020-09-24
* @export
* @class SelectionDispatcher
*/
export class CdkAccordionDispatcher {
static key = Symbol() as InjectionKey<CdkAccordionDispatcher>;
static instance() {
return inject(this.key);
}
readonly states: AccordionItemState[] = [];
multiple = false;
initValue = false;
constructor() {
provide(CdkAccordionDispatcher.key, this);
}
subscribe(state: AccordionItemState) {
if (this.states.indexOf(state) !== -1) {
return;
}
if (this.multiple) {
state.expanded = this.initValue;
}
this.states.push(state);
watch(() => state.expanded, (value) => {
if (this.multiple || !value) {
return;
}
this.states.forEach((curState) => {
if (curState !== state) {
curState.expanded = false;
}
});
});
onUnmounted(() => {
const index = this.states.findIndex(fn => fn === state);
if (index === -1) {
return;
}
this.states.splice(index, 1);
});
}
notify(value: boolean) {
if (this.multiple) {
this.initValue = value;
this.states.forEach(state => state.expanded = value);
}
}
}
|
7dddb333b73708dfdc187c0c8f7eb6d9bc81cbc7
|
TypeScript
|
fanneiOZ/sertis-fs-exercise
|
/packages/back-end/src/cores/mini-blog/repositories/card.repository.ts
| 2.515625
| 3
|
import {injectable} from "tsyringe";
import {MongoDbAdaptor} from "../../../libs/database/nosql/mongo-db-adaptor";
import {DocumentRepository} from "../../../libs/domain-driven/document-repository";
import {Identifier, Writable} from "../../../libs/domain-driven/interfaces/repository.interface";
import {Card} from "../models/card";
import {CardState} from "../models/interfaces/card.interface";
@injectable()
export class CardRepository extends DocumentRepository<CardState>{
constructor() {
super(
MongoDbAdaptor.getInstance(),
{
dbName: 'sertis',
schemaName: 'blog',
tableName: 'cards',
schemaDefinitions: []
}
)
}
async getById(id: Identifier): Promise<Card | undefined> {
try {
const query = {
id: {
$eq: id
}
}
const data = await this.db.select(this.entityInfo, query) as CardState
return Card.create(data.id, data.category, data.name, data.content, data.author)
} catch (e) {
throw e
}
}
async getAll(): Promise<Card[]> {
try {
const data = await this.db.selectAll(this.entityInfo)
if (!data) return []
return data.map(data => {
const {id, category, name, content, author} = data as CardState
return Card.create(id, category, name, content, author)
})
} catch (e) {
throw e
}
}
async deleteById(id: Identifier): Promise<void> {
const query = {
id: {
$eq: id
}
}
await this.db.delete(this.entityInfo, query)
}
async update(card: Card): Promise<void> {
const query = {
id: {
$eq: card.getId()
}
}
await this.db.update(this.entityInfo, card, query)
}
createPersistence(writable: Writable<CardState>): unknown {
return writable.toJSON()
}
createWritable(document: CardState): Writable<CardState> {
return undefined;
}
}
|
832cac560378f955cefd1b4fd1aab43724054201
|
TypeScript
|
MikeKoval/genetic-algo2
|
/src/generation.ts
| 3.0625
| 3
|
import { Chromosome } from './chromosome';
import { random } from './random';
export class Generation {
constructor(public chromosomes: Chromosome[], private offSpringPercent: number) {
}
public get averageFitness() {
let sum = 0;
this.chromosomes.forEach(c => sum += c.z);
return sum / this.chromosomes.length;
}
public get fittest(): Chromosome {
let fittest: Chromosome = null;
for(let c of this.chromosomes){
if(!fittest || fittest.z < c.z) fittest = c;
}
return fittest;
}
next() {
let childAmount = Math.floor(this.chromosomes.length * this.offSpringPercent);
if(childAmount > this.chromosomes.length) throw new RangeError('Child percent is too big.');
this.chromosomes.sort((a, b) => b.z - a.z);
let childs: Chromosome[] = [];
for(let i = 0; i < childAmount; i++){
let parent1Index = Math.floor(random(0, this.chromosomes.length));
let parent2Index = Math.floor(random(0, this.chromosomes.length));
let parent3Index = Math.floor(random(0, this.chromosomes.length));
let parent4Index = Math.floor(random(0, this.chromosomes.length));
let partner1 = this.chromosomes[parent1Index],
partner2 = this.chromosomes[parent2Index],
partner3 = this.chromosomes[parent3Index],
partner4 = this.chromosomes[parent4Index];
let partners = [partner1, partner2, partner3, partner4].sort((a, b) => b.z - a.z);
let child1: Chromosome = partners[0].mate(partners[1]);
childs.push(child1);
}
this.chromosomes.splice(this.chromosomes.length - childAmount, childAmount, ...childs);
let chromosomes = this.chromosomes.map(chromosome => chromosome.mutate());
return new Generation(chromosomes, this.offSpringPercent);
}
}
|
03c9f6f766378b9a85178dd3825f9fe7bfa59e78
|
TypeScript
|
tony-lang/cli
|
/.yalc/tony-lang/src/code_generation/services/ResolvePattern.ts
| 2.984375
| 3
|
import {
TRANSFORM_IDENTIFIER_PATTERN,
TRANSFORM_REST_PATTERN,
} from '../../constants'
import { INTERNAL_TEMP_TOKEN } from '../GenerateCode'
export class ResolvePattern {
static perform = (pattern: string): [string, string[]] => {
const obj = ResolvePattern.parsePattern(pattern)
return ResolvePattern.rec(obj)
}
private static rec = (obj: any): [string, string[]] => {
if (
typeof obj === 'string' &&
obj.startsWith(INTERNAL_TEMP_TOKEN.repeat(2))
)
return ResolvePattern.representRest(obj)
else if (typeof obj === 'string' && obj.startsWith(INTERNAL_TEMP_TOKEN))
return ResolvePattern.representIdentifier(obj)
else if (typeof obj !== 'object')
return ResolvePattern.representLiteral(obj)
else if (Array.isArray(obj)) return ResolvePattern.representArray(obj)
else return ResolvePattern.representObject(obj)
}
private static representRest = (obj: any): [string, string[]] => [
`"${TRANSFORM_REST_PATTERN}"`,
[obj.substring(2 * INTERNAL_TEMP_TOKEN.length)],
]
private static representIdentifier = (obj: any): [string, string[]] => [
`"${TRANSFORM_IDENTIFIER_PATTERN}"`,
[obj.substring(INTERNAL_TEMP_TOKEN.length)],
]
private static representLiteral = (obj: any): [string, string[]] => [
typeof obj === 'string' ? `'${obj}'` : `${obj}`,
[],
]
private static representArray = (obj: any[]): [string, string[]] => {
const [patterns, identifiers] = obj.reduce(
([patterns, identifiers], element) => {
const [newPattern, newIdentifiers] = ResolvePattern.rec(element)
return [patterns.concat(newPattern), identifiers.concat(newIdentifiers)]
},
[[], []],
)
return [`[${patterns.join(',')}]`, identifiers]
}
private static representObject = (obj: any): [string, string[]] => {
const [patterns, identifiers] = Object.entries(obj).reduce(
([patterns, identifiers]: [string[], string[]], [key, value]) => {
const [newPattern, newIdentifiers] = ResolvePattern.rec(value)
return [
patterns.concat([`${key}:${newPattern}`]),
identifiers.concat(newIdentifiers),
]
},
[[], []],
)
return [`{${patterns.join(',')}}`, identifiers]
}
private static parsePattern = (pattern: string): any => JSON.parse(pattern)
}
|
41ef17f97e785f3e5b4f30b21f7d3901ca48852f
|
TypeScript
|
juliushekkala/ohjelmistoprojekti
|
/src/readapi.ts
| 2.859375
| 3
|
import * as datavalid from "./datavalid";
const yaml = require('js-yaml');
const fs = require('fs');
const validUrl = require('valid-url');
//This file is imported to the main plugin file
//Includes functions that check security features of a OPENAPI-file
export class Apicheck {
yaml: any;
constructor(doc: any) {
this.yaml = doc;
}
checkHTTP() {
//Returns an object (dictionary) where each found url is linked to boolean. True = https, False = http
var servers = this.yaml.servers;
var addr_list: {[index: string]:any} = {};
//Go through servers, check if their urls start with https and update object accordingly
if (typeof servers !== "undefined") {
for (var server of servers) {
var address = server['url'];
//console.log(address);
if (address.startsWith("https")){
addr_list[address] = true;
}
else {
addr_list[address] = false;
addr_list['status'] = false;
}
}
}
//console.log(addrlist);
return addr_list;
}
checkSecurityScheme() {
var sec_schemes = this.yaml.components.securitySchemes;
if (typeof sec_schemes === "undefined") {
let sec_schemes: {[index: string]:boolean} = {};
sec_schemes['status'] = false;
return sec_schemes;
}
var statusValue: boolean = this.checkOAuth2Urls(sec_schemes);
sec_schemes['status'] = statusValue;
return sec_schemes;
}
//Checks that OAuth2 authorization and token URLs in security schemes are valid HTTPS URLs
checkOAuth2Urls(sec_schemes: any): boolean {
var returnValue: boolean;
returnValue = true;
//Go through all the different schemes
for (var secScheme in sec_schemes) {
var schemeType = sec_schemes[secScheme]['type'];
//If the scheme uses oauth2
if (schemeType === "oauth2") {
var flows = sec_schemes[secScheme]['flows'];
//Go through the different flows
for (var flowType in flows) {
if (sec_schemes[secScheme]['flows'][flowType]['authorizationUrl'] !== undefined) {
var authorizationUrl = sec_schemes[secScheme]['flows'][flowType]['authorizationUrl'];
//If the authorization url is not a valid https url
if (!validUrl.isHttpsUri(authorizationUrl)) {
sec_schemes[secScheme]['flows'][flowType]['status'] = false;
sec_schemes[authorizationUrl] = false;
returnValue = false;
//If the authorization url is a valid https url
} else {
sec_schemes[secScheme]['flows'][flowType]['status'] = true;
}
}
if (sec_schemes[secScheme]['flows'][flowType]['tokenUrl'] !== undefined) {
var tokenUrl = sec_schemes[secScheme]['flows'][flowType]['tokenUrl'];
//If the token url is not a valid https url
if (!validUrl.isHttpsUri(tokenUrl)) {
sec_schemes[secScheme]['flows'][flowType]['status'] = false;
sec_schemes[tokenUrl] = false;
returnValue = false;
//If the token url is a valid https url
} else {
sec_schemes[secScheme]['flows'][flowType]['status'] = true;
}
}
}
}
}
return returnValue;
}
//Check whether global security field is defined && that it is not an empty array
checkSecurityField(sec_field: any) {
//console.log(sec_field);
//not defined
if (typeof sec_field === "undefined") {
let sec_field: {[index: string]:boolean} = {};
sec_field['status'] = false;
return sec_field;
}
//if the security field is just an empty array
if (sec_field.length === 0) {
let sec_field: {[index: string]:boolean} = {};
sec_field['status'] = false;
return sec_field;
}
//if there are empty security requirements in a list(as in just "- {}"))
if (sec_field.length > 0) {
for (var sec in sec_field) {
if (Object.keys(sec_field[sec]).length === 0) {
let sec_field: {[index: string]:boolean} = {};
sec_field['status'] = false;
return sec_field;
}
}
}
//If the global security field is an empty object (as in "{}")
if (typeof sec_field === "object") {
if (Object.keys(sec_field).length === 0) {
let sec_field: {[index: string]:boolean} = {};
sec_field['status'] = false;
return sec_field;
}
}
sec_field['status'] = true;
return sec_field;
}
//Checks the correctness of different response definitions.
responseCheck(secStatus: boolean) {
//Use the Json object parser found in datavalid.ts
let targetFinder = new datavalid.Datavalidationcheck(this.yaml);
var responses: {[index: string]:any} = {};
var responseSec: {[index: string]: any} = {};
let field = this.yaml.paths;
if (typeof field === 'object') {
//Find all response definitions in the yaml
targetFinder.findTargets('responses', field, responses, 'paths');
targetFinder.findTargets('security', field, responseSec, 'paths');
}
//Go through the different responses
for (var response in responses) {
//Split the location string
var resp = response.split("/");
//Get the operation that the response codes refer to
var operation = resp[resp.length - 2];
var oper_long: string = response.substring(0, response.length - 9);
var security_check: string = oper_long + "security";
//For each response code
for (var responseCode in responses[response]) {
if (operation !== "head") {
//Check if 400 response code is defined
if (responses[response]['400status'] !== true) {
if (responseCode === '400') {
responses[response]['400status'] = true;
} else {
responses[response]['400status'] = false;
}
}
//Check if 429 response code is defined
if (responses[response]['429status'] !== true) {
if (responseCode === '429') {
responses[response]['429status'] = true;
} else {
responses[response]['429status'] = false;
}
}
//Check if 500 response code is defined
if (responses[response]['500status'] !== true) {
if (responseCode === '500') {
responses[response]['500status'] = true;
} else {
responses[response]['500status'] = false;
}
}
}
//Check if GET, PUT, HEAD and DELETE operations have their 404 response defined
if ((operation === "get" || operation === "put" || operation === "head" || operation === "delete") && responses[response]['404status'] !== true) {
if (responseCode === '404') {
responses[response]['404status'] = true;
} else {
responses[response]['404status'] = false;
}
}
//GET operations: Is a 200 or 202 response defined
if (operation === "get" && responses[response]['getStatus'] !== true) {
if (responseCode === '200' || responseCode === '202') {
responses[response]['getStatus'] = true;
} else {
responses[response]['getStatus'] = false;
}
}
//OPTIONS operations should have 200 response code defined
if (operation === "options" && responses[response]['oper200status'] !== true) {
if (responseCode === '200') {
responses[response]['oper200status'] = true;
} else {
responses[response]['oper200status'] = false;
}
}
//HEAD operations: Is a 200 or 202 response defined
if (operation === "head" && responses[response]['headStatus'] !== true) {
if (responseCode === '200' || responseCode === '202') {
responses[response]['headStatus'] = true;
} else {
responses[response]['headStatus'] = false;
}
}
//DELETE operations: Is a 200, 201, 202 or 204 response defined
if (operation === "delete" && responses[response]['deleteStatus'] !== true) {
if (responseCode === '200' || responseCode === '201' || responseCode === '202' || responseCode === '204') {
responses[response]['deleteStatus'] = true;
} else {
responses[response]['deleteStatus'] = false;
}
}
//PATCH operations: Is a 200, 201, 202 or 204 response defined
if (operation === "patch" && responses[response]['patchStatus'] !== true) {
if (responseCode === '200' || responseCode === '201' || responseCode === '202' || responseCode === '204') {
responses[response]['patchStatus'] = true;
} else {
responses[response]['patchStatus'] = false;
}
}
//POST operations: Is a 200, 201, 202 or 204 response defined
if (operation === "post" && responses[response]['postStatus'] !== true) {
if (responseCode === '200' || responseCode === '201' || responseCode === '202' || responseCode === '204') {
responses[response]['postStatus'] = true;
} else {
responses[response]['postStatus'] = false;
}
}
//PUT operations: Is a 200, 201, 202 or 204 response defined
if (operation === "put" && responses[response]['putStatus'] !== true) {
if (responseCode === '200' || responseCode === '201' || responseCode === '202' || responseCode === '204') {
responses[response]['putStatus'] = true;
} else {
responses[response]['putStatus'] = false;
}
}
//Checks if default status is defined. It is optional so not that big of a deal
if (responses[response]['defaultstatus'] !== true) {
if (responseCode === 'default') {
responses[response]['defaultstatus'] = true;
} else {
responses[response]['defaultstatus'] = false;
}
}
//If security is defined for the operation, 401 and 403 responses should be defined
if (responses[response]['sec401status'] !== true || responses[response]['sec403status'] !== true) {
//If global securily defined
if (secStatus === true) {
if (responseCode === '401') {
responses[response]['sec401status'] = true;
}
else if (responseCode === '403') {
responses[response]['sec403status'] = true;
} else {
if (typeof responses[response]['sec401status'] === "undefined") {
responses[response]['sec401status'] = false;
}
if (typeof responses[response]['sec403status'] === "undefined") {
responses[response]['sec403status'] = false;
}
}
//If operation has specific security defined
} else if (typeof responseSec[security_check] !== "undefined") {
//Check the security field
var sec = this.checkSecurityField(Object.assign({}, responseSec[security_check]));
//console.log(sec);
if (sec['status'] === true) {
if (responseCode === '401') {
responses[response]['sec401status'] = true;
}
else if (responseCode === '403') {
responses[response]['sec403status'] = true;
} else {
if (typeof responses[response]['sec401status'] === "undefined") {
responses[response]['sec401status'] = false;
}
if (typeof responses[response]['sec403status'] === "undefined") {
responses[response]['sec403status'] = false;
}
}
}
} else {
responses[response]['sec401status'] = true;
responses[response]['sec403status'] = true;
}
}
}
}
return responses;
}
public checkSecurity() {
var api_object: {[index: string]:any} = {};
api_object['addr_list'] = this.checkHTTP();
api_object['sec_schemes'] = this.checkSecurityScheme();
api_object['sec_field'] = this.checkSecurityField(this.yaml.security);
api_object['responses'] = this.responseCheck(api_object['sec_field']['status']);
console.log(api_object);
return api_object;
}
}
//Everything below is testing only and should always be commented out before committing changes
/*
try {
var ymlfile = yaml.safeLoad(fs.readFileSync('test/petstore.yaml', 'utf8'));
} catch (e) {
console.log(e);
}
var schemes = checkSecurity(ymlfile);
console.log(schemes);
*/
|
8f892a7f4dc2662252a060acc8adc0d64c566def
|
TypeScript
|
khellytaguinod/IONIC-Project-Team-iACADEMY
|
/marathon-app/src/services/auth.ts
| 2.703125
| 3
|
import firebase from 'firebase';
export class AuthService {
public username: string;
public email: string;
public photoURL: string;
// public id: string;
signup(email: string, password: string, name: string) {
return firebase.auth().createUserWithEmailAndPassword(email, password).then((user) => {
user = firebase.auth().currentUser;
user.updateProfile({displayName: name}).then(() => {
firebase.database().ref('users').child(user.uid).set({
email: user.email,
name: user.displayName,
userType: 'user'
});
});
})
}
signin(email: string, password: string) {
return firebase.auth().signInWithEmailAndPassword(email, password);
}
logout() {
return firebase.auth().signOut();
}
editUser(displayName: string, photoURL: string) {
let user = firebase.auth().currentUser;
if(user) {
user.updateProfile({
displayName: displayName,
photoURL: photoURL
})
}
return firebase.database().ref('/users').child(user.uid).update({
name: displayName
});
}
changeUserPhoto(imgUrl: string) {
let user = firebase.auth().currentUser;
let imgPath = `users/${user.uid}.jpg`;
return firebase.storage().ref('img').child(imgPath)
.putString(imgUrl, firebase.storage.StringFormat.DATA_URL)
.then(imgData => {
user.updateProfile({
displayName: user.displayName,
photoURL: imgData.downloadURL
})
firebase.database().ref('/users').child(user.uid).update({
imgPath: imgData.downloadURL
});
})
}
updateUserEmail(email: string) {
let user = firebase.auth().currentUser;
user.updateEmail(email);
return firebase.database().ref('/users').child(user.uid).update({
email: email
})
}
changePassword(password: string) {
let user = firebase.auth().currentUser;
return user.updatePassword(password);
}
getUserDetails() {
let user = firebase.auth().currentUser;
if (user) {
this.username = user.displayName;
this.email = user.email;
this.photoURL = user.photoURL;
}
}
reauthenticateUser(email: string, password: string) {
let user = firebase.auth().currentUser;
let credential = firebase.auth.EmailAuthProvider.credential(email, password);
return user.reauthenticateWithCredential(credential);
}
}
|
91e4f66bba2d2175b2be29f22a5b53b32361a09c
|
TypeScript
|
exercism/typescript
|
/exercises/practice/rectangles/.meta/proof.ci.ts
| 3.109375
| 3
|
export function count(diagram: string[]): number {
const rows = diagram.length
const cols = rows ? diagram[0].length : 0
let rectangles = 0
// All possible topleft corners
for (let y = 0; y < rows - 1; y++) {
for (let x = 0; x < cols - 1; x++) {
if (diagram[y].charAt(x) === '+') {
// All possible bottomright corners
for (let j = y + 1; j < rows; j++) {
for (let i = x + 1; i < cols; i++) {
// Check if all corners are valid
if (
diagram[j].charAt(i) === '+' &&
diagram[y].charAt(i) === '+' &&
diagram[j].charAt(x) === '+'
) {
let validRectangle = true
// Check if all sides are valid
for (let s = x + 1; s < i; s++) {
if (!'+-'.includes(diagram[y].charAt(s))) {
validRectangle = false
}
}
for (let s = x + 1; s < i; s++) {
if (!'+-'.includes(diagram[j].charAt(s))) {
validRectangle = false
}
}
for (let t = y + 1; t < j; t++) {
if (!'+|'.includes(diagram[t].charAt(x))) {
validRectangle = false
}
}
for (let t = y + 1; t < j; t++) {
if (!'+|'.includes(diagram[t].charAt(i))) {
validRectangle = false
}
}
if (validRectangle) {
rectangles++
}
}
}
}
}
}
}
return rectangles
}
|
f101d1df9e7d6a382a7102e38cbf81df0bef0f42
|
TypeScript
|
microsoft/fluentui
|
/packages/react-components/react-avatar/src/components/AvatarGroupPopover/AvatarGroupPopover.types.ts
| 2.6875
| 3
|
import * as React from 'react';
import type { AvatarSize } from '../Avatar/Avatar.types';
import type { AvatarGroupProps } from '../AvatarGroup/AvatarGroup.types';
import type { ComponentProps, ComponentState, Slot } from '@fluentui/react-utilities';
import type { PopoverProps, PopoverSurface } from '@fluentui/react-popover';
import type { TooltipProps } from '@fluentui/react-tooltip';
export type AvatarGroupPopoverSlots = {
root: NonNullable<Slot<PopoverProps>>;
/**
* Button that triggers the Popover.
*/
triggerButton: NonNullable<Slot<'button'>>;
/**
* List that contains the overflowed AvatarGroupItems.
*/
content: NonNullable<Slot<'ul'>>;
/**
* PopoverSurface that contains the content.
*/
popoverSurface: NonNullable<Slot<typeof PopoverSurface>>;
/**
* Tooltip shown when triggerButton is hovered.
*/
tooltip: NonNullable<Slot<TooltipProps>>;
};
/**
* AvatarGroupPopover Props
*/
export type AvatarGroupPopoverProps = Omit<ComponentProps<Partial<AvatarGroupPopoverSlots>>, 'children'> & {
/**
* Whether the triggerButton should render an icon instead of the number of overflowed AvatarGroupItems.
* Note: The indicator will default to `icon` when the size is less than 24.
* @default count
*/
indicator?: 'count' | 'icon';
/**
* Number of AvatarGroupItems that will be rendered.
*
* Note: AvatarGroupPopover handles counting the number of children, but when using a react fragment to wrap the
* children, this is not possible and therefore it has do be added manually.
*/
count?: number;
children: React.ReactNode;
};
/**
* State used in rendering AvatarGroupPopover
*/
export type AvatarGroupPopoverState = ComponentState<AvatarGroupPopoverSlots> &
Required<Pick<AvatarGroupPopoverProps, 'count' | 'indicator'>> & {
popoverOpen: boolean;
layout: AvatarGroupProps['layout'];
size: AvatarSize;
};
|
7085b01a77d018b8a12bd5256e99495ac504f193
|
TypeScript
|
FlorianGlt/koala-test
|
/src/Utils/Interfaces.ts
| 2.515625
| 3
|
export interface Contract {
id: string;
type: "flight";
flight: {
from: {
name: string;
iata: string;
};
to: {
name: string;
iata: string;
};
number: string;
start: string;
nbOfTravellers: number;
};
}
export interface DetailedContract extends Contract {
product: {
minDelay: number;
};
claim: {
status: "accepted" | "rejected";
flightStatus: {
delay: number;
};
};
}
|
012bb3e3cddec3bf8500f708ec1d9d96d58f1ada
|
TypeScript
|
jaccomeijer/wheelroom
|
/packages/admin-theme-switcher/src/lib/theme-switcher-reducer.ts
| 2.828125
| 3
|
import { ActionTypes, ThemeSwitcherState } from './types'
export const themeSwitcherReducer = (
state: ThemeSwitcherState,
action: ActionTypes
): ThemeSwitcherState => {
switch (action.type) {
case 'SET_ACTIVE_THEME':
return {
...state,
lastThemeId: undefined,
activeThemeId: action.themeId,
}
case 'SET_TEMPORARY_ACTIVE_THEME':
return {
...state,
lastThemeId: state.activeThemeId,
activeThemeId: action.themeId,
}
case 'SET_LAST_THEME':
return {
...state,
activeThemeId: state.lastThemeId
? state.lastThemeId
: state.activeThemeId,
}
default:
throw new Error()
}
}
|
b4c1522d6596a9819768304a156e880eb0a5d645
|
TypeScript
|
SimonLoir/SMath
|
/src/drawer_obj.ts
| 2.640625
| 3
|
import { $ } from './extjs';
export default class Menu {
constructor() {}
public fdata: any;
public update(fdata: any, object_list: any) {
let container = $('#functions');
container.html('');
let keys = Object.keys(fdata);
keys.forEach(key => {
let item = container.child('div').addClass('item');
let span = item.child('span').html(
`<i style="background:${
fdata[key].color
}; width:5px;height:5px;border-radius:5px;display:inline-block;"></i>
${key}(x) = ${fdata[key].initial}`
);
});
let obj_container = $('#objs');
obj_container.html('');
let grid = obj_container.child('div').addClass('item');
let letters = 'abcdefghijklmnopqrstuvwxyz';
let li = 0;
let row = 0;
object_list.forEach((object: any) => {
let item = grid.child('div').addClass('item');
if (object.type == 'point') {
let letter = '';
letter += letters[li].toUpperCase();
if (row != 0) letter += row;
li++;
if (li > 25) {
li = 0;
row++;
}
let span = item
.child('span')
.text(`${letter}(${object.x};${object.yString})`);
} else {
let span = item.child('span').text(`${object.type}`);
}
console.log(object);
});
grid.child('span').text('Grille');
grid.child('button').html('🖉');
}
public updateCallback(callback: (fdata: any) => {}) {}
}
|
79b39cffcfb2ab04e643cd22923ffb575b754f8f
|
TypeScript
|
xDveGax/exo-frontend
|
/src/app/core/store/user/user.reducer.ts
| 2.765625
| 3
|
import { AppState } from '@core/store/reducers';
import { UserModel } from '@core/models/user/user.model';
import * as fromActions from './user.action';
export const reducers = {
user: reducer
};
export interface UserState {
user: UserModel;
loggedIntercom: boolean;
}
const initialState: UserState = {
user: undefined,
loggedIntercom: false,
};
export function reducer(state: UserState = initialState, action: fromActions.UserActions): UserState {
switch (action.type) {
case fromActions.GET_USER: {
return {
...state
};
}
case fromActions.GET_USER_SUCCESS: {
return {
...state,
user: action.payload
};
}
case fromActions.GET_USER_FAIL: {
return {
...state
};
}
// Update the user with a new instance of user
case fromActions.UPDATE_USER: {
return {
...state,
user: action.payload
};
}
// Update some attributes of user with information sent from payload
case fromActions.UPDATE_DATA_USER: {
const newUser = Object.assign(new UserModel(), { ...state.user, ...action.payload});
return {
...state,
user: newUser
};
}
case fromActions.LOGGED_INTERCOM: {
return {
...state,
loggedIntercom: action.payload
};
}
case fromActions.UPDATE_USER_PICTURE:
return {
...state,
user: Object.assign(new UserModel(), { ...state.user, ...action.payload})
};
case fromActions.LOGOUT_USER_SUCCESS: {
return initialState;
}
default:
return state;
}
}
// selectors
export const getUser = (state: AppState) => state.user.user;
export const getLoggedIntercom = (state: AppState) => state.user.loggedIntercom;
|
de90319a77fe985e95af20214f359ca75347e094
|
TypeScript
|
CodeChain-io/codechain-keystore-cli
|
/src/command/delete.ts
| 2.53125
| 3
|
import { prompt } from "enquirer";
import { CLIError, CLIErrorType } from "../error";
import { Context } from "../types";
import { findMatchingKey } from "../util";
export async function deleteKey(
{ cckey, accountType, networkId }: Context,
address: string
): Promise<void> {
const keys = await cckey[accountType].getKeys();
const key = findMatchingKey(accountType, keys, address, networkId);
const question = {
type: "confirm",
name: "delete",
message: "Do you really want to delete the key?"
};
const answer: any = await prompt(question);
if (answer.delete) {
const result = await cckey[accountType].deleteKey({ key });
if (!result) {
throw new CLIError(CLIErrorType.Unknown, {
message: "Delete failed"
});
}
}
}
|
2953407f27271db43db10f9fb5459454256f0bac
|
TypeScript
|
Bakuenjin/rpg-content-management
|
/src/managers/ArmorManager.ts
| 2.625
| 3
|
import { Armor, Attribute } from "@bakuenjin/rpg-core";
import { RawArmor } from "../utils/types";
import ContentManager from "./ContentManager";
export default class ArmorManager extends ContentManager<Armor> {
constructor(attributeManager: ContentManager<Attribute>, armors: RawArmor[]) {
super()
armors.forEach(rawArmor => {
const attributeValues = new Map<Attribute, number>()
rawArmor.attributes.forEach(attributeInfo => {
const attribute = attributeManager.getContentById(attributeInfo.id)
if (attribute) attributeValues.set(attribute, attributeInfo.value)
})
const armor = new Armor(
rawArmor.id,
rawArmor.name,
rawArmor.rarity,
rawArmor.type,
rawArmor.element,
attributeValues
)
this._contents.set(armor.id, armor)
})
}
}
|
47d5a33a00794d44767023a0ef6439af910016dd
|
TypeScript
|
notaphplover/ant-js
|
/src/api/config/api-query-config.ts
| 2.78125
| 3
|
import { QueryResult, TMQuery, TQuery } from '../../persistence/primary/query/query-types';
import { Entity } from '../../model/entity';
export interface ApiQueryConfig<TEntity extends Entity, TQueryResult extends QueryResult> {
/**
* True if the query returns an array of results instead of a single result.
*/
readonly isMultiple: boolean;
/**
* Entity key generator.
*
* This function is used in order to generate a key from an entity.
* This function is called whenever the query manager needs to know which query key is associated to a certain entity.
*/
readonly entityKeyGen?: (entity: TEntity) => string;
/**
* Query key generator.
*
* This function is used in order to know which query key is accesed when a query is performed.
*/
readonly queryKeyGen: (params: any) => string;
/**
* Multiple query.
* This function receives an array of queries and returns a promise of an array of query results.
* There must be a result for each query performed.
* The ith query result must be the result of the ith query requested.
*/
readonly mQuery?: TMQuery<TQueryResult>;
/**
* Single query.
* This function receives a query and returns a promise of query results.
*/
readonly query: TQuery<TQueryResult>;
/**
* Key to store a hash used by AntJS to manage queries properly.
*/
readonly reverseHashKey: string;
}
|
30139767a32da7b08470b9f46681c0d0aa1beeff
|
TypeScript
|
justincohan/angular-chess
|
/src/app/bishop.ts
| 3.046875
| 3
|
import { Piece } from './piece';
import { Move } from './move';
export class Bishop extends Piece {
type = 'Bishop';
possibleMoves: Move[] = [
new Move([1, 1], this.canMove, this.applyMove, []),
new Move([2, 2], this.canMove, this.applyMove, [[1, 1]]),
new Move([3, 3], this.canMove, this.applyMove, [[1, 1], [2, 2]]),
new Move([4, 4], this.canMove, this.applyMove, [[1, 1], [2, 2], [3, 3]]),
new Move([5, 5], this.canMove, this.applyMove, [[1, 1], [2, 2], [3, 3], [4, 4]]),
new Move([6, 6], this.canMove, this.applyMove, [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]),
new Move([7, 7], this.canMove, this.applyMove, [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6]]),
new Move([1, -1], this.canMove, this.applyMove, []),
new Move([2, -2], this.canMove, this.applyMove, [[1, -1]]),
new Move([3, -3], this.canMove, this.applyMove, [[1, -1], [2, -2]]),
new Move([4, -4], this.canMove, this.applyMove, [[1, -1], [2, -2], [3, -3]]),
new Move([5, -5], this.canMove, this.applyMove, [[1, -1], [2, -2], [3, -3], [4, -4]]),
new Move([6, -6], this.canMove, this.applyMove, [[1, -1], [2, -2], [3, -3], [4, -4], [5, -5]]),
new Move([7, -7], this.canMove, this.applyMove, [[1, -1], [2, -2], [3, -3], [4, -4], [5, -5], [6, -6]]),
new Move([-1, 1], this.canMove, this.applyMove, []),
new Move([-2, 2], this.canMove, this.applyMove, [[-1, 1]]),
new Move([-3, 3], this.canMove, this.applyMove, [[-1, 1], [-2, 2]]),
new Move([-4, 4], this.canMove, this.applyMove, [[-1, 1], [-2, 2], [-3, 3]]),
new Move([-5, 5], this.canMove, this.applyMove, [[-1, 1], [-2, 2], [-3, 3], [-4, 4]]),
new Move([-6, 6], this.canMove, this.applyMove, [[-1, 1], [-2, 2], [-3, 3], [-4, 4], [-5, 5]]),
new Move([-7, 7], this.canMove, this.applyMove, [[-1, 1], [-2, 2], [-3, 3], [-4, 4], [-5, 5], [-6, 6]]),
new Move([-1, -1], this.canMove, this.applyMove, []),
new Move([-2, -2], this.canMove, this.applyMove, [[-1, -1]]),
new Move([-3, -3], this.canMove, this.applyMove, [[-1, -1], [-2, -2]]),
new Move([-4, -4], this.canMove, this.applyMove, [[-1, -1], [-2, -2], [-3, -3]]),
new Move([-5, -5], this.canMove, this.applyMove, [[-1, -1], [-2, -2], [-3, -3], [-4, -4]]),
new Move([-6, -6], this.canMove, this.applyMove, [[-1, -1], [-2, -2], [-3, -3], [-4, -4], [-5, -5]]),
new Move([-7, -7], this.canMove, this.applyMove, [[-1, -1], [-2, -2], [-3, -3], [-4, -4], [-5, -5], [-6, -6]])
];
}
|
284b26e124bcd97a04ff9b93fe580cfe0284cc47
|
TypeScript
|
sdlcldw/oa
|
/src/app/valldators/valldators.ts
| 2.875
| 3
|
import { FormControl } from "@angular/forms";
//日期格式Sat Jan 13 2018 12:18:48 GMT+0800
export function dateValidator(date:FormControl):any{
let value = (date.value || '')+'';
var myreg = /^([a-zA-Z]{3})\s([a-zA-Z]{3})\s(\d{2})\s(\d{4}).*/;
let valid = myreg.test(value);
return valid ? null : {date:true};
}
//非负整数
export function zzsValidator(data:FormControl):any{
let value = (data.value || '')+'';
var myreg = /^\d+$/;
let valid = myreg.test(value);
return valid ? null : {zzs:true};
}
// 验证非零的正整数:
export function flzzsValidator(data:FormControl):any{
let value = (data.value || '')+'';
var myreg = /^\+?[1-9][0-9]*$/;
let valid = myreg.test(value);
return valid ? null : {flzzs:true};
}
|
d131855cb5231de7d6e6193a30c99b5168020624
|
TypeScript
|
hubert-associates/speckle-server
|
/packages/ui-components/src/helpers/layout/components.ts
| 2.5625
| 3
|
export enum GridListToggleValue {
Grid = 'grid',
List = 'list'
}
export type LayoutTabItem<I extends string = string> = {
title: string
id: I
}
export type LayoutMenuItem<I extends string = string> = {
title: string
id: I
disabled?: boolean
}
|
aac69573cc5b10f4284b8658072353442be09e71
|
TypeScript
|
nicolebarleta/web-425
|
/week-3/enhanced-secure-profile-app/src/app/sign-in.guard.ts
| 2.515625
| 3
|
/**
* Title: sign-in.guard.ts
* Author: Professor Krasso
* Date: 18 January 2021
* Modified by: Marie Nicole Barleta
* Description: CanActive function is used in this file
* This is guarding the app from unauthorized users,
* further authorization will be made at WEB 450 course
*/
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class SignInGuard implements CanActivate {
constructor(private router: Router) {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
let isLoggedIn = next.queryParams.isLoggedIn;
/* if isLoggedin returned true the user can access the index page
* if false the user will go back to the sign-in page
*/
if (isLoggedIn) {
return true;
} else {
this.router.navigate(['/']);
return false;
}
}
}
|
1062f429d461962f0fdf03e215e7867e8ae228a5
|
TypeScript
|
devlev1980/100-Algorithm-s-Challenge
|
/Lesson-16/arrayMaximalAdjacentDifference.ts
| 3.25
| 3
|
function arrayMaximalAdjacentDifference(inputArray:number[]):number {
let maxDiffrence = Math.abs(inputArray[0]-inputArray[1]);
console.log(maxDiffrence)
for (let i = 0; i < inputArray.length; i++) {
let absoluteDiff = Math.abs(inputArray[i-1] - inputArray[i])
console.log(inputArray[i-1]);
console.log(inputArray[i]);
console.log(absoluteDiff);
// if(absoluteDiff> maxDiffrence){
// maxDiffrence = absoluteDiff;
// }
maxDiffrence = absoluteDiff>maxDiffrence? absoluteDiff: maxDiffrence
}
return maxDiffrence
}
console.log(arrayMaximalAdjacentDifference([2,4,1,0]))
|
25a5ab8d60ed15d3902fa2b51680aa94972d8e82
|
TypeScript
|
shanehofstetter/rails-i18n-vscode
|
/src/keyDetector.ts
| 3
| 3
|
import { Position, Range, TextDocument } from 'vscode';
import { logger } from './logger';
/**
* Provides functions to detect and transform i18n keys
*/
export class KeyDetector {
/**
* check if i18n key is valid
* @param key i18n to validate
*/
public static isValidI18nKey(key: string): boolean {
return typeof key === "string";
}
/**
* find a i18n.translation call at position and return its range
* @param position position to look for the i18n call
* @param document current document
*/
public static getRangeOfI18nKeyAtPosition(position: Position, document: TextDocument): Range {
let i18nCallRegex = /(I18n\.)?t(ranslate)?[\(\s]+[\"\'][\w-\.\/]+[\"\'\.]\)?/g;
return document.getWordRangeAtPosition(position, i18nCallRegex);
}
/**
* get the i18n key as text from i18n call range
* @param range range where i18n call occurs
* @param document current document
*/
public static getI18nKeyAtRangeFromDocument(range: Range, document: TextDocument): string {
return document.getText(range).replace(/\"|\'|(I18n\.)?t(ranslate)?[\(\s]+|\)/g, "");
}
/**
* make absolute i18n key based on relative key, depending on current file location
* @param key key to make absolute (a relative key begins with a period)
* @param currentFilename current file name / path
*/
public static makeAbsoluteKey(key: string, currentFilename: string): string {
if (!this.isRelativeKey(key)) {
return key;
}
let relativeKeyPart = this.getRelativeKeyPart(currentFilename);
if (!relativeKeyPart) {
return key;
}
return relativeKeyPart + key;
}
public static getRelativeKeyPart(currentFilename: string): string {
try {
// get the relative key from current file path, starting at directory "views"
let relativeKey = currentFilename.split("views")[1].split(".")[0].replace(/\\|\//g, ".");
if (relativeKey.startsWith(".")) {
relativeKey = relativeKey.substring(1);
}
let relativeKeyParts = relativeKey.split(".");
relativeKeyParts = relativeKeyParts.map(keyPart => {
if (keyPart.startsWith("_")) {
return keyPart.substring(1);
}
return keyPart;
});
return relativeKeyParts.join(".");
} catch (Error) {
return "";
}
}
public static isRelativeKey(key: string): boolean {
return key.startsWith(".");
}
public static getAbsoluteKeyFromPositionInDocument(position: Position, document: TextDocument): { key: string, range: Range } | null {
let range = KeyDetector.getRangeOfI18nKeyAtPosition(position, document);
if (!range) {
return null;
}
let i18nKey = KeyDetector.getI18nKeyAtRangeFromDocument(range, document);
logger.debug('getAbsoluteKeyFromPositionInDocument', { i18nKey, range });
if (!KeyDetector.isValidI18nKey(i18nKey)) {
return null;
}
return { key: KeyDetector.makeAbsoluteKey(i18nKey, document.fileName), range };
}
}
|
4480016f2e17c2ae471ba8e596a5dbada1eed685
|
TypeScript
|
dzibler/types-ol-ext
|
/@types/ol-ext/util/input/List.d.ts
| 2.84375
| 3
|
import Base from "./Base";
export interface Options {
className?: string;
options?: any[];
input?: Element;
parent?: Element;
fixed?: boolean;
align?: 'left' | 'right' | 'middle';
}
/** Checkbox input
* @constructor
* @extends {ol_ext_input_Base}
* @param {*} options
* @param {string} [options.className]
* @param {Array<Object>} options.options an array of options to place in the popup { html:, title:, value: }
* @param {Element} [options.input] input element, if non create one
* @param {Element} [options.parent] parent element, if create an input
* @param {boolean} [options.fixed=false] don't use a popup, default use a popup
* @param {string} [options.align=left] align popup left/right/middle
* @param {boolean} [options.fixed=false] no popup
*/
export default class List extends Base {
constructor(options: any);
element: HTMLElement | Text;
popup: HTMLElement | Text;
}
|
f3b51ab87c40671e099616a0225fc78c18f7efd2
|
TypeScript
|
raini-dev/pipes
|
/src/helpers.ts
| 3.15625
| 3
|
export type TUnwrap<X> = X extends Promise<infer U> ? U : X
export function extend<T, K>(f: (x: T) => K) {
return function extendTo(x: T): T & K {
return Array.isArray(x)
? (([...x, ...((f(x) as unknown) as any[])] as unknown) as T & K)
: ({ ...x, ...f(x) } as T & K)
}
}
export function tap<T, K>(f: (x: T) => K) {
return function tapTo(x: T) {
f(x)
return x
}
}
|
7bd7ea6e054b4c55c0c96a69fc422aad860f1fd7
|
TypeScript
|
Sarariach/Student-evaluation
|
/server/src/batches/controller.ts
| 2.71875
| 3
|
import { JsonController, Get, Param, HttpCode, Body, Post, Authorized, NotFoundError } from 'routing-controllers'
import Batch from './entity'
@JsonController()
export default class BatchController {
// requests all users
@Get('/batches')
async allBatches(){
const batches = await Batch.find()
if (!batches) throw new NotFoundError('Batch table doesn\'t exist')
return {batches}
}
// requests one user
@Get('/batches/:id([0-9]+)')
async getbatch(
@Param('id') id: number
){
const batch = await Batch.findOne(id)
if (!batch) throw new NotFoundError('Batch doesn\'t exist')
if (batch) {
return { batch }
}
}
@Post('/batches')
@HttpCode(201)
async createBatch(
@Body() batch: Batch,
) {
const entity = await batch.save()
return { entity }
}
}
// // edits a user
// @Put('/batches/:id')
// // @HttpCode(200)
// async editBatch(
// @Param('id') id: number,
// @Body() update : Partial<Batch>
// ){
// const batch = await Batch.findOne(id)
// if (!batch) throw new NotFoundError('Batch doesn\'t exist')
// return Batch.merge(batch, update).save()
// }
// deletes a user
// @Delete('/batches/:id')
// async deleteBatch(
// @Param('id') id: number
// ) {
// const batch = await Batch.findOne(id)
// if (!batch) throw new NotFoundError('Batch doesn\'t exist')
// if(batch) Batch.removeBy(id)
// return 'successfully deleted'
// }
|
e4ed246f838efc49073158f0e00ed72a6009ac15
|
TypeScript
|
enzg/webgpu-computing-jpeg
|
/src/index.ts
| 2.65625
| 3
|
import { decode, encode, RawImageData, BufferLike } from 'jpeg-js'
import * as buffer from 'buffer';
(window as any).Buffer = buffer.Buffer;
document.getElementById('fileinput').onchange = imageSelected;
function imageSelected (event: Event) {
const files = this.files;
if (!files || files.length < 1) {
return;
}
if (files[0].type != 'image/jpeg') {
console.log('file is not a jpeg!');
return;
}
const dataUrlReader = new FileReader();
dataUrlReader.addEventListener('load', function () {
(document.getElementById('inputimage') as HTMLImageElement).src = dataUrlReader.result as string;
});
dataUrlReader.readAsDataURL(files[0]);
const arrayReader = new FileReader();
arrayReader.addEventListener('load', function () {
const d = decode(arrayReader.result as ArrayBuffer);
processImage(new Uint8Array(d.data), d.width, d.height). then(result => {
// ENCODE TO JPEG DATA
const resultImage: RawImageData<BufferLike> = {
width: d.width,
height: d.height,
data: result
}
const encoded = encode(resultImage, 100)
// AS DATA URL
let binary = '';
var bytes = new Uint8Array(encoded.data);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
let processed = 'data:' + files[0].type + ';base64,'
processed += window.btoa(binary);
// ASSIGN DATA URL TO OUTPUT IMAGE ELEMENT
(document.getElementById('outputimage') as HTMLImageElement).src = processed
});
})
arrayReader.readAsArrayBuffer(files[0]);
}
async function processImage (array: Uint8Array, width: number, height: number) : Promise<Uint8Array> {
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
return new Promise(resolve => {
// INIT BUFFERS
const sizeArray= new Int32Array([width, height]);
const gpuWidthHeightBuffer = device.createBuffer({
mappedAtCreation: true,
size: sizeArray.byteLength,
usage: GPUBufferUsage.STORAGE
});
new Int32Array(gpuWidthHeightBuffer.getMappedRange()).set(sizeArray);
gpuWidthHeightBuffer.unmap();
const gpuInputBuffer = device.createBuffer({
mappedAtCreation: true,
size: array.byteLength,
usage: GPUBufferUsage.STORAGE
});
new Uint8Array(gpuInputBuffer.getMappedRange()).set(array);
gpuInputBuffer.unmap();
const gpuResultBuffer = device.createBuffer({
size: array.byteLength,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC
});
const gpuReadBuffer = device.createBuffer({
size: array.byteLength,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
});
// BINDING GROUP LAYOUT
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer : {
type: "read-only-storage"
}
} as GPUBindGroupLayoutEntry,
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: "read-only-storage"
}
} as GPUBindGroupLayoutEntry,
{
binding: 2,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: "storage"
}
} as GPUBindGroupLayoutEntry
]
});
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: gpuWidthHeightBuffer
}
},
{
binding: 1,
resource: {
buffer: gpuInputBuffer
}
},
{
binding: 2,
resource: {
buffer: gpuResultBuffer
}
}
]
});
// SHADER
const shaderModule = device.createShaderModule({
code: `
[[block]] struct Size {
size: vec2<u32>;
};
[[block]] struct Image {
rgba: array<u32>;
};
[[group(0), binding(0)]] var<storage> widthHeight: [[access(read)]] Size;
[[group(0), binding(1)]] var<storage> inputPixels: [[access(read)]] Image;
[[group(0), binding(2)]] var<storage> outputPixels: [[access(write)]] Image;
[[stage(compute)]]
fn main ([[builtin(global_invocation_id)]] global_id: vec3<u32>) {
let index : u32 = global_id.x + global_id.y * widthHeight.size.x;
outputPixels.rgba[index] = 4294967295u - inputPixels.rgba[index];
}
`
});
const computePipeline = device.createComputePipeline({
layout: device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout]
}),
compute: {
module: shaderModule,
entryPoint: "main"
}
});
// START COMPUTE PASS
const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginComputePass();
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatch(width, height);
passEncoder.endPass();
commandEncoder.copyBufferToBuffer(gpuResultBuffer, 0, gpuReadBuffer, 0, array.byteLength);
device.queue.submit([commandEncoder.finish()]);
gpuReadBuffer.mapAsync(GPUMapMode.READ).then( () => {
resolve(new Uint8Array(gpuReadBuffer.getMappedRange()));
});
});
}
|
1457cdf6c7e4ff3a1325e3dd8e0fc1ba7f2412bd
|
TypeScript
|
TGlas/tscript
|
/src/lang/parser/parse_lhs.ts
| 2.6875
| 3
|
import { ErrorHelper } from "../errors/ErrorHelper";
import { binary_operator_impl } from "./parser_helper";
import { TScript } from "..";
import { simtrue } from "../helpers/sims";
import { Typeid } from "../helpers/typeIds";
import { parse_expression } from "./parse_expression";
export function parse_lhs(state, parent, options) {
// parse the LHS as an expression
let ex = parse_expression(state, parent, options, true);
let back = ex.passResolveBack;
ex.passResolveBack = function (state) {
if (back) back(state);
// replace the topmost step function
if (ex.petype === "name") {
if (
ex.reference.petype !== "variable" &&
ex.reference.petype !== "attribute"
)
state.error("/argument-mismatch/am-32", [
"name of type '" + ex.reference.petype + "'",
]);
ex.step = function () {
let frame = this.stack[this.stack.length - 1];
let pe: any = frame.pe[frame.pe.length - 1];
let ip = frame.ip[frame.ip.length - 1];
let op = frame.temporaries.pop();
let rhs = frame.temporaries.pop();
let base: any = null;
if (pe.scope === "global") base = this.stack[0].variables;
else if (pe.scope === "local") base = frame.variables;
else if (pe.scope === "object") base = frame.object.value.a;
else
ErrorHelper.assert(false, "unknown scope type " + pe.scope);
let index = pe.id;
let tv = base[index];
if (!tv || !tv?.type || !tv?.value)
this.error("/name/ne-29", [TScript.displayname(pe)]);
if (op !== "=") {
// binary operator corresponding to compound assignment
let binop = op.substring(0, op.length - 1);
rhs = binary_operator_impl[binop].call(
this,
base[index],
rhs
);
}
// actual assignment as a copy of the typed value
base[index] = { type: rhs.type, value: rhs.value };
frame.pe.pop();
frame.ip.pop();
return true;
};
ex.sim = simtrue;
} else if (ex.petype === "item access") {
ex.step = function () {
let frame = this.stack[this.stack.length - 1];
let pe: any = frame.pe[frame.pe.length - 1];
let ip = frame.ip[frame.ip.length - 1];
if (ip === 0) {
// evaluate the container
frame.pe.push(pe.base);
frame.ip.push(-1);
return false;
} else if (ip === 1) {
// evaluate the index
frame.pe.push(pe.argument);
frame.ip.push(-1);
return false;
} else {
// obtain all relevant values
let index = frame.temporaries.pop();
let container = frame.temporaries.pop();
let op = frame.temporaries.pop();
let rhs = frame.temporaries.pop();
// check validity
let key;
if (
TScript.isDerivedFrom(
container.type,
Typeid.typeid_string
)
) {
state.error("/argument-mismatch/am-32", [
"a substring",
]);
} else if (
TScript.isDerivedFrom(
container.type,
Typeid.typeid_array
)
) {
if (
TScript.isDerivedFrom(
index.type,
Typeid.typeid_integer
)
) {
if (index.value.b < 0)
state.error("/argument-mismatch/am-23", [
TScript.toString.call(this, index),
]);
else if (index.value.b >= container.value.b.length)
state.error("/argument-mismatch/am-24", [
TScript.toString.call(this, index),
container.value.b.length,
]);
key = index.value.b;
} else
state.error("/argument-mismatch/am-25", [
TScript.toString.call(this, index),
TScript.displayname(index.type),
]);
} else if (
TScript.isDerivedFrom(
container.type,
Typeid.typeid_dictionary
)
) {
if (
!TScript.isDerivedFrom(
index.type,
Typeid.typeid_string
)
)
state.error("/argument-mismatch/am-28", [
TScript.displayname(index.type),
]);
key = "#" + index.value.b;
} else
state.error("/argument-mismatch/am-31b", [
container.type,
]);
if (op !== "=") {
// binary operator corresponding to compound assignment
let binop = op.substring(0, op.length - 1);
// in this specific case the key must exist
if (
TScript.isDerivedFrom(
container.type,
Typeid.typeid_dictionary
)
) {
if (!container.value.b.hasOwnProperty(key))
state.error("/argument-mismatch/am-27", [
index.value.b,
]);
}
rhs = binary_operator_impl[binop].call(
this,
container.value.b[key],
rhs
);
}
// actual assignment as a deep copy of the typed value
container.value.b[key] = {
type: rhs.type,
value: rhs.value,
};
frame.pe.pop();
frame.ip.pop();
return true;
}
};
ex.sim = function () {
let frame = this.stack[this.stack.length - 1];
let ip = frame.ip[frame.ip.length - 1];
return ip > 1;
};
} else if (ex.petype.substring(0, 17) === "access of member ") {
ex.step = function () {
let frame = this.stack[this.stack.length - 1];
let pe: any = frame.pe[frame.pe.length - 1];
let ip = frame.ip[frame.ip.length - 1];
if (ip === 0) {
// evaluate the object
frame.pe.push(pe.object);
frame.ip.push(-1);
return false;
} else {
// obtain all relevant values
let object = frame.temporaries.pop();
let op = frame.temporaries.pop();
let rhs = frame.temporaries.pop();
// find the public member in the super class chain
let m: any = null;
if (
TScript.isDerivedFrom(object.type, Typeid.typeid_type)
) {
// static case
let type = object.value.b;
let sup = type;
while (sup) {
if (
sup.staticmembers.hasOwnProperty(pe.member) &&
sup.staticmembers[pe.member].access === "public"
) {
m = sup.staticmembers[pe.member];
break;
}
sup = sup.superclass;
}
if (m === null)
state.error("/name/ne-12", [
TScript.displayname(type),
pe.member,
]);
} else {
// non-static case
let type = object.type;
let sup = type;
while (sup) {
if (
sup.members.hasOwnProperty(pe.member) &&
sup.members[pe.member].access === "public"
) {
m = sup.members[pe.member];
break;
} else if (
sup.staticmembers.hasOwnProperty(pe.member) &&
sup.staticmembers[pe.member].access === "public"
) {
m = sup.staticmembers[pe.member];
break;
}
sup = sup.superclass;
}
if (m === null)
state.error("/name/ne-13", [
TScript.displayname(type),
pe.member,
]);
}
// obtain container and index
let container: any = null;
let index: any = null;
if (m.petype === "method") {
// non-static method
state.error("/argument-mismatch/am-32", ["a method"]);
} else if (m.petype === "attribute") {
// non-static attribute
container = object.value.a;
index = m.id;
} else if (m.petype === "function") {
// static function
state.error("/argument-mismatch/am-32", [
"a static method",
]);
} else if (m.petype === "variable") {
// static variable
container = this.stack[0].variables;
index = m.id;
} else if (m.petype === "type") {
// nested class
state.error("/argument-mismatch/am-32", ["a class"]);
} else
ErrorHelper.assert(
false,
"[member access] internal error; unknown member type " +
m.petype
);
let tv = container[index];
if (!tv || !tv?.type || !tv?.value)
this.error("/name/ne-29", [TScript.displayname(m)]);
if (op !== "=") {
// binary operator corresponding to compound assignment
let binop = op.substring(0, op.length - 1);
rhs = binary_operator_impl[binop].call(
this,
container[index],
rhs
);
}
// actual assignment as a deep copy of the typed value
container[index] = { type: rhs.type, value: rhs.value };
frame.pe.pop();
frame.ip.pop();
return true;
}
};
ex.sim = function () {
let frame = this.stack[this.stack.length - 1];
let ip = frame.ip[frame.ip.length - 1];
return ip !== 0;
};
} else state.error("/argument-mismatch/am-32", [ex.petype]);
};
return ex;
}
|
00c9c51d7b706db61a9b271348d6a630688715f7
|
TypeScript
|
tktsai/note_searcher
|
/vscode/e2e/utils/wait.ts
| 2.796875
| 3
|
export const waitFor = (check: () => boolean, timeoutMs = 1000, failMessage = 'timed out') => {
return new Promise((resolve, reject) => {
let start = Date.now();
const doCheck = () => {
if (Date.now() - start > timeoutMs) {
reject(failMessage);
}
if (!check()) {
setTimeout(() => doCheck(), 100);
} else {
resolve(true);
}
};
doCheck();
});
};
export const waitForAsync = (check: () => Promise<boolean>, timeoutMs = 1000) => {
return new Promise((resolve, reject) => {
let start = Date.now();
const doCheck = () => {
if (Date.now() - start > timeoutMs) {
reject('timed out');
}
check().then(result => {
if (!result) {
setTimeout(() => doCheck(), 100);
} else {
resolve(true);
}
});
};
doCheck();
});
};
|
26678d4b599b771ffdb8c17a3efd2250d73a535a
|
TypeScript
|
christopherstock/babylon-zero
|
/src/typescript/de/mayflower/bz/util/String.ts
| 3.328125
| 3
|
/** The Moment.js library import. */
const moment:any = require('moment');
/** ****************************************************************************************************************
* Offers extended string functionality.
*******************************************************************************************************************/
export class String
{
/** ************************************************************************************************************
* Returns a formatted timestamp of the current system date and time.
*
* @return string A formatted timestamp of the current system date and time.
***************************************************************************************************************/
public static getDateTimeString():string
{
return new moment().format( 'DD.MM.YYYY HH:mm:ss' );
}
/** ************************************************************************************************************
* Returns an array of all found regular expression matches.
* The subject will need the 'multiple' modifier for this method to work as expected.
* e.g. /[a-z]+/g
*
* @param subject The target string to apply the regular expression search on.
* @param regEx The regular expression.
* This string MUST NOT be enclosed in string quotes!
* @return An array containing all matched results.
***************************************************************************************************************/
public static searchRegEx( subject:string, regEx:RegExp ) : string[]
{
const results:RegExpMatchArray = subject.match( regEx );
const ret:string[] = [];
if ( results != null )
{
for ( const result of results )
{
ret.push( result );
}
}
return ret;
}
}
|
899a0b072a98659cb08d8a13a5e73fe41216a140
|
TypeScript
|
qathom/asad-lab1
|
/backend/src/app/Player.ts
| 3.03125
| 3
|
export class Player {
// Private id
// Private bank ?
id: string
password: string
bank: number
currentAmountBetted: number
constructor(id: string, password: string, bank: number) {
this.id = id
this.password = password
this.bank = bank
this.currentAmountBetted = 0
}
canBet(amount: number): boolean {
return (this.currentAmountBetted + amount) <= this.bank
}
toJSON() {
return {
id: this.id,
password: this.password,
bank: this.bank,
}
}
}
|
2a71a7810f9eeedf3293c07542df3955f3713c9e
|
TypeScript
|
reduxjs/redux-toolkit
|
/packages/toolkit/src/getDefaultMiddleware.ts
| 2.78125
| 3
|
import type { Middleware, AnyAction } from 'redux'
import type { ThunkMiddleware } from 'redux-thunk'
import thunkMiddleware from 'redux-thunk'
import type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
import { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
import type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware'
/* PROD_START_REMOVE_UMD */
import { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware'
/* PROD_STOP_REMOVE_UMD */
import type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware'
import { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware'
import type { ExcludeFromTuple } from './tsHelpers'
import { MiddlewareArray } from './utils'
function isBoolean(x: any): x is boolean {
return typeof x === 'boolean'
}
interface ThunkOptions<E = any> {
extraArgument: E
}
interface GetDefaultMiddlewareOptions {
thunk?: boolean | ThunkOptions
immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions
serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions
actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions
}
export type ThunkMiddlewareFor<
S,
O extends GetDefaultMiddlewareOptions = {}
> = O extends {
thunk: false
}
? never
: O extends { thunk: { extraArgument: infer E } }
? ThunkMiddleware<S, AnyAction, E>
: ThunkMiddleware<S, AnyAction>
export type CurriedGetDefaultMiddleware<S = any> = <
O extends Partial<GetDefaultMiddlewareOptions> = {
thunk: true
immutableCheck: true
serializableCheck: true
actionCreatorCheck: true
}
>(
options?: O
) => MiddlewareArray<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>
export function curryGetDefaultMiddleware<
S = any
>(): CurriedGetDefaultMiddleware<S> {
return function curriedGetDefaultMiddleware(options) {
return getDefaultMiddleware(options)
}
}
/**
* Returns any array containing the default middleware installed by
* `configureStore()`. Useful if you want to configure your store with a custom
* `middleware` array but still keep the default set.
*
* @return The default middleware used by `configureStore()`.
*
* @public
*
* @deprecated Prefer to use the callback notation for the `middleware` option in `configureStore`
* to access a pre-typed `getDefaultMiddleware` instead.
*/
export function getDefaultMiddleware<
S = any,
O extends Partial<GetDefaultMiddlewareOptions> = {
thunk: true
immutableCheck: true
serializableCheck: true
actionCreatorCheck: true
}
>(
options: O = {} as O
): MiddlewareArray<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>> {
const {
thunk = true,
immutableCheck = true,
serializableCheck = true,
actionCreatorCheck = true,
} = options
let middlewareArray = new MiddlewareArray<Middleware[]>()
if (thunk) {
if (isBoolean(thunk)) {
middlewareArray.push(thunkMiddleware)
} else {
middlewareArray.push(
thunkMiddleware.withExtraArgument(thunk.extraArgument)
)
}
}
if (process.env.NODE_ENV !== 'production') {
if (immutableCheck) {
/* PROD_START_REMOVE_UMD */
let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {}
if (!isBoolean(immutableCheck)) {
immutableOptions = immutableCheck
}
middlewareArray.unshift(
createImmutableStateInvariantMiddleware(immutableOptions)
)
/* PROD_STOP_REMOVE_UMD */
}
if (serializableCheck) {
let serializableOptions: SerializableStateInvariantMiddlewareOptions = {}
if (!isBoolean(serializableCheck)) {
serializableOptions = serializableCheck
}
middlewareArray.push(
createSerializableStateInvariantMiddleware(serializableOptions)
)
}
if (actionCreatorCheck) {
let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {}
if (!isBoolean(actionCreatorCheck)) {
actionCreatorOptions = actionCreatorCheck
}
middlewareArray.unshift(
createActionCreatorInvariantMiddleware(actionCreatorOptions)
)
}
}
return middlewareArray as any
}
|
e88ae66eed62fec8d3c8dbfbbb078cdddea21616
|
TypeScript
|
blackbaud/skyux
|
/libs/components/theme/src/lib/theming/theme.ts
| 3.015625
| 3
|
import { SkyThemeMode } from './theme-mode';
import { SkyThemeSpacing } from './theme-spacing';
/**
* Defines properties of a SKY UX theme.
*/
export class SkyTheme {
/**
* The preset themes available in SKY UX.
*/
public static readonly presets = {
default: new SkyTheme(
'default',
'sky-theme-default',
[SkyThemeMode.presets.light],
[SkyThemeSpacing.presets.standard]
),
modern: new SkyTheme(
'modern',
'sky-theme-modern',
[SkyThemeMode.presets.light, SkyThemeMode.presets.dark],
[SkyThemeSpacing.presets.standard, SkyThemeSpacing.presets.compact]
),
};
/**
* Creates a new theme.
* @param name The name of the theme.
* @param hostClass The class on the host element which child components should reference when
* adjusting for a specified theme.
* @param supportedModes An array of modes supported by the theme.
* @param supportedSpacing An array of spacing modes supported by the theme.
*/
constructor(
public readonly name: string,
public readonly hostClass: string,
public readonly supportedModes: SkyThemeMode[],
public readonly supportedSpacing = [SkyThemeSpacing.presets.standard]
) {}
}
|
5854c3d9375ecf26454f203c8e4f00f84b0bc550
|
TypeScript
|
rodskin/frogtown2020
|
/src/integration_tests/assertions.test.ts
| 2.609375
| 3
|
// eslint-disable-next-line node/no-unpublished-import
import puppeteer from "puppeteer";
import Assert from "./assertions";
let browser: puppeteer.Browser | null = null;
const pageGetter = (async () => {
browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(`
<html>
<head>
<style>
.nodisp {
display: none;
}
</style>
</head>
<body>
<div id="divOne">div one content</div>
<div id="divTwo">
<div id="divThree" class="nodisp">div three content</div>
</div>
<div id="divFour" class="nodisp"></div>
<div id="divFive" class="nodisp">
<div id="divSix">div six content</div>
</div>
<input type="text" id="inputText" value="input content" />
</body>
</html>
`);
return page;
})();
test("Assert.equals", async () => {
await expect(Assert.equals("a", "a")).resolves.not.toThrow();
await expect(Assert.equals("1", "1")).resolves.not.toThrow();
await expect(Assert.equals(1, 1)).resolves.not.toThrow();
await expect(Assert.equals(2, 1)).rejects.toThrow();
await expect(Assert.equals("a", "b")).rejects.toThrow();
});
test("Assert.notEquals", async () => {
await expect(Assert.notEquals("a", "a")).rejects.toThrow();
await expect(Assert.notEquals("1", "1")).rejects.toThrow();
await expect(Assert.notEquals(1, 1)).rejects.toThrow();
await expect(Assert.notEquals(2, 1)).resolves.not.toThrow();
await expect(Assert.notEquals("a", "b")).resolves.not.toThrow();
});
test("Assert.contains", async () => {
await expect(Assert.contains("abcdefg", "xyz")).rejects.toThrow();
await expect(Assert.contains("xyz", "y")).resolves.not.toThrow();
});
test("Assert.doesntContain", async () => {
await expect(Assert.doesntContain("abcdefg", "xyz")).resolves.not.toThrow();
await expect(Assert.doesntContain("xyz", "y")).rejects.toThrow();
});
test("Assert.visible", async () => {
const page = await pageGetter;
await expect(Assert.visible(page, "#divOne")).resolves.not.toThrow();
await expect(Assert.visible(page, "#divTwo")).resolves.not.toThrow();
await expect(Assert.visible(page, "#divThree")).rejects.toThrow();
await expect(Assert.visible(page, "#divFour")).rejects.toThrow();
await expect(Assert.visible(page, "#divFive")).rejects.toThrow();
await expect(Assert.visible(page, "#divSix")).rejects.toThrow();
});
test("Assert.notVisible", async () => {
const page = await pageGetter;
await expect(Assert.notVisible(page, "#divOne")).rejects.toThrow();
await expect(Assert.notVisible(page, "#divTwo")).rejects.toThrow();
await expect(Assert.notVisible(page, "#divThree")).resolves.not.toThrow();
await expect(Assert.notVisible(page, "#divFour")).resolves.not.toThrow();
await expect(Assert.notVisible(page, "#divFive")).resolves.not.toThrow();
await expect(Assert.notVisible(page, "#divSix")).resolves.not.toThrow();
});
test("Assert.existsAndGetValue", async () => {
const page = await pageGetter;
await expect(
Assert.existsAndGetValue(page, "#fakeDiv", "className")
).rejects.toThrow();
await expect(
Assert.existsAndGetValue(page, "#divThree", "className")
).resolves.toBe("nodisp");
await expect(
Assert.existsAndGetValue(page, "#inputText", "value")
).resolves.toBe("input content");
});
test("Assert.valueSatisfies", async () => {
const page = await pageGetter;
await expect(
Assert.valueSatisfies(
page,
"#fakeDiv",
"className",
(className) => className === ""
)
).rejects.toThrow();
await expect(
Assert.valueSatisfies(
page,
"#divThree",
"className",
(className: string) => className === "nodisp"
)
).resolves.not.toThrow();
await expect(
Assert.valueSatisfies(
page,
"#inputText",
"value",
(className: string) => className === "input content"
)
).resolves.not.toThrow();
await expect(
Assert.valueSatisfies(
page,
"#inputText",
"value",
(className: string) => className === "wrong input content"
)
).rejects.toThrow();
});
afterAll(async () => {
await browser!.close();
});
|
c86b7e5a69bd432fa52c90298f50a62246d2fe58
|
TypeScript
|
Rian8337/Alice
|
/src/localization/interactions/commands/Bot Creators/unbind/translations/UnbindESTranslation.ts
| 2.671875
| 3
|
import { Translation } from "@alice-localization/base/Translation";
import { UnbindStrings } from "../UnbindLocalization";
/**
* The Spanish translation for the `unbind` command.
*/
export class UnbindESTranslation extends Translation<UnbindStrings> {
override readonly translations: UnbindStrings = {
invalidUid: "Hey, por favor ingresa un uid válido!",
uidNotBinded: "Lo siento, ese uid no esta asociado a nadie!",
unbindFailed: "Lo siento, no puedo desenlazar el uid: %s",
unbindSuccessful: "Uid %s desenlazado correctamente.",
};
}
|
797d63b8bc895b1357ea68097e6c09f5f347b5fb
|
TypeScript
|
eddie-englund/CourseBot
|
/src/bot/commands/moderation/case.ts
| 2.828125
| 3
|
import { Command } from 'discord-akairo';
import { CourseClient } from '../../client/CourseClient';
import { Message } from 'discord.js';
export default class CaseEdit extends Command {
public client: CourseClient;
public constructor() {
super('case-edit', {
aliases: ['case', 'editcase'],
userPermissions: ['MANAGE_MESSAGES'],
clientPermissions: ['SEND_MESSAGES'],
category: 'moderation',
description: {
content: 'edits a case',
usage: '<case> <new reason>',
},
args: [
{
id: 'case',
type: 'integer',
prompt: {
start: (message: Message): string => `${message.author}, which case would you like to update?`,
retry: (message: Message): string => `${message.author}, please provide a valid case number`,
},
},
{
id: 'reason',
type: 'string',
match: 'rest',
prompt: {
start: (message: Message): string => `${message.author}, what was the reason for that case?`,
retry: (message: Message): string => `${message.author}, please provid a reason for that case.`,
},
},
],
});
}
public async exec(message: Message, args) {
try {
await this.client.db.GetCase(args.case);
} catch (error) {
this.client.logger.error(error);
return message.util!.reply(
`It appears that there is no such entry in the db! The database returned error: ${error.message}`
);
}
try {
await this.client.db.UpdateCase(args.case, { reason: args.reason });
} catch (error) {
this.client.logger.error(error);
return message.util!.reply(`Something went wrong updating the tag! Error message: ${error.message}`);
}
return message.util!.send(`Updated case **${args.case}**`);
}
}
|
1a96f920550509004f0cffa6cb82577d775bd456
|
TypeScript
|
GabrielDertoni/notes
|
/src/entities/Image.ts
| 2.53125
| 3
|
import IBlock from "./Block";
export default class Image implements IBlock {
public readonly type = "image";
constructor(protected src?: string) {}
get data() {
return {}
}
}
|
dd5a6dad96f6191073096548a7a5f470bb39d349
|
TypeScript
|
waaaave/lsl_fullstack
|
/typescript/src/user.ts
| 3.140625
| 3
|
// 不严格
type User = {
name:string;
age:number;
occupation:string;
}
const users:User[] = [
{
name:"wave",
age:17,
occupation:"Chimney sweep"
},
{
name:"刘印",
age:18,
occupation:"Astronaut"
}
]
users.map(user =>`
<li>
${user.name}-${user.age}-${user.occupation}
</li>
`
)
|
cf0ef3376b3ecfafa24018a7794992a1db9591da
|
TypeScript
|
green-fox-academy/Hpeter1988
|
/week-04/day-3/comperator/domino.ts
| 4.125
| 4
|
"use strict";
interface Comparable {
compareTo(other: Comparable): number;
/*
* returns negative number if this is smaller than other
* returns 0 if they are the same
* returns positive number if this is greater than other
*/
}
class Domino implements Comparable {
values: number[];
constructor(valueA: number, valueB: number) {
this.values = [valueA, valueB];
}
compareTo(other: Domino): number {
if (this.values[0] < other.values[0]) {
return -1;
} else if (this.values[0] > other.values[0]) {
return 1;
} else return 0;
}
}
let dominoes: Domino[] = [];
dominoes.push(new Domino(5, 2));
dominoes.push(new Domino(4, 6));
dominoes.push(new Domino(1, 5));
dominoes.push(new Domino(6, 7));
dominoes.push(new Domino(2, 4));
dominoes.push(new Domino(7, 1));
console.log(dominoes);
dominoes.sort(function(a: Domino, b: Domino): number {
return a.compareTo(b);
});
console.log('-----------------------')
console.log(dominoes)
// the order of your dominoes should look like this: [[1,5], [2,4], [4,6], [5,2], [6,7], [7,1]]
export { Comparable };
|
5e9e0fc4c5ad07a70a94c607a29a7caf6b313a70
|
TypeScript
|
kcsry/infotv
|
/infotv/frontend/src/DatumManager.ts
| 3.171875
| 3
|
export interface Datum<T = any> {
value: T;
mtime: number;
virtual?: boolean;
}
const datums: Record<string, Datum> = {};
export class DatumManager {
public update(data: Record<string, Datum>) {
Object.assign(datums, data);
}
public setValue<T = any>(key: string, value: T): Datum<T> {
const datum: Datum<T> = { value, mtime: 0, virtual: true };
datums[key] = datum;
return datum;
}
public getValue<T = any>(key: string, defaultValue?: T): T {
const datum = datums[key];
if (datum) {
return datum.value as T;
}
return defaultValue as T;
}
public getFull<T = any>(key: string): Datum<T> | undefined {
return datums[key] || undefined;
}
}
const instance = new DatumManager();
export default instance;
|
98055176102ec02f0d19ac8e494fc85f37ebc14a
|
TypeScript
|
DSpace/dspace-angular
|
/src/app/core/shared/hal-resource.model.ts
| 2.703125
| 3
|
import { HALLink } from './hal-link.model';
import { deserialize } from 'cerialize';
/**
* Represents HAL resources.
*
* A HAL resource has a _links section with at least a self link.
*/
export class HALResource {
/**
* The {@link HALLink}s for this {@link HALResource}
*/
@deserialize
_links: {
/**
* The {@link HALLink} that refers to this {@link HALResource}
*/
self: HALLink
/**
* {@link HALLink}s to related {@link HALResource}s
*/
[k: string]: HALLink | HALLink[];
};
}
|
4feb7def15a5d3b7fbae280d22fd53fdce278ccb
|
TypeScript
|
linz/GNSS-Site-Manager
|
/src/client/app/shared/service-worker/service-worker.service.ts
| 2.765625
| 3
|
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { MessageObject } from './messages.interface';
/**
* This class provides the service for the application's service worker that is global to the browser.
*/
@Injectable()
export class ServiceWorkerService {
// Setup Observables (BehaviorSubject's to be specific) to communicate between components
protected clearCacheFlag = new BehaviorSubject<boolean>(false);
// Observable
public clearCacheObservable = this.clearCacheFlag.asObservable();
/**
*
* @returns {Promise<any>} that may contain a message about the operation
*/
clearCache(): Promise<string> {
let promise: Promise<string> = this.postMessage({operation: 'clear_cache'});
promise.then(() => {
this.clearCacheFlag.next(true);
});
return promise;
}
/**
*
* @returns {Promise<any>} that contains an array of items in the cache
*/
getCacheList(): Promise<string[]> {
return this.postMessage({operation: 'get_cache'});
}
/**
* Generic method to post messages to the service worker and return a promise to the caller
* @param operation to be performed
* @param message is the optional message to be sent with that operation
* @returns {Promise<T>} that is appropriate to the client of this method
*/
/**
* Generic method to post messages to the service worker and return a promise to the caller
* @param message MessageObject with fields 'operation' and optional message.
* @returns {Promise<T>} that is appropriate to the client of this method
*/
postMessage(message: MessageObject): Promise<any> {
// let messageObject = {operation: operation, message: message} as MessageObject;
return new Promise((resolve: Function, reject: Function) => {
if ('serviceWorker' in navigator && navigator.serviceWorker
&& 'controller' in navigator.serviceWorker
&& navigator.serviceWorker.controller) {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function (event: MessageEvent) {
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
// This sends the message data as well as transferring messageChannel.port2 to the service worker.
// The service worker can then use the transferred port to reply via postMessage(), which
// will in turn trigger the onmessage handler on messageChannel.port1.
navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]);
} else {
console.log('postMessage: service worker not ready');
}
});
}
}
|
c2566e3c2315191f45df8d54a417e3a33596b5a5
|
TypeScript
|
WisdomSpirit/typescript-task-1
|
/src/views/common-view.ts
| 3.125
| 3
|
import { IObservable } from '../utils/observable/types';
import { NewsState } from '../state/news';
import { WeatherState } from '../state/weather';
import { IArticle } from '../state/news/types';
import { IMeasurement } from '../state/weather/types';
export class CommonView {
private readonly weatherCount: number;
private readonly newsCount: number;
private currentNews: IArticle[] = [];
private currentWeather: IMeasurement[] = [];
private newsToRender: IArticle[] = [];
private weatherToRender: IMeasurement[] = [];
protected constructor(newsCount: number, weatherCount: number) {
this.weatherCount = weatherCount;
this.newsCount = newsCount;
}
protected commonUpdate(observable: IObservable) {
if (observable instanceof NewsState) {
const all = observable.getArticles();
this.newsToRender = all.slice(all.length - this.newsCount);
} else if (observable instanceof WeatherState) {
const all = observable.getMeasurements();
this.weatherToRender = all.slice(all.length - this.weatherCount);
} else {
throw new Error('Wrong state: should be news or weather');
}
}
protected preRender(): string {
let result: string = '';
this.newsToRender.forEach(n => (result += `[${n.time}] ${n.category} - ${n.title}\n`));
this.weatherToRender.forEach(
w => (result += `[${w.time}] ${w.temperature} C, ${w.pressure} P, ${w.humidity} U\n`)
);
this.tidyUp();
return result;
}
protected isRenderNeeded(): boolean {
return (
!this.isShallowEqual(this.currentNews, this.newsToRender) ||
!this.isShallowEqual(this.currentWeather, this.weatherToRender)
);
}
private tidyUp() {
this.currentNews.splice(0, this.currentNews.length, ...this.newsToRender);
this.currentWeather.splice(0, this.currentWeather.length, ...this.weatherToRender);
}
private isShallowEqual(
arr1: IArticle[] | IMeasurement[],
arr2: IArticle[] | IMeasurement[]
): boolean {
if (arr1.length === arr2.length) {
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
return false;
}
}
|
f654ed7d81b31c2a292a05bfce24db71d0093dfe
|
TypeScript
|
filipeferreira-dev/neo-tinder-app
|
/src/pages/home-catalog/crush.model.ts
| 2.53125
| 3
|
export class Crush {
constructor(
public name: string,
public age: number,
public percent: number,
public description: string,
public image: string
) {
}
}
|
fb953c6f78c7b030eeac5751df65f7e5b917803d
|
TypeScript
|
tpandseed/get-hitched
|
/_site/index.ts
| 2.734375
| 3
|
import { User } from "netlify-identity-widget";
const zeroDay = new Date('2020-09-15T16:20:00');
function userEvent(userObj: User | null) {
window.dispatchEvent(new CustomEvent('user-login', { detail: userObj }));
}
declare var netlifyIdentity: { on: (event: string, user: { (u: User): void; }) => void; };
netlifyIdentity.on('init', u => userEvent(u));
netlifyIdentity.on('login', u => userEvent(u));
netlifyIdentity.on('logout', () => userEvent(null));
function calcDays() {
return ((Date.now() - zeroDay.getTime()) / (1000 * 3600 * 24)).toFixed(5);
}
function stuff() {
return {
user: null as unknown as User,
setUser(userInfo : User) {
this.user = userInfo;
},
userDisplay() {
if (this.user)
return this.userFirstName();
return 'everyone';
},
userFirstName() {
if (this.user)
return this.user.user_metadata.full_name.split(' ')[0];
return ''
},
daysUntil: calcDays().toString(),
dayTimer() {
setInterval(() => {
this.daysUntil = calcDays().toString();
}, 1000);
},
click() {
console.log(this.user);
}
}
}
|
f1fa693f5e1cc75a12e5e8c0d9f5841e09a528bc
|
TypeScript
|
veranoo/simple-unsplash-app
|
/src/reducers/section-reducer.ts
| 2.75
| 3
|
export const SET_ERROR = 'SET_ERROR';
export const SET_PHOTOS = 'SET_PHOTOS';
export const SET_LOAD_MORE = 'SET_LOAD_MORE';
export const SET_NOT_LOAD_MORE = 'SET_NOT_LOAD_MORE';
export const SET_LOAD_MORE_ERROR = 'SET_LOAD_MORE_ERROR';
export const sectionReducer = (state, action) => {
switch (action.type) {
case SET_ERROR:
return {
...state,
hasMore: false,
error: true,
photos: []
};
case SET_PHOTOS:
return {
...state,
photos: action.payload.photos,
hasMore: true
};
case SET_LOAD_MORE:
return {
...state,
photos: [...state.photos, ...action.payload.photos],
hasMore: true
};
case SET_NOT_LOAD_MORE:
return {
...state,
hasMore: false
};
case SET_LOAD_MORE_ERROR:
return {
...state,
error: true,
hasMore: false
};
}
};
|
c957c3e325e4cc5585f164dec728fa84f553f4fe
|
TypeScript
|
TyTy-cf/hb_pe1_angular
|
/src/models/yatzee/yahtzee.ts
| 3
| 3
|
import {Dice} from "./dice";
export class Yahtzee {
private _myDice: Array<Dice> = [];
private _round: number = 0;
throwDice(): void {
this._myDice = [];
for (let i = 1; i <= 5; i++) {
this._myDice.push(new Dice());
}
this.round++;
}
get round(): number {
return this._round;
}
set round(value: number) {
this._round = value;
}
/**
* Fonction permettant de relancer les dés selectionnés
* (Ou les non-sélectionnés, au choix...)
*/
rerollDice(): void {
// parcourir le tableau de dés
for (const index in this._myDice) {
// si mon dé est sélectionné
if (this._myDice[index].isSelected) {
// je re-créé le dé
this._myDice[index] = new Dice();
}
}
}
get myDice(): Array<Dice> {
return this._myDice;
}
}
|
c225e8a77d7725e83d8705ef29a9ba87f121b21e
|
TypeScript
|
pedroamaral91/github-api
|
/packages/api/src/main/decorators/axios-exception-handler.decorator.ts
| 2.703125
| 3
|
import { Controller } from '@/presentation/protocols/controller'
import { HttpResponse } from '@/presentation/protocols/http'
export class AxiosHttpExceptionHandlerDecorator implements Controller {
constructor (
private readonly controller: Controller
) {}
async handle (request: any): Promise<HttpResponse> {
try {
return await this.controller.handle(request)
} catch (err) {
const statusCode = err?.response?.status ?? 500
const response = { status: statusCode, error: err?.response?.data?.errors ?? 'INTERNAL SERVER ERROR' }
return { statusCode, body: response }
}
}
}
|
6b105ea93d0809dc3e14d9e07609afffb0cad0d5
|
TypeScript
|
matrix-org/matrix-appservice-bridge
|
/src/components/event-bridge-store.ts
| 2.546875
| 3
|
/*
Copyright 2019 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Datastore from "nedb";
import { BridgeStore } from "./bridge-store";
import { StoredEvent, StoredEventDoc } from "../models/events/event";
/**
* Construct a store suitable for event mapping information. Data is stored
* as {@link StoredEvent}s.
* @constructor
* @param db The connected NEDB database instance
*/
export class EventBridgeStore extends BridgeStore {
constructor(db: Datastore) { super(db) }
/**
* Insert an event, clobbering based on the ID of the StoredEvent.
* @param event
*/
public upsertEvent(event: StoredEvent) {
return this.upsert({
id: event.getId()
}, event.serialize());
}
/**
* Get an existing event based on the provided matrix IDs.
* @param roomId The ID of the room.
* @param eventId The ID of the event.
* @return A promise which resolves to the StoredEvent or null.
*/
public getEntryByMatrixId(roomId: string, eventId: string): Promise<StoredEvent|null> {
return this.selectOne<any, StoredEvent>({
"matrix.roomId": roomId,
"matrix.eventId": eventId,
}, (this.convertTo(function(doc: StoredEventDoc) {
return StoredEvent.deserialize(doc);
})));
}
/**
* Get an existing event based on the provided remote IDs.
* @param roomId The ID of the room.
* @param eventId The ID of the event.
* @return A promise which resolves to the StoredEvent or null.
*/
public getEntryByRemoteId(roomId: string, eventId: string) {
return this.selectOne({
"remote.roomId": roomId,
"remote.eventId": eventId,
}, this.convertTo((doc: StoredEventDoc) => {
return StoredEvent.deserialize(doc);
}));
}
/**
* Remove entries based on the event data.
* @param event The event to remove.
*/
public removeEvent(event: StoredEvent) {
return this.delete({
id: event.getId(),
});
}
/**
* Remove entries based on the matrix IDs.
* @param roomId The ID of the room.
* @param eventId The ID of the event.
*/
public removeEventByMatrixId(roomId: string, eventId: string) {
return this.delete({
"matrix.roomId": roomId,
"matrix.eventId": eventId,
});
}
/**
* Remove entries based on the matrix IDs.
* @param roomId The ID of the room.
* @param eventId The ID of the event.
*/
public removeEventByRemoteId(roomId: string, eventId: string) {
return this.delete({
"remote.roomId": roomId,
"remote.eventId": eventId,
});
}
}
|
094faaa34e4f5fc8e05bd6496dc10085ed8340db
|
TypeScript
|
vercel/next.js
|
/packages/next/src/client/router.ts
| 2.59375
| 3
|
/* global window */
import React from 'react'
import Router from '../shared/lib/router/router'
import type { NextRouter } from '../shared/lib/router/router'
import { RouterContext } from '../shared/lib/router-context'
import isError from '../lib/is-error'
type SingletonRouterBase = {
router: Router | null
readyCallbacks: Array<() => any>
ready(cb: () => any): void
}
export { Router }
export type { NextRouter }
export type SingletonRouter = SingletonRouterBase & NextRouter
const singletonRouter: SingletonRouterBase = {
router: null, // holds the actual router instance
readyCallbacks: [],
ready(callback: () => void) {
if (this.router) return callback()
if (typeof window !== 'undefined') {
this.readyCallbacks.push(callback)
}
},
}
// Create public properties and methods of the router in the singletonRouter
const urlPropertyFields = [
'pathname',
'route',
'query',
'asPath',
'components',
'isFallback',
'basePath',
'locale',
'locales',
'defaultLocale',
'isReady',
'isPreview',
'isLocaleDomain',
'domainLocales',
] as const
const routerEvents = [
'routeChangeStart',
'beforeHistoryChange',
'routeChangeComplete',
'routeChangeError',
'hashChangeStart',
'hashChangeComplete',
] as const
export type RouterEvent = (typeof routerEvents)[number]
const coreMethodFields = [
'push',
'replace',
'reload',
'back',
'prefetch',
'beforePopState',
] as const
// Events is a static property on the router, the router doesn't have to be initialized to use it
Object.defineProperty(singletonRouter, 'events', {
get() {
return Router.events
},
})
function getRouter(): Router {
if (!singletonRouter.router) {
const message =
'No router instance found.\n' +
'You should only use "next/router" on the client side of your app.\n'
throw new Error(message)
}
return singletonRouter.router
}
urlPropertyFields.forEach((field) => {
// Here we need to use Object.defineProperty because we need to return
// the property assigned to the actual router
// The value might get changed as we change routes and this is the
// proper way to access it
Object.defineProperty(singletonRouter, field, {
get() {
const router = getRouter()
return router[field] as string
},
})
})
coreMethodFields.forEach((field) => {
// We don't really know the types here, so we add them later instead
;(singletonRouter as any)[field] = (...args: any[]) => {
const router = getRouter() as any
return router[field](...args)
}
})
routerEvents.forEach((event) => {
singletonRouter.ready(() => {
Router.events.on(event, (...args) => {
const eventField = `on${event.charAt(0).toUpperCase()}${event.substring(
1
)}`
const _singletonRouter = singletonRouter as any
if (_singletonRouter[eventField]) {
try {
_singletonRouter[eventField](...args)
} catch (err) {
console.error(`Error when running the Router event: ${eventField}`)
console.error(
isError(err) ? `${err.message}\n${err.stack}` : err + ''
)
}
}
})
})
})
// Export the singletonRouter and this is the public API.
export default singletonRouter as SingletonRouter
// Reexport the withRouter HOC
export { default as withRouter } from './with-router'
export function useRouter(): NextRouter {
const router = React.useContext(RouterContext)
if (!router) {
throw new Error(
'NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted'
)
}
return router
}
// INTERNAL APIS
// -------------
// (do not use following exports inside the app)
/**
* Create a router and assign it as the singleton instance.
* This is used in client side when we are initializing the app.
* This should **not** be used inside the server.
* @internal
*/
export function createRouter(
...args: ConstructorParameters<typeof Router>
): Router {
singletonRouter.router = new Router(...args)
singletonRouter.readyCallbacks.forEach((cb) => cb())
singletonRouter.readyCallbacks = []
return singletonRouter.router
}
/**
* This function is used to create the `withRouter` router instance
* @internal
*/
export function makePublicRouterInstance(router: Router): NextRouter {
const scopedRouter = router as any
const instance = {} as any
for (const property of urlPropertyFields) {
if (typeof scopedRouter[property] === 'object') {
instance[property] = Object.assign(
Array.isArray(scopedRouter[property]) ? [] : {},
scopedRouter[property]
) // makes sure query is not stateful
continue
}
instance[property] = scopedRouter[property]
}
// Events is a static property on the router, the router doesn't have to be initialized to use it
instance.events = Router.events
coreMethodFields.forEach((field) => {
instance[field] = (...args: any[]) => {
return scopedRouter[field](...args)
}
})
return instance
}
|
eea1059bc98bc65fe6e65655469812dcedfb8d32
|
TypeScript
|
hhp1614/utils-ts
|
/src/common/math/thousandth/index.ts
| 2.96875
| 3
|
/**
* 数字转化为千分位格式
* @description 超大数字会有问题
* @param num 数字
*/
export function thousandth(num: number) {
return (+num).toLocaleString('en-us');
}
|
9543853d9a8ab79f3072ccf3a01f0ff2006312a0
|
TypeScript
|
Cuality/ERC721-Marketplace
|
/store/scene.ts
| 2.515625
| 3
|
import { NuxtApp } from 'nuxt'
import { ActionTree, GetterTree, MutationTree } from 'vuex'
import { RootActionTree, RootState } from '../types'
import { SceneState } from '../types/scene'
export const SET_SIZE = 'SET_SIZE'
export const state = (): SceneState => ({
width: 500,
height: 500
})
export const getters: GetterTree<SceneState, RootState> = {
scene(state) {
return {
width: state.width,
height: state.height,
}
}
}
export const mutations: MutationTree<SceneState> = {
SET_SIZE(state: SceneState, payload) {
state.width = payload.width
state.height = payload.height
}
}
export const actions: ActionTree<SceneState, RootState> = {
async setSize({ commit }, payload) {
commit(SET_SIZE, payload)
}
}
|
3fefec20b1cd13969922a250565d82e6e7ada0d4
|
TypeScript
|
vikramIde/airgap-coin-lib
|
/src/protocols/cosmos/CosmosCoin.ts
| 2.8125
| 3
|
import { JSONConvertible, RPCConvertible } from './CosmosTransaction'
export interface CosmosCoinJSON {
denom: string
amount: string
}
export class CosmosCoin implements JSONConvertible, RPCConvertible {
private static readonly supportedDenominations = ['uatom']
public readonly denom: string
public readonly amount: string
constructor(denom: string, amount: string) {
this.denom = denom
this.amount = amount
}
public toJSON(): CosmosCoinJSON {
return {
amount: this.amount,
denom: this.denom
}
}
public static fromJSON(json: CosmosCoinJSON): CosmosCoin {
if (!CosmosCoin.supportedDenominations.includes(json.denom)) {
throw new Error('Unsupported cosmos denomination')
}
return new CosmosCoin(json.denom, json.amount)
}
public toRPCBody(): any {
return {
amount: this.amount,
denom: this.denom
}
}
public static fromRPCBody(json: any): CosmosCoin {
return new CosmosCoin(json.denom, json.amount)
}
}
|
a74ac79e6137315b7d0265acaeb46acf0da50a12
|
TypeScript
|
xiangbin0712/ying-datastructures-algorithms
|
/src/core/datastructures/linkedList/doublyLinkedList.ts
| 3.40625
| 3
|
'use strict'
import { DLLNode } from 'core/node'
import LinkedList from './linkedList'
/**
* 双向链表(DoublyLinkedList):双向链表与普通链表的区别在于,双向链表是双向的....有点废话
*/
export default class DoublyLinkedList<T> extends LinkedList<T> {
public head: DLLNode<T> | undefined // 表头
public tail: DLLNode<T> | undefined // 表尾
constructor() {
super()
// this.head = null // 链表头部
// this.length = 0 // 链表长度
}
append(element: T): DoublyLinkedList<T> {
let node: DLLNode<T> = new DLLNode(element)
if (this.head === null) {
// 链表中第一个节点
this.head = node
this.tail = node
} else {
this.tail.next = node
node.prev = this.tail
this.tail = node
}
this.length++ // 更新链表的长度
return this
}
insert(position: number, element: T): DoublyLinkedList<T> {
// 向链表的特定位置插入一个新的元素。
//检查越界值
if (position >= 0 && position <= this.length) {
let node: DLLNode<T> = new DLLNode(element)
let current: DLLNode<T> = this.head
let previous: DLLNode<T>
let index: number = 0
if (position === 0) {
if (!this.head) {
this.head = node
this.tail = node
} else {
node.next = current
current.prev = node
this.head = node
}
} else if (position === this.length) {
current = this.tail
current.next = node
node.prev = current
this.tail = node
} else {
while (index++ < position) {
previous = current
current = current.next
}
node.next = current
previous.next = node
current.prev = node
node.prev = previous
}
this.length++
}
return this
}
removeAt(position: number): T | null {
// 删除指定位置元素
if (position >= 0 && position < this.length) {
let current = this.head
if (position === 0) {
this.head = this.head.next
if (this.length === 1) {
this.tail = null
} else {
this.head.prev = null
}
} else if (position === this.length - 1) {
current = this.tail
this.tail = current.prev
this.tail.next = null
} else {
current = this.getAt(position)
const previous = current.prev
previous.next = current.next
current.next.prev = previous
}
this.length--
return current.element
} else {
return null
}
}
getTail(): DLLNode<T> {
// 返回尾部信息
return this.tail || null
}
toString(): string {
// 转换为字符串
if (this.tail == null) {
return ''
}
let objString = `${this.tail.element}`
let previous = this.tail.prev
while (previous != null) {
objString = `${objString},${previous.element}`
previous = previous.prev
}
return objString
}
print() {
console.log(this.toString())
}
clear() {
super.clear()
this.tail = null
}
}
|
3bd67b3c2b94b36506be06ac19b1a6f34f9f0200
|
TypeScript
|
ArthurAkhmerov/sd-olimpiad
|
/src/app/services/domains.service.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
import { Cell } from 'app/classes/Cell';
import { colorPalette } from 'app/constants/colorPalette';
@Injectable()
export class DomainsService {
visitedCells: boolean[][];
currentRow: Cell[];
currentCell:Cell;
currentColor: string;
c: number;
r: number;
domains: number[][][];
domainsToJoin: { i: number, domain: number[][] }[];
public matrix: Cell[][];
constructor() { }
public countDomains():number
{
var domainsCount = 0;
this.visitedCells = [];
this.currentColor = colorPalette[0];
for(this.r = 0; this.r < this.matrix.length; this.r++)
{
this.currentRow = this.matrix[this.r];
for(this.c = 0; this.c < this.currentRow.length; this.c++)
{
this.currentCell = this.currentRow[this.c];
if(this.explore((c, r) => {})) {
domainsCount++;
this.currentColor = colorPalette[domainsCount % colorPalette.length];
}
}
}
return domainsCount;
}
public findDomains():number[][][]
{
var domainsCount = 0;
this.domains = [];
this.visitedCells = [];
this.currentColor = colorPalette[0];
for(this.r = 0; this.r < this.matrix.length; this.r++)
{
this.currentRow = this.matrix[this.r];
for(this.c = 0; this.c < this.currentRow.length; this.c++)
{
this.currentCell = this.currentRow[this.c];
if(this.explore((c, r) => {
if(!this.domains[domainsCount])
this.domains[domainsCount] = [];
this.domains[domainsCount].push([r, c]);
})) {
domainsCount++;
this.currentColor = colorPalette[domainsCount % colorPalette.length];
}
}
}
return this.domains;
}
private tryToJoinBy(r: number, c: number) {
let d = this.findDomainByItem([r, c]);
if(d) {
this.currentCell.includeToDomain(this.matrix[r][c].Color);
if(this.domainsToJoin.filter(x => x.i == d.i).length === 0) {
this.domainsToJoin.push(d);
if(this.domainsToJoin.length === 1) {
d.domain.push([this.r, this.c]);
}
}
}
}
private exploreNewDomain(r: number, c: number) {
this.r = r;
this.c = c;
this.currentCell = this.matrix[r][c];
if(this.currentCell){
this.currentColor = this.currentCell.Color;
let domainsCount = this.domains.length;
if(this.exploreFull((c, r) => {
if(!this.domains[domainsCount]){
this.domains[domainsCount] = [];
this.currentColor = colorPalette[(this.domains.length-1) % colorPalette.length];
}
this.domains[domainsCount].push([r, c]);
this.currentCell.includeToDomain(this.currentColor);
})) {
}
}
}
public recalculateDomains(r: number, c: number) {
this.visitedCells = [];
this.r = r;
this.c = c;
this.currentCell = this.matrix[r][c];
if(this.matrix[r][c] && this.matrix[r][c].Value) {
this.domainsToJoin = [];
if(this.matrix[r-1] && this.matrix[r-1][c] && this.matrix[r-1][c].Value) {
this.tryToJoinBy(r-1, c)
}
if(this.matrix[r] && this.matrix[r][c-1] && this.matrix[r][c-1].Value) {
this.tryToJoinBy(r, c-1)
}
if(this.matrix[r+1] && this.matrix[r+1][c] && this.matrix[r+1][c].Value) {
this.tryToJoinBy(r+1, c)
}
if(this.matrix[r] && this.matrix[r][c+1] && this.matrix[r][c+1].Value) {
this.tryToJoinBy(r, c+1)
}
if(this.domainsToJoin.length > 1){
for(var i = 1; i < this.domainsToJoin.length; i++){
this.domainsToJoin[i].domain.forEach(el => {
if(this.domainsToJoin[0].domain.indexOf(el) === -1){
this.domainsToJoin[0].domain.push(el);
}
});
this.domains[this.domainsToJoin[0].i] = this.domainsToJoin[0].domain;
let domainToJoin = this.domains[this.domainsToJoin[0].i];
domainToJoin.forEach(el => {
let firstItemFromDomain = domainToJoin[0];
this.matrix[el[0]][el[1]].includeToDomain(this.matrix[firstItemFromDomain[0]][firstItemFromDomain[1]].Color);
});
if(this.domains.indexOf(this.domainsToJoin[i].domain) !== -1)
this.domains.splice(this.domains.indexOf(this.domainsToJoin[i].domain), 1);
}
}
if(this.domainsToJoin.length === 0) {
if(!this.domains) this.domains = [];
this.domains[this.domains.length] = [[r,c]];
this.matrix[r][c].includeToDomain(colorPalette[(this.domains.length-1) % colorPalette.length]);
}
} else if(this.matrix[r][c] && !this.matrix[r][c].Value) {
this.matrix[r][c] = new Cell();
let domainToSplit = this.findDomainByItem([r,c]);
if(!!domainToSplit) {
let domainIndexToDelete = this.domains.indexOf(this.domains[domainToSplit.i]);
let itemIndexToDelete = this.domains[domainToSplit.i].indexOf(this.domains[domainToSplit.i][domainToSplit.j]);
if(domainToSplit.domain.length > 1){
this.domains.splice(domainIndexToDelete, 1);
var domainsCount = this.domains.length;
if(this.matrix[r-1] && this.matrix[r-1][c] && this.matrix[r-1][c].Value) {
this.exploreNewDomain(r-1, c);
}
if(this.matrix[r] && this.matrix[r][c-1] && this.matrix[r][c-1].Value) {
this.exploreNewDomain(r, c-1);
}
if(this.matrix[r+1] && this.matrix[r+1][c] && this.matrix[r+1][c].Value) {
this.exploreNewDomain(r+1, c);
}
if(this.matrix[r] && this.matrix[r][c+1] && this.matrix[r][c+1].Value) {
this.exploreNewDomain(r, c+1);
}
}
else {
this.domains.splice(domainIndexToDelete, 1);
}
}
}
this.domains = this.domains.filter((item, i) => {
return this.domains.indexOf(item) == i;
});
// reapply colors
for(var i = 0; i < this.domains.length; i++) {
this.domains[i].forEach(el => {
this.matrix[el[0]][el[1]].includeToDomain(colorPalette[i % colorPalette.length]);
});
}
}
public findDomainByItem(itemToFind: number[]): { i: number, j: number, domain: number[][] } {
for(var i = 0; i < this.domains.length; i++) {
for(var j = 0; j < this.domains[i].length; j++) {
if(this.domains[i][j][0] == itemToFind[0]
&& this.domains[i][j][1] == itemToFind[1]) {
return { i, j, domain: this.domains[i] } ;
}
}
}
return null;;
}
public get Domains(): number[][][] {
return this.domains;
}
private explore(includeToDomain: (c: number, r: number) => void): boolean
{
if(this.isVisited(this.c, this.r)) return false;
if(this.currentCell.Value)
{
this.currentCell.includeToDomain(this.currentColor);
includeToDomain(this.c, this.r);
this.exploreBy(this.c, this.r+1, includeToDomain);
this.c += this.exploreBy(this.c+1, this.r, includeToDomain);
}
return !!this.currentCell.Value;
}
private exploreFull(includeToDomain: (c: number, r: number) => void): boolean
{
if(this.isVisited(this.c, this.r)) return false;
if(this.currentCell.Value)
{
this.currentCell.includeToDomain(this.currentColor);
includeToDomain(this.c, this.r);
this.exploreBy(this.c-1, this.r, includeToDomain);
this.exploreBy(this.c, this.r-1, includeToDomain);
this.exploreBy(this.c, this.r+1, includeToDomain);
this.c += this.exploreBy(this.c+1, this.r, includeToDomain);
}
return !!this.currentCell.Value;
}
private exploreBy(c1:number, r1:number, includeToDomain: (c: number, r: number) => void):number
{
if(c1>=0 && r1>=0
&& r1<this.matrix.length
&& c1<this.matrix[r1].length
&& !this.isVisited(c1, r1)
&& this.matrix[r1][c1].Value)
{
this.matrix[r1][c1].includeToDomain(this.currentColor);
includeToDomain(c1, r1);
this.exploreBy(c1 - 1, r1, includeToDomain);
this.exploreBy(c1, r1 - 1, includeToDomain);
this.exploreBy(c1, r1 + 1, includeToDomain);
return this.exploreBy(c1 + 1, r1, includeToDomain) + 1;
}
return 0;
}
private isVisited(c:number, r:number):boolean
{
let visitedRow = this.visitedCells[r];
if(!visitedRow) this.visitedCells[r] = visitedRow = [];
let result = !!visitedRow[c];
visitedRow[c] = true;
return result;
}
}
|
4edbe1a25df371b2b9ddbeb97452d2b300a9a5b9
|
TypeScript
|
marynashapoval/project-catalog
|
/my-project/frontend/src/app/helpers/queryStatusCheck.ts
| 2.53125
| 3
|
export class QueryStatusCheck {
static showData(parsedData: any) {
const checkStatus = (res: any) => {
if (res.status >= 200 && res.status < 300) {
return res;
}
return parsedData(res).then((res: any) => {
throw res;
});
};
}
static parseJSON(parseJSON: any) {
parseJSON = (res: any) => (res.json ? res.json() : res);
}
}
|
7e04bfe1983096543dd84f116dfd9ea3f460ee43
|
TypeScript
|
taksenov/ui-nucleons
|
/src/helpers/__test__/scroll-to-child.test.ts
| 2.578125
| 3
|
import { scrollToChild } from '../scroll-to-child';
const makeRectangleMock = jest.fn((left, top, width, height) => ({
left,
top,
right: left + width,
bottom: top + height,
}));
const getBoundingClientRect = makeRectangleMock;
describe('scrollToChild', () => {
let child;
let parent;
it('test scrollToChild if childRect.bottom >/< parentRect.bottom', () => {
child = document.createElement('div');
parent = document.createElement('div');
parent.getBoundingClientRect = jest.fn(() => getBoundingClientRect(20, 20, 20, 20)) as unknown as () => DOMRect;
child.getBoundingClientRect = jest.fn(() => getBoundingClientRect(10, 10, 10, 10)) as unknown as () => DOMRect;
scrollToChild(parent, child);
parent.getBoundingClientRect = jest.fn(() => getBoundingClientRect(20, 20, 20, 20)) as unknown as () => DOMRect;
child.getBoundingClientRect = jest.fn(() => getBoundingClientRect(110, 110, 110, 110)) as unknown as () => DOMRect;
scrollToChild(parent, child);
expect(parent.getBoundingClientRect).toHaveBeenCalled();
expect(child.getBoundingClientRect).toHaveBeenCalled();
});
it('test scrollToChild if isInsideRect', () => {
child = document.createElement('div');
parent = document.createElement('div');
parent.getBoundingClientRect = jest.fn(() => getBoundingClientRect(0, 0, 150, 150)) as unknown as () => DOMRect;
child.getBoundingClientRect = jest.fn(() => getBoundingClientRect(0, 0, 100, 100)) as unknown as () => DOMRect;
scrollToChild(parent, child);
expect(parent.getBoundingClientRect).toHaveBeenCalled();
expect(child.getBoundingClientRect).toHaveBeenCalled();
});
});
|
5f1fcb9f1e96eaaa7ba006239e0da40477a10284
|
TypeScript
|
shazam2064/angular-course2
|
/angular-rpg-master/src/app/models/item.ts
| 2.78125
| 3
|
import {EntityObject} from './base-entity';
import {ItemCategories, ITemplateItem} from './game-data/game-data.model';
/**
* An instance of a template item that has been created.
*/
export interface Item extends ITemplateItem, EntityObject {
/**
* The ID of the entity that this item is equipped by (if any)
*/
readonly equippedBy?: string | undefined;
/**
* The category of the item. Useful for filtering by item type.
*/
readonly category?: ItemCategories;
}
|
43814a360325876048914e13325a4053324d2920
|
TypeScript
|
jasminmif/big-sir
|
/src/hooks/useIsFocused.ts
| 2.671875
| 3
|
import { MutableRefObject, useEffect, useState } from 'react';
function useIsFocused(ref: MutableRefObject<HTMLDivElement | null>) {
const [isFocused, setIsFocused] = useState(false);
useEffect(() => {
const listener = (event: any) => {
if (!ref.current || ref.current.contains(event.target)) {
event.preventDefault();
setIsFocused(true);
} else {
setIsFocused(false);
}
};
window.addEventListener('mousedown', listener);
window.addEventListener('touchstart', listener);
return () => {
window.removeEventListener('mousedown', listener);
window.removeEventListener('touchstart', listener);
};
}, [ref]);
return { isFocused, setIsFocused };
}
export default useIsFocused;
|
75450dfb2fa15812adcde14af4475fab49f67f36
|
TypeScript
|
ecelustka/cactus-homework
|
/backend/nodejs/src/helpers/modify-cactus.ts
| 2.671875
| 3
|
import type { MongoClient } from 'mongodb'
import type { Request, Response } from 'express'
import type { CactusItem, DbResponse } from '../types'
import { bodyOk } from './body-ok'
import dbConnection from './mongo-connect'
// Update item in db
const updateData = async (data: CactusItem): Promise<DbResponse> => {
const client: MongoClient = dbConnection()
try {
await client.connect()
delete data['_id']
const { ops } = await client
.db('db')
.collection('cactuses')
.replaceOne({ id: data.id }, data)
return { err: false, data: ops[0] }
} catch (err) {
console.log(err)
return {
err: true,
message: "We are sorry, there's problem on the server.",
}
} finally {
await client.close()
}
}
// PUT /cactus
export const modifyCactus = async (
req: Request,
res: Response
): Promise<void> => {
if (!req.body) {
res.status(204).json({
error: true,
message: 'The request is empty.',
})
return
}
const bodyError = bodyOk(req.body)
if (bodyError) {
res.status(400).json(bodyError)
return
}
const response: DbResponse = await updateData(req.body)
if (response.err) {
res.status(500).json(response)
return
}
res.status(200).json(response.data)
}
|
9706a6e092454c2a8579dcde89763df63c77ad34
|
TypeScript
|
kbespalyi/CarInventory
|
/app/cars/car-detail-edit/my-image-add-remove/my-image-add-remove.component.ts
| 2.578125
| 3
|
import { Component, EventEmitter, Input, Output } from "@angular/core";
import * as imagePicker from "nativescript-imagepicker";
/* ***********************************************************
* The MyImageAddRemove custom component uses an imagepicker plugin to let the user select
* an image and provides custom logic and design to the process.
*************************************************************/
@Component({
selector: "MyImageAddRemove",
moduleId: module.id,
templateUrl: "./my-image-add-remove.component.html",
styleUrls: ["./my-image-add-remove.component.css"]
})
export class MyImageAddRemoveComponent {
@Input() imageUrl: string = "";
@Output() imageUrlChange = new EventEmitter<string>();
onImageAddRemoveTap(): void {
if (this.imageUrl) {
this.handleImageChange(null);
return;
}
const context = imagePicker.create({
mode: "single"
});
context
.authorize()
.then(() => context.present())
.then((selection) => selection.forEach(
(selectedImage) => this.handleImageChange(selectedImage.fileUri))
).catch((errorMessage: any) => console.log(errorMessage));
}
handleImageChange(newValue): void {
const oldValue = this.imageUrl;
if (newValue) {
// iOS simulator fileUri looks like file:///Users/...
newValue = newValue.replace("file://", "");
}
if (oldValue === newValue) {
return;
}
this.imageUrl = newValue;
this.imageUrlChange.emit(this.imageUrl);
}
}
|
82748efae587e380866c246e92c5c4158707f865
|
TypeScript
|
RobinBuschmann/angular-typescript
|
/src/at-angular.ts
| 2.890625
| 3
|
// Support AMD require
// and SystemJS import
declare module 'at' {
export = at;
}
module at {
'use strict';
/* tslint:disable:no-any */
export interface IClassAnnotationDecorator {
(target: any): void;
(t: any, key: string, index: any): void;
}
/* tslint:disable:no-any */
export interface IMemberAnnotationDecorator {
(target: any, key: string): void;
}
/**
* Retrieves injectNames from specified classes,
* to generate an array, which only consists of
* inject names
*
* @param values
* @return {string|Function|any[]}
*/
export function retrieveInjectNames(values: Array<string|Function>) {
return values.map(value => {
if(angular.isString(value)) {
return value;
}
const injectName = Reflect.getMetadata('injectName', value);
if(!injectName) {
throw new Error(`Specified class '${getFunctionName(value)}' has no meta data for injectName`);
}
return injectName;
});
}
/**
* Helper method to get name of function
*
* @param fn
* @return {any}
*/
function getFunctionName(fn) {
if(fn.name) {
return fn.name;
}
return /^function\s+([\w\$]+)\s*\(/.exec( fn.toString() )[ 1 ];
}
/**
* A helper method to generate an annotated function
* in the old angular way. This accepts beside strings
* annotated classes.
*
*
* @param dependencies
* @return {string|Function[]|string|Function|any[]}
*/
export function invokable(...dependencies: Array<string|Function>) {
let fn = dependencies.pop();
return retrieveInjectNames(dependencies).concat(fn);
}
/**
* This generates an identifier for any app component
* (services, providers, factories, controllers).
* To ensure, that each component gets an unique
* identifier, an autoincrement numerical value
* is used. To prevent collision with external
* modules, the identifier consists of the components
* module name, which already has to be unique
* regarding other modules.
*
* @param moduleName
* @return {string}
*/
export const createIdentifier = (function () {
let count = 1; // the counter prevents internal collisions
return moduleName => moduleName + '-' + (count++);
}());
/**
* Processes annotations for services, providers, factories and controllers.
* Stores meta data for injectName for each class and initializes each
* component with specified module.
*
* @param any
* @param name
* @param mode
* @param providedServiceClass
* @param create
* @return {function(any): void}
*/
export function process(any: any, name: string, mode: string, providedServiceClass?: Function, create = true): IClassAnnotationDecorator {
return (target: any): void => {
let module = angular.isObject(any) ? any : angular.module(any);
// if Provider annotation passes provided service class,
// retrieve inject name from service
if (providedServiceClass) {
name = Reflect.getMetadata('injectName', providedServiceClass);
} else {
// generate inject name if necessary
name = name || createIdentifier(module.name);
}
// store inject name via reflect-metadata
Reflect.defineMetadata('injectName', mode === 'provider' ? name + 'Provider' : name, target);
if (create) module[mode](name, target);
};
}
}
|
358f73daa794c4fff023ca79b940bb300a2ed69a
|
TypeScript
|
uhyo/masaospace
|
/src/api/series.ts
| 2.703125
| 3
|
///<reference path="../node.d.ts" />
import express = require('express');
import Controller from '../controllers/index';
import util = require('../util');
import { SeriesQuery } from '../data';
class C {
route(router: express.Router, c: Controller): void {
// シリーズを作成する
// IN name: シリーズ名
// IN description: 説明
// OUT id: シリーズID
router.post('/new', util.apim.useUser, (req, res) => {
req.validateBody('name').isSeriesName();
req.validateBody('description').isSeriesDescription();
if (req.validationErrorResponse(res)) {
return;
}
var now = new Date();
c.series.newSeries(
{
id: Number.NaN,
owner: req.session!.user,
name: req.body.name,
description: req.body.description,
games: [],
created: now,
updated: now,
},
(err, newid) => {
if (err) {
res.json({
error: String(err),
});
return;
}
//OK
res.json({
id: newid,
});
},
);
});
// シリーズを編集する
// IN id: シリーズID
// IN name: シリーズ名
// IN description: 説明
// IN games: ゲームIDを","で区切った文字列
router.post('/save', util.apim.useUser, (req, res) => {
req.validateBody('id').isInteger();
req.validateBody('name').isSeriesName();
req.validateBody('description').isSeriesDescription();
req.validateBody('games').isnotEmpty();
if (req.validationErrorResponse(res)) {
return;
}
//該当のシリーズを探す
c.series.findSeries(
{
id: parseInt(req.body.id),
owner: req.session!.user,
},
(err, docs) => {
if (err || docs == null) {
res.json({
error: String(err),
});
return;
}
if (docs.length < 1) {
res.json({
error: 'シリーズが見つかりません。',
});
return;
}
var series = docs[0];
//ゲームを探す
var gameids = req.body.games.split(',').map((id: string) => {
return Number(id);
});
c.game.findGames(
{
owner: req.session!.user,
ids: gameids,
},
(err, metadatas) => {
if (err || metadatas == null) {
res.json({
error: String(err),
});
return;
}
if (metadatas.length < gameids.length) {
//足りない
res.json({
error: 'ゲーム指定が不正です。',
});
return;
}
//OK シリーズを書き換える
c.series.updateSeries(
{
id: series.id,
owner: series.owner,
name: req.body.name,
description: req.body.description,
games: gameids,
created: series.created,
updated: new Date(),
},
err => {
if (err) {
res.json({
error: String(err),
});
} else {
res.json({
success: true,
});
}
},
);
},
);
},
);
});
// シリーズを検索する
// IN owner: オーナーのユーザーID
// OUT series: シリーズたち
router.post('/find', (req, res) => {
var qu: SeriesQuery = {
owner: req.body.owner,
};
c.series.findSeries(qu, (err, docs) => {
if (err) {
res.json({
error: String(err),
});
return;
}
res.json({
series: docs,
});
});
});
// シリーズに属するゲームの一覧
// IN series: シリーズID
// OUT games: ゲームたち
router.post('/games', (req, res) => {
var qu: SeriesQuery = {
id: Number(req.body.series),
limit: 1,
};
c.series.findSeries(qu, (err, docs) => {
if (err || docs == null) {
res.json({
error: String(err),
});
return;
}
if (docs.length < 1) {
res.json({
error: 'シリーズが見つかりませんでした。',
});
return;
}
var se = docs[0];
c.game.findGames(
{
ids: se.games,
},
(err, docs) => {
if (err) {
res.json({
error: String(err),
});
return;
}
res.json({
games: docs,
});
},
);
});
});
}
}
export = C;
|