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
|
|---|---|---|---|---|---|---|
1f11f1865d65e1246e2824cabaa87da73c55247c
|
TypeScript
|
KelvinMitaki/Fullstack-GraphQL-Typescript
|
/Schema/Mutation.ts
| 2.515625
| 3
|
import { Request } from "express";
import bcrypt from "bcrypt";
import {
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLString
} from "graphql";
import { User } from "../model/User";
import { UserType } from "./User";
declare module "express-session" {
export interface Session {
user?: { email: string; _id: string };
}
}
const mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
signup: {
type: UserType,
args: {
email: { type: new GraphQLNonNull(GraphQLString) },
password: { type: new GraphQLNonNull(GraphQLString) }
},
async resolve(parent, args, ctx: Request) {
const emailExist = await User.findOne({ email: args.email });
if (emailExist) {
throw new Error("email already exists");
}
args.password = await bcrypt.hash(args.password, 10);
const user = User.build({
email: args.email,
password: args.password
});
await user.save();
// @ts-ignore
ctx.session.user = user;
return user;
}
},
login: {
type: UserType,
args: {
email: { type: new GraphQLNonNull(GraphQLString) },
password: { type: new GraphQLNonNull(GraphQLString) }
},
async resolve(parent, args, ctx: Request) {
const user = await User.findOne({ email: args.email });
if (!user) {
throw new Error("Invalid email or password");
}
const isMatch = await bcrypt.compare(args.password, user.password);
if (!isMatch) {
throw new Error("Invalid email or password");
}
ctx.session.user = user as typeof ctx.session.user;
return user;
}
},
logout: {
type: UserType,
async resolve(parent, args, ctx: Request) {
const user = ctx.session.user;
ctx.session.destroy(err => (err ? console.log(err) : null));
return user;
}
}
}
});
export { mutation };
|
42121e69e3fbf00b02ec2839e76c53f0db691f37
|
TypeScript
|
pamplonafala/tstl
|
/src/std/base/containers/_ListContainer.ts
| 3.234375
| 3
|
/// <reference path="../../API.ts" />
/// <reference path="Container.ts" />
namespace std.base
{
/**
* @hidden
*/
export abstract class _ListContainer<T, BidirectionalIterator extends _ListIteratorBase<T>>
extends Container<T>
implements IDequeContainer<T>
{
/**
* @hidden
*/
private begin_: BidirectionalIterator;
/**
* @hidden
*/
private end_: BidirectionalIterator;
/**
* @hidden
*/
private size_: number;
/* ---------------------------------------------------------
CONSTRUCTORS
--------------------------------------------------------- */
/**
* Default Constructor.
*/
protected constructor()
{
super();
// INIT MEMBERS
this.end_ = this._Create_iterator(null, null, null);
this.end_["prev_"] = this.end_;
this.end_["next_"] = this.end_;
this._Set_begin(this.end_);
this.size_ = 0;
}
/**
* @hidden
*/
protected abstract _Create_iterator(prev: BidirectionalIterator, next: BidirectionalIterator, val: T): BidirectionalIterator;
/**
* @hidden
*/
protected _Set_begin(it: BidirectionalIterator): void
{
this.begin_ = it;
}
/**
* @inheritdoc
*/
public assign<U extends T, InputIterator extends Iterator<U>>
(first: InputIterator, last: InputIterator): void
{
this.clear();
this.insert(this.end(), first, last);
}
/**
* @inheritdoc
*/
public clear(): void
{
// DISCONNECT NODES
this._Set_begin(this.end_);
this.end_["prev_"] = (this.end_);
this.end_["next_"] = (this.end_);
// RE-SIZE -> 0
this.size_ = 0;
}
/* ---------------------------------------------------------
ACCESSORS
--------------------------------------------------------- */
/**
* @inheritdoc
*/
public begin(): BidirectionalIterator
{
return this.begin_;
}
/**
* @inheritdoc
*/
public end(): BidirectionalIterator
{
return this.end_;
}
/**
* @inheritdoc
*/
public size(): number
{
return this.size_;
}
/**
* @inheritdoc
*/
public front(): T;
/**
* @inheritdoc
*/
public front(val: T): void;
public front(val: T = null): T | void
{
if (val == null)
return this.begin_.value;
else
this.begin_["value_"] = val;
}
/**
* @inheritdoc
*/
public back(): T;
/**
* @inheritdoc
*/
public back(val: T): void;
public back(val: T = null): T | void
{
let it: _ListIteratorBase<T> = this.end().prev();
if (val == null)
return it.value;
else
it["value_"] = val;
}
/* =========================================================
ELEMENTS I/O
- PUSH & POP
- INSERT
- ERASE
- POST-PROCESS
============================================================
PUSH & POP
--------------------------------------------------------- */
/**
* @inheritdoc
*/
public push_front(val: T): void
{
this.insert(this.begin_, val);
}
/**
* @inheritdoc
*/
public push_back(val: T): void
{
this.insert(this.end_, val);
}
/**
* @inheritdoc
*/
public pop_front(): void
{
this.erase(this.begin_);
}
/**
* @inheritdoc
*/
public pop_back(): void
{
this.erase(this.end_.prev() as BidirectionalIterator);
}
/* ---------------------------------------------------------
INSERT
--------------------------------------------------------- */
/**
* @inheritdoc
*/
public push(...items: T[]): number
{
if (items.length == 0)
return this.size();
// INSERT BY RANGE
let first: _NativeArrayIterator<T> = new _NativeArrayIterator<T>(items, 0);
let last: _NativeArrayIterator<T> = new _NativeArrayIterator<T>(items, items.length);
this._Insert_by_range(this.end(), first, last);
// RETURN SIZE
return this.size();
}
/**
* Insert an element.
*
* The container is extended by inserting a new element before the element at the specified
* <i>position</i>. This effectively increases the {@link List.size List size} by the amount of elements
* inserted.
*
* Unlike other standard sequence containers, {@link List} is specifically designed to be efficient
* inserting and removing elements in any position, even in the middle of the sequence.
*
* @param position Position in the container where the new element is inserted.
* {@link iterator}> is a member type, defined as a
* {@link ListIterator bidirectional iterator} type that points to elements.
* @param val Value to be inserted as an element.
*
* @return An iterator that points to the newly inserted element; <i>val</i>.
*/
public insert(position: BidirectionalIterator, val: T): BidirectionalIterator;
/**
* Insert elements by repeated filling.
*
* The container is extended by inserting a new element before the element at the specified
* <i>position</i>. This effectively increases the {@link List.size List size} by the amount of elements
* inserted.
*
* Unlike other standard sequence containers, {@link List} is specifically designed to be efficient
* inserting and removing elements in any position, even in the middle of the sequence.
*
* @param position Position in the container where the new elements are inserted. The {@link iterator} is a
* member type, defined as a {@link ListIterator bidirectional iterator} type that points to
* elements.
* @param size Number of elements to insert.
* @param val Value to be inserted as an element.
*
* @return An iterator that points to the first of the newly inserted elements.
*/
public insert(position: BidirectionalIterator, size: number, val: T): BidirectionalIterator;
/**
* Insert elements by range iterators.
*
* The container is extended by inserting a new element before the element at the specified
* <i>position</i>. This effectively increases the {@link List.size List size} by the amount of elements
* inserted.
*
* Unlike other standard sequence containers, {@link List} is specifically designed to be efficient
* inserting and removing elements in any position, even in the middle of the sequence.
*
* @param position Position in the container where the new elements are inserted. The {@link iterator} is a
* member type, defined as a {@link ListIterator bidirectional iterator} type that points to
* elements.
* @param begin An iterator specifying range of the begining element.
* @param end An iterator specifying range of the ending element.
*
* @return An iterator that points to the first of the newly inserted elements.
*/
public insert<U extends T, InputIterator extends Iterator<U>>
(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator;
public insert(...args: any[]): BidirectionalIterator
{
let ret: BidirectionalIterator;
// BRANCHES
if (args.length == 2)
ret = this._Insert_by_repeating_val(args[0], 1, args[1]);
else if (args.length == 3 && typeof args[1] == "number")
ret = this._Insert_by_repeating_val(args[0], args[1], args[2]);
else
ret = this._Insert_by_range(args[0], args[1], args[2]);
// RETURNS
return ret;
}
/**
* @hidden
*/
private _Insert_by_repeating_val(position: BidirectionalIterator, n: number, val: T): BidirectionalIterator
{
let first: base._Repeater<T> = new base._Repeater<T>(0, val);
let last: base._Repeater<T> = new base._Repeater<T>(n);
return this._Insert_by_range(position, first, last);
}
/**
* @hidden
*/
protected _Insert_by_range<U extends T, InputIterator extends Iterator<U>>
(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator
{
// INVALID ITERATOR
if (this != position["source_"])
throw new InvalidArgument("Parametric iterator is not this container's own.");
let prev: BidirectionalIterator = <BidirectionalIterator>position.prev();
let first: BidirectionalIterator = null;
let size: number = 0;
for (let it = begin; it.equals(end) == false; it = it.next() as InputIterator)
{
// CONSTRUCT ITEM, THE NEW ELEMENT
let item: BidirectionalIterator = this._Create_iterator(prev, null, it.value);
if (size == 0)
first = item;
// PLACE ITEM ON THE NEXT OF "PREV"
prev["next_"] = item;
// SHIFT CURRENT ITEM TO PREVIOUS
prev = item;
size++;
}
// WILL FIRST BE THE BEGIN?
if (position.equals(this.begin()) == true)
this._Set_begin(first);
// CONNECT BETWEEN LAST AND POSITION
prev["next_"] = position;
position["prev_"] = prev;
this.size_ += size;
return first;
}
/* ---------------------------------------------------------
ERASE
--------------------------------------------------------- */
/**
* Erase an element.
*
* Removes from the {@link List} either a single element; <i>position</i>.
*
* This effectively reduces the container size by the number of element removed.
*
* Unlike other standard sequence containers, {@link List} objects are specifically designed to be
* efficient inserting and removing elements in any position, even in the middle of the sequence.
*
* @param position Iterator pointing to a single element to be removed from the {@link List}.
*
* @return An iterator pointing to the element that followed the last element erased by the function call.
* This is the {@link end end()} if the operation erased the last element in the sequence.
*/
public erase(position: BidirectionalIterator): BidirectionalIterator;
/**
* Erase elements.
*
* Removes from the {@link List} container a range of elements.
*
* This effectively reduces the container {@link size} by the number of elements removed.
*
* Unlike other standard sequence containers, {@link List} objects are specifically designed to be
* efficient inserting and removing elements in any position, even in the middle of the sequence.
*
* @param begin An iterator specifying a range of beginning to erase.
* @param end An iterator specifying a range of end to erase.
*
* @return An iterator pointing to the element that followed the last element erased by the function call.
* This is the {@link end end()} if the operation erased the last element in the sequence.
*/
public erase(begin: BidirectionalIterator, end: BidirectionalIterator): BidirectionalIterator;
public erase(first: BidirectionalIterator, last: BidirectionalIterator = first.next() as BidirectionalIterator): BidirectionalIterator
{
return this._Erase_by_range(first, last);
}
/**
* @hidden
*/
protected _Erase_by_range(first: BidirectionalIterator, last: BidirectionalIterator): BidirectionalIterator
{
// FIND PREV AND NEXT
let prev: BidirectionalIterator = <BidirectionalIterator>first.prev();
// CALCULATE THE SIZE
let size: number = distance(first, last);
// SHRINK
prev["next_"] = (last);
last["prev_"] = (prev);
this.size_ -= size;
if (first.equals(this.begin_))
this._Set_begin(last);
return last;
}
/* ---------------------------------------------------------
SWAP
--------------------------------------------------------- */
/**
* Swap content.
*
* Exchanges the content of the container by the content of <i>obj</i>, which is another
* {@link List container} object with same type of elements. Sizes and container type may differ.
*
* After the call to this member function, the elements in this container are those which were in <i>obj</i>
* before the call, and the elements of <i>obj</i> are those which were in this. All iterators, references and
* pointers remain valid for the swapped objects.
*
* Notice that a non-member function exists with the same name, {@link swap swap}, overloading that
* algorithm with an optimization that behaves like this member function.
*
* @param obj Another {@link List container} of the same type of elements (i.e., instantiated
* with the same template parameter, <b>T</b>) whose content is swapped with that of this
* {@link List container}.
*/
public swap(obj: _ListContainer<T, BidirectionalIterator>): void
/**
* @inheritdoc
*/
public swap(obj: Container<T>): void;
public swap(obj: _ListContainer<T, BidirectionalIterator> | Container<T>): void
{
if (obj instanceof _ListContainer)
{
[this.begin_, obj.begin_] = [obj.begin_, this.begin_];
[this.end_, obj.end_] = [obj.end_, this.end_];
[this.size_, obj.size_] = [obj.size_, this.size_];
}
else
super.swap(obj);
}
}
}
|
744df27a0e6eddb7003e9ca84b90af9ba39e5d9f
|
TypeScript
|
mister-what/ex-patterns
|
/test/flowStructures/suppose.test.ts
| 2.921875
| 3
|
/* eslint-disable no-unused-vars */
/* eslint-disable no-unused-expressions */
/* eslint-disable indent */
/* eslint-disable func-call-spacing */
/* eslint-disable no-spaced-func */
/* eslint-disable no-unexpected-multiline */
/* eslint-disable arrow-parens */
/* eslint-disable operator-linebreak */
import { expect } from 'chai';
import { suppose, then, end, otherwise, _, R, S, A, B, C, D, E, F, G, V } from '../../src';
describe('the suppose function: base cases', () => {
it('should execute the then clause if the suppose clause matches (1)', () => {
const result =
suppose
(1, () => 1)
(then)
(() => 'success')
(otherwise)
(_, () => 'no success')
(end);
expect(result).to.deep.equal('success');
});
it('should execute the then clause if the suppose clause matches (2)', () => {
const result =
suppose
(1, () => 1)
(2, () => 2)
(then)
(() => 'success')
(otherwise)
(_, () => 'no success')
(end);
expect(result).to.deep.equal('success');
});
it('should execute the then clause if the suppose clause matches (3)', () => {
const result =
suppose
(1, () => 1)
(2, () => 2)
(3, () => 3)
(then)
(() => 'success')
(otherwise)
(_, () => 'no success')
(end);
expect(result).to.deep.equal('success');
});
it('should pipe matches through the suppose clauses (1)', () => {
const result =
suppose
(A, () => 1)
(1, ({ A }) => A)
(1, ({ A }) => A)
(then)
(() => 'success')
(otherwise)
(_, () => 'no success')
(end);
expect(result).to.deep.equal('success');
});
it('should pipe matches through the suppose clauses (2)', () => {
const result =
suppose
(A, () => 1)
(B, ({ A }) => A + 1)
([1, 2], ({ A, B }) => [A, B])
(then)
(() => 'success')
(otherwise)
(_, () => 'no success')
(end);
expect(result).to.deep.equal('success');
});
it('should pipe matches to the then clause', () => {
const result =
suppose
(A, () => 1)
(B, ({ A }) => A + 1)
([1, 2, C], ({ A, B }) => [A, B, 3])
(then)
(({ A, B, C }) => [A, B, C])
(otherwise)
(_, () => 'no success')
(end);
expect(result).to.deep.equal([1, 2, 3]);
});
it('should work with parent capturing', () => {
const result =
suppose
(A({ name: 'foo' }), () => ({ name: 'foo', id: '123' }))
(A, ({ A }) => A)
(then)
(({ A }) => A)
(otherwise)
(_, () => 'no success')
(end);
expect(result).to.deep.equal({ name: 'foo', id: '123' });
});
it('should catch if suppose clause does not match', () => {
const result =
suppose
(2, () => 1)
(then)
(() => 'success')
(otherwise)
(_, () => 'no success')
(end);
expect(result).to.deep.equal('no success');
});
it('should pipe result of first non-matching suppose clause to otherwise clauses', () => {
const result =
suppose
(2, () => 1)
(then)
(() => 'success')
(otherwise)
(1, () => 'got it!')
(_, () => 'no success!')
(end);
expect(result).to.deep.equal('got it!');
});
it('should throw if second argument in suppose clause is not a function', () => {
const func = () => (
suppose
(2, 'not a function')
(then)
(() => 'success')
(otherwise)
(1, () => 'got it!')
(_, () => 'no success!')
(end)
);
expect(func).to.throw(Error);
});
it('should return happy path result if called with end and all clauses matched', () => {
const result = (
suppose
(A, () => 1)
(then)
(({ A }) => A + 1)
(end)
);
expect(result).to.deep.equal(2);
});
it('should throw if called with end of happy path and not all clauses matched', () => {
const func = () => (
suppose
(2, () => 1)
(then)
(({ A }) => A + 1)
(end)
);
expect(func).to.throw(Error);
});
it('should throw if called with end prematurely', () => {
const func = () => (
suppose
(2, () => 1)
(end)
);
expect(func).to.throw(Error);
});
it('should throw if then clause is not a function', () => {
const func = () => (
suppose
(2, () => 2)
(then)
('not a function')
(otherwise)
(1, () => 'got it!')
(_, () => 'no success!')
(end)
);
expect(func).to.throw(Error);
});
});
|
47952a0be895776d1c3027096e99b3e8e9fadeaf
|
TypeScript
|
dmarquez83/ecommerce
|
/src/modules/files/images.service.ts
| 2.921875
| 3
|
const sharp = require('sharp');
export class ImageServices {
/**
* Compress image JPEG or JPG, change quality 40% and reduce 40% pixels
* @param file Image to compress
*/
async compressJPEGorJPG(file: any) {
const metaData = await sharp(file.buffer)
.metadata();
return await sharp(file.buffer)
.resize(Math.trunc(Number(metaData.width * 0.60)),
Math.trunc(Number(metaData.height * 0.60)))
.median()
.jpeg({
quality: 40,
progressive: true,
trellisQuantisation: true,
force: false,
})
.toBuffer({ resolveWithObject: true })
.catch(err => {
console.log('err', err);
});
}
/**
* Compression handle by mimetype
* @param mimeType mime type of image
* @param file Image to compress
*/
async sharpHandle(file: any) {
const sizeInMB = file.size / Math.pow(1024, 2);
if (sizeInMB < 3) {
return file;
}
return this.compressJPEGorJPG(file);
}
}
|
e11a08de1740a0e417aa280251a04b4b428de744
|
TypeScript
|
PepVal/drawing-app
|
/src/index.ts
| 2.734375
| 3
|
import express from "express";
import path from "path";
import nanoid from "nanoid";
import { Room, Player, GameState, CurrentTurn } from "./types";
var start_game = require("./gameLoop.ts");
const app = express();
//Listen on port 3000
let server = app.listen(process.env.PORT || 3000);
console.log("Listening on port " + (process.env.PORT || 3000));
// game constants
const MAX_PLAYERS: number = 5;
let gameState: GameState = {
rooms: [],
};
//socket.io instantiation
const io = require("socket.io")(server);
//listen on every connection
io.on("connection", (socket: any) => {
// USER
console.log("New player connected");
socket.on("join_public_room", async (data: any) => {
try {
let rooms: Room[] = gameState.rooms;
//join public room with public type, only takes username
// check if public, has less than MAX_PLAYERS and same language
var joiner = data.player;
console.log("Esto es rooms length: " + rooms.length);
let found_room: any = rooms.find(function(room: Room) {
return (
room &&
room.type == "public" &&
room.language == data.locale &&
room.players.length < MAX_PLAYERS
);
});
if (found_room != undefined) {
let room: Room = found_room;
let new_joiner_name = joiner;
// if player has same name as other player in room, concatenate room_index to name
// as many times as necessary, to make it unique
for (let i = 0; i < room.players.length; i++) {
if (room.players[i].username == new_joiner_name) {
new_joiner_name += "-" + rooms.length;
}
}
let new_player: Player = {
username: new_joiner_name,
score: 0,
points_gained: 0,
};
found_room.players.push(new_player);
// send to client new player list with new player inside
socket.join(room.index);
socket.username = new_joiner_name;
socket.room_index = room.index;
socket.isInRoom = true;
io.in(room.index).emit("joined_room", {
players: room.players,
});
socket.emit("user_join", {
id: room.index,
original_joiner_name: joiner,
new_joiner_name: new_joiner_name,
players: room.players,
painter: room.players[room.painter_index].username,
word: room.current_turn.word.length,
});
io.in(room.index).emit("chat_evt", {
evt_type: "player_joined",
username: new_joiner_name,
});
} else {
// create new public room and join in the first player
// start the game with rounds
let randomid = nanoid();
let room: Room = {
index: randomid,
type: "public",
language: data.locale,
current_round: 1,
painter_index: 0,
current_turn: {
word: "",
painter_left: false,
num_reports: 0,
is_canceled: false,
countdown: 0,
revealed: [],
guessed: [],
},
players: [
{
username: joiner,
score: 0,
points_gained: 0,
},
],
};
console.log("this is room index now: " + room.index);
rooms.push(room);
// Setting socket variables:
socket.join(room.index);
socket.username = joiner;
socket.room_index = room.index;
socket.isInRoom = true;
socket.is_waiting_next_round = true;
io.in(room.index).emit("joined_room", {
players: room.players,
});
socket.emit("user_join", {
id: room.index,
original_joiner_name: joiner,
new_joiner_name: joiner,
players: room.players,
});
io.in(room.index).emit("chat_evt", {
evt_type: "player_joined",
username: joiner,
});
// the first player to join will start the game loop
await start_game(io, gameState, room.index);
}
} catch (e) {
console.log("Error joining player");
console.log(e);
}
});
//drawing
socket.on("drawing", (data: any) => {
let room: any = gameState.rooms.find((r: Room) => {
return r.index == socket.room_index;
});
let painter = room.players.findIndex((p: Player) => {
return p.username === socket.username;
});
if (painter == room.painter_index) {
io.in(socket.room_index).emit("drawing", data);
}
});
//chat messages
socket.on("new_message", (data: any) => {
let room: any = gameState.rooms.find((r: any) => {
return r.index == socket.room_index;
});
let word = room.current_turn.word;
let has_already_guessed = room.current_turn.guessed.find(function(
already_guessed: Player
) {
return already_guessed.username == socket.username;
});
let player_index = room.players.findIndex(function(element: Player) {
return element.username == socket.username;
});
if (data.message.includes(word) && word != "") {
if (
!has_already_guessed &&
socket.username != room.players[room.painter_index].username
) {
// change score
if (room.current_turn.countdown !== 0) {
room.players[player_index].score += room.current_turn.countdown;
room.players[room.painter_index].score += 5;
room.players[player_index].points_gained +=
room.current_turn.countdown;
room.players[room.painter_index].points_gained += 5;
room.current_turn.guessed.push({
username: socket.username,
});
io.in(socket.room_index).emit("score_change", {
players: room.players,
});
io.in(socket.room_index).emit("chat_evt", {
username: socket.username,
evt_type: "guessed_word",
});
}
}
} else {
//broadcast the new message to others if it doesn't match word (in the same room).
io.in(socket.room_index).emit("new_message", {
message: data.message,
username: data.username,
});
}
});
socket.on("choose_word", (data: any) => {
let room: any = gameState.rooms.find((r: any) => {
return r.index == socket.room_index;
});
// must be valid index
if (data.option_index >= 0 && data.option_index <= 3) {
room.current_turn.word = room.current_turn.options[data.option_index];
}
});
socket.on("chat_evt", (data: any) => {
io.in(socket.room_index).emit("chat_evt", data);
});
socket.on("clear_canvas", () => {
io.in(socket.room_index).emit("clear_canvas");
});
socket.on("disconnect", function() {
let rooms = gameState.rooms;
let room_index = socket.room_index;
let room: any = rooms.find((r: any) => {
return r.index == socket.room_index;
});
console.log(
"someone left: " +
socket.username +
" room id: " +
socket.room_index +
" isInroom: " +
socket.isInRoom +
" room_index: " +
socket.room_index
);
if (socket && socket.isInRoom && room) {
let arrIndex = rooms.findIndex((r: Room) => {
return r.index == socket.room_index;
});
if (room.players.length - 1 == 0) {
// borrar toda la sala directamente
rooms.splice(arrIndex, 1);
io.in(room_index).emit("left_room", {
players: [],
});
socket.isInRoom = false;
socket.leave(room_index);
console.log(
"Room #ID: " +
room_index +
" has been removed from database for no players are inside."
);
console.log("This is gamestate: ");
console.log(gameState);
} else {
// borrar solo ese jugador
let player_gone = room.players.findIndex((p: Player) => {
return p.username === socket.username;
});
if (player_gone == room.painter_index) {
room.current_turn.painter_left = true;
}
room.players.splice(player_gone, 1);
console.log("This is gamestate: ");
console.log(gameState);
socket.isInRoom = false;
socket.leave(room_index);
io.in(room_index).emit("left_room", {
players: room.players,
});
io.in(room_index).emit("chat_evt", {
evt_type: "player_left",
username: socket.username,
});
}
}
});
});
|
2b3c3a3be63a910fb3fbd039806b79c85ab372df
|
TypeScript
|
hanuz06/Miscellaneous
|
/ts-kata/roman-numerals.ts
| 3.609375
| 4
|
function solution(roman: string): number {
// complete the solution by transforming the
// string roman numeral into an integer
interface romanNumbers {
[key: string]: number;
}
let result: number = 0;
const romanNumbers: romanNumbers = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
if (roman === 'IV'){
result += 4;
} else if (roman === 'IX'){
result += 9;
} else {
roman.split("").map((i: string) => {
for (const key in romanNumbers) {
if (i === key) {
result += romanNumbers[key];
}
}
});
}
console.log('FINAL ', result);
return result;
}
solution("IV"); //4)
// solution("IX"); //9)
// solution("XXI"); //21)
// solution("MMVIII"); //2008
// solution("MDCLXVI"); //1666
|
5e59ee4a31c3347f373f35b4f70693474d7a3f25
|
TypeScript
|
Kunstmaan/snipsonian
|
/packages/snipsonian-core/src/url/appendUrlParamIfNotAlready.ts
| 2.78125
| 3
|
import appendUrlParam, { encodeParamName, IAppendUrlParamInput } from './appendUrlParam';
export default function appendUrlParamIfNotAlready({
url,
paramName,
paramValue,
}: IAppendUrlParamInput): string {
if (doesUrlContainParam({ url, paramName })) {
return url;
}
return appendUrlParam({ url, paramName, paramValue });
}
function doesUrlContainParam({ url, paramName }: { url: string; paramName: string }): boolean {
const encodedParamName = encodeParamName(paramName);
return url.search(new RegExp(`[\\?&]${encodedParamName}=`)) > -1;
}
|
9c0d471f784953cf3ff848f82f0d5305f90f48e0
|
TypeScript
|
diegocastreje/Restaurante
|
/restaurante-app/src/app/mesas/mesa/mesa.ts
| 2.515625
| 3
|
import { MesaProductos } from './mesa-productos';
export class Mesa {
id: number;
fecha: string;
productos: MesaProductos[] = [];
total: number;
calcularTotal(): number{
this.total = 0;
this.productos.forEach((item: MesaProductos) =>{
this.total += item.calcularImporte();
});
return this.total;
}
}
|
ce8c85b84595e86382e86848042edbb8c43231ac
|
TypeScript
|
Ollererr/redux-model
|
/packages/core/src/utils/shallowEqual.ts
| 3.421875
| 3
|
const own = Object.prototype.hasOwnProperty;
const str = Object.prototype.toString;
const equal = (x: any, y: any) => {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
}
// NaN !== NaN
return x !== x && y !== y;
};
export const shallowEqual = (objA: any, objB: any) => {
if (equal(objA, objB)) {
return true;
}
if (
objA === null ||
objB === null ||
typeof objA !== 'object' ||
typeof objB !== 'object'
) {
return false;
}
// The map and set are different from plain object, Object.key(map) always returns [].
switch (str.call(objA)) {
case '[object Map]':
case '[object Set]':
case '[object WeakMap]':
case '[object WeakSet]':
return false;
}
// For plain object
const keys = Object.keys(objA), keysLen = keys.length;
if (keysLen !== Object.keys(objB).length) {
return false;
}
for (let i = 0; i < keysLen; ++i) {
const key = keys[i];
if (!own.call(objB, key) || !equal(objA[key], objB[key])) {
return false;
}
}
return true;
};
|
4f8c10a66f3bb04a7e83776bf56850f7bd995615
|
TypeScript
|
taurus-77/rarible-lazymint
|
/src/lazy-mint/domain.ts
| 2.578125
| 3
|
type Part = {
account: string
value: string
}
type ERC721LazyMint = {
"@type": "ERC721",
contract: string,
tokenId: string,
uri: string,
creators: Part[],
royalties: Part[],
signatures: string[]
}
type ERC1155LazyMint = {
"@type": "ERC1155",
contract: string,
tokenId: string,
uri: string,
creators: Part[],
royalties: Part[],
supply: string,
signatures: string[]
}
export type LazyMint = ERC721LazyMint | ERC1155LazyMint
export const ERC721Types = {
Part: [
{name: 'account', type: 'address'},
{name: 'value', type: 'uint96'}
],
Mint721: [
{name: 'tokenId', type: 'uint256'},
{name: 'tokenURI', type: 'string'},
{name: 'creators', type: 'Part[]'},
{name: 'royalties', type: 'Part[]'}
]
};
export const ERC1155Types = {
Part: [
{name: 'account', type: 'address'},
{name: 'value', type: 'uint96'}
],
Mint1155: [
{name: 'tokenId', type: 'uint256'},
{name: 'supply', type: 'uint256'},
{name: 'tokenURI', type: 'string'},
{name: 'creators', type: 'Part[]'},
{name: 'royalties', type: 'Part[]'}
]
};
|
eb0f4e7186ebcc8aba1efc999795c609bc96a8a3
|
TypeScript
|
savewhatyoulove/d2s
|
/src/d2/stash.ts
| 2.734375
| 3
|
import * as types from "./types";
import { BitWriter } from "../binary/bitwriter";
import * as items from "./items";
import { enhanceItems } from "./attribute_enhancer";
import { BitReader } from "../binary/bitreader";
const defaultConfig = {
extendedStash: false,
} as types.IConfig;
export async function read(
buffer: Uint8Array,
constants: types.IConstantData,
version: number,
userConfig?: types.IConfig
): Promise<types.IStash> {
const stash = {} as types.IStash;
const reader = new BitReader(buffer);
const config = Object.assign(defaultConfig, userConfig);
await readStashHeader(stash, reader);
//could load constants based on version here
await readStashPages(stash, reader, version, constants);
return stash;
}
async function readStashHeader(stash: types.IStash, reader: BitReader) {
const header = reader.ReadString(4);
if (header !== "SSS\0") {
throw new Error(`shared stash header 'SSS' not found at position ${reader.offset - 3 * 8}`);
}
const version = reader.ReadString(2);
stash.version = version;
if (version !== "01" && version !== "02") {
throw new Error(`unkown shared stash version ${version} at position ${reader.offset - 2 * 8}`);
}
if (version == "02") {
stash.sharedGold = reader.ReadUInt32();
}
stash.pageCount = reader.ReadUInt32();
}
async function readStashPages(stash: types.IStash, reader: BitReader, version: number, constants: types.IConstantData) {
stash.pages = [];
for (let i = 0; i < stash.pageCount; i++) {
await readStashPage(stash, reader, version, constants);
}
}
async function readStashPage(stash: types.IStash, reader: BitReader, version: number, constants: types.IConstantData) {
const page: types.IStashPage = {
items: [],
name: "",
type: 0,
};
const header = reader.ReadString(2);
if (header !== "ST") {
throw new Error(`can not read stash page header ST at position ${reader.offset - 2 * 8}`);
}
page.type = reader.ReadUInt32();
page.name = reader.ReadNullTerminatedString();
page.items = await items.readItems(reader, version, constants, defaultConfig);
enhanceItems(page.items, constants, 1);
stash.pages.push(page);
}
export async function write(
data: types.IStash,
constants: types.IConstantData,
version: number,
userConfig?: types.IConfig
): Promise<Uint8Array> {
const config = Object.assign(defaultConfig, userConfig);
const writer = new BitWriter();
writer.WriteArray(await writeStashHeader(data));
writer.WriteArray(await writeStashPages(data, version, constants, config));
return writer.ToArray();
}
async function writeStashHeader(data: types.IStash): Promise<Uint8Array> {
const writer = new BitWriter();
writer.WriteString("SSS", 4);
writer.WriteString(data.version, data.version.length);
if (data.version == "02") {
writer.WriteUInt32(data.sharedGold);
}
writer.WriteUInt32(data.pages.length);
return writer.ToArray();
}
async function writeStashPages(
data: types.IStash,
version: number,
constants: types.IConstantData,
config: types.IConfig
): Promise<Uint8Array> {
const writer = new BitWriter();
for (let i = 0; i < data.pages.length; i++) {
writer.WriteArray(await writeStashPage(data.pages[i], version, constants, config));
}
return writer.ToArray();
}
async function writeStashPage(
data: types.IStashPage,
version: number,
constants: types.IConstantData,
config: types.IConfig
): Promise<Uint8Array> {
const writer = new BitWriter();
writer.WriteString("ST", 2);
writer.WriteUInt32(data.type);
writer.WriteString(data.name, data.name.length + 1);
writer.WriteArray(await items.writeItems(data.items, version, constants, config));
return writer.ToArray();
}
|
8b4ebf44fd9f6f076a34644b7099073a56f42c27
|
TypeScript
|
IsraelGomes/ProjetoRedeSocial
|
/Projeto/src/app/usuario.service.ts
| 2.625
| 3
|
import { Injectable } from '@angular/core';
import { delay } from 'q';
import { HttpClient } from '@angular/common/http';
import { Usuario } from './usuario';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class UsuarioService {
static logado = false;
static usuarioLogado: Usuario;
apiUsuarios = 'http://localhost:3000/usuarios';
constructor(private http: HttpClient) { }
static postar(conteudo: string) {
}
loginAutomatico(): string{
let info: string;
let informacao: string[];
let email: string;
let senha: string;
info = (localStorage.usuario);
if(info == null)
{
UsuarioService.usuarioLogado = null;
UsuarioService.logado = false;
return;
}
informacao = info.split("\n");
email = informacao[0];
senha = informacao[1];
this.logar(email, senha);
}
logar(email: string, senha: string): string {
let resultado: string;
let usuarios: Observable<Usuario[]>;
usuarios = this.http.get<Usuario[]>(this.apiUsuarios);
usuarios.subscribe(
ok => {
for(let usuario of ok)
{
if(usuario.email == email && usuario.senha == senha)
{
UsuarioService.logado = true;
UsuarioService.usuarioLogado = usuario;
}
}
},
erro => {
resultado = "erro ao logar";
}
);
return resultado;
}
cadastrar(usuario: Usuario): string {
let resultado: string;
let usuarios: Observable<Usuario[]>;
usuarios = this.http.get<Usuario[]>(this.apiUsuarios);
usuarios.subscribe(
ok => {
for(let user of ok)
{
if(user.email == usuario.email && user.senha == usuario.senha)
{
UsuarioService.logado = false;
UsuarioService.usuarioLogado = null;
resultado = "erro ao cadastrar";
break;
}
}
if(resultado != "erro ao cadastrar")
{
this.http.post(this.apiUsuarios, usuario).subscribe(
cadastrado => {
UsuarioService.logado = true;
UsuarioService.usuarioLogado = usuario;
localStorage.usuario = usuario.getEmail() + "\n" + usuario.getSenha();
resultado = "Cadastrado com sucesso";
},
erroAoCadastrar => {
UsuarioService.logado = false;
UsuarioService.usuarioLogado = null;
resultado = "erro ao cadastrar";
}
);
}
},
erro => {
resultado = "erro ao cadastrar";
});
return resultado;
}
sair(){
localStorage.removeItem("usuario");
UsuarioService.logado = false;
UsuarioService.usuarioLogado = null;
}
}
|
7aecd3edb14fbd4c7d6a1d47b29ec4714327eef3
|
TypeScript
|
Ahryman40k/typescript-fhir-types
|
/src/R4/Resource/RTTI_BodyStructure.ts
| 2.734375
| 3
|
import * as t from 'io-ts';
import { RTTI_id } from '../Scalar/RTTI_id';
import { RTTI_Meta, IMeta } from './RTTI_Meta';
import { RTTI_uri } from '../Scalar/RTTI_uri';
import { RTTI_Element, IElement } from './RTTI_Element';
import { RTTI_code } from '../Scalar/RTTI_code';
import { RTTI_Narrative, INarrative } from './RTTI_Narrative';
import { RTTI_ResourceList, IResourceList } from '../Union/RTTI_ResourceList';
import { RTTI_Extension, IExtension } from './RTTI_Extension';
import { RTTI_Identifier, IIdentifier } from './RTTI_Identifier';
import { RTTI_CodeableConcept, ICodeableConcept } from './RTTI_CodeableConcept';
import { RTTI_Attachment, IAttachment } from './RTTI_Attachment';
import { RTTI_Reference, IReference } from './RTTI_Reference';
import { IDomainResource } from './IDomainResource';
export interface IBodyStructure extends IDomainResource {
/**
* This is a BodyStructure resource
*/
resourceType: 'BodyStructure';
/**
* The person to which the body site belongs.
*/
patient: IReference;
/**
* The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.
*/
id?: string;
/**
* The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content might not always be associated with version changes to the resource.
*/
meta?: IMeta;
/**
* A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. Often, this is a reference to an implementation guide that defines the special rules along with other profiles etc.
*/
implicitRules?: string;
/**
* Extensions for implicitRules
*/
_implicitRules?: IElement;
/**
* The base language in which the resource is written.
*/
language?: string;
/**
* Extensions for language
*/
_language?: IElement;
/**
* A human-readable narrative that contains a summary of the resource and can be used to represent the content of the resource to a human. The narrative need not encode all the structured data, but is required to contain sufficient detail to make it "clinically safe" for a human to just read the narrative. Resource definitions may define what content should be represented in the narrative to ensure clinical safety.
*/
text?: INarrative;
/**
* These resources do not have an independent existence apart from the resource that contains them - they cannot be identified independently, and nor can they have their own independent transaction scope.
*/
contained?: IResourceList[];
/**
* May be used to represent additional information that is not part of the basic definition of the resource. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension.
*/
extension?: IExtension[];
/**
* May be used to represent additional information that is not part of the basic definition of the resource and that modifies the understanding of the element that contains it and/or the understanding of the containing element's descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself).
*/
modifierExtension?: IExtension[];
/**
* Identifier for this instance of the anatomical structure.
*/
identifier?: IIdentifier[];
/**
* Whether this body site is in active use.
*/
active?: boolean;
/**
* Extensions for active
*/
_active?: IElement;
/**
* The kind of structure being represented by the body structure at `BodyStructure.location`. This can define both normal and abnormal morphologies.
*/
morphology?: ICodeableConcept;
/**
* The anatomical location or region of the specimen, lesion, or body structure.
*/
location?: ICodeableConcept;
/**
* Qualifier to refine the anatomical location. These include qualifiers for laterality, relative location, directionality, number, and plane.
*/
locationQualifier?: ICodeableConcept[];
/**
* A summary, characterization or explanation of the body structure.
*/
description?: string;
/**
* Extensions for description
*/
_description?: IElement;
/**
* Image or images used to identify a location.
*/
image?: IAttachment[];
}
export const RTTI_BodyStructure: t.Type<IBodyStructure> = t.recursion(
'IBodyStructure',
() =>
t.intersection([
t.type({
resourceType: t.literal('BodyStructure'),
patient: RTTI_Reference
}),
t.partial({
id: RTTI_id,
meta: RTTI_Meta,
implicitRules: RTTI_uri,
_implicitRules: RTTI_Element,
language: RTTI_code,
_language: RTTI_Element,
text: RTTI_Narrative,
contained: t.array(RTTI_ResourceList),
extension: t.array(RTTI_Extension),
modifierExtension: t.array(RTTI_Extension),
identifier: t.array(RTTI_Identifier),
active: t.boolean,
_active: RTTI_Element,
morphology: RTTI_CodeableConcept,
location: RTTI_CodeableConcept,
locationQualifier: t.array(RTTI_CodeableConcept),
description: t.string,
_description: RTTI_Element,
image: t.array(RTTI_Attachment)
})
])
);
|
a29dd1703948483c52aa505be1588e6ac79730db
|
TypeScript
|
wr719152280/re
|
/src/store/reducers/loadding.ts
| 2.75
| 3
|
import { DefaultRootState } from "react-redux"
import { CHANGELOADINGAction } from "../action"
import { CHANGE_LOADING } from "../const";
export interface IInitState extends DefaultRootState{
loading:boolean
}
const initState = {
loading:false
}
export default (state:IInitState = initState,action:CHANGELOADINGAction) => {
switch (action.type) {
case CHANGE_LOADING:
const newState = JSON.parse(JSON.stringify(state))
newState.loading = action.loading
return newState
default:
return state
}
}
|
d62eb7e5a2d6bf3347611d9249c6ea7387db9a3d
|
TypeScript
|
NJVIRANI/startfireweb
|
/src/main/webapp/app/entities/award-type/award-type.reducer.ts
| 2.640625
| 3
|
import axios from 'axios';
import { ICrudGetAction, ICrudGetAllAction, ICrudPutAction, ICrudDeleteAction } from 'react-jhipster';
import { cleanEntity } from 'app/shared/util/entity-utils';
import { REQUEST, SUCCESS, FAILURE } from 'app/shared/reducers/action-type.util';
import { IAwardType, defaultValue } from 'app/shared/model/award-type.model';
export const ACTION_TYPES = {
FETCH_AWARDTYPE_LIST: 'awardType/FETCH_AWARDTYPE_LIST',
FETCH_AWARDTYPE: 'awardType/FETCH_AWARDTYPE',
CREATE_AWARDTYPE: 'awardType/CREATE_AWARDTYPE',
UPDATE_AWARDTYPE: 'awardType/UPDATE_AWARDTYPE',
DELETE_AWARDTYPE: 'awardType/DELETE_AWARDTYPE',
RESET: 'awardType/RESET',
};
const initialState = {
loading: false,
errorMessage: null,
entities: [] as ReadonlyArray<IAwardType>,
entity: defaultValue,
updating: false,
totalItems: 0,
updateSuccess: false,
};
export type AwardTypeState = Readonly<typeof initialState>;
// Reducer
export default (state: AwardTypeState = initialState, action): AwardTypeState => {
switch (action.type) {
case REQUEST(ACTION_TYPES.FETCH_AWARDTYPE_LIST):
case REQUEST(ACTION_TYPES.FETCH_AWARDTYPE):
return {
...state,
errorMessage: null,
updateSuccess: false,
loading: true,
};
case REQUEST(ACTION_TYPES.CREATE_AWARDTYPE):
case REQUEST(ACTION_TYPES.UPDATE_AWARDTYPE):
case REQUEST(ACTION_TYPES.DELETE_AWARDTYPE):
return {
...state,
errorMessage: null,
updateSuccess: false,
updating: true,
};
case FAILURE(ACTION_TYPES.FETCH_AWARDTYPE_LIST):
case FAILURE(ACTION_TYPES.FETCH_AWARDTYPE):
case FAILURE(ACTION_TYPES.CREATE_AWARDTYPE):
case FAILURE(ACTION_TYPES.UPDATE_AWARDTYPE):
case FAILURE(ACTION_TYPES.DELETE_AWARDTYPE):
return {
...state,
loading: false,
updating: false,
updateSuccess: false,
errorMessage: action.payload,
};
case SUCCESS(ACTION_TYPES.FETCH_AWARDTYPE_LIST):
return {
...state,
loading: false,
entities: action.payload.data,
totalItems: parseInt(action.payload.headers['x-total-count'], 10),
};
case SUCCESS(ACTION_TYPES.FETCH_AWARDTYPE):
return {
...state,
loading: false,
entity: action.payload.data,
};
case SUCCESS(ACTION_TYPES.CREATE_AWARDTYPE):
case SUCCESS(ACTION_TYPES.UPDATE_AWARDTYPE):
return {
...state,
updating: false,
updateSuccess: true,
entity: action.payload.data,
};
case SUCCESS(ACTION_TYPES.DELETE_AWARDTYPE):
return {
...state,
updating: false,
updateSuccess: true,
entity: {},
};
case ACTION_TYPES.RESET:
return {
...initialState,
};
default:
return state;
}
};
const apiUrl = 'api/award-types';
// Actions
export const getEntities: ICrudGetAllAction<IAwardType> = (page, size, sort) => {
const requestUrl = `${apiUrl}${sort ? `?page=${page}&size=${size}&sort=${sort}` : ''}`;
return {
type: ACTION_TYPES.FETCH_AWARDTYPE_LIST,
payload: axios.get<IAwardType>(`${requestUrl}${sort ? '&' : '?'}cacheBuster=${new Date().getTime()}`),
};
};
export const getEntity: ICrudGetAction<IAwardType> = id => {
const requestUrl = `${apiUrl}/${id}`;
return {
type: ACTION_TYPES.FETCH_AWARDTYPE,
payload: axios.get<IAwardType>(requestUrl),
};
};
export const createEntity: ICrudPutAction<IAwardType> = entity => async dispatch => {
const result = await dispatch({
type: ACTION_TYPES.CREATE_AWARDTYPE,
payload: axios.post(apiUrl, cleanEntity(entity)),
});
dispatch(getEntities());
return result;
};
export const updateEntity: ICrudPutAction<IAwardType> = entity => async dispatch => {
const result = await dispatch({
type: ACTION_TYPES.UPDATE_AWARDTYPE,
payload: axios.put(apiUrl, cleanEntity(entity)),
});
return result;
};
export const deleteEntity: ICrudDeleteAction<IAwardType> = id => async dispatch => {
const requestUrl = `${apiUrl}/${id}`;
const result = await dispatch({
type: ACTION_TYPES.DELETE_AWARDTYPE,
payload: axios.delete(requestUrl),
});
dispatch(getEntities());
return result;
};
export const reset = () => ({
type: ACTION_TYPES.RESET,
});
|
45cb4312a910f540a4e4eb7b547cc0f283e06f96
|
TypeScript
|
alibaba/hooks
|
/packages/hooks/src/useGetState/__tests__/index.test.ts
| 2.609375
| 3
|
import { act, renderHook } from '@testing-library/react';
import useGetState from '../index';
describe('useGetState', () => {
const setUp = <T>(initialValue: T) =>
renderHook(() => {
const [state, setState, getState] = useGetState<T>(initialValue);
return {
state,
setState,
getState,
} as const;
});
it('should support initialValue', () => {
const hook = setUp(() => 0);
expect(hook.result.current.state).toBe(0);
});
it('should support update', () => {
const hook = setUp(0);
act(() => {
hook.result.current.setState(1);
});
expect(hook.result.current.getState()).toBe(1);
});
it('should getState frozen', () => {
const hook = setUp(0);
const prevGetState = hook.result.current.getState;
act(() => {
hook.result.current.setState(1);
});
expect(hook.result.current.getState).toBe(prevGetState);
});
});
|
fcf20c806895f5c494f3a91f80f4299c98007a95
|
TypeScript
|
green-fox-academy/vis0rka
|
/week-04/day-3/pirates.ts
| 3.46875
| 3
|
class Pirate {
name: string;
intoxicates: number;
constructor(name: string, intoxicates: number = 0) {
this.name = name;
this.intoxicates = intoxicates;
}
drinkSomeRum(rums: number): void {
this.intoxicates += rums;
}
howsItGoingMate(): void {
if (this.intoxicates < 4) {
console.log('Pour me anudder!');
} else {
console.log(`Arghh, I'ma Pirate. How d'ya d'ink its goin?`);
}
}
}
let barbossa = new Pirate("barbossa");
let blackBarney = new Pirate("blackBarney");
let firebrand = new Pirate("firebrand");
barbossa.drinkSomeRum(5);
blackBarney.drinkSomeRum(2);
firebrand.drinkSomeRum(1);
barbossa.howsItGoingMate();
console.log(barbossa);
|
76ae704c5a0f38a4eeebc93766672f84403ab31f
|
TypeScript
|
boosteel/hancomee
|
/web-resources/lib/core/component/focusBtn.ts
| 3.140625
| 3
|
/*
* 버튼과 인풋을 일원화시킨다.
*/
type Handler = (input: HTMLInputElement, btn: HTMLButtonElement) => void
export function focusBtn(input: HTMLInputElement, btn: HTMLButtonElement, handler: {focus: Handler, blur: Handler}) {
let temp = false;
input.addEventListener('focusin', () => {
handler.focus(input, btn);
});
input.addEventListener('focusout', () => {
handler.blur(input, btn);
});
btn.addEventListener('mousedown', () => {
temp = document.activeElement !== input;
})
btn.addEventListener('click', () => {
temp && input.focus();
temp = false;
})
}
|
a3d5c9c23af5456a1be5ebacbbc448407b5a1ca9
|
TypeScript
|
orsilarssen/EmeseEeva
|
/week-04/day-4/string1.ts
| 3.796875
| 4
|
export { }
// Given a string, compute recursively (no loops) a new string where all the
// lowercase 'x' chars have been changed to 'y' chars.
function replaceXtoY(characters: string, charX: string, charY: string):string {
if (characters.indexOf(charX) === -1) {
return characters;
}
else {
return replaceXtoY(characters.replace(charX, charY), charX, charY);
}
}
console.log(replaceXtoY('vbbnzzhjko','x','y'));
|
385f2fa046e8a6ca83c970cd6e70a41a40e7cccd
|
TypeScript
|
thomas-lowry/themer
|
/src/scripts/applyTheme.ts
| 2.625
| 3
|
//imports
import { hasChildren } from "./hasChildren";
import { hasFillStyles } from "./hasFillStyles";
import { hasStrokeStyle } from "./hasStrokeStyle";
import { hasEffects } from "./hasEffects";
//variables we will use to apply the right type of styles
let colorStyles = false;
let textStyles = false;
let effectStyles = false;
//imported styles
let allThemes = [];
let selectedThemeStyles = [];
let selectedTheme; //name of the theme we are applying
//collect the number of nodes affected
let count = {};
//collect the styles applied so we don't import them twice
const styles = {};
//notifications
let notify;
//failed styles
let failedStyles = {};
export async function applyTheme(themeData, theme) {
failedStyles = {};
//tell the user the theme is being applied
notify = figma.notify('Applying ' + theme + ' theme...', {timeout: Infinity})
//this is the theme the user selected to apply
//normalizing in lowercase for comparison reasons
selectedTheme = theme.toLowerCase();
//all of the theme data which includes the keys, provided from the JSONbin
allThemes = themeData;
console.log('all themes: ', allThemes)
//filter all of the theme data down to just the styles associated with the selected theme
selectedThemeStyles = themeData.filter(style => style.theme.toLowerCase() === selectedTheme);
//get for selection
let selection = figma.currentPage.selection;
//check for selection
//TODO: turn into guard
if (selection.length >= 1) {
//identify which type of styles are present
themeData.forEach(style => {
if (style.type === 'PAINT') { colorStyles = true };
if (style.type === 'TEXT') { textStyles = true };
if (style.type === 'EFFECT') { effectStyles = true };
})
//now we iterate through every node in the selection
const promises = selection.map(applyStyleToNode);
await Promise.all(promises);
//filter out unique nodes so we don't count the same node twice
//this is possible because the same node could have multiple styles applied to it
let actualCount = Object.keys(count).length;
//cancel the current notification
notify.cancel();
//add a msg for failed styles
let numOfFailedStyles = Object.keys(failedStyles).length;
console.log('failed style stuff:', failedStyles, numOfFailedStyles);
let failedMsg;
if(numOfFailedStyles > 0) {
let word = numOfFailedStyles > 1 ? ' styles':' style';
failedMsg = numOfFailedStyles + word + ' failed to import, see console for details.'
}
//Msg to user
if (actualCount > 0) {
if (numOfFailedStyles === 0) {
figma.notify(selectedTheme + ' theme applied to ' + actualCount + ' layers');
} else {
figma.notify(selectedTheme + ' theme applied to ' + actualCount + ' layers. ' + failedMsg, {timeout: 5000});
}
} else {
figma.notify('No styles from your themes were found.');
}
count = {};
} else {
figma.notify('Please make a selection');
}
}
async function applyStyleToNode(node: SceneNode) {
//console.log('apply to node')
//skip hidden nodes to improve performance
if (!node.visible) return true;
//FILL & STROKE STYLES
if (colorStyles && hasFillStyles(node) && node.fillStyleId != '') {
//if the node does not have a mixed property, match and apply paint style
if (typeof (node.fillStyleId) != 'symbol') {
//get the style currently applied to the node
let originalStyle = figma.getStyleById(node.fillStyleId) as PaintStyle;
//see if there is a matching style in the selected theme, apply it if there is
let matchedStyle = returnMatchingStyle(originalStyle.name, 'PAINT');
if (matchedStyle !== null) {
let styleId = await findMatchedKeyOrImportStyle(matchedStyle);
if (styleId) {
styles[matchedStyle.key] = styleId;
node.fillStyleId = styleId;
count[node.id] = 1;
}
}
//for text nodes that have mixed color styles, match and apply paint style
} else if (node.type === 'TEXT' && typeof (node.fillStyleId) === 'symbol') {
//do this if there are multiple color styles in the same text box
let uniqueTextColorStyles = node.getStyledTextSegments(['fillStyleId']);
for await (const fillStyle of uniqueTextColorStyles) {
//get the style currently applied to the node
let originalStyle = figma.getStyleById(fillStyle.fillStyleId);
//apply style if there is a match in selected theme
let matchedStyle = returnMatchingStyle(originalStyle.name, 'PAINT');
if (matchedStyle !== null) {
let styleId = await findMatchedKeyOrImportStyle(matchedStyle);
if (styleId) {
styles[matchedStyle.key] = styleId;
node.setRangeFillStyleId(fillStyle.start, fillStyle.end, styleId);
count[node.id] = 1;
}
}
}
}
}
//for nodes with strokes
if (colorStyles && hasStrokeStyle(node) && node.strokeStyleId != '') {
//get the style currently applied to the node
let originalStyle = figma.getStyleById(node.strokeStyleId) as PaintStyle;
//see if there is a matching style in the selected theme, apply it if there is
let matchedStyle = returnMatchingStyle(originalStyle.name, 'PAINT');
if (matchedStyle !== null) {
let styleId = await findMatchedKeyOrImportStyle(matchedStyle);
if (styleId) {
styles[matchedStyle.key] = styleId;
node.strokeStyleId = styleId;
count[node.id] = 1;
}
}
}
//TEXT STYLES
if (textStyles && node.type === "TEXT") {
//do this for text nodes with a single style applied
if (node.textStyleId != '' && typeof (node.textStyleId) != 'symbol') {
//get the currently applied text style
let originalStyle = figma.getStyleById(node.textStyleId) as TextStyle;
//see if there is a matching style in the selected theme
let matchedStyle = returnMatchingStyle(originalStyle.name, 'TEXT');
if (matchedStyle !== null) {
let styleId = await findMatchedKeyOrImportStyle(matchedStyle);
if (styleId) {
styles[matchedStyle.key] = styleId;
let style = figma.getStyleById(styleId) as TextStyle;
//load the fonts for the new style
await figma.loadFontAsync({
'family': style.fontName.family,
'style': style.fontName.style
});
node.textStyleId = styleId;
count[node.id] = 1;
}
}
//do this for text nodes that have multiple text styles
} else if (typeof (node.textStyleId) === 'symbol') {
//do this if there are multiple text styles in the same text box
let uniqueTextStyles = node.getStyledTextSegments(['textStyleId']);
for await (const textStyle of uniqueTextStyles) {
let originalStyle = figma.getStyleById(textStyle.textStyleId);
let matchedStyle = returnMatchingStyle(originalStyle.name, 'TEXT') as TextStyle;
if (matchedStyle !== null) {
let styleId = await findMatchedKeyOrImportStyle(matchedStyle);
if (styleId) {
styles[matchedStyle.key] = styleId;
let style = figma.getStyleById(styleId) as TextStyle;
//load the fonts for the new style
await figma.loadFontAsync({
'family': style.fontName.family,
'style': style.fontName.style
});
//apply the style to the correct range
node.setRangeTextStyleId(textStyle.start, textStyle.end, styleId);
count[node.id] = 1;
}
}
}
}
}
//EFFECT STYLES
if (effectStyles && hasEffects(node) && node.effectStyleId != '' && typeof (node.effectStyleId) != 'symbol') {
//get currently applied effect style
let originalStyle = figma.getStyleById(node.effectStyleId) as EffectStyle;
//see if there is a matching style in the selected theme
let matchedStyle = returnMatchingStyle(originalStyle.name, 'EFFECT') as EffectStyle;
if (matchedStyle !== null) {
let styleId = await findMatchedKeyOrImportStyle(matchedStyle);
if (styleId) {
styles[matchedStyle.key] = styleId;
node.effectStyleId = styleId;
count[node.id] = 1;
}
}
}
//repeat the process for all children
return hasChildren(node) ? Promise.all(node.children.map(applyStyleToNode)) : true;
}
//HELPERS
//find a matching style in the selected theme
function returnMatchingStyle(name, type) {
//console.log('looking for matching style');
//make an array of all of the unique theme names, make sure they are all lower case
let uniqueThemes = [...new Set(allThemes.map(item => item.theme.toLowerCase()))];
//normalize style name for matching
let normalizedCurrentStyleName = processStyleNameWithThemeNameIncluded(name.toLowerCase(), uniqueThemes);
//match will default to null unless we find one
let match = null;
//console.log('selected theme styles: ', selectedThemeStyles)
//iterate through all styles in all themes to find a match
selectedThemeStyles.forEach(style => {
let normalizedNewStyleName = processStyleNameWithThemeNameIncluded(style.name.toLowerCase(), uniqueThemes);
//console.log('current style name:', normalizedCurrentStyleName)
//console.log('new style name:', normalizedNewStyleName)
if (normalizedNewStyleName === normalizedCurrentStyleName && style.type === type) {
console.log('found a match!');
match = style;
return match;
}
});
return match;
}
//this will check to see if the name of theme is present in the style name
//but it also checks to make sure that theme name is in the prefix of the style name
//if those conditions are met, strip the theme from the style name
//if not, return the full name
function processStyleNameWithThemeNameIncluded(name, uniqueThemes) {
//console.log('processing! name')
let newName;
let splitName = name.toLowerCase().split('/');
//console.log('split name:', splitName);
// console.log('splitName[0]', splitName[0])
//console.log(uniqueThemes.length);
if (splitName.length >= 2) {
for (const theme of uniqueThemes) {
if (splitName[0].includes(theme.toLowerCase())) {
//console.log('contains a theme name!');
splitName.shift();
//console.log('base name:', name)
//console.log('shifted name:', splitName)
newName = splitName.join('/').toString();
break;
}
}
}
console.log('new name final:' , newName ? newName : name)
return newName ? newName : name;
}
async function findMatchedKeyOrImportStyle(matchedStyle) {
let result = null;
if (styles[matchedStyle.key]) {
result = styles[matchedStyle.key];
} else {
try{
result = (await figma.importStyleByKeyAsync(matchedStyle.key)).id;
} catch(err) {
let style = allThemes.find(style => style.key === matchedStyle.key);
console.log('Error importing style: ', style.name);
failedStyles[matchedStyle.key] = 1;
}
}
return result;
}
|
403cc65a22d6ae67a030f5b6ea216f940d5db1b1
|
TypeScript
|
rodrigopaixao/api-ui-data-model
|
/src/app/models/traceable.model.ts
| 2.78125
| 3
|
import { Exclude } from 'class-transformer';
export abstract class Traceable {
@Exclude()
protected isNewStatus: boolean;
@Exclude()
protected isUpdatedStatus: boolean;
get isNew() {
return this.isNewStatus;
}
get isUpdated() {
return this.isUpdatedStatus;
}
setAsNew() {
this.isNewStatus = true;
this.cancelHighlight();
}
setAsUpdated() {
this.isUpdatedStatus = true;
this.cancelHighlight();
}
private cancelHighlight() {
setTimeout(() => {
this.isNewStatus = false;
this.isUpdatedStatus = false;
}, 2000);
}
}
|
f3a72893a4e3b53beacd9dec3851f4ad3150ce96
|
TypeScript
|
pathakvivek7865/node-practices
|
/jwt-authentication/src/security/jwt.ts
| 2.84375
| 3
|
import * as jwt from "jsonwebtoken";
import { User } from "../entity/User";
import { v4 as uuidv4 } from "uuid";
import { RefreshToken } from "../entity/RefreshToken";
import * as moment from "moment";
import { Database } from "../database";
export class JWT {
//specify a secret key for jwt generateion
private static JWT_SECRET = "123456";
public static async generateTokenAndRefreshToken(user: User) {
//specify a payload that holds the users id (and) email
const payload = {
id: user.id,
email: user.email,
};
const jwtId = uuidv4();
const token = jwt.sign(payload, this.JWT_SECRET, {
expiresIn: "1h", // specify when does the token expires
jwtid: jwtId, // specify jwtid (an id of that token) (needed for the refresh token, as refresh token only points to one single uinque token)
subject: user.id.toString(), // the subject should be the users id (primary key)
});
// create a refresh token
const refreshToken = await this.generateRefreshTokenForUserAndToken(
user,
jwtId
);
// link that token with the refresh token
return { token, refreshToken };
}
private static async generateRefreshTokenForUserAndToken(
user: User,
jwtId: string
) {
// create a new record of refresh token
const refreshToken = new RefreshToken();
refreshToken.user = user;
refreshToken.jwtId = jwtId;
// set the expiry date of the refesh for eg. 10 days
refreshToken.expiryDate = moment().add(10, "d").toDate();
// store this refresh token
await Database.refreshTokenRepository.save(refreshToken);
return refreshToken.id;
}
}
|
eeea32f4c9ff5682b8873469176cb355cc912db8
|
TypeScript
|
soumyamishra89/github-analyser
|
/frontend/src/__tests__/redux/reducers/testReduxReducers.ts
| 2.5625
| 3
|
import reducers from '../../../redux/reducers';
import { ReduxActionType, LoggedStatus } from "../../../types";
import mockData from '../../../__mock__/mockData.json';
describe("Test redux reducers", () => {
describe("loggedStatusReducer", () => {
it("loggedStatusReducer Logged in", () => {
const expectedReducer = {
githubRepos: [],
loggedStatus: LoggedStatus.LOGGED_IN,
isGithubReposLoading: false
}
expect(reducers(undefined, {type: ReduxActionType.LOGGED_STATUS, data: LoggedStatus.LOGGED_IN})).toEqual(expectedReducer);
})
it("loggedStatusReducer Logged out", () => {
const expectedReducer = {
githubRepos: [],
loggedStatus: LoggedStatus.LOGGED_OUT,
isGithubReposLoading: false
}
expect(reducers(undefined, {type: ReduxActionType.LOGGED_STATUS, data: LoggedStatus.LOGGED_OUT})).toEqual(expectedReducer);
})
});
describe("githubReposReducer", () => {
it("githubReposReducer with data", () => {
const expectedReducer = {
githubRepos: mockData.githubInfo,
loggedStatus: LoggedStatus.LOGGED_OUT,
isGithubReposLoading: false
}
expect(reducers(undefined, {type: ReduxActionType.GITHUB_REPO, data: mockData.githubInfo})).toEqual(expectedReducer);
})
it("githubReposReducer without data", () => {
const expectedReducer = {
githubRepos: [],
loggedStatus: LoggedStatus.LOGGED_OUT,
isGithubReposLoading: false
}
expect(reducers(undefined, {type: ReduxActionType.GITHUB_REPO, data: undefined})).toEqual(expectedReducer);
})
});
describe("isGithubReposLoadingReducer", () => {
it("isGithubReposLoadingReducer loading", () => {
const expectedReducer = {
githubRepos: [],
loggedStatus: LoggedStatus.LOGGED_OUT,
isGithubReposLoading: true
}
expect(reducers(undefined, {type: ReduxActionType.LOADING_GITHUB_REPO, data: true})).toEqual(expectedReducer);
})
it("isGithubReposLoadingReducer not loading", () => {
const expectedReducer = {
githubRepos: [],
loggedStatus: LoggedStatus.LOGGED_OUT,
isGithubReposLoading: false
}
expect(reducers(undefined, {type: ReduxActionType.LOADING_GITHUB_REPO, data: false})).toEqual(expectedReducer);
})
});
})
|
ec166ed2d1864313c16d1da7247142d8f90d60b6
|
TypeScript
|
TitechMeister/growi
|
/packages/app/src/server/service/page-operation.ts
| 2.640625
| 3
|
import { pagePathUtils } from '@growi/core';
import PageOperation from '~/server/models/page-operation';
const { isEitherOfPathAreaOverlap, isPathAreaOverlap, isTrashPage } = pagePathUtils;
class PageOperationService {
crowi: any;
constructor(crowi) {
this.crowi = crowi;
}
// TODO: Remove this code when resuming feature is implemented
async init():Promise<void> {
await PageOperation.deleteMany({});
}
/**
* Check if the operation is operatable
* @param isRecursively Boolean that determines whether the operation is recursive or not
* @param fromPathToOp The path to operate from
* @param toPathToOp The path to operate to
* @returns boolean
*/
async canOperate(isRecursively: boolean, fromPathToOp: string | null, toPathToOp: string | null): Promise<boolean> {
const mainOps = await PageOperation.findMainOps();
if (mainOps.length === 0) {
return true;
}
const toPaths = mainOps.map(op => op.toPath).filter((p): p is string => p != null);
if (isRecursively) {
if (fromPathToOp != null && !isTrashPage(fromPathToOp)) {
const flag = toPaths.some(p => isEitherOfPathAreaOverlap(p, fromPathToOp));
if (flag) return false;
}
if (toPathToOp != null && !isTrashPage(toPathToOp)) {
const flag = toPaths.some(p => isPathAreaOverlap(p, toPathToOp));
if (flag) return false;
}
}
else {
if (fromPathToOp != null && !isTrashPage(fromPathToOp)) {
const flag = toPaths.some(p => isPathAreaOverlap(p, fromPathToOp));
if (flag) return false;
}
if (toPathToOp != null && !isTrashPage(toPathToOp)) {
const flag = toPaths.some(p => isPathAreaOverlap(p, toPathToOp));
if (flag) return false;
}
}
return true;
}
}
export default PageOperationService;
|
4948687695fd1f287094d5a6eb2a7cb94f9ea07d
|
TypeScript
|
Dihcar-76/TP-Blog2-Angular-OpenCLassrooms-
|
/src/app/services/post.service.ts
| 2.875
| 3
|
import { Subject } from 'rxjs/Subject';
import { Post } from '../models/post.model';
export class PostService {
postsSubject = new Subject<any[]>();
private posts: Array<object> = [
{
title: 'mon premier post',
content: 'blablaqui?',
loveIt: 5,
postcreatedAt: new Date()
},
{
title: 'mon deuxieme post',
content: 'blablaquoi?',
loveIt: 4,
postcreatedAt: new Date()
},
{
title: 'un nouveau post',
content: 'blablacar',
loveIt: 6,
postcreatedAt: new Date()
}
];
emmitPostSubject() {
this.postsSubject.next(this.posts.slice());
}
getColor(post: Post) {
if (post.loveIt >= 5) {
return 'darkgreen';
} else if (post.loveIt < 5) {
return 'darkred';
}
}
unlikePost(post: Post) {
post.loveIt--;
}
likePost(post: Post) {
post.loveIt++;
}
addPost(post: Post) {
this.posts.push(post);
}
removePost(post: Post) {
this.posts.splice(this.posts.findIndex(postObj => postObj === post), 1);
this.emmitPostSubject();
}
}
|
9afc6114fe89faca61ce25aa55c6df63b00b6c3d
|
TypeScript
|
tylerthecoder/friend-graph
|
/src/components/actions/action-types/rm-node/rm-node.test.ts
| 2.625
| 3
|
import { getNodeIds } from "../../../../testing/helpers";
import { eventDiff } from "../../../../testing/test-data";
import {
emptyGraphState,
moveToNextEvent,
moveToPrevEvent,
} from "../../../events/functions";
import {
applyActionAndUpdate,
cleanupEventDiffs,
IAction,
} from "../../functions";
import { IActionType } from "../action-types";
import RmNode from "./rm-node";
const actionClass = new RmNode();
const RM_TYLER_NODE_ACTION: IAction = {
type: IActionType.RM_NODE,
id: "1",
payload: {
id: "tyler",
x: 0,
y: 0,
img: "",
},
};
const ADD_TYLER_CARTER_CONNECTION: IAction = {
type: IActionType.ADD_CON,
id: "2",
payload: {
startId: "carter",
endId: "tyler",
weight: 1,
},
};
describe("Remove Node", () => {
it("Applies Action", () => {
let [GS, ED] = moveToNextEvent(emptyGraphState, eventDiff);
[GS, ED] = moveToNextEvent(GS, ED);
GS = actionClass.applyAction(GS, RM_TYLER_NODE_ACTION);
ED = cleanupEventDiffs(ED, GS, RM_TYLER_NODE_ACTION);
expect(getNodeIds(GS)).toEqual(["carter"]);
// if we go back the node should re-appear
[GS, ED] = moveToPrevEvent(GS, ED);
expect(getNodeIds(GS)).toEqual(["tyler"]);
});
it("Removes bad actions", () => {
// move forward thrice
let [GS, ED] = moveToNextEvent(emptyGraphState, eventDiff);
[GS, ED] = moveToNextEvent(GS, ED);
[GS, ED] = moveToNextEvent(GS, ED);
// add a connection and move back
[GS, ED] = applyActionAndUpdate(ADD_TYLER_CARTER_CONNECTION, GS, ED);
[GS, ED] = moveToPrevEvent(GS, ED);
// remove node (add hopefully next connection)
[GS, ED] = applyActionAndUpdate(RM_TYLER_NODE_ACTION, GS, ED);
expect(getNodeIds(GS)).toEqual(["carter"]);
[GS, ED] = moveToNextEvent(GS, ED);
expect(getNodeIds(GS)).toEqual(["carter", "will"]);
expect(Object.values(GS.connections).length).toBe(0);
});
});
|
bbcc7cf4efe5abbb45bc5d2ba2eb323146c5c9cb
|
TypeScript
|
PRNDcompany/canvas-object
|
/src/graphics/DisplayObject.ts
| 2.984375
| 3
|
import FastVector from 'fast-vector';
export interface DisplayObjectBasicOptions {
alpha?: number;
color?: string;
scale?: number;
rotation?: number;
}
export interface DisplayObjectOptions extends DisplayObjectBasicOptions {
position?: FastVector;
}
export class DisplayObject {
public position: FastVector;
public alpha: number;
public color: string;
public scale: number;
public rotation: number;
public render(context: CanvasRenderingContext2D): void {}
public update(delta: number): void {}
constructor({ position, alpha, color, scale, rotation }: DisplayObjectOptions) {
this.position = position || new FastVector();
this.alpha = alpha || 1;
this.color = color || '#000000';
this.scale = scale || 1;
this.rotation = rotation || 0;
}
}
|
4acf147b89633246e7105a12f265096146d62e27
|
TypeScript
|
aermolinskaya/nine-mens-morris-game-server
|
/sources/server/game/game.ts
| 2.78125
| 3
|
import WebSocket from 'ws';
import { onError } from './on-error.js';
import type {
AnyClientMessage,
AnyServerMessage,
GameStartedMessage,
GameAbortedMessage,
} from '../../common/messages.js';
import type { Color } from '../../common/color.js';
import type { PlayerState } from '../../common/playerState.js';
import { Player } from './player.js';
import { Board } from './board.js';
/**
* Класс игры
*
* Запускает игровую сессию.
*/
class Game
{
/**
* Количество игроков в сессии
*/
static readonly PLAYERS_IN_SESSION = 2;
/**
* Игровая доска
*/
private _board: Board;
/**
* Игроки игровой сессии
*/
private _session: Player[] = [];
/**
* Цвет фишек ходящего игрока
*/
private _currentPlayerColor!: Color;
/**
* @param session Сессия игры, содержащая перечень соединений с игроками
*/
constructor( session: WebSocket[] )
{
this._board = new Board();
this._session.push( new Player( session[0], 'blue' ) );
this._session.push( new Player( session[1], 'red' ) );
this._setStartGameColor();
this._sendStartMessage()
.then(
() =>
{
this._listenMessages();
}
)
.catch( onError );
}
/**
* Уничтожает данные игровой сессии
*/
destroy(): void
{
// Можно вызвать только один раз
this.destroy = () => {};
for ( const player of this._session )
{
if (
( player.connection.readyState !== WebSocket.CLOSED )
&& ( player.connection.readyState !== WebSocket.CLOSING )
)
{
const message: GameAbortedMessage = {
type: 'gameAborted',
};
this._sendMessage( player.connection, message )
.catch( onError );
player.connection.close();
}
}
// Обнуляем ссылки
this._board.clearBoard();
this._board = null as unknown as Game['_board'];
this._session = null as unknown as Game['_session'];
this._currentPlayerColor = null as unknown as Game['_currentPlayerColor'];
}
/**
* Отправляет сообщение о начале игры
*/
private _sendStartMessage(): Promise<void[]>
{
const data: GameStartedMessage = {
type: 'gameStarted',
myTurn: true,
};
const promises: Promise<void>[] = [];
for ( const player of this._session )
{
promises.push( this._sendMessage( player.connection, data ) );
data.myTurn = false;
}
return Promise.all( promises );
}
/**
* Отправляет сообщение игроку
*
* @param player Игрок
* @param message Сообщение
*/
private _sendMessage( player: WebSocket, message: AnyServerMessage ): Promise<void>
{
return new Promise(
( resolve, reject ) =>
{
player.send(
JSON.stringify( message ),
( error ) =>
{
if ( error )
{
reject();
return;
}
resolve();
}
);
},
);
}
/**
* Добавляет слушателя сообщений от игроков
*/
private _listenMessages(): void
{
for ( const player of this._session )
{
player.connection.on(
'message',
( data ) =>
{
const message = this._parseMessage( data );
this._processMessage( player, message );
},
);
player.connection.on( 'close', () => this.destroy() );
}
}
/**
* Разбирает полученное сообщение
*
* @param data Полученное сообщение
*/
private _parseMessage( data: unknown ): AnyClientMessage
{
if ( typeof data !== 'string' )
{
return {
type: 'incorrectRequest',
message: 'Wrong data type',
};
}
try
{
return JSON.parse( data );
}
catch ( error )
{
return {
type: 'incorrectRequest',
message: 'Can\'t parse JSON data: ' + error,
};
}
}
/**
* Выполняет действие, соответствующее полученному сообщению
*
* @param player Игрок, от которого поступило сообщение
* @param message Сообщение
*/
private _processMessage( player: Player, message: AnyClientMessage ): void
{
switch ( message.type )
{
case 'playerMoveChecker':
this._onPlayerMoveChecker( message.from, message.to, player );
break;
case 'playerRemoveChecker':
this._onPlayerRemoveChecker( message.from, player );
break;
case 'repeatGame':
this._restartGame();
this._session[ 0 ].init( 'blue' );
this._session[ 1 ].init( 'red' );
this._sendStartMessage()
.catch( onError );
break;
case 'gameAborted':
this.destroy();
break;
case 'incorrectRequest':
this._sendMessage( player.connection, message )
.catch( onError );
break;
case 'incorrectResponse':
console.error( 'Incorrect request: ', message.message );
break;
default:
this._sendMessage(
player.connection,
{
type: 'incorrectRequest',
message: `Unknown message type: "${(message as AnyClientMessage).type}"`,
},
)
.catch( onError );
break;
}
}
/**
* Обрабатывает запрос о повторе игры
*/
private _restartGame(): void
{
this._board.clearBoard();
this._setStartGameColor();
}
/**
* Инициализирует первого ходящего игрока
*/
private _setStartGameColor(): void
{
this._currentPlayerColor = 'blue';
}
/**
* Меняет ходящего игрока
*/
private _changeCurrentPlayer(): void
{
this._currentPlayerColor = (
this._currentPlayerColor === 'blue' ? 'red' : 'blue'
);
}
/**
* Возвращает второго (противоположного) игрока
*
* @param firstPlayer Первый игрок
*/
private _getSecondPlayer( firstPlayer: Player ): Player
{
return (
firstPlayer === this._session[0]
? this._session[1]
: this._session[0]
);
}
/**
* Возвращает актуальное состояние игрока по его этапу игры
*
* @param player Игрок
*/
private _checkPlayerState( player: Player ): PlayerState
{
const player2 = this._getSecondPlayer( player );
const busyPlayers2CheckersNumber: number = this._board.getBusyCheckersNumberByColor( player2.сolor );
const busyPlayersMerellusNumber: number = this._board.getMerellusNumberByColor( player.сolor );
if (
busyPlayersMerellusNumber
!== ( Player.START_CHECKERS_NUMBER - player2.freeCheckers - busyPlayers2CheckersNumber )
)
{
return 'removingChecker';
}
if ( player.freeCheckers > 0 )
{
return '1_part';
}
const busyPlayersCheckersNumber: number = this._board.getBusyCheckersNumberByColor( player.сolor );
if (
busyPlayersCheckersNumber > 3
&& !this._areAllCheckersClosed( player.сolor )
)
{
return '2_part';
}
else if ( busyPlayersCheckersNumber === 3 )
{
return '3_part';
}
else
{
return 'finish';
}
}
/**
* Проверяет, возможен ли строгий ход фишки из клетку в клетку вдоль линии на один шаг
*
* @param from Клетка с передвигаемой фишкой
* @param to Новая клетка
*/
private _isPossibleMove( from: string, to: string ): boolean
{
let notCommonLine: string[] = Board.getCellLines( from );
for ( const line of Board.getCellLines( to ) )
{
if ( notCommonLine.includes( line ) )
{
notCommonLine.splice( notCommonLine.indexOf( line ), 1 );
}
else
{
notCommonLine.push( line );
}
}
// Проверка, что фишки на одной общей линии
if ( notCommonLine.length !== 2 )
{
return false;
}
const magicNumber: number = Math.abs(
Number( notCommonLine[0].slice(5) ) - Number( notCommonLine[1].slice(5) )
);
return (
magicNumber != 2
&& magicNumber != 8
);
};
/**
* Проверяет, закрыта ли фишка в клетке для строгого хода вдоль линии на один шаг
*
* @param cell Клетка с фишкой
*/
private _isCheckerClosed( cell: string ): boolean
{
for ( const line of Board.getCellLines( cell ) )
{
for ( const cellOnLine of Board.getLineCells( line ) )
{
if (
this._board.haveCheckerOn( cellOnLine ) === undefined
&& this._isPossibleMove( cell, cellOnLine )
)
{
return false;
}
}
}
return true;
};
/**
* Проверяет, закрыты ли все выставленные фишки игрока
* для строгого хода вдоль линии на один шаг
*
* @param playerColor Цвет фишек игрока
*/
private _areAllCheckersClosed( playerColor: Color ): boolean
{
for ( const checker of this._board.getBusyCheckersWithColor( playerColor ) )
{
if ( !this._isCheckerClosed( checker ) )
{
return false;
}
}
return true;
};
/**
* Проверяет, построена ли у игрока на линии новая, ещё не записанная мельница
*
* @param line Проверяемая линия
* @param color Цвет фишек игрока
*/
private _checkNewMerellusOnLine( line: string, color: Color ): boolean
{
if ( this._board.haveMerellusOn( line ) !== undefined )
{
return false;
}
for ( const cellOfLine of Board.getLineCells( line ) )
{
if ( this._board.haveCheckerOn( cellOfLine ) !== color)
{
return false;
}
}
return true;
}
/**
* Возвращает, если есть, новые построенные, но ещё не записанные, мельницы
* на линиях, содержащих заданную клетку
*
* @param cell Заданная клетка
*/
private _isNewMerellus( cell: string ): string[]
{
let linesWithNewMerellus: string[] = [];
for ( const line of Board.getCellLines( cell ) )
{
if ( this._checkNewMerellusOnLine( line, this._board.haveCheckerOn( cell )! ) )
{
linesWithNewMerellus.push( line );
}
}
return linesWithNewMerellus;
};
/**
* Проверяет, есть записанные, но нереализованные мельницы (не убрана фишка соперника)
*/
private _hasUnusedMerellus(): boolean
{
return (
(this._session[0].freeCheckers
+ this._session[1].freeCheckers
+ this._board.getAllBusyCheckersNumber()
+ this._board.getAllMerellusNumber())
!== (Game.PLAYERS_IN_SESSION * Player.START_CHECKERS_NUMBER)
);
};
/**
* Отправляет сообщение игроку о том, что сейчас не его ход
*
* @param connection Соединение с игроком
*/
private _sendIncorrectCurrentPlayerMessage( connection: WebSocket ): void
{
this._sendMessage(
connection,
{
type: 'incorrectRequest',
message: 'Ошибка: ходит другой игрок',
},
)
.catch( onError );
};
/**
* Отправляет сообщение о некорректном ходе игроку
*
* @param connection Соединение с игроком
* @param message Сообщение
*/
private _sendIncorrectMoveMessage( connection: WebSocket, message: string ): void
{
this._sendMessage(
connection,
{
type: 'incorrectRequest',
message,
},
)
.catch( onError );
};
/**
* Отправляет сообщение всем игрокам сессии с состоянием фишек на игровой доске
*/
private _sendToAllUpdateBoardMessage(): void
{
for ( const player of this._session )
{
this._sendMessage(
player.connection,
{
type: 'changeBoard',
busyField: this._board.busyField,
},
)
.catch( onError );
}
};
/**
* Отправляет сообщение всем игрокам сессии с состоянием мельниц на игровой доске
*/
private _sendToAllUpdateMerellusMessage(): void
{
for ( const player of this._session )
{
this._sendMessage(
player.connection,
{
type: 'changeMerellus',
lines: this._board.merellus,
},
)
.catch( onError );
}
}
/**
* Отправляет сообщение всем игрокам сессии об обновлении количества свободных фишек у заданного игрока
*
* @param updatingPlayer Заданный игрок
*/
private _sendToAllChangeFreeCheckersMessage( updatingPlayer: Player ): void
{
for ( const player of this._session )
{
this._sendMessage(
player.connection,
{
type: 'changeFreeCheckers',
color: updatingPlayer.сolor,
freeCheckers: updatingPlayer.freeCheckers,
},
)
.catch( onError );
}
};
/**
* Отправляет сообщение игроку о смене ходящего игрока
*
* @param updatingPlayer Игрок, которому отправляется сообщение
* @param isPlayerTurn Ход этого игрока?
*/
private _sendChangePlayerMessage( updatingPlayer: Player, isPlayerTurn: boolean ): void
{
this._sendMessage(
updatingPlayer.connection,
{
type: 'changePlayer',
myTurn: isPlayerTurn,
},
)
.catch( onError );
};
/**
* Отправляет сообщение игроку об обновлении его состояния в игре
*
* @param updatingPlayer Игрок, которому отправляется сообщение
*/
private _sendChangePlayerStateMessage( updatingPlayer: Player ): void
{
this._sendMessage(
updatingPlayer.connection,
{
type: 'changePlayerState',
myState: updatingPlayer.playerState,
},
)
.catch( onError );
};
/**
* Отправляет сообщение всем игрокам сессии об окончании игры и её результат
*/
private _sendToAllEndGameMessage(): void
{
for ( const player of this._session )
{
this._sendMessage(
player.connection,
{
type: 'gameResult',
win: player.сolor !== this._currentPlayerColor,
},
)
.catch( onError );
}
};
/**
* Обрабатывает запрос игрока на выставление или передвижение своей фишки
*
* @param from Клетка, из которой передвинуть фишку
* @param to Клетка, в которой должна оказаться фишка
* @param currentPlayer Игрок, от которого поступило сообщение
*/
private _onPlayerMoveChecker( from: string | null, to: string, currentPlayer: Player): void
{
if ( currentPlayer.сolor !== this._currentPlayerColor )
{
this._sendIncorrectCurrentPlayerMessage( currentPlayer.connection );
return;
}
if (
currentPlayer.playerState === 'removingChecker'
|| currentPlayer.playerState === 'finish'
)
{
this._sendIncorrectMoveMessage( currentPlayer.connection, 'Вы не можете сейчас передвигать свои фишки' );
return;
}
// Если from задано, то подразумевается передвижение фишки
// Если from отсутствует, то подразумевается выставление фишки
if ( !Board.isExist( to ) )
{
this._sendIncorrectMoveMessage( currentPlayer.connection, `Новая клетка ${to} не существует` );
return;
}
else if ( !from )
{
// 1-ый этап, нестрогое выставление в любую клетку свободных фишек
if ( currentPlayer.playerState === '1_part' )
{
if ( this._board.haveCheckerOn( to ) === undefined )
{
this._board.setChecker( to, currentPlayer.сolor );
currentPlayer.setCheckerOnBoard();
this._sendToAllChangeFreeCheckersMessage( currentPlayer );
}
else
{
this._sendIncorrectMoveMessage( currentPlayer.connection, `Клетка ${to} уже занята` );
return;
}
}
else
{
this._sendIncorrectMoveMessage( currentPlayer.connection, 'Ход не соответствует этапу игры' );
return;
}
}
else if ( !Board.isExist( from ) )
{
this._sendIncorrectMoveMessage( currentPlayer.connection, `Предыдущая клетка ${from} не существует` );
return;
}
else
{
// 2-ой этап, строгое передвижение выставленных фишек вдоль линии на 1 шаг
// или 3-й этап, нестрогое передвижение выставленных фишек в любую клетку
if (
this._board.haveCheckerOn( from ) === currentPlayer.сolor
&& this._board.haveCheckerOn( to ) === undefined
)
{
if (
currentPlayer.playerState === '3_part'
|| ( currentPlayer.playerState === '2_part' && this._isPossibleMove( from, to ) )
)
{
this._board.moveChecker( from, to );
}
else
{
this._sendIncorrectMoveMessage(
currentPlayer.connection,
`Ход из ${from} в ${to} нарушает правила этапа - только строгий ход на одну клетку по линии`
);
return;
}
}
else
{
this._sendIncorrectMoveMessage( currentPlayer.connection, `Предыдущая клетка ${from} не Ваша или ${to} не пуста` );
return;
}
}
this._sendToAllUpdateBoardMessage();
// Проверка на новые мельницы, их запись
const newMerellus: string[] = this._isNewMerellus( to );
for ( const line of newMerellus )
{
this._board.setMerellus( line, currentPlayer.сolor );
}
// Проверка смены состояний игроков
for ( const player of this._session )
{
const newPlayerState = this._checkPlayerState( player );
if ( player.playerState !== newPlayerState )
{
player.setPlayerState( newPlayerState );
this._sendChangePlayerStateMessage( player );
}
}
// Рассылка новых мельниц только после смены состояний игроков
if ( newMerellus.length !== 0 )
{
this._sendToAllUpdateMerellusMessage();
return;
}
// Рассылка всем смены ходящего игрока
this._changeCurrentPlayer();
for ( const player of this._session )
{
if ( player.сolor === this._currentPlayerColor )
{
currentPlayer = player;
this._sendChangePlayerMessage( player, true );
}
else
{
this._sendChangePlayerMessage( player, false );
}
}
// Конец игры, если ходящий игрок не имеет возможности хода
if ( currentPlayer.playerState === 'finish' )
{
this._sendToAllEndGameMessage();
}
}
/**
* Обрабатывает запрос игрока удаление фишки соперника с поля
*
* @param from Клетка, из которой убрать фишку
* @param currentPlayer Игрок, от которого поступило сообщение
*/
private _onPlayerRemoveChecker( from: string, currentPlayer: Player): void
{
if ( currentPlayer.сolor !== this._currentPlayerColor )
{
this._sendIncorrectCurrentPlayerMessage( currentPlayer.connection );
return;
}
if (
currentPlayer.playerState === 'removingChecker'
&& Board.isExist( from )
)
{
if ( this._board.haveCheckerOn( from ) === this._getSecondPlayer( currentPlayer ).сolor )
{
this._board.removeChecker( from );
}
else
{
this._sendIncorrectMoveMessage( currentPlayer.connection, `Клетка ${from} пустая или принадлежит Вам` );
return;
}
}
else
{
this._sendIncorrectMoveMessage(
currentPlayer.connection,
`Вы не можете сейчас убрать фишку соперника или клетка ${from} не существует`
);
return;
}
this._sendToAllUpdateBoardMessage();
// Если нереализованных мельниц больше нет, то смена состояний и ходящего игрока
if ( !this._hasUnusedMerellus() )
{
for ( const player of this._session )
{
const newPlayerState = this._checkPlayerState( player );
if ( player.playerState !== newPlayerState )
{
player.setPlayerState( newPlayerState );
this._sendChangePlayerStateMessage( player );
}
}
this._changeCurrentPlayer();
for ( const player of this._session )
{
if ( player.сolor === this._currentPlayerColor )
{
currentPlayer = player;
this._sendChangePlayerMessage( player, true );
}
else
{
this._sendChangePlayerMessage( player, false );
}
}
// Конец игры, если ходящий игрок не имеет возможности хода
if ( currentPlayer.playerState === 'finish' )
{
this._sendToAllEndGameMessage();
}
}
}
}
export {
Game,
};
|
cbe4ca9dcbb3dd46bd5e27eb16e0f4f86a913329
|
TypeScript
|
lumio/dockery
|
/src/lib/docker/checkIfImageExists.ts
| 2.78125
| 3
|
import runCommand from '../runCommand';
const checkIfImageExists = async (
tag: string,
cwd: string,
failIfExists: boolean = true,
): Promise<string | false> => {
let result;
try {
result = await runCommand('docker', ['images'], cwd, true);
} catch (e) {
result = e;
}
if (result.exitCode) {
throw new Error('Failed checking for current docker image list');
}
const tagParts = tag.split(':');
const imageList = result.stdout.split('\n').splice(1);
for (const image of imageList) {
if (!image.trim()) {
continue;
}
const imageParts = image.split(/\s+/);
if (tagParts[0] === imageParts[0] && tagParts[1] === imageParts[1]) {
if (!failIfExists) {
return imageParts[2];
}
throw new Error(`Image with the tag ${tag} already exists`);
}
}
return false;
};
export default checkIfImageExists;
|
4be0333f9a071621d11f885fd077c4e338d27d07
|
TypeScript
|
IvoKroon/PRG08-Week3-oefening2
|
/dev/washing.ts
| 2.578125
| 3
|
class Washing extends Behavior{
constructor(jibby:Jibby){
super(jibby);
}
performBehavior() : void{
console.log("Washing");
this.jibby.div.style.backgroundImage = "url('images/washing.png')";
// this.div.style.backgroundImage = "url('images/washing.png')";
}
update(){
super.update();
if(this.checkTimer()){
this.jibby.hygiene += 10;
this.jibby.setBehavior(new Happy(this.jibby));
}
}
onWash(){}
onPet(){
this.jibby.setBehavior(new Angry(this.jibby));
}
onEat(){
this.jibby.setBehavior(new Angry(this.jibby));
}
}
|
d3d67f9d754769937ece3158227ba1063ff25549
|
TypeScript
|
2muchcoffeecom/invoice-app-api
|
/src/modules/shared/errors/parse-error.interceptor.ts
| 2.59375
| 3
|
import { HttpException, Injectable, ExecutionContext, CallHandler, NestInterceptor } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ParsedError } from './parsed-error';
@Injectable()
export class ParseErrorInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
return next
.handle()
.pipe(
catchError((error: ParsedError) => {
let parsedError: Error = error;
/**
* Condition to parse before unparsed error.
* Looking for better solution.
*/
if (!(error instanceof HttpException) && !(error instanceof ParsedError)) {
parsedError = new ParsedError(error);
}
return throwError(parsedError);
}),
);
}
}
|
50dd9e196e795b6d28cfab50ac81375afe6afbd9
|
TypeScript
|
smashdevcode/the-latest-on-typescript-2016
|
/demos/promises/index.ts
| 3.421875
| 3
|
'use strict';
function f() {
return new Promise<string>((resolve, reject) => {
resolve('Original value');
// reject(new Error('Something went wrong!'));
});
}
f().then(value => {
console.log(value);
return 'New value 1';
}).catch(error => {
console.log('Oh oh!');
throw error;
}).then(value => {
console.log(value);
return 'New value 2';
}).catch(error => {
console.error(error);
return 'Caught value!';
}).then(value => console.log(value));
|
94eece16a956bfe0ad836b3d1a3ec55d2ecc5cee
|
TypeScript
|
DawnLck/umi-plugin-extensions
|
/types/chromeManifest/TTSEngine.d.ts
| 2.625
| 3
|
declare namespace chromeManifest {
export interface TTSEngine {
voices?: Voice[];
}
export interface Voice {
voice_name: string;
lang: string;
event_types?: EventType[];
}
type EventType =
/**
*
The engine has started speaking the utterance.
*/
| 'start'
/**
* A word boundary was reached. Use `event.charIndex` to
* determine the current speech position.
*/
| 'word'
/**
* A sentence boundary was reached. Use `event.charIndex` to
* determine the current speech position.
*/
| 'sentence'
/**
* An SSML marker was reached. Use `event.charIndex` to
* determine the current speech position.
*/
| 'marker'
/**
* The engine has finished speaking the utterance.
*/
| 'end'
/**
* An engine-specific error occurred and this utterance cannot be spoken.
* Pass more information in event.errorMessage.
*/
| 'error';
}
|
86a9a7c3df2ec57311f2893e1146bb54b27cfc59
|
TypeScript
|
LiskHQ/lisk-sdk
|
/elements/lisk-codec/src/utils/default_value.ts
| 2.59375
| 3
|
/*
* Copyright © 2020 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
import { BaseTypes } from '../types';
export const getDefaultValue = (dataType: string): BaseTypes => {
switch (dataType) {
case 'string':
return '';
case 'boolean':
return false;
case 'bytes':
return Buffer.alloc(0);
case 'uint32':
case 'sint32':
return 0;
case 'uint64':
case 'sint64':
return BigInt(0);
default:
throw new Error('Invalid data type');
}
};
|
a6906410fb589bf8ff9c3d10b3ff3746a6970920
|
TypeScript
|
daangemist/superplug
|
/src/package/reader.ts
| 2.609375
| 3
|
import fs from 'fs';
import { promisify } from 'util';
import { Package } from './types';
const readFile = promisify(fs.readFile);
export default async function read(path: string): Promise<Package> {
const contents = await readFile(path);
return JSON.parse(contents.toLocaleString()) as Package;
}
module.exports = read
|
b90cd8bc53be8a405a7b12215e4e2bdf8d2d5ead
|
TypeScript
|
arthurvenicio/CursoTs
|
/src/A0042-es2020-operators/index.ts
| 4.09375
| 4
|
// Encadeamento opcional e Operador de coalescência nula
// Encadeamento opcional = ? // ex: documento.data?.toDateString()
// Operador de coalescência nula = Checar se o valor recebido no lado esquerdo é um não valor : null e undefined
// ex: documento.data?.toDateString() ?? 'Não existe data' // quando não tiver executa a opção ao lado nesse caso o 'Não...'
type Documento = {
titulo: string;
texto: string;
data?: Date;
};
const documento: Documento = {
titulo: 'O titulo',
texto: 'O texto',
// data: new Date(),
};
console.log(documento.data?.toDateString() ?? 'Não existe data!');
|
d27c4f99ca730abefb3e172c153e3c3c532dc2c8
|
TypeScript
|
iloveivyxuan/vectorious
|
/src/core/subtract.spec.ts
| 3.1875
| 3
|
import {
deepStrictEqual,
throws,
} from 'assert';
import v = require('..');
describe('(v) subtract', () => {
it('should return empty vector if subtracting two empty vectors', () => {
const x: v = v.array();
const y: v = v.array();
deepStrictEqual(v.array(), x.subtract(y));
});
it('should throw error if sizes do not match', () => {
const x: v = v.array([1]);
const y: v = v.array([1, 2]);
throws(() => { x.subtract(y); }, Error);
});
it('should produce v(-3, -3, -3) from v(1, 2, 3) and v(4, 5, 6)', () => {
const x: v = v.array([1, 2, 3]);
const y: v = v.array([4, 5, 6]);
const z: v = v.array([-3, -3, -3]);
deepStrictEqual(z, x.subtract(y));
});
it('should work as the static equivalent', () => {
const x: v = v.array([1, 2, 3]);
const y: v = v.array([4, 5, 6]);
const z: v = v.array([-3, -3, -3]);
deepStrictEqual(z, v.subtract(x, y));
});
});
|
515bfbc48676b86a2aefea3ab946e9ad68b37698
|
TypeScript
|
EitanElbaz/json-2-yup
|
/src/tests/types/number/typeError.test.ts
| 2.765625
| 3
|
import { NumberSchema, ValidationError } from 'yup';
import to from 'await-to-js';
import { NumberTypeSchema } from 'src/types';
import { toYup } from 'src/toYup';
const errorMsg = 'Has to be a number';
const schema: NumberTypeSchema = {
type: 'number',
strict: true,
required: true,
errors: {
typeError: errorMsg,
},
};
const yupSchema = toYup(schema) as NumberSchema;
test('typeError expect fail', async () => {
expect(yupSchema.isValidSync('5')).toBe(false);
expect(yupSchema.isValidSync(false)).toBe(false);
expect(yupSchema.isValidSync([])).toBe(false);
expect(yupSchema.isValidSync({})).toBe(false);
expect(yupSchema.isValidSync(null)).toBe(false);
expect(yupSchema.isValidSync(undefined)).toBe(false);
});
test('typeError expect pass', async () => {
expect(yupSchema.isValidSync(5)).toBe(true);
});
test('typeError expect fail message', async () => {
const [error] = await to(yupSchema.validate('5'));
expect((error as ValidationError).message).toBe(errorMsg);
});
|
38f09a401d77b9d9ec9c7a491bcd4fc954886953
|
TypeScript
|
tkddn204/cra-template-rightpair
|
/template/src/Components/Theme/themeSlice.ts
| 2.796875
| 3
|
import { createSlice, CaseReducer, SliceCaseReducers } from '@reduxjs/toolkit'
export type ThemeState = 'default' | 'dark'
type SliceName = 'theme'
interface CaseReducers extends SliceCaseReducers<ThemeState> {
changeThemeMode: CaseReducer<ThemeState>
}
const themeSlice = createSlice<ThemeState, CaseReducers, SliceName>({
name: 'theme',
initialState: 'default',
reducers: {
changeThemeMode: (state, action): void => {
state = action.payload
},
},
})
export const { changeThemeMode } = themeSlice.actions
export default themeSlice.reducer
|
55a4b8d805b07b07471465af5bbb1a7cb81734f6
|
TypeScript
|
theednaffattack/create-project
|
/src/templates/project-templates/backend/src/modules/user/edit-user-info.ts
| 2.75
| 3
|
import { Arg, Resolver, Mutation, UseMiddleware, Ctx } from "type-graphql";
import { User } from "../../entity/User";
import { EditUserInput } from "./register/edit-user-input";
import { isAuth } from "../middleware/isAuth";
import { loggerMiddleware } from "../middleware/logger";
import { MyContext } from "../../types/MyContext";
let errorMessageBase = "Error saving info to database";
@Resolver()
export class EditUserInfoResolver {
@UseMiddleware(isAuth, loggerMiddleware)
@Mutation(() => User)
async editUserInfo(
@Arg("data")
{ email, firstName, lastName }: EditUserInput,
@Ctx() ctx: MyContext
): Promise<any> {
// most efficient way to set records in the DB
// returns nothing
await User.createQueryBuilder()
.update(User)
.set({ email, firstName, lastName })
.where("id = :id", { id: ctx.userId })
.execute()
.then(data => console.log(data))
.catch(error => console.error(error));
// since an error is thrown above on errors
// it may be smarter to return the data passed in via
// arguments rather than perform a lookup
let userToReturn = await User.createQueryBuilder()
.where("id = :id", { id: ctx.userId })
.getOne()
.catch(error => {
console.error(error);
throw Error(`${errorMessageBase}\n${error}`);
});
console.log({ userToReturn });
return userToReturn;
}
}
|
778b407cd3cc9cd3bbadd3b8de8c009b688612ab
|
TypeScript
|
spitfiremunguia/viaro_nodeks
|
/src/controllers/account.controller.ts
| 2.5625
| 3
|
import { Account } from '../models/Account';
import {AccountService} from '../services/account.service';
import {AuthService}from '../services/auth.service';
import {CustomError} from '../models/CustomError';
const objectidRegex=/^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i;
export class AccountController
{
private accountService:AccountService;
private authService:AuthService;
constructor(accountService:AccountService,authService:AuthService)
{
this.accountService=accountService;
this.authService=authService;
}
public async GetUser(id:string)
{
// validate userid
const user=await this.accountService.GetUser(id);
if(!user)
throw new CustomError(404,'USER NOT FOUND');
return user;
}
public async CreateAccount(account:Account)
{
const usernameExists=await this.accountService.UsernameExists(account.credentials.username);
if(usernameExists)
throw new CustomError (400,'USERNAME NOT AVAILABLE');
// need to encryp account credentials first
let id:string;
try{
id=await this.accountService.CreateAccount(account);
}
catch(err){
throw new CustomError(400,err.message);
}
// create token
const newToken=this.authService.createAuthToken(id);
const result={
accountid:id,
token:newToken
}
return result;
}
}
|
1d41a7f78daecca7812438ed9c350006891108f8
|
TypeScript
|
ManuSquall/TypeScript-Website-Localizations
|
/docs/playground/zh/TypeScript/Primitives/Unknown and Never.ts
| 4.21875
| 4
|
// Unknown
// Unknown is one of those types that once it clicks, you
// can find quite a lot of uses for it. It acts like a sibling
// to the any type. Where any allows for ambiguity - unknown
// requires specifics.
// 封装 JSON 解析器是一个不错的例子,JSON 数据可以以多种不同的形式出现,
// 并且 JSON 解析器函数的作者并不知道数据的形状。而调用解析函数的人应该知道。
const jsonParser = (jsonString: string) => JSON.parse(jsonString);
const myAccount = jsonParser(`{ "name": "Dorothea" }`);
myAccount.name;
myAccount.email;
// 如果你将鼠标悬停在 jsonParser 上,你可以看到它的返回值类型是 any,
// myAccount 也是如此,虽然可以使用泛型来解决这个问题,但是我们也可以使用 unknown。
const jsonParserUnknown = (jsonString: string): unknown => JSON.parse(jsonString);
const myOtherAccount = jsonParserUnknown(`{ "name": "Samuel" }`);
myOtherAccount.name;
// myOtherAccount 对象在类型声明给 TypeScript 之前不可以被使用,
// 这可以保证 API 的使用者预先考虑他们的类型。
type User = { name: string };
const myUserAccount = jsonParserUnknown(`{ "name": "Samuel" }`) as User;
myUserAccount.name;
// unknown 是一个很好的工具,可以查看这些以了解更多:
// https://mariusschulz.com/blog/the-unknown-type-in-typescript
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type
// Never
// 由于 TypeScript 支持代码流分析,语言必须可以表示在逻辑上不会执行的代码。
// 例如,这个函数将永远不会返回:
const neverReturns = () => {
// If it throws on the first line
throw new Error("Always throws, never returns");
};
// 如果你将鼠标悬停在 neverReturns 上,你可以看到它的类型是 () => never,
// 这代表着它永远不会执行。这依然可以像其他值一样传递:
const myValue = neverReturns();
// 对于处理不可预测的 JavaScript 运行时行为以及当 API 的使用者不适用类型时,
// 使函数永不返回(返回 never) 非常有用。
const validateUser = (user: User) => {
if (user) {
return user.name !== "NaN";
}
// 在类型系统中,这条路径上的代码永远不会被执行,这与 neverReturns 的
// 返回值类型 never 相匹配。
return neverReturns();
};
// 虽然类型定义规定用户必须按类型传递参数,但是在 JavaScript 中有足够
// 多的特殊情况,所以您不能保证这一点。
// 使用永不返回的函数可以允许您在一些不可能的地方上添加额外的代码。
// 这对于提供更好的错误信息,或者释放一些诸如文件的资源或循环时非常有用。
// 一个非常常见的 never 的使用方法是确保 switch 是被穷尽的。
// 也就是每个路径都有被覆盖到。
// 有一个枚举和一个穷尽的 switch,你可以尝试为枚举添加一个新的选项(例如 Tulip?)。
enum Flower {
Rose,
Rhododendron,
Violet,
Daisy,
}
const flowerLatinName = (flower: Flower) => {
switch (flower) {
case Flower.Rose:
return "Rosa rubiginosa";
case Flower.Rhododendron:
return "Rhododendron ferrugineum";
case Flower.Violet:
return "Viola reichenbachiana";
case Flower.Daisy:
return "Bellis perennis";
default:
const _exhaustiveCheck: never = flower;
return _exhaustiveCheck;
}
};
// 你会收到一个编译期错误,表示 flower 的类型不可以被转换为 never。
// 并集类型中的 Never
// never 会在并集类型中被自动移除。
type NeverIsRemoved = string | never | number;
// 如果你查看 NeverIsRemoved 的类型,你会看到它是 string | number。
// 这是因为在运行时你永远不能将 never 赋值给它,所以它永远不会发生。
// 这个特性经常被使用到:example:conditional-types
|
25100c6a35e6926ebe7dab60e224f5bee7b7edf9
|
TypeScript
|
Carloss-Jr/Projeto_Db
|
/src/controllers/ClienteController.ts
| 2.71875
| 3
|
import { Request, Response} from 'express'
import { getConnection, getCustomRepository } from 'typeorm'
import { Cliente } from '../entities/Cliente'
import { ClienteTelefone } from '../entities/ClienteTelefone'
import { ClienteRepository } from '../repositores/ClienteRepository'
class ClienteController {
async create(req: Request, res: Response) {
const { cpfCnpj, nome, endereco, telefones} = req.body
let data = { cpfCnpj, nome, endereco, telefones }
const repository = getCustomRepository(ClienteRepository)
data = await repository.save(data)
return res.status(201).json({data:data})
}
async update(req: Request, res: Response) {
const { id } = req.params
const {cpfCnpj, nome } = req.body
const cliente = { cpfCnpj, nome}
const repository = getCustomRepository(ClienteRepository)
await repository.update( id, cliente)
return res.status(200).json({msg: "Cliente alterado com sucesso " + cliente.cpfCnpj})
}
async list (req: Request, res: Response) {
const repository = getCustomRepository(ClienteRepository)
const data = await repository.find()
return res.status(200).json({data:data})
}
async find (req: Request, res: Response) {
const { id } = req.params
const repository = getCustomRepository(ClienteRepository)
const data = await repository.findOne(id)
return res.status(200).json({data:data})
}
async delete (req: Request, res: Response) {
const { id } = req.params
const repository = getCustomRepository(ClienteRepository)
await repository.delete(id)
return res.status(200).json({msg: "Registro deletado" + id})
}
async addTel (req: Request, res: Response) {
const { id } = req.params
const { ddd, numero, tipo } = req.body
const repository = getCustomRepository(ClienteRepository)
const cliente = await repository.findOne(id)
const telefone = new ClienteTelefone()
telefone.numero = numero
telefone.ddd = ddd
telefone.tipo = tipo
telefone.cliente = cliente
console.log(telefone)
cliente.telefones.push(telefone)
console.log(cliente)
await repository.save( cliente )
return res.status(200).json({msg: "Telefone adicionado com sucesso"})
}
async lisCity (req: Request, res: Response) {
const { nome } = req.params
const data = await getConnection()
.getRepository(Cliente)
.createQueryBuilder("cliente").innerJoin("cliente.endereco", "endereco")
.where("endereco.cidade = :nome", {nome: nome})
.getMany()
return res.status(200).json({ data:data })
}
}
export { ClienteController }
|
3b798ef29137191889c6010f30e99b6672284df6
|
TypeScript
|
swc-project/swc
|
/crates/swc_bundler/tests/.cache/deno/a001e0eaeb21f32126184e530076160ecf8f0dcd.ts
| 3.1875
| 3
|
// Loaded from https://deno.land/x/cliffy@v0.18.0/flags/normalize.ts
/**
* Normalize command line arguments.
* @param args Command line arguments e.g: `Deno.args`
*/
export function normalize(args: string[]) {
const normalized = [];
let inLiteral = false;
for (const arg of args) {
if (inLiteral) {
normalized.push(arg);
} else if (arg === "--") {
inLiteral = true;
normalized.push(arg);
} else if (arg.length > 1 && arg[0] === "-") {
const isLong = arg[1] === "-";
const isDotted = !isLong && arg[2] === ".";
if (arg.includes("=")) {
const parts = arg.split("=");
const flag = parts.shift() as string;
if (isLong) {
normalized.push(flag);
} else {
normalizeShortFlags(flag);
}
normalized.push(parts.join("="));
} else if (isLong || isDotted) {
normalized.push(arg);
} else {
normalizeShortFlags(arg);
}
} else {
normalized.push(arg);
}
}
return normalized;
/**
* Normalize short flags.
* @param flag Flag string: `-abc`
*/
function normalizeShortFlags(flag: string): void {
const flags = flag.slice(1).split("");
if (isNaN(Number(flag[flag.length - 1]))) {
flags.forEach((val) => normalized.push(`-${val}`));
} else {
normalized.push(`-${flags.shift()}`);
normalized.push(flags.join(""));
}
}
}
|
b2a82605b2a02b02e68d6ad678d55e1063d5e754
|
TypeScript
|
eugenioenko/interpreter
|
/src/token.ts
| 3.1875
| 3
|
export enum TokenType {
// Parser Tokens
Eof,
Panic,
Lambda,
// Single Character Tokens
Ampersand,
AtSign,
Caret,
Comma,
Dollar,
Dot,
Hash,
LeftBrace,
LeftBracket,
LeftParen,
Percent,
Pipe,
RightBrace,
RightBracket,
RightParen,
Semicolon,
Slash,
Star,
// One Or Two Character Tokens
Arrow,
Bang,
BangEqual,
Colon,
Equal,
EqualEqual,
Greater,
GreaterEqual,
Less,
LessEqual,
Minus,
MinusEqual,
MinusMinus,
PercentEqual,
Plus,
PlusEqual,
PlusPlus,
Question,
QuestionDot,
QuestionQuestion,
SlashEqual,
StarEqual,
DotDot,
DotDotDot,
LessEqualGreater,
// Literals
Identifier,
Template,
String,
Number,
Regex,
// Keywords
And,
Break,
Base,
Class,
Continue,
Delete,
Do,
Else,
Extends,
False,
For,
Foreach,
Function,
If,
In,
Instanceof,
Is,
New,
None,
Null,
Or,
Print,
Return,
True,
Typeof,
Var,
Void,
While,
With,
}
export class Token {
public name: string;
public line: number;
public col: number;
public type: TokenType;
public literal: any;
public lexeme: string;
constructor(
type: TokenType,
lexeme: string,
literal: any,
line: number,
col: number
) {
this.name = TokenType[type];
this.type = type;
this.lexeme = lexeme;
this.literal = literal;
this.line = line;
this.col = col;
}
public toString() {
return `[(${this.line}):"${this.lexeme}"]`;
}
}
|
ebfc5a3eb1d55b5780516a4f22d0f4026e1091ce
|
TypeScript
|
Xamian/easy-template-x
|
/dist/misc.d.ts
| 2.734375
| 3
|
export type Binary = Blob | Buffer | ArrayBuffer;
export enum MimeType {
Png = 'image/png',
Jpeg = 'image/jpeg',
Gif = 'image/gif',
Bmp = 'image/bmp',
Svg = 'image/svg+xml'
}
export interface IMap<T> {
[key: string]: T;
}
export interface Constructor<T> {
new(...args: any[]): T;
}
|
d5d3f7ddf158260a2b737613534980c07170e39b
|
TypeScript
|
udecode/plate
|
/packages/test-utils/src/createDataTransfer.ts
| 2.96875
| 3
|
export type DataTransferDataType = 'text/plain' | 'text/html' | string;
export type DataTransferDataMap = Map<DataTransferDataType, unknown>;
export const createDataTransfer = (dataMap: DataTransferDataMap = new Map()) =>
({
getData: (type: string) => dataMap.get(type) ?? '',
setData: (type: string, value: string) => dataMap.set(type, value),
}) as unknown as DataTransfer;
|
cbde4c6bf96a36b9a8ea347290f94c9ab7122580
|
TypeScript
|
Ulrikop/cucumber-7
|
/src/index.ts
| 2.734375
| 3
|
import { DataTable } from '@cucumber/cucumber';
import type { IParameterTypeDefinition } from '@cucumber/cucumber/lib/support_code_library_builder/types';
export function parseSomething(parser: DataTable) {
return parser.rows;
}
/**
* Will be later used `defineParameterType(timeParameterType)`.
*/
export const timeParameterType: IParameterTypeDefinition<{ hours: number; minutes: number; seconds: number }> = {
name: 'time',
regexp: /(\d\d):(\d\d)(?::(\d\d))?/u,
transformer: (...parts) => {
const [hours = 0, minutes = 0, seconds = 0] = parts.map(part => parseInt(part));
return {
hours,
minutes,
seconds,
};
},
};
|
5eb147948294d6bc19adc0a54bdb3af2d7ef84b8
|
TypeScript
|
zougui1/drawings
|
/packages/drawer/src/V2/utils/segment.ts
| 2.921875
| 3
|
import { Position } from '../commands';
const rePathSeparation = /[ ,\n]+/g;
export const parseSegment = (segment: string): [Position, ...number[]] => {
const [command, ...numberStrings] = segment
.replace(rePathSeparation, ' ')
.split(' ');
const position = command.toUpperCase() === command
? Position.absolute
: Position.relative;
const numbers = numberStrings.map(num => Number(num));
return [position, ...numbers];
}
|
b571d9d54e33bb4d862280334cfc801b5b0a5e24
|
TypeScript
|
petkoxray/JavaScript-Data-Structures-and-Algorithms-Book
|
/Chapter 5 Lists/LinkedList.ts
| 3.859375
| 4
|
class LinkedList<T> {
private head: null | ListNode<T>;
private count: number;
constructor() {
this.head = null;
this.count = 0;
}
AddLast(value: T): void {
if (this.head === null) {
this.head = new ListNode<T>(value);
} else {
let currentNode = this.head;
while (currentNode.next !== null) {
currentNode = currentNode.next;
}
currentNode.next = new ListNode<T>(value);
}
this.count++;
}
AddFirst(value: T): void {
let newNode = new ListNode<T>(value);
newNode.next = this.head;
this.head = newNode;
this.count++;
}
RemoveAt(position: number): T {
if (position > -1 && position < this.count) {
let current = this.head,
previous,
index = 0;
if (position === 0) {
this.head = this.head.next;
} else {
while (++index <= position) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.count--;
return current.value;
} else {
throw new RangeError("Invalid index");
}
}
RemoveFirst(): T {
if (this.isEmpty()) {
throw new RangeError("List is empty!");
}
return this.RemoveAt(0);
}
RemoveLast(): T {
if (this.isEmpty()) {
throw new RangeError("List is empty!");
}
return this.RemoveAt(this.count - 1);
}
get Count(): number {
return this.count;
}
isEmpty(): boolean {
return this.count === 0;
}
indexOf(value: T): number {
let current = this.head,
index = 0;
while (current) {
if (value === current.value) {
return index;
}
index++;
current = current.next;
}
return -1;
}
forEach = (func) => {
let cur = this.head;
while (cur) {
func(cur.value);
cur = cur.next;
}
}
ToArray(): Array<T> {
let arr = new Array<T>(this.count);
let index = 0;
let currentNode = this.head;
while (currentNode !== null) {
arr[index++] = currentNode.value;
currentNode = currentNode.next;
}
return arr;
}
}
class ListNode<T> {
public next: ListNode<T> | null;
constructor(public value: T) {
this.next = null;
}
}
let ll = new LinkedList<string>();
ll.AddLast("migsho");
ll.AddLast("gosho");
ll.AddLast("pesho");
ll.AddFirst("dido");
// console.log(ll.RemoveFirst());
// console.log(ll.RemoveLast());
// console.log(ll.ToArray());
// console.log(ll.indexOf("gdosho"));
// console.log(ll.ToArray());
ll.forEach((el) => {
console.log(el);
});
|
4f452418647820ba536e60cbc1993d7e06477039
|
TypeScript
|
JosifV/ChemApp
|
/server/src/controllers/utils/seeder.ts
| 3.328125
| 3
|
import { shufleArr } from "./shufleArr"
export const seeder = (): string[] => {
let arrToReturn: string[] = []
let arrOfEls: string[] = shufleArr(["H", "O", "C"])
for (let n = 0; n < 15000; n++) {
if (n % 2 === 0) arrToReturn.push(arrOfEls[0])
else if (n % 3 === 0) arrToReturn.push(arrOfEls[1])
else if (n % 5 === 0) arrToReturn.push(arrOfEls[2])
}
return arrToReturn
}
|
b9443220a0cdf012b4227af84aec448777e11d8f
|
TypeScript
|
VertaAI/modeldb
|
/webapp/client/src/shared/routes/makeRoute.ts
| 2.59375
| 3
|
import qs from 'query-string';
import { matchPath, generatePath } from 'react-router';
import * as PathBuilder from './pathBuilder';
type AllowedUserType = 'unauthorized' | 'authorized' | 'any';
export interface IRouteSettings<
Params,
QueryParams extends Record<any, any> | undefined = undefined
> {
getPath: () => string;
allowedUserType: AllowedUserType;
}
export interface IRoute<
Params,
QueryParams extends Record<any, any> | undefined = undefined,
GetRedirectPathOptions = Params
> {
allowedUserType: AllowedUserType;
getPath: () => string;
getRedirectPath: (options: GetRedirectPathOptions) => string;
getRedirectPathWithQueryParams: (opts: {
params: Params;
queryParams: Partial<QueryParams>;
}) => string;
parseQueryParams: (location: string) => Partial<QueryParams> | undefined;
getMatch(location: string, exact?: boolean): Params | null;
}
export const makeRouteFromPath = <Path extends PathBuilder.IPath<any, any>>({
getPath,
...restSettings
}: { getPath: () => Path } & Omit<IRouteSettings<any, any>, 'getPath'>): IRoute<
PathBuilder.GetParams<Path>,
PathBuilder.GetQueryParams<Path>
> => {
return makeRoute({
getPath: () => getPath().value,
...restSettings,
});
};
export default function makeRoute<
Params extends Record<any, any>,
QueryParams extends Record<any, any> | undefined = undefined,
GetRedirectPathOptions extends Record<any, any> = Params
>({
getPath,
allowedUserType,
}: IRouteSettings<Params, QueryParams>): IRoute<Params, QueryParams> {
return {
allowedUserType,
getPath,
getRedirectPath: (options: GetRedirectPathOptions) => {
const path = getPath();
return generatePath(path, { ...options });
},
getRedirectPathWithQueryParams({ params, queryParams }) {
const queryParamsInPath = Object.entries((queryParams || {}) as Record<
any,
any
>)
.map(([key, value]) => `${key}=${value}`)
.join('&');
return `${this.getRedirectPath(params)}?${queryParamsInPath}`;
},
parseQueryParams: (search: string) => {
return (qs.parseUrl(search).query || undefined) as any;
},
getMatch: (location: string, exact: boolean = true) => {
const path = getPath();
const match = matchPath<Params>(location, { path, exact });
if (match) {
return match.params;
}
return null;
},
};
}
|
7a5043eacb8ba5308361584c9468692fbfc15b84
|
TypeScript
|
vinukumar-vs/angular-event-generator
|
/src/app/factory/event-factory.service.ts
| 3.09375
| 3
|
import { AppEvents } from '../interfaces/app-events';
import { ErrorEventService } from '../services/error-event.service';
export class EventFactoryService {
constructor() { }
/**
* Library/Application will call this method to generate specific event based on condition where they want to generate the event.service
*
* @param eventName
* @param data
*/
trigger(eventName, data) {
switch(eventName) {
case AppEvents.ERROR :
// Generate specific event instance based on EventName
let errorEventSerObj = new ErrorEventService();
errorEventSerObj.emit(data);
break;
case AppEvents.SUCCESS :
console.log("No implementation");
break;
default :
console.log(`There is no implementation for the event: ${eventName}`);
break;;
}
}
}
|
05f6ce0fc3353c47ddf7137419e60ecaebc8db6f
|
TypeScript
|
fengzhicool163/Sibo
|
/src/lobbySrc/practical/components/LobbyTabelPageBox.ts
| 2.765625
| 3
|
module lobby.component{
/** 游戏房间牌桌列表页面盒子 */
export class LobbyTabelPageBox extends common.component.UIBox{
public bindObj : ui.lobbyUI.Boxs.LobbyTabelPageBoxUI;
protected barPool : util.PoolView;
protected curShowTableBar : Array<LobbyTableBarBox>;
protected initComponents() {
//牌桌条缓存池
this.barPool = new util.PoolView(LobbyTableBarBox,ui.lobbyUI.Boxs.LobbyTableBarBoxUI,4,4);
//牌桌条
this.curShowTableBar = [];
}
/** 重置页面回收牌桌条 */
public resetBox() {
for (let index = 0; index < this.curShowTableBar.length; index++) {
const bar = this.curShowTableBar[index];
bar.clearBox();
this.barPool.recover(bar);
}
this.curShowTableBar.length = 0;
}
/** 重置页面并隐藏 */
public clearBox() {
this.resetBox();
this.bindObj.visible = false;
}
/** 销毁页面 */
public destroy(){
this.clearBox();
this.barPool.destroy();
super.destroy();
}
/**
* 设置页面数据 data下的tables数据
* @param roomData
*/
public setData( roomData : any ) {
//重置
this.resetBox();
//生成牌桌条
for (let index = 0; index < roomData.tables.length; index++) {
const tableData = roomData.tables[index];
tableData.roomId = roomData.roomid;
const tableBar = this.barPool.getComponent();// as LobbyTableBarBox;
tableBar.setData(tableData);
this.bindObj.barNode.addChild(tableBar.bindObj);
tableBar.bindObj.y = index * 260;
this.curShowTableBar.push(tableBar);
}
//刷新页面大小
//this.bindObj.barNode.width = 900;
this.bindObj.barNode.height = roomData.tables.length * 270;
}
public onTest(){
console.log("sssssssss");
}
}
}
|
a379958efecadf547e3eb3acd138f36fec5a9fcd
|
TypeScript
|
aesy/geem
|
/src/scripts/Systems/RenderSystem.ts
| 2.609375
| 3
|
import {
Object3D,
Scene,
WebGLRenderer,
VSMShadowMap,
} from 'three';
import { Entity } from '../Entities/Entity';
import { EntityRemoved } from '../Event/EntityRemoved';
import { Game } from '../Game/Game';
import { System } from './System';
export class RenderSystem extends System {
public readonly renderer: WebGLRenderer;
private readonly scene: Scene;
private readonly deleted: Object3D[] = [];
public constructor() {
super();
const { innerHeight, innerWidth } = window;
const scene = new Scene();
const renderer = new WebGLRenderer();
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = VSMShadowMap;
renderer.setClearColor(0x5D95A9);
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
this.scene = scene;
this.renderer = renderer;
}
public initialize(game: Game): void {
game.events.register(EntityRemoved, (event: EntityRemoved) => {
const entity = event.entity;
const object = entity.getComponent(Object3D);
this.deleted.push(object);
});
}
public appliesTo(entity: Entity): boolean {
return entity.hasComponent(Object3D);
}
public update(dt: number, entities: Entity[], game: Game): void {
while (this.deleted.length) {
const deleted = this.deleted.pop()!;
this.scene.remove(deleted);
}
for (const entity of entities) {
const object = entity.getComponent(Object3D);
this.scene.add(object);
}
this.renderer.render(this.scene, game.camera);
}
}
|
7f5b1d7ff2b1d8c4764925f9075c5e9eb731ce82
|
TypeScript
|
mateogalic112/next-ts-ecommerce
|
/pages/api/auth/me.ts
| 2.546875
| 3
|
import axios, { AxiosError, AxiosResponse } from 'axios';
import cookie from 'cookie';
import type { NextApiRequest, NextApiResponse } from 'next';
import { API_URL } from '../../../config';
import { User } from '../../../models/User';
export default async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') {
if (!req.headers.cookie) {
res.status(403).json({
message: 'Not authorized!',
});
return;
}
const { token } = cookie.parse(req.headers.cookie);
await axios
.get<User | AxiosError>(`${API_URL}/users/me`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((r: AxiosResponse<User>) => {
res.status(r.status).json({ user: r.data, jwt: token });
})
.catch((err: AxiosError) => {
res.status(err.response?.status || 403).json({
message: err.response?.data,
});
});
} else {
res.setHeader('Allow', ['GET']);
res.status(405).json({ message: `Method ${req.method} not allowed` });
}
};
|
203e6fc7abdb5be1aca3e17744f010767dcb9cce
|
TypeScript
|
pinyin/tslint
|
/ts/onlyImportFromIndexRule.ts
| 2.625
| 3
|
import {assume, Maybe, notExisting} from '@pinyin/maybe'
import * as path from 'path'
import * as tslint from 'tslint'
import * as ts from 'typescript'
export class OnlyImportFromIndexRule extends tslint.Rules.TypedRule {
static metadata: tslint.IRuleMetadata = {
ruleName: 'only-import-from-index',
type: 'style',
description: 'When a directory contains an file named index (e.g. index.ts, index.js), files outside of the directory can no longer import other files in the directory except the index. Only import statements are checked at this moment.',
options: null,
optionsDescription: '',
typescriptOnly: false,
}
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): tslint.RuleFailure[] {
const walker = new Walker(sourceFile, this.getOptions(), program)
return this.applyWithWalker(walker)
}
}
export const Rule = OnlyImportFromIndexRule // For naming conversion
type Path = string
type TargetNode = ts.ImportDeclaration | ts.ExportDeclaration
function isTargetNode(node: ts.Node): node is TargetNode {
return ts.isImportDeclaration(node) || ts.isExportDeclaration(node)
}
class Walker extends tslint.ProgramAwareRuleWalker {
protected visitSourceFile(node: ts.SourceFile): void {
node.statements
.filter(isTargetNode)
.forEach(statement => this.visitTargetNode(statement as TargetNode))
}
private hasIndex = new Map<Path, boolean>()
private indexAtPath = new Map<Path, Path>()
protected visitTargetNode(node: TargetNode): void {
if (notExisting(node.moduleSpecifier) || !ts.isStringLiteral(node.moduleSpecifier)) {
return
}
if (!node.parent || !ts.isSourceFile(node.parent)) {
return
}
const fromPath = path.normalize(node.parent.fileName)
const moduleLiteral = node.moduleSpecifier.text
const indexedAncestor = this.getIndexedPath(moduleLiteral, fromPath)
if (notExisting(indexedAncestor)) {
return
}
const fix = assume(node.moduleSpecifier, specifier => {
const start = specifier.getFullStart()
const width = specifier.getFullWidth()
return new tslint.Replacement(start, width, indexedAncestor)
})
this.addFailureAtNode(
node,
errorMessage(indexedAncestor),
fix,
)
}
private getIndexedPath(moduleSpecifierText: string, fromPath: Path): Maybe<Path> {
const compiler = this.getProgram()
const compilerOptions = compiler.getCompilerOptions()
const baseDIR = path.normalize(compiler.getCurrentDirectory()) // fixme
if (!moduleSpecifierText.startsWith('.')) {
return null
}
const moduleResolved = ts.resolveModuleName(moduleSpecifierText, fromPath, compilerOptions, ts.sys)
if (!moduleResolved || !moduleResolved.resolvedModule) {
return null
}
const targetPath = path.normalize(moduleResolved.resolvedModule.resolvedFileName)
const fromAncestors = getAncestorsSince(fromPath, baseDIR)
const targetAncestors = getAncestorsSince(targetPath, baseDIR)
for (const targetAncestor of targetAncestors) {
if (fromAncestors.includes(targetAncestor)) {
continue
}
const relativePath = path.relative(path.dirname(fromPath), targetAncestor)
const prefix = relativePath.startsWith('.') ? '' : './'
const potentialIndexedImport = `${prefix}${relativePath}` // TODO
let hasIndex = this.hasIndex.get(targetAncestor)
if (notExisting(hasIndex)) {
const resolvedIndex = ts.resolveModuleName(potentialIndexedImport, fromPath, compilerOptions, ts.sys)
if (resolvedIndex && resolvedIndex.resolvedModule) {
this.indexAtPath.set(targetAncestor, path.normalize(resolvedIndex.resolvedModule.resolvedFileName))
this.hasIndex.set(targetAncestor, true)
hasIndex = true
} else {
this.hasIndex.set(targetAncestor, false)
}
}
const notImportingFromIndex = targetPath !== this.indexAtPath.get(targetAncestor)
if (hasIndex && notImportingFromIndex) {
return potentialIndexedImport
}
}
return null
}
}
function getAncestorsSince(of: Path, since: Path): Array<string> {
const result = []
for (let current = path.normalize(path.dirname(of));
current.startsWith(since);
current = path.join(current, '..')
) {
result.push(current)
}
return result.reverse()
}
function errorMessage(dir: Path): string {
const module = dir.replace(/\\/g, '/')
return `Directory '${module}' has index file. Please import from '${module}' instead.`
}
|
e0aefaff9a37a5a71b31e345c4e6ec47504d0843
|
TypeScript
|
FallOutChonny/next-gql-hnpwa
|
/apollo/hn-data-api.ts
| 2.53125
| 3
|
import firebase from 'firebase/app'
import { HN_API_URL, HN_API_VERSION } from './config'
import type { NewsItems } from './news-items'
let api: firebase.database.Reference
if (!firebase.apps.length) {
firebase.initializeApp({ databaseURL: HN_API_URL })
}
if (!(process as any).browser) {
require('firebase/database')
api = firebase.database().ref(HN_API_VERSION)
}
export async function fetch(url: string) {
return (await api.child(url).once('value')).val()
}
export async function fetchNewsItems(id: number): Promise<NewsItems> {
return await fetch(`item/${id}`)
}
export async function loopFetchNewsItemsComments(items: NewsItems) {
if (items.kids && items.kids.length > 0) {
items.kids = await Promise.all(
items.kids.map(async id =>
loopFetchNewsItemsComments(await fetchNewsItems(id as any)),
),
)
}
return items
}
export async function fetchUser(id: string) {
return await fetch(`user/${id}`)
}
export default api
|
50ded2ff5677023c586fd596dca16f9322148890
|
TypeScript
|
rakhmax/ts-express-graphql-template
|
/src/graphql/resolvers/user.ts
| 2.59375
| 3
|
import bcrypt from 'bcrypt';
import { AuthenticationError, ValidationError ,UserInputError } from 'apollo-server-express'
import jwt from 'jsonwebtoken';
import { User } from '../../models/User';
interface IUser {
userId: String
firstname: String
lastname: String
username: String
email: String
password: String
userInput: any
}
export const mutations = {
createUser: async (_: void, { userInput }: IUser): Promise<{}> => {
try {
const user = await User.findOne({ username: userInput.username });
if (user) {
throw new UserInputError('User already exists.');
}
let password = await bcrypt.hash(userInput.password, 10);
const res: {} = await User.create({ ...userInput, password });
return res;
} catch (error) {
throw error;
}
},
authUser: async (_: void, { userInput }: IUser): Promise<{}> => {
try {
const user: any = await User.findOne({ username: userInput.username });
if (!user) {
throw new UserInputError('User does not exist.');
}
const isPasswordCorrect: boolean = await bcrypt.compare(userInput.password, user.password);
if (!isPasswordCorrect) {
throw new UserInputError("Password is incorrect!");
}
const token: string = jwt.sign(
{ userId: user.id, username: user.username },
process.env.JWT_SECRET,
{ expiresIn: `1h` }
);
return { userId: user.id, token: token, tokenExpiration: 1 };
} catch (error) {
throw error;
}
},
updateUser: async (_: void, { userInput }: IUser, { isAuth, userId }: any): Promise<{}> => {
if (!isAuth) {
throw new AuthenticationError('Unauthorized');
}
try {
const res: {} = await User.findByIdAndUpdate(userId, userInput, { new: true });
if (!res) {
throw new Error('Could not update user data.');
}
return res;
} catch (error) {
throw error;
}
},
deleteUser: async (_: void, args: IUser, { isAuth, userId }: any): Promise<{}> => {
if (!isAuth) {
throw new AuthenticationError('Unauthorized');
}
try {
const res: {} = await User.findByIdAndDelete(userId);
if (!res) {
throw new Error('Could not delete user.');
}
return res;
} catch (error) {
throw error;
}
}
}
|
f4e59c39cb62738ed639bf210488e4a682a5d290
|
TypeScript
|
glad/watchnext-rn
|
/src/domain/throwables/ContentFailedToLoadThrowable.ts
| 2.625
| 3
|
import {BaseThrowable} from './BaseThrowable';
export class ContentFailedToLoadThrowable extends BaseThrowable {
constructor(message?: string) {
super('ContentFailedToLoadThrowable', message || 'Content failed to load');
}
}
|
602cb9877d552604df10921d24ff1d2831430316
|
TypeScript
|
hellochar/mito
|
/src/math/poissonDisc.ts
| 3.046875
| 3
|
import { Vector2 } from "three";
// https://github.com/beaugunderson/poisson-disc-sampler/blob/master/poisson-disc-sampler.js
export function poissonDisc({
width = 1,
height = 1,
radius = 0.1,
max = 1000,
initialSample = undefined as [number, number] | undefined,
rng = Math.random,
}): Vector2[] {
// maximum number of samples before rejection
var k = 30;
var radius2 = radius * radius;
var R = 3 * radius2;
var cellSize = radius * Math.SQRT1_2;
var gridWidth = Math.ceil(width / cellSize);
var gridHeight = Math.ceil(height / cellSize);
var grid = new Array(gridWidth * gridHeight);
var queue: number[][] = [];
var queueSize = 0;
var sampleSize = 0;
rng = rng || Math.random;
function far(x: number, y: number) {
var i = (x / cellSize) | 0;
var j = (y / cellSize) | 0;
var i0 = Math.max(i - 2, 0);
var j0 = Math.max(j - 2, 0);
var i1 = Math.min(i + 3, gridWidth);
var j1 = Math.min(j + 3, gridHeight);
for (j = j0; j < j1; ++j) {
var o = j * gridWidth;
for (i = i0; i < i1; ++i) {
var s;
if ((s = grid[o + i])) {
var dx = s[0] - x,
dy = s[1] - y;
if (dx * dx + dy * dy < radius2) {
return false;
}
}
}
}
return true;
}
function sample(x: number, y: number) {
const s = [x, y];
queue.push(s);
grid[gridWidth * ((y / cellSize) | 0) + ((x / cellSize) | 0)] = s;
sampleSize++;
queueSize++;
return s;
}
const sampler = function() {
if (!sampleSize) {
if (initialSample != null) {
return sample(initialSample[0], initialSample[1]);
} else {
return sample(rng() * width, rng() * height);
}
}
// Pick a random existing sample and remove it from the queue.
while (queueSize) {
var i = (rng() * queueSize) | 0;
var s = queue[i];
// Make a new candidate between [radius, 2 * radius] from the existing
// sample.
for (var j = 0; j < k; ++j) {
var a = 2 * Math.PI * rng();
var r = Math.sqrt(rng() * R + radius2);
var x = s[0] + r * Math.cos(a);
var y = s[1] + r * Math.sin(a);
// Reject candidates that are outside the allowed extent,
// or closer than 2 * radius to any existing sample.
if (x >= 0 && x < width && y >= 0 && y < height && far(x, y)) {
return sample(x, y);
}
}
queue[i] = queue[--queueSize];
queue.length = queueSize;
}
};
const samples: Vector2[] = [];
for (let i = 0; i < max; i++) {
const sample = sampler();
// we can't get any more
if (sample == null) {
break;
}
samples.push(new Vector2(sample[0], sample[1]));
}
return samples;
}
|
7ae23d28686316f0e0491955e3e43f07056173fc
|
TypeScript
|
tiago-jv0/design-patterns-ts
|
/Adapter/Adapter.ts
| 3.71875
| 4
|
interface ITarget {
request(): string;
}
class Target implements ITarget {
public request(): string {
return 'Target: The default target\'s behavior.';
}
}
class Adaptee {
public specificRequest(): string {
return '.eetpadA eht fo roivaheb laicepS';
}
}
class Adapter implements ITarget {
constructor(private readonly adaptee: Adaptee) {}
request(): string {
return this.adaptee.specificRequest().split('').reverse().join('');
}
}
const clientCode = (target: Target) : void => console.log(target.request())
console.log('Client: I can work just fine with the Target objects:');
const target: ITarget = new Target;
clientCode(target)
const adaptee : Adaptee = new Adaptee();
console.log('Client: The Adaptee class has a weird interface. See, I don\'t understand it:');
console.log(`Adaptee: ${adaptee.specificRequest()}`);
console.log('Client: But I can work with it via the Adapter:');
const adapter = new Adapter(adaptee);
clientCode(adapter);
|
92569c8315f45df422afcb680ee587ef86f4b1ed
|
TypeScript
|
yb50110/yunhaseo-ng
|
/src/app/project/design/yunhaseo.ts
| 2.8125
| 3
|
export const Yunhaseo: yunhaseo[] = [
{
category: 'design',
mainImageUrl: 'yunhaseo/yunhaseo-desktop.png',
mainImageSize: 'contain',
title: 'Personal Branding',
year: '2017',
company: 'Personal Project',
role: 'Graphic Designer',
url: '',
content: [
{
text: 'As I was creating my resume and writing my cover letters for various companies, I was driven by the want to have them both look consistent so that it was blatantly obvious the two documents were from the same person. Thus, I created a simple document template that boldly shows my name in order to help it become memorable and quick to identify (out of the potential piles/list of other resumes).',
},
{
text: 'This lead to my exploration of personal identity and personality. I challenged myself to create a logo and a website that visually defines who I am and what I value.'
},
],
images: [
{
url: 'yunhaseo/letter.png',
size: 'half',
imageHeight: '',
backgroundSize: 'contain'
},
{
url: 'yunhaseo/cards.png',
size: 'half',
imageHeight: '',
backgroundSize: 'contain'
},
],
content2: [
{
text: 'To represent my Korean background, I selected the colors black and red and a serif font as they are reminiscent of a traditional Asian stamp as well as the brushstroke of the Asian characters. The generous white spaces are perfect example for my preference for minimalism, simplicity, and lots of breathing room.'
},
{
text: 'I began my logo creation by sketching numerous ideas, which wws then traced and modified on Adobe Illustrator. The logo represents a traditional Korean stamp; however, instead of the usual Chinese characters, I used Korean characters to write my name. As most of my audience would be American, by intentionally using Korean, I have made my logo more of a image rather than a text.'
},
{
text: 'I later programmed my website design into this website using the Angular 5 Javascript framework along with SCSS.'
}
],
images2: [
{
url: 'yunhaseo/yunhaseo-phone.png',
size: 'half',
imageHeight: '',
backgroundSize: 'contain'
},
{
url: 'yunhaseo/yunhaseo-phone-2.png',
size: 'half',
imageHeight: '',
backgroundSize: 'contain'
}
],
tools: [
{
name: 'Adobe Photoshop CC'
},
{
name: 'Adobe Illustrator CC'
},
{
name: 'Traditional Media (paper and pencil)'
}
],
skills: [
{
description: 'Maintained style consistency'
},
{
description: 'Explored personal style'
}
]
}
];
interface yunhaseo {
category: string;
mainImageUrl: string;
mainImageSize: string;
title: string;
year: string;
company: string;
role: string;
url: string;
content: eachContent[];
images: eachImage[];
content2: eachContent[];
images2: eachImage[];
tools: eachTool[];
skills: eachSkill[];
}
interface eachContent {
text: string;
}
interface eachImage {
url: string;
size: string;
imageHeight: string;
backgroundSize: string;
}
interface eachTool {
name: string;
}
interface eachSkill {
description: string;
}
|
fed48cc9d011a20a8282df03b6875e08d3dc81ee
|
TypeScript
|
nrwl/nx
|
/packages/webpack/src/executors/dev-server/lib/serve-path.ts
| 2.921875
| 3
|
import type { NormalizedWebpackExecutorOptions } from '../../webpack/schema';
export function buildServePath(
browserOptions: NormalizedWebpackExecutorOptions
) {
let servePath =
_findDefaultServePath(browserOptions.baseHref, browserOptions.deployUrl) ||
'/';
if (servePath.endsWith('/')) {
servePath = servePath.slice(0, -1);
}
if (!servePath.startsWith('/')) {
servePath = `/${servePath}`;
}
return servePath;
}
export function _findDefaultServePath(
baseHref?: string,
deployUrl?: string
): string | null {
if (!baseHref && !deployUrl) {
return '';
}
if (
/^(\w+:)?\/\//.test(baseHref || '') ||
/^(\w+:)?\/\//.test(deployUrl || '')
) {
// If baseHref or deployUrl is absolute, unsupported by nx serve
return null;
}
// normalize baseHref
// for nx serve the starting base is always `/` so a relative
// and root relative value are identical
const baseHrefParts = (baseHref || '')
.split('/')
.filter((part) => part !== '');
if (baseHref && !baseHref.endsWith('/')) {
baseHrefParts.pop();
}
const normalizedBaseHref =
baseHrefParts.length === 0 ? '/' : `/${baseHrefParts.join('/')}/`;
if (deployUrl && deployUrl[0] === '/') {
if (baseHref && baseHref[0] === '/' && normalizedBaseHref !== deployUrl) {
// If baseHref and deployUrl are root relative and not equivalent, unsupported by nx serve
return null;
}
return deployUrl;
}
// Join together baseHref and deployUrl
return `${normalizedBaseHref}${deployUrl || ''}`;
}
|
604fe55e954cf95a91cd8c4b6f3de3531d2d2014
|
TypeScript
|
maknifirasing/Clinisys
|
/src/models/Rigime.ts
| 2.65625
| 3
|
export class Rigime{
private _designation: string;
constructor() {
}
getdesignation(): string {
return this._designation;
}
setdesignation(value: string) {
this._designation = value;
}
}
|
045a2e741311adb00fffb365edaaf6f30911ed35
|
TypeScript
|
47ng/env-alias
|
/src/index.ts
| 2.890625
| 3
|
export interface Options {
prefix: string
}
export interface Alias {
sourceName: string
destName: string
}
const defaultOptions: Options = {
prefix: 'ENV_ALIAS_'
}
// --
/**
* @internal Exported for tests only
*/
export const _extractAliasingDeclarations = (
env: NodeJS.ProcessEnv,
options: Options
): Alias[] => {
return Object.keys(env)
.filter(key => key.startsWith(options.prefix) && !!env[key])
.map(key => {
const sourceName = env[key]!
const destName = key.slice(options.prefix.length, key.length)
return { sourceName, destName }
})
}
/**
* @internal Exported for tests only
*/
export const _injectAlias = (env: NodeJS.ProcessEnv, alias: Alias) => {
if (env[alias.destName] !== undefined) {
return // don't overwrite existing destination variables
}
env[alias.destName] = env[alias.sourceName]
}
/**
* @internal Exported for tests only
*/
export const _createEnvAliaser =
(env: NodeJS.ProcessEnv) =>
(options: Options = defaultOptions): Alias[] => {
const aliases = _extractAliasingDeclarations(env, options)
aliases.forEach(alias => _injectAlias(env, alias))
return aliases
}
export const envAlias = _createEnvAliaser(process.env)
|
705140810cbedfae0748c1e81d9d8739b4a403db
|
TypeScript
|
andykais/ink-cpu-usage-example
|
/src/hooks/use-memory.ts
| 2.921875
| 3
|
import * as os from 'os'
import { useState } from 'react'
const useMemoryUsage = () => {
const [state, setState] = useState({ total: 0, used: 0, percent: 0 })
const setMemory = () => {
const total = os.totalmem() / 1e9
const used = total - os.freemem() / 1e9
const percent = (used / total) * 100
setState({ total, used, percent })
}
return [state, setMemory] as [typeof state, typeof setMemory]
}
type CpuChange = os.CpuInfo & { percent: number }
const useCpuUsage = () => {
const [state, setState] = useState<CpuChange[]>([])
const setCpuUsage = () => {
setState(prevCpuUsage => {
const cores = os.cpus() as CpuChange[]
for (let i = 0; i < cores.length; i++) {
const core = cores[i]
const prevCore = prevCpuUsage[i]
const coreChanged: os.CpuInfo['times'] = prevCore
? Object.keys(core.times).reduce(
(acc, key: keyof os.CpuInfo['times']) => ({
...acc,
[key]: core.times[key] - prevCore.times[key]
}),
{} as os.CpuInfo['times']
)
: core.times
const { user, nice, idle, irq, sys } = coreChanged
core.percent = (user + nice + irq + sys) / (user + nice + idle + irq + sys)
}
return cores
})
}
return [state, setCpuUsage] as [typeof state, typeof setCpuUsage]
}
export { useMemoryUsage, useCpuUsage }
|
8d408bd59b5c6bd0d6c794ed4b74273ee74b06d7
|
TypeScript
|
GongT/baobao
|
/@idlebox/common/src/function/asyncCallbackList.ts
| 3.5
| 4
|
import { nameFunction } from './functionName';
export interface MyAsyncCallback<Argument extends unknown[]> {
displayName?: string;
(...param: Argument): Promise<void | undefined | boolean> | void | undefined | boolean;
}
/**
* like CallbackList, but async
*/
export class AsyncCallbackList<Argument extends unknown[]> {
protected list: MyAsyncCallback<Argument>[] = [];
protected running: boolean = false;
constructor() {
this.run = (this.run as any).bind(this);
}
count() {
return this.list.length;
}
reset() {
if (this.running) {
throw new Error("Can not reset when it's running.");
}
this.list.length = 0;
}
/**
* @param name optional name of `item` (will assign displayName to `item`)
* @returns function list length
*/
add(item: MyAsyncCallback<Argument>, name?: string): number {
if (this.running) {
throw new Error("Can not add callback when it's running.");
}
if (name) {
nameFunction(name, item);
}
return this.list.push(item);
}
/**
* @returns if removed: return `item`; if did not exists: return null
*/
remove(item: MyAsyncCallback<Argument>): null | MyAsyncCallback<Argument> {
if (this.running) {
throw new Error("Can not remove callback when it's running.");
}
const found = this.list.indexOf(item);
if (found !== -1) {
return this.list.splice(found, 1)[0]!;
}
return null;
}
/**
* Stop run if one callback return `true`
* @returns {boolean} true if one callback return true
*/
async run(...argument: Argument): Promise<boolean> {
this.running = true;
let ret: boolean | undefined | void;
for (const cb of this.list) {
ret = await cb(...argument);
if (ret === true) {
break;
}
}
this.running = false;
return ret || false;
}
}
|
124a414819c93f2835b520237b6c338bba10ce1d
|
TypeScript
|
DomThePorcupine/worldpoo.ps
|
/frontend/utils/modules/Api.ts
| 2.953125
| 3
|
import axios, { AxiosInstance } from 'axios';
/**
* Namespace module that handles API requests
*/
class Api {
endpoint: string;
transport: AxiosInstance
constructor() {
// Use location.host for testing
// this.endpoint = (location.host.indexOf('xyz') >= 0) ? 'https://api.worldpoops.xyz/v1' : 'http://0.0.0.0:5000/v1';
this.endpoint = 'https://api.worldpoops.xyz/v1';
this.transport = axios.create({
withCredentials: true, // Needed for the token
});
}
/**
* Get a rnadom stall
* @returns {Promise} - Contains the random stall id
*/
getRandomStall(): Promise<any> {
return this.transport.get(`${this.endpoint}/stall/random`);
}
/**
* Gets stall name without having to authenticate
* @param stallId
*/
getNoAuthStallInfo(stallId: number): Promise<any> {
return axios.get(`${this.endpoint}/stall/${stallId}/noauth`);
}
/**
* Gets stall information
* @param stallId - stallId to get stall for
* @returns {Promise} - promise containing result from API call
*/
getStallInfo(stallId: number): Promise<any> {
return this.transport.get(`${this.endpoint}/stall/${stallId}`);
}
/**
* Registers user
* @param username - username
* @param password - password
* @returns {Promise} - promise containing result from API call
*/
registerUser(username: string, password: string): Promise<any> {
return this.transport.post(`${this.endpoint}/user/register`, {
username,
password
});
}
/**
* Get username of current user (this means that the user is already authenticated token-wise)
*/
getUsername(): Promise<any> {
return this.transport.get(`${this.endpoint}/user/whois`);
}
/**
* Logs in user
* @param username - username
* @param password - password
* @returns {Promise} - promise containing result from API call
*/
loginUser(username: string, password: string): Promise<any> {
return this.transport.post(`${this.endpoint}/auth/login`, {
username,
password
});
}
/**
* Submits tale
* @param taleText - body of tale
* @param stallId - stale id of the tale
*/
submitTale(taleText: string, stallId: number): Promise<any> {
return this.transport.post(`${this.endpoint}/tale`, {
taleText,
stallId
});
}
/**
* Rates stall
* @param stallId - stall to give rating
* @param score - score to give stall
*/
rateStall(stallId: number, score: number): Promise<any> {
return this.transport.post(`${this.endpoint}/rating`, {
stallId,
score
});
}
/**
* Vote tale
* @param taleId - tale to vote
* @param vote - true if upvote, flase if downvote
*/
voteTale(taleId: number, vote: boolean): Promise<any> {
return this.transport.post(`${this.endpoint}/vote`, {
taleId,
vote
});
}
createStall(address: string, name: string): Promise<any> {
return this.transport.post(`${this.endpoint}/stall`, {
address,
name
});
}
}
export default new Api();
|
d2a3a6815a4d6b84e439a00f707b0934cdf9189c
|
TypeScript
|
irfatku2/todo-list-learning
|
/src/app/pages/todo/services/todo.api.service.ts
| 2.875
| 3
|
import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";
import { Todo } from "../models/todo";
const TODOS: Todo[] = [
{ id: 1, title: "Buy milk", completed: false },
{ id: 2, title: "Timesheet", completed: false },
{ id: 3, title: "Joker", completed: false },
];
@Injectable()
export class TodoApiService {
todos = TODOS;
get(): Observable<Todo[]> {
return of(this.todos);
}
post(todo: Todo): Observable<Todo> {
const maxArr = this.todos.map(
(t: Todo) => {
return t.id;
});
const maxId = Math.max.apply(null, maxArr);
todo.id = maxId + 1;
this.todos = [...this.todos, todo];
return of(todo);
}
update(todo: Todo): Observable<Todo> {
this.todos = this.todos.map((t) => {
if (t.id !== todo.id) {
return t;
}
return { ...todo, completed: !todo.completed };
});
return of({...todo, completed: !todo.completed});
}
delete(todo: Todo) {
this.todos = this.todos.filter((t) => t.id !== todo.id);
}
}
|
8c46aed0b369d740a14a1a0311e3d3e94a68e7d2
|
TypeScript
|
SteffTek/WerwolfDC
|
/src/commands/cmd_pool.ts
| 2.671875
| 3
|
import {Command} from "./command";
import Discord = require("discord.js");
import {constants} from '../utils/const';
import {GuildGameManager} from "../server/guild";
import {MainIndex} from "../../index";
import {User} from "../game/user";
import {Game, GamePhase} from "../game/game";
export class cmd_pool extends Command {
constructor(){
super("pool", "Rollen festlegen", "3 Werwolf(wwchat) Hexe(hexenchat) Jäger Amor(amorchat) 4 Dorfbewohner");
}
execute(dcMessage: Discord.Message) {
// !pool 3 Werwolf(wwchat) Hexe(hexenchat) Jäger Amor 4 Dorfbewohner
let guild = dcMessage.guild;
if(guild == null) {
return;
}
let id = -1;
let guildManager: GuildGameManager = MainIndex.instance.guildGameManagerByGuild(guild);
for (let game in guildManager.games) {
if (guildManager.games[game].leader.dcUser == dcMessage.member) {
id = parseInt(game);
break;
}
}
if (id != -1) {
let game: Game = guildManager.games[id];
if(game.gamePhase != GamePhase.created) {
dcMessage.channel.send("Die Spielphase ist zu weit fortgeschritten!").then(function(msg: Discord.Message) {
msg.delete(3000);
});
return;
}
//ARGS PARSEN => ARRAY
let array = new Array<string>();
let message = dcMessage.content.substr(6);
let args = message.split(" ");
let amount = 1;
let currentArg = 0;
let maxArgs = args.length;
for(let i = 0; i < maxArgs; i++){
amount = parseInt(args[currentArg]);
if(isNaN(amount)) {
amount = 1;
} else {
currentArg++;
maxArgs--;
}
for(let x = 0; x < amount; x++){
array.push(args[currentArg]);
}
currentArg++;
amount = 1;
}
game.setRoles(array);
} else {
let tmpMsg;
dcMessage.channel.send("Du leitest gerade kein Spiel!").then((msg) => {
tmpMsg = msg;
tmpMsg.delete(3000);
}
);
}
}
}
|
e6871f086ce0514eb560a5b59fd09934198345b8
|
TypeScript
|
ms314006/Chat_Room-With-React
|
/src/class/Message.ts
| 2.703125
| 3
|
import uuidv1 from 'uuid/v1';
import { IMessage } from "../interface/IMessage";
class Message implements IMessage {
id: string = uuidv1();
sendTime: string;
name: string;
message: string;
constructor(sendTime: string, name: string, message: string) {
this.sendTime = sendTime;
this.name = name;
this.message = message;
}
}
export default Message;
|
2643ff3d536c16efaf85835ab3aa7cf48e6295b0
|
TypeScript
|
Sarafa2n/technopark_db
|
/src/forum/forum-model.ts
| 2.84375
| 3
|
import { Model } from "../base-model/model";
export interface IForum {
id?: number,
title: string,
user: string,
slug: string,
posts?: number,
threads?: number
}
export class ModelForum extends Model<IForum> {
constructor(attrs: IForum = null) {
super(attrs);
const defaults: IForum = {
title: null,
user: null,
slug: null,
posts: null,
threads: null
};
this.attrs = { ...defaults, ...attrs };
}
static serialize(data: any) {
return {
title: data.title,
user: data.nickname,
slug: data.slug,
posts: data.posts,
threads: data.threads
}
}
}
|
f1e9d4cd4b9e7f6e4b8c1049eed35ef172748edb
|
TypeScript
|
mark146/nameless-fullstack-boilerplate
|
/apps/backend/src/rest/routes/api/cars.ts
| 2.578125
| 3
|
import type { RouteOptions } from 'fastify';
import {
addCar,
deleteCar,
getCars,
getSingleCar,
updateCar,
} from '../../controllers/carsController';
import { CarDocument, CarData } from '../../../models/schema/Car.json';
const tags = ['cars'];
const params = {
id: {
type: 'string',
},
};
const getCarsRoute: RouteOptions = {
method: 'GET',
url: '/cars',
handler: getCars,
schema: {
description: 'Returns all cars',
tags,
summary: 'Returns all cars',
response: {
200: {
type: 'array',
items: CarDocument,
},
},
},
};
const getCarRoute = <RouteOptions>{
method: 'GET',
url: '/cars/:id',
handler: getSingleCar,
schema: {
description: 'Returns a car',
tags,
summary: 'Returns a car with given id',
params,
response: {
200: {
nullable: true,
...CarData,
},
},
},
};
const postCarRoute = <RouteOptions>{
method: 'POST',
url: '/cars',
handler: addCar,
schema: {
description: 'Create a new car',
tags,
summary: 'Creates new car with given values',
body: CarData,
response: {
200: CarDocument,
},
},
};
const putCarRoute = <RouteOptions>{
method: 'PUT',
url: '/cars/:id',
handler: updateCar,
schema: {
description: 'Update a car',
tags,
summary: 'Updates a car with given values',
params,
body: CarData,
response: {
200: CarData,
},
},
};
const deleteCarRoute = <RouteOptions>{
method: 'DELETE',
url: '/cars/:id',
handler: deleteCar,
schema: {
description: 'Deletes a car',
tags,
summary: 'Deletes a car with given id',
params,
response: {
200: {
nullable: true,
type: 'object',
properties: {
id: { type: 'string' },
},
},
},
},
};
export default [
getCarsRoute,
getCarRoute,
postCarRoute,
putCarRoute,
deleteCarRoute,
];
|
d364695629eefc83a9df7203924de46cc37db911
|
TypeScript
|
TrueRegin/i-learned-bezier-curves
|
/src/main.ts
| 2.9375
| 3
|
import { Vector2D, cubicBezier } from './bezier';
const canvas = document.querySelector('canvas#canvas') as HTMLCanvasElement;
let ctx: CanvasRenderingContext2D;
const controlPoints: [Vector2D, Vector2D, Vector2D, Vector2D] = [
[20, window.innerHeight],
[20, 20],
[window.innerWidth - 20, 20],
[window.innerWidth - 20, window.innerHeight],
];
const mousePos: [number, number] = [0, 0];
let transform: [number, number] = [0, 0];
let scale = 1;
let mousedown = false;
let selectedControl = -1;
const CIRCLE_RADIUS = 6;
const INTERACT_RADIUS = CIRCLE_RADIUS * 2.3;
// Main Function
(() => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx = canvas.getContext('2d');
// ? Setting canvas defaults
ctx.shadowOffsetY = 3;
ctx.shadowColor = '#000';
ctx.shadowBlur = 6;
ctx.font = '40px monospace, bold';
redrawFrame();
/**
* On window resize make sure the canvas always fits the screen
*/
window.onresize = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
redrawFrame();
};
/**
* If you press the keys 1, 2, 3 or 4 the corresponding handle moves to your mouse position.
*/
window.addEventListener('keydown', (event: KeyboardEvent) => {
for (let i = 0; i < 4; i++) {
if (event.key === (i + 1).toString()) {
const transformedMousePos = screenToCanvasSpace(mousePos);
for (let j = 0; j < 2; j++) {
controlPoints[i][j] = transformedMousePos[j];
}
redrawFrame();
}
}
});
/**
* Zooms in your view whenever the escape key is pressed.
* The complicated code is just to make it zoom in smoothly instead of abruptly
*
* ! That code is partially broken at the moment !
*/
window.addEventListener('keydown', (event: KeyboardEvent) => {
console.log(event.key);
if (event.key == 'Escape') {
// The number of iterations since the zoom start.
const DUR = 1000;
let t = 0;
// [SCALE, X, Y]
let start = [scale, ...transform];
let dest = [1, 0, 0];
// Loop until we have reached our destination.
let prevTime = Date.now();
let interval = setInterval(() => {
const now = Date.now();
const elapsed = now - prevTime;
t += elapsed / DUR;
if (t > 1) t = 1;
// Easing value of t so the transition isn't linear.
let tEasing = Math.pow(t, 1 / 3);
console.log(start[0], dest[0]);
scale = ease(start[0], dest[0], tEasing);
transform[0] = ease(start[1], dest[1], tEasing);
transform[1] = ease(start[2], dest[2], tEasing);
redrawFrame();
if (t == 1) {
clearInterval(interval);
}
}, 1000 / 60);
function ease(dest: number, start: number, t: number) {
return (t - 1) * dest + t * start;
}
}
});
/**
* We want to zoom in on the canvas whenever we scroll towards the screen
* and out when we scroll away from it.
*
* The negative before `event.deltaY` is because scrolling in is by default -100 which would zoom us in not out.
*/
window.onwheel = (event: WheelEvent) => {
console.log(event.deltaY, {});
scale += -event.deltaY / 500;
if (scale < 0.3) scale = 0.3;
else if (scale > 5) scale = 5;
redrawFrame();
};
/**
* We want to pan the camera when the mouse is down and the mouse is moving.
* We don't pan the camera when a handle is selected.
*/
window.onmousemove = (event: MouseEvent) => {
mousePos[0] = event.pageX;
mousePos[1] = event.pageY;
if (mousedown) {
if (selectedControl === -1) {
// ? If we are not selecting a handle pan the screen.
transform[0] += -event.movementX;
transform[1] += -event.movementY;
} else {
// ? If we are selecting a handle, move it to the mouse's position in canvas coordinates.
let mouseCoords = screenToCanvasSpace([event.x, event.y]);
controlPoints[selectedControl][0] = mouseCoords[0];
controlPoints[selectedControl][1] = mouseCoords[1];
}
}
redrawFrame();
};
window.onmousedown = (event: MouseEvent) => {
let mouseCoords = screenToCanvasSpace([event.clientX, event.clientY]);
for (let i = 3; i >= 0; i--) {
let a = mouseCoords[0] - controlPoints[i][0];
let b = mouseCoords[1] - controlPoints[i][1];
let dist = Math.sqrt(a * a + b * b);
if (dist < INTERACT_RADIUS) {
selectedControl = i;
break;
}
}
mousedown = true;
};
window.onmouseup = () => {
selectedControl = -1;
mousedown = false;
};
})();
/**
* Redraws the bezier curve, bezier control point text, and background.
*/
function redrawFrame() {
/**
* First we want to clear the screen of the previous frame.
* We also modify what we display using a scale + transform.
* Scale is less than 1 when we're zoomed in from where we start and greater than 1 when we're zoomed out from where we start.
*/
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.translate(0 - transform[0], -transform[1]);
ctx.scale(scale, scale);
/**
* We draw the lines from the curves starting points to its control handles.
*/
for (let i = 0; i < 4; i += 2) {
ctx.beginPath();
ctx.strokeStyle = '#FFF';
ctx.lineWidth = 1;
ctx.moveTo(controlPoints[i][0], controlPoints[i][1]);
ctx.lineTo(controlPoints[i + 1][0], controlPoints[i + 1][1]);
ctx.stroke();
}
/**
* We want to draw the bezier curve onto the screen next.
*/
ctx.strokeStyle = '#FFF';
ctx.lineWidth = 3;
let x = controlPoints[0][0];
let y = controlPoints[0][1];
ctx.beginPath();
ctx.moveTo(x, y);
const LINE_SEGMENTS = 100;
for (let i = 1; i < LINE_SEGMENTS + 1; i++) {
const bezierPoint = cubicBezier(
controlPoints[0],
controlPoints[1],
controlPoints[2],
controlPoints[3],
i / LINE_SEGMENTS
);
x = bezierPoint[0];
y = bezierPoint[1];
ctx.lineTo(x, y);
}
ctx.stroke();
/**
* We want to draw text on the control handles that is ALWAYS on the screen.
*
* If we're inside a zone where we can drag a control handle, we want to place an opaque square behind the handle.
*
* We're going backwards here because the handle in the last index of the array is
* Rendered on top of the others (thus it should be interacted with first and display on top)
*/
// A temporary variable that stores the index of the control we're hovering over. It has a really bad name though.
let circledrawn = -1;
for (let i = 3; i >= 0; i--) {
/**
* In this first part we get the coordinates we'll need for calculations
*/
let textPosOnScreen = canvasToScreenSpace(controlPoints[i]);
let x = controlPoints[i][0];
let y = controlPoints[i][1];
let sx = textPosOnScreen[0];
let sy = textPosOnScreen[1];
let tx = x + 30;
let ty = y + 30;
const mouseInCanvasCoords = screenToCanvasSpace(mousePos);
/**
* Text coordinates for calculations
*/
const text = i + 1 + '';
const textMetrics = ctx.measureText(text);
const tWidth = textMetrics.width;
// Buffer between the edge of the screen before text gets flopped.
const BUFFER = 50;
/**
* If the control handle number on the left or bottom went off the screen we move it to the
* top of the control handle or to the right of it (or both if that applies)
*/
if (sx + tWidth + BUFFER > window.innerWidth) tx -= 70;
if (sy + BUFFER > window.innerHeight) ty -= 60;
/**
* If we're hovering over a handle, queue the redrawing of that handle with an opaque selector circle
* under it FOR LATER. (Code is after this for loop)
*
* NOTE: If we already are selecting a handle, we don't do anything here.
*/
if (
circledrawn === -1 &&
selectedControl === -1 &&
distance(mouseInCanvasCoords, [x, y]) <= INTERACT_RADIUS
) {
circledrawn = i;
}
/**
* Filling in the handle itself for each handle.
*/
ctx.fillStyle = '#FFFFFF';
ctx.strokeStyle = '#FFFFFF';
ctx.beginPath();
ctx.arc(x, y, CIRCLE_RADIUS, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();
/**
* We want to draw the pastel yellow text with some spacing from
* the bezier control point (hence using tx & ty instead of x & y)
*/
ctx.fillStyle = '#FFF89C';
ctx.fillText(text.toString(), tx, ty);
}
/**
* We draw the selection circle + the actual circle of a handle we're hovering over after we draw the handles at
* first. Otherwise there will be issues with what handle appears on top because of the drawing order.
*
* the selected control handle (one we're dragging) takes priority over the
* hovered control handle (one we're hovering over).
*/
if (circledrawn !== -1 || selectedControl !== -1) {
if(circledrawn === -1) circledrawn = selectedControl;
x = controlPoints[circledrawn][0];
y = controlPoints[circledrawn][1];
ctx.fillStyle = '#9cfaff99';
ctx.strokeStyle = '#9cfaff99';
ctx.beginPath();
ctx.arc(x, y, INTERACT_RADIUS, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();
/**
* Filling in the handle itself.
*/
ctx.fillStyle = '#FFFFFF';
ctx.strokeStyle = '#FFFFFF';
ctx.beginPath();
ctx.arc(x, y, CIRCLE_RADIUS, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();
}
ctx.resetTransform();
}
/**
* Transforms a mouse from web window coordinates to the coordinates of our canvas so
* we can use them to transform the bezier controls fluidly.
*
* As a note, this could easily be transformed into a matrix format, just something I was thinking about.
*/
function screenToCanvasSpace(pos: Vector2D): Vector2D {
let temp: Vector2D = [...pos];
for (let i = 0; i < pos.length; i++) {
temp[i] += transform[i];
temp[i] *= 1 / scale;
}
return temp;
}
/**
* Inverts the function `screenToCanvasSpace` above so we can make
* sure the text for the handles doesn't appear offscreen.
*/
function canvasToScreenSpace(pos: Vector2D): Vector2D {
let temp: Vector2D = [...pos];
for (let i = 0; i < pos.length; i++) {
temp[i] -= transform[i];
temp[i] *= scale;
}
return temp;
}
function distance(pos1: Vector2D, pos2: Vector2D) {
const a = pos1[0] - pos2[0];
const b = pos1[1] - pos2[1];
return Math.sqrt(a * a + b * b);
}
|
0c5900673931ad090f9f78cf6689bafe81a82983
|
TypeScript
|
metapages/asman.io
|
/.cloudseed/deno/git/getGitSha.ts
| 3.015625
| 3
|
/**
* Print the git SHA (if you can find it out) to stdout
* Arguments:
* --short=<count> (default 8 if set)
* The universal env var key for this value is DOCKER_TAG
* So if that value is found in the env vars, just use it
*/
import { parse } from "https://deno.land/std/flags/mod.ts";
import { getGitSha } from "./mod.ts";
const CLI_ARGS = parse(Deno.args);
let short: number = 0;
if (Deno.env.get('DOCKER_TAG')) {
console.log(Deno.env.get('DOCKER_TAG'));
Deno.exit(0);
}
if (CLI_ARGS['short']) {
if (typeof (CLI_ARGS['short']) === 'boolean') {
//default to 8
short = 8;
} else {
short = parseInt(CLI_ARGS['short']);
}
}
const sha = await getGitSha({ short });
console.log(sha);
|
b7eb8d69d8b4d027d81bbd58eb384238d9ba8855
|
TypeScript
|
abstractor97/EgretExample
|
/GuildExample/src/guide/GuideMask.ts
| 3.078125
| 3
|
/**
* 新手指引的遮罩
* @author chenkai
* @since 2017/7/4
*
* 在不需遮罩的矩形区域四周,创建4个半透明rect。
*
* example:
* 在(100,100)位置,显示200x50的可点击区域
* GuideMask.getInstance().show(100,100,200, 50, this);
* GuideMask.getInstance().hide();
*/
class GuideMask extends eui.Group{
/**颜色 */
public color:number = 0x000000;
/**透明度 */
public alpha:number = 0.5;
public constructor() {
super();
}
public childrenCreated(){
this.touchEnabled = true;
this.touchChildren = true;
}
//单例
private static instance:GuideMask;
public static getInstance():GuideMask{
if(this.instance == null){
this.instance = new GuideMask();
}
return this.instance;
}
/**
* 显示指引半透明遮罩
* @x 不需遮罩的矩形区域x
* @y 不需遮罩的矩形区域y
* @w 不需遮罩的矩形区域宽度
* @h 不需遮罩的矩形区域高度
* @doc GuildMask显示的容器
*/
public show(x:number, y:number, w:number, h:number, doc:egret.DisplayObjectContainer){
var stage:egret.Stage = egret.lifecycle.stage;
//上部遮罩
var rectTop:eui.Rect = new eui.Rect(stage.stageWidth, y, this.color);
rectTop.x = 0;
rectTop.y = 0;
this.addChild(rectTop);
//下部遮罩
var rectFoot:eui.Rect = new eui.Rect(stage.stageWidth, stage.stageHeight - y - h, this.color);
rectFoot.x = 0;
rectFoot.y = h+y;
this.addChild(rectFoot);
//左边遮罩
var rectLeft:eui.Rect = new eui.Rect(x, h, this.color);
rectLeft.x = 0;
rectLeft.y = y;
this.addChild(rectLeft);
//右边遮罩
var rectRight:eui.Rect = new eui.Rect(stage.stageWidth - x - w, h, this.color);
rectRight.x = x + w;
rectRight.y = y;
this.addChild(rectRight);
doc.addChild(this);
}
/**
* 隐藏
*/
public hide(){
this.removeChildren();
this.parent && this.parent.removeChild(this);
}
}
|
6f5e0cb6c22670e6217f95360c0bc06a4a392b54
|
TypeScript
|
SagnikPradhan/Lily
|
/src/modules/bot/library/utils/multipart.ts
| 3.4375
| 3
|
// Types and Interfaces
type ValidValues = boolean | number | string | ValidValues[];
type MultipartValidObjType =
Record<string, ValidValues | Record<string, ValidValues>> ;
interface FileInterface {
file: Buffer;
fileName: string;
}
/**
* Multipart Data
*/
export default class Multipart {
public readonly boundary = '966853828642832635284737392';
#data: [string, MultipartValidObjType | FileInterface][];
/**
* Create Multipart Form Data
* @param data - Object to be sent as Multipart
*/
constructor(data = {}) {
this.#data = Object.entries(data);
}
/**
* Add data or property
* @param name - Name of the data or property
* @param data - Data to be appended
*/
append(name: string, data: MultipartValidObjType | FileInterface): void {
this.#data.push([name, data]);
}
/**
* Parse the Multipart into string
*/
parse(): string {
const lines: string[] = [];
const data = this.#data;
const length = this.#data.length;
const boundary = this.boundary;
// Body
for (let index = 0; index < length; index++) {
const [name, value] = data[index];
const isFile = name === 'file';
// New segment start
lines.push(`--${boundary}`);
// For files
if (isFile) {
if (!(value.file instanceof Buffer)) throw new Error('Invalid File');
// If file is Buffer
else {
const file = value.file;
const fileName = value.fileName || 'unknown';
lines.push(
`Content-Disposition: file; name="file"; filename="${fileName}"`,
);
lines.push('Content-Type: application/octet-stream');
lines.push('');
lines.push(file.toString());
}
// For Payloads
} else {
if (typeof value !== 'object') throw new Error('Invalid Payload');
lines.push(`Content-Disposition: form-data; name="${name}"`);
lines.push('Content-Type: application/json');
lines.push('');
// Try parsing the object
try {
lines.push(JSON.stringify(value));
} catch (err) {
throw new Error('Invalid Payload');
}
}
}
// End
lines.push(`--${boundary}--`);
return lines.join('\r\n');
}
}
|
d56fdb89ec5c2f2f806319f4bf8806972b3de73a
|
TypeScript
|
khiemnd777/project_resume_client
|
/src/_stdio/shared/components/meta-tag/meta-tag.ts
| 2.875
| 3
|
const createMetaTags = (tags: {}[], type: string) => {
tags.forEach((element: {}, index: number) => {
const attribute = Object.keys(element)[0];
const content = (element['content'] as string) || '';
const existedTag = document.querySelector(`meta[${attribute}='${element[attribute]}']`) as HTMLMetaElement;
if (!!existedTag) {
existedTag.content = content;
return;
}
if (index === 0) {
const comment = document.createComment(type);
document.getElementsByTagName('head')[0].appendChild(comment);
}
const link = document.createElement('meta');
link.setAttribute(attribute, element[attribute]);
link.content = content;
document.getElementsByTagName('head')[0].appendChild(link);
});
};
export default createMetaTags;
|
841a7f6acadfb32c680ced224bf6527ecf626c7c
|
TypeScript
|
MHekert/nestjs-graphql
|
/src/modules/profiles/repositories/profiles.repository.ts
| 2.515625
| 3
|
import { EntityRepository, Repository } from 'typeorm';
import { Profile } from '../entities/profile.entity';
@EntityRepository(Profile)
export class ProfilesRepository extends Repository<Profile> {
createProfile(username: string, bio: string): Promise<Profile> {
return this.create({
username,
bio,
}).save();
}
}
|
ab9ae58f9889217101045263d417399b3cc4250e
|
TypeScript
|
thewrath/Black
|
/src/core/System.js
| 2.921875
| 3
|
import { MessageDispatcher } from "../messages/MessageDispatcher";
/**
* Base class for custom systems. System is used to listen scene changes.
*
* @cat core
* @extends black-engine~MessageDispatcher
*/
export class System extends MessageDispatcher {
constructor() {
super();
}
/**
* Called when engine is paused.
*
* @public
* @return {void}
*/
onPause() { }
/**
* Called when engine is resumed.
*
* @public
* @return {void}
*/
onResume() { }
/**
* onUpdate
*
* @protected
* @return {void}
*/
onUpdate() { }
/**
* onPostUpdate
*
* @protected
* @return {void}
*/
onPostUpdate() { }
/**
* onRender
*
* @protected
* @return {void}
*/
onRender() { }
/**
* onChildrenAdded
*
* @protected
* @param {black-engine~GameObject} gameObject GameObject instance.
* @return {void}
*/
onChildrenAdded(gameObject) { }
/**
* onChildrenRemoved
*
* @protected
* @param {black-engine~GameObject} gameObject GameObject instance.
* @return {void}
*/
onChildrenRemoved(gameObject) { }
/**
* onChildrenRemoved
*
* @protected
* @param {black-engine~GameObject} gameObject GameObject instance.
* @return {void}
*/
onChildrenChanged(gameObject) { }
/**
* onComponentAdded
*
* @protected
* @param {black-engine~GameObject} child GameObject instance.
* @param {black-engine~Component} component Component instance added to game object.
* @return {void}
*/
onComponentAdded(child, component) { }
/**
* onComponentRemoved
*
* @protected
* @param {black-engine~GameObject} child GameObject instance.
* @param {black-engine~Component} component Component instance removed from game object.
* @return {void}
*/
onComponentRemoved(child, component) { }
/**
* Disposes all allocated resources.
*/
dispose() { }
}
|
23351f73df0991a46e82410ebf5295347200efa1
|
TypeScript
|
aldringutierrez/sic
|
/Auth0-Aeg/src/app/pipes/marcas.pipe.ts
| 2.578125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'marcas'
})
export class MarcasPipe implements PipeTransform {
transform(codigo: number): string {
if(codigo==1){
return "Intel";
}
if(codigo==2){
return "Amd";
}
if(codigo==3){
return "Mac";
}
return "";
}
}
|
e164cae526bd924a4e028ecc0301297d61551081
|
TypeScript
|
MDLeide/screeps
|
/cashew/src/lib/creep/CreepControllerRepository.ts
| 2.828125
| 3
|
import { CreepController } from "./CreepController";
export class CreepControllerRepository {
public static register(controllerType: CreepControllerType, loadDelegate: (memory: CreepControllerMemory) => CreepController) {
this.delegates[controllerType] = loadDelegate;
}
public static load(memory: CreepControllerMemory): CreepController {
let delegate = this.delegates[memory.type];
if (!delegate)
throw new Error(`Creep Controller Type ${memory.type} has not been registered.`);
return delegate(memory);
}
private static delegates: { [controllerType: string]: (memory: any) => CreepController } = {};
}
|
ca9129a89dc94cfed7bd5fbb2ae4e74acc2c0fe6
|
TypeScript
|
rtlocman/js
|
/Labs/Lab2/lab2/src/app/notes/notes.component.ts
| 2.640625
| 3
|
import { Component, OnInit } from '@angular/core';
import 'rxjs/add/operator/toPromise';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'notes',
templateUrl: './notes.component.html',
styleUrls: ['./notes.component.css']
})
export class NotesComponent implements OnInit {
notes: Note[] ;
text: string;
private notesUrl = 'http://localhost:8080/notes'; // URL to web api
constructor(private http: HttpClient) {
this.notes = [
{text:'Note one'},
{text:'Note two'}
] ;
}
ngOnInit() {
}
add() {
const note = { text: this.text }
this.notes.push(note);
this.text = '';
}
remove(idx) {
this.notes.splice(idx,1);
}
// getNotes(): Observable <Note[]> {
// return this.http.get<Note[]>(this.notesUrl);
// }
}
interface Note {
text: string;
}
|
3c1de55bc5b6494450cb17ac5f2dc4685be8ccc1
|
TypeScript
|
FishOrBear/csg.ts
|
/src/api/primitives3d-api.ts
| 3.015625
| 3
|
import { CSG } from "../core/CSG";
import { fromPolygons } from "../core/CSGFactories";
import { defaultShared, Polygon, Shared } from "../core/math/Polygon3";
import { Vector3D } from "../core/math/Vector3";
import { Vertex3D } from "../core/math/Vertex3";
import { rotate_extrude } from "./ops-extrusions";
import { scale, translate } from "./ops-transformations";
import { circle } from "./primitives2d-api";
import { roundedCube, roundedCylinder } from "./primitives3d";
/** Construct a cuboid
* @param {Object} [options] - options for construction
* @param {Float} [options.size=1] - size of the side of the cuboid : can be either:
* - a scalar : ie a single float, in which case all dimensions will be the same
* - or an array: to specify different dimensions along x/y/z
* @param {Integer} [options.fn=32] - segments of the sphere (ie quality/resolution)
* @param {Integer} [options.fno=32] - segments of extrusion (ie quality)
* @param {String} [options.type='normal'] - type of sphere : either 'normal' or 'geodesic'
* @returns {CSG} new sphere
*
* @example
* let cube1 = cube({
* r: 10,
* fn: 20
* })
*/
export function cube(params): CSG
{
const defaults = {
size: 1,
offset: [0, 0, 0],
round: false,
radius: 0,
fn: 8
};
let { round, radius, fn, size } = Object.assign({}, defaults, params);
let offset = [0, 0, 0];
let v = null;
if (params && params.length) v = params;
if (params && params.size && params.size.length) v = params.size; // { size: [1,2,3] }
if (params && params.size && !params.size.length) size = params.size; // { size: 1 }
if (params && typeof params !== "object") size = params; // (2)
if (params && params.round === true)
{
round = true;
radius = v && v.length ? (v[0] + v[1] + v[2]) / 30 : size / 10;
}
if (params && params.radius)
{
round = true;
radius = params.radius;
}
let x = size;
let y = size;
let z = size;
if (v && v.length)
{
[x, y, z] = v;
}
offset = [x / 2, y / 2, z / 2]; // center: false default
let object = round
? roundedCube({
radius: [x / 2, y / 2, z / 2],
roundradius: radius,
resolution: fn
})
: cube({ radius: [x / 2, y / 2, z / 2] });
if (params && params.center && params.center.length)
{
offset = [
params.center[0] ? 0 : x / 2,
params.center[1] ? 0 : y / 2,
params.center[2] ? 0 : z / 2
];
} else if (params && params.center === true)
{
offset = [0, 0, 0];
} else if (params && params.center === false)
{
offset = [x / 2, y / 2, z / 2];
}
return offset[0] || offset[1] || offset[2]
? translate(offset, object)
: object;
}
/** Construct a sphere
* @param {Object} [options] - options for construction
* @param {Float} [options.r=1] - radius of the sphere
* @param {Integer} [options.fn=32] - segments of the sphere (ie quality/resolution)
* @param {Integer} [options.fno=32] - segments of extrusion (ie quality)
* @param {String} [options.type='normal'] - type of sphere : either 'normal' or 'geodesic'
* @returns {CSG} new sphere
*
* @example
* let sphere1 = sphere({
* r: 10,
* fn: 20
* })
*/
export function sphere(params): CSG
{
const defaults = {
r: 1,
fn: 32,
type: "normal"
};
let { r, fn, type } = Object.assign({}, defaults, params);
let offset = [0, 0, 0]; // center: false (default)
if (params && typeof params !== "object")
{
r = params;
}
// let zoffset = 0 // sphere() in openscad has no center:true|false
let output =
type === "geodesic"
? geodesicSphere(params)
: sphere({ radius: r, resolution: fn });
// preparing individual x,y,z center
if (params && params.center && params.center.length)
{
offset = [
params.center[0] ? 0 : r,
params.center[1] ? 0 : r,
params.center[2] ? 0 : r
];
} else if (params && params.center === true)
{
offset = [0, 0, 0];
} else if (params && params.center === false)
{
offset = [r, r, r];
}
return offset[0] || offset[1] || offset[2]
? translate(offset, output)
: output;
}
export function geodesicSphere(params)
{
const defaults = {
r: 1,
fn: 5
};
let { r, fn } = Object.assign({}, defaults, params);
let ci = [
// hard-coded data of icosahedron (20 faces, all triangles)
[0.850651, 0.0, -0.525731],
[0.850651, -0.0, 0.525731],
[-0.850651, -0.0, 0.525731],
[-0.850651, 0.0, -0.525731],
[0.0, -0.525731, 0.850651],
[0.0, 0.525731, 0.850651],
[0.0, 0.525731, -0.850651],
[0.0, -0.525731, -0.850651],
[-0.525731, -0.850651, -0.0],
[0.525731, -0.850651, -0.0],
[0.525731, 0.850651, 0.0],
[-0.525731, 0.850651, 0.0]
];
let ti = [
[0, 9, 1],
[1, 10, 0],
[6, 7, 0],
[10, 6, 0],
[7, 9, 0],
[5, 1, 4],
[4, 1, 9],
[5, 10, 1],
[2, 8, 3],
[3, 11, 2],
[2, 5, 4],
[4, 8, 2],
[2, 11, 5],
[3, 7, 6],
[6, 11, 3],
[8, 7, 3],
[9, 8, 4],
[11, 10, 5],
[10, 11, 6],
[8, 9, 7]
];
let geodesicSubDivide = function (p, fn, offset)
{
let p1 = p[0];
let p2 = p[1];
let p3 = p[2];
let n = offset;
let c = [];
let f = [];
// p3
// /\
// /__\ fn = 3
// i /\ /\
// /__\/__\ total triangles = 9 (fn*fn)
// /\ /\ /\
// 0/__\/__\/__\
// p1 0 j p2
for (let i = 0; i < fn; i++)
{
for (let j = 0; j < fn - i; j++)
{
let t0 = i / fn;
let t1 = (i + 1) / fn;
let s0 = j / (fn - i);
let s1 = (j + 1) / (fn - i);
let s2 = fn - i - 1 ? j / (fn - i - 1) : 1;
let q = [];
q[0] = mix3(mix3(p1, p2, s0), p3, t0);
q[1] = mix3(mix3(p1, p2, s1), p3, t0);
q[2] = mix3(mix3(p1, p2, s2), p3, t1);
// -- normalize
for (let k = 0; k < 3; k++)
{
let r = Math.sqrt(
q[k][0] * q[k][0] +
q[k][1] * q[k][1] +
q[k][2] * q[k][2]
);
for (let l = 0; l < 3; l++)
{
q[k][l] /= r;
}
}
c.push(q[0], q[1], q[2]);
f.push([n, n + 1, n + 2]);
n += 3;
if (j < fn - i - 1)
{
let s3 = fn - i - 1 ? (j + 1) / (fn - i - 1) : 1;
q[0] = mix3(mix3(p1, p2, s1), p3, t0);
q[1] = mix3(mix3(p1, p2, s3), p3, t1);
q[2] = mix3(mix3(p1, p2, s2), p3, t1);
// -- normalize
for (let k = 0; k < 3; k++)
{
let r = Math.sqrt(
q[k][0] * q[k][0] +
q[k][1] * q[k][1] +
q[k][2] * q[k][2]
);
for (let l = 0; l < 3; l++)
{
q[k][l] /= r;
}
}
c.push(q[0], q[1], q[2]);
f.push([n, n + 1, n + 2]);
n += 3;
}
}
}
return { points: c, triangles: f, offset: n };
};
const mix3 = function (a, b, f)
{
let _f = 1 - f;
let c = [];
for (let i = 0; i < 3; i++)
{
c[i] = a[i] * _f + b[i] * f;
}
return c;
};
if (params)
{
if (params.fn) fn = Math.floor(params.fn / 6);
}
if (fn <= 0) fn = 1;
let c = [];
let f = [];
let offset = 0;
for (let i = 0; i < ti.length; i++)
{
let g = geodesicSubDivide(
[ci[ti[i][0]], ci[ti[i][1]], ci[ti[i][2]]],
fn,
offset
);
c = c.concat(g.points);
f = f.concat(g.triangles);
offset = g.offset;
}
return scale(r, polyhedron({ points: c, triangles: f }));
}
/** Construct a cylinder
* @param {Object} [options] - options for construction
* @param {Float} [options.r=1] - radius of the cylinder
* @param {Float} [options.r1=1] - radius of the top of the cylinder
* @param {Float} [options.r2=1] - radius of the bottom of the cylinder
* @param {Float} [options.d=1] - diameter of the cylinder
* @param {Float} [options.d1=1] - diameter of the top of the cylinder
* @param {Float} [options.d2=1] - diameter of the bottom of the cylinder
* @param {Integer} [options.fn=32] - number of sides of the cylinder (ie quality/resolution)
* @returns {CSG} new cylinder
*
* @example
* let cylinder = cylinder({
* d: 10,
* fn: 20
* })
*/
export function cylinder(params)
{
const defaults = {
r: 1,
r1: 1,
r2: 1,
h: 1,
fn: 32,
round: false
};
let { r1, r2, h, fn, round } = Object.assign({}, defaults, params);
let offset = [0, 0, 0];
let a = arguments;
if (params && params.d)
{
r1 = r2 = params.d / 2;
}
if (params && params.r)
{
r1 = params.r;
r2 = params.r;
}
if (params && params.h)
{
h = params.h;
}
if (params && (params.r1 || params.r2))
{
r1 = params.r1;
r2 = params.r2;
if (params.h) h = params.h;
}
if (params && (params.d1 || params.d2))
{
r1 = params.d1 / 2;
r2 = params.d2 / 2;
}
if (a && a[0] && a[0].length)
{
a = a[0];
r1 = a[0];
r2 = a[1];
h = a[2];
if (a.length === 4) fn = a[3];
}
let object;
if (params && (params.start && params.end))
{
object = round
? roundedCylinder({
start: params.start,
end: params.end,
radiusStart: r1,
radiusEnd: r2,
resolution: fn
})
: cylinder({
start: params.start,
end: params.end,
radiusStart: r1,
radiusEnd: r2,
resolution: fn
});
} else
{
object = round
? roundedCylinder({
start: [0, 0, 0],
end: [0, 0, h],
radiusStart: r1,
radiusEnd: r2,
resolution: fn
})
: cylinder({
start: [0, 0, 0],
end: [0, 0, h],
radiusStart: r1,
radiusEnd: r2,
resolution: fn
});
let r = r1 > r2 ? r1 : r2;
if (params && params.center && params.center.length)
{
// preparing individual x,y,z center
offset = [
params.center[0] ? 0 : r,
params.center[1] ? 0 : r,
params.center[2] ? -h / 2 : 0
];
} else if (params && params.center === true)
{
offset = [0, 0, -h / 2];
} else if (params && params.center === false)
{
offset = [0, 0, 0];
}
object =
offset[0] || offset[1] || offset[2]
? translate(offset, object)
: object;
}
return object;
}
/** Construct a torus
* @param {Object} [options] - options for construction
* @param {Float} [options.ri=1] - radius of base circle
* @param {Float} [options.ro=4] - radius offset
* @param {Integer} [options.fni=16] - segments of base circle (ie quality)
* @param {Integer} [options.fno=32] - segments of extrusion (ie quality)
* @param {Integer} [options.roti=0] - rotation angle of base circle
* @returns {CSG} new torus
*
* @example
* let torus1 = torus({
* ri: 10
* })
*/
export function torus(params)
{
const defaults = {
ri: 1,
ro: 4,
fni: 16,
fno: 32,
roti: 0
};
params = Object.assign({}, defaults, params);
/* possible enhancements ? declarative limits
const limits = {
fni: {min: 3},
fno: {min: 3}
} */
let { ri, ro, fni, fno, roti } = params;
if (fni < 3) fni = 3;
if (fno < 3) fno = 3;
let baseCircle = circle({ r: ri, fn: fni, center: true });
if (roti) baseCircle = baseCircle.rotateZ(roti);
let result = rotate_extrude({ fn: fno }, translate([ro, 0, 0], baseCircle));
// result = result.union(result)
return result;
}
/** Construct a polyhedron from the given triangles/ polygons/points
* @param {Object} [options] - options for construction
* @param {Array} [options.triangles] - triangles to build the polyhedron from
* @param {Array} [options.polygons] - polygons to build the polyhedron from
* @param {Array} [options.points] - points to build the polyhedron from
* @param {Array} [options.colors] - colors to apply to the polyhedron
* @returns {CSG} new polyhedron
*
* @example
* let torus1 = polyhedron({
* points: [...]
* })
*/
export function polyhedron(params)
{
let pgs = [];
let ref = params.triangles || params.polygons;
let colors = params.colors || null;
for (let i = 0; i < ref.length; i++)
{
let pp = [];
for (let j = 0; j < ref[i].length; j++)
{
pp[j] = params.points[ref[i][j]];
}
let v = [];
for (let j = ref[i].length - 1; j >= 0; j--)
{
// --- we reverse order for examples of OpenSCAD work
v.push(new Vertex3D(new Vector3D(pp[j][0], pp[j][1], pp[j][2])));
}
let s = defaultShared;
if (colors && colors[i]) s = Shared.fromColor(colors[i]);
pgs.push(new Polygon(v, s));
}
return fromPolygons(pgs);
}
|
c1dd8fa27b80506a0c06e327b26ad0a50f1ccb38
|
TypeScript
|
Vinci-da-Gama/a4_bindings
|
/src/app.convertstyle.ts
| 2.546875
| 3
|
import { Component } from '@angular/core';
import { ExchangeRateService } from './services/ExchangeRate.Service';
@Component({
selector: 'converter-with-style',
providers: [ExchangeRateService],
template: `
L30: <span>class binding - [class.error]="..."<span>
<br />
Convert: <input type="number" [(ngModel)]="baseAmt" [class.error]="inFinite(baseAmt)" /> USD
<br />
<p class="simple-hint">
This is demo for (style) => [style.cssAttribute] = "..."
</p>
<input type="number" [(ngModel)]="baseAmt"
[style.backgroundColor]="inFinite(baseAmt)? '#ff6666':'#fff' " />
USD
<p>
<b>{{baseAmt}}</b> US dollars =
<cite>{{getterTargetAmt}}</cite> GRP
</p>
L30: (7: 33) <span>ngClass binding with multiple condidions.<span>
<br />
Convert:
<input type="number" [(ngModel)]="baseAmt0" [ngClass]="{error: inInvalid(baseAmt0), warning: baseAmt0 < 0}" />
USD
<p>
<b>{{baseAmt0}}</b> US dollars =
<cite>{{getterTargetAmt0}}</cite> GRP
</p>
L31: <span>Services with provider and ngFor and event 2 way binding to do selection --- get exchange rate from service <span>
<br />
Convert:
<input type="number" [(ngModel)]="baseAmt1" />
<currency-type-selector [(culler)]="baseCurrency"></currency-type-selector>
= <cite>{{getterTargetAmt1}}</cite>
<currency-type-selector [(culler)]="targetCurrency"></currency-type-selector>
<br />
<br />
L35: <span>ngIf -- <b>prevent choose same types of both currencies and number pipe</b>.<span>
<br />
Convert:
<input type="number" [(ngModel)]="baseAmt2" [ngClass]="{error: inInvalid(baseAmt2), warning: baseAmt2 <= 0}" />
<currency-type-selector [(culler)]="baseCurrency1"></currency-type-selector>
= <cite>{{getterTargetAmt2 | number: '1.2-2'}}</cite>
<currency-type-selector [(culler)]="targetCurrency1"></currency-type-selector>
<ng-template [ngIf]="inInvalid(baseAmt2)">
<p class="errfont">The base amount is incorrect.</p>
</ng-template>
<!-- <p class="errfont" *ngIf="inInvalid(baseAmt2)">The base amount is incorrect.</p> -->
<p>
s5L36 -- pipe
</p>
<cite>{{now | date:'dd/mm/yyyy'}}</cite>
<cite>
{{ {name: "jsonPipe"} | json }}
</cite>
<p>
s5L37 -- custome-pipe <strong>(write our own pipe)</strong>
</p>
Convert:
<input type="number" [(ngModel)]="baseAmt3" [ngClass]="{error: inInvalid(baseAmt3), warning: baseAmt3 <= 0}" />
<currency-type-selector [(culler)]="baseCurrency2"></currency-type-selector>
= <cite>{{getterTargetAmt3 | fixedNum: 3}}</cite>
<currency-type-selector [(culler)]="targetCurrency2"></currency-type-selector>
<ng-template [ngIf]="inInvalid(baseAmt3)">
<p class="errfont">The base amount is incorrect.</p>
</ng-template>
`,
styles: [
`
input[type="number"] {
width: 10ex;
text-align: right;
}
.error {
background-color: red;
}
.errfont {
color: red;
font-weight: bold;
}
.warning {
background-color: orange;
}
.simple-hint {
color: blue;
font-weight: 900;
}
`
]
})
export class ConverterStyle {
now = Date.now();
exchangeRate:number = 0.7;
baseAmt:number = 1;
exchangeRate0:number = 0.66;
baseAmt0:number = 1;
baseCurrency: string = 'USD';
targetCurrency: string = 'GBP';
baseAmt1:number = 1;
baseCurrency1: string = 'EUR';
targetCurrency1: string = 'USD';
baseAmt2:number = 1;
baseCurrency2: string = 'GBP';
targetCurrency2: string = 'USD';
baseAmt3:number = 1;
constructor ( private ers: ExchangeRateService ) {}
get getterTargetAmt() {
return this.baseAmt * this.exchangeRate;
}
get getterTargetAmt0() {
return this.baseAmt0 * this.exchangeRate0;
}
get getterTargetAmt1() {
const exchangeRate1: number = this.ers.fetchExchangeRate(this.baseCurrency, this.targetCurrency);
return this.baseAmt1 * exchangeRate1;
}
get getterTargetAmt2() {
const exchangeRate2: number = this.ers.fetchExchangeRate(this.baseCurrency1, this.targetCurrency1);
return this.baseAmt2 * exchangeRate2;
}
get getterTargetAmt3() {
const exchangeRate3: number = this.ers.fetchExchangeRate(this.baseCurrency2, this.targetCurrency2);
return this.baseAmt3 * exchangeRate3;
}
inFinite(val: number) {
return !Number.isFinite(val);
}
inInvalid(val: number) {
return !Number.isFinite(val);
}
}
|
25dccc3bf381e3c613c255edff4fd05a1c8554e3
|
TypeScript
|
YuraGB/Task
|
/src/app/Service/app.service.ts
| 2.625
| 3
|
import { Injectable } from '@angular/core';
import { data } from './data';
@Injectable()
export class AppService {
constructor() { }
getAllGoods() {
return data.goods;
}
get(name) {
return this.getAllGoods().filter( (element: any) => {
if (element.type === name) {
return element;
}
});
}
putAnEstimate(event) {
let target = event.target;
this.getAllGoods().forEach( (element: any) => {
while (element.id !== +target.parentElement.id && !target.parentElement.id) {
target = target.parentElement;
}
if (+target.parentElement.id === +element.id ) {
element.rating = element.rating.map((el, index) => {
if (index === +event.target.textContent - 1) {
return el += 1;
}
return el;
});
}
});
}
getGoodById(id): any {
return this.getAllGoods().filter( element => {
if (element.id === id) {
return element;
}
});
}
getContacts(): any {
return data.contacts;
}
}
|
a03f14a62a67b00c1eac76e8a92858fd94c476c5
|
TypeScript
|
iiuni/projektzapisy
|
/zapisy/apps/enrollment/timetable/assets/store/filters.ts
| 2.640625
| 3
|
// Module filters implements the registration and current state of course
// filters.
import { every, invokeMap, values } from "lodash";
import { CourseInfo } from "./courses";
export interface Filter {
visible(c: CourseInfo): boolean;
}
interface State {
filters: { [id: string]: Filter };
}
const state: State = {
filters: {},
};
const getters = {
// visible runs all the registered filters on the given course.
visible: (state: State) => (c: CourseInfo) => {
return every(invokeMap(values(state.filters), "visible", c));
},
};
const mutations = {
// registerFilter can be also used to update filter data.
registerFilter(state: State, { k, f }: { k: string; f: Filter }) {
state.filters[k] = f;
},
// clearFilter can be used to notify filters to reset their state.
clearFilters(_: State) {
// Intentionally left empty. No state change is required to notify
// subscribers of 'filters/clearFilters' mutation.
},
};
const actions = {};
export default {
namespaced: true,
state,
getters,
actions,
mutations,
};
|
c5accc59de23934c0b832783a97071bf87bb2bd6
|
TypeScript
|
flood-io/element
|
/packages/core/src/page/conditions/URLCondition.ts
| 2.8125
| 3
|
import { Condition } from '../Condition'
import { Frame } from 'playwright'
export class URLCondition extends Condition {
constructor(desc: string, public url: string, public partial: boolean = false) {
super(desc)
}
toString() {
return `waiting for URL to equal "${this.url}"`
}
public async waitFor(frame: Frame): Promise<boolean> {
await frame.waitForFunction(
(args: string) => {
const [url, partial] = JSON.parse(args)
if (typeof url === 'string') {
if (url.startsWith('/') && url.endsWith('/')) {
// RegExp
const exp = new RegExp(url.slice(1, url.length - 1))
return exp.test(window.location.href)
} else if (partial) {
return window.location.href.toLowerCase().indexOf(url.toLowerCase()) > -1
} else {
return window.location.href.trim().toLowerCase() === url.trim().toLowerCase()
}
}
},
JSON.stringify([this.url, this.partial]),
{ timeout: 30e3 }
)
return true
}
public async waitForEvent(): Promise<any> {
return
}
}
|
f82784f8b93c6eb2339213fb2979f6471ccf4351
|
TypeScript
|
marcos514/Laboratorio_3
|
/27_4/ajax.ts
| 2.65625
| 3
|
function validarUsuario():void
{
let nombre=<HTMLInputElement>document.getElementById("txtUsuario");
let pass=<HTMLInputElement>document.getElementById("txtPass");
if(nombre.value!="" && pass.value!="")
{
let peticion=new XMLHttpRequest();
peticion.open("GET","validar.php?nombre="+nombre.value+"&pass="+pass.value,true);
peticion.send();
peticion.onreadystatechange = () =>{
if(peticion.status==200&&peticion.readyState==4)
{
let respuesta=peticion.responseText;
if(respuesta=="OK")
{
(<HTMLBodyElement>document.getElementById("body")).style.backgroundColor="#00ff00";
}
else
{
(<HTMLBodyElement>document.getElementById("body")).style.backgroundColor="#FF0000";
}
}
}
}
}
|
c8ea7cab0a861f70a52a8529c116ca3bdd1b38ba
|
TypeScript
|
kingdavid6336/MyCrypto
|
/src/services/FeatureFlagProvider.test.ts
| 2.546875
| 3
|
import { act, renderHook } from '@testing-library/react-hooks';
import { FEATURE_FLAGS } from '@config';
import { FeatureFlagProvider, useFeatureFlags } from './FeatureFlagProvider';
const renderUseFeatureFlags = () => {
return renderHook(() => useFeatureFlags(), { wrapper: FeatureFlagProvider });
};
describe('useFeatureFlags', () => {
it('uses the features config file', () => {
const { result } = renderUseFeatureFlags();
expect(result.current.featureFlags).toEqual(FEATURE_FLAGS);
});
it('can set a feature flag value to false', () => {
const { result } = renderUseFeatureFlags();
const { setFeatureFlag } = result.current;
const target = 'DASHBOARD';
act(() => setFeatureFlag(target, false));
expect(result.current.featureFlags[target]).toEqual(false);
});
it('can set a feature flag value to true', () => {
const { result } = renderUseFeatureFlags();
const { setFeatureFlag } = result.current;
const target = 'DASHBOARD';
act(() => setFeatureFlag(target, true));
expect(result.current.featureFlags[target]).toEqual(true);
});
it('can reset the values to default', () => {
const { result } = renderUseFeatureFlags();
const { setFeatureFlag, resetFeatureFlags } = result.current;
const target = 'DASHBOARD';
act(() => setFeatureFlag(target, false));
act(() => resetFeatureFlags());
expect(result.current.featureFlags[target]).toEqual(FEATURE_FLAGS[target]);
});
it('can toggle a value', () => {
const { result } = renderUseFeatureFlags();
const { toggleFeatureFlag, featureFlags } = result.current;
const target = 'DASHBOARD';
const original = featureFlags[target];
act(() => toggleFeatureFlag(target));
expect(result.current.featureFlags[target]).toEqual(!original);
});
});
|
f4b39193661b29f6deca5efc82e20de5a707b333
|
TypeScript
|
andrasferenczi/next-env-runtime
|
/packages/node/src/functionality.ts
| 2.546875
| 3
|
export const doSomething = (value: string): string => {
return `some ${value.toUpperCase()} thing`;
};
|
238b669dd69a2c7e026b724ca876a3f968470b69
|
TypeScript
|
p18a/codechallenge2021
|
/src/hooks/useTripData.ts
| 3.015625
| 3
|
import { useMemo } from 'react';
import { Consumption, Distance, Duration, FuelUnit, Velocity } from '../types';
export interface TripData {
readonly t: Duration;
readonly fuelUsed: FuelUnit;
}
function tripDuration(v: Velocity, d: Distance): Duration {
return d / v;
}
function fuelUsed(v: Velocity, d: Distance, c: Consumption, multiplier: number): FuelUnit {
return ((c * Math.pow(multiplier, v - 1)) / 100) * d;
}
export default function useTripData(
v: Velocity | null,
d: Distance | null,
c: Consumption | null,
multiplier: number,
): TripData {
return useMemo(
() => ({
t: v && d ? tripDuration(v, d) : NaN,
fuelUsed: v && d && c && multiplier ? fuelUsed(v, d, c, multiplier) : NaN,
}),
[v, d, c, multiplier],
);
}
|
2e3fbb5347aa1f75475ae7ec9a284ca76c8ddfbd
|
TypeScript
|
dtjohnson/typeshield
|
/src/guards/is-equatable.ts
| 3.171875
| 3
|
import { Equatable, Guard } from '../types';
import { hasInterface } from './has-interface';
import { isFunction } from './is-function';
/**
* @ignore
*/
const guard = hasInterface<Equatable>('Equatable', {
equals: isFunction,
});
/**
* Guard that tests if the value implements the [[Equatable]] interface
* @param value The value to test
* @returns The result of the test
*/
export function isEquatable(value: unknown): value is Equatable {
return guard(value);
}
(isEquatable as Guard).expectation = guard.expectation;
|
4965912ce9eb9422536bbac7e9a4f4a61fd02aaf
|
TypeScript
|
SamuelKasper/Prima-Endabgabe
|
/EndabgabeCode/Sounds.ts
| 2.59375
| 3
|
namespace Dodge {
import f = FudgeCore;
export enum SoundList { collectCoin, settingTrap }
export class Sounds {
private music: f.Audio;
private coin: f.Audio;
private cmpBackgroundMusic: f.ComponentAudio;
private cmpCoinSound: f.ComponentAudio;
public constructor() {
this.music = new f.Audio("Audio/Final.mp3");
this.cmpBackgroundMusic = new f.ComponentAudio(this.music, true, false);
this.cmpBackgroundMusic.connect(true);
this.cmpBackgroundMusic.volume = 0.5;
this.coin = new f.Audio("Audio/CoinSoundE.mp3");
this.cmpCoinSound = new f.ComponentAudio(this.coin, false, false);
this.cmpCoinSound.connect(true);
this.cmpCoinSound.volume = 0.5;
}
public playSound(_sound: SoundList): void {
if (_sound == SoundList.collectCoin) {
this.cmpCoinSound.play(true);
}
}
public playBackgroundMusic(_state: boolean): void {
this.cmpBackgroundMusic.play(_state);
}
}
}
|
9c0a3bf0f9443c144a61676a376d6f2fddd54118
|
TypeScript
|
green-fox-academy/KornelKovats
|
/week-02/day-02/Data_Sctructure/shopping-list.ts
| 3.21875
| 3
|
let list: string[]= ['Eggs', 'milk', 'fish', 'apples', 'bread', 'chicken'];
let dowehavemilk: boolean = false;
let dowehavebananas: boolean = false
list.forEach(function (value, index, array) {
if (value=="milk"){
dowehavemilk= true;
}
if (value=="bananas"){
dowehavebananas= true;
}
});
if (dowehavemilk){
console.log("yes we have milk");
} else{
console.log("no we dont have milk");
}
if (dowehavebananas){
console.log("yes we have bananas");
} else{
console.log("no we dont have bananas");
}
|
5a3c74354775c31f75cbd3ce5c40fd77d1994143
|
TypeScript
|
Lixuan-Qiu/theBuzz
|
/web/ts/Login.ts
| 3.078125
| 3
|
/**
* Login encapsulates all of the code for the form for adding an entry
*/
class Login {
/**
* The name of the DOM entry associated with Login
*/
public static readonly NAME = "Login";
/**
* Track if the Singleton has been initialized
*/
private static isInit = false;
/**
* Initialize the Login by creating its element in the DOM and
* configuring its buttons. This needs to be called from any public static
* method, to ensure that the Singleton is initialized before use
*/
private static init() {
if (!Login.isInit) {
Login.isInit = true;
}
}
/**
* Refresh() doesn't really have much meaning, but just like in sNavbar, we
* have a refresh() method so that we don't have front-end code calling
* init().
*/
public static refresh() {
Login.init();
}
/**
* Send data to submit the form only if the fields are both valid.
* Immediately hide the form when we send data, so that the user knows that
* their click was received.
*/
private static submitForm() {
// get the values of the two fields, force them to be strings, and check
// that neither is empty
if (id_token === "" || id_token === null) {
window.alert("Error: id_token is not valid");
return;
}
console.log("Login: requesting put to " + backendUrl + "/login");
// set up an AJAX post. When the server replies, the result will go to
// onSubmitResponse
$.ajax({
type: "POST",
url: backendUrl + "/login",
dataType: "json",
data: JSON.stringify({ id_token: id_token}),
success: Login.onSubmitResponse
});
}
/**
* onSubmitResponse runs when the AJAX call in submitForm() returns a
* result.
*
* @param data The object returned by the server
*/
private static onSubmitResponse(data: any) {
// If we get an "ok" message, clear the form and refresh the main
// listing of messages
if (data.mStatus === "ok") {
console.log("Login: success, key: " + data.sessionkey);
user_id = data.uid;
session_key = data.sessionkey;
ElementList.refresh();
Login.callMainPage();
}
// Handle explicit errors with a detailed popup message
else if (data.mStatus === "error") {
window.alert("The server replied with an error:\n" + data.echoMessage);
}
// Handle other errors with a less-detailed popup message
else {
window.alert("Unspecified error");
}
}
private static callMainPage(){
console.log("Login: call main page");
$("#" + Login.NAME + "-container").hide();
$("#" + ElementList.NAME).show();
$("#" + NewEntryForm.NAME).show();
}
public static hideMainPage() {
console.log("Login: hide main page");
$("#" + Login.NAME + "-container").show();
$("#" + ElementList.NAME).hide();
$("#" + NewEntryForm.NAME).hide();
session_key = "";
}
}
|
af7400438111f186865fbf7f8306b313e1415cb0
|
TypeScript
|
ngld/knossos
|
/packages/front/src/lib/twirp-helpers.ts
| 2.546875
| 3
|
import { TwirpErrorCode } from '@protobuf-ts/twirp-transport';
import { alert } from './alert';
export function presentTwirpError(code: string | TwirpErrorCode): void {
if (typeof code === 'string') {
code = parseInt(code, 10) as TwirpErrorCode;
}
switch (code) {
case TwirpErrorCode.cancelled:
case TwirpErrorCode.aborted:
// ignore
return;
case TwirpErrorCode.invalid_argument:
case TwirpErrorCode.malformed:
case TwirpErrorCode.not_found:
case TwirpErrorCode.bad_route:
case TwirpErrorCode.unimplemented:
alert({
children:
"The server didn't recognize our request. Please clear your cache and reload the page.",
confirmButtonText: 'OK',
});
return;
case TwirpErrorCode.deadline_exceeded:
case TwirpErrorCode.resource_exhausted:
case TwirpErrorCode.unavailable:
// transient error
alert({
children: 'The server ran into an issue while responding. Please try again.',
confirmButtonText: 'OK',
});
return;
case TwirpErrorCode.internal:
// internal error
alert({
children: 'An internal error occurred. Please try again later.',
confirmButtonText: 'OK',
});
return;
case TwirpErrorCode.unknown:
default:
// report
alert({
children: 'An unknown error occured. Please report it and try again.',
confirmButtonText: 'OK',
});
return;
}
}
|
26d4a00baf8c9de63df10094482b616c1cb2534d
|
TypeScript
|
forabi/sirriyah
|
/src/client/store/middleware/encryption.ts
| 2.53125
| 3
|
import { Store, Dispatch, Middleware } from 'redux';
import {
updateMessage,
sendFailed,
sendEncryptedMessage,
keyPairGenereated,
keyPairGenereationFailed,
} from '../../actions';
import { getPrivateKey } from '../reducer';
import { isActionOfType } from '../utils';
import { encrypt, decrypt, generateKeyPair } from 'client/crypto';
const middleware: Middleware = ({ getState }: Store<StoreState>) =>
(next: Dispatch<GenericAction>) => async (action: GenericAction) => {
if (isActionOfType(action, 'GENERATE_KEYS_REQUESTED')) {
try {
const { publicKey, privateKey } = await generateKeyPair();
next(keyPairGenereated({ privateKey, publicKey }));
} catch (error) {
next(keyPairGenereationFailed(error));
}
} else if (isActionOfType(action, 'SEND_MESSAGE_REQUESTED')) {
next(action);
const { message, publicKey } = action.payload;
const { localId } = message;
next(updateMessage({ localId, status: 'encrypting' }));
try {
const encryptedMessage = await encrypt(message, publicKey);
next(sendEncryptedMessage(encryptedMessage));
} catch (error) {
next(sendFailed({ localId, message: error.message }));
}
} else if (isActionOfType(action, 'MESSAGE_RECEIVED')) {
const { payload: message } = action;
const { localId } = message;
next(updateMessage({ localId, status: 'decrypting' }));
const state = getState();
try {
const privateKey = getPrivateKey(state);
if (privateKey !== null) {
const decryptedMessage = await decrypt(message, privateKey);
next(updateMessage({ ...decryptedMessage, localId }));
} else {
throw new TypeError('Missing private key');
}
} catch (error) {
next(sendFailed({ localId, message: error.message }));
}
} else {
next(action);
}
};
export default middleware;
|
6f9c1d4298d38d400c15dd51eea6eccb006decc4
|
TypeScript
|
chiamtc/udemy-angular4
|
/more-angular-material/src/app/training/training.reducer.ts
| 2.828125
| 3
|
import {Action, createFeatureSelector, createSelector} from '@ngrx/store';
import {SET_AVAILABLE_TRAININGS, SET_FINISHED_TRAININGS, START_TRAINING, STOP_TRAINING} from "./training.action";
import {Exercise} from "./exercise.model";
import * as fromRoot from '../app.reducer';
import {
TrainingAction,
StopTraining,
StartTraining,
SetFinishedTrainings,
SetAvailableTrainings
} from "./training.action";
export interface TrainingState {
availableExercises: Exercise[];
finishedExercises: Exercise[];
activeTraining: Exercise;
}
//lazy routing purpose.
// fromRoot.State doesn't know trainingState but trainingState knows fromRoot.State, so
// training variable is an instance of TrainingState < this is a global state for training.
// Treat it like it's in app.reducer but only for lazy routing module. Add it in training.module instead of app.module
export interface State extends fromRoot.State {
training: TrainingState
}
const initialState: TrainingState = {
availableExercises: [],
finishedExercises: [],
activeTraining: null
};
export function trainingReducer(state = initialState, action: TrainingAction) {
switch (action.type) {
case SET_AVAILABLE_TRAININGS:
return {
...state,
availableExercises: action.payload
};
case SET_FINISHED_TRAININGS:
return {
...state,
finishedExercises: action.payload
};
case START_TRAINING:
return {
...state,
activeTraining: {...state.availableExercises.find(ex => ex.id=== action.payload)}
};
case STOP_TRAINING:
return {
...state,
activeTraining: null
};
default:
return state;
}
}
export const getTrainingState = createFeatureSelector<TrainingState>('training');
export const getAvailableExercises = createSelector(getTrainingState, (state: TrainingState) => state.availableExercises);
export const getFinishedExercises = createSelector(getTrainingState, (state: TrainingState) => state.finishedExercises);
export const getActiveTraining =createSelector(getTrainingState, (state: TrainingState) => state.activeTraining);
export const getIsTraining = createSelector(getTrainingState, (state:TrainingState)=> state.activeTraining != null);
|