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
|
|---|---|---|---|---|---|---|
930997c02a20093484160af46a09b8dd5fffe09b
|
TypeScript
|
bc-krishsenthilraj/checkout-sdk-js
|
/src/coupon/map-to-internal-coupon.ts
| 2.625
| 3
|
import Coupon from './coupon';
import InternalCoupon from './internal-coupon';
const couponTypes = [
'per_item_discount',
'percentage_discount',
'per_total_discount',
'shipping_discount',
'free_shipping',
];
export default function mapToInternalCoupon(coupon: Coupon): InternalCoupon {
return {
code: coupon.code,
discount: coupon.displayName,
discountType: couponTypes.indexOf(coupon.couponType),
};
}
|
e9aea511d58bc36a141a5f1d22949c08aa83af89
|
TypeScript
|
fabiolarobles1/los-reyes-de-la-punta-backend
|
/src/entities/students.entity.ts
| 2.6875
| 3
|
import { Exclude } from 'class-transformer/decorators';
import { Entity, Column, PrimaryGeneratedColumn, BeforeInsert } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { classToPlain } from 'class-transformer';
import { StudentResponseInterface } from '../students/interfaces/student.response.interface';
@Entity('students')
export class StudentsEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
stu_id: string;
@Column()
stu_fname: string;
@Column()
stu_lname: string;
@Column()
stu_email: string;
@Column()
@Exclude()
stu_password: string;
@Column()
stu_degree: number;
@Column()
stu_year: string;
@BeforeInsert()
async hashPassword() {
this.stu_password = await bcrypt.hash(this.stu_password, 10);
}
async comparePassword(input: string) {
return await bcrypt.compare(input, this.stu_password);
}
toJSON(): StudentResponseInterface {
return <StudentResponseInterface>classToPlain(this);
}
}
|
091597c8790bab76f2c4e6b55e16b77d0043755f
|
TypeScript
|
codeVirtuoso21/MySolutions-codesignal
|
/!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!/V/variable-name/index.ts
| 2.640625
| 3
|
export function variableName(name: string): boolean {
return /^[a-z_][a-z_0-9]*$/i.test(name);
}
|
afe11e98ac0ef00f63ffb3330506e639e6c1401b
|
TypeScript
|
tomtiao/TodoList-frontend
|
/src/util/TodoRequest.ts
| 2.78125
| 3
|
import { Todo, TodoPartial } from '../Todo/Todo'
import { InvalidRequestError, NetworkError, NotFoundError } from '../util/AppMessage'
const TODO_API = '/todo'
async function getTodos (mode: 'all' | 'keyword' = 'all', kw?: string): Promise<Todo[]> {
let requestURL = `${TODO_API}`
if (mode === 'all') {
requestURL = `${TODO_API}`
} else if (mode === 'keyword') {
requestURL = `${TODO_API}?kw=${kw}`
}
const res = await fetch(requestURL)
if (res.ok) {
const objects = await res.json()
return objects
} else {
throw new NetworkError(res.statusText)
}
}
async function sendDeleteRequest (id: number): Promise<number> {
const res = await fetch(`${TODO_API}/${id}`, { method: 'DELETE' })
if (res.ok) {
const replied = await res.json()
return replied
} else {
if (res.status === 400) {
throw new InvalidRequestError(res.statusText)
} else if (res.status === 404) {
throw new NotFoundError(res.statusText)
} else {
throw new NetworkError(res.statusText)
}
}
}
async function sendAddRequest (todo: TodoPartial): Promise<string> {
const res = await fetch(`${TODO_API}`, { method: 'POST', body: JSON.stringify(todo), headers: { 'content-type': 'application/json' } })
if (res.ok) {
return res.headers.get('Location') as string
} else {
if (res.status === 400) {
throw new InvalidRequestError(res.statusText)
} else {
throw new NetworkError(res.statusText)
}
}
}
async function getTodoById (id: number): Promise<Todo> {
const res = await fetch(`${TODO_API}/${id}`)
if (res.ok) {
const todo = await res.json()
return todo
} else {
if (res.status === 400) {
throw new InvalidRequestError(res.statusText)
} else if (res.status === 404) {
throw new NotFoundError(res.statusText)
} else {
throw new NetworkError(res.statusText)
}
}
}
async function sendModifyRequest (id: number, todo: TodoPartial): Promise<string> {
const res = await fetch(`${TODO_API}/${id}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(todo) })
if (res.ok) {
return res.headers.get('Content-Location') as string
} else {
if (res.status === 400) {
throw new InvalidRequestError(res.statusText)
} else if (res.status === 404) {
throw new NotFoundError(res.statusText)
} else {
throw new NetworkError(res.statusText)
}
}
}
export {
getTodos,
getTodoById,
sendAddRequest,
sendDeleteRequest,
sendModifyRequest
}
|
dde8a0478fa9720e71ad2939f17aeab6f2b07199
|
TypeScript
|
satanTime/ng-mocks
|
/libs/ng-mocks/src/lib/mock-helper/mock-helper.stub-member.ts
| 2.578125
| 3
|
import helperExtractPropertyDescriptor from '../mock-service/helper.extract-property-descriptor';
export default <T extends object>(
instance: T & { __ngMocks__source?: object },
key: any,
value: any,
encapsulation?: 'get' | 'set',
): any => {
const def = helperExtractPropertyDescriptor(instance, key) ?? {};
if (!encapsulation && def.set && (def.set as any).__ngMocksProxy) {
def.set(value);
return value;
}
const descriptor: PropertyDescriptor = {
configurable: true,
enumerable: true,
};
if (encapsulation === 'get' && def.set) {
descriptor.set = def.set;
} else if (encapsulation === 'set' && def.get) {
descriptor.get = def.get;
}
if (encapsulation) {
descriptor[encapsulation] = value;
} else {
descriptor.writable = true;
descriptor.value = value;
}
Object.defineProperty(instance, key, descriptor);
return value;
};
|
af8de1413d6a0def9532949fa6ee037d68385cb1
|
TypeScript
|
mohitbagra/azure-devops-extensions
|
/src/Common/ServiceWrappers/HostPageLayoutService.ts
| 2.515625
| 3
|
import {
CommonServiceIds,
IDialogOptions,
IHostPageLayoutService,
IMessageDialogOptions,
IPanelOptions
} from "azure-devops-extension-api/Common/CommonServices";
import * as SDK from "azure-devops-extension-sdk";
let hostPageLayoutService: IHostPageLayoutService;
export async function getHostPageLayoutService(): Promise<IHostPageLayoutService> {
if (!hostPageLayoutService) {
hostPageLayoutService = await SDK.getService<IHostPageLayoutService>(CommonServiceIds.HostPageLayoutService);
}
return hostPageLayoutService;
}
export async function confirmAction(title: string | undefined, msg: string, callback: (ok: boolean) => void) {
const service = await getHostPageLayoutService();
service.openMessageDialog(msg, { onClose: callback, showCancel: true, title: title });
}
export async function openErrorDialog(message: string, reason?: string | Error) {
const reasonStr = typeof reason === "string" ? reason : reason && reason.message;
const errorMsg = reasonStr ? `${message} Reason: ${reasonStr}` : message;
const service = await getHostPageLayoutService();
service.openMessageDialog(errorMsg);
}
export async function openMessageDialog(message: string, options?: IMessageDialogOptions) {
const service = await getHostPageLayoutService();
service.openMessageDialog(message, options);
}
export async function openCustomDialog<TResult>(contentContributionId: string, options?: IDialogOptions<TResult>) {
const service = await getHostPageLayoutService();
service.openCustomDialog(contentContributionId, options);
}
export async function openPanel<TResult>(contentContributionId: string, options: IPanelOptions<TResult>) {
const service = await getHostPageLayoutService();
service.openPanel(contentContributionId, options);
}
export async function getFullScreenMode(): Promise<boolean> {
const service = await getHostPageLayoutService();
return service.getFullScreenMode();
}
export async function setFullScreenMode(fullScreenMode: boolean) {
const service = await getHostPageLayoutService();
service.setFullScreenMode(fullScreenMode);
}
|
37e69bede8bbc0485856039dcd2ed446f71894b6
|
TypeScript
|
juanfalconcodigo/Graphql-Proyect-2
|
/src/resolvers/mutation.ts
| 2.5625
| 3
|
import {IResolvers} from 'graphql-tools';
import { courses } from '../data/data.store';
const mutation:IResolvers={
Mutation:{
addCourse(__:void,{course}):any{
const id=String(courses.length+1);
const newCourse={
id,
...course,
reviews:[]
}
if(courses.filter(courseFilter=>courseFilter.title===newCourse.title).length >0){
return {
id:'-1',
title:'Curso ya existe',
description:'',
clases:-1,
time:0.0,
level:'ALL',
logo:'',
path:'',
teacher:'',
reviews:[]
}
}
courses.push(newCourse);
return newCourse;
},
updateCourse(__,{id,course}):any{
let index:number;
const update=courses.find(findCourse=>findCourse.id===id);
if(update===undefined){
return{
id:'-1',
title:`No existe un curso con el id : ${id}`,
description:'',
clases:-1,
time:0.0,
level:'ALL',
logo:'',
path:'',
teacher:'',
reviews:[]
}
}
const updateCourse={
id,
...course,
reviews:update.reviews
}
index=courses.indexOf(update);
courses[index]=updateCourse;
return updateCourse;
},
deleteCourse(__:void,{id}):any{
let index:number;
const course=courses.find(findCourse=>findCourse.id===id);
if(course===undefined){
return{
id:'-1',
title:`No existe un curso con el id : ${id}`,
description:'',
clases:-1,
time:0.0,
level:'ALL',
logo:'',
path:'',
teacher:'',
reviews:[]
}
}
index=courses.indexOf(course);
courses.splice(index,1);
return course;
}
}
}
export default mutation;
|
0d3f215ea4ff434e1d7154f391efec97b5b47751
|
TypeScript
|
manken/needle
|
/main/annotations/lazy.ts
| 2.71875
| 3
|
import { v4 as uuid } from 'uuid';
import { Newable } from '../contracts/contracts';
import { getRootInjector } from '../core/util.functions';
/**
* The @Lazy annotation allows you inject a Lazy<T> into a given parameter.
*
* constructor(@Lazy(MyInjectableType) myLazy: LazyInstance<MyInjectableType>){
* const instance = lazy.value;
* }
*/
export function Lazy(lazyTarget: Newable) {
// the original decorator
function lazy(target: any, property: string | symbol | undefined, index: number): void {
getRootInjector().tokenCache.register({
token: `lazy_${uuid()}`, // We can auto generate a token for lazy.
owner: target,
lazyTarget,
property,
index,
injectionType: 'lazy',
});
}
// return the decorator
return lazy;
}
|
a192f420fc714dcdaf4a66b65bf4c5d35f3bc39c
|
TypeScript
|
hugodutka/www-dom2
|
/front/src/utils/relax/jsx.ts
| 3.203125
| 3
|
export const JSX = {
createElement: (tag, attrs = {}, ...children) => {
attrs = attrs || {};
var elem: HTMLElement;
if (typeof tag === "string") {
// if an HTML tag was passed, simply create a matching element
elem = Object.assign(document.createElement(tag), attrs);
} else {
// if something else was passed, it was likely a function that will return an HTML element,
// so try to evaluate it
try {
const htmlAttrs = attrs.hasOwnProperty("html") ? attrs["html"] : {};
elem = Object.assign(tag(attrs), htmlAttrs);
} catch (err) {
console.log(err);
// if it cannot be evaluated, return something so as not to break the application
return document.createElement("div");
}
}
for (const child of children) {
if (Array.isArray(child)) elem.append(...child);
else elem.append(child);
}
return elem;
},
};
|
290e14a85ac8de0ba02b7d7995cbace5baefaced
|
TypeScript
|
dmit-git/angular-brewcraft
|
/client/src/app/dashboard/my-recipe/my-recipe.component.ts
| 2.65625
| 3
|
import { Component, OnInit } from '@angular/core';
import { Recipe, RecipeService } from '../../services';
@Component({
selector: 'app-my-recipe',
templateUrl: './my-recipe.component.html',
styleUrls: ['./my-recipe.component.css']
})
export class MyRecipeComponent implements OnInit {
recipes: Recipe[];
constructor(
private recipeService: RecipeService,
) {
}
ngOnInit() {
this.recipeService.getRecipes()
.then(res => {
this.recipes = res.data;
console.log(this.recipes);
});
}
getTimeDiff(date: Date) {
var today = new Date();
var diffMs = (today.getTime() - new Date(date).getTime()); // milliseconds between now & Christmas
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
if (diffDays != 0)
return diffDays + ' days ago';
if (diffHrs != 0)
return diffHrs + ' hours ago';
if (diffMins != 0)
return diffMins + ' mins ago';
else
return Math.floor(diffMs / 1000) + ' secs ago';
}
}
|
f1eacebe51b636610e6521675caabaf510389efc
|
TypeScript
|
dongchenchen/analysis_middleware
|
/src/index.ts
| 2.84375
| 3
|
/**
* @author dididong
* @description 入口页支持纯获取数据、绘制折线图、绘制饼图、绘制表格、绘制昨日数据
*
* @param DataRequest {busi:业务id,tmpl:模板id, args:查询参数(json字符串)}
*/
import { DataRequest, ShowConfig, AnalysisConfig } from './common/config';
import { Controller } from './controller/controller';
export default class AnalysisMiddleware {
private Controller: Controller;
constructor(config: AnalysisConfig) {
this.Controller = new Controller(config);
}
/**
* 绘制折线图
* @param dataRequest
* {
* busi: 业务id
* tmpl: 模板id
* args: 参数
* }
* @param showConfig
* {
* xAxis: x轴 type: string
* yAxis: y轴列表, type: array | string | Object 当为对象时支持传递处理函数
* [{
* name: '',
* formatFunc: Function
* }]
* ['play_pv', 'play_uv'] 这种形式默认不对数据进行处理
* mapInfo: y轴对应的中文名称 type: object
* autoFillDate: 是否自动补充日期 (当x轴的值为refDate时有效) type: boolean
* dataRange: 日期区间 (当autoFillDate为true时有效)
* {
* beginDate: 开始时间
* endDate: 结束时间
* }
* domId: 绘制折线图的domid type: string
* }
*/
public drawLine(dataRequest: DataRequest, showConfig: ShowConfig): any {
return this.Controller.drawLine(dataRequest, showConfig);
}
public drawLineWithData(data: Array<object>, showConfig: ShowConfig): any {
return this.Controller.drawLineWithData(data, showConfig);
}
/**
*
* @param dataRequest 同上
* @param showConfig
* {
* domId: 绘制饼图的domid type: string
* sceneMapInfo: 每个场景值对应的中文名 type: object
* mainSceneList: 主要场景数组 type: array
* otherSceneList: 其他场景数组 type: array
* key: 分析指标 type: string
* }
*/
public drawPie(dataRequest: DataRequest, showConfig: ShowConfig): any {
return this.Controller.drawPie(dataRequest, showConfig);
}
public drawPieWithData(data: Array<object>, showConfig: ShowConfig): any {
return this.Controller.drawPieWithData(data, showConfig);
}
/**
*
* @param dataRequest 同上
* @param showConfig
* {
* headList: 表头列表 type: array
* ['xxx', 'xxx'] 或
* [{
* 'name': 'xxx',
* 'formatFunc': Function
* }]
* mapInfo: 中英文对照表 type: object
* }
*/
public drawTable(dataRequest: DataRequest, showConfig: ShowConfig): any {
return this.Controller.drawTable(dataRequest, showConfig);
}
/**
*
* @param dataRequest 同上
* @param showConfig
* {
* quatoList: 指标列表 type: array
* }
*/
public drawYesterdayData(dataRequest: DataRequest, showConfig: ShowConfig): any {
return this.Controller.drawYesterdayData(dataRequest, showConfig);
}
/**
*
* @param dataRequest 同上
*/
public getRawData(dataRequest: DataRequest): any {
return this.Controller.getRawData(dataRequest);
}
public drawBarChart(dataRequest: DataRequest, showConfig: ShowConfig): any {
return this.Controller.drawBarChart(dataRequest, showConfig);
}
}
|
355c6c9b9883008d6e582f65e8113921ab8e85e7
|
TypeScript
|
SocialGouv/pass-emploi-api
|
/src/building-blocks/types/result-api.ts
| 2.734375
| 3
|
import { ErreurHttp } from './domain-error'
import { DateTime } from 'luxon'
export type ResultApi<Data = void> = SuccessApi<Data> | FailureApi
export type SuccessApi<Data = void> = {
_isSuccess: true
data: Data
dateCache?: DateTime
}
export type FailureApi = { _isSuccess: false; error: ErreurHttp }
export function successApi<Data = void>(
data: Data,
dateCache?: DateTime
): SuccessApi<Data> {
return { _isSuccess: true, data, dateCache }
}
export function failureApi(error: ErreurHttp): FailureApi {
return { _isSuccess: false, error }
}
export function isSuccessApi<Data = void>(
result: ResultApi<Data>
): result is SuccessApi<Data> {
return result._isSuccess
}
export function isFailureApi<Data = void>(
result: ResultApi<Data>
): result is FailureApi {
return !result._isSuccess
}
|
fa680c5570ef663f28fc90c9f3231bded001cda6
|
TypeScript
|
Tinend/cube_trainer
|
/app/javascript/cube_trainer/app/users/authentication.service.ts
| 2.59375
| 3
|
import { RailsService } from '../rails/rails.service';
import { Injectable } from '@angular/core';
import { HttpVerb } from '../rails/http-verb';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from './user';
import { some, none, ofNull, mapOptional, Optional, hasValue } from '../utils/optional';
const LOCAL_STORAGE_USER_KEY = 'currentUser';
@Injectable({
providedIn: 'root',
})
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<Optional<User>>;
public readonly currentUser$: Observable<Optional<User>>;
constructor(private readonly rails: RailsService) {
const unparsed = ofNull(localStorage.getItem(LOCAL_STORAGE_USER_KEY));
const parsed = mapOptional(unparsed, s => JSON.parse(s));
this.currentUserSubject = new BehaviorSubject<Optional<User>>(parsed);
this.currentUser$ = this.currentUserSubject.asObservable();
}
public get currentUser(): Optional<User> {
return this.currentUserSubject.value;
}
public get loggedIn() {
return hasValue(this.currentUser);
}
login(usernameOrEmail: string, password: string) {
return this.rails.ajax<User>(HttpVerb.Post, '/login', {usernameOrEmail, password})
.pipe(map(user => {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem(LOCAL_STORAGE_USER_KEY, JSON.stringify(user));
this.currentUserSubject.next(some(user));
return user;
}));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem(LOCAL_STORAGE_USER_KEY);
this.currentUserSubject.next(none);
return this.rails.ajax<void>(HttpVerb.Post, '/logout', {});
}
}
|
99a61e7364ac7a00098621d1cf22cf0aa21583cf
|
TypeScript
|
QuocAnhVu/CrosschainFastTransfers
|
/test/index.ts
| 2.625
| 3
|
import { Provider } from "@ethersproject/abstract-provider";
import { Signer } from "@ethersproject/abstract-signer";
import { expect } from "chai";
import { ethers } from "hardhat";
import { ethers as eth } from "ethers";
import Web3 from "web3";
import { Bond, BondClaim, ERC20Mintable } from "../typechain";
import chalk from "chalk";
describe("Generic Bond", function () {
let bonds: Bond;
let claims: BondClaim;
let tokens: ERC20Mintable;
let alice;
let bob;
let charlie;
beforeEach(async function () {
// Deploy contracts.
const Bond = await ethers.getContractFactory("Bond");
const BondClaim = await ethers.getContractFactory("BondClaim");
const Token = await ethers.getContractFactory("ERC20Mintable");
claims = await BondClaim.deploy();
bonds = await Bond.deploy(claims.address);
tokens = await Token.deploy();
[alice, bob, charlie] = await ethers.getSigners();
await claims.deployed();
await bonds.deployed();
await tokens.deployed();
// Log addresses and setup listeners to log events.
let names = {};
names[alice.address] = chalk.red("Alice");
names[bob.address] = chalk.blue("Bob");
names[charlie.address] = chalk.green("Charlie");
names[bonds.address] = chalk.magenta("BondContract");
console.log(names[alice.address] + "@" + alice.address);
console.log(names[bob.address] + "@" + bob.address);
console.log(names[charlie.address] + "@" + charlie.address);
console.log(names[bonds.address] + "@" + bonds.address);
tokens.on("Transfer", (_from, _to, _value) => {
console.log(
chalk.bold("Transfer(") +
names[_from] +
"@" +
_from.substring(0, 8) +
"..." +
", " +
names[_to] +
"@" +
_to.substring(0, 8) +
"..." +
", " +
_value +
chalk.bold(")")
);
});
bonds.on("Issued", (_value, _token, _orderHash) => {
console.log(
chalk.bold("Issued(") +
"value: " +
_value +
", " +
"token: @" +
_token +
", " +
"@" +
_orderHash +
chalk.bold(")")
);
});
claims.on("Claimed", (_orderHash) => {
console.log(chalk.bold("Claimed(@") + _orderHash + chalk.bold(")"));
});
bonds.on("Settled", (_orderHash) => {
console.log(chalk.bold("Settled(@") + _orderHash + chalk.bold(")"));
});
});
it("Should complete full transaction successfully", async function () {
// 1) Mint tokens to Alice and Bob.
await tokens.mint(alice.address, 1000);
await tokens.mint(bob.address, 99);
// 2) Alice creates a bond. Alice wants to send $99 to Charlie. Alice will pay $100.
const principal: Principal = { value: 100, token: tokens.address };
const order: Order = {
to: charlie.address,
value: 99,
token: tokens.address, // ERC-20 token
nonce: eth.utils.randomBytes(32), // This is a random hash supplied by the borrower
};
await tokens.connect(alice).approve(bonds.address, 100);
await bonds.connect(alice).issue(principal, order);
let issuedEvent = new Promise<eth.BytesLike>((resolve) => {
bonds.on("Issued", (_value, _token, _orderHash) => {
resolve(_orderHash);
});
});
const orderHash = await issuedEvent;
// 3) Bob creates a bond claim. Bob sends $99 to Charlie.
await tokens.connect(bob).approve(claims.address, 99);
await claims.connect(bob).claim(order);
expect(await claims.ownerOf(orderHash)).to.equal(bob.address);
// 4) Later, Bob settles the bond. Bob receives $100 from the bond.
await bonds.connect(bob).settle(orderHash);
expect(await bonds.isSettled(orderHash));
await new Promise<void>((resolve) => {
tokens.on("Transfer", (_from, _to, _value) => {
if (_to == bob.address) {
resolve();
}
});
});
// 5) Ensure that everybody gets what they expect.
expect(await tokens.balanceOf(alice.address)).to.equal(900);
expect(await tokens.balanceOf(bob.address)).to.equal(100);
expect(await tokens.balanceOf(charlie.address)).to.equal(99);
});
});
interface Principal {
value: number;
token: string;
}
interface Order {
to: string;
value: number;
token: string; // ERC-20 token
nonce: eth.Bytes; // This is a random hash supplied by the borrower
}
|
ae199f636132e690aae742b5d399e28e42149e31
|
TypeScript
|
Wend1go/superpowers-common-plugins
|
/three/helpers/SelectionBoxRenderer.ts
| 2.59375
| 3
|
export default class SelectionBoxRenderer {
private mesh: THREE.Mesh;
private target: THREE.Object3D;
constructor(root: THREE.Object3D) {
this.mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial({ color: 0x00ffff, side: THREE.BackSide }));
root.add(this.mesh);
}
setTarget(target: THREE.Object3D) {
this.target = target;
this.mesh.visible = true;
this.move();
this.resize();
return this;
}
move() {
this.mesh.position.copy(this.target.getWorldPosition());
this.mesh.quaternion.copy(this.target.getWorldQuaternion());
this.mesh.updateMatrixWorld(false);
return this;
}
resize() {
const vec = new THREE.Vector3();
const box = new THREE.Box3();
const inverseTargetMatrixWorld = new THREE.Matrix4().compose(this.target.getWorldPosition(), this.target.getWorldQuaternion(), { x: 1, y: 1, z: 1 } as THREE.Vector3);
inverseTargetMatrixWorld.getInverse(inverseTargetMatrixWorld);
this.target.traverse((node: THREE.Mesh) => {
const geometry = node.geometry;
if (geometry != null) {
node.updateMatrixWorld(false);
if (geometry instanceof THREE.Geometry) {
const vertices = geometry.vertices;
for (let i = 0, il = vertices.length; i < il; i++) {
vec.copy(vertices[i]).applyMatrix4(node.matrixWorld).applyMatrix4(inverseTargetMatrixWorld);
box.expandByPoint(vec);
}
} else if (geometry instanceof THREE.BufferGeometry && (geometry.attributes as any)["position"] != null) {
const positions: Float32Array = (geometry.attributes as any)["position"].array;
for (let i = 0, il = positions.length; i < il; i += 3) {
vec.set(positions[i], positions[i + 1], positions[i + 2]);
vec.applyMatrix4(node.matrixWorld).applyMatrix4(inverseTargetMatrixWorld);
box.expandByPoint(vec);
}
}
}
});
const size = box.size();
const thickness = 0.1;
this.mesh.scale.copy(size).add(new THREE.Vector3(thickness, thickness, thickness));
this.mesh.updateMatrixWorld(false);
return this;
}
hide() {
this.mesh.visible = false;
return this;
}
}
|
4285cb33abc16d4c152163762928f096071c6875
|
TypeScript
|
leobar37/gsap_exercices
|
/gsap_01/src/ts/functions.ts
| 2.5625
| 3
|
export const addSectionCallback = (
timline: TimelineMax,
params: {
start: number;
end: number;
onEnter: () => void;
onLeave: () => void;
onEnterBack: () => void;
onLeaveBack: () => void;
}
) => {
const trackDirection = (animation: TimelineLite) => {
let onUpdate = animation.eventCallback('onUpdate'); // if exist callback onUpadate
let prevTime = animation.time();
let direction = animation.reversed() ? -1 : 1;
animation.eventCallback('onUpdate', () => {
const time = animation.time();
if (time !== direction) {
direction = time < prevTime ? -1 : 1;
prevTime = time;
}
onUpdate && onUpdate.call(animation);
});
};
trackDirection(timline);
// timline.d
// timline.d
};
|
9fe76322c24b779be3149b033b9b339210d55722
|
TypeScript
|
JoakimLevorsen/statistik-index
|
/src/data/dec2018.ts
| 3.078125
| 3
|
export default [`
Which of the following is a standard 99% confidence interval for the theoretical standard deviation σ?
1* [0.20, 0.73]
2 0.57 ± 1.96 · 0.32
3 [0.22, 0.58]
4 [0.05, 0.34]
5 [0.03, 0.53]
----------------------------------- FACIT-BEGIN -----------------------------------
See Method 3.19. Here, n = 10 and α = 0.01, so the left and right endpoints are, respectively,
sqrt( (10-1)*0.32^2/qchisq(0.995, df = 9) )
## [1] 0.1976575
sqrt( (10-1)*0.32^2/qchisq(0.005, df = 9) )
## [1] 0.7288361
which result in the interval [0.20, 0.73] when rounded to two decimals.
------------------------------------ FACIT-END ------------------------------------
Exercise II
2
We would like to determine the median of X1/X2, when X1 and X2 are independent stochastic
variables, which are both normal distributed with mean 1 and variance 1. The distribution
of the ratio is not trivial; therefore we resort to simulation to determine an estimate and a
confidence interval for the median of the distribution of X1/X2.
`,`
First, 10000 medians are simulated, each being the median of 10000 ratios. We store these in
R in the vector medians:
ratio <- replicate(10000, rnorm(10000, mean = 1)/rnorm(10000, mean = 1))
medians <- apply(ratio, 2, median)
Subsequently, the sample mean and a series of percentiles are calculated for these 10000 medians:
mean(medians)
## [1] 0.6193
quantile(medians, c(0.005, 0.025, 0.05, 0.5, 0.95, 0.975, 0.995), type = 2)
## 0.5% 2.5% 5% 50% 95% 97.5% 99.5%
## 0.5873 0.5949 0.5989 0.6193 0.6402 0.6443 0.6515
Which of the following choices yields an estimate for the median of X1/X2 and a 95% confidence
interval for this median?
1 Estimate: 1.
95% confidence interval: [1 − 1.96 · 0.6193, 1 + 1.96 · 0.6193].
2* Estimate: 0.6193.
95% confidence interval: [0.5949, 0.6443].
3 Estimate: 1.
95% confidence interval: [1 − 0.5949, 1 + 0.6443].
4 Estimate: 0.6193.
95% confidence interval: [0.5873, 0.6515].
5 Estimate: 0.6193.
95% confidence interval: [0.6193 − 0.5949, 0.6193 + 0.5949].
----------------------------------- FACIT-BEGIN -----------------------------------
3
The estimate is the average of the simulated medians, i.e. the estimated median is 0.6193. The
left and right endpoints of the 95% confidence interval are, respectively, the 2.5% and 97.5%
quantiles of the simulated medians, so the confidence interval becomes [0.5949, 0.6443].
------------------------------------ FACIT-END ------------------------------------
Exercise III
A normal distributed population has mean µ = 100 and standard deviation σ = 15.
`,`
In a random draw, what is the probability of obtaining an observation below 90?
1* 0.252
2 0.482
3 0.518
4 0.631
5 0.748
----------------------------------- FACIT-BEGIN -----------------------------------
Let X ∼ N(100, 152
). Then, we may find P(X < 90) = P(X ≤ 90) as:
pnorm(90, mean = 100, sd = 15)
## [1] 0.2524925
------------------------------------ FACIT-END ------------------------------------
`,`
If a random sample of n = 10 independent observations is drawn from the population, what is
the probability that the sample mean is below 90?
1 0.000783
2* 0.0175
4
3 0.146
4 0.252
5 0.482
----------------------------------- FACIT-BEGIN -----------------------------------
Let X¯ denote the sample mean, i.e. the average of 10 independent random variables X1, . . . , X10,
each with the same distribution as X. Use the mean and variance identities for linear combinations of independent random variables (Theorem 2.54) to compute the mean
E
X¯
= E
1
10
X
10
i=1
Xi
!
=
1
10
X
10
i=1
E(Xi) = 1
10
· 10 · µ = µ = 100
and the variance
V
X¯
= V
1
10
X
10
i=1
Xi
!
=
1
102
X
10
i=1
V(Xi) = 1
102
· 10 · σ
2 =
1
10
152 = 22.5 .
Now, P(X <¯ 90) = P(X¯ ≤ 90) may be found as
pnorm(90, mean = 100, sd = sqrt(22.5))
## [1] 0.01750749
------------------------------------ FACIT-END ------------------------------------
`,`
Suppose that a random sample of n independent observations is repeatedly drawn from the
population, and that the sample variance S
2
is calculated in each repetition. What holds true
for S
2
?
1 n
2S
2
is F-distributed with n − 1 and n − 2 degrees of freedom.
2 S
2
is χ
2
-distributed with n − 1 degrees of freedom.
3* (n − 1)S
2/σ2
is χ
2
-distributed with n − 1 degrees of freedom.
4 S
2
is normal distributed with mean µ and variance σ
2/n2
.
5 S
2 has the same distribution as (Z − σ
2
)/n, where Z is standard normal distributed.
----------------------------------- FACIT-BEGIN -----------------------------------
See Section 3.1.6 from beginning and after one page you find the result, that the sampling
distribution of the sample variance transformed by multiplying with (n − 1) and dividing with
σ
2
is χ
2
-distributed with n − 1 degrees of freedom. It is stated in Equation 3-17.
------------------------------------ FACIT-END ------------------------------------
Exercise IV
10 people have had their daily energy intake measured (in kJ). The measurements in the sample
are shown in the table below:
Energy intake (kJ): 8230 5470 7515 5260 6390 6180 6515 6805 7515 5640
`,`
What is the median of the sample?
1 6390
2 6515
3 (8230+5260)/2
4 (6390+6180)/2
5* (6390+6515)/2
----------------------------------- FACIT-BEGIN -----------------------------------
You can rather easily copy from the pdf into an R script and add some commas between the
values, and then:
# Read data into R and sort:
x <- sort(c(8230, 5470, 7515, 5260, 6390, 6180, 6515, 6805, 7515, 5640))
x
## [1] 5260 5470 5640 6180 6390 6515 6805 7515 7515 8230
As there are 10 observations, the median is computed as the mean of observations number 5
and 6 after sorting:
(6390 + 6515)
2
= 6452.5
6
The result may be verified using R:
median(x)
## [1] 6452.5
or:
quantile(x, prob=0.5, type=2)
## 50%
## 6452.5
------------------------------------ FACIT-END ------------------------------------
`,`
The sample mean is ¯x = 6552, while the sample standard deviation is s = 975.94. It is
assumed that the daily energy intake may be modelled by a normal distribution, and that the
observations are independent and identically distributed. What is the p-value for the t-test
that tests the hypothesis that the mean daily energy intake is 7725 kJ?
1 0.4
2 0.06
3 0.04
4 0.006
5* 0.004
----------------------------------- FACIT-BEGIN -----------------------------------
See Method 3.23. With ¯x = 6552, s = 975.94 and n = 10, the observed t-test statistic is
calculated as
tobs =
6552 − 7725
975.94/
√
10
= −3.8007989
and the p-value is thus found as
2P(T ≤ tobs) = 2 · 0.0021061 = 0.004 .
P(T ≤ tobs) is found in R as:
7
pt(-3.8007989, 10-1)
## [1] 0.002106097
The in-built function could also be used:
t.test(x, mu=7725)
##
## One Sample t-test
##
## data: x
## t = -3.8008, df = 9, p-value = 0.004212
## alternative hypothesis: true mean is not equal to 7725
## 95 percent confidence interval:
## 5853.853 7250.147
## sample estimates:
## mean of x
## 6552
------------------------------------ FACIT-END ------------------------------------
Exercise V
A married couple visits the same restaurant several times a month. Typically, they order a
glass of red wine with their food. One day, they decide to complain to the owner. They believe
that one of the waiters pours less wine into the glass than what they pay for. Consequently,
the owner launches an experiment with three of the restaurant’s waiters in order to investigate
how much they pour into wine glasses, when they pour using a rule of thumb. Each of the
three waiters (here anonymized by A, B, and C) were asked to pour red wine into 20 wine
glasses, after which the content in each glass was measured. The data were read into R in two
variables: waiter, indicating which waiter poured the wine, and wine, indicating the amount
of wine in the glass (in mL).
The following code was run in R to analyze the data:
anova(lm(wine ~ waiter))
## Analysis of Variance Table
##
## Response: wine
## Df Sum Sq Mean Sq F value Pr(>F)
## waiter 2 1043.4 521.71 6.9594 0.001976 **
8
## Residuals 57 4273.0 74.97
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
`,`
What may be concluded from the R output above, when a significance level of 5% is used (both
the reasoning and conclusion must be correct)?
1 As the observed F-test statistic is larger than the 0.95 quantile of the F(57, 2)-distribution,
there is a significant difference in the expected amount of wine in glasses poured by the
three different waiters.
2 As the p-value is larger than 5%, there is no significant difference in the expected amount
of wine in glasses poured by the three different waiters.
3 As the sum of squared errors, SSE, is more than four times the size of the treatment sum
of squares, SS(Tr), there is too much noise in the data for it to be meaningful to perform
a one-way analysis of variance.
4* As the observed F-test statistic is larger than the 0.95 quantile of the F(2, 57)-distribution,
there is a significant difference in the expected amount of wine in glasses poured by the
three different waiters.
5 As the p-value is less than 5%, there is no significant difference in the expected amount
of wine in glasses poured by the three different waiters.
----------------------------------- FACIT-BEGIN -----------------------------------
See Theorem 8.6. From the R-output, it is seen that the relevant F-test statistic is Fobs =
6.9594. The 0.95 quantile of the F(2, 57) distribution may be found using R:
qf(0.95, df1 = 2, df2 = 57)
## [1] 3.158843
------------------------------------ FACIT-END ------------------------------------
`,`
Among other things, the owner would like to make a comparison between waiter A (the young
waiter, whom the couple complained about) and waiter B (an older waiter with many years of
experience in the business). On average, waiter A poured 127 mL of wine into each glass, while
9
waiter B poured 135 mL. Compute the t-test statistic for the post hoc pairwise hypothesis test
which compares the expected amount of wine in glasses poured by waiter A and waiter B.
1 tobs = −0.92
2 tobs = −4.13
3* tobs = −2.92
4 tobs = −1.07
5 tobs = −0.11
----------------------------------- FACIT-BEGIN -----------------------------------
See Method 8.10. The relevant post hoc t-test statistic is computed as follows:
tobs =
(127 − 135)
q
74.97
1
20 +
1
20 = −2.92
So its like the two-sample t.test, except that the estimate of the error variance is taken from
the model fitted to all the data ˆσ
2 = MSE =
SSE
n−k
, i.e. the pooled variance estimate.
------------------------------------ FACIT-END ------------------------------------
`,`
In addition to the information in the previous question, it is given that, on average, waiter
C poured 136 mL into each glass. Compute the Bonferroni corrected LSD (“least significant
difference”) value used to perform all possible pairwise comparisons between the three waiters,
and determine where there are significant differences (both the LSD value and the conclusion
must be correct). Use the significance level α = 5%.
1 LSD0.05/3 = 7 mL, so there is a significant difference between the expected amount of
wine in glasses poured by waiters B and C, but no significant difference between waiters
A and B or between waiters A and C.
2* LSD0.05/3 = 7 mL, so there is a significant difference between the expected amount of
wine in glasses poured by waiters A and B as well as between waiters A and C, but no
significant difference between waiters B and C.
3 LSD0.05/3 = 4 mL, so there is a significant difference between the expected amount of wine
in glasses poured by waiters A and B and between waiters A and C, but no significant
difference between waiters B and C.
1
4 LSD0.05/3 = 17 mL, so there is a significant difference between the expected amount
of wine in glasses poured by waiters A and B and between waiters A and C, but no
significant difference between waiters B and C.
5 LSD0.05/3 = 4 mL, so there is a significant difference between the expected amount of
wine in glasses poured by waiters B and C, but no significant difference between waiters
A and B or between waiters A and C.
----------------------------------- FACIT-BEGIN -----------------------------------
See Remark 8.13.
LSD0.05/3 = t1−(0.05/3)/2
p
2 · MSE/20 = 2.466687 ·
p
2 · 74.97/20 = 6.8 ,
where t1−(0.05/3)/2 = t5.95/6 is the 5.95/6 = 0.9916667 quantile of the t-distribution with 60−3 =
57 degrees of freedom, found in R as follows:
qt(5.95/6, df = 60-3)
## [1] 2.466687
So we can use that to determine which of the three waiters will be tested significantly different
in two-sample post hoc comparisons. We have information about the average for each waiter:
x¯A = 127 mL
x¯B = 135 mL
x¯C = 136 mL
from which we can see that A is significantly different from B and C, since their differences are
higher than 7 mL, and that there is no significant difference between B and C.
------------------------------------ FACIT-END ------------------------------------
Exercise VI
A spring is characterized by its spring constant, k. When a spring is stretched, Hooke’s law
states that
F = −k · x ,
where x is the length (in meters) by which the spring is extended, and F is the applied force
(in Newtons). The following six observations were made for a given spring:
1 2 3 4 5 6
x 0.22 0.24 0.26 0.28 0.30 0.32
F -0.51 -0.85 -0.89 -1.59 -1.97 -2.06
11
The observations were read into two vectors in R, x (length) and F (force), respectively, after
which the following model was estimated:
model1 <- lm(F ~ x)
The output from summary(model1) is shown below, where some numbers are replaced by
letters:
##
## Call:
## lm(formula = F ~ x)
##
## Residuals:
## 1 2 3 4 5 6
## -0.04484 -0.04146 0.25365 -0.10667 -0.15758 0.09690
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.2433 0.5483 A C **
## x -16.8663 2.0148 B D **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.1686 on 4 degrees of freedom
## Multiple R-squared: 0.946,Adjusted R-squared: 0.9325
## F-statistic: 70.08 on 1 and 4 DF, p-value: 0.001114
`,`
How may the statistical model corresponding to model1 be described?
1 Yi = β0 + β1xi + εi
, where Yi represents the length by which the spring is extended
when the force xi
is applied, and ε1, . . . , ε6 are assumed to be independent and identically
N(0, σ2
)-distributed.
2 Yi = β1xi + εi
, where Yi represents the force used to extend the spring by the length xi
,
and ε1, . . . , ε6 are assumed to be independent and identically N(0, 1)-distributed.
3 Yi = β1xi + εi
, where Yi represents the length by which the spring is extended when
the force xi
is applied, and ε1, . . . , ε6 are assumed to be independent and identically
N(0, 1)-distributed.
4 Yi = β0 + β1xi + εi
, where Yi represents the length by which the spring is extended
when the force xi
is applied, and ε1, . . . , ε6 are assumed to be independent and identically
N(0, 1)-distributed.
12
5* Yi = β0 + β1xi + εi
, where Yi represents the force used to extend the spring by the length
xi
, and ε1, . . . , ε6 are assumed to be independent and identically N(0, σ2
)-distributed.
----------------------------------- FACIT-BEGIN -----------------------------------
See Chapter 5. The R-code lm(F ~ x) fits a simple linear regression model, in which F (The
force) is the dependent variable and x (distance) is the explanatory variable. The model is
defined in Equation 5-16 and some more information is given in Remark 5.6.
There are n = 6 observations in the sample, hence since i = 1, . . . , n, there are: six stochastic
variables Yi
, six variables xi and six stochastic variables εi
. The i.i.d. assumption is that the
six errors:
• all come from the same population, which is normal distributed N(0, σ2
)
• are drawn independently from the population
The assumption of independence of the errors is actually not trivial! It can be summed up
in that the conditions, which leads to “unmodelled” variance in Yi
, must be varied randomly.
As an example think of: if another variable (e.g. temperature) actually affected the dependent
variables Yi
, and this variable is not measured and thus not included in the model, then the
experiment should actually be carried out such that this variable is varied randomly. If not
then the sample will be biased and eventually (some of) the conclusions drawn can be affected
(estimates, p-values, ...). This basically means, that one should be very careful when designing
experiments and making sure that the studied phenomena is not affected by some unmeasured
non-random conditions during the experiment...
------------------------------------ FACIT-END ------------------------------------
`,`
Based on the estimated slope in model1, give an estimate of the spring constant, k:
1 0.5483
2 3.2433
3 2.0148
4* 16.8663
5 5.2004
13
----------------------------------- FACIT-BEGIN -----------------------------------
According to Hooke’s law given above, the spring constant corresponds to the estimated slope,
but with the opposite sign, i.e. ˆk = −βˆ
1.
------------------------------------ FACIT-END ------------------------------------
`,`
It is of interest to test whether the model’s intercept is significantly different from zero. Give
the relevant test statistic:
1 -8.371
2* 5.915
3 0.004
4 0.548
5 0.169
----------------------------------- FACIT-BEGIN -----------------------------------
The null hypothesis is H0 : β0 = 0, so β0,0 = 0 in Theorem 5.12. Using the R output (and
standard notation from the book), the observed t-test statistic may be computed as
tobs =
βˆ
0
σˆβ0
=
3.2433
0.5483
= 5.915.
------------------------------------ FACIT-END ------------------------------------
`,`
What is the distribution of the test statistic used to test whether the model’s slope can be
assumed to be zero?
1 A t-distribution with 6 degrees of freedom.
2 A standard normal distribution.
3 An F-distribution with 6 degrees of freedom.
4 A normal distribution with mean zero and standard deviation 0.1686.
14
5* A t-distribution with 4 degrees of freedom.
----------------------------------- FACIT-BEGIN -----------------------------------
See again Theorem 5.12. Here n = 6, so degrees of freedom is n − 2 = 4.
------------------------------------ FACIT-END ------------------------------------
`,`
In a simple linear regression like the above, the estimators of the intercept and slope parameters
are often correlated. When is this correlation zero?
1 When the standard deviation of the dependent variable is 1.
2 When the slope is estimated as zero.
3* When the average of the explanatory variable is zero.
4 When the standard deviation of the explanatory variable is 1.
5 When the average of the dependent variable is zero.
----------------------------------- FACIT-BEGIN -----------------------------------
According to Theorem 5.8 Equation 5-29, the covariance, and hence the correlation, between
the intercept and the slope is zero if the sample mean of the explanatory variable, ¯x, is zero.
------------------------------------ FACIT-END ------------------------------------
Exercise VII
In order to investigate whether data from a single sample is log-normal distributed, one could
compare the data to a normal distribution using a qq-plot. If the data is log-normal distributed
there will (typically) be fewer small values and more large values in the data, compared to a
normal distribution with the same mean and variance as the sample.
`,`
Below, four qq-plots are shown in which four different samples with mean 0 and variance 1 are
each compared to a standard normal distribution. Let z0.25 and z0.75 denote the first and third
quartile of the standard normal distribution, respectively, while q0.25 and q0.75 denote the first
15
and third quartile of the sample. The red line is drawn through the points (z0.25, q0.25) and
(z0.75, q0.75). Which sample fulfills the above description of log-normal distributed data?●● ●●●●●● ● ●●●● ●●● ● ●●● ●● ● ●● ●●● ● ● ● ● ● ● ● ● ●● ●●● ● ● ● ●● ● ● ● ● ●
−3 −2 −1 0 1 2 3
−1
0 1 2
3
4
5
6
Standard normal distribution N(0,1)
Sample
A ● ● ● ● ●● ● ● ● ● ●● ● ● ● ● ● ● ● ● ●●●● ● ●● ● ● ● ●● ●●● ● ● ●● ● ● ● ● ● ● ● ● ● ● ●● ● ●● ● ●●● ● ● ● ● ● ● ● ●● ● ● ●●●
−3 −2 −1 0 1 2 3
−4 −2
0
2
4
6
Standard normal distribution N(0,1)
Sample
B●●●● ●●●●●
−3 −2 −1 0 1 2 3
−1.5 −0.5 0.5 1.0 1.5
Standard normal distribution N(0,1)
Sample
C●●●●● ●●●
−3 −2 −1 0 1 2 3
−3 −2 −1
0 1 2
Standard normal distribution N(0,1)
Sample
D
1* A
2 B
3 C
4 D
5 None of the above.
16
----------------------------------- FACIT-BEGIN -----------------------------------
The answer is A. In B, the sample has more small values as well as more large values. The
sample in C has fewer small values and fewer large values. The sample in D seems to be normal
distributed. Verify the shape of a qq-plot of a log-normal distribution vs. a normal distribution
in R:
x <- rlnorm(100)
qqnorm(x)
qqline(x) ● ●● ● ● ● ●● ● ● ● ● ● ● ● ● ● ●● ● ● ● ● ● ●●● ●● ● ● ● ● ● ●● ●●● ●● ● ● ●
−2 −1 0 1 2
0 5 10 15
Normal Q−Q Plot
Theoretical Quantiles
Sample Quantiles
------------------------------------ FACIT-END ------------------------------------
Exercise VIII
17
Histogram 1
Density
−4 −2 0 2 4 6 8
0.00 0.05 0.10 0.15
Histogram 2
Density
5 10 15 20 25 30
0.00 0.02 0.04 0.06 0.08 0.10
Histogram 3
Density
0 10 20 30 40
0.00 0.02 0.04 0.06 0.08 0.10 0.12
`,`
Which distributions are simulated above? (N(µ, σ2
) refers to the normal distribution with
mean µ and variance σ
2
, χ
2
a
to the χ
2 distribution with a degrees of freedom, and Exp(β) to
the exponential distribution with rate β).
1 1: N(0, 4), 2: χ
2
10, 3: Exp(1/5)
2 1: χ
2
4
, 2: N(2, 4), 3: χ
2
1
.
3* 1: N(2, 4), 2: χ
2
12, 3: Exp(1/5)
18
4 1: N(2, 4), 2: Exp(5), 3: χ
2
1
5 1: N(2, 4), 2: χ
2
1
, 3: Exp(1/5)
----------------------------------- FACIT-BEGIN -----------------------------------
The distribution in Histogram 1 takes negative values (which the χ
2 distribution doesn’t), and
it seems symmetric around 2, so based on the available choices, it can only be the N(2, 4)
distribution. The χ
2
1 distribution has mean 1, and the Exp(5) distribution has mean 1/5.
Thus, based on Histogram 2 (where there isn’t even any values in the data which are as small
as 1), option 3 is the only possible choice. (This may be further verified by considering the
means of some of the other distributions as well).
------------------------------------ FACIT-END ------------------------------------
Exercise IX
Two groups of rats are put on a diet while growing up, and their weight gain between day 28
and day 84 is recorded. 10 rats are put on a diet with a high protein content, while 7 rats are
put on a diet with a low protein content. The collected data (weight gain in grams) is shown
in the table below, with the total weight gain in each group given in the last row:
High protein content Low protein content
134 70
146 118
104 101
119 85
124 107
161 132
107 94
83
113
129
Total 1220 707
Using the numbers in the table, the sample variances in the two groups are calculated to be
s
2
H = 495 and s
2
L = 425, where H and L indicate the groups with high and low protein content,
respectively. It is further given that the usual test, for whether the expected weight gain is the
same for rats on high and low protein diets, has 13.7 degrees of freedom.
`,`
19
Which of the following choices is correct (both statements need to be correct)?
1 Rats in the low protein diet group gain more weight than rats in the high protein diet
group. However, the difference is not statistically significant at the significance level
α = 0.05.
2 Rats in the high protein diet group gain more weight than rats in the low protein diet
group. The difference is statistically significant at the significance level α = 0.05.
3 Rats in the high protein diet group gain more weight than rats in the low protein diet
group. The difference is statistically significant at the significance level α = 0.01.
4 Rats in the low protein diet group gain more weight than rats in the high protein diet
group. The difference is statistically significant at the significance level α = 0.05.
5* Rats in the high protein diet group gain more weight than rats in the low protein diet
group. However, the difference is not statistically significant at the significance level
α = 0.05.
----------------------------------- FACIT-BEGIN -----------------------------------
The estimated difference in expected weight increase is
1220
10
−
707
7
= 21 ,
that is, the increase is larger in the high protein group. However, the observed t-test statistic
is
tobs =
21
p
495/10 + 425/7
= 2.000324
and as the 0.975 percentile of the t-distribution with 13.7 degrees of freedom is
qt(0.975, df = 13.7)
## [1] 2.149201
we conclude that the difference is not significant. This could also be concluded by writing in
the values in R and using the t.test() function.
------------------------------------ FACIT-END ------------------------------------
Exercise X
Statistics Denmark provides data related to Denmark at www.statistikbanken.dk, among it
data on traffic accidents. The following count data is taken from there:
20
Year 2010 2017
Type All Alcohol All Alcohol
Zone City Rural City Rural City Rural City Rural
Single-vehicle accidents 240 491 107 178 174 340 55 96
Others 1779 988 161 84 1456 819 106 48
Values under “all” count all accidents (including drunk-driving accidents) while numbers under
“alcohol” include only drunk-driving accidents.
`,`
Give a 99% confidence interval for the total proportion of drunk driving accidents in 2010,
where you use the relevant normal distribution approximation.
1 0.848 ± 2.58q
0.848
3498
2 0.152 ± 2.58q
0.848
3498
3 0.848 ± 1.96q
0.152·0.848
3498
4 0.848 ± 2.58q
0.152
3498
5* 0.152 ± 2.58q
0.152·0.848
3498
----------------------------------- FACIT-BEGIN -----------------------------------
See Method 7.3. Here, x = 107 + 178 + 161 + 84 = 530 and n = 240 + 491 + 1779 + 988 = 3498,
so
pˆ =
530
3498
= 0.152 , 1 − pˆ = 0.848 ,
and z0.995 = 2.58 is the 0.995 quantile of the standard normal distribution.
------------------------------------ FACIT-END ------------------------------------
`,`
Assume that the proportion of drunk-driving accidents in the “single-vehicle accidents” category
is representative of the total proportion of drunk-driving. (Thus, data from the “others”
category should not be used in this question).
21
Then, using the numbers from the table above and the wording from Table 3.1 of the book,
what may be concluded about the difference in drunk driving between the years 2010 and 2017?
1* There is very strong evidence of a decrease in the proportion of drunk-driving accidents.
2 There is weak evidence of a decrease in the proportion of drunk-driving accidents.
3 There is little or no evidence of a difference in the proportion of drunk-driving accidents.
4 There is weak evidence of an increase in the proportion of drunk-driving accidents.
5 There is very strong evidence of an increase in the proportion of drunk-driving accidents.
----------------------------------- FACIT-BEGIN -----------------------------------
See Method 7.18. Here, x1 = 107 + 178 = 285, n1 = 240 + 491 = 731, x2 = 55 + 96 = 151,
n2 = 174 + 340 = 514. The test for equality of two proportions can be tested in R using the
following:
x1 <- 285
n1 <- 731
x2 <- 151
n2 <- 514
prop.test(c(x1,x2), c(n1,n2), correct = FALSE)
##
## 2-sample test for equality of proportions without continuity
## correction
##
## data: c(x1, x2) out of c(n1, n2)
## X-squared = 12.249, df = 1, p-value = 0.0004656
## alternative hypothesis: two.sided
## 95 percent confidence interval:
## 0.04318181 0.14902331
## sample estimates:
## prop 1 prop 2
## 0.3898769 0.2937743
The estimated proportion of alcohol-related accidents is smaller in 2017 than in 2010, and the
small p-value indicates very strong evidence against the hypothesis of no change from 2010 to
2017.
------------------------------------ FACIT-END ------------------------------------
22
`,`
From the same source, there is also data available on the speed limits for the road stretches
where the accidents occurred. The following data, describing the number of rural zone accidents
at different speed limits in the years 2010 and 2017, were extracted:
2010 2017
0 to 50 km/h 54 58
50 to 100 km/h 1280 966
100 to 130 km/h 144 135
What is the result of the usual test for no change in the distribution of accidents in the speed
limit intervals between the two years (both your conclusion and reasoning must be correct)?
Use the significance level α = 1%.
1* No significant difference is found in the distribution of speed limits between the two years,
as the p-value is larger than the significance level.
2 A significant difference is found in the distribution of speed limits between the two years,
as the p-value is larger than the significance level.
3 A significant difference is found in the distribution of speed limits between the two years,
as the p-value is smaller than the significance level.
4 No significant difference is found in the distribution of speed limits between the two years,
as the p-value is smaller than the significance level.
5 None of the above statements are true.
----------------------------------- FACIT-BEGIN -----------------------------------
Data is read into R and a χ
2
-test is carried out:
data <- matrix(c(54, 1280, 144, 58, 966, 135), ncol = 2)
chisq.test(data)
##
## Pearson's Chi-squared test
##
## data: data
## X-squared = 5.8273, df = 2, p-value = 0.05428
It shows that the p-value for the test is above 1%, and hence a significant difference is found.
23
------------------------------------ FACIT-END ------------------------------------
`,`
In connection with the usual test for whether the distribution of speed limits is the same in
the two years, the following question is asked: What is the estimated proportion of accidents
on roads with speed limits from 50 to 100 km/h in 2017 under the null hypothesis?
1 (58 + 966 + 135)/(54 + 1280 + 144 + 58 + 966 + 135) = 0.440
2 (966)/(54 + 1280 + 144 + 58 + 966 + 135) = 0.366
3 (966)/(58 + 966 + 135) = 0.833
4* (1280 + 966)/(54 + 1280 + 144 + 58 + 966 + 135) = 0.852
5 (54 + 58 + 144 + 135)/(54 + 1280 + 144 + 58 + 966 + 135) = 0.148
----------------------------------- FACIT-BEGIN -----------------------------------
Under the null hypothesis, the proportion of accidents that happen at 50 to 100 km/h roads
does not depend on the accident year, then the proportion is estimated using the data from both
years: x50−100km/h = 1280+966 = 2246 and n50−100km/h = 54+1280+144+58+966+135 = 2637.
Then
pˆ50-100km/h =
x50-100km/h
n50-100km/h
= 0.852
------------------------------------ FACIT-END ------------------------------------
Exercise XI
Below is a sample of 20 independent observations, read into R in the vector x:
x <-
c(13, 12, 9, 7, 12, 15, 12, 10, 6, 13, 7, 13, 19, 12, 6, 4, 15, 16, 11, 18)
The data do not originate from a known distribution, but we are interested in the population
mean and the uncertainty of its estimate.
`,`
What is the sample mean ¯x and variance s
2
(both quantities must be correct)?
24
1 x¯ = 11.2 and s
2 = 16.7.
2* x¯ = 11.5 and s
2 = 16.7.
3 x¯ = 11.2 and s
2 = 4.1.
4 x¯ = 11.5 and s
2 = 4.1.
5 x¯ = 11.5 and s
2 = 16.7
2
.
----------------------------------- FACIT-BEGIN -----------------------------------
Data can be read into R, and sample mean and variance calculated:
x <-
c(13, 12, 9, 7, 12, 15, 12, 10, 6, 13, 7, 13, 19, 12, 6, 4, 15, 16, 11, 18)
mean(x)
## [1] 11.5
var(x)
## [1] 16.68421
------------------------------------ FACIT-END ------------------------------------
`,`
Now, we perform a resampling of x to get an idea of the uncertainty of the sample mean. We
draw 200 resamples with replacement from the 20 observations in x, each with sample size
20. Subsequently, the mean of each of the 200 resamples is calculated. The R code for this
operation is:
apply(replicate(200, sample(x, replace = TRUE)), 2, mean)
Below, the 10 largest and 10 smallest sample means of the 200 resamples are shown.
smallest 9.00 9.65 9.65 9.80 9.90 9.95 10.00 10.00 10.00 10.05
largest 12.95 12.95 12.95 13.00 13.05 13.10 13.10 13.10 13.15 13.40
Using the results above and the book’s definition of percentiles (“type = 2” in R), which of
the following is a 95% bootstrap confidence interval for the population mean?
1 [10.05, 12.95]
25
2 [9.00, 13.40]
3 [9.80, 13.10]
4 [9.65, 13.10]
5* [9.925, 13.075]
----------------------------------- FACIT-BEGIN -----------------------------------
See Definition 1.7. For n = 200, and p1 = 0.025, p2 = 0.975, it holds that p1n = 5 and
p2n = 195. Then, the relevant 0.25 quantile q0.025 is the average of the 5th and 6th ordered
averages, while the 0.975 quantile q0.975 is average of the 195th and 196th ordered averages:
q0.025 =
9.90 + 9.95
2
= 9.925 and q0.975 =
13.05 + 13.10
2
= 13.075
------------------------------------ FACIT-END ------------------------------------
Exercise XII
During the preparation for a small festival, the toilet facilities are taken under consideration.
Mobile toilets need to be ordered such that the capacity is sufficient, but not too high, since
will lead to more cleaning and higher costs.
It is assumed that, on average, 150 guests need to use the toilets every hour, and that their
arrival follows a Poisson distribution. In addition, it is assumed that each toilet can serve 20
guests per hour.
`,`
Suppose that 10 toilets are ordered. What is then the probability that, in a randomly selected
hour, the number of guests who arrive at the toilets exceeds the capacity?
1* 0.0042%
2 2.3%
3 11%
4 24%
5 99%
26
----------------------------------- FACIT-BEGIN -----------------------------------
Let X represent the number of guests arriving at the toilets in a randomly selected hour,
then X ∼ Pois(150). The capacity is 10 · 20 = 200 per hour, hence we need to calculate
P(X > 200) = 1 − P(X ≤ 200):
1 - ppois(200, lambda=150)
## [1] 4.205886e-05
------------------------------------ FACIT-END ------------------------------------
`,`
A group of DTU students have decided to help small festivals optimize their logistical conditions. Among other things, the students have collected data on the use of toilets at small
festivals. An examination of these data shows that a better model can be made to represent
the number of guests who need to use the facilities in a randomly selected hour. This number
can be modelled by an exponential distribution with mean “number of guests”
10 , where “number of
guests” is the total number of guests at the festival. In this question, this new model must be
used.
A festival with 1500 guests is now considered. How many toilets should, at least, be ordered to
ensure that the probability that not everyone can use the facilities is less than 2% in a randomly
selected hour (given as a call in R)? It is still assumed that each toilet can serve 20 guests per
hour.
1 ppois(20, lambda = 15) * 20
2 qpois(0.98, lambda = 1500/10) / 20
3 qexp(0.98, rate = 10/15)
4* qexp(0.98, rate = 10/1500) / 20
5 qexp(0.98, rate = 10/1500) * 20
----------------------------------- FACIT-BEGIN -----------------------------------
Let Y represent the number of guests arriving at the toilets in a randomly selected hour. Then
Y ∼ Exp(10/1500). We need to find y such that
P(Y ≤ 20y) ≥ 0.98.
We can solve P(Y ≤ 20y) = 0.98 for y by computing
27
qexp(0.98, rate = 10/1500) / 20
## [1] 29.34017
Thus, ordering 30 toilets or more ensures that the probability in focus stays below 2%.
------------------------------------ FACIT-END ------------------------------------
Exercise XIII
Below, there’s a small sample with 5 independent observations:
Observations: 11.8071067 -1.7913888 -9.1872410 -4.4860901 -0.2324924
`,`
Which of the following answer options is the only one that can possibly be correct?
1 It is impossible that the observations were sampled from a normal distribution with mean
0 and variance 102
.
2 It is possible that the observations were sampled from a uniform distribution with parameters -9 and 12.
3* It is possible that the observations were sampled from a t-distribution with 1 degree of
freedom.
4 It is possible that the observations were sampled from an F-distribution with 1 and 2
degrees of freedom.
5 It is possible that the observations were sampled from an exponential distribution with
rate 1.
----------------------------------- FACIT-BEGIN -----------------------------------
The F distributions and exponential distributions don’t give rise to negative observations,
which eliminates options 4 and 5. Likewise, the uniform distribution with parameters -9 and
12 wouldn’t yield the observation −9.1872410, which elimates option 2. There is no reason
why the observations could not come from the N(0, 102
) distribution, which elimates option 1.
We’re then left with option 3: There’s no reason why these observations couldn’t come from
a t-distribution with 1 degree of freedom (like normal distributions, t distributions take both
positive and negative values).
28
------------------------------------ FACIT-END ------------------------------------
Exercise XIV
A sample was collected, and the following summary statistics were calculated:
Statistic Value
x¯ 5.69
s
2 7.96
Minimum 2.26
Q1 3.45
Q2 5.49
Q3 6.72
Maximum 11.46
n 15
Furthermore, a normal qq-plot was made of the observations: ●
−1 0 1
2 4 6 8 10
Normal Q−Q Plot
Theoretical Quantiles
Sample Quantiles
`,`
Which of the following can be concluded using the given information and the book’s definition
of extreme observations in a sample?
1 There is one extreme observation in the sample.
2 There are two extreme observations in the sample.
29
3 There are at least three extreme observations in the sample.
4* There are no extreme observations in the sample.
5 With the given information, it cannot be concluded whether or not there are extreme
observations in the sample.
----------------------------------- FACIT-BEGIN -----------------------------------
First, note that
IQR = Q3 − Q1 = 6.72 − 3.45 = 3.27 ,
(Definition 1.15) so
Q3 + 1.5 · IQR = 11.625
Q1 − 1.5 · IQR = −1.455
There are no extreme observations in the sample, as the maximum is smaller than Q3+1.5·IQR
and the minimum is larger than Q1 − 1.5 · IQR.
------------------------------------ FACIT-END ------------------------------------
`,`
Which of the following conclusions can, with certainty, be drawn about the population using
the given information?
1 The population has no negative values.
2 The population is normal distributed.
3 The distribution of the population is left-skewed.
4 The population has no values above 11.46.
5* None of the four conclusions above can be drawn.
----------------------------------- FACIT-BEGIN -----------------------------------
The summary statistics contribute to describing the sample and the data generating distribution, but they don’t tell the whole story about the population.
------------------------------------ FACIT-END ------------------------------------
30
`,`
Assuming that the observations in the sample are independent and identically normal distributed, what is a correct 95% confidence interval for the population mean?
1 5.69 ± 2.95 ·
2.82
14
2 5.69 ± 2.98 · √
7.96
15
3 5.69 ± 1.96 · √
2.82
14
4* 5.69 ± 2.14 · √
2.82
15
5 5.69 ± 2.58 · √
7.96
14
----------------------------------- FACIT-BEGIN -----------------------------------
See Method 3.9:
x¯ ± t0.975 ·
√
s
2
√
n
= 5.69 ± 2.14 ·
2.82
√
15
where t0.975 is the 0.975 quantile in the t-distribution with 14 degrees of freedom.
------------------------------------ FACIT-END ------------------------------------
The exam paper is finished. Have a great Christmas vacation!
31`]
|
58d6e6dc335d90d69cb853345bf32ed5fcb0f1c0
|
TypeScript
|
johnnyicarus/star-wars-opedia
|
/src/app/core/reducers/film.reducer.ts
| 2.71875
| 3
|
import { FilmActions, FilmActionTypes } from '../actions/film.actions';
import { addSearchIfNew, setAddManyState } from '../utils/state.utils';
import { Film } from '../models/film.model';
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';
import { SearchResults } from '../../search/models/search.model';
export interface FilmState extends EntityState<Film> {
count: number;
searches: {
[term: string]: SearchResults;
};
}
export const filmAdapter: EntityAdapter<Film> = createEntityAdapter<Film>();
export const filmInitialState: FilmState = filmAdapter.getInitialState({
count: 0,
searches: {}
});
export function filmReducer(
state = filmInitialState,
action: FilmActions
): FilmState {
switch (action.type) {
case FilmActionTypes.AddFilm:
return filmAdapter.addOne(action.payload.entity, state);
case FilmActionTypes.AddFilms:
return filmAdapter.addMany(<Film[]>action.payload.results, <FilmState>setAddManyState(state, action.payload));
case FilmActionTypes.InitializeFilms:
return <FilmState>addSearchIfNew(action.payload.term, state);
default:
return state;
}
}
|
dd2c17f1472694b31738b13fd8682e12fae9503e
|
TypeScript
|
ggeorgievx/core
|
/packages/core/src/metrics/metrics/number.ts
| 2.546875
| 3
|
import { Glue42Core } from "../../../glue";
import { Protocol } from "../types";
import { BaseMetric } from "./base";
import metricTypes from "../const/metric-types";
export class NumberMetric extends BaseMetric<number> implements Glue42Core.Metrics.NumberMetric {
constructor(definition: Glue42Core.Metrics.MetricDefinition, system: Glue42Core.Metrics.System, transport: Protocol, value: number) {
super(definition, system, transport, value, metricTypes.NUMBER);
}
public incrementBy(num: number): void {
this.update(this.value + num);
}
public increment(): void {
this.incrementBy(1);
}
public decrement(): void {
this.incrementBy(-1);
}
public decrementBy(num: number): void {
this.incrementBy(num * -1);
}
}
|
6b6b97daefc54c43cbf95ab99e5d7c3a1c21b420
|
TypeScript
|
Aydoun/hot-packets
|
/src/middleware/token-middleware.ts
| 2.515625
| 3
|
import jwt from "jsonwebtoken";
import { Request, Response, NextFunction } from "express";
export default async (req: Request, res: Response, next: NextFunction) => {
const token = req.headers["x-api-key"] as string;
if (token) {
try {
const decoded = await jwt.verify(token, process.env.TOKEN_SECRET);
// @ts-ignore
req.decoded = decoded;
next();
} catch (e) {
next(new Error("Invalid Token"));
}
} else {
next(new Error("No Token Provided"));
}
};
|
aaaf937eb4cdc1e15bfe9ab2114d7921984e218d
|
TypeScript
|
CodeKul/ts-brushup-sg-1-3
|
/first/ts-oops.ts
| 2.640625
| 3
|
export class Car {
speed: number;
cost: string;
constructor(
private highSpd = 500
) {
this.speed = 100;
}
}
|
33269236d2797f7f950346d465ece0a9157db649
|
TypeScript
|
HymanHuang/angular2-lesson
|
/examples/service/ts/InputItem.ts
| 2.515625
| 3
|
import {Component, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'input-item',
template: `
<form (ngSubmit)="onSubmit()">
<input type="text" [(ngModel)]="text" name="todo">
<button type="submit">Add Item</button>
</form>
`
})
export class InputItem {
text: string;
@Output() onItemAdded = new EventEmitter();
onSubmit() {
this.onItemAdded.emit({
isChecked: false,
txt: this.text
});
this.text = '';
}
}
|
210870f866ff8eb9c03a0af47050ed76548ff8db
|
TypeScript
|
dogukanucak/Nyx-Bulma
|
/projects/nyx-bulma/src/lib/common/nyx-elements/nyx-tag/nyx-tag.component.ts
| 2.546875
| 3
|
import { Component, OnInit, Input } from '@angular/core';
import { BaseElement } from '../../abstracts/nyx-base-element';
import { Bulma } from '../../../decorators/bulma.decorator';
/**
* Nyx Tag Component
* Based on: {@link https://bulma.io/documentation/elements/tag/}
* @example
* Usage Example: ```<nyx-tag text='Hello' color='success' size='medium'></nyx-tag>```
*/
@Component({
selector: 'nyx-tag',
templateUrl: './nyx-tag.component.html',
styleUrls: ['./nyx-tag.component.scss']
})
export class NyxTagComponent extends BaseElement implements OnInit {
protected elementType = 'tag';
@Input() @Bulma() color: string;
@Input() @Bulma() size: string;
@Input() @Bulma() rounded: boolean;
@Input() text: string;
constructor() {
super();
}
ngOnInit() {
}
getClass(): string {
if(this.bulmaClass) {
return super.getClass();
} else {
return `${this.elementType}${this.color}${this.size}${this.rounded}`;
}
}
}
|
b88627c4c0357daeebb71139951df29b2b5aef49
|
TypeScript
|
risatino/mapboxgl-powerbi
|
/src/ts/mapboxConverter.ts
| 2.6875
| 3
|
module powerbi.extensibility.visual {
export module mapboxConverter {
const isTooltip = (role) => {
return role == 'color' || role == 'size' || role == 'tooltips' || role == 'cluster';
}
const checkLngLatValid = (feat) => {
return feat.longitude != undefined && feat.latitude != undefined &&
feat.latitude >= -90 && feat.latitude <= 90 &&
feat.longitude >= -180 && feat.longitude <= 180
}
const transformToObjectArray = (rows, columns) => {
let domain : any = [];
const datas = rows.map( row => {
return row.reduce( (obj, value, index) => {
const column = columns[index]
Object.keys(column.roles).map( role => {
if (isTooltip(role)) {
if (!obj.tooltip) {
obj.tooltip = {}
}
obj.tooltip[column.displayName] = value;
}
if (role == 'cluster') {
obj.clusterField = column.displayName;
}
obj[role] = value;
if (role == 'color') {
const t = column.type.primitiveType;
mapboxUtils.pushIfNotExist(domain, value);
if (typeof value != 'number') {
const colorIndex = mapboxUtils.positionInArray(domain, value);
obj.color = mapboxUtils.getColorFromIndex(colorIndex);
} else {
obj.color = value;
}
}
})
return obj;
}, {});
});
return {
datas,
domain,
}
}
const getFeatures = (rows, columns) => {
const { datas, domain } = transformToObjectArray(rows, columns);
return datas.filter(checkLngLatValid).map(d => {
let properties : any = {
"colorValue": d.color,
"tooltip": JSON.stringify({
clusterField: d.clusterField,
content: d.tooltip
}),
"sizeValue": d.size,
"location": d.location,
"clusterValue": d.cluster
}
if ( d.location ) {
// If location for choropleth
return { properties }
}
else {
// Return geojson feature
let feat: GeoJSON.Feature<any> = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [d.longitude, d.latitude]
},
"properties": properties
}
return feat;
}
});
}
export function convert(dataView: DataView, host: IVisualHost) {
const {columns, rows} = dataView.table;
return getFeatures(rows, columns)
}
}
}
|
ec9f053bfc6715637a8eb39c0e0ca61ee2c7373d
|
TypeScript
|
matyj/fonn-interview
|
/src/events/services/impl/create-event.service.ts
| 2.734375
| 3
|
import { BusinessError } from '../../../errors/business.error';
import { Event } from '../../../events/models/event';
import { EventsRepo } from '../../../events/repos/events.repo';
import { DateRangeValidator } from '../../../events/validators/date-range.validator';
import { DateTime } from '../../../utils/date-time';
import { uniqueId } from '../../../utils/unique-id.generator';
export class CreateEventService {
constructor(private eventsRepo: EventsRepo) {}
async execute(dateFrom: DateTime, dateTo: DateTime, title: string) {
await this.validateParams(dateFrom, dateTo);
const newEvent = new Event(uniqueId(), title, dateFrom, dateTo);
this.eventsRepo.save(newEvent);
return Promise.resolve(newEvent);
}
private async validateParams(dateFrom: DateTime, dateTo: DateTime) {
DateRangeValidator.validate(dateFrom, dateTo);
(await this.eventsRepo.getAll()).forEach((item) => {
if (item.startDate.isBetween(dateFrom, dateTo)) {
throw new BusinessError('The new events date is conflicting with the already saved event');
}
});
}
}
|
12e3702f61a78fb593bc79e11d80c754d2ad96d7
|
TypeScript
|
Ac-blog/Ac-varok-client-nuxt
|
/api/request.ts
| 2.875
| 3
|
/**
* 封装Axios
* 处理请求、响应错误信息
*/
// import { Message } from 'iView'
import axios from 'axios' //引用axios
// create an axios instance
const service = axios.create({
baseURL: 'http://127.0.0.1:7001',
withCredentials: false, // send cookies when cross-domain requests
timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
// config.headers['-Token'] = getToken()
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
const res = response.data //res is my own data
if (res.code === 200) {
// do somethings when response success
return res.data
} else {
// if the custom code is not 200, it is judged as an error.
// new Message().error({
// content: res.msg || 'Error',
// duration: 2 * 1000
// })
return Promise.reject(new Error(res.msg || 'Error'))
}
},
error => {
console.log('err' + error) // for debug
// new Message().error({
// content: error.message,
// duration: 5 * 1000
// })
return Promise.reject(error)
}
)
export default service
|
4b176bc7a331e6ed0269ac34bd6c8c0d1caf6d2f
|
TypeScript
|
Zilborg/payload
|
/src/collections/requestHandlers/updateByID.ts
| 2.59375
| 3
|
import { Response, NextFunction } from 'express';
import httpStatus from 'http-status';
import { PayloadRequest } from '../../express/types';
import formatSuccessResponse from '../../express/responses/formatSuccess';
import updateByID from '../operations/updateByID';
export type UpdateResult = {
message: string
doc: Document
};
export async function deprecatedUpdate(req: PayloadRequest, res: Response, next: NextFunction): Promise<Response<UpdateResult> | void> {
req.payload.logger.warn('The PUT method is deprecated and will no longer be supported in a future release. Please use the PATCH method for update requests.');
return updateByIDHandler(req, res, next);
}
export default async function updateByIDHandler(req: PayloadRequest, res: Response, next: NextFunction): Promise<Response<UpdateResult> | void> {
try {
const draft = req.query.draft === 'true';
const autosave = req.query.autosave === 'true';
const doc = await updateByID({
req,
collection: req.collection,
id: req.params.id,
data: req.body,
depth: parseInt(String(req.query.depth), 10),
draft,
autosave,
});
let message = req.t('general:updatedSuccessfully');
if (draft) message = req.t('version:draftSavedSuccessfully');
if (autosave) message = req.t('version:autosavedSuccessfully');
return res.status(httpStatus.OK).json({
...formatSuccessResponse(message, 'message'),
doc,
});
} catch (error) {
return next(error);
}
}
|
729639e564e816e2d57eb67f3afa77ec9291555a
|
TypeScript
|
alexanderstueben/neverdrinkagain
|
/src/store/actions/TaskActions.ts
| 2.515625
| 3
|
import { ThunkAction, ThunkDispatch } from 'redux-thunk';
import {
AddTaskActionType,
SetTasksActionType,
SetTasksWithGamemodesActionType, TaskActionTypes, UpdateTaskActionType
} from '../../types/action-types/TaskActionTypes';
// import { Task } from '../../types/models/Task';
import { TaskState } from '../../types/states/TaskState';
import { getRepository } from 'typeorm';
import { Task } from '../../entities/task.entity';
import { Gamemode } from '../../entities/gamemode.entity';
export const SET_TASKS = 'SET_TASKS';
export const SET_TASK_BY_ID = 'SET_TASK_BY_ID';
export const SET_TASKS_WITH_GAMEMODES = 'SET_TASKS_WITH_GAMEMODES'
export const ADD_TASK = 'ADD_TASK';
export const UPDATE_TASK = 'UPDATE_TASK';
export const TaskActions = {
fetchTasks: (): ThunkAction<Promise<void>, TaskState, {}, SetTasksActionType> => {
return async (dispatch: ThunkDispatch<TaskState, {}, SetTasksActionType>) => {
const tasks = await getRepository(Task).find();
dispatch({ type: SET_TASKS, tasks });
}
},
fetchTasksWithGamemodes: (): ThunkAction<Promise<void>, TaskState, {}, SetTasksWithGamemodesActionType> => {
return async (dispatch: ThunkDispatch<TaskState, {}, SetTasksWithGamemodesActionType>) => {
const tasksWithGamemodes = await getRepository(Task).findOne(1, { relations: ['gamemodes'] })
if (tasksWithGamemodes) {
dispatch({ type: SET_TASKS_WITH_GAMEMODES, tasksWithGamemodes: [tasksWithGamemodes] });
}
}
}
// fetchTasksByGameModeId: (gameModeId: string): ThunkAction<Promise<void>, TaskState, {}, SetTasksByGameModeIdActionType> => {
// return async (dispatch: ThunkDispatch<TaskState, {}, SetTasksByGameModeIdActionType>) => {
// const response = await fetch(`http://10.0.19.31:9000/tasks.json?ns=neverdrinkagain-app`);
// if (!response.ok) {
// throw new Error(`Error while getting tasks !`);
// }
// const data: {[key: string]: Task} = await response.json();
// const tasks: Task[] = [];
// for (const key in data) {
// if (data[key].gamemodes?.includes(gameModeId)) {
// tasks.push({
// id: key,
// text: data[key].text,
// category: data[key].category,
// createDate: data[key].createDate,
// updateDate: data[key].updateDate,
// gamemodes: data[key].gamemodes
// });
// }
// }
// dispatch({ type: SET_TASKS_BY_GAMEMODE_ID, tasks });
// }
// },
// addTask: (text: string, category: string): ThunkAction<Promise<void>, TaskState, {}, AddTaskActionType> => {
// return async (dispatch: ThunkDispatch<TaskState, {}, AddTaskActionType>) => {
// const createDate = new Date().getTime();
// const updateDate = new Date().getTime();
// const response = await fetch('http://10.0.19.31:9000/tasks.json?ns=neverdrinkagain-app', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({
// text,
// category,
// gamemodes: [],
// createDate,
// updateDate
// })
// });
// if (!response.ok) {
// throw new Error('Error while creating a task!');
// }
// const resData: {name: string} = await response.json();
// const task: Task = {
// id: resData.name,
// text,
// category,
// gamemodes: [],
// updateDate,
// createDate
// }
// dispatch({ type: ADD_TASK, task })
// }
// },
// updateTask: (taskId: string, text?: string, category?: string, gamemodes?: string[]): ThunkAction<Promise<void>, TaskState, {}, UpdateTaskActionType> => {
// return async (dispatch: ThunkDispatch<TaskState, {}, UpdateTaskActionType>) => {
// const updateDate = new Date().getTime();
// const response = await fetch(`http://10.0.19.31:9000/tasks/${taskId}.json?ns=neverdrinkagain-app`, {
// method: 'PATCH',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({
// text,
// category,
// gamemodes,
// updateDate
// })
// });
// if (!response.ok) {
// throw new Error('Error while creating a task!');
// }
//
// const data = {
// text,
// category,
// gamemodes: [],
// updateDate,
// }
// dispatch({ type: UPDATE_TASK, taskId, data })
// }
// }
}
|
30559de08bccbfda738c66ca4dcd6201e6d26b82
|
TypeScript
|
onthia/seq-image-player
|
/src/utils/checkLowBattery.ts
| 3.015625
| 3
|
// 通过setTimeout执行的前后时间差和实际经过的时间差来判断IPhone设备是否处于低电量
// 参数全是基于经验
const OFFSET = 4;
const CHECK_TIME = 30;
const NEED_PASS_RESULT_PERCENTAGE = 0.4;
const INTERVAL = 16;
const checkInterval = (interval: number): boolean => {
return interval > INTERVAL * 2 - OFFSET;
};
const checkPercentage = (checkResult: number[]): boolean => {
return checkResult.filter((item) => item).length / checkResult.length > NEED_PASS_RESULT_PERCENTAGE;
};
export default (): Promise<boolean> => {
return new Promise((resolve) => {
let checkTime = 0;
let lastTime = Date.now();
const checkResult = [];
const fn = () => {
setTimeout(() => {
const now = Date.now();
checkResult.push(checkInterval(now - lastTime));
lastTime = now;
checkTime += 1;
if (checkTime < CHECK_TIME) {
fn();
} else {
resolve(checkPercentage(checkResult));
}
}, INTERVAL);
};
fn();
});
};
|
0e3dfb366c6d547485502ce9d329303d40f47f45
|
TypeScript
|
moredrowsy/react-native-sudoku
|
/src/storage/store/slices/options.slice.ts
| 2.5625
| 3
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState, AppThunk } from '..';
import * as LocalStorage from '../../local-storage';
import { AppOptions, ThemeNames } from '../../../types';
import { setThemeType } from './theme.slice';
const sliceName = 'options';
const initialState: AppOptions = {
showHints: true,
showReveal: true,
themeName: 'indigo',
};
// SLICE
const options = createSlice({
name: sliceName,
initialState,
reducers: {
setOptions: (state, action: PayloadAction<AppOptions>) => {
return action.payload;
},
setShowHints: (state, action: PayloadAction<boolean>) => {
state.showHints = action.payload;
},
setShowReveal: (state, action: PayloadAction<boolean>) => {
state.showReveal = action.payload;
},
setThemeName: (state, action: PayloadAction<ThemeNames>) => {
state.themeName = action.payload;
},
},
});
export const { setOptions, setShowHints, setShowReveal, setThemeName } =
options.actions;
// SELECTOR
export const selectOptions = (state: RootState) => state.options;
// ASYNC ACTIONS
export const setShowHintsAsync =
(
showHints: boolean,
onSuccess?: () => void,
onError?: (msg: string) => void
): AppThunk =>
async (dispatch, getState) => {
try {
const options = selectOptions(getState());
LocalStorage.options.setOptions({ ...options, showHints });
dispatch(setShowHints(showHints));
if (onSuccess) onSuccess();
} catch (e: unknown) {
if (onError) {
if (e instanceof Error) onError(e.message);
else if (typeof e === 'string') onError(e);
else onError('Error');
}
}
};
export const setShowRevealAsync =
(
showReveal: boolean,
onSuccess?: () => void,
onError?: (msg: string) => void
): AppThunk =>
async (dispatch, getState) => {
try {
const options = selectOptions(getState());
LocalStorage.options.setOptions({ ...options, showReveal });
dispatch(setShowReveal(showReveal));
if (onSuccess) onSuccess();
} catch (e: unknown) {
if (onError) {
if (e instanceof Error) onError(e.message);
else if (typeof e === 'string') onError(e);
else onError('Error');
}
}
};
export const setThemeNameAsync =
(
themeName: ThemeNames,
onSuccess?: () => void,
onError?: (msg: string) => void
): AppThunk =>
async (dispatch, getState) => {
try {
const options = selectOptions(getState());
LocalStorage.options.setOptions({ ...options, themeName });
dispatch(setThemeName(themeName));
dispatch(setThemeType(themeName));
if (onSuccess) onSuccess();
} catch (e: unknown) {
if (onError) {
if (e instanceof Error) onError(e.message);
else if (typeof e === 'string') onError(e);
else onError('Error');
}
}
};
export const initAppOptionsAsync =
(onSuccess?: () => void, onError?: (msg: string) => void): AppThunk =>
async (dispatch, getState) => {
try {
const options = await LocalStorage.options.getOptions();
if (options) {
dispatch(setOptions(options));
dispatch(setThemeType(options.themeName));
}
if (onSuccess) onSuccess();
} catch (e: unknown) {
if (onError) {
if (e instanceof Error) onError(e.message);
else if (typeof e === 'string') onError(e);
else onError('Error');
}
}
};
export default options.reducer;
|
34fc3f1e8962c89f626f48049f5dc5b131b2e166
|
TypeScript
|
ElNinjaGaiden/2FAuthLabClient
|
/src/store/session/reducer.ts
| 2.859375
| 3
|
import * as session from './actions';
import { ActionType, getType } from 'typesafe-actions';
import { SessionState } from './types';
export type SessionAction = ActionType<typeof session>;
const defaultState: SessionState = {
user: undefined,
passwordVerified: false,
tokenVerified: false
}
const reducer = (state = defaultState, action: SessionAction): SessionState => {
switch (action.type) {
// case getType(session.registerUser.success):
// return {
// ...state,
// authenticationFactor1: true,
// user: action.payload
// }
// case getType(session.verifySecret.success):
// return {
// ...state,
// authenticationFactor2: true
// }
case getType(session.updateUser):
return {
...state,
user: action.payload
}
case getType(session.passwordVerificationSuccesful):
return {
...state,
passwordVerified: true
}
case getType(session.tokenVerificationSuccesful):
return {
...state,
tokenVerified: true
}
default:
return state;
}
}
export default reducer;
|
6eb5fb97532870dd01fb4ef35969bd55e981ead8
|
TypeScript
|
eMed-com/amazon-chime-sdk-js
|
/build/modality/Modality.d.ts
| 3.09375
| 3
|
export default interface Modality {
/**
* The participant Id
*/
id(): string;
/**
* The base of the Id
*/
base(): string;
/**
* The modality of the Id
*/
modality(): string;
/**
* Check whether the current Id contains the input modality
*/
hasModality(modality: string): boolean;
/**
* Create a new Id using the base of the current Id and the input modality
*/
withModality(modality: string): Modality;
}
|
4b468d9ca1fdda27822f5e5648b0d93a744248c4
|
TypeScript
|
csj-libs/JSBridge-1
|
/bridgejs/src/core/proxy.ts
| 2.828125
| 3
|
import { Request, Response } from "./models";
const REMOTE_PROXY = "REMOTE_PROXY";
const LOCAL_PROXY = "LOCAL_PROXY";
// Proxy this class is mounted on window for Native calling
class Proxy {
constructor(private readonly listenr: IProxyListener) {
(window as any)[LOCAL_PROXY] = this;
}
/**
* request2Native
* @param req request
*/
public request2Native(req: Request<any>) {
((window as any)[REMOTE_PROXY] as IRemoteProxy).requestFromJS(JSON.stringify(req));
}
/**
* response2Native
* @param uuid unique identifier for the corresponding request from native
*/
public response2Native(uuid: string, res: Response<any>) {
((window as any)[REMOTE_PROXY] as IRemoteProxy).responseFromJS(uuid, JSON.stringify(res));
}
/**
* requestFromNative
* @param service target service name
* @param req request entity with uuid、service and params
*/
public requestFromNative(service: string, req: Request<any>) {
this.listenr.onRequest(service, req, this);
}
/**
* responseFromNative
* @param uuid unique identifier for the corresponding request to native
*/
public responseFromNative(uuid: string, res: Response<any>) {
this.listenr.onResponse(uuid, res);
}
}
interface IProxyListener {
onRequest(service: string, req: Request<any>, proxy: Proxy): void;
onResponse(uuid: string, res: Response<any>): void;
}
interface IRemoteProxy {
requestFromJS(reqStr: string): void;
responseFromJS(uuid: string, resStr: string): void;
}
export {
Proxy,
IProxyListener,
};
|
49aba8db13be95a72becc78f779cf740a945df92
|
TypeScript
|
flurescein/fenya
|
/src/HtmlAttribute.ts
| 2.609375
| 3
|
import { VirtualNode } from './VirtualNode'
export class HtmlAttribute extends VirtualNode {
constructor(public name: string, public value: string) {
super()
}
get html(): string {
return `${this.name}="${this.value}"`
}
}
|
5fb4880bb8dd970dfd3cf30bd9948f336970a245
|
TypeScript
|
NSFI/ppfish-components
|
/source/components/FormHook/rcFieldForm/utils/typeUtil.ts
| 3.265625
| 3
|
export function toArray<T>(value?: T | T[] | null): T[] {
if (value === undefined || value === null) {
return [];
}
return Array.isArray(value) ? value : [value];
}
|
8d52434d001bbc8a8a84691b1ef89b280eaa456a
|
TypeScript
|
mtringel/BikeRentals
|
/Web.UI/ClientApp/helpers/reduxListDataCache.ts
| 3.25
| 3
|
/// <summary>
/// Cache for advanced filtered data, where filter is complex object. Subset matching is supported.
/// TData, TItem, TKey and TFilter are expected to be immutable. (We don't clone them, just share the references.)
/// </summary>
import { TypeHelper } from "./typeHelper";
import { ArrayHelper } from "./arrayHelper";
import { DateHelper } from "./dateHelper";
import { StringHelper } from "./stringHelper";
export class ReduxListDataCacheProps<TData, TItem, TKey, TFilter> {
// For direct maching:
public readonly getKey: (item: TItem) => TKey;
public readonly newData: () => TData;
public readonly getItems: (data: TData) => TItem[];
public readonly setItems: (data: TData | null, newItems: TItem[]) => TData;
// For sub-set matching:
/// <summary>
/// Evaluates whether subFilter filters a sub-set of parentFilter.
/// Should return null, if subset cannot be calculated. (for example: parentData is not complete set, contains only the first N rows)
/// </summary>
public readonly isSubSet: (parentFilter: TFilter, parentData: TData, subFilter: TFilter) => boolean;
/// <summary>
/// Evaluates subFilter on a subset of data filtered by parentFilter.
/// Should return null, if subset cannot be calculated. (for example: parentData is not complete set, contains only the first N rows)
/// </summary>
public readonly getSubSet: ((
parentFilter: TFilter,
parentData: TData,
subFilter: TFilter,
getMatch: ((item: TItem, filter: TFilter) => boolean) | null
) => TData) | null;
public readonly getMatch: ((item: TItem, filter: TFilter) => boolean) | null;
public readonly supportsSubSets: boolean;
public constructor(
getKey: (item: TItem) => TKey,
getItems: (data: TData) => TItem[],
setItems: (data: TData | null, newItems: TItem[]) => TData,
newData: () => TData,
getMatch?: ((item: TItem, filter: TFilter) => boolean) | undefined | null,
isSubSet?: (parentFilter: TFilter, parentData: TData, subFilter: TFilter) => boolean | undefined | null,
getSubSet?: ((parentFilter: TFilter, parentData: TData, subFilter: TFilter, getMatch: ((item: TItem, filter: TFilter) => boolean) | null) => TData) | undefined | null
) {
this.getKey = getKey;
this.newData = newData;
this.getItems = getItems;
this.setItems = setItems;
this.isSubSet = isSubSet;
this.getSubSet = getSubSet;
this.getMatch = getMatch;
this.supportsSubSets = !TypeHelper.isNullOrEmpty(isSubSet) &&
!TypeHelper.isNullOrEmpty(getMatch) &&
!TypeHelper.isNullOrEmpty(getSubSet);
}
}
class ReduxListDataCacheItem<TData, TFilter> {
filter: TFilter;
data: TData;
}
type ReduxListDataCacheState<TData, TFilter> = { [filterKey: string]: ReduxListDataCacheItem<TData, TFilter> };
/// <summary>
/// Immutable. All methods returns a new instance.
/// </summary>
export class ReduxListDataCache<TData, TItem, TKey, TFilter> {
public readonly EmptyFilter: TFilter = null;
private props: ReduxListDataCacheProps<TData, TItem, TKey, TFilter>;
private state: ReduxListDataCacheState<TData, TFilter>;
public constructor(
props: ReduxListDataCacheProps<TData, TItem, TKey, TFilter>,
state?: ReduxListDataCacheState<TData, TFilter> | undefined | null
) {
this.props = props;
this.state = !TypeHelper.isNullOrEmpty(state) ? state : {};
}
public clear(): ReduxListDataCache<TData, TItem, TKey, TFilter> {
return new ReduxListDataCache<TData, TItem, TKey, TFilter>(this.props);
}
/// <summary>
/// Returns cached data. Calculates sub-sets, if getMatch and getSubSet are specified.
/// Returns null otherways. DOES NOT call server.
/// </summary>
public getListData(filter: TFilter): TData | null {
var filterStr = JSON.stringify(filter);
var directHit = this.state[filterStr];
if (!TypeHelper.isNullOrEmpty(directHit))
return directHit.data;
else if (this.props.supportsSubSets) {
var partialHit = ArrayHelper.firstOrDefault(
ArrayHelper.whereMax(
ArrayHelper.filterDict(this.state, (key, item) => this.props.isSubSet(item.filter, item.data, filter)),
t => t.key.length
));
if (!TypeHelper.isNullOrEmpty(partialHit))
// Should return null, if subset cannot be calculated. (for example: parentData is not complete set, contains only the first N rows)
return this.props.getSubSet(partialHit.item.filter, partialHit.item.data, filter, this.props.getMatch);
else
return null;
}
else
return null;
}
public getById(itemKey: TKey): TItem | null {
return ArrayHelper.findByPredicateInDict(
this.state,
t => this.props.getItems(t.data),
t => TypeHelper.shallowEquals(this.props.getKey(t), itemKey)
);
}
/// <summary>
/// Sets filtered data result. DOES NOT update calculated sub-sets.
/// (According to normal process, this method is called when data was loaded from the server, after it was not possible to get that data from the cache.)
/// </summary>
public setListData(filter: TFilter, newData: TData): ReduxListDataCache<TData, TItem, TKey, TFilter> {
var filterStr = JSON.stringify(filter);
return new ReduxListDataCache<TData, TItem, TKey, TFilter>(
this.props,
ArrayHelper.addToDict(
this.state,
filterStr,
// entities are immutable, clone the list
{
filter: filter,
data: this.props.setItems(newData, ArrayHelper.clone(this.props.getItems(newData)))
}
));
}
/// <summary>
/// We can add the item to all matching sets.
/// Does not assume that sets are already loaded.
/// </summary>
public postSuccess(newItem: TItem, addToFilter?: TFilter | undefined | null): ReduxListDataCache<TData, TItem, TKey, TFilter> {
if (!TypeHelper.isNullOrEmpty(this.props.getMatch)) {
// add to matching sets
return new ReduxListDataCache<TData, TItem, TKey, TFilter>(
this.props,
ArrayHelper.updateDictByPredicate(
this.state,
(key, item) => this.props.getMatch(newItem, item.filter),
// entities are immutable, clone the list
(key, item) => {
return {
filter: item.filter,
data: this.props.setItems(item.data, ArrayHelper.add(this.props.getItems(item.data), newItem))
}
}
));
} else {
if (TypeHelper.isNullOrEmpty(addToFilter))
addToFilter = this.EmptyFilter;
var filterKey = JSON.stringify(addToFilter);
if (!TypeHelper.isNullOrEmpty(this.state[filterKey])) {
// add to last set
return new ReduxListDataCache<TData, TItem, TKey, TFilter>(
this.props,
ArrayHelper.updateDictByPredicate(
this.state,
(key, item) => key === filterKey,
// entities are immutable, clone the list
(key, item) => {
return {
filter: item.filter,
data: this.props.setItems(item.data, ArrayHelper.insert(this.props.getItems(item.data), 0, newItem))
}
}
));
}
else {
// add to new set
return new ReduxListDataCache<TData, TItem, TKey, TFilter>(
this.props,
ArrayHelper.addToDict(
this.state,
filterKey,
// entities are immutable, clone the list
{
filter: addToFilter,
data: this.props.setItems(this.props.newData(), [newItem])
}
));
}
}
}
/// <summary>
/// We can update in all sets by id.
/// Assumes that sets are already loaded.
/// </summary>
public putSuccess(newItem: TItem): ReduxListDataCache<TData, TItem, TKey, TFilter> {
var newKey = this.props.getKey(newItem);
// update all
return new ReduxListDataCache<TData, TItem, TKey, TFilter>(
this.props,
ArrayHelper.updateDictAll(
this.state,
// entities are immutable, clone the list
(key, item) => {
return {
filter: item.filter,
data: this.props.setItems(item.data, ArrayHelper.update(this.props.getItems(item.data), newItem, t => TypeHelper.shallowEquals(this.props.getKey(t), newKey)))
}
}
));
}
/// <summary>
/// We can update in all sets by id.
/// Assumes that sets are already loaded.
/// </summary>
public setFormData(item: TItem): ReduxListDataCache<TData, TItem, TKey, TFilter> {
if (TypeHelper.isNullOrAllItemsAreEmpty(this.props.getKey(item)))
return this; // new, don't add
else
return this.putSuccess(item); // update, if loaded already, this is a newer version
}
/// <summary>
/// We can remove from all sets.
/// Assumes that sets are already loaded.
/// </summary>
public deleteSuccess(itemKey: TKey): ReduxListDataCache<TData, TItem, TKey, TFilter> {
// delete from all
return new ReduxListDataCache<TData, TItem, TKey, TFilter>(
this.props,
ArrayHelper.updateDictAll(
this.state,
// entities are immutable, clone the list
(key, item) => {
return {
filter: item.filter,
data: this.props.setItems(item.data, ArrayHelper.remove(this.props.getItems(item.data), t => TypeHelper.shallowEquals(this.props.getKey(t), itemKey)))
}
}
));
}
}
|
579a3387b506d6ce769f58a3ec7754112bd019cb
|
TypeScript
|
kng83/compound
|
/src/patterns/structural_patterns/bridge_pattern.ts
| 3.640625
| 4
|
interface UIToolkit {
drawBorder(): void;
drawImage(src: string): void;
drawText(text: string): void;
}
//** Wymuszanie by klasa interfejsowa przyjmowala interfejs UIToolKit i metode dostepowo do niego render */
abstract class BasicRender {
constructor(public toolkit: UIToolkit) { }
abstract render(): void;
}
class TextElement extends BasicRender {
constructor(public text: string, toolkit: UIToolkit) {
super(toolkit);
}
render(): void {
this.toolkit.drawText(this.text);
}
}
class ImageElement extends BasicRender {
constructor(public src: string, toolkit: UIToolkit) {
super(toolkit);
}
render(): void {
this.toolkit.drawImage(this.src);
}
}
class Gui implements UIToolkit{
drawBorder(): void {
console.log("DrawBorder not Implemented");
}
drawImage(src: string): void {
console.log("Draw image Method not implemented.");
}
drawText(text: string): void {
console.log("Draw TextMethod not implemented.");
}
some = 4;
}
let toolkit: UIToolkit = new Gui();
let imageElement = new ImageElement('foo.jpg', toolkit);
imageElement.render();
let textElement = new TextElement('bar', toolkit);
textElement.render();
|
62ae4c2704df9e2de6139d42b99ef3d8b8ce973c
|
TypeScript
|
Yanpix/nestjs-app-hybrid
|
/src/modules/dashboard/services/profile.service.ts
| 2.6875
| 3
|
import { Injectable } from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { UserService } from '../../user/user.service';
import { SelectUserDto } from '../../user/dto';
import { ProfileError } from '@exceptions';
@Injectable()
export class ProfileService {
constructor(
private readonly userService: UserService,
) { }
/**
* Update user profile in database
* @param avatar Object: get - filename
* @param userData Object: UpdateUserDto
*/
async getUpdate(avatar: { filename: string }, userData): Promise<SelectUserDto> {
let updateInfo: any = {
fullname: userData.fullname,
email: userData.email,
}
if (avatar != undefined) {
updateInfo.image = `/images/avatar/${avatar.filename}`;
}
let verifPass = await this.comparePasswords(userData);
if (verifPass) {
updateInfo.password = verifPass;
}
let user = await this.userService.updateProfile(userData.id, updateInfo);
return plainToClass(SelectUserDto, user);
}
/**
* Compare passwords
* @param data Object: get - User ID, password and old password
*/
async comparePasswords(data: { id: string, password: string, old_password: string }) {
if (data.password != '' && data.old_password == '') {
throw new ProfileError('Old password and new password should not be empty');
}
if (data.old_password != '' && data.old_password != undefined && data.password != '' && data.password != undefined) {
let user = await this.userService.findById(data.id);
if (await user.validatePassword(data.old_password)) {
let entity = await user.setPassword(data.password);
return entity.password;
} else {
throw new ProfileError('Old password is incorrect');
}
} else {
return false;
}
}
}
|
91229138db5b81d71383a88824d94521c3ef5dd3
|
TypeScript
|
dingzhichao700/DingProj
|
/testarpg/src/webgame/modules/scene/view/DamageItem.ts
| 2.765625
| 3
|
module egret {
export class DamageItem extends egret.gui.UIComponent{
private imgState:egret.gui.UIAsset;
private boxCon:egret.gui.Group;
public constructor() {
super();
}
public setData(text:string, color:number):void {
if(!this.imgState){
this.imgState = new egret.gui.UIAsset();
this.addChild(this.imgState);
}
if(!this.boxCon) {
this.boxCon = new egret.gui.Group();
this.addChild(this.boxCon);
}
this.boxCon.removeAllElements();
if(text.indexOf("闪避") >= 0) {
this.imgState.visible = true;
this.imgState.source = "resource/main/dodge.png";
} else if(text.indexOf("暴") >= 0) {
this.imgState.visible = true;
this.imgState.source = "resource/main/critical.png";
var startX:number = 32;
this.getImage("mark_minus",this.boxCon,startX ,0);
var text:string = text.slice(2);
for(var i: number = 0;i < text.length;i++){
this.getImage("damage_" + text[i], this.boxCon, startX+19*(i+1), 0);
}
} else {
this.imgState.visible = false;
var startX: number = 0;
this.getImage("mark_minus",this.boxCon,startX,0);
var text: string = text.slice(1);
for(var i: number = 0;i < text.length;i++) {
this.getImage("damage_" + text[i],this.boxCon,startX + 19 * (i + 1),0);
}
}
}
private getImage(url:string, con:egret.gui.Group, _x:number=0, _y:number=0):egret.gui.UIAsset {
var img:egret.gui.UIAsset = new egret.gui.UIAsset();
img.source = "resource/main/" + url + ".png";
img.x = _x;
img.y = _y;
con.addElement(img);
return img;
}
}
}
|
47290ec61c4cb8b4b788c3294ed92a944f5ee8e9
|
TypeScript
|
source-academy/js-slang
|
/src/vm/svml-compiler.ts
| 2.703125
| 3
|
import * as es from 'estree'
import { UNKNOWN_LOCATION } from '../constants'
import { ConstAssignment, UndefinedVariable } from '../errors/errors'
import { parse } from '../parser/parser'
import {
CONSTANT_PRIMITIVES,
generatePrimitiveFunctionCode,
INTERNAL_FUNCTIONS,
PRIMITIVE_FUNCTION_NAMES,
vmPrelude
} from '../stdlib/vm.prelude'
import { Context, ContiguousArrayElements } from '../types'
import * as create from '../utils/astCreator'
import { recursive, simple } from '../utils/walkers'
import OpCodes from './opcodes'
const VALID_UNARY_OPERATORS = new Map([
['!', OpCodes.NOTG],
['-', OpCodes.NEGG]
])
const VALID_BINARY_OPERATORS = new Map([
['+', OpCodes.ADDG],
['-', OpCodes.SUBG],
['*', OpCodes.MULG],
['/', OpCodes.DIVG],
['%', OpCodes.MODG],
['<', OpCodes.LTG],
['>', OpCodes.GTG],
['<=', OpCodes.LEG],
['>=', OpCodes.GEG],
['===', OpCodes.EQG],
['!==', OpCodes.NEQG]
])
export type Offset = number // instructions to skip
export type Address = [
number, // function index
number? // instruction index within function; optional
]
export type Instruction = [
number, // opcode
Argument?,
Argument?
]
export type Argument = number | boolean | string | Offset | Address
export type SVMFunction = [
number, // stack size
number, // environment size
number, // number of arguments
Instruction[] // code
]
export type Program = [
number, // index of entry point function
SVMFunction[]
]
// Array of function headers in the compiled program
let SVMFunctions: SVMFunction[] = []
function updateFunction(index: number, stackSize: number, ins: Instruction[]) {
const f = SVMFunctions[index]
f[0] = stackSize
f[3] = ins
}
// Individual function's machine code
let functionCode: Instruction[] = []
// three insert functions (nullary, unary, binary)
function addNullaryInstruction(opCode: number) {
const ins: Instruction = [opCode]
functionCode.push(ins)
}
function addUnaryInstruction(opCode: number, arg1: Argument) {
const ins: Instruction = [opCode, arg1]
functionCode.push(ins)
}
function addBinaryInstruction(opCode: number, arg1: Argument, arg2: Argument) {
const ins: Instruction = [opCode, arg1, arg2]
functionCode.push(ins)
}
type CompileTask = [es.BlockStatement | es.Program, Address, Map<string, EnvEntry>[]]
// toCompile stack keeps track of remaining compiler work:
// these are function bodies that still need to be compiled
let toCompile: CompileTask[] = []
function popToCompile(): CompileTask {
const next = toCompile.pop()
if (!next) {
throw Error('Unable to compile')
}
return next
}
function pushToCompile(task: CompileTask) {
toCompile.push(task)
}
// to compile a function body, we need an index table
// to get the environment indices for each name
// (parameters, globals and locals)
// Each compile function returns the max operand stack
// size needed for running the code. When compilation of
// a function body is done, the function continueToCompile
// writes the max operand stack size and the address of the
// function body to the given addresses.
// must ensure body passed in is something that has an array of nodes
// Program or BlockStatement
function makeToCompileTask(
body: es.BlockStatement | es.Program,
functionAddress: Address,
indexTable: Map<string, EnvEntry>[]
): CompileTask {
return [body, functionAddress, indexTable]
}
function toCompileTaskBody(toCompileTask: CompileTask): es.BlockStatement | es.Program {
return toCompileTask[0]
}
function toCompileTaskFunctionAddress(toCompileTask: CompileTask): Address {
return toCompileTask[1]
}
function toCompileTaskIndexTable(toCompileTask: CompileTask): Map<string, EnvEntry>[] {
return toCompileTask[2]
}
// indexTable keeps track of environment addresses
// assigned to names
function makeEmptyIndexTable(): Map<string, EnvEntry>[] {
return []
}
function makeIndexTableWithPrimitivesAndInternals(
vmInternalFunctions?: string[]
): Map<string, EnvEntry>[] {
const names = new Map<string, EnvEntry>()
for (let i = 0; i < PRIMITIVE_FUNCTION_NAMES.length; i++) {
const name = PRIMITIVE_FUNCTION_NAMES[i]
names.set(name, { index: i, isVar: false, type: 'primitive' })
}
if (vmInternalFunctions) {
for (let i = 0; i < vmInternalFunctions.length; i++) {
const name = vmInternalFunctions[i]
names.set(name, { index: i, isVar: false, type: 'internal' })
}
}
return extendIndexTable(makeEmptyIndexTable(), names)
}
function extendIndexTable(indexTable: Map<string, EnvEntry>[], names: Map<string, EnvEntry>) {
return indexTable.concat([names])
}
function indexOf(indexTable: Map<string, EnvEntry>[], node: es.Identifier) {
const name = node.name
for (let i = indexTable.length - 1; i >= 0; i--) {
if (indexTable[i].has(name)) {
const envLevel = indexTable.length - 1 - i
const { index, isVar, type } = indexTable[i].get(name)!
return { envLevel, index, isVar, type }
}
}
throw new UndefinedVariable(name, node)
}
// a small complication: the toplevel function
// needs to return the value of the last statement
let toplevel = true
const toplevelReturnNodes = new Set([
'Literal',
'UnaryExpression',
'BinaryExpression',
'CallExpression',
'Identifier',
'ArrayExpression',
'LogicalExpression',
'MemberExpression',
'AssignmentExpression',
'ArrowFunctionExpression',
'IfStatement',
'VariableDeclaration'
])
function continueToCompile() {
while (toCompile.length !== 0) {
const nextToCompile = popToCompile()
const functionAddress = toCompileTaskFunctionAddress(nextToCompile)
const indexTable = toCompileTaskIndexTable(nextToCompile)
const body = toCompileTaskBody(nextToCompile) as taggedBlockStatement
body.isFunctionBlock = true
const { maxStackSize } = compile(body, indexTable, true)
const functionIndex = functionAddress[0]
updateFunction(functionIndex, maxStackSize, functionCode)
functionCode = []
toplevel = false
}
}
interface EnvEntry {
index: number
isVar: boolean
type?: 'primitive' | 'internal' // for functions
}
// extracts all name declarations within a function or block,
// renaming every declaration if rename is true.
// if rename is true, rename to name_line_col and recursively rename identifiers in ast if no same scope declaration
// (check for variable, function declaration in each block. Check for params in each function call)
// for any duplicates, rename recursively within scope
// recurse for any blocks with rename = true
function extractAndRenameNames(
baseNode: es.BlockStatement | es.Program,
names: Map<string, EnvEntry>,
rename: boolean = true
) {
// get all declared names of current scope and keep track of names to rename
const namesToRename = new Map<string, string>()
for (const stmt of baseNode.body) {
if (stmt.type === 'VariableDeclaration') {
const node = stmt as es.VariableDeclaration
let name = (node.declarations[0].id as es.Identifier).name
if (rename) {
const loc = (node.loc ?? UNKNOWN_LOCATION).start
const oldName = name
do {
name = `${name}-${loc.line}-${loc.column}`
} while (names.has(name))
namesToRename.set(oldName, name)
}
const isVar = node.kind === 'let'
const index = names.size
names.set(name, { index, isVar })
} else if (stmt.type === 'FunctionDeclaration') {
const node = stmt
if (node.id === null) {
throw new Error(
'Encountered a FunctionDeclaration node without an identifier. This should have been caught when parsing.'
)
}
let name = node.id.name
if (rename) {
const loc = (node.loc ?? UNKNOWN_LOCATION).start
const oldName = name
do {
name = `${name}-${loc.line}-${loc.column}`
} while (names.has(name))
namesToRename.set(oldName, name)
}
const isVar = false
const index = names.size
names.set(name, { index, isVar })
}
}
// rename all references within blocks if nested block does not redeclare name
renameVariables(baseNode, namesToRename)
// recurse for blocks. Need to manually add all cases to recurse
for (const stmt of baseNode.body) {
if (stmt.type === 'BlockStatement') {
const node = stmt as es.BlockStatement
extractAndRenameNames(node, names, true)
}
if (stmt.type === 'IfStatement') {
let nextAlt = stmt as es.IfStatement | es.BlockStatement
while (nextAlt.type === 'IfStatement') {
// if else if...
const { consequent, alternate } = nextAlt as es.IfStatement
extractAndRenameNames(consequent as es.BlockStatement, names, true)
// Source spec must have alternate
nextAlt = alternate as es.IfStatement | es.BlockStatement
}
extractAndRenameNames(nextAlt as es.BlockStatement, names, true)
}
if (stmt.type === 'WhileStatement') {
extractAndRenameNames(stmt.body as es.BlockStatement, names, true)
}
}
return names
}
// rename variables if nested scope does not redeclare names
// redeclaration occurs on VariableDeclaration and FunctionDeclaration
function renameVariables(
baseNode: es.BlockStatement | es.Program,
namesToRename: Map<string, string>
) {
if (namesToRename.size === 0) return
let baseScope = true
function recurseBlock(
node: es.BlockStatement,
inactive: Set<string>,
c: (node: es.Node, state: Set<string>) => void
) {
// get names in current scope
const locals = getLocalsInScope(node)
// add names to state
const oldActive = new Set(inactive)
for (const name of locals) {
inactive.add(name)
}
// recurse
for (const stmt of node.body) {
c(stmt, inactive)
}
// reset state to normal
for (const name of locals) {
if (oldActive.has(name)) {
continue
}
inactive.delete(name) // delete if not in old scope
}
}
recursive(baseNode, new Set<string>(), {
VariablePattern(node: es.Identifier, inactive, _c) {
// for declarations
const name = node.name
if (inactive.has(name)) {
return
}
if (namesToRename.has(name)) {
node.name = namesToRename.get(name)!
}
},
Identifier(node: es.Identifier, inactive, _c) {
// for lone references
const name = node.name
if (inactive.has(name)) {
return
}
if (namesToRename.has(name)) {
node.name = namesToRename.get(name)!
}
},
BlockStatement(node: es.BlockStatement, inactive, c) {
if (baseScope) {
baseScope = false
for (const stmt of node.body) {
c(stmt, inactive)
}
} else {
recurseBlock(node, inactive, c)
}
},
IfStatement(node: es.IfStatement, inactive, c) {
c(node.test, inactive)
let nextAlt = node as es.IfStatement | es.BlockStatement
while (nextAlt.type === 'IfStatement') {
const { consequent, alternate } = nextAlt
recurseBlock(consequent as es.BlockStatement, inactive, c)
c(nextAlt.test, inactive)
nextAlt = alternate as es.IfStatement | es.BlockStatement
}
recurseBlock(nextAlt! as es.BlockStatement, inactive, c)
},
Function(node: es.Function, inactive, c) {
if (node.type === 'FunctionDeclaration') {
if (node.id === null) {
throw new Error(
'Encountered a FunctionDeclaration node without an identifier. This should have been caught when parsing.'
)
}
c(node.id, inactive)
}
const oldActive = new Set(inactive)
const locals = new Set<string>()
for (const param of node.params) {
const id = param as es.Identifier
locals.add(id.name)
}
for (const name of locals) {
inactive.add(name)
}
c(
node.body,
inactive,
node.type === 'ArrowFunctionExpression' && node.expression ? 'Expression' : 'Statement'
)
for (const name of locals) {
if (oldActive.has(name)) {
continue
}
inactive.delete(name) // delete if not in old scope
}
},
WhileStatement(node: es.WhileStatement, inactive, c) {
c(node.test, inactive)
recurseBlock(node.body as es.BlockStatement, inactive, c)
}
})
}
function getLocalsInScope(node: es.BlockStatement | es.Program) {
const locals = new Set<string>()
for (const stmt of node.body) {
if (stmt.type === 'VariableDeclaration') {
const name = (stmt.declarations[0].id as es.Identifier).name
locals.add(name)
} else if (stmt.type === 'FunctionDeclaration') {
if (stmt.id === null) {
throw new Error(
'Encountered a FunctionDeclaration node without an identifier. This should have been caught when parsing.'
)
}
const name = stmt.id.name
locals.add(name)
}
}
return locals
}
function compileArguments(exprs: es.Node[], indexTable: Map<string, EnvEntry>[]) {
let maxStackSize = 0
for (let i = 0; i < exprs.length; i++) {
const { maxStackSize: curExpSize } = compile(exprs[i], indexTable, false)
maxStackSize = Math.max(i + curExpSize, maxStackSize)
}
return maxStackSize
}
// tuple of loop type, breaks, continues and continueDestinationIndex
// break and continue need to know how much to offset for the branch
// instruction. When compiling the individual instruction, that info
// is not available, so need to keep track of the break and continue
// instruction's index to update the offset when the compiler finishes
// compiling the loop. We need to keep track of continue destination as
// a for loop needs to know where the assignment instructions are.
// This works because of the way a for loop is transformed to a while loop.
// If the loop is a for loop, the last statement in the while loop block
// is always the assignment expression
let loopTracker: ['for' | 'while', number[], number[], number][] = []
const LOOP_TYPE = 0
const BREAK_INDEX = 1
const CONT_INDEX = 2
const CONT_DEST_INDEX = 3
type taggedWhileStatement = es.WhileStatement & { isFor?: boolean }
// tag loop blocks when compiling. Untagged (i.e. undefined) would mean
// the block is not a loop block.
// for loop blocks, need to ensure the last statement is also popped to prevent
// stack overflow. also note that compileStatements for loop blocks will always
// have insertFlag: false
// need to detect function blocks due to compilation issues with empty blocks.
// compiler does not know when to return
type taggedBlockStatement = (es.Program | es.BlockStatement) & {
isLoopBlock?: boolean
isFunctionBlock?: boolean
}
// used to compile block bodies
function compileStatements(
node: taggedBlockStatement,
indexTable: Map<string, EnvEntry>[],
insertFlag: boolean
) {
const statements = node.body
let maxStackSize = 0
for (let i = 0; i < statements.length; i++) {
if (
node.isLoopBlock &&
i === statements.length - 1 &&
loopTracker[loopTracker.length - 1][LOOP_TYPE] === 'for'
) {
loopTracker[loopTracker.length - 1][CONT_DEST_INDEX] = functionCode.length
}
const { maxStackSize: curExprSize } = compile(
statements[i],
indexTable,
i === statements.length - 1 ? insertFlag : false
)
if (i !== statements.length - 1 || node.isLoopBlock) {
addNullaryInstruction(OpCodes.POPG)
}
maxStackSize = Math.max(maxStackSize, curExprSize)
}
if (statements.length === 0 && !node.isLoopBlock) {
addNullaryInstruction(OpCodes.LGCU)
if (insertFlag || node.isFunctionBlock) {
addNullaryInstruction(OpCodes.RETG)
}
maxStackSize++
}
return { maxStackSize, insertFlag: false }
}
// each compiler should return a maxStackSize
const compilers = {
// wrapper
Program(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.Program
return compileStatements(node, indexTable, insertFlag)
},
// wrapper
BlockStatement(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.BlockStatement
return compileStatements(node, indexTable, insertFlag)
},
// wrapper
ExpressionStatement(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.ExpressionStatement
return compile(node.expression, indexTable, insertFlag)
},
IfStatement(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
const { test, consequent, alternate } = node as es.IfStatement
const { maxStackSize: m1 } = compile(test, indexTable, false)
addUnaryInstruction(OpCodes.BRF, NaN)
const BRFIndex = functionCode.length - 1
const { maxStackSize: m2 } = compile(consequent, indexTable, false)
addUnaryInstruction(OpCodes.BR, NaN)
const BRIndex = functionCode.length - 1
functionCode[BRFIndex][1] = functionCode.length - BRFIndex
// source spec: must have alternate
const { maxStackSize: m3 } = compile(alternate!, indexTable, false)
functionCode[BRIndex][1] = functionCode.length - BRIndex
const maxStackSize = Math.max(m1, m2, m3)
return { maxStackSize, insertFlag }
},
// wrapper, compile as an arrow function expression instead
FunctionDeclaration(
node: es.FunctionDeclaration,
indexTable: Map<string, EnvEntry>[],
insertFlag: boolean
) {
if (node.id === null) {
throw new Error(
'Encountered a FunctionDeclaration node without an identifier. This should have been caught when parsing.'
)
}
return compile(
create.constantDeclaration(
node.id.name,
create.arrowFunctionExpression(node.params, node.body)
),
indexTable,
insertFlag
)
},
VariableDeclaration(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
// only supports const / let
node = node as es.VariableDeclaration
if (node.kind === 'const' || node.kind === 'let') {
// assumes left side can only be name
// source spec: only 1 declaration at a time
const id = node.declarations[0].id as es.Identifier
const { envLevel, index } = indexOf(indexTable, id)
const { maxStackSize } = compile(
node.declarations[0].init as es.Expression,
indexTable,
false
)
if (envLevel === 0) {
addUnaryInstruction(OpCodes.STLG, index)
} else {
// this should never happen
addBinaryInstruction(OpCodes.STPG, index, envLevel)
}
addNullaryInstruction(OpCodes.LGCU)
return { maxStackSize, insertFlag }
}
throw Error('Invalid declaration')
},
// handled by insertFlag in compile function
ReturnStatement(node: es.Node, indexTable: Map<string, EnvEntry>[], _insertFlag: boolean) {
node = node as es.ReturnStatement
if (loopTracker.length > 0) {
throw Error('return not allowed in loops')
}
const { maxStackSize } = compile(node.argument as es.Expression, indexTable, false, true)
return { maxStackSize, insertFlag: true }
},
// Three types of calls, normal function calls declared by the Source program,
// primitive function calls that are predefined, and internal calls.
// We differentiate them with callType.
CallExpression(
node: es.Node,
indexTable: Map<string, EnvEntry>[],
insertFlag: boolean,
isTailCallPosition: boolean = false
) {
node = node as es.CallExpression
let maxStackOperator = 0
let callType: 'normal' | 'primitive' | 'internal' = 'normal'
let callValue: any = NaN
if (node.callee.type === 'Identifier') {
const callee = node.callee as es.Identifier
const { envLevel, index, type } = indexOf(indexTable, callee)
if (type === 'primitive' || type === 'internal') {
callType = type
callValue = index
} else if (envLevel === 0) {
addUnaryInstruction(OpCodes.LDLG, index)
} else {
addBinaryInstruction(OpCodes.LDPG, index, envLevel)
}
} else {
;({ maxStackSize: maxStackOperator } = compile(node.callee, indexTable, false))
}
let maxStackOperands = compileArguments(node.arguments, indexTable)
if (callType === 'primitive') {
addBinaryInstruction(
isTailCallPosition ? OpCodes.CALLTP : OpCodes.CALLP,
callValue,
node.arguments.length
)
} else if (callType === 'internal') {
addBinaryInstruction(
isTailCallPosition ? OpCodes.CALLTV : OpCodes.CALLV,
callValue,
node.arguments.length
)
} else {
// normal call. only normal function calls have the function on the stack
addUnaryInstruction(isTailCallPosition ? OpCodes.CALLT : OpCodes.CALL, node.arguments.length)
maxStackOperands++
}
// need at least 1 stack slot for the return value!
return { maxStackSize: Math.max(maxStackOperator, maxStackOperands, 1), insertFlag }
},
UnaryExpression(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.UnaryExpression
if (VALID_UNARY_OPERATORS.has(node.operator)) {
const opCode = VALID_UNARY_OPERATORS.get(node.operator) as number
const { maxStackSize } = compile(node.argument, indexTable, false)
addNullaryInstruction(opCode)
return { maxStackSize, insertFlag }
}
throw Error('Unsupported operation')
},
BinaryExpression(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.BinaryExpression
if (VALID_BINARY_OPERATORS.has(node.operator)) {
const opCode = VALID_BINARY_OPERATORS.get(node.operator) as number
const { maxStackSize: m1 } = compile(node.left, indexTable, false)
const { maxStackSize: m2 } = compile(node.right, indexTable, false)
addNullaryInstruction(opCode)
return { maxStackSize: Math.max(m1, 1 + m2), insertFlag }
}
throw Error('Unsupported operation')
},
// convert logical expressions to conditional expressions
LogicalExpression(
node: es.Node,
indexTable: Map<string, EnvEntry>[],
insertFlag: boolean,
isTailCallPosition: boolean = false
) {
node = node as es.LogicalExpression
if (node.operator === '&&') {
const { maxStackSize } = compile(
create.conditionalExpression(node.left, node.right, create.literal(false)),
indexTable,
false,
isTailCallPosition
)
return { maxStackSize, insertFlag }
} else if (node.operator === '||') {
const { maxStackSize } = compile(
create.conditionalExpression(node.left, create.literal(true), node.right),
indexTable,
false,
isTailCallPosition
)
return { maxStackSize, insertFlag }
}
throw Error('Unsupported operation')
},
ConditionalExpression(
node: es.Node,
indexTable: Map<string, EnvEntry>[],
insertFlag: boolean,
isTailCallPosition: boolean = false
) {
const { test, consequent, alternate } = node as es.ConditionalExpression
const { maxStackSize: m1 } = compile(test, indexTable, false)
addUnaryInstruction(OpCodes.BRF, NaN)
const BRFIndex = functionCode.length - 1
const { maxStackSize: m2 } = compile(consequent, indexTable, insertFlag, isTailCallPosition)
let BRIndex = NaN
if (!insertFlag) {
addUnaryInstruction(OpCodes.BR, NaN)
BRIndex = functionCode.length - 1
}
functionCode[BRFIndex][1] = functionCode.length - BRFIndex
const { maxStackSize: m3 } = compile(alternate!, indexTable, insertFlag, isTailCallPosition)
if (!insertFlag) {
functionCode[BRIndex][1] = functionCode.length - BRIndex
}
const maxStackSize = Math.max(m1, m2, m3)
return { maxStackSize, insertFlag: false }
},
ArrowFunctionExpression(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.ArrowFunctionExpression
// node.body is either a block statement or a single node to return
const bodyNode =
node.body.type === 'BlockStatement'
? node.body
: create.blockStatement([create.returnStatement(node.body)])
const names = new Map<string, EnvEntry>()
for (let param of node.params) {
param = param as es.Identifier
const index = names.size
names.set(param.name, { index, isVar: true })
}
extractAndRenameNames(bodyNode, names)
const extendedIndexTable = extendIndexTable(indexTable, names)
const newSVMFunction: SVMFunction = [NaN, names.size, node.params.length, []]
const functionIndex = SVMFunctions.length
SVMFunctions.push(newSVMFunction)
pushToCompile(makeToCompileTask(bodyNode, [functionIndex], extendedIndexTable))
addUnaryInstruction(OpCodes.NEWC, [functionIndex])
return { maxStackSize: 1, insertFlag }
},
Identifier(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.Identifier
let envLevel
let index
let type
try {
;({ envLevel, index, type } = indexOf(indexTable, node))
if (type === 'primitive') {
addUnaryInstruction(OpCodes.NEWCP, index)
} else if (type === 'internal') {
addUnaryInstruction(OpCodes.NEWCV, index)
} else if (envLevel === 0) {
addUnaryInstruction(OpCodes.LDLG, index)
} else {
addBinaryInstruction(OpCodes.LDPG, index, envLevel)
}
} catch (error) {
// only possible to have UndefinedVariable error
const matches = CONSTANT_PRIMITIVES.filter(f => f[0] === error.name)
if (matches.length === 0) {
throw error
}
if (typeof matches[0][1] === 'number') {
// for NaN and Infinity
addUnaryInstruction(OpCodes.LGCF32, matches[0][1])
} else if (matches[0][1] === undefined) {
addNullaryInstruction(OpCodes.LGCU)
} else {
throw Error('Unknown primitive constant')
}
}
return { maxStackSize: 1, insertFlag }
},
// string, boolean, number or null
Literal(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.Literal
const value = node.value
if (value === null) {
addNullaryInstruction(OpCodes.LGCN)
} else {
switch (typeof value) {
case 'boolean':
if (value) {
addNullaryInstruction(OpCodes.LGCB1)
} else {
addNullaryInstruction(OpCodes.LGCB0)
}
break
case 'number': // need to adjust depending on target
// LGCI takes a signed 32-bit integer operand (hence the range)
if (Number.isInteger(value) && -2_147_483_648 <= value && value <= 2_147_483_647) {
addUnaryInstruction(OpCodes.LGCI, value)
} else {
addUnaryInstruction(OpCodes.LGCF64, value)
}
break
case 'string':
addUnaryInstruction(OpCodes.LGCS, value)
break
default:
throw Error('Unsupported literal')
}
}
return { maxStackSize: 1, insertFlag }
},
// array declarations
ArrayExpression(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.ArrayExpression
addNullaryInstruction(OpCodes.NEWA)
const elements = node.elements as ContiguousArrayElements
let maxStackSize = 1
for (let i = 0; i < elements.length; i++) {
// special case when element wasnt specified
// i.e. [,]. Treat as undefined element
if (elements[i] === null) {
continue
}
// keep the array in the stack
addNullaryInstruction(OpCodes.DUP)
addUnaryInstruction(OpCodes.LGCI, i)
const { maxStackSize: m1 } = compile(elements[i], indexTable, false)
addNullaryInstruction(OpCodes.STAG)
maxStackSize = Math.max(1 + 2 + m1, maxStackSize)
}
return { maxStackSize, insertFlag }
},
AssignmentExpression(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.AssignmentExpression
if (node.left.type === 'Identifier') {
const { envLevel, index, isVar } = indexOf(indexTable, node.left)
if (!isVar) {
throw new ConstAssignment(node.left, node.left.name)
}
const { maxStackSize } = compile(node.right, indexTable, false)
if (envLevel === 0) {
addUnaryInstruction(OpCodes.STLG, index)
} else {
addBinaryInstruction(OpCodes.STPG, index, envLevel)
}
addNullaryInstruction(OpCodes.LGCU)
return { maxStackSize, insertFlag }
} else if (node.left.type === 'MemberExpression' && node.left.computed === true) {
// case for array member assignment
const { maxStackSize: m1 } = compile(node.left.object, indexTable, false)
const { maxStackSize: m2 } = compile(node.left.property, indexTable, false)
const { maxStackSize: m3 } = compile(node.right, indexTable, false)
addNullaryInstruction(OpCodes.STAG)
addNullaryInstruction(OpCodes.LGCU)
return { maxStackSize: Math.max(m1, 1 + m2, 2 + m3), insertFlag }
}
// property assignments are not supported
throw Error('Invalid Assignment')
},
ForStatement(_node: es.Node, _indexTable: Map<string, EnvEntry>[], _insertFlag: boolean) {
throw Error('Unsupported operation')
},
// Loops need to have their own environment due to closures
WhileStatement(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as taggedWhileStatement
const isFor = (node as taggedWhileStatement).isFor
const condIndex = functionCode.length
const { maxStackSize: m1 } = compile(node.test, indexTable, false)
addUnaryInstruction(OpCodes.BRF, NaN)
const BRFIndex = functionCode.length - 1
loopTracker.push([isFor ? 'for' : 'while', [], [], NaN])
// Add environment for loop and run in new environment
const locals = extractAndRenameNames(node.body as es.BlockStatement, new Map())
addUnaryInstruction(OpCodes.NEWENV, locals.size)
const extendedIndexTable = extendIndexTable(indexTable, locals)
const body = node.body as taggedBlockStatement
body.isLoopBlock = true
const { maxStackSize: m2 } = compile(body, extendedIndexTable, false)
if (!isFor) {
// for while loops, the `continue` statement should branch here
loopTracker[loopTracker.length - 1][CONT_DEST_INDEX] = functionCode.length
}
addNullaryInstruction(OpCodes.POPENV)
const endLoopIndex = functionCode.length
addUnaryInstruction(OpCodes.BR, condIndex - endLoopIndex)
functionCode[BRFIndex][1] = functionCode.length - BRFIndex
// update BR instructions within loop
const curLoop = loopTracker.pop()!
for (const b of curLoop[BREAK_INDEX]) {
functionCode[b][1] = functionCode.length - b
}
for (const c of curLoop[CONT_INDEX]) {
functionCode[c][1] = curLoop[CONT_DEST_INDEX] - c
}
addNullaryInstruction(OpCodes.LGCU)
return { maxStackSize: Math.max(m1, m2), insertFlag }
},
BreakStatement(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
// keep track of break instruction
addNullaryInstruction(OpCodes.POPENV)
loopTracker[loopTracker.length - 1][BREAK_INDEX].push(functionCode.length)
addUnaryInstruction(OpCodes.BR, NaN)
return { maxStackSize: 0, insertFlag }
},
ContinueStatement(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
// keep track of continue instruction
// no need to POPENV as continue will go to the end of the while loop
loopTracker[loopTracker.length - 1][CONT_INDEX].push(functionCode.length)
addUnaryInstruction(OpCodes.BR, NaN)
return { maxStackSize: 0, insertFlag }
},
ObjectExpression(_node: es.Node, _indexTable: Map<string, EnvEntry>[], _insertFlag: boolean) {
throw Error('Unsupported operation')
},
MemberExpression(node: es.Node, indexTable: Map<string, EnvEntry>[], insertFlag: boolean) {
node = node as es.MemberExpression
if (node.computed) {
const { maxStackSize: m1 } = compile(node.object, indexTable, false)
const { maxStackSize: m2 } = compile(node.property, indexTable, false)
addNullaryInstruction(OpCodes.LDAG)
return { maxStackSize: Math.max(m1, 1 + m2), insertFlag }
}
// properties are not supported
throw Error('Unsupported operation')
},
Property(_node: es.Node, _indexTable: Map<string, EnvEntry>[], _insertFlag: boolean) {
throw Error('Unsupported operation')
},
DebuggerStatement(_node: es.Node, _indexTable: Map<string, EnvEntry>[], _insertFlag: boolean) {
throw Error('Unsupported operation')
}
}
function compile(
expr: es.Node,
indexTable: Map<string, EnvEntry>[],
insertFlag: boolean,
isTailCallPosition: boolean = false
) {
const compiler = compilers[expr.type]
if (!compiler) {
throw Error('Unsupported operation')
}
const { maxStackSize: temp, insertFlag: newInsertFlag } = compiler(
expr,
indexTable,
insertFlag,
isTailCallPosition
)
let maxStackSize = temp
// insertFlag decides whether we need to introduce a RETG instruction. For some functions
// where return is not specified, there is an implicit "return undefined", which we do here.
// Source programs should return the last evaluated statement, which is what toplevel handles.
// TODO: Don't emit an unnecessary RETG after a tail call. (This is harmless, but wastes an instruction.)
// (There are unnecessary RETG for many cases at the top level)
// TODO: Source programs should return last evaluated statement.
if (newInsertFlag) {
if (expr.type === 'ReturnStatement') {
addNullaryInstruction(OpCodes.RETG)
} else if (toplevel && toplevelReturnNodes.has(expr.type)) {
// conditional expressions already handled
addNullaryInstruction(OpCodes.RETG)
} else if (
expr.type === 'Program' ||
expr.type === 'ExpressionStatement' ||
expr.type === 'BlockStatement' ||
expr.type === 'FunctionDeclaration'
) {
// do nothing for wrapper nodes
} else {
maxStackSize += 1
addNullaryInstruction(OpCodes.LGCU)
addNullaryInstruction(OpCodes.RETG)
}
}
return { maxStackSize, insertFlag: newInsertFlag }
}
export function compileForConcurrent(program: es.Program, context: Context) {
// assume vmPrelude is always a correct program
const prelude = compilePreludeToIns(parse(vmPrelude, context)!)
generatePrimitiveFunctionCode(prelude)
const vmInternalFunctions = INTERNAL_FUNCTIONS.map(([name]) => name)
return compileToIns(program, prelude, vmInternalFunctions)
}
export function compilePreludeToIns(program: es.Program): Program {
// reset variables
SVMFunctions = []
functionCode = []
toCompile = []
loopTracker = []
toplevel = true
transformForLoopsToWhileLoops(program)
// don't rename names at the top level, because we need them for linking
const locals = extractAndRenameNames(program, new Map<string, EnvEntry>(), false)
const topFunction: SVMFunction = [NaN, locals.size, 0, []]
const topFunctionIndex = 0 // GE + # primitive func
SVMFunctions[topFunctionIndex] = topFunction
const extendedTable = extendIndexTable(makeIndexTableWithPrimitivesAndInternals(), locals)
pushToCompile(makeToCompileTask(program, [topFunctionIndex], extendedTable))
continueToCompile()
return [0, SVMFunctions]
}
export function compileToIns(
program: es.Program,
prelude?: Program,
vmInternalFunctions?: string[]
): Program {
// reset variables
SVMFunctions = []
functionCode = []
toCompile = []
loopTracker = []
toplevel = true
transformForLoopsToWhileLoops(program)
insertEmptyElseBlocks(program)
const locals = extractAndRenameNames(program, new Map<string, EnvEntry>())
const topFunction: SVMFunction = [NaN, locals.size, 0, []]
if (prelude) {
SVMFunctions.push(...prelude[1])
}
const topFunctionIndex = prelude ? PRIMITIVE_FUNCTION_NAMES.length + 1 : 0 // GE + # primitive func
SVMFunctions[topFunctionIndex] = topFunction
const extendedTable = extendIndexTable(
makeIndexTableWithPrimitivesAndInternals(vmInternalFunctions),
locals
)
pushToCompile(makeToCompileTask(program, [topFunctionIndex], extendedTable))
continueToCompile()
return [0, SVMFunctions]
}
// transform according to Source 3 spec. Refer to spec for the way of transformation
function transformForLoopsToWhileLoops(program: es.Program) {
simple(program, {
ForStatement(node) {
const { test, body, init, update } = node as es.ForStatement
let forLoopBody = body
// Source spec: init must be present
if (init!.type === 'VariableDeclaration') {
const loopVarName = ((init as es.VariableDeclaration).declarations[0].id as es.Identifier)
.name
// loc is used for renaming. It doesn't matter if we use the same location, as the
// renaming function will notice that they are the same, and rename it further so that
// there aren't any clashes.
const loc = init!.loc
const copyOfLoopVarName = 'copy-of-' + loopVarName
const innerBlock = create.blockStatement([
create.constantDeclaration(loopVarName, create.identifier(copyOfLoopVarName), loc),
body
])
forLoopBody = create.blockStatement([
create.constantDeclaration(copyOfLoopVarName, create.identifier(loopVarName), loc),
innerBlock
])
}
const assignment1 =
init && init.type === 'VariableDeclaration'
? init
: create.expressionStatement(init as es.Expression)
const assignment2 = create.expressionStatement(update!)
const newLoopBody = create.blockStatement([forLoopBody, assignment2])
const newLoop = create.whileStatement(newLoopBody, test!) as taggedWhileStatement
newLoop.isFor = true
const newBlockBody = [assignment1, newLoop]
node = node as es.BlockStatement
node.body = newBlockBody
node.type = 'BlockStatement'
}
})
}
function insertEmptyElseBlocks(program: es.Program) {
simple(program, {
IfStatement(node: es.IfStatement) {
node.alternate ??= {
type: 'BlockStatement',
body: []
}
}
})
}
|
a9c04bfb276df7b66d5a1e43b82ac79d91be9e41
|
TypeScript
|
elprotto/Angular101
|
/1. TypeScript and OOP/Examples/Example 3 - Types/Number.ts
| 3.203125
| 3
|
let first: number = 123; // number
let second: number = 0x37cf; // hexadecimal
let third: number = 0o377; // octal
let fourth: number = 0b111001; // binary
console.log(first); // 123
console.log(second); // 14287
console.log(third); // 255
console.log(fourth); // 57
|
bf3aa7cb929daed93ed567294668b0fb96e6707e
|
TypeScript
|
pitust/ts2c
|
/tests/numbers/numbers2.ts
| 2.703125
| 3
|
var n1 = parseInt('3');
console.log(n1);
var n2 = parseInt('2342');
console.log(n2);
var n3 = parseInt(' 3');
console.log(n3);
var n4 = parseInt(' 1212');
console.log(n4);
var n5 = parseInt(' 3 wew');
console.log(n5);
var n6 = parseInt(' 902 wew');
console.log(n6);
var n7 = parseInt(' 12 3 wew');
console.log(n7);
|
5e69fe4f1940ac256ab839fffd618ea8ac6210b3
|
TypeScript
|
dazejs/daze
|
/packages/framework/__tests__/src/container/index.spec.ts
| 2.828125
| 3
|
import 'reflect-metadata';
import { Container, Injectable } from '../../../src';
import * as symbols from '../../../src/symbol';
it('Container.setInstance', () => {
const App = class { };
Container.setInstance(App);
expect(Container.instance).toBe(App);
});
it('Container.bind and Container.get', () => {
Container.setInstance(null);
const App = class { };
Container.bind(App, App);
Container.bind('a', null);
expect(Container.get('a')).toBeUndefined();
expect(Container.get(App)).toBeInstanceOf(App);
});
it('Container.has', () => {
Container.setInstance(null);
const App = class { };
const Non = class { };
Container.bind(App, App);
expect(Container.has(App)).toBeTruthy();
expect(Container.has(Non)).toBeFalsy();
});
it('Container#bound', () => {
Container.setInstance(null);
const App = class { };
const Non = class { };
const ContainerInstance = new Container();
ContainerInstance.singleton(App, App);
expect(ContainerInstance.bound(App)).toBeTruthy();
expect(ContainerInstance.bound(Non)).toBeFalsy();
});
it('Container#exists', () => {
Container.setInstance(null);
const App = class { };
const AppInstance = new App();
const ContainerInstance = new Container();
ContainerInstance.singleton(AppInstance, AppInstance);
expect(ContainerInstance.exists(AppInstance)).toBeTruthy();
});
it('Container.get', () => {
Container.setInstance(null);
const fn = () => {
//
};
const App = class {};
// shared
Container.bind('a', App, true);
expect(Container.get('a')).toBe(Container.get('a'));
// not shared
Container.bind('b', App, false);
expect(Container.get('b')).not.toBe(Container.get('b'));
Container.bind('c', fn);
Container.bind('d', fn);
Container.bind('e', fn);
Container.bind('f', fn);
});
it('singleton and multiton', () => {
Container.setInstance(null);
const Singleton = class { };
const Multiton = class { };
const normalFun = () => {
//
};
const ContainerInstance = new Container();
ContainerInstance.singleton(Singleton, Singleton);
ContainerInstance.multiton(Multiton, Multiton);
ContainerInstance.multiton(normalFun, normalFun);
expect(ContainerInstance.isShared(Singleton)).toBeTruthy();
expect(ContainerInstance.isShared(Multiton)).toBeFalsy();
});
it('instance replace', () => {
class App extends Container { }
Container.setInstance(App);
const app = new App();
app.singleton('app', App);
expect(app.make('app')).toBeInstanceOf(App);
Container.instance = null;
});
it('Container#callable', () => {
const callableFn = () => 'callable';
Container.bind('callable', callableFn, false, true);
expect(Container.get('callable')).toBe('callable');
});
it('Container inject class', () => {
@Injectable
class App {
param: any;
prop: any;
constructor(param: any) {
this.param = param;
this.prop = '';
}
index(param: any) {
return param;
}
}
Container.bind(App, App);
Container.bind('request', (r: any) => r, false, true);
Reflect.defineMetadata(symbols.INJECTTYPE_METADATA, [
{
abstract: 'request',
params: ['request']
}
], App);
Reflect.defineMetadata(symbols.INJECTTYPE_METADATA, [
{
abstract: 'request',
params: ['request']
}
], App, 'prop');
Reflect.defineMetadata(symbols.INJECTTYPE_METADATA, [
{
abstract: 'request',
params: ['request']
}
], App, 'index');
const app = Container.get(App);
expect(app.param).toBe('request');
expect(app.index()).toBe('request');
expect(app.prop).toBe('request');
});
|
798f42218de1b6b0a124596eaf7a08e2d3053f87
|
TypeScript
|
MatthiasKunnen/TypedJSON
|
/spec/any.spec.ts
| 3.109375
| 3
|
import {AnyT, jsonArrayMember, jsonMember, jsonObject, jsonSetMember, TypedJSON} from '../src';
describe('AnyT', () => {
describe('on a simple class property', () => {
@jsonObject
class SimplePropertyAny {
@jsonMember(AnyT)
any: any;
@jsonMember(AnyT)
anyNullable?: any | null;
}
it('should deserialize simple object correctly', () => {
const result = TypedJSON.parse({
any: {foo: 'bar'},
anyNullable: {foo: 'bar'},
}, SimplePropertyAny);
expect(result.any).toHaveProperties(['foo']);
expect(result.anyNullable).toHaveProperties(['foo']);
});
it('should deserialize class instance correctly', () => {
const foo = {foo: 'bar'};
const result = TypedJSON.parse({
any: foo,
anyNullable: foo,
}, SimplePropertyAny);
expect(result.any).toEqual(foo);
expect(result.anyNullable).toEqual(foo);
});
it('should serialize with referential equality', () => {
const foo = {foo: 'bar'};
const simplePropertyAny = new SimplePropertyAny();
simplePropertyAny.any = foo;
simplePropertyAny.anyNullable = foo;
const result: any = TypedJSON.toPlainJson(simplePropertyAny, SimplePropertyAny);
expect(result.any).toEqual(foo);
expect(result.anyNullable).toEqual(foo);
});
});
describe('on arrays', () => {
@jsonObject
class ArrayPropertyAny {
@jsonArrayMember(AnyT)
any: Array<any>;
@jsonArrayMember(AnyT)
anyNullable?: Array<any> | null;
}
it('should deserialize simple object correctly', () => {
const result = TypedJSON.parse({
any: [{foo: 'bar'}],
anyNullable: [{foo: 'bar'}],
}, ArrayPropertyAny);
expect(result.any).toBeInstanceOf(Array);
expect(result.any[0].foo).toEqual('bar');
expect(result.anyNullable).toBeInstanceOf(Array);
expect(result.anyNullable[0].foo).toEqual('bar');
});
it('should deserialize class instance correctly', () => {
const foo = {foo: 'bar'};
const result = TypedJSON.parse({
any: [foo],
anyNullable: [foo],
}, ArrayPropertyAny);
expect(result.any).toBeInstanceOf(Array);
expect(result.any[0]).toEqual(foo);
expect(result.anyNullable).toBeInstanceOf(Array);
expect(result.anyNullable[0]).toEqual(foo);
});
it('should serialize with referential equality', () => {
const foo = {foo: 'bar'};
const arrayPropertyAny = new ArrayPropertyAny();
arrayPropertyAny.any = [foo];
arrayPropertyAny.anyNullable = [foo];
const result: any = TypedJSON.toPlainJson(arrayPropertyAny, ArrayPropertyAny);
expect(result.any[0]).toEqual(foo);
expect(result.anyNullable[0]).toEqual(foo);
});
});
describe('on set', () => {
@jsonObject
class SetPropertyAny {
@jsonSetMember(AnyT)
any: Set<any>;
@jsonSetMember(AnyT)
anyNullable?: Set<any> | null;
}
it('should deserialize simple object correctly', () => {
const foo = {foo: 'bar'};
const result = TypedJSON.parse({
any: [foo, foo],
anyNullable: [foo, foo],
}, SetPropertyAny);
expect(result.any).toBeInstanceOf(Set);
expect(result.any.size).toBe(1);
expect(result.any.values().next().value).toEqual(foo);
expect(result.anyNullable).toBeInstanceOf(Set);
expect(result.anyNullable.size).toBe(1);
expect(result.anyNullable.values().next().value).toEqual(foo);
});
it('should deserialize with referential equality', () => {
const foo = {foo: 'bar'};
const result = TypedJSON.parse({
any: [foo, foo],
anyNullable: [foo, foo],
}, SetPropertyAny);
expect(result.any).toBeInstanceOf(Set);
expect(result.any.values().next().value).toBe(foo);
expect(result.anyNullable).toBeInstanceOf(Set);
expect(result.anyNullable.values().next().value).toBe(foo);
});
it('should serialize with referential equality', () => {
const foo = {foo: 'bar'};
const setPropertyAny = new SetPropertyAny();
setPropertyAny.any = new Set([foo, foo]);
setPropertyAny.anyNullable = new Set([foo, foo]);
const result: any = TypedJSON.toPlainJson(setPropertyAny, SetPropertyAny);
expect(result.any.values().next().value).toEqual(foo);
expect(result.anyNullable.values().next().value).toEqual(foo);
});
});
it('should handle complex structures', () => {
@jsonObject
class Event {
@jsonMember(AnyT)
data?: {[k: string]: any} | null;
}
@jsonObject
class A {
@jsonArrayMember(Event)
events: Array<Event>
}
const result = TypedJSON.parse({
events: [
{
data: {
files: [
{
name: 'file1',
},
],
},
},
],
}, A);
expect(result.events[0].data.files[0].name).toEqual('file1');
});
});
|
22b14bcdbe2fbe48f7924af769aba3bdbc32aab4
|
TypeScript
|
ColMarek/Sozui
|
/src/core.ts
| 2.78125
| 3
|
import * as discordUtils from "./utils/discord";
import * as anilist from "./anilist";
import { Media, MediaType } from "./models/Media";
import { Logger } from "./utils/Logger";
const logger = new Logger();
if (require.main == module) {
parseMessage(":{Black Clover}: and :<<Black Clover>>:").catch(e => console.log(e));
}
export interface SearchArg {
title: string;
extended: boolean;
type: MediaType
}
export function extractArgs(content: string): SearchArg[] {
const args: SearchArg[] = [];
content.match(discordUtils.animeExtendedRegex)?.forEach(t => {
args.push({ title: stripTags(t), extended: true, type: MediaType.ANIME });
});
content.match(discordUtils.animeRegex)?.forEach(t => {
args.push({ title: stripTags(t), extended: false, type: MediaType.ANIME });
});
content.match(discordUtils.mangaExtendedRegex)?.forEach(t => {
args.push({ title: stripTags(t), extended: true, type: MediaType.MANGA });
});
content.match(discordUtils.mangaRegex)?.forEach(t => {
args.push({ title: stripTags(t), extended: false, type: MediaType.MANGA });
});
return args;
}
export async function parseMessage(content: string): Promise<{ media: Media | undefined, arg: SearchArg }[]> {
const args = extractArgs(content);
logger.debug(`Extracted [${args.map(a => a.title).join(",")}] searches`, "parseMessage");
const result: { media: Media, arg: SearchArg }[] = [];
for (const arg of args) {
result.push({
media: (await anilist.searchMedia(arg.type, arg.title, 1))[0],
arg
});
}
return result;
}
export async function searchMedia(title: string, type: MediaType): Promise<Media[]> {
return anilist.searchMedia(type, title, 5);
}
export async function getMediaById(id: number): Promise<Media | null> {
return anilist.getMediaById(id);
}
function stripTags(query: string): string {
return query
.replace(":{{", "")
.replace("}}:", "")
.replace(":{", "")
.replace("}:", "")
.replace(":<<", "")
.replace(">>:", "")
.replace(":<", "")
.replace(">:", "");
}
|
62a47a8249c9f96ce09dd85bc76704eb148794ff
|
TypeScript
|
uiwjs/react-baidu-map
|
/packages/types/src/panorama.d.ts
| 2.828125
| 3
|
/// <reference path="./base.d.ts" />
/// <reference path="./control.d.ts" />
declare namespace BMap {
/**
* 在给定的结点中创建全景
* 此类用来展示某位置的全景视图,可以单独放置在一个div容器中,也可以放在Map类的容器中。
* http://lbsyun.baidu.com/cms/jsapi/reference/jsapi_reference_3_0.html#a8b0
*/
class Panorama {
/**
* 在给定的结点中创建全景
*/
constructor(container: string | HTMLElement, opts?: PanoramaOptions);
/**
* 获取全景中道路指示信息
*/
getLinks: () => Array<PanoramaLink>;
/**
* 获取当前全景的id
*/
getId: () => string;
/**
* 获取当前全景的位置,通过经纬度描述
*/
getPosition: () => Point;
/**
* 获取当前全景的视角
*/
getPov: () => PanoramaPov;
/**
* 获取当前全景的级别
*/
getZoom: () => Number;
/**
* 设置全景的 id
*/
setId: (id: string) => void;
/**
* 设置全景的位置
*/
setPosition: (position: Point) => void;
/**
* 设置全景的视角
*/
setPov: (pov: PanoramaPov) => void;
/**
* 设置全景的级别
*/
setZoom: (zoom: Number) => void;
/**
* 开启鼠标滚轮缩放功能。仅对PC上有效
*/
enableScrollWheelZoom: () => void;
/**
* 关闭鼠标滚轮缩放功能
*/
disableScrollWheelZoom: () => void;
/**
* 显示全景
*/
show: () => void;
/**
* 隐藏全景
*/
hide: () => void;
/**
* 全景场景内添加覆盖物
*/
addOverlay: (overlay: PanoramaLabel) => void;
/**
* 删除全景内的覆盖物
*/
removeOverlay: (overlay: PanoramaLabel) => void;
/**
* 获取全景的类型(室外景返回BMAP_PANORAMA_STREET_SCENE、室内景返回BMAP_PANORAMA_INDOOR_SCENE)
*/
getSceneType: () => PanoramaPOIType;
/**
* 设置全景可配置参数
*/
setOptions: (opts: PanoramaOptions) => void;
/**
* 设置全景外景场景点内可见的POI类型,默认为隐藏所有类型poi
*/
setPanoramaPOIType: () => PanoramaPOIType;
/**
* 全景位置发生变化时触发
*/
onposition_changed?: () => void;
/**
* 全景相邻道路发生变化时触发,通常是在位置变化时,异步获取新数据之后触发
*/
onlinks_changed?: () => void;
/**
* 全景视角发生变化时触发
*/
onpov_changed?: () => void;
/**
* 全景级别发生变化时触发
*/
onzoom_changed?: () => void;
/**
* 全景场景点类型改变(室内景、室外景)时触发
*/
onscene_type_changed?: () => void;
}
/**
* 此类为Panorama类构造函数的可选参数,使用对象字面量形式表示,不可实例化。
*/
interface PanoramaOptions {
/**
* 是否显示全景的导航控件,默认为true
*/
navigationControl: boolean;
/**
* 是否显示道路指示控件。默认为true
*/
linksControl: boolean;
/**
* 是否显示全景室内场景的切换控件,默认为false,仅对室内景生效
*/
indoorSceneSwitchControl: boolean;
/**
* 是否显示相册控件,默认为false
*/
albumsControl: boolean;
/**
* 全景相册控件配置参数
*/
albumsControlOptions: AlbumsControlOptions;
}
interface PanoramaLink {
/**
* 相连全景的描述信息
*/
description: string;
/**
* 相连道路的方向,正北方向为0,正东为90,正南为180,正西为270
*/
heading: string;
/**
* 相邻全景的id
*/
id: string;
}
interface PanoramaPov {
/**
* 水平方向的角度,正北方向为0,正东为90,正南为180,正西为270
*/
heading: number;
/**
* 竖直方向的角度,向上最大到90度,向下最大到-90度。(在某些场景下,俯角可能无法到达最大值)
*/
pitch: number;
}
/**
* 此类用来检索全景数据信息。
*/
class PanoramaService {
/**
* 在创建检索全景数据信息类的实例
*/
constructor();
/**
* 根据全景id返回全景数据,当获取不到数据时,回调函数参数为null
*/
getPanoramaById(id: string, callback: (data: PanoramaData) => void): void;
/**
* 根据坐标及半径返回该范围内的全景数据;
* 不设置半径参数时,默认半径为50米;当获取不到数据时,回调函数参数为null
*/
getPanoramaByLocation(point: Point, radius?: number, callback?: (data: PanoramaData) => void): void;
}
interface PanoramaData {
id: string;
description: string;
links: PanoramaLink[];
position: Point;
tiles: PanoramaTileData;
}
interface PanoramaTileData {
centerHeading: number;
tileSize: Size;
worldSize: Size;
}
/**
* 该类提供在全景中添加标签功能。
*/
class PanoramaLabel {
constructor(content: string, opts?: PanoramaLabelOptions);
/**
* 设置标签的经纬度坐标
*/
setPosition?: (position: Point) => void;
/**
* 获取标签的经纬度坐标
*/
getPosition?: () => Point;
/**
* 获取标签与全景中心点的视角
*/
getPov?: () => PanoramaPov;
/**
* 设置标签显示内容
*/
setContent?: (content: String) => void;
/**
* 获取标签的显示内容
*/
getContent?: () => string;
/**
* 设置标签可见
*/
show?: () => void;
/**
* 设置标签不可见
*/
hide?: () => void;
/**
* 设置标签距离地面的高度
*/
setAltitude?: (altitude: number) => void;
/**
* 获取标签距离地面的高度
*/
getAltitude?: () => number;
/**
* 注册事件
*/
addEventListener?: () => void;
/**
* 移除事件
*/
removeEventListener?: () => void;
onclick: (event: { type: string; target: any }) => void;
onmouseover: (event: { type: string; target: any }) => void;
onmouseout: (event: { type: string; target: any }) => void;
onremove: (event: { type: string; target: any }) => void;
}
interface PanoramaLabelOptions {
/**
* 文本标注的地理位置
*/
position?: Point;
/**
* 文本标注在全景场景点中距地面的高度。(javascript全景实现方式暂不支持),默认为2米
*/
altitude?: number;
}
interface AlbumsControlOptions {
/**
* 相册控件的停靠位置
*/
anchor?: ControlAnchor;
/**
* 相册的偏移量
*/
offset?: Size;
/**
* 相册控件的最大宽度,可以设置总宽度百分比(例如50%) 或者像素数字(500),默认值为100%
*/
maxWidth?: number | string;
/**
* 相册内图片的高度。默认为 80px。(为保证图片比例,只设置高度,宽度自如会拉宽)
*/
imageHeight?: number;
}
type PanoramaSceneType = string;
type PanoramaPOIType = string;
}
/**
* 全景场景点的类型为室内场景
*/
declare const BMAP_PANORAMA_INDOOR_SCENE: string;
/**
* 全景场景点的类型为室外场景
*/
declare const BMAP_PANORAMA_STREET_SCENE: string;
declare const BMAP_PANORAMA_POI_HOTEL: string;
declare const BMAP_PANORAMA_POI_CATERING: string;
declare const BMAP_PANORAMA_POI_MOVIE: string;
declare const BMAP_PANORAMA_POI_TRANSIT: string;
declare const BMAP_PANORAMA_POI_INDOOR_SCENE: string;
declare const BMAP_PANORAMA_POI_NONE: string;
|
31dced08e0eb24ed59a6e96578463e6233966b62
|
TypeScript
|
CaoMeiYouRen/node-cq-robot
|
/dist/utils/timeHelp.d.ts
| 3.140625
| 3
|
/**
* 格式化时间
* @export
* @param {(Date | number | string)} [date=Date.now()]
* @param {string} [pattern='YYYY-MM-DD HH:mm:ss']
* @returns {string}
*/
export declare function timeFormat(date?: Date | number | string, pattern?: string): string;
/**
*
* 在控制台输出 HH:mm:ss:SSS->msg 格式的消息
* @export
* @param {string} msg
* @param {number} [level=0]
*/
export declare function printTime(msg: string, level?: number): void;
|
69208d0a39658663b083c16c9f1589d6b4e90d12
|
TypeScript
|
olaoluwa-98/indicative-compiler
|
/test/ast-walker.spec.ts
| 2.546875
| 3
|
/**
* indicative-compiler
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import * as test from 'japa'
import { TreeWalker } from '../src/TreeWalker'
import { rulesParser } from 'indicative-parser'
test.group('Tree walker', () => {
test('walk over all literal nodes', (assert) => {
const schema = {
username: 'required',
age: 'required',
}
const stack = new TreeWalker((field, type, rules, dotPath, pointer) => {
return { field, type, rules, dotPath, pointer }
}, () => {}).walk(rulesParser(schema))
assert.deepEqual(stack, [
{
field: 'username',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'username',
},
{
field: 'age',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'age',
},
])
})
test('walk over all object nodes', (assert) => {
const schema = {
'user.username': 'required',
age: 'required',
}
const stack = new TreeWalker((field, type, rules, dotPath, pointer) => {
return { field, type, rules, dotPath, pointer }
}, () => {}).walk(rulesParser(schema))
assert.deepEqual(stack, [
{
field: 'username',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: ['user'],
pointer: 'user.username',
},
{
field: 'age',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'age',
},
])
})
test('walk over all object node parent and children both', (assert) => {
const schema = {
user: 'required',
'user.username': 'required',
age: 'required',
}
const stack = new TreeWalker((field, type, rules, dotPath, pointer) => {
return { field, type, rules, dotPath, pointer }
}, () => {}).walk(rulesParser(schema))
assert.deepEqual(stack, [
{
field: 'user',
type: 'object',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'user',
},
{
field: 'username',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: ['user'],
pointer: 'user.username',
},
{
field: 'age',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'age',
},
])
})
test('walk over all array nodes', (assert) => {
const schema = {
'users.*.username': 'required',
}
const stack = new TreeWalker((field, type, rules, dotPath, pointer) => {
return { field, type, rules, dotPath, pointer }
}, (index, field, children, dotPath) => {
return { index, field, children, dotPath }
}).walk(rulesParser(schema))
assert.deepEqual(stack, [
{
index: '*',
dotPath: [],
field: 'users',
children: [
{
field: 'username',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users.*.username',
},
],
},
])
})
test('walk over array nested inside object nodes', (assert) => {
const schema = {
'user.profiles.*.username': 'required',
}
const stack = new TreeWalker((field, type, rules, dotPath, pointer) => {
return { field, type, rules, dotPath, pointer }
}, (index, field, children, dotPath) => {
return { index, field, children, dotPath }
}).walk(rulesParser(schema))
assert.deepEqual(stack, [
{
index: '*',
dotPath: ['user'],
field: 'profiles',
children: [
{
field: 'username',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'user.profiles.*.username',
},
],
},
])
})
test('walk over array nested child', (assert) => {
const schema = {
'users': 'required',
'users.*.profile': 'required',
'users.*.profile.username': 'required',
}
const stack = new TreeWalker((field, type, rules, dotPath, pointer) => {
return { field, type, rules, dotPath, pointer }
}, (index, field, children, dotPath) => {
return { index, field, children, dotPath }
}).walk(rulesParser(schema))
assert.deepEqual(stack, [
{
field: 'users',
type: 'array',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users',
},
{
index: '*',
dotPath: [],
field: 'users',
children: [
{
field: 'profile',
type: 'object',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users.*.profile',
},
{
field: 'username',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: ['profile'],
pointer: 'users.*.profile.username',
},
],
},
])
})
test('walk over array indexed and wildcard children', (assert) => {
const schema = {
'users': 'required',
'users.0.profile.type': 'required',
'users.*.profile': 'required',
'users.*.profile.username': 'required',
}
const stack = new TreeWalker((field, type, rules, dotPath, pointer) => {
return { field, type, rules, dotPath, pointer }
}, (index, field, children, dotPath) => {
return { index, field, children, dotPath }
}).walk(rulesParser(schema))
assert.deepEqual(stack, [
{
field: 'users',
type: 'array',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users',
},
{
index: '0',
dotPath: [],
field: 'users',
children: [
{
field: 'type',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: ['profile'],
pointer: 'users.0.profile.type',
},
],
},
{
index: '*',
dotPath: [],
field: 'users',
children: [
{
field: 'profile',
type: 'object',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users.*.profile',
},
{
field: 'username',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: ['profile'],
pointer: 'users.*.profile.username',
},
],
},
])
})
test('walk over array indexed and wildcard tip', (assert) => {
const schema = {
'users': 'required',
'users.0': 'required',
'users.*': 'required',
}
const stack = new TreeWalker((field, type, rules, dotPath, pointer) => {
return { field, type, rules, dotPath, pointer }
}, (index, field, children, dotPath) => {
return { index, field, children, dotPath }
}).walk(rulesParser(schema))
assert.deepEqual(stack, [
{
field: 'users',
type: 'array',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users',
},
{
index: '0',
dotPath: [],
field: 'users',
children: [
{
field: '::tip::',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users.0',
},
],
},
{
index: '*',
dotPath: [],
field: 'users',
children: [
{
field: '::tip::',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users.*',
},
],
},
])
})
test('walk over nested arrays', (assert) => {
const schema = {
'users.*.profiles.*.username': 'required',
'users.*.account_status': 'required',
}
const stack = new TreeWalker((field, type, rules, dotPath, pointer) => {
return { field, type, rules, dotPath, pointer }
}, (index, field, children, dotPath) => {
return { index, field, children, dotPath }
}).walk(rulesParser(schema))
assert.deepEqual(stack, [
{
index: '*',
dotPath: [],
field: 'users',
children: [
{
field: 'profiles',
index: '*',
dotPath: [],
children: [
{
field: 'username',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users.*.profiles.*.username',
},
],
},
{
field: 'account_status',
type: 'literal',
rules: [{ name: 'required', args: [] }],
dotPath: [],
pointer: 'users.*.account_status',
},
],
},
])
})
})
|
5c6d8c3bb9f6140d82189d2d26d2bf14a6e0d235
|
TypeScript
|
brijal1987/typescript-crud
|
/src/controllers/user.ts
| 2.71875
| 3
|
import { Request, Response, Router } from 'express';
import { getCustomRepository } from 'typeorm';
import { UserService } from 'src/services/user';
import { UserRepository } from 'src/repositories/user';
import { logger } from '../util/logger';
// eslint-disable-next-line @typescript-eslint/no-empty-interface
// export interface IUserService {
// getAll: (limit: number, offset: number) => {}
// }
export class UsersController {
// private readonly userService: IUserService;
private router: Router;
public constructor() {
this.router = Router();
this.router.get('/', UsersController.getUsers);
this.router.post('/', UsersController.createUser);
this.router.get('/:id', UsersController.getUser);
this.router.put('/:id', UsersController.updateUser);
this.router.delete('/:id', UsersController.deleteUser);
// this.userService = userService;
// this.userRepository = userRepository;
}
getRouter() {
return this.router;
}
/**
* GET /
* all users with limit
*/
static async getUsers(req: Request, res: Response) {
try {
const limit: string = req.query.limit.toString();
const offset: string = req.query.offset.toString();
const userRepo = getCustomRepository(UserRepository);
// services
const users = await new UserService(userRepo).getAll(limit, offset);
logger.info('Getting users');
return res.json(users);
} catch (e) {
logger.info('Error while Getting users');
return res.json({
message: e.message,
errors: e.errors
});
}
}
/**
* POST /
* create new user
*/
static async createUser(req: Request, res: Response) {
try {
const { firstName, lastName, address, isActive } = req.body;
const userRepo = getCustomRepository(UserRepository);
let id;
// services
const createUserData = {
id,
firstName,
lastName,
address,
isActive
};
const user = await new UserService(userRepo).createUser(createUserData);
logger.info('Creating new user');
return res.json(user);
} catch (e) {
logger.info('Error while creating new user');
return res.json({
message: e.message,
errors: e.errors
});
}
}
/**
* GET /:id
* user by id
*/
static async getUser(req: Request, res: Response) {
try {
const { id } = req.params;
const userRepo = getCustomRepository(UserRepository);
// services
const user = await new UserService(userRepo).getById(id);
if (user) {
logger.info('Getting user by ID');
return res.status(200).json(user);
}
return res.status(404).json({
error_code: 404,
message: 'User not found!'
});
} catch (e) {
logger.info('Error while Getting user by ID');
return res.json({
message: e.message,
errors: e.errors
});
}
}
/**
* PUT /
* update user by id
*/
static async updateUser(req: Request, res: Response) {
try {
const { firstName, lastName, address, isActive } = req.body;
const { id } = req.params;
const userRepo = getCustomRepository(UserRepository);
// services
const updateUserData = {
id: parseInt(id, 10),
firstName,
lastName,
address,
isActive
};
const user = await new UserService(userRepo).updateUser(id, updateUserData);
if (user) {
logger.info('Updating user');
return res.json(user);
}
return res.status(404).json({
error_code: 404,
message: 'User not found!'
});
} catch (e) {
logger.info('Error while Updating user');
return res.json({
message: e.message,
errors: e.errors
});
}
}
/**
* Delete /:id
* delete user by id
*/
static async deleteUser(req: Request, res: Response) {
try {
const { id } = req.params;
const userRepo = getCustomRepository(UserRepository);
// services
if (await new UserService(userRepo).deleteById(id)) {
logger.info('Deleting user by ID');
return res.json({
status: 200,
message: 'User deleted!'
});
}
return res.status(404).json({
error_code: 404,
message: 'User not found!'
});
} catch (e) {
logger.info('Error while Deleting user by ID');
return res.json({
message: e.message,
errors: e.errors
});
}
}
}
|
68e125a200f7ba592bebab7665d54d81097ee610
|
TypeScript
|
AGhariebiyan/ipsen5
|
/src/app/models/role.model.ts
| 2.6875
| 3
|
export class Role {
id: string;
title: string;
description: string;
canEditCompany: boolean;
constructor(title: string, description: string, canEditCompany: boolean) {
this.title = title;
this.description = description;
this.canEditCompany = canEditCompany;
}
}
|
abeb1fa03027ee87a8c4655157ca7ab5f54ab14a
|
TypeScript
|
DevTobias/highlight-ts
|
/test/markup/nix.ts
| 2.53125
| 3
|
export default [
`{ stdenv, foo, bar ? false, ... }:
/*
* foo
*/
let
a = 1; # just a comment
b = null;
c = toString 10;
in stdenv.mkDerivation rec {
name = "foo-\${version}";
version = "1.3";
configureFlags = [ "--with-foo2" ] ++ stdenv.lib.optional bar "--with-foo=\${ with stdenv.lib; foo }"
postInstall = ''
\${ if true then "--\${test}" else false }
'';
meta = with stdenv.lib; {
homepage = https://nixos.org;
};
}`,
`{ stdenv, foo, bar ? <span class="hljs-literal">false</span>, ... }:
<span class="hljs-comment">/*
* foo
*/</span>
<span class="hljs-keyword">let</span>
<span class="hljs-attr">a</span> = <span class="hljs-number">1</span>; <span class="hljs-comment"># just a comment</span>
<span class="hljs-attr">b</span> = <span class="hljs-literal">null</span>;
<span class="hljs-attr">c</span> = <span class="hljs-built_in">toString</span> <span class="hljs-number">10</span>;
<span class="hljs-keyword">in</span> stdenv.mkDerivation <span class="hljs-keyword">rec</span> {
<span class="hljs-attr">name</span> = <span class="hljs-string">"foo-<span class="hljs-subst">\${version}</span>"</span>;
<span class="hljs-attr">version</span> = <span class="hljs-string">"1.3"</span>;
<span class="hljs-attr">configureFlags</span> = [ <span class="hljs-string">"--with-foo2"</span> ] ++ stdenv.lib.optional bar <span class="hljs-string">"--with-foo=<span class="hljs-subst">\${ <span class="hljs-keyword">with</span> stdenv.lib; foo }</span>"</span>
<span class="hljs-attr">postInstall</span> = <span class="hljs-string">\'\'
<span class="hljs-subst">\${ <span class="hljs-keyword">if</span> <span class="hljs-literal">true</span> <span class="hljs-keyword">then</span> <span class="hljs-string">"--<span class="hljs-subst">\${test}</span>"</span> <span class="hljs-keyword">else</span> <span class="hljs-literal">false</span> }</span>
\'\'</span>;
<span class="hljs-attr">meta</span> = <span class="hljs-keyword">with</span> stdenv.lib; {
<span class="hljs-attr">homepage</span> = https://nixos.org;
};
}`
];
|
5a01e6f25d8b82cd9cd550b0163b3489afdc14d7
|
TypeScript
|
khanhtoandng/typescript-crash
|
/src/3_Tuple.ts
| 3.90625
| 4
|
// Normal shape
const drink = {
color: "white",
carbonated: true,
sugar: 40,
};
// Tuple
const pepsi: [string, boolean, number] = ["white", true, 50];
// pepsi[0] = false; //error
// Tuple Array
let employee: [number, string][];
employee = [
[1, "Toan"],
[2, "Huynh"],
];
// Using Type Alias
type Drink = [string, boolean, number];
const sprite: Drink = ["clear", true, 40];
const tea: Drink = ["brown", false, 0];
|
31d9c17847bb11b053fecb0e07a694eb5df3bcf9
|
TypeScript
|
ConnorFields/netflix-crusher
|
/src/app/home/home.component.ts
| 2.6875
| 3
|
import { Component, OnInit } from '@angular/core';
//Service Import
import { VideoImporterService } from '../video-importer.service';
import { VideoHistoryService } from '../video-history.service';
//Model import
import { Video } from '../data-source.model';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(
private _service: VideoImporterService,
private _historyService: VideoHistoryService) { }
//Global Variables
videoList: Video[];
offset: number = 0;
selectedVideo: Video;
videoHistoryList: Video[];
//Calculate position to set what items are displayed in frame
getItemPosition(index: number) {
let width: number = 300;
return (index * width + (-this.offset)) + 'px';
}
//focus indicator
setSelectedVideo(selectedVideo: any) {
this.selectedVideo = selectedVideo;
for(let video of this.videoList){
video.isSelected = false;
}
selectedVideo.isSelected = true;
}
//on click function for right arrow
navigateRight() {
if(!this.rightArrowDisabled){
this.offset += 300;
this.leftArrowDisabled = false;
}
//Disable button once list is has reached end
if(this.offset >= (this.videoList.length*300 - 1200)){
this.rightArrowDisabled = true;
}
}
//on click function for left arrow
navigateLeft() {
if(!this.leftArrowDisabled){
this.offset -= 300;
this.rightArrowDisabled = false;
}
//Disable button if list is at beginning
if(this.offset <= 0){
this.leftArrowDisabled = true;
}
}
//internal variables to control whether or not arrows are clickable
rightArrowDisabled: boolean;
leftArrowDisabled: boolean;
//subscribing to video service to get video data
ngOnInit() {
this._service.getVideoList().subscribe(
data => { this.videoList = data.entries
//storing previously selected videos in new array
this.videoHistoryList = this._historyService.listHistory();
}
);
//Using callback for keyboard controls and highlight effect on focused item (video)
document.addEventListener('keydown', (ev:KeyboardEvent) => {
let indexOfSelected = 0;
if(this.selectedVideo == undefined) {
this.selectedVideo = this.videoList[0];
}
switch(ev.keyCode){
case 39://Right Arrow
this.navigateRight();
indexOfSelected = this.videoList.indexOf(this.selectedVideo);
if(indexOfSelected < (this.videoList.length-1) ){
this.setSelectedVideo(this.videoList[indexOfSelected + 1]);
}
break;
case 37://Left Arrow
this.navigateLeft();
indexOfSelected = this.videoList.indexOf(this.selectedVideo);
if(indexOfSelected > 0){
this.setSelectedVideo(this.videoList[indexOfSelected - 1]);
}
break;
}
});
}
}
|
cda5bb37104aa542fb518fd6647e7e8a1c400008
|
TypeScript
|
greguz/rxdable
|
/src/getObservableByStream.spec.ts
| 2.71875
| 3
|
import test from 'ava'
import { Readable } from 'stream'
import { toArray } from 'rxjs/operators'
import { getObservableByStream } from './index'
test('should work', async t => {
const readable = new Readable({
objectMode: true,
read () {
for (let i = 65; i <= 90; i++) {
this.push(String.fromCharCode(i))
}
this.push(null)
}
})
const observable = getObservableByStream<string>(readable)
const chunks = await observable.pipe(toArray()).toPromise()
for (let i = 0; i < chunks.length; i++) {
t.is(chunks[i], String.fromCharCode(i + 65))
}
})
test.cb('should handle readable errors', t => {
const readable = new Readable({
objectMode: true,
read () {
this.emit('error', new Error('STOP'))
}
})
const observable = getObservableByStream<void>(readable)
observable.subscribe(
undefined,
error => {
if (error instanceof Error && error.message === 'STOP') {
t.end()
} else {
t.end(error)
}
},
() => {
t.end(new Error('Oh no'))
}
)
})
|
78c7cc9c7d0b355b413fe8d11e0df47e9733218c
|
TypeScript
|
jyand/dbmgmt
|
/doc.ts
| 2.96875
| 3
|
const FORMID: string = "container" ;
// These are effectively aliases for DOM Methods but with strict typing
export function Id(s: string): HTMLElement | null {
return document.getElementById(s) ;
}
export function Listen (s: string, e, func: EventListener): void {
document.getElementById(s),addEventListener(e, func) ;
}
export function Tags(s: string): HTMLCollectionOf<Element> | null {
return document.getElementsByTagName(s) ;
}
export function Form(input: string): string | number | boolean {
return document.forms[FORMID][input].value ;
}
// for efficiently generating HTML in the page
export class InputElement {
inputType: string ;
inputId: string ;
value: string | null ;
constructor(inputType: string, inputId: string, value: string | null) {
this.inputType = inputType ;
this.inputId = inputId ;
this.value = value ;
}
NewElement(): void {
let input: HTMLElement = document.createElement("input") ;
document.getElementById(FORMID).appendChild(document.createElement("p").appendChild(input)) ;
input.setAttribute("type", this.inputType) ;
input.setAttribute("id", this.inputId) ;
if (this.value != null) {
input.setAttribute("value", this.value) ;
}
}
}
export function BuildForms(prev: InputElement, n: number, i: number): void {
if (n <= i) {
return ;
}
prev.NewElement() ;
let next = new InputElement(prev.inputType, `${prev.inputId}${i+1}`, null) ;
BuildForms(next, n-1, i+1) ;
}
|
280ac6400e82705cbe55daa274bd0ceea2c87d17
|
TypeScript
|
aaronchenhg/varlet
|
/packages/varlet-ui/types/counter.d.ts
| 2.515625
| 3
|
import { VarComponent } from './varComponent'
export type CounterValidateTriggers = 'onIncrement' | 'onDecrement' | 'onInputChange' | 'onLazyChange'
export interface CounterProps {
modelValue?: string | number
min?: string | number
max?: string | number
step?: string | number
color?: string
inputWidth?: string | number
inputTextSize?: string | number
buttonSize?: string | number
decimalLength?: string | number
disabled?: boolean
readonly?: boolean
disableIncrement?: boolean
disableDecrement?: boolean
disableInput?: boolean
lazyChange?: boolean
incrementButton?: boolean
decrementButton?: boolean
press?: boolean
ripple?: boolean
validateTrigger?: Array<CounterValidateTriggers>
rules?: Array<(v: number) => any>
onBeforeChange?: (value: number, change: (value: string | number) => void) => void
onChange?: (value: number) => void
onIncrement?: (value: number) => void
onDecrement?: (value: number) => void
'onUpdate:modelValue'?: (value: number) => void
}
export class Counter extends VarComponent {
$props: CounterProps
validate(): Promise<boolean>
resetValidation(): void
reset(): void
}
export class _CounterComponent extends Counter {}
|
30d7b585cd9555fd11a7af9d79dcffae25da9dfd
|
TypeScript
|
TheRedLegz/simple_calculator_sia
|
/script.ts
| 3.15625
| 3
|
let currentOperation : string = ''
let operand1 : number
let operand2 : number
let isNew : boolean = true
let isOp2Good: boolean = false
function getInput(input : string) {
let output = <HTMLInputElement>document.getElementById("output")
let currentOperationOutput = <HTMLSpanElement>document.getElementById("currentOperation")
if (!isNaN(+input)) {
if (isNew) {
output.value = ''
isNew = false
}
output.value += input
if (currentOperation == '') {
operand1 = +output.value
}
else {
isOp2Good = true;
operand2 = +output.value
}
}
else {
if (currentOperation == '') {
isNew = true
}
else {
if (isOp2Good) {
solve()
}
}
currentOperation = input
currentOperationOutput.innerHTML = currentOperation
}
}
function solve() {
let output = <HTMLInputElement>document.getElementById("output")
let result : number = 0
let history = <HTMLParagraphElement>document.getElementById("history")
let currentOperationOutput = <HTMLSpanElement>document.getElementById("currentOperation")
if (currentOperation != '' && isOp2Good) {
if (currentOperation == '+') {
result = operand1 + operand2
}
else if (currentOperation == '-') {
result = operand1 - operand2
}
else if (currentOperation == '/') {
result = operand1 / operand2
}
else if (currentOperation == '*') {
result = operand1 * operand2
}
else if (currentOperation == '%') {
result = operand1 % operand2
}
history.innerHTML += `${operand1} ${currentOperation} ${operand2} = ${result} <br/>`
output.value = result.toString()
currentOperation = ''
currentOperationOutput.innerHTML = ''
operand1 = +output.value
isNew = true
isOp2Good = false;
}
}
|
fcf55a0452fd99e7244b590713bb665182357b26
|
TypeScript
|
demurgos/stream
|
/src/lib/concat-bytes.ts
| 2.53125
| 3
|
import { UintSize } from "semantic-types";
export function concatBytes(chunks: Uint8Array[]): Uint8Array {
let totalSize: UintSize = 0;
for (const chunk of chunks) {
totalSize += chunk.length;
}
const result: Uint8Array = new Uint8Array(totalSize);
let offset: UintSize = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
|
089a63d9813034edad263fb7f3afcb27a6bb4ece
|
TypeScript
|
silvioiannone/spa-skeleton
|
/src/Library/App/Filters/Truncate.ts
| 3.546875
| 4
|
import { AbstractFilter } from './AbstractFilter';
/**
* This filter truncates the text at the specified amount of characters.
*/
export class Truncate extends AbstractFilter
{
/**
* Run the filter.
*/
public run(): (value: string, ...args: any[]) => string
{
return (value: string, ...args: any[]): string => {
let length = args[0] || 300;
let append = args[1] || '...';
if (value.length < length) {
return value;
}
let sliceEnd = length;
// If the character at `sliceEnd` position is not a whitespace we keep increasing the
// `sliceEnd` in order to not cut words in half.
while (! /\s/.test(value.charAt(sliceEnd))) {
sliceEnd++;
}
return value.slice(0, sliceEnd) + append;
}
}
}
|
ac39970157600561f23a246e9032bd0b9e022261
|
TypeScript
|
RolandCsibrei/babylonjs-vue-messages-driven-scene
|
/src/utils/async.ts
| 3.109375
| 3
|
export async function asyncForEach<T>(array: Array<T>, callback: (item: T, index: number) => Promise<void>) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index)
}
}
|
b7fb9503c91cc4150cdf277f32de6caa9c807073
|
TypeScript
|
cxqntnt/blog-tutorials
|
/node-webapp-pdf/src/models/address.model.ts
| 2.546875
| 3
|
import mongoose, { Schema, Document, Model } from 'mongoose';
type AddressDocument = Document & {
firstName: string;
lastName: string;
phoneNumber: string;
country: string;
city: string;
state: string;
street: string;
postalCode: string;
user: string;
};
type AddressInput = {
firstName: AddressDocument['firstName'];
lastName: AddressDocument['lastName'];
phoneNumber: AddressDocument['phoneNumber'];
country: AddressDocument['country'];
city: AddressDocument['city'];
state: AddressDocument['state'];
street: AddressDocument['street'];
postalCode: AddressDocument['postalCode'];
user: AddressDocument['user'];
};
const addressSchema = new Schema(
{
firstName: {
type: Schema.Types.String,
required: true,
},
lastName: {
type: Schema.Types.String,
required: true,
},
phoneNumber: {
type: Schema.Types.String,
required: true,
},
country: {
type: Schema.Types.String,
required: true,
},
city: {
type: Schema.Types.String,
required: true,
},
state: {
type: Schema.Types.String,
required: true,
},
street: {
type: Schema.Types.String,
required: true,
},
postalCode: {
type: Schema.Types.String,
required: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
index: true,
},
},
{
collection: 'store_addresses',
timestamps: true,
},
);
const Address: Model<AddressDocument> = mongoose.model('Address', addressSchema);
export { Address, AddressDocument, AddressInput };
|
8b34fdfcc83004e75d93d40a4756741c375e5b99
|
TypeScript
|
tlekenta/cepik-front
|
/src/app/pipes/from-to.pipe.ts
| 2.671875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { Vehicle } from '../model/cep/vehicle';
@Pipe({
name: 'fromToPipe'
})
export class FromToPipe implements PipeTransform {
transform(items: Vehicle[], which: string, filterFrom: number, filterTo: number, maxLength: number): any {
if(!items) {
return items;
}
return this.filterTo(this.filterFrom(items, which, filterFrom, maxLength), which, filterTo, maxLength);
}
private filterTo(items: Vehicle[], which: string, filter: number, maxLength: number): Vehicle[] {
if(!filter || filter < Math.pow(10, maxLength - 1)) return items;
return items.filter(veh => parseFloat(veh[which]) <= filter);
}
private filterFrom(items: Vehicle[], which: string, filter: number, maxLength: number): Vehicle[] {
if(!filter || filter < Math.pow(10, maxLength - 2)) return items;
return items.filter(veh => parseFloat(veh[which]) >= filter);
}
}
|
cf3c9fa474ee49e4c7748cc9955f4a8dfd6777bc
|
TypeScript
|
splinkns/circus
|
/packages/circus-rs/src/common/CCL/ConnectedComponentLabeling3D26.ts
| 2.796875
| 3
|
import { CCL3D } from './ccl-types';
/**
* @param array input binary image
* @param width width of array
* @param height height of array
* @param nSlices slice number of array
* @param threshold voxel value of threshold
*/
const CCL: CCL3D = (array, width, height, nSlices, threshold = 0) => {
const [dx, dy, dz] = [
[-1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1],
[0, -1, -1, -1, -1, -1, -1, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1]
];
const num_maxCCL = 2 ** 8;
const chiefLabelTable = new Uint8Array(num_maxCCL);
const substituteLabels = new Uint8Array(num_maxCCL ** 2);
const resolve = (label1: number, label2: number) => {
if (chiefLabelTable[label1] === chiefLabelTable[label2]) {
return;
}
if (chiefLabelTable[label1] > chiefLabelTable[label2]) {
[label1, label2] = [label2, label1];
}
const chiefLabel = chiefLabelTable[label1];
const _chiefLabel = chiefLabelTable[label2];
for (let i = 1; i <= substituteLabels[_chiefLabel * num_maxCCL]; i++) {
substituteLabels[
chiefLabel * num_maxCCL + substituteLabels[chiefLabel * num_maxCCL] + i
] = substituteLabels[_chiefLabel * num_maxCCL + i];
chiefLabelTable[
substituteLabels[_chiefLabel * num_maxCCL + i]
] = chiefLabel;
}
substituteLabels[chiefLabel * num_maxCCL] +=
substituteLabels[_chiefLabel * num_maxCCL];
substituteLabels[_chiefLabel * num_maxCCL] = 0;
};
const setNewLabel = (label: number) => {
chiefLabelTable[label] = label;
substituteLabels[label * num_maxCCL + 1] = label;
substituteLabels[label * num_maxCCL] = 1;
};
const val0 = (x: number, y: number, z: number) => {
return x < 0 || width <= x || y < 0 || height <= y || z < 0 || nSlices <= z
? -1
: array[x + width * (y + z * height)];
};
const labelImg = new Uint8Array(width * height * nSlices);
const val = (x: number, y: number, z: number) => {
return x < 0 || width <= x || y < 0 || height <= y || z < 0 || nSlices <= z
? -1
: labelImg[x + width * (y + z * height)];
};
let label = 0;
for (let k = 0; k < nSlices; k++) {
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
if (val0(i, j, k) <= threshold) {
continue;
}
if (val(i + dx[8], j + dy[8], k + dz[8]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[8],
j + dy[8],
k + dz[8]
);
} else if (val(i + dx[2], j + dy[2], k + dz[2]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[2],
j + dy[2],
k + dz[2]
);
if (
val(i + dx[11], j + dy[11], k + dz[11]) > 0 &&
val(i + dx[7], j + dy[7], k + dz[7]) <= 0 &&
val(i + dx[9], j + dy[9], k + dz[9]) <= 0
) {
resolve(
val(i + dx[2], j + dy[2], k + dz[2]),
val(i + dx[11], j + dy[11], k + dz[11])
);
} else {
if (
val(i + dx[10], j + dy[10], k + dz[10]) > 0 &&
val(i + dx[7], j + dy[7], k + dz[7]) <= 0
) {
resolve(
val(i + dx[2], j + dy[2], k + dz[2]),
val(i + dx[10], j + dy[10], k + dz[10])
);
}
if (
val(i + dx[12], j + dy[12], k + dz[12]) > 0 &&
val(i + dx[9], j + dy[9], k + dz[9]) <= 0
) {
resolve(
val(i + dx[2], j + dy[2], k + dz[2]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
}
} else if (val(i + dx[5], j + dy[5], k + dz[5]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[5],
j + dy[5],
k + dz[5]
);
if (
val(i + dx[11], j + dy[11], k + dz[11]) > 0 &&
val(i + dx[7], j + dy[7], k + dz[7]) <= 0 &&
val(i + dx[9], j + dy[9], k + dz[9]) <= 0
) {
resolve(
val(i + dx[5], j + dy[5], k + dz[5]),
val(i + dx[11], j + dy[11], k + dz[11])
);
} else {
if (
val(i + dx[10], j + dy[10], k + dz[10]) > 0 &&
val(i + dx[7], j + dy[7], k + dz[7]) <= 0
) {
resolve(
val(i + dx[5], j + dy[5], k + dz[5]),
val(i + dx[10], j + dy[10], k + dz[10])
);
}
if (
val(i + dx[12], j + dy[12], k + dz[12]) > 0 &&
val(i + dx[9], j + dy[9], k + dz[9]) <= 0
) {
resolve(
val(i + dx[5], j + dy[5], k + dz[5]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
}
} else if (val(i + dx[0], j + dy[0], k + dz[0]) > 0) {
labelImg[i + j * width + k * width * height] = val(
i + dx[0],
j + dy[0],
k + dz[0]
);
if (
val(i + dx[9], j + dy[9], k + dz[9]) > 0 &&
val(i + dx[11], j + dy[11], k + dz[11]) <= 0
) {
resolve(
val(i + dx[0], j + dy[0], k + dz[0]),
val(i + dx[9], j + dy[9], k + dz[9])
);
} else if (val(i + dx[6], j + dy[6], k + dz[6]) > 0) {
resolve(
val(i + dx[0], j + dy[0], k + dz[0]),
val(i + dx[6], j + dy[6], k + dz[6])
);
if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
resolve(
val(i + dx[0], j + dy[0], k + dz[0]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (val(i + dx[3], j + dy[3], k + dz[3]) > 0) {
resolve(
val(i + dx[0], j + dy[0], k + dz[0]),
val(i + dx[3], j + dy[3], k + dz[3])
);
if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
resolve(
val(i + dx[0], j + dy[0], k + dz[0]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (
val(i + dx[12], j + dy[12], k + dz[12]) > 0 &&
val(i + dx[11], j + dy[11], k + dz[11]) <= 0
) {
resolve(
val(i + dx[0], j + dy[0], k + dz[0]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (val(i + dx[7], j + dy[7], k + dz[7]) > 0) {
labelImg[i + j * width + k * width * height] = val(
i + dx[7],
j + dy[7],
k + dz[7]
);
if (
val(i + dx[9], j + dy[9], k + dz[9]) > 0 &&
val(i + dx[11], j + dy[11], k + dz[11]) <= 0
) {
resolve(
val(i + dx[7], j + dy[7], k + dz[7]),
val(i + dx[9], j + dy[9], k + dz[9])
);
} else if (val(i + dx[6], j + dy[6], k + dz[6]) > 0) {
resolve(
val(i + dx[7], j + dy[7], k + dz[7]),
val(i + dx[6], j + dy[6], k + dz[6])
);
if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
resolve(
val(i + dx[7], j + dy[7], k + dz[7]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (val(i + dx[3], j + dy[3], k + dz[3]) > 0) {
resolve(
val(i + dx[7], j + dy[7], k + dz[7]),
val(i + dx[3], j + dy[3], k + dz[3])
);
if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
resolve(
val(i + dx[7], j + dy[7], k + dz[7]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (
val(i + dx[12], j + dy[12], k + dz[12]) > 0 &&
val(i + dx[11], j + dy[11], k + dz[11]) <= 0
) {
resolve(
val(i + dx[7], j + dy[7], k + dz[7]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (val(i + dx[9], j + dy[9], k + dz[9]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[9],
j + dy[9],
k + dz[9]
);
if (
val(i + dx[10], j + dy[10], k + dz[10]) > 0 &&
val(i + dx[11], j + dy[11], k + dz[11]) <= 0
) {
resolve(
val(i + dx[9], j + dy[9], k + dz[9]),
val(i + dx[10], j + dy[10], k + dz[10])
);
}
if (val(i + dx[4], j + dy[4], k + dz[4]) > 0) {
resolve(
val(i + dx[9], j + dy[9], k + dz[9]),
val(i + dx[4], j + dy[4], k + dz[4])
);
} else if (val(i + dx[1], j + dy[1], k + dz[1]) > 0) {
resolve(
val(i + dx[9], j + dy[9], k + dz[9]),
val(i + dx[1], j + dy[1], k + dz[1])
);
}
} else if (val(i + dx[11], j + dy[11], k + dz[11]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[11],
j + dy[11],
k + dz[11]
);
if (val(i + dx[3], j + dy[3], k + dz[3]) > 0) {
resolve(
val(i + dx[11], j + dy[11], k + dz[11]),
val(i + dx[3], j + dy[3], k + dz[3])
);
} else if (val(i + dx[6], j + dy[6], k + dz[6]) > 0) {
resolve(
val(i + dx[11], j + dy[11], k + dz[11]),
val(i + dx[6], j + dy[6], k + dz[6])
);
}
if (val(i + dx[1], j + dy[1], k + dz[1]) > 0) {
resolve(
val(i + dx[11], j + dy[11], k + dz[11]),
val(i + dx[1], j + dy[1], k + dz[1])
);
} else if (val(i + dx[4], j + dy[4], k + dz[4]) > 0) {
resolve(
val(i + dx[11], j + dy[11], k + dz[11]),
val(i + dx[4], j + dy[4], k + dz[4])
);
}
} else if (val(i + dx[4], j + dy[4], k + dz[4]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[4],
j + dy[4],
k + dz[4]
);
if (val(i + dx[3], j + dy[3], k + dz[3]) > 0) {
resolve(
val(i + dx[4], j + dy[4], k + dz[4]),
val(i + dx[3], j + dy[3], k + dz[3])
);
} else if (val(i + dx[6], j + dy[6], k + dz[6]) > 0) {
resolve(
val(i + dx[4], j + dy[4], k + dz[4]),
val(i + dx[6], j + dy[6], k + dz[6])
);
}
if (val(i + dx[10], j + dy[10], k + dz[10]) > 0) {
resolve(
val(i + dx[4], j + dy[4], k + dz[4]),
val(i + dx[10], j + dy[10], k + dz[10])
);
}
if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
resolve(
val(i + dx[4], j + dy[4], k + dz[4]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (val(i + dx[1], j + dy[1], k + dz[1]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[1],
j + dy[1],
k + dz[1]
);
if (val(i + dx[3], j + dy[3], k + dz[3]) > 0) {
resolve(
val(i + dx[1], j + dy[1], k + dz[1]),
val(i + dx[3], j + dy[3], k + dz[3])
);
} else if (val(i + dx[6], j + dy[6], k + dz[6]) > 0) {
resolve(
val(i + dx[1], j + dy[1], k + dz[1]),
val(i + dx[6], j + dy[6], k + dz[6])
);
}
if (val(i + dx[10], j + dy[10], k + dz[10]) > 0) {
resolve(
val(i + dx[1], j + dy[1], k + dz[1]),
val(i + dx[10], j + dy[10], k + dz[10])
);
}
if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
resolve(
val(i + dx[1], j + dy[1], k + dz[1]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (val(i + dx[3], j + dy[3], k + dz[3]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[3],
j + dy[3],
k + dz[3]
);
if (val(i + dx[10], j + dy[10], k + dz[10]) > 0) {
resolve(
val(i + dx[3], j + dy[3], k + dz[3]),
val(i + dx[10], j + dy[10], k + dz[10])
);
}
if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
resolve(
val(i + dx[3], j + dy[3], k + dz[3]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (val(i + dx[6], j + dy[6], k + dz[6]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[6],
j + dy[6],
k + dz[6]
);
if (val(i + dx[10], j + dy[10], k + dz[10]) > 0) {
resolve(
val(i + dx[6], j + dy[6], k + dz[6]),
val(i + dx[10], j + dy[10], k + dz[10])
);
}
if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
resolve(
val(i + dx[6], j + dy[6], k + dz[6]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (val(i + dx[10], j + dy[10], k + dz[10]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[10],
j + dy[10],
k + dz[10]
);
if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
resolve(
val(i + dx[10], j + dy[10], k + dz[10]),
val(i + dx[12], j + dy[12], k + dz[12])
);
}
} else if (val(i + dx[12], j + dy[12], k + dz[12]) > 0) {
labelImg[i + width * (j + k * height)] = val(
i + dx[12],
j + dy[12],
k + dz[12]
);
} else {
++label;
if (num_maxCCL <= label) {
throw new Error(`number of tentative label is not in 8 bit.`);
}
labelImg[i + width * (j + k * height)] = label;
setNewLabel(label);
}
}
}
}
let labelCount = 0;
for (let i = 1; i < num_maxCCL; i++) {
if (substituteLabels[i * num_maxCCL] != 0) {
labelCount++;
for (
let j = i * num_maxCCL + 1;
j <= i * num_maxCCL + substituteLabels[i * num_maxCCL];
j++
) {
chiefLabelTable[substituteLabels[j]] = labelCount;
}
}
}
const volume = new Uint32Array(labelCount + 1);
const max =
width < height
? height < nSlices
? nSlices
: height
: width < nSlices
? nSlices
: width;
const UL = new Uint16Array((labelCount + 1) * 3).map(() => max);
const LR = new Uint16Array((labelCount + 1) * 3);
for (let k = 0; k < nSlices; k++) {
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
const pos = i + width * (j + k * height);
const labeltmp = chiefLabelTable[labelImg[pos]];
const labeltmp3 = labeltmp * 3;
labelImg[pos] = labeltmp;
//labeltmp
if (i < UL[labeltmp3]) {
UL[labeltmp3] = i;
}
if (LR[labeltmp3] < i) {
LR[labeltmp3] = i;
}
if (j < UL[labeltmp3 + 1]) {
UL[labeltmp3 + 1] = j;
}
if (LR[labeltmp3 + 1] < j) {
LR[labeltmp3 + 1] = j;
}
if (k < UL[labeltmp3 + 2]) {
UL[labeltmp3 + 2] = k;
}
if (LR[labeltmp3 + 2] < k) {
LR[labeltmp3 + 2] = k;
}
volume[labeltmp]++;
}
}
}
const labels = new Array(labelCount + 1);
for (let i = 0; i <= labelCount; i++) {
const pos = [i * 3, i * 3 + 1, i * 3 + 2];
labels[i] = {
volume: volume[i],
min: [UL[pos[0]], UL[pos[1]], UL[pos[2]]],
max: [LR[pos[0]], LR[pos[1]], LR[pos[2]]]
};
}
return { labelMap: labelImg, labelNum: labelCount, labels };
};
export default CCL;
|
54cc4201886da45c1dd18c77ff6a82768d102327
|
TypeScript
|
dedalusmax/dice-and-roll2
|
/src/services/textual.service.ts
| 2.515625
| 3
|
import { Settings } from "../models/settings";
export class TextualService {
static createTextButton(scene: Phaser.Scene, text, x, y, style, action): Phaser.GameObjects.Text {
var item = scene.add.text(x, y, text, style);
item.setOrigin(0.5, 0.5);
item.setInteractive();
item.on('pointerdown', e => {
scene.sound.add('click', { volume: Settings.sound.sfxVolume }).play();
if (action) action.call();
});
return item;
};
}
|
7ddb670a8cf1f09b3488c3c58dd7379df2913c7c
|
TypeScript
|
marcindlu993/angular4front
|
/src/app/models/project.ts
| 2.625
| 3
|
export interface IProjectDTO {
ProjectId: number;
Name: string;
StartDate: Date;
EndDate: Date;
LastModifyDate: Date;
Comment: string;
}
export class ProjectModel {
ProjectId: number;
Name: string;
StartDate: Date;
EndDate: Date;
LastModifyDate: Date;
Comment: string;
constructor(data: IProjectDTO)
{
this.ProjectId = data.ProjectId,
this.StartDate = data.StartDate,
this.EndDate = data.EndDate,
this.LastModifyDate = data.LastModifyDate,
this.Name = data.Name,
this.Comment = data.Comment
}
}
|
20ed7dfa4ee6eaf0bd5dcefa0c33466b40599ebe
|
TypeScript
|
PoEManager/Backend-Server
|
/app/model/password.ts
| 3.296875
| 3
|
import bcrypt from 'bcrypt';
import config from '../core/config';
/**
* A class that creates and compares encrypted passwords.
*/
class Password {
/**
* ```true```, if the salt was already generated, ```false``` if not.
*
* Salt generation only has to take place once.
*/
private static generatedSalt = false;
/**
* The salt that is used to generate the encrypted passwords.
*/
private static salt: any;
/**
* A factory method that encrypts new passwords.
*
* @param password The unencrypted password that will be encrypted.
*/
public static async encryptPassword(password: string): Promise<Password> {
if (!Password.generatedSalt) {
Password.salt = await bcrypt.genSalt(Password.SALT_ROUNDS);
Password.generatedSalt = true;
}
return new Password(await bcrypt.hash(password, Password.salt));
}
/**
* The encrypted password.
*/
private readonly encrypted: string;
/**
* Create a new instance from an encrypted password string.
*
* @param encrypted The encrypted password.
*/
public constructor(encrypted: string) {
this.encrypted = encrypted;
}
/**
* Compares the instance to another, unencrypted password.
*
* @param password The unencrypted password to compare to.
*/
public async compareTo(password: string): Promise<boolean> {
return await bcrypt.compare(password, this.encrypted);
}
/**
* @returns The encrypted password as a string.
*/
public getEncrypted(): string {
return this.encrypted;
}
}
/* istanbul ignore next */
namespace Password {
/**
* The amount of rounds used to generate the salt.
*/
export const SALT_ROUNDS = config.security.passwordSaltRounds;
}
export = Password;
|
0d86aa5c783f2c55e9b17c981b738931369b320a
|
TypeScript
|
SocialGouv/pass-emploi-api
|
/test/fixtures/date.fixture.ts
| 2.5625
| 3
|
import { DateTime } from 'luxon'
export const uneDatetime = (): DateTime =>
DateTime.fromISO('2020-04-06T12:00:00.000Z')
export const uneDatetimeAvecOffset = (): DateTime =>
DateTime.fromISO('2020-04-06T12:00:00.000Z', { setZone: true })
export const uneDatetimeLocale = (): DateTime =>
DateTime.fromISO('2020-04-06T12:00:00.000')
export const uneAutreDatetime = (): DateTime =>
DateTime.fromISO('2020-04-07T12:00:00.000Z')
export const uneDatetimeMoinsRecente = (): DateTime =>
DateTime.fromISO('2019-04-06T12:00:00.000Z')
export const uneDatetimeMinuit = (): DateTime =>
DateTime.fromISO('2020-04-06T00:00:00.000Z')
export const uneDate = (): Date => new Date('2022-03-01T03:24:00')
export const uneAutreDate = (): Date => new Date('2022-04-01T03:24:00')
|
5522944819ddd28c151b6b19db9a10c4ea7ebb07
|
TypeScript
|
ConanSpithoven/PRG8-Game
|
/dev/Notes/note.ts
| 2.984375
| 3
|
abstract class Note implements Observer {
//specifiers how the note plays
protected _noteController : NoteController;
protected _element:HTMLElement;
protected _fretID:number;
protected _fret:HTMLElement;
protected _y:number = 0;
protected _gravity:number = 9;
protected _stop:boolean = false;
public now:boolean = false;
public subject:Subject;
public multiplier:number = 1;
constructor(fretID:number, level:Subject) {
this.subject = level;
level.registerObserver(this);
this._element = document.createElement('div');
this._fretID = fretID;
}
update():void {
if (Game.getInstance().streak > 8){
this._noteController = new NoteHitStreakController(this);
} else {
this._noteController = new NoteHitController(this);
}
//move the note
if (this._y < (this._fret.getBoundingClientRect().height - this._element.getBoundingClientRect().height)){
this._y += this._gravity;
this.element.style.transform = 'translate(0px. ${this._y}px)';
}
// destroy the note if it goes offscreen(out of the fret)
else{
Game.getInstance().decreaseScore(5);
//remove the observer
this.subject.removeObserver(this);
//remove the DOM and the reference
DOMHelper.removeNote(this);
//reset the hit streak because a note was missed
Game.getInstance().streak = 0;
}
this.checkPosition();
}
//is the note on the button
checkPosition():void{
this._noteController.checkPosition();
}
//stop the note when it is being removed, when stopped it cant be hit extra for more points
stopNote():void {
this._gravity = 0;
this._stop = true;
}
//increase the score
registerScore():void {
//handled in children
}
protected controllerChanger(controller:NoteController):void {
this._noteController = controller;
}
get element():HTMLElement {
return this._element;
}
get y():number {
return this._y
}
get fretID():number {
return this._fretID
}
get stop():boolean {
return this._stop
}
}
|
b7f233e2758f70c200d9554c6fb21580f96db759
|
TypeScript
|
yxue/cdn_check
|
/src/util.ts
| 2.5625
| 3
|
/// <reference path='../typings/index.d.ts' />
import * as dns from "dns";
import * as fs from "fs";
import * as hostile from 'hostile';
import * as child_process from 'child_process';
import * as path from 'path';
import * as md5file from 'md5-file';
export class Util{
public static unique(arr:any[]): any[]{
return arr.filter(function(item, pos){
return arr.indexOf(item) == pos;
})
}
private static _resolve(domain: string, server: string){
return new Promise<any>((resolve, reject)=>{
let dservers = dns.getServers();
dns.setServers([server]);
dns.resolve4(domain, (err, add)=>{
if(err) console.log(err);
setTimeout(()=>{
dns.setServers(dservers);
if(err){
resolve([]);
}else{
resolve(add);
}
})
});
});
}
public static async resolve(domain: string, servers: string[]){
let res = [];
for(let i = 0; i < servers.length; i ++){
let tmp = await this._resolve(domain, servers[i]);
console.log(tmp);
tmp.forEach(e => {
res.push(e);
});
}
return this.unique(res);
}
public static _wget(domain: string, ip: string, types: string[]){
return new Promise<any>((resolve, reject)=>{
hostile.set(ip, domain, (err)=>{
if(err){
resolve({
error: err,
ip: ip,
domain: domain
})
}else{
let error = "";
let cmd = 'wget -m -nd -A '+ types.join(',') + ' -P ./tmp/' + domain + '@' + ip + ' ' + domain;
console.log(cmd);
child_process.exec(cmd, {timeout: 30000}, (err, stdout, stderr)=>{
hostile.remove(ip, domain, (error)=>{
resolve({
error: error,
ip: ip,
domain: domain
})
});
})
}
});
});
}
public static async wget(domain: string, ip: string[], types: string[]){
for(var i = 0; i < ip.length; i ++){
await this._wget(domain, ip[i], types);
}
}
public static dircmp(dir1: string, dir2: string): any[]{
let res = [];
if(dir1 == dir2) return res;
let files = fs.readdirSync(dir1);
let sep = path.sep;
files.forEach(file=>{
let name1 = [dir1, file].join(sep);
let name2 = [dir2, file].join(sep);
let stats = fs.statSync(name1);
if(stats.isFile()){
try {
if(fs.statSync(name2).isFile()){
if(md5file.sync(name1) != md5file.sync(name2)){
res.push({
host: name1,
cdn: name2,
reason: 'MD5 Fail'
});
}
}else{
res.push({
host: name1,
cdn: name2,
reason: "Can't find file"
})
}
} catch (error) {
res.push({
host: name1,
cdn: name2,
reason: "Can't find file"
})
}
}else if(stats.isDirectory()){
try {
if(fs.statSync(name2).isDirectory()){
let ret = this.dircmp(name1, name2);
ret.forEach(e=>res.push(e));
}else{
res.push({
host: name1,
cdn: name2,
reason: "Can't find directory"
})
}
} catch (error) {
res.push({
host: name1,
cdn: name2,
reason: "Can't find directory"
})
}
}
})
return res;
}
}
|
fc5190de16bb06436c56cac297d3daf26789aca0
|
TypeScript
|
svikashk/daxc
|
/packages/daxc-i/src/attribute.opts.spec.ts
| 2.671875
| 3
|
import { expect } from "chai";
import { ATTRIBUTE_OPTS, _matching } from "./attribute.opts";
describe("#attribute.opts.js tests", () => {
describe("#_matching", () => {
it("expect to match values", () => {
// arranges
// acts
const result01 = _matching("val", "val");
const result02 = _matching(["val"], "val");
const result03 = _matching("val", ["val"]);
const result04 = _matching(["val"], ["val"]);
const result05 = _matching([true], [true]);
const result06 = _matching([false], [false]);
// asserts
expect(result01).to.be.true;
expect(result02).to.be.true;
expect(result03).to.be.true;
expect(result04).to.be.true;
expect(result05).to.be.true;
expect(result06).to.be.true;
});
it("expect not to match any empty array", () => {
// arranges
// acts
const result01 = _matching([], []);
const result02 = _matching([], ["val"]);
const result03 = _matching(["val"], []);
// asserts
expect(result01).to.be.false;
expect(result02).to.be.false;
expect(result03).to.be.false;
});
it("expect not to match any undefined or array of undefined", () => {
// arranges
// acts
const result01 = _matching(undefined, undefined);
const result02 = _matching([undefined], [undefined]);
const result03 = _matching(undefined, [undefined, "val"]);
const result04 = _matching([undefined, "val"], undefined);
const result05 = _matching([undefined, false], [undefined, false]);
const result06 = _matching([undefined, false], [undefined, 0]);
// asserts
expect(result01).to.be.false;
expect(result02).to.be.false;
expect(result03).to.be.false;
expect(result04).to.be.false;
expect(result05).to.be.true;
expect(result06).to.be.false;
});
});
describe("#ATTRIBUTE_OPTS", () => {
describe("ATTRIBUTE_OPTS.owner()", () => {
it("expect to verify an owner, #1", () => {
// arranges
const accessOwner = "Test Owner";
const identity = { accessOwner };
const resource = { accessOwner };
// acts
const result = ATTRIBUTE_OPTS.owner(identity, resource);
// asserts
expect(result).to.be.true;
});
it("expect to verify an owner, #2", () => {
// arranges
const accessOwner = "Test Owner";
const identity = { name: accessOwner };
const resource = { accessOwner };
// acts
const result = ATTRIBUTE_OPTS.owner(identity, resource);
// asserts
expect(result).to.be.false;
});
it("expect to verify an owner, #3", () => {
// arranges
const accessOwner = "Test Owner";
const identity = { accessOwner };
const resource = { name: accessOwner };
// acts
const result = ATTRIBUTE_OPTS.owner(identity, resource);
// asserts
expect(result).to.be.false;
});
it("expect to verify an owner, #4", () => {
// arranges
const accessOwner = "Test Owner";
const identity: any = undefined;
const resource = { name: accessOwner };
// acts
const result = ATTRIBUTE_OPTS.owner(identity, resource);
// asserts
expect(result).to.be.false;
});
it("expect to verify an owner, #5", () => {
// arranges
const accessOwner = "Test Owner";
const identity = { name: accessOwner };
const resource: any = undefined;
// acts
const result = ATTRIBUTE_OPTS.owner(identity, resource);
// asserts
expect(result).to.be.false;
});
});
describe("ATTRIBUTE_OPTS.attributes()", () => {
it("expect to verify an attributes, #1", () => {
// arranges
const identity = { accessAttrs: ["1"] };
const resource = { accessAttrs: ["0", "1", "2"] };
// acts
const result = ATTRIBUTE_OPTS.attributes(identity, resource);
// asserts
expect(result).to.be.true;
});
it("expect to verify an attributes, #2", () => {
// arranges
const identity: any = { accessAttrs: [] };
const resource: any = { accessAttrs: [] };
// acts
const result = ATTRIBUTE_OPTS.attributes(identity, resource);
// asserts
expect(result).to.be.false;
});
it("expect to verify an attributes, #3", () => {
// arranges
const identity = { accessAttrs: ["1"] };
const resource = { accessAttrs: ["0", "2"] };
// acts
const result = ATTRIBUTE_OPTS.attributes(identity, resource);
// asserts
expect(result).to.be.false;
});
it("expect to verify an attributes, #4", () => {
// arranges
const identity = { accessAttrs: ["1", "2"] };
const resource = { accessAttrs: ["0", "2"] };
// acts
const result = ATTRIBUTE_OPTS.attributes(identity, resource);
// asserts
expect(result).to.be.true;
});
it("expect to verify an attributes, #5", () => {
// arranges
const identity = { accessAttrs: ["0", "1"] };
// acts
const result = ATTRIBUTE_OPTS.attributes(identity, undefined);
// asserts
expect(result).to.be.false;
});
it("expect to verify an attributes, #6", () => {
// arranges
const resource = { accessAttrs: ["0", "1"] };
// acts
const result = ATTRIBUTE_OPTS.attributes(undefined, resource);
// asserts
expect(result).to.be.false;
});
});
});
});
|
92d5d504e6a80c1f239fd199cb7afc95b447517f
|
TypeScript
|
TBubba/launcher
|
/tests/src/renderer/uuid.test.ts
| 3
| 3
|
/* Tests for src/renderer/uuid.test.ts */
import { validateSemiUUID, uuid } from '../../../src/renderer/uuid';
describe('uuid.uuid()', function () {
test('Returns string of proper length?', () => {
expect(uuid()).toHaveLength(36);
});
});
describe('uuid.validateSemiUUID()', function () {
test('Empty string', () => {
expect(validateSemiUUID('')).toBe(false);
});
test('Under 36 characters', () => {
const str: string = '12345678abc';
expect(validateSemiUUID(str)).toBe(false);
});
test('Over 36 characters', () => {
const str: string = 'asdhbgfgfgajk123214543612312323asadghfga';
expect(validateSemiUUID(str)).toBe(false);
});
test('Invalid hexidecimal characters', () => {
const str: string = 'bbzz1234-0abc-llll-abcd-abc12345678z';
expect(validateSemiUUID(str)).toBe(false);
});
test('Valid UUID', () => {
const str: string = '0123abcd-fee2-0987-dfea-cd341234cdef';
expect(validateSemiUUID(str)).toBe(true);
});
});
|
2caa6f18a47382179c01ac303cb05e12c9734646
|
TypeScript
|
SergeyGrib712/Weather
|
/src/helpers/mappingForecast.ts
| 2.609375
| 3
|
import kelvinToCelsius from './kelvinToCelsius';
const mappingForecast = <T extends any>(forecast: any = {}): T => {
return {
temp: kelvinToCelsius(forecast.main?.temp || 0),
feelsLike: kelvinToCelsius(forecast.main?.feels_like || 0),
city: forecast.name || '',
icon: forecast.weather?.[0]?.icon || '',
windSpeed: Math.round(forecast.wind?.speed || 0),
clouds: forecast.clouds?.all || 0,
} as T;
};
export default mappingForecast;
|
bf303c2105c5598c13ad6c0ac54df6cc0a9404b6
|
TypeScript
|
keeema/bobrilstrap
|
/src/utilities/font.ts
| 2.8125
| 3
|
import * as b from "bobril";
import { createFilledDictionary } from "../../utils/dict";
export type FontWeight = "bold" | "bolder" | "normal" | "light" | "lighter";
export type FontStyle = "normal" | "italic";
export type FontSize = 1 | 2 | 3 | 4 | 5 | 6;
export type LineHeight = 1 | "sm" | "base" | "lg";
export const fontWeights: FontWeight[] = ["bold", "bolder", "normal", "light", "lighter"];
export const fontStyles: FontStyle[] = ["normal", "italic"];
export const fontSizes: FontSize[] = [1, 2, 3, 4, 5, 6];
export const lineHeights: LineHeight[] = [1, "sm", "base", "lg"];
export const fontWeight = createFilledDictionary(fontWeights.map((value) => [value, b.styleDef(`fw-${value}`)]));
export const fontStyle = createFilledDictionary(fontStyles.map((value) => [value, b.styleDef(`fst-${value}`)]));
export const fontSize = createFilledDictionary(fontSizes.map((value) => [value, b.styleDef(`fs-${value}`)]));
export const fontMonospace = b.styleDef("font-monospace");
export const lineHeight = createFilledDictionary(lineHeights.map((value) => [value, b.styleDef(`lh-${value}`)]));
|
8c91a57ef1edfbc1712dfcd256be3470aa7d6283
|
TypeScript
|
nozzlegear/Shopify-Prime
|
/models/address.ts
| 2.921875
| 3
|
import { ShopifyObject } from "./base";
export interface Address extends ShopifyObject {
/**
* The mailing address.
*/
address1?: string;
/**
* An additional field for the mailing address.
*/
address2?: string;
/**
* The city.
*/
city?: string;
/**
* The company.
*/
company?: string;
/**
* The country.
*/
country?: string;
/**
* The two-letter country code corresponding to the country.
*/
country_code?: string;
/**
* The normalized country name.
*/
country_name?: string;
/**
* Indicates whether this address is the default address.
*/
default?: boolean;
/**
* The first name.
*/
first_name?: string;
/**
* The last name.
*/
last_name?: string;
/**
* The name.
*/
name?: string;
/**
* The phone number.
*/
phone?: string;
/**
* The province or state name
*/
province?: string;
/**
* The two-letter province or state code.
*/
province_code?: string;
/**
* The ZIP or postal code.
*/
zip?: string;
}
|
39ce1d03ea075cbad595da8a602f7451f42fe619
|
TypeScript
|
Scarsniik/readium-desktop
|
/src/actions/i18n.ts
| 2.796875
| 3
|
import { Action } from "redux";
export const SET_LOCALE = "SET_LOCALE";
export interface LocaleAction extends Action {
locale: string;
}
export function setLocale(locale: string): LocaleAction {
return {
type: SET_LOCALE,
locale,
};
}
|
ad7e700ee52074cc2c93bc8c551ca66ec7fa068d
|
TypeScript
|
ElielC/honeypots-web
|
/src/hooks/useHasMounted.ts
| 2.59375
| 3
|
import { useEffect, useState } from "react"
function useHasMounted(): boolean {
const [hasMounted, setHasMounted] = useState<boolean>(false)
useEffect(() => {
setHasMounted(true)
}, [])
return hasMounted
}
export default useHasMounted
|
c52cdab5d3a581b3a2b6d53f63184b3f3a6a39f6
|
TypeScript
|
g00gle/crisp
|
/app/scripts/framework/framework.ts
| 2.8125
| 3
|
import { Entity } from '../shared/entity/entity';
export class Framework extends Entity {
/**
* Framework name
*/
public name: string;
/**
* Framework description
*/
public description?: string;
/**
* Creates new Framework object
*/
constructor(
name: string,
description: string = '',
id?: string,
date?: Date | string,
) {
super(id, date);
this.name = name;
this.description = description;
}
}
|
8b5adeb5bf2210c0dd3feab300c7674bcd581461
|
TypeScript
|
acacode/swagger-typescript-api
|
/tests/spec/discriminator/expected.ts
| 2.765625
| 3
|
/* eslint-disable */
/* tslint:disable */
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
export type SimpleDiscriminator = SimpleObject | ComplexObject;
export interface SimpleObject {
objectType: string;
}
export interface ComplexObject {
objectType: string;
}
export enum BlockDTOEnum {
Csv = "csv",
File = "file",
Kek = "kek",
}
export type BlockDTOWithEnum = BaseBlockDtoWithEnum &
(
| BaseBlockDtoWithEnumTypeMapping<BlockDTOEnum.Csv, CsvBlockWithEnumDTO>
| BaseBlockDtoWithEnumTypeMapping<BlockDTOEnum.File, FileBlockWithEnumDTO>
);
export type CsvBlockWithEnumDTO = BaseBlockDtoWithEnum & {
type: BlockDTOEnum.Csv;
text: string;
};
export type FileBlockWithEnumDTO = BaseBlockDtoWithEnum & {
type: BlockDTOEnum.File;
fileId: string;
};
export type BlockDTO = BaseBlockDto &
(BaseBlockDtoTypeMapping<"csv", CsvBlockDTO> | BaseBlockDtoTypeMapping<"file", FileBlockDTO>);
export type CsvBlockDTO = BaseBlockDto & {
/** @default "csv" */
type: "csv";
text: string;
};
export type FileBlockDTO = BaseBlockDto & {
/** @default "file" */
type: "file";
fileId: string;
};
export type Pet = BasePet &
(BasePetPetTypeMapping<"dog", Dog> | BasePetPetTypeMapping<"cat", Cat> | BasePetPetTypeMapping<"lizard", Lizard>);
export type PetOnlyDiscriminator =
| ({
pet_type: "dog";
} & Dog)
| ({
pet_type: "cat";
} & Cat)
| ({
pet_type: "lizard";
} & Lizard);
export type Cat = BasePet & {
name?: string;
};
export type Dog = BasePet & {
bark?: string;
};
export type Lizard = BasePet & {
lovesRocks?: boolean;
};
export enum PetEnum {
Dog = "dog",
Lizard = "lizard",
Cat = "cat",
}
export type PetWithEnum = BasePetWithEnum &
(
| BasePetWithEnumPetTypeMapping<PetEnum.Dog, DogWithEnum>
| BasePetWithEnumPetTypeMapping<PetEnum.Cat, CatWithEnum>
| BasePetWithEnumPetTypeMapping<PetEnum.Lizard, LizardWithEnum>
);
export type CatWithEnum = BasePetWithEnum & {
name?: string;
};
export type DogWithEnum = BasePetWithEnum & {
bark?: string;
};
export type LizardWithEnum = BasePetWithEnum & {
lovesRocks?: boolean;
};
export type InvalidDiscriminatorPropertyName = BaseInvalidDiscriminatorPropertyName &
(
| BaseInvalidDiscriminatorPropertyNameTypeMapping<"num", number>
| BaseInvalidDiscriminatorPropertyNameTypeMapping<"str", string>
);
/** kek pek */
export type Variant =
| ({
type: "update";
} & VariantUpdate)
| ({
type: "undo";
} & VariantUndo)
| ({
type: "rollback";
} & VariantRollback)
| ({
type: "scale";
} & VariantScale)
| ({
type: "resources";
} & VariantResources)
| ({
type: "firewall";
} & VariantFirewall)
| ({
type: "gateway";
} & VariantGateway);
/** Proposal to change firewall rules for deployment. */
export interface VariantFirewall {
/** asdasdasdasdasdsad added to deployment. If not set, no rules are added. */
rules_added?: string[];
/** asdasdasdasdasdsad removed from deployment. If not set, no rules were removed. */
rules_removed?: string[];
}
/** asdasdasdasdasd */
export interface VariantScale {
/**
* asdasdasdasdasdsad
* @example 3
*/
replicas: number;
}
/** asdasdasdasdasd */
export interface VariantResources {
resources: string;
}
/** asdasdasdasdasd */
export interface VariantGateway {
/** asdasdasdasdasdsad */
port?: string;
/** asdasdasdasdasdsad */
name?: string;
/** asdasdasdasdasdsad */
domain?: string;
}
/** Pasdasdasdasdasd. */
export type VariantUpdate = object;
/** asdasdasdasdasd */
export interface VariantRollback {
/**
* asdasdasdasdasdsad
* @example 42
*/
revision_id: number;
}
/** asdasdasdasdasdn */
export type VariantUndo = object;
interface BaseBlockDtoWithEnum {
title: string;
type: BlockDTOEnum;
}
type BaseBlockDtoWithEnumTypeMapping<Key, Type> = {
type: Key;
} & Type;
interface BaseBlockDto {
title: string;
}
type BaseBlockDtoTypeMapping<Key, Type> = {
type: Key;
} & Type;
interface BasePet {
pet_type: string;
}
type BasePetPetTypeMapping<Key, Type> = {
pet_type: Key;
} & Type;
interface BasePetWithEnum {
pet_type: PetEnum;
}
type BasePetWithEnumPetTypeMapping<Key, Type> = {
pet_type: Key;
} & Type;
type BaseInvalidDiscriminatorPropertyName = object;
type BaseInvalidDiscriminatorPropertyNameTypeMapping<Key, Type> = {
"@type": Key;
} & Type;
|
cb67f49c2382385ffd26174d76f471bc8f550a3f
|
TypeScript
|
delta94/ServiceHero
|
/servicehero-api/src/user/user.schema.ts
| 2.640625
| 3
|
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { UserType } from './types';
export type UserDocument = User & Document;
@Schema()
export class User {
id: string;
@Prop({type: String, required: true})
name: string;
@Prop({type: String, required: true, unique: true})
email: string;
@Prop({type: String, required: true })
password: string;
@Prop({type: String, required: true, enum: Object.keys(UserType)})
type: UserType;
@Prop({type: Number, required: false, min: 0, max: 5 })
rating?: number;
}
export const UserSchema = SchemaFactory.createForClass(User);
|
2a2f4b12677766eb5f2d7b99f22d9bdff4881d7e
|
TypeScript
|
TheDotLabs/todo-asana-action
|
/src/utils/utils.ts
| 3.0625
| 3
|
export function parseContent(content: string, createTask: (username: string, task: string) => void) {
let match;
const regExp: RegExp = /TODO\((?<username>\w+)\): (?<task>.*)/g;
while ((match = regExp.exec(content)) !== null) {
const username = match.groups?.username ?? "";
const task = match.groups?.task ?? "TBD";
createTask(username, task);
}
}
|
b8f035ec7ac29605e74816426e60d79c5b23b1a1
|
TypeScript
|
DarioDiGulio/Ajedrez
|
/ts/models/HTTPHelper.ts
| 3.15625
| 3
|
export enum HTTPHelper {
INFO = "info",
SUCCESS = "success",
WARNING = "warning",
ERROR = "errror",
GET = "GET",
HEAD = "HEAD",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
CONNECT = "CONNECT",
OPTIONS = "OPTIONS",
TRACE = "TRACE",
PATCH = "PATCH",
}
/**
* isMethodValid
* @param {string} method
* @returns {boolean}
*/
export function isMethodValid(method: string): boolean {
let isValid: boolean;
switch (method) {
case HTTPHelper.GET:
isValid = true;
break;
case HTTPHelper.HEAD:
isValid = true;
break;
case HTTPHelper.POST:
isValid = true;
break;
case HTTPHelper.PUT:
isValid = true;
break;
case HTTPHelper.DELETE:
isValid = true;
break;
case HTTPHelper.CONNECT:
isValid = true;
break;
case HTTPHelper.OPTIONS:
isValid = true;
break;
case HTTPHelper.TRACE:
isValid = true;
break;
case HTTPHelper.PATCH:
isValid = true;
break;
default:
isValid = false;
break;
}
if (isValid) {
return isValid;
} else {
throw new Error(`El método HTTP ${method} no es correcto.`);
}
}
/**
* isCodeValid
* @param {string} code
* @returns {boolean}
*/
export function isCodeValid(code: string): boolean {
let isValid: boolean;
switch (code) {
case HTTPHelper.ERROR:
isValid = true;
break;
case HTTPHelper.INFO:
isValid = true;
break;
case HTTPHelper.SUCCESS:
isValid = true;
break;
case HTTPHelper.WARNING:
isValid = true;
break;
default:
isValid = false;
break;
}
if (isValid) {
return isValid;
} else {
throw new Error(`El codigo de respuesta HTTP ${code} no es correcto.`);
}
}
export default HTTPHelper;
|
0ef9c2531050199f67d434212a52a5a0b15a5493
|
TypeScript
|
vdab-pierre/udemyAng
|
/ng4-complete-guide/src/app/shopping-list/shopping-list.service.ts
| 2.640625
| 3
|
import { Injectable, EventEmitter } from '@angular/core';
import { Ingredient } from '../shared/ingredient';
@Injectable()
export class ShoppingListService {
ingredientsChanged = new EventEmitter<Ingredient[]>();
private ingredients:Ingredient[]=[
new Ingredient("Apples",5),
new Ingredient("Tomatoes",10)
];
constructor() { }
getIngredients(){
return this.ingredients.slice();
}
addIngredient(ingr:Ingredient){
this.ingredients.push(ingr);
this.ingredientsChanged.emit(this.ingredients.slice());
}
}
|
b21c0130f49876104cb8cf58e88d06e2b37e6d79
|
TypeScript
|
rabelloo/lit
|
/src/store/createStore.ts
| 3.046875
| 3
|
import { CaseSetup } from './case-setup';
import { createSlice } from './createSlice';
import { Store } from './store';
import { Subscription } from './subscription';
import { MetaReducer, Reducer, Subscriber } from './types';
/**
* Creates a new `Store` for state that can be subscribed for changes
* and updated immutably by registering reducers
* and calling their respective dispatch functions.
* @param initialData Data to initialize the store with.
* @param metaReducers Optionally provide meta reducers,
* which run on every dispatch but have no effect on state.
* `logger()` available.
* @example
* createStore({ count: 0, name: '' }, logger())
*/
export function createStore<S extends {}>(
initialData: S,
...metaReducers: Array<MetaReducer<S, any>>
): Store<S> {
let store: S;
const types = new Set<string>();
const subscribers = new Set<Subscriber<S>>();
set({ ...initialData }, '[Core] initialize store');
return {
case: caseType,
slice: (property: keyof S) =>
createSlice({
getState: () => store,
property: property as any,
register,
setProp,
subscribe,
}),
subscribe,
};
function caseType(type: string): CaseSetup<S> {
return {
reduce: <P>(reducer: Reducer<S, P>) => {
register(type);
return (payload?: P) => set(reducer(store, payload), type, payload);
},
};
}
function register(type: string) {
if (types.has(type)) {
throw new Error(`Store already has registration of type (${type}).
Choose a different type and make sure you only call register() once per type.`);
}
types.add(type);
}
function set<P>(state: S, type: string, payload?: P) {
store = Object.freeze(state);
metaReducers.forEach(meta => meta(store, { type, payload }));
subscribers.forEach(subscriber => subscriber(store));
}
function setProp<K extends keyof S, P>(
prop: K,
propState: S[K],
type: string,
payload?: P
) {
set({ ...store, [prop]: Object.freeze(propState) }, type, payload);
}
function subscribe(subscriber: Subscriber<S>): Subscription {
subscribers.add(subscriber);
subscriber(store);
return {
unsubscribe: () => subscribers.delete(subscriber),
};
}
}
|
2457f8cb608b914990b855f8b79766c0175c2786
|
TypeScript
|
skmail/responsive-viewer
|
/src/utils/state.ts
| 2.53125
| 3
|
import platform from '../platform'
import { State } from '../reducers/app'
const STORAGE_KEY = 'APP_STATE'
export const loadState = async () => {
try {
const state = await platform.storage.local.get(STORAGE_KEY)
if (!state) {
return {}
}
return state
} catch (e) {
return {}
}
}
export const saveState = async (state: State) => {
await platform.storage.local.set({
[STORAGE_KEY]: state,
})
}
export const resetState = async () => {
await platform.storage.local.remove(STORAGE_KEY)
}
|
29e92141b6ab08b5757fe3db120518ee511a6c46
|
TypeScript
|
alexeyinkin/neural-tennis-js
|
/src/app/Color.ts
| 3.203125
| 3
|
export default class Color {
private readonly red: number;
private readonly green: number;
private readonly blue: number;
constructor (red: number, green: number, blue: number) {
this.red = red;
this.green = green;
this.blue = blue;
}
public getRgb(): string {
return `rgb(${this.red}, ${this.green}, ${this.blue})`;
}
public getRgba(alpha: number): string {
return `rgba(${this.red}, ${this.green}, ${this.blue}, ${alpha})`;
}
}
|
7ef6e007b38af0274ae34e593ee0088845682ee2
|
TypeScript
|
chrisxian/oshop
|
/src/app/model/shopping-cart.ts
| 2.96875
| 3
|
import { ShoppingCartItem } from "./shopping-cart-item";
import { Product } from ".";
export class ShoppingCart {
public items: ShoppingCartItem[] = [];
constructor(public id: string,
public dateCreated: string,
private itemsArray: { product: Product, quantity: number }[]) {
itemsArray?.forEach(x =>
this.items.push(new ShoppingCartItem(x.product, x.quantity)));
}
get totalItemsCount(): number {
let count = 0;
this.items?.forEach(item => count += item.quantity);
return count;
}
get totalPrice(): number {
let sum = 0;
this.items?.forEach(item => sum += item.totalPrice);
return sum;
}
getQuantity(product: Product) {
let item = this.items.find(x => x.product.id == product.id);
return item ? item.quantity : 0
}
}
|
613d0e967eddd180d4b968b5199dbb64458b26bd
|
TypeScript
|
bbrunocosta/WeDecode-backend-test
|
/src/infra/database/mongoose/adapters/spectatorRepository.adapter.spec.ts
| 2.71875
| 3
|
import MongooseHelper from '../mongoose.Helper'
import MongooseFilmRepositoryAdapter from './filmRepository.adapter'
import MongoSpectatorRepositoryAdapter from './spectatorRepository.adapter'
import env from '../../../../main/config/env'
describe('MongoSpectatorRepositoryAdapter', () => {
beforeAll(async () => {
await MongooseHelper.connect(env.mongoUri)
})
afterAll(async () => {
await MongooseHelper.disconnect()
})
beforeEach(async () => {
await MongooseHelper.dropCollection('spectators')
})
const fakeSpectatorRequest = {
name: 'Bruno'
}
const fakeSpectatorRequest2 = {
name: 'felipe'
}
const filmRepository = new MongooseFilmRepositoryAdapter()
const spectatorRepository = new MongoSpectatorRepositoryAdapter()
test('addSpectator should return a Spectator on sucess', async () => {
const result = await spectatorRepository.addSpectator(fakeSpectatorRequest)
expect(result.id).toBeTruthy()
expect(result.whatchedFilms.length).toBe(0)
})
test('getAll should return a list of Spectators', async () => {
await spectatorRepository.addSpectator(fakeSpectatorRequest)
await spectatorRepository.addSpectator(fakeSpectatorRequest2)
const result = await spectatorRepository.getAll()
expect(result.length).toBe(2)
})
test('getAll should return empty array if any Spectator was found', async () => {
const result = await spectatorRepository.getAll()
expect(result).toEqual([])
})
test('findOneById should return a Spectator if it exists', async () => {
const fake2 = await spectatorRepository.addSpectator(fakeSpectatorRequest2)
const fake = await spectatorRepository.addSpectator(fakeSpectatorRequest)
const result = await spectatorRepository.findOneById(fake.id)
const result2 = await spectatorRepository.findOneById(fake2.id)
expect(result).toBeTruthy()
expect(result?.name).toBe(fakeSpectatorRequest.name)
expect(result2).toBeTruthy()
expect(result2?.name).toBe(fakeSpectatorRequest2.name)
})
test('findOneById should return null if Spectator was not found', async () => {
const result3 = await spectatorRepository.findOneById('51bb793aca2ab77a3200000d')
expect(result3).toBeFalsy()
expect(result3).toBe(null)
})
test('findOneByName should return a Spectator if it exists', async () => {
await spectatorRepository.addSpectator(fakeSpectatorRequest2)
await spectatorRepository.addSpectator(fakeSpectatorRequest)
const result = await spectatorRepository.findOneByName('bruno')
if (result) {
expect(result.name).toBe('bruno')
}
})
test('findOneByName should return null if Spectator was not found', async () => {
await spectatorRepository.addSpectator(fakeSpectatorRequest2)
await spectatorRepository.addSpectator(fakeSpectatorRequest)
const result = await spectatorRepository.findOneByName('not regitered name')
expect(result).toBe(null)
})
test('addWhactchedFilm should add a filmId to whatedFilms array', async () => {
const film = await filmRepository.addFilm({
title: 'a title',
author: 'an author',
director: 'a director'
})
const film2 = await filmRepository.addFilm({
title: 'a title2',
author: 'an author2',
director: 'a director2'
})
const fakeSpectator = await spectatorRepository.addSpectator(fakeSpectatorRequest2)
const updatedSpectator = await spectatorRepository.addWatchedFilm(fakeSpectator.id, film.id)
expect(updatedSpectator?.whatchedFilms.length).toBe(1)
const updatedSpectator2 = await spectatorRepository.addWatchedFilm(fakeSpectator.id, film2.id)
expect(updatedSpectator2?.whatchedFilms.length).toBe(2)
})
test('addWhactchedFilm should return null if spectator is invalid', async () => {
const film = await filmRepository.addFilm({
title: 'a title',
author: 'an author',
director: 'a director'
})
const updatedSpectator2 = await spectatorRepository.addWatchedFilm('51bb793aca2ab77a3200000d', film.id)
expect(updatedSpectator2).toBeFalsy()
})
})
|
04a6afc41cf7f906652fbeacd1b5074fcdb1901b
|
TypeScript
|
sadri-fertani/slider
|
/src/app/slider-side.ts
| 2.609375
| 3
|
import { Component, AfterViewInit, ElementRef, Renderer2, ViewChild, HostListener } from '@angular/core';
export abstract class SliderSide {
public width: number;
public height: number;
@ViewChild('content')
public content: ElementRef;
@HostListener('mousedown', ['$event'])
onMousedown(event) {
// Arreter la propagation de l'évenemnt, pour éviter le déplacement du pointeur
event.stopPropagation();
}
constructor(public elementRef: ElementRef, public rendered: Renderer2) {
// R.A.S
}
ngAfterViewInit(): void {
let dimension = this.content.nativeElement.getBoundingClientRect();
this.width = dimension.width;
this.height = dimension.height;
// console.log('---------');
// console.log(this.constructor.name);
// console.log(dimension);
// console.log('---------');
}
setPosition(verticalDirection: boolean, offset: number) {
this.rendered.setStyle(this.content.nativeElement, verticalDirection ? 'top' : 'left', String(offset) + 'px');
}
setTranslatePosition(verticalDirection: boolean, offset: number): void {
if(!verticalDirection) {
this.rendered.setStyle(this.content.nativeElement, verticalDirection ? 'left' : 'top', '-' + Number(this.height + 10) + 'px');
}
this.rendered.setStyle(this.content.nativeElement, 'transform', verticalDirection ? 'translateY(' : 'translateX(' + String(offset) + 'px)');
}
}
|
609853db4a30e5298410aa759ae49f256bedec44
|
TypeScript
|
GalenWong/groundy
|
/test/backend/songstore/songstore.spec.ts
| 2.6875
| 3
|
import * as os from 'os';
import * as fs from 'fs';
import SongStore from '../../../app/backend/SongStore';
jest.mock('fs');
describe('songstore', () => {
it('getInstance', () => {
expect(SongStore.getInstance()).toBeInstanceOf(SongStore);
});
it('getStorageDirectory', () => {
const tempDir = os.tmpdir();
const s = SongStore.getInstance();
expect(() => {
s.getStorageDirectory();
}).toThrow();
s.setDirectory(tempDir);
expect(s.getStorageDirectory()).toEqual(tempDir);
expect(() => {
s.setDirectory('');
}).toThrow();
});
it('getWriteStream', () => {
const tempDir = os.tmpdir();
const s = SongStore.getInstance();
s.setDirectory(tempDir);
s.getWriteStream('dummy.txt');
expect(fs.createWriteStream).toHaveBeenCalled();
});
it('delete', () => {
const tempDir = os.tmpdir();
const s = SongStore.getInstance();
s.setDirectory(tempDir);
s.delete('dummy.txt');
expect(fs.unlink).toHaveBeenCalled();
});
it('getAllSongs', () => {
const tempDir = os.tmpdir();
const s = SongStore.getInstance();
s.setDirectory(tempDir);
s.getAllSongs();
expect(fs.readdir).toHaveBeenCalled();
});
});
|
a624a4ec66b38147682f8fc7332fcde14f44e8d1
|
TypeScript
|
martin-fabbri/webgl-playground
|
/react-webgl-viz/src/clientProcess/reactComponents/flowjo-vis/webgl/resource.test.ts
| 2.84375
| 3
|
import {
HTMLCanvasElementMock,
WebGL2RenderingContextMock
} from './../../../../../tests/webgl2-canvas-mock/index';
import { default as Resource, Handle, IResourceProps, uid } from './resource';
const canvas = new HTMLCanvasElementMock(100, 100);
const gl = new WebGL2RenderingContextMock(canvas);
// tslint:disable-next-line: max-classes-per-file
class TestResource extends Resource {
constructor(testGl: WebGL2RenderingContext, testProps: IResourceProps = {}) {
super(testGl, testProps);
}
protected createHandle() {
return gl.createVertexArray();
}
}
const testHandle: Handle = { id: 'test' };
describe('WebGL#Resouce', () => {
it('generates a new uid with default name prefix', () => {
const uid1 = uid();
expect(uid1).toContain('1');
const uid2 = uid();
expect(uid2).toContain('2');
const uid3 = uid();
expect(uid3).toContain('3');
});
it('generates a new uid prefixed with the provided name', () => {
const puid1 = uid('program');
expect(puid1).toContain('program');
expect(puid1).toContain('1');
const puid2 = uid('program');
expect(puid2).toContain('program');
expect(puid2).toContain('2');
});
it('creates a resource; assigns an uid, creates handle', () => {
const testResource1 = new TestResource(gl);
expect(testResource1).toBeInstanceOf(TestResource);
expect(testResource1.id).toContain('TestResource');
expect(testResource1.id).toContain('1');
expect(testResource1.handle).toBeDefined();
const testResource2 = new TestResource(gl);
expect(testResource2).toBeInstanceOf(TestResource);
expect(testResource2.id).toContain('TestResource');
expect(testResource2.id).toContain('2');
expect(testResource2.handle).toBeDefined();
});
it('creates a resource; assign handle passed in props', () => {
const testResource = new TestResource(gl, { handle: testHandle });
expect(testResource).toBeInstanceOf(TestResource);
expect(testResource.id).toContain('TestResource');
expect(testResource.handle).toBeDefined();
expect(testResource.handle).toBe(testHandle);
});
});
|
94c4b9e6160745aa96f1a0fb8f11787445d4d510
|
TypeScript
|
artsy/force
|
/src/Utils/color.ts
| 3.265625
| 3
|
export interface RGB {
r: number
g: number
b: number
}
export interface RGBA extends RGB {
a: number
}
export const stringifyRgba = (color: RGBA): string => {
return `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`
}
export const compareColors = (color1: RGBA, color2: RGBA): boolean => {
return (
color1.r === color2.r &&
color1.g === color2.g &&
color1.b === color2.b &&
color1.a === color2.a
)
}
export const adjustAlpha = (color: RGBA, alpha: number): RGBA => {
return { ...color, a: alpha }
}
export const hexToRgba = (value: string): RGBA => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(value)
if (!result) {
throw new Error(`Invalid input ${value}`)
}
return {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
a: 1,
}
}
export const BLACK: RGBA = { r: 0, g: 0, b: 0, a: 1 }
export const WHITE: RGBA = { r: 255, g: 255, b: 255, a: 1 }
export const getContrastTIQ = ({ r, g, b, a }: RGBA): RGBA => {
if (a === 0) return BLACK
const yiq = (r * 299 + g * 587 + b * 114) / 1000
return yiq >= 128 ? BLACK : WHITE
}
export const luminance = ({ r, g, b }: RGB): number => {
const a = [r, g, b].map(v => {
v /= 255
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4)
})
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722
}
export const getContrastRatio = (color1: RGBA, color2: RGBA): number => {
const l1 = luminance(rgbaToRgb(color1, color2))
const l2 = luminance(rgbaToRgb(color2, color1))
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05)
}
export const rgbaToRgb = (color: RGBA, background: RGBA): RGB => {
const alpha = color.a
const inverseAlpha = 1 - alpha
return {
r: Math.round(color.r * alpha + background.r * inverseAlpha),
g: Math.round(color.g * alpha + background.g * inverseAlpha),
b: Math.round(color.b * alpha + background.b * inverseAlpha),
}
}
|
881e542e260779904e0da68ce0780f1072fc8b43
|
TypeScript
|
mhsss/social
|
/src/api/profile-api.ts
| 2.59375
| 3
|
import {PhotosType, ProfileType} from "../types/types";
import {instance,APIResponseType} from "./api";
type SavePhotoResponseDataType = {
photos: PhotosType
}
export const profileAPI = {
getProfile(userId: number) {
return instance.get<ProfileType>(`profile/${userId}`).then(resp => resp.data)
},
getStatus(userId: number) {
return instance.get<string>(`profile/status/${userId}`).then(resp => resp.data)
},
updateStatus(status: string) {
return instance.put<APIResponseType>(`profile/status/`, {status}).then(resp => resp.data)
},
savePhoto(photos: any) {
let formData = new FormData()
formData.append('image', photos)
return instance.put<APIResponseType<SavePhotoResponseDataType>>(`profile/photo/`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
},
saveProfile(profile: ProfileType) {
return instance.put<APIResponseType>(`profile`, profile).then(resp => resp.data)
}
}
|
591925f689a1506a079616ed5741f3b3a9434f25
|
TypeScript
|
mswjs/msw
|
/src/utils/request/pruneGetRequestBody.test.ts
| 2.546875
| 3
|
/**
* @jest-environment jsdom
*/
import { pruneGetRequestBody } from './pruneGetRequestBody'
test('sets empty GET request body to undefined', () => {
const body = pruneGetRequestBody({
method: 'GET',
body: '',
})
expect(body).toBeUndefined()
})
test('preserves non-empty GET request body', () => {
const body = pruneGetRequestBody({
method: 'GET',
body: 'text-body',
})
expect(body).toBe('text-body')
})
test('ignores requests of the other method than GET', () => {
expect(
pruneGetRequestBody({
method: 'HEAD',
body: JSON.stringify({ a: 1 }),
}),
).toBe(JSON.stringify({ a: 1 }))
expect(
pruneGetRequestBody({
method: 'POST',
body: 'text-body',
}),
).toBe('text-body')
})
|
50ca9ac163fe19c8f660c14d4e358bda1817f4b0
|
TypeScript
|
retojs/comicvm-dom
|
/src/dom/Button.test.ts
| 2.890625
| 3
|
import { Button } from "./Button";
describe("Button", () => {
it("can be created with constructor", () => {
const btn = new Button(
"container",
"label",
(e: MouseEvent) => expect(e).toBeDefined(),
"style-class"
);
expect(btn).toBeDefined();
expect(btn.htmlElement).toBeDefined();
expect(btn.htmlElement.innerText).toBe("label");
expect(btn.htmlElement.classList).toContain("style-class");
btn.htmlElement.click();
});
it("can be created with config", () => {
const btn = Button.create({
container: "container",
label: "label",
onClick: (e: MouseEvent) => expect(e).toBeDefined(),
styleClass: "style-class"
});
expect(btn).toBeDefined();
expect(btn.htmlElement).toBeDefined();
expect(btn.htmlElement.innerText).toBe("label");
expect(btn.htmlElement.classList).toContain("style-class");
btn.htmlElement.click();
});
it("can be created without config", () => {
const btn = Button.create();
expect(btn).toBeDefined();
expect(btn.htmlElement).toBeDefined();
expect(btn.htmlElement.innerText).toBeUndefined();
});
it("can be created without constructor arguments", () => {
const btn = new Button();
expect(btn).toBeDefined();
expect(btn.htmlElement).toBeDefined();
expect(btn.htmlElement.innerText).toBeUndefined();
});
});
|
d6e61097ca0b9fc3b249d02264cde93f1c9d23d6
|
TypeScript
|
enco164/racun-sekvenata
|
/src/FormulaTree/Atom.ts
| 3.015625
| 3
|
import {Formula, FormulaType} from './Formula'
import {AtomicFormula} from './AtomicFormula'
import {Valuation} from './Valuation'
import {AtomSet} from "./AtomSet";
/**
* Atom
*/
export class Atom extends AtomicFormula {
private _varNum : string;
constructor(num: string) {
super();
this._varNum = num;
}
public get varNum() : string {
return this._varNum;
}
public set varNum(v : string) {
this._varNum = v;
}
public equals(f: Formula): boolean
{
return f.getType() === FormulaType.T_ATOM &&
(<Atom>f).varNum === this.varNum;
}
public getType(): FormulaType
{
return FormulaType.T_ATOM;
}
public getAtoms(atoms: AtomSet): void
{
atoms.add(this._varNum);
}
public evaluate(v: Valuation): boolean
{
return v.getValueOfAtom(this._varNum);
}
public toString = ():string => {
return this._varNum;
};
public print():void
{
console.log(this.toString());
}
}
|
4b4b02b7bb4a71f4f8b7fcb8d93d1ca9f8020c3a
|
TypeScript
|
spinlud/linkedin-jobs-scraper
|
/src/scraper/Scraper.ts
| 2.640625
| 3
|
import { EventEmitter } from "events";
import TypedEmitter from "typed-emitter";
import { IEventListeners } from "./events";
import { LaunchOptions, BrowserLaunchArgumentOptions, BrowserConnectOptions } from "puppeteer";
import { IQuery, IQueryOptions } from "./query";
import { logger } from "../logger/logger";
export type ScraperOptions = LaunchOptions & BrowserLaunchArgumentOptions & BrowserConnectOptions;
export abstract class Scraper extends (EventEmitter as new () => TypedEmitter<IEventListeners>) {
public options: ScraperOptions;
/**
* @constructor
* @param {LaunchOptions} options
*/
protected constructor(options: ScraperOptions) {
super();
this.options = options;
}
/**
* Enable logger
* @returns void
* @static
*/
public static enableLogger = () => logger.enable();
/**
* Disable logger
* @returns void
* @static
*/
public static disableLogger = () => logger.disable();
/**
* Enable logger debug namespace
* @returns void
* @static
*/
public static enableLoggerDebug = () => logger.enableDebug();
/**
* Enable logger info namespace
* @returns void
* @static
*/
public static enableLoggerInfo = () => logger.enableInfo();
/**
* Enable logger warn namespace
* @returns void
* @static
*/
public static enableLoggerWarn = () => logger.enableWarn();
/**
* Enable logger error namespace
* @returns void
* @static
*/
public static enableLoggerError = () => logger.enableError();
/**
* Run scraper
* @param {IQuery | IQuery[]} queries
* @param {IQueryOptions} [options]
* @return {Promise<void>}
*/
abstract run (queries: IQuery | IQuery[], options?: IQueryOptions): Promise<void>;
/**
* Close scraper browser instance
* @returns {Promise<void>}
*/
abstract close(): Promise<void>;
}
|
7846b87981127fe17e05eb730ec038ef65dc3b4e
|
TypeScript
|
rweda/status-site
|
/client/ts/modules/utility.ts
| 3.140625
| 3
|
import "bootstrap-notify";
/**
* Static class that provides useful utility methods.
*
* @export
* @class Utility
*/
export class Utility {
/**
* Returns properly formatted GET request query URL.
*
* @static
* @param {string} url - URL of the endpoint
* @param {...[string, string][]} parameters - set of tuples: param - value
* @returns {string} - proper URL for GET request
*
* @memberOf Utility
*/
public static generateQuery(url: string, ...parameters: [string, string][]): string {
let result = `${url}?`;
for (var param of parameters) {
result += `${param[0]}=${param[1]}&`;
}
if (result.charAt(result.length - 1) == '&') {
result.substr(0, result.length - 1);
}
return result;
}
/**
* GET request AJAX wrapper that works on promises
*
* @static
* @param {string} url - endpoint URL
* @returns {Promise<any>} - promise of get request result
*
* @memberOf Utility
*/
public static async get(url: string): Promise<any> {
return new Promise((resolve, reject) => {
$.ajax(url, {
type: "GET",
dataType: "json",
statusCode: {
204: (result) => { resolve([]) },
200: (result) => { resolve(result) }
},
error: (result) => { reject(result) }
});
});
}
/**
* DELETE request AJAX wrapper that works on promises
*
* @static
* @param {string} url - endpoint URL
* @param {*} data - request parameters
* @returns {Promise<any>} - promise of delete request result
*
* @memberOf Utility
*/
public static async delete(url: string, data: any): Promise<any> {
return new Promise((resolve, reject) => {
$.ajax(url, {
type: "DELETE",
data: data,
statusCode: {
200: (result) => { resolve(result) }
},
error: (result) => { reject(result) }
});
});
}
/**
* Converts .NET timestamp string to TS Date
*
* @static
* @param {string} dotNetDate - .NET formatted timestamp
* @returns {Date} - equivalent TS Date object
*
* @memberOf Utility
*/
public static toDate(dotNetDate: string): Date {
return new Date(Date.parse(dotNetDate));
}
/**
* Mutes thread for a time interval
*
* @static
* @param {number} time - time interval in milliseconds
* @returns {Promise<any>}
*
* @memberOf Utility
*/
public static async sleep(time: number): Promise<any> {
return new Promise(resolve => window.setTimeout(resolve, time));
}
/**
* Returns nicely looking string representing time.
* Example: 3:09:05 PM
*
* @static
* @param {Date} date - date to display
* @returns {string} - string representation of the date
*
* @memberOf Utility
*/
public static toHHMMSS(date: Date): string {
let hours = date.getHours();
let ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
let minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
return `${hours}:${minutes}:${seconds} ${ampm}`;
}
// http://stackoverflow.com/a/18330682/1644554
public static toLocalTimezone(date: Date): Date {
let newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
let offset = date.getTimezoneOffset() / 60;
let hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
public static fixUtcTime(): void {
$(".utc-time").each(function () {
$(this).text(
Utility.toHHMMSS(
Utility.toLocalTimezone(
new Date($(this).text())
)
)
);
});
}
public static toUtcDate(date : Date): number {
return Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
date.getUTCMilliseconds()
);
}
}
/**
* Static class that provides useful UI related methods.
*
* @export
* @class UIHelper
*/
export class UIHelper {
/**
* Triggers notification message in the UI.
* Uses "bootstrap-notify" library.
*
* @static
* @param {any} message
* @param {any} type
*
* @memberOf UIHelper
*/
public static notify(message, type) {
$.notify(
{
message: message
},
{
type: type,
allow_dismiss: true,
allow_duplicates: false,
timer: 1000,
placement: {
from: 'bottom',
align: 'left'
},
delay: 500,
animate: {
enter: 'animated fadeInUp',
exit: 'animated fadeOutDown'
},
offset: {
x: 30,
y: 30
}
}
);
};
}
|
ed109194684ffa0933a54826ddc015f977c04678
|
TypeScript
|
pmb0/express-sharp
|
/src/decorators.ts
| 3.34375
| 3
|
import 'reflect-metadata'
function makePropertyMapper<T, U>(
prototype: unknown,
key: string,
mapper: (value: U) => T,
) {
Object.defineProperty(prototype, key, {
enumerable: true,
set(value: U) {
Object.defineProperty(this, key, {
enumerable: true,
get() {
return Reflect.getMetadata(key, this) as T
},
set(value: U) {
Reflect.defineMetadata(key, mapper(value), this)
},
})
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
this[key] = value
},
})
}
export function Transform<T, U = string>(transformer: (value: U) => T) {
return function (target: unknown, key: string): void {
makePropertyMapper<T, U>(target, key, transformer)
}
}
export function ToNumber() {
return function (target: unknown, key: string): void {
makePropertyMapper(target, key, Number)
}
}
|
14f6ced5d856fbe92d68eb6107d8157cdab418b9
|
TypeScript
|
and-forks/opsmap-toolkit
|
/src/domain/csv/TKCSVReader.ts
| 2.578125
| 3
|
/* eslint-disable @typescript-eslint/no-explicit-any */
import { parse } from "papaparse";
// ////////////////////////////////////////////////////////////////////////////
// Temaplted Read method for csv inputs
// ////////////////////////////////////////////////////////////////////////////
export async function TKCSVRead<T>(
name: string,
folder: string,
header: boolean
): Promise<T> {
return new Promise((resolve, reject) => {
parse(`${process.env.BASE_URL}/${folder}/${name}.csv`, {
header: header,
download: true,
encoding: "utf-8",
skipEmptyLines: true,
complete(results: any) {
// ? ParseResult<T> ?
resolve(results.data);
},
error(err) {
reject(err);
}
});
});
}
|
d3630a02ce02fb996cfd1857e26e656b38f93163
|
TypeScript
|
cwondany/uke-tabs-creator
|
/src/app/tab-creation/chord.model.ts
| 2.734375
| 3
|
export class Chord {
public gNote: string;
public cNote: string;
public aNote: string;
public eNote: string;
constructor(gNote, cNote, aNote, eNote) {
this.gNote = gNote;
this.cNote = cNote;
this.aNote = aNote;
this.eNote = eNote;
}
}
|