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
|
|---|---|---|---|---|---|---|
8e675c5e18ba2f1390e5495c10a26f137661deb9
|
TypeScript
|
Ramdhanll/trishop
|
/src/contexts/UserReducer.ts
| 3.140625
| 3
|
import { Dispatch } from 'react'
// context initial state type
export interface InitialState {
user: null | UserPayload
dispatchUser: Dispatch<Action>
}
export type UserPayload = {
_id: string
name: string
email: string
// password: string
role: 'ADMIN' | 'USER'
createdAt: string
updatedAt: string
}
export type Action =
| {
type: 'ADD_USER'
payload: UserPayload
}
| {
type: 'DEL_USER'
payload?: never
}
export default function UserReducer(
state: InitialState,
action: Action
): InitialState {
switch (action.type) {
case 'ADD_USER':
return {
...state,
user: action.payload,
}
case 'DEL_USER':
return {
...state,
user: null,
}
default:
throw new Error('Unhandled action type')
}
}
|
0af2a06621f381867d649d25bfa13ee421e4c484
|
TypeScript
|
mikgor/Wallethon
|
/frontend/src/app/shared/models/transactions-summary/sell-related-transaction.ts
| 2.625
| 3
|
import {StockTransaction} from '../../../main/components/dashboard/models/StockTransaction';
import {Money} from '../money';
export class SellRelatedTransaction {
soldQuantity: number;
originQuantitySoldRatio: number;
costs: Money;
income: Money;
public constructor(soldQuantity: number, originQuantitySoldRatio: number, costs: number, costsCurrency: string,
income: number, incomeCurrency: string) {
this.soldQuantity = soldQuantity;
this.originQuantitySoldRatio = originQuantitySoldRatio;
this.costs = new Money(costs, costsCurrency);
this.income = new Money(income, incomeCurrency);
}
public setCostsAndIncome(costs: Money, income: Money) {
this.costs = costs;
this.income = income;
}
public getProfitLoss() {
const profitLoss = this.income.subtract(this.costs);
return profitLoss;
}
public getAdditionalCosts(sellStockTransaction: StockTransaction) {
const commissionsSum = sellStockTransaction.commission.sum(sellStockTransaction.tax);
return commissionsSum.multiply(this.originQuantitySoldRatio);
}
public getTransactionDate() {
return null;
}
}
|
8b35aecc1f5d63802f159b33c65fce7736dde149
|
TypeScript
|
victorfernandesraton/control-warehouse
|
/src/adapters/Storage.ts
| 2.75
| 3
|
import Storage from '../core/entity/Storage';
export interface CreateStorageParams {
id?: string;
name: string;
description?: string;
}
export default class StorageAdapter {
static create({ id, name, description }: CreateStorageParams): Storage {
return new Storage({
id,
name,
description,
});
}
}
|
8447463b8345d1314bd29c093a9bbbca523b6564
|
TypeScript
|
Akashh1996/Skylab-Bootcmamp-2020
|
/eric-martinez/ts-demo/greeter.ts
| 3.5
| 4
|
class Student {
fullname: string
constructor(public firstname: string, public lastname: string) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = `${firstname} ${lastname}`
}
}
interface Person {
firstname: string;
lastname: string;
}
function greeter(person: Person){
return `hola ${person.firstname} ${person.lastname}`;
}
let user = new Student('Eric', 'Martínez');
document.getElementById('root').textContent = greeter(user);
|
8a51d34bfb1cba9ae7be4920b5d9383dfaafefae
|
TypeScript
|
DaVince/Excalibur
|
/src/engine/Graphics/Context/renderer.ts
| 2.5625
| 3
|
import { BatchCommand } from './batch';
import { Shader } from './shader';
// import { Pool, Poolable } from './pool';
import { GraphicsDiagnostics } from '../GraphicsDiagnostics';
import { Pool, Poolable } from '../../Util/Pool';
export interface Renderer {
render(): void;
}
export interface Ctor<T> {
new (): T;
}
export interface BatchRendererOptions<T extends Poolable> {
gl: WebGLRenderingContext;
/**
* Draw command constructor
*/
command: Ctor<T>;
/**
* Number of vertices that are generated per draw command
*/
verticesPerCommand?: number;
/**
* Maximum commands to batch before drawing
*/
maxCommandsPerBatch?: number;
/**
* Override the built in command batching mechanism
*/
batchFactory?: () => BatchCommand<T>;
}
export abstract class BatchRenderer<T extends Poolable> implements Renderer {
priority = 0;
private _gl: WebGLRenderingContext;
private _vertices: Float32Array;
private _verticesPerCommand: number;
private _buffer: WebGLBuffer | null = null;
private _maxCommandsPerBatch: number = 2000;
public shader: Shader;
public commands: Pool<T>;
private _batchPool: Pool<BatchCommand<T>>;
private _batches: BatchCommand<T>[] = [];
constructor(options: BatchRendererOptions<T>) {
this._gl = options.gl;
const command = options.command;
this._verticesPerCommand = options?.verticesPerCommand ?? 1;
this._maxCommandsPerBatch = options?.maxCommandsPerBatch ?? this._maxCommandsPerBatch;
const batchFactory = options?.batchFactory ?? (() => new BatchCommand<T>(this._maxCommandsPerBatch));
this.commands = new Pool<T>(
() => new command(),
(c) => c.dispose(),
this._maxCommandsPerBatch
);
this._batchPool = new Pool<BatchCommand<T>>(batchFactory, (b) => b.dispose(), 100);
}
/**
* Initialize render, builds shader and initialized webgl buffers
*/
public init() {
const gl = this._gl;
this.shader = this.buildShader(gl);
// Initialize VBO
// https://groups.google.com/forum/#!topic/webgl-dev-list/vMNXSNRAg8M
this._vertices = new Float32Array(this.shader.vertexAttributeSize * this._verticesPerCommand * this._maxCommandsPerBatch);
this._buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this._buffer);
gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW);
}
public get vertexSize(): number {
return this.shader.vertexAttributeSize;
}
public addCommand(cmd: T) {
if (this._batches.length === 0) {
this._batches.push(this._batchPool.get());
}
const lastBatch = this._batches[this._batches.length - 1];
if (lastBatch.canAdd()) {
lastBatch.add(cmd);
} else {
const newBatch = this._batchPool.get();
newBatch.add(cmd);
this._batches.push(newBatch);
}
}
/**
* Construct or return the Shader to be used in this batch renderer
* @param gl
*/
abstract buildShader(gl: WebGLRenderingContext): Shader;
/**
* Implement populating the vertex buffer, return the number of vertices added to the buffer
* @param vertices
* @param batch
*/
abstract buildBatchVertices(vertexBuffer: Float32Array, batch: BatchCommand<T>): number;
/**
* Implement gl draw call to render batch. The vertextBuffer from buildBatchVertices is already bound and the data has been updated.
*/
abstract renderBatch(gl: WebGLRenderingContext, batch: BatchCommand<T>, vertexCount: number): void;
/**
* Build batch geometry, submit to the gpu, and issue draw command to underlying webgl
*/
public render(): void {
const gl = this._gl;
gl.bindBuffer(gl.ARRAY_BUFFER, this._buffer);
this.shader.use();
let drawCallCount = 0;
let drawnImagesCount = 0;
for (const batch of this._batches) {
// Build all geometry and ship to GPU
// interleave VBOs https://goharsha.com/lwjgl-tutorial-series/interleaving-buffer-objects/
const vertexCount = this.buildBatchVertices(this._vertices, batch);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this._vertices);
this.renderBatch(gl, batch, vertexCount);
drawnImagesCount += batch.commands.length;
drawCallCount++;
}
this.commands.done();
this._batchPool.done();
this._batches.length = 0;
GraphicsDiagnostics.DrawCallCount += drawCallCount;
GraphicsDiagnostics.DrawnImagesCount += drawnImagesCount;
}
}
|
3eeba0b54e13d0a0b1fb3a9e5b6244b3f340033f
|
TypeScript
|
jajaperson/IxJS
|
/src/asynciterable/fromeventpattern.ts
| 3.40625
| 3
|
import { AsyncIterableX } from './asynciterablex';
import { AsyncSink } from './asyncsink';
import { memoize } from './operators/memoize';
/**
* Creates asnyc-iterable from an event emitter by adding handlers for both listening and unsubscribing from events.
*
* @template TSource The type of elements in the event emitter.
* @param {(handler: (...args: any[]) => void) => void} addHandler The function to add a listener to the source.
* @param {(handler: (...args: any[]) => void) => void} removeHandler The function to remove a listener from the source.
* @returns {AsyncIterableX<TSource>} An async-iterable which contains the data from the underlying events as wrapped by the handlers.
*/
export function fromEventPattern<TSource>(
addHandler: (handler: (...args: any[]) => void) => void,
removeHandler: (handler: (...args: any[]) => void) => void
): AsyncIterableX<TSource> {
const sink = new AsyncSink<TSource>();
const handler = (e: TSource) => sink.write(e);
addHandler(handler);
const yielder = async function* () {
for (let next; !(next = await sink.next()).done; ) {
yield next.value;
}
removeHandler(handler);
sink.end();
};
return memoize<TSource>()(yielder());
}
|
a7c686bc4b68790629aad1c23550ff4be8d8abcb
|
TypeScript
|
hombrevrc/prerender
|
/lib/PrerenderWorker.ts
| 2.515625
| 3
|
import * as puppeteer from "puppeteer";
import {CrawlPage} from "./CrawlPage";
import {crawlerSanitizePage, crawlerScrapeAllLinks} from "./Helpers";
export class PrerenderWorker {
private browser = null;
private readonly crawlRegex: RegExp;
constructor(crawlRegex: RegExp) {
this.crawlRegex = crawlRegex;
}
async setup() {
this.browser = await puppeteer.launch({
headless: true,
args: ['--disable-dev-shm-usage']
});
}
private getWhitelistedUrls(all: string[]) {
if (!all || all.length < 1) {
return [] as string[];
}
return all.filter(url => url.match(this.crawlRegex));
}
async render(cp: CrawlPage) {
console.debug("Rendering URL: ", cp.url);
if (!this.browser) {
return Promise.reject("Worker not setup");
}
const page = await this.browser.newPage();
await page.setUserAgent('bot-exlpre-0.0.1');
await page.goto(cp.url, {
waitUntil: "networkidle0",
});
await page.evaluate(crawlerSanitizePage);
cp.resultHTML = await page.evaluate(() => {
return document.documentElement.innerHTML;
});
cp.linksTo = this.getWhitelistedUrls(await page.evaluate(crawlerScrapeAllLinks));
// Clean up the tab
await page.goto('about:blank');
await page.close();
console.debug("Completed rendering URL: ", cp.url);
}
}
|
10a75a96124c39725fd75ac8390d8191b31b465d
|
TypeScript
|
Svetov/angular-calendar
|
/src/app/root-store/clock-store/clock-action.ts
| 2.546875
| 3
|
import { Action } from '@ngrx/store';
export enum ClockActionTypes {
SELECT_CLOCKS = 'SELECT_CLOCKS',
}
export class selectClockAction implements Action {
readonly type = ClockActionTypes.SELECT_CLOCKS;
constructor(public payload: { clocks: Array<string> }) {}
}
export type ClockActions = selectClockAction;
|
387dc1bf9d2bc22353a9e75e87c146e4a03dce4c
|
TypeScript
|
nathan-oliveira/Projeto_Financas_Pessoais_Backend
|
/app/controllers/Controller.ts
| 2.53125
| 3
|
import * as express from "express";
abstract class Controller {
public req: express.Request;
public res: express.Response;
constructor(req: express.Request, res: express.Response) {
this.req = req;
this.res = res;
}
protected response(result: any) {
return this.res.status(result.statusCode).json(result.body);
}
}
export default Controller;
|
aa86044d4a5d2cf5169f0ddf7d9c4cb36060dc50
|
TypeScript
|
c2c-project/prytaneum-typings
|
/src/auth.ts
| 2.6875
| 3
|
import faker from 'faker';
export interface RegisterForm {
password: string;
email: string;
confirmPassword: string;
firstName: string;
lastName: string;
}
export const makeRegisterForm = (): RegisterForm => {
const password = faker.internet.password();
return {
password,
email: faker.internet.email(),
confirmPassword: password,
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
};
};
export interface ForgotPassRequestForm {
email: string;
}
export const makeForgotPassRequestForm = (): ForgotPassRequestForm => ({
email: faker.internet.email(),
});
export interface ForgotPassForm {
password: string;
confirmPassword: string;
}
export const makeForgotPassForm = (): ForgotPassForm => {
const password = faker.internet.password();
return {
password,
confirmPassword: password,
};
};
|
6ccf72acbe9d05c2fd68d50eaf9cf577c197cf34
|
TypeScript
|
EvgeniyGordinskiy/trello_api_node
|
/app/Controllers/authController.ts
| 2.625
| 3
|
import {Response, Request} from 'express';
import passport from 'passport';
import bcrypt from 'bcrypt';
import _passport from '../passport/passport';
_passport(passport);
import User from '../models/user';
import validations from '../helpers/validations';
let auth = {
// Render register page
getRegister(req: Request, res: Response) {
res.status(200).send();
},
/**
* Handle user registration process.
* 1. Check if user is already registered by checking email
* 2. Encrypt password
* 3. Save user information in MongoDB
* 4. Create a customer on Stripe with Free Plan
**/
register(req: Request, res: Response) {
let name = req.query.registerName;
let email = req.query.registerEmail;
let password = req.query.registerPassword;
if (name.trim().length === 0) {
return res.status(400).send('Name cannot be empty');
}
if (!validations(email)) {
return res.status(400)
.send('Email cannot be empty & should be valid format');
}
if (password.trim().length < 6) {
return res.status(400).send('Password should be at least 6 characters');
}
let hashedPassword = null;
User.findOne(
{'email': email}
, (err0, user: any)=> {
if (err0) {
return res.status(400).send('Error on finding user');
}
if (user && user.email === email) {
return res.status(400).send('This email is already registered');
}
// Encrypt user password
bcrypt.genSalt(10, (err, salt)=> {
bcrypt.hash(password, salt, (err1, hash)=> {
if (err1) {
return res.status(400).send('Error on hashing password');
}
hashedPassword = hash;
// User object to be saved in MongoDB
let newUser = new User({
'name': name,
'email': email,
'password': hashedPassword
});
newUser.save((err2, theUser)=> {
if (err) {
return res.status(500).send('Could not save user');
}
req.login(theUser, (err3)=> {
if (err3) {
return res.status(400).send('Something went wrong. Try again.');
}
return res.status(200).send('Welcome to Meetup Event Planner!');
});
});
});
});
});
},
// Render login page
getLogin(req: Request, res: Response) {
return res.status(200);
},
/**
* Handle user login process via Passport
**/
login(req: Request, res: Response) {
let email = req.query.loginEmail;
let password = req.query.loginPassword;
if (!validations(email)) {
return res.status(400).send('Please enter the correct email');
}
if (password.trim().length < 8) {
return res.status(400).send('Please enter the correct password');
}
passport.authenticate('local', (err0, user, info)=> {
if (err0) {
return res.status(400).send('Cannot login. Try again.');
}
if (!user) {
return res.status(400).send('User Not Found / Password is incorrect');
}
req.logIn(user, (err1)=> {
if (err1) {
return res.status(400).send('Cannot login. Try again.');
}
return res.status(200).send('Logged in');
});
})(req, res);
},
// Render Forgot Password page
getForgotPassword(req: Request, res: Response) {
res.status(200);
},
// Logout
logout(req: Request, res: Response) {
req.logout();
return res.status(200).send('You are logged out');
}
};
export default auth;
|
2abad98f856a8423c7d511283cbf02e2a150e4c9
|
TypeScript
|
Harsh-Pareek-Commits/MyTrip-FrontEnd
|
/src/app/Models/feedback.ts
| 2.6875
| 3
|
import { Customer } from "./customer";
export class Feedback{
feedbackId:number;
customer:Customer;
feedback:string;
rating:number;
submitDate:Date;
constructor(feedbackId:number,
customer:Customer,
feedback:string,
rating:number,
submitDate:Date)
{
this.feedbackId = feedbackId;
this.customer = customer;
this.feedback = feedback;
this.rating = rating;
this.submitDate = submitDate;
}
}
|
f1bcc9555f3bc732ef7745ee9e804cff6c4fbe30
|
TypeScript
|
juliandavidmr/Servue
|
/core/decorators/controller.ts
| 2.546875
| 3
|
import * as Vue from 'vue'
import * as clone from 'clone'
import Config from './_config'
import * as cf from "../constants/request_classifier";
import { ITarget } from "../interfaces/ITarget";
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
export function VueController(options?: string)
export function VueController(options: vuejs.ComponentOption)
export function VueController(first_argv: any, options?: vuejs.ComponentOption) {
var type = typeof first_argv;
if (type == 'function') { //No param decorator, called at construction
createDecorator(null, null)(first_argv);
} else if (type == 'string') { //name and options or name only
return createDecorator(first_argv, options);
} else if (type == 'object') { //options only
return createDecorator(null, first_argv);
} else {
throw Error("First parameter of VueController must be a string or an object");
}
}
function camelToSnake(str: string) {
var snake = str.replace(/([A-Z])/g, function ($1) { return "-" + $1.toLowerCase(); });
if (snake.charAt(0) == '-') snake = snake.substring(1);
return snake;
};
function getPrefix(option: any, className: string) {
let prefix_base = ((): string => {
if (typeof option === 'string') {
return option;
} else if (typeof option === 'object') {
if (!!option.prefix && typeof option.prefix === 'string') {
return option.prefix;
}
return className;
}
})()
if (prefix_base.trim().startsWith('/')) {
return prefix_base.trim();
}
return `/${prefix_base.trim()}`
}
function createDecorator(name?: string, options?: vuejs.ComponentOption) {
return function decorator(target: any) {
// console.log("Proto: ", arguments[0].prototype);
var prefix = '';
let methods: Array<{ type: string, name: string, func: Function }> = Object.getOwnPropertyDescriptor(arguments[0].prototype, "$$methods")["value"];
console.log("Metodos=>", methods);
// save a reference to the original constructor
var original = target;
var className = camelToSnake(target.toString().match(/\w+/g)[1]);
prefix = getPrefix(options, className);
if (!options) options = {};
if (!options.methods) options.methods = {};
// a utility function to generate instances of a class
function construct(constructor, args) {
var c: any = function () {
return constructor.apply(this, args);
}
c.prototype = constructor.prototype;
return new c();
}
if (!name) name = camelToSnake(target.toString().match(/\w+/g)[1]);
if (!options) options = {};
if (!options.props) options.props = {};
if (!options.watch) options.watch = {};
if (!options.computed) options.computed = {};
if (options.data) {
if (typeof options.data == 'function') {
var data_rtn = (<any>options).data();
options.data = data_rtn;
}
} else options.data = {};
if (options['style']) delete options['style'];
var instance = construct(original, {});
for (var key in instance) {
if (key.charAt(0) != '$' && key.charAt(0) != '_') {
var prop_desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
if (prop_desc && prop_desc.get) {
// console.log("prop desc:", prop_desc);
var computed_obj: any = {};
if (prop_desc.set) {
computed_obj.get = prop_desc.get;
computed_obj.set = prop_desc.set;
} else {
computed_obj = prop_desc.get;
}
options.computed[key] = computed_obj;
}
if (typeof (instance[key]) == 'function') {
// console.log("function desc:", key, instance[key]);
if (Config.vueInstanceFunctions.indexOf(key) > -1) {
options[key] = instance[key]
}
} else {
options.data[key] = instance[key];
}
} else if (key == "$$props") {
for (var prop in instance.$$props) {
options.props[prop] = instance.$$props[prop];
}
} else if (key == "$$watch") {
for (var watch in instance.$$watch) {
options.watch[watch] = instance.$$watch[watch];
delete options.methods[watch]
}
}
}
for (key in options.props) {
var default_val = options.data[key];
if (default_val == null || default_val == undefined) default_val = options.methods[key]
if (default_val != null && default_val != undefined) {
if (!options.props[key])
options.props[key] = {};
if (typeof default_val == 'function') options.props[key].type = Function;
if (typeof default_val == 'object') {
var copy = clone(default_val, false);
default_val = function () {
return clone(copy, false);
};
}
options.props[key].default = default_val;
}
delete options.data[key];
delete options.methods[key];
}
for (var i in instance.$$methodsToRemove) {
delete options.methods[instance.$$methodsToRemove[i]]
}
var data = options.data;
options.data = () => {
return data;
}
methods.map(it => {
let route = cf.concatUrl([prefix, it.name]);
// console.log('route added:', route);
options.methods[it.type + cf.SEPARATOR + route] = it.func;
})
// options.$$methods = methods;
return options;
}
}
|
0ae8f056082f081d96a7ebd2ead6ccce03172f97
|
TypeScript
|
zumo/zumokit-react-native
|
/src/utility/errorProxy.ts
| 2.8125
| 3
|
import { ZumoKitError } from '../ZumoKitError';
/** @internal */
function handler(fun: any) {
return function bar(this: any) {
try {
// eslint-disable-next-line prefer-rest-params
const res = fun.apply(this, arguments);
if (Promise.resolve(res) === res) {
return res.catch((e: any) => {
return e instanceof Error ? Promise.reject(e) : Promise.reject(new ZumoKitError(e));
});
}
return res;
} catch (e) {
if (e instanceof Error) {
throw e;
} else {
throw new ZumoKitError(e as any);
}
}
};
}
/** @internal */
export function tryCatchProxy(constructor: Function) {
const { prototype } = constructor;
if (Object.getOwnPropertyNames(prototype).length < 2) {
return;
}
// eslint-disable-next-line no-restricted-syntax
for (const property in Object.getOwnPropertyDescriptors(prototype)) {
if (
Object.prototype.hasOwnProperty.call(prototype, property) &&
property !== 'constructor' &&
typeof prototype[property] === 'function'
) {
prototype[property] = handler(prototype[property]);
}
}
}
|
09be3cfab19a37111580e9950026c6286a63b6c4
|
TypeScript
|
aizigao/BracketEnum
|
/src/BracketEnum/index.ts
| 3.234375
| 3
|
type Code = string;
type Value = string | number;
type Desc = string;
type Extra = any;
const isNil = (v: any) => v == null;
export type IEnumOption<IEmumValue, IEmumDesc> = {
label?: IEmumDesc;
value?: IEmumValue;
key?: IEmumValue;
extra?: any;
};
type IValueEnum = Record<
string,
{
text: string;
status?: 'Success' | 'Error' | 'Processing' | 'Warning' | 'Default';
extra?: any;
}
>;
/**
* 枚举定义工具
* @example
* ```jsx
* const STATUS = new DtEnum([
* ['AUDIT_WAIT', [1, '审核中']],
* ['AUDIT_PASS', [2, '审核通过']]
* ])
* ```
*/
class DtEnum<
C extends [T, [V, D, Extra?]],
T extends Code,
V extends Value | number,
D extends Desc
> {
private byCodeMap: Record<
string,
{
code: C[0];
value: C[1][0];
desc: C[1][1];
extra?: C[1][2];
}
> = {};
private byValueMap: Record<
string,
{
code: C[0];
value: C[1][0];
desc: C[1][1];
extra?: C[1][2];
}
> = {};
private configList: C[] = [];
static of<
FC extends [FT, [FV, FD, Extra?]],
FT extends Code,
FV extends Value | number,
FD extends Desc
>(config: FC[]) {
return new DtEnum(config);
}
values: C[1][0][];
constructor(config: C[]) {
this.configList = config;
this.values = [];
config.forEach(item => {
const [code, [value, desc, extra]] = item;
this.byCodeMap[code] = { code, value, desc, extra };
this.byValueMap[String(value)] = { code, value, desc, extra };
this.values.push(value);
});
}
/**
* 由code获取value
* @param code
*/
getValueByCode(code: C[0]): C[1][0] {
return this.byCodeMap[code]?.value;
}
/**
* 由code获取desc
* @param code
*/
getDescByCode(code: C[0]): C[1][1] {
return this.byCodeMap[code]?.desc;
}
/**
* 由code获取extra
* @param code
*/
getExtraByCode(code: C[0]): C[1][2] {
return this.byCodeMap[code]?.extra;
}
/**
* 由value获取desc
* @param value
*/
getDescByValue(value: C[1][0]): C[1][1] | undefined {
if (String(value) in this.byValueMap) {
return this.byValueMap[String(value)]?.desc;
}
}
/**
* 由value获取extra
* @param value
*/
getExtraByValue(value: C[1][0]): C[1][2] | undefined {
if (String(value) in this.byValueMap) {
return this.byValueMap[String(value)]?.extra;
}
}
/**
* 获取所有values
* @example
* ```jsx
* STATUS.getAllValues() // => [1,2]
* ```
*/
getAllValues() {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return this.configList.map(([code, [value]]) => value);
}
/**
* 转为form要使用的option
* @example
* STATUS.toFormOptions()
*/
toFormOptions(hasAll: boolean = false): any[] {
const allOption = {
key: null,
value: null,
label: '全部',
extra: null,
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const result = this.configList.map(([code, [value, desc, extra]]) => {
return {
key: value,
value,
label: desc,
extra,
};
});
if (hasAll) {
return [allOption, ...result];
}
return result;
}
/**
* 转为antd pro table 需要的ValueEnum
* @example
* STATUS.toFormValueEnum()
*
* // return example
* {
* 1: {text: '审核中'}
* }
*/
toFormValueEnum(): IValueEnum {
const result: IValueEnum = {};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
this.configList.forEach(([code, [value, desc, extra]]) => {
if (!isNil(value)) {
result[String(value)] = {
text: desc,
status: extra && extra.status,
extra,
};
}
});
return result;
}
/**
* value与code对应值匹配
* @example
* STATUS.checkValueByCode('AUDIT_WAIT',1)
*/
checkValueByCode(code: C[0], value: C[1][0]): boolean {
const iValue = this.getValueByCode(code);
return iValue === value;
}
}
export { DtEnum, DtEnum as default };
|
4751f76027ede5eaad44ee342104048cef50ec8b
|
TypeScript
|
bnteau/deno-todolist
|
/todo.ts
| 3.390625
| 3
|
import { Drash } from "https://deno.land/x/drash@v1.5.1/mod.ts";
interface Todo {
id: number,
title: string,
completed: boolean
}
// Juste des fausses données
let todos:Todo[] = [
{
id: 1,
title: "Passer à Typescript",
completed: false,
},
{
id: 2,
title: "Créer une API REST",
completed: false,
},
{
id: 3,
title: "Faire un beau design",
completed: false,
},
]
export class TodoList extends Drash.Http.Resource {
// On indique ici le chemin sur lequel la requête peut être faite
static paths = ["/todos"];
// La fonction indique le verbe HTTP à utiliser pour la requête
public GET() {
this.response.body = JSON.stringify(todos);
return this.response;
}
// Fonction très simple pour créer une nouvelle tâche
public POST() {
// this.request.getBodyParam() nous permet de récupérer les données entrées lors de la requête
// il nous suffit simplement d'indiquer la propriété voulue (title, completed)
const newTodo:Todo = {
id: Math.floor(Math.random() * Math.floor(100000)),
title: this.request.getBodyParam("title") as string,
completed: this.request.getBodyParam("completed") as boolean,
}
todos.push(newTodo);
this.response.body = JSON.stringify(newTodo);
return this.response;
}
}
// Cette classe va nous permettre de manipuler les tâches une par une
export class TodoElement extends Drash.Http.Resource {
// Ici, l'id sera donc une variable...
static paths = ["/todos/:id"];
// ...que l'on peut récupérer avec la fonction getPathParam()
public GET() {
const URLParam = this.request.getPathParam("id");
// On peut alors simplement récupérer la tâche ciblée
const todoToGet = todos.find((t) => t.id.toString() == URLParam);
// Rapide gestion d'erreur pour le principe
if (!todoToGet) {
throw new Drash.Exceptions.HttpException(
404,
`Tod with id ${URLParam} not found`,
);
}
this.response.body = JSON.stringify(todoToGet);
return this.response;
}
public PUT() {
const URLParam = this.request.getPathParam("id");
const todoToModify = todos.find((t) => t.id.toString() == URLParam);
if (!todoToModify) {
throw new Drash.Exceptions.HttpException(
404,
`Todo with id ${URLParam} not found`,
);
}
todoToModify.completed =
this.request.getBodyParam("completed") === true ? true : false;
this.response.body = JSON.stringify(todoToModify);
return this.response;
}
public DELETE() {
const URLParam = this.request.getPathParam("id");
const todoToDelete = todos.find((t) => t.id.toString() == URLParam);
if (!todoToDelete) {
throw new Drash.Exceptions.HttpException(
404,
`Todo with id ${URLParam} not found`,
);
}
todos = todos.filter((t) => t.id.toString() != URLParam);
this.response.body = JSON.stringify(todos);
return this.response;
}
}
|
714477796d9ecfb834ab5c76a57644243561f730
|
TypeScript
|
KosmosKey/Aiflow_Backend
|
/src/Mongo/ContactListService.service.ts
| 2.890625
| 3
|
// Importing dependencies....
import { ListDataType } from './ListDataType';
import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
// Injecting the MongoDB Modals
// This is where all the functions happens when it comes to Create Data and Get Data From MongoDB
@Injectable()
export class ContactListService {
// Constructor accepts listModal which is a Model comes from Mongoose
// Model will then have a Types of ListDataType which is an Object (name, age) and etc...
constructor(
@InjectModel('ListContact') private listModal: Model<ListDataType>,
) {}
// Creating new mongoose schema
// Accepts a createNewList createNewList
// We use createNewList argument value in order to create a mongoose schema
// We use create() function in the Resolver.ts.
async create(createNewList) {
const createdListContact = new this.listModal(createNewList);
return createdListContact.save();
}
// Getting all the lists data
// It has a promise which will be an array of ListData Object types
async getAllList(): Promise<ListDataType[]> {
return await this.listModal.find().exec();
}
// Deleting a Mongoose Schema
// It has a promise which will return an object which has been deleted
async deleteSchema(id: string): Promise<ListDataType> {
return await this.listModal.findByIdAndDelete(id);
}
}
|
9df140bec44198e4c9dc3a86b6ef401f93f09d32
|
TypeScript
|
seangomes/matchfinder
|
/src/app/shared/models/user.ts
| 2.515625
| 3
|
export class User {
uid?: string;
email: string;
password?: string;
photoUrl?: string;
username: string;
firstname?: string;
lastname?: string;
online: boolean;
clan?: string;
favweap?: string;
rank?: string
country?: string;
age?: number;
// constructor(public uid: string, public email: string, public password: string,
// public photoUrl: string, public username: string, public firstname: string,
// public lastname: string, public online: boolean, public clan: string,
// public favweap: string, public rank: string, public country: string, public age: number) {
// }
}
|
f24964d27a0da05eee540dae5359d301b0b83177
|
TypeScript
|
Grupo-E-022018-DAPP-sgonzalez-lvaquel/Grupo-E-react-frontend
|
/src/store/selectors/bets.ts
| 2.53125
| 3
|
import { IStore } from '../reducers/rootReducer';
export function getBetsByIds(state: IStore, ids: [number]) {
return ids.map(id => getBetById(state, id))
}
export function getBetById(state: IStore, id: number) {
return state.bets.byIds[id]
}
|
ccb31372f74758d4a340fb57c5d209295adb8d16
|
TypeScript
|
cocytus1223/TypeScript
|
/src/learning/datetype.ts
| 4.09375
| 4
|
// 原始类型
let bool: boolean = true
let num: number = 123
let str: string = 'abc'
// 数组
let arr1: number[] = [1, 2, 3]
let arr2: Array<number> = [1, 2, 3]
let arr3: Array<number | string> = [1, 2, 3, '4']
// 元组
let tuple: [number, string] = [0, '1']
// 函数
let Add = (x: number, y: number) => x + y
let compute: (x: number, y: number) => number
compute = (a, b) => a + b
// 对象
let obj: {x: number, y: number} = {x: 1, y: 2}
obj.x = 2
// symbol
let s1: symbol = Symbol()
let s2 = Symbol
// undefined, null
let un: undefined = undefined
let nu: null = null
// void
let noReturn = () => {}
// any
let x
// never 永远不会有返回值,死循环函数
let error = () => {
throw new Error('error')
}
let endless = () => {
while(true) {}
}
|
aa19f5512cdf4f943328d17b02c478ff8104a2e4
|
TypeScript
|
amiraElmergawy/NTI2-REPO
|
/session15/src/app/interfaces/tasks.ts
| 2.53125
| 3
|
export interface Tasks {
taskTitle: string
taskStatus: boolean
taskType: string
}
|
3e1c4f3da5ac3639407c2d3efea39b0c831a9b37
|
TypeScript
|
dhmw/dynamo-easy
|
/src/decorator/metadata/property-metadata.model.ts
| 3.0625
| 3
|
/**
* @module metadata
*/
import * as DynamoDB from 'aws-sdk/clients/dynamodb'
import { MapperForType } from '../../mapper/for-type/base.mapper'
import { Attribute } from '../../mapper/type/attribute.type'
import { ModelConstructor } from '../../model/model-constructor'
export interface TypeInfo {
type: ModelConstructor<any>
genericType?: ModelConstructor<any>
}
export interface Key {
type: DynamoDB.KeyType
}
export interface PropertyMetadata<T, R extends Attribute = Attribute> {
// this property describes a key attribute (either partition or sort) for the table
key?: Key
// name of the property on js side
name: keyof T
// name of the dynamoDB attribute, same as key by default
nameDb: string
/*
* the type will re resolved using compile time information leveraging the reflect api, due to some limitations we
* cannot differ between Object, Set, Map and custom Classes so we need an additional @Type decorator
*/
typeInfo?: TypeInfo
/*
* defines which dynamoDB type should be used for storing collection data, only L(ist) preserves order (compared to Set types)
*/
isSortedCollection?: boolean
mapper?: () => MapperForType<any, R>
mapperForSingleItem?: () => MapperForType<any, any>
// maps the index name to the key type to describe for which GSI this property describes a key attribute
keyForGSI?: Record<string, DynamoDB.KeyType>
// holds all the the index names for which this property describes the sort key attribute
sortKeyForLSI?: string[]
// index?: IModelAttributeIndex
transient?: boolean
defaultValueProvider?: () => any
}
/**
* @hidden
*/
export function hasGenericType(
propertyMetadata?: PropertyMetadata<any, any>,
): propertyMetadata is PropertyMetadata<any, any> & { typeInfo: { genericType: ModelConstructor<any> } } {
return !!(propertyMetadata && propertyMetadata.typeInfo && propertyMetadata.typeInfo.genericType)
}
/**
* @hidden
*/
export function hasType(
propertyMetadata?: PropertyMetadata<any, any>,
): propertyMetadata is PropertyMetadata<any, any> & { typeInfo: { type: ModelConstructor<any> } } {
return !!(propertyMetadata && propertyMetadata.typeInfo && propertyMetadata.typeInfo.type)
}
/**
* @hidden
*/
export function alterCollectionPropertyMetadataForSingleItem<T>(
propertyMeta?: PropertyMetadata<T> | null,
): PropertyMetadata<T> | undefined {
if (!propertyMeta) {
return
}
if (propertyMeta.mapper && propertyMeta.mapperForSingleItem) {
return { ...propertyMeta, mapper: propertyMeta.mapperForSingleItem }
}
if (propertyMeta.typeInfo && (propertyMeta.typeInfo.type === Set || propertyMeta.typeInfo.type === Array)) {
if (hasGenericType(propertyMeta)) {
return <PropertyMetadata<T>>{ ...propertyMeta, typeInfo: { type: propertyMeta.typeInfo.genericType } }
} else {
return
}
}
return { ...propertyMeta }
}
|
4ef700f8ab6fd0c4176cbf6c087aeceaeaea1174
|
TypeScript
|
DeveloperMetal/kecs-cli
|
/src/generator/generators/interfaces.ts
| 2.5625
| 3
|
import { IECSSchema } from "../../schema/types";
import { reduce } from "../utils";
export const generate = (data: IECSSchema) => `
${reduce(Object.values(data.components), (component) => `
export interface I${component.component} {
${component.component}: {${reduce(Object.entries(
component.fields || {}), ([fieldName, field]) => `
${fieldName}: ${field.type}${field.allowNull?' | null': ''}`)}
}
}`)}
export interface IClientComponents extends IComponentDefinition {${reduce(Object.values(data.components), (component) => `
${component.component}: I${component.component}`)}
}
export type IClientComponentNames = ${Object.values(data.components).reduce((p, component) => p.concat(`"${component.component}"`), [] as string[]).join(' | ')};
`;
|
04629948be74f22e8da3beb05ced5e56757f1f78
|
TypeScript
|
MSXALL/DeZog
|
/src/remotes/zsimulator/z80cpu.ts
| 2.5625
| 3
|
import {Z80Ports} from './z80ports';
import {Z80RegistersClass} from '../z80registers';
import {MemBuffer, Serializeable} from '../../misc/membuffer'
import {Settings} from '../../settings';
import * as Z80 from '../../3rdparty/z80.js/Z80.js';
import {SimulatedMemory} from './simmemory';
export class Z80Cpu implements Serializeable {
// Pointer to the Z80.js (Z80.ts) simulator
protected z80: any;
// Time until next interrupt.
protected remainingInterruptTstates: number;
// Time for interrupt in T-States
protected INTERRUPT_TIME_AS_T_STATES: number;
// For calculation of the CPU load.
// Summarizes all instruction besides HALT.
protected cpuLoadTstates: number;
// Summarizes all instruction including HALT.
public cpuWithHaltTstates: number;
// cpuLoadTstates divided by cpuTotalTstates.
public cpuLoad: number;
// The number of interrupts to calculate the average from.
protected cpuLoadRange: number;
// Counts the current number of interrupts.
protected cpuLoadRangeCounter: number;
// Used to calculate the number of t-states for a step-over or similar.
// Is reset by the remote.
public cpuTstatesCounter: number;
// Set to true if a ZX Spectrum like interrupt should be generated.
protected vsyncInterrupt: boolean;
// At the moment just a constant. CPU frequency.
public cpuFreq: number;
// Memory
public memory: SimulatedMemory;
// Ports
public ports: Z80Ports;
// Used to indicate an error in peripherals, i.e. an error in the custom javascript code.
// Will make the program break.
// undefined = no error
public error: string|undefined;
// A function that is called when a vertical interrupt is generated.
protected vertInterruptFunc: () => void;
/**
* Constructor.
* @param memory The Z80 memory.
* @param ports The Z80 ports.
* @param vertInterruptFunc An optional function that is called on a vertical interrupt.
* Can be used by teh caller to sync the display.
*/
constructor(memory: SimulatedMemory, ports: Z80Ports, vertInterruptFunc = () => {}) {
this.vertInterruptFunc = vertInterruptFunc;
this.error=undefined;
this.memory=memory;
this.ports=ports;
this.cpuFreq = Settings.launch.zsim.cpuFrequency; // e.g. 3500000.0 for 3.5MHz.
this.INTERRUPT_TIME_AS_T_STATES=0.02*this.cpuFreq; // 20ms * 3.5 MHz
this.remainingInterruptTstates=this.INTERRUPT_TIME_AS_T_STATES;
/*
IM 0: Executes an instruction that is placed on the data bus by a peripheral.
IM 1: Jumps to address &0038
IM 2: Uses an interrupt vector table, indexed by value on data bus.
*/
this.cpuTstatesCounter=0
this.cpuLoadTstates=0;
this.cpuWithHaltTstates=0;
this.cpuLoad=1.0; // Start with full load
this.cpuLoadRangeCounter=0;
this.cpuLoadRange=Settings.launch.zsim.cpuLoadInterruptRange;
this.vsyncInterrupt=Settings.launch.zsim.vsyncInterrupt;
// Initialize Z80, call constructor
const z80n_enabled=Settings.launch.zsim.Z80N;
this.z80=new (Z80.Z80 as any)({
mem_read: (address) => {return memory.read8(address);},
mem_write: (address, val) => {memory.write8(address, val);
},
io_read: (address) => {
try {
return ports.read(address);
}
catch(e) {
this.error="io_read: "+e.message;
return 0;
};
},
io_write: (address, val) => {
try {
ports.write(address, val);
}
catch (e) {
this.error="io_write: "+e.message;
};
},
z80n_enabled: z80n_enabled
});
}
/**
* Executes one instruction.
* @returns The number of t-states used for execution.
* Sets also the 'update' variable:
* true if a (vertical) interrupt happened or would have happened.
* Also if interrupts are disabled at the Z80.
* And also if 'vsyncInterrupt' is false.
* The return value is used for regularly updating the ZSimulationView.
* And this is required even if interrupts are off. Or even if
* there is only Z80 simulation without ZX Spectrum.
*/
public execute(): number {
const z80=this.z80;
// Handle instruction
const tStates = z80.run_instruction();
let accumulatedTstates = tStates;
// Statistics
if (z80.halted) {
// HALT instruction
if (z80.interruptsEnabled && this.vsyncInterrupt) {
// HALT instructions are treated specially:
// If a HALT is found the t-states to the next interrupt are calculated.
// The t-states are added and the interrupt is executed immediately.
// So only one HALT is ever executed, skipping execution of the others
// saves processing time.
accumulatedTstates = this.remainingInterruptTstates;
this.remainingInterruptTstates = 0;
}
else {
// Simply count the HALT instruction, no optimization
this.cpuLoadTstates += tStates;
}
}
else {
// No HALT: Count everything besides the HALT instruction and add to cpu-load.
this.cpuLoadTstates+=tStates;
}
// Add t-states
this.cpuTstatesCounter += accumulatedTstates;
this.cpuWithHaltTstates += accumulatedTstates;
// Interrupt
this.remainingInterruptTstates-=tStates;
if (this.remainingInterruptTstates<=0) {
// Interrupt
this.remainingInterruptTstates = this.INTERRUPT_TIME_AS_T_STATES;
// Really generate interrupt?
if (this.vsyncInterrupt) {
// Inform e.g. ZSimulationView about interrupt, for synching of the display
this.vertInterruptFunc();
// And generate
this.generateInterrupt(false, 0);
}
}
return accumulatedTstates;
}
/**
* Properties to set flags.
*/
set pc(value) {
this.z80.pc=value;
}
get pc() {return this.z80.pc;}
set sp(value) {this.z80.sp=value;}
get sp() {return this.z80.sp;}
set af(value) {
const r=this.z80.getState();
r.a=value>>>8;
r.flags=this.revConvertFlags(value&0xFF);
this.z80.setState(r);
}
set bc(value) {
const r=this.z80.getState();
r.b=value>>>8;
r.c=value&0xFF;
this.z80.setState(r);
}
set de(value) {
const r=this.z80.getState();
r.d=value>>>8;
r.e=value&0xFF;
this.z80.setState(r);
}
set hl(value) {
const r=this.z80.getState();
r.h=value>>>8;
r.l=value&0xFF;
this.z80.setState(r);
}
set ix(value) {
const r=this.z80.getState();
r.ix=value;
this.z80.setState(r);
}
set iy(value) {
const r=this.z80.getState();
r.iy=value;
this.z80.setState(r);
}
set af2(value) {
const r=this.z80.getState();
r.a_prime=value>>>8;
r.flags_prime=this.revConvertFlags(value&0xFF);
this.z80.setState(r);
}
set bc2(value) {
const r=this.z80.getState();
r.b_prime=value>>>8;
r.c_prime=value&0xFF;
this.z80.setState(r);
}
set de2(value) {
const r=this.z80.getState();
r.d_prime=value>>>8;
r.e_prime=value&0xFF;
this.z80.setState(r);
}
set hl2(value) {
const r=this.z80.getState();
r.h_prime=value>>>8;
r.l_prime=value&0xFF;
this.z80.setState(r);
}
set im(value) {
const r=this.z80.getState();
r.imode=value;
this.z80.setState(r);
}
set iff1(value) {
const r=this.z80.getState();
r.iff1=value;
this.z80.setState(r);
}
set iff2(value) {
const r=this.z80.getState();
r.iff2=value;
this.z80.setState(r);
}
set r(value) {
const r=this.z80.getState();
r.r=value;
this.z80.setState(r);
}
set i(value) {
const r=this.z80.getState();
r.i=value;
this.z80.setState(r);
}
set a(value) {
const r=this.z80.getState();
r.a=value;
this.z80.setState(r);
}
set f(value) {
const r=this.z80.getState();
r.f=this.revConvertFlags(value);
this.z80.setState(r);
}
set b(value) {
const r=this.z80.getState();
r.b=value;
this.z80.setState(r);
}
set c(value) {
const r=this.z80.getState();
r.c=value;
this.z80.setState(r);
}
set d(value) {
const r=this.z80.getState();
r.d=value;
this.z80.setState(r);
}
set e(value) {
const r=this.z80.getState();
r.e=value;
this.z80.setState(r);
}
set h(value) {
const r=this.z80.getState();
r.h=value;
this.z80.setState(r);
}
set l(value) {
const r=this.z80.getState();
r.l=value;
this.z80.setState(r);
}
set ixl(value) {
const r=this.z80.getState();
r.ix=(r.ix&0xFF00)+value;
this.z80.setState(r);
}
set ixh(value) {
const r=this.z80.getState();
r.ix=(r.ix&0xFF)+256*value;
this.z80.setState(r);
}
set iyl(value) {
const r=this.z80.getState();
r.iy=(r.iy&0xFF00)+value;
this.z80.setState(r);
}
set iyh(value) {
const r=this.z80.getState();
r.iy=(r.iy&0xFF)+256*value;
this.z80.setState(r);
}
/**
* Simulates pulsing the processor's INT (or NMI) pin.
* Is called for the ULA vertical sync and also from custom code.
* @param non_maskable - true if this is a non-maskable interrupt.
* @param data - the value to be placed on the data bus, if needed.
*/
public generateInterrupt(non_maskable: boolean, data: number) {
this.z80.interrupt(non_maskable, data);
// Measure CPU load
this.cpuLoadRangeCounter++;
if (this.cpuLoadRangeCounter>=this.cpuLoadRange) {
if (this.cpuWithHaltTstates>0) {
this.cpuLoad=this.cpuLoadTstates/this.cpuWithHaltTstates;
this.cpuLoadTstates=0;
this.cpuWithHaltTstates=0;
this.cpuLoadRangeCounter=0;
}
}
}
/**
* Converts the Z80 flags object into a number.
*/
protected convertFlags(flags: {
S: number,
Z: number,
Y: number,
H: number,
X: number,
P: number,
N: number,
C: number
}): number {
const f=128*flags.S+64*flags.Z+32*flags.Y+16*flags.H+8*flags.X+4*flags.P+2*flags.N+flags.C;
return f;
}
/**
* Returns all registers.
*/
protected getAllRegisters(): {
pc: number,
sp: number,
af: number,
bc: number,
de: number,
hl: number,
ix: number,
iy: number,
af2: number,
bc2: number,
de2: number,
hl2: number,
i: number,
r: number,
im: number,
iff1: number,
iff2: number,
} {
const r=this.z80.getState();
const flags=this.convertFlags(r.flags);
const flags2=this.convertFlags(r.flags_prime);
const regs={
pc: r.pc,
sp: r.sp,
af: r.a*256+flags,
bc: r.b*256+r.c,
de: r.d*256+r.e,
hl: r.h*256+r.l,
ix: r.ix,
iy: r.iy,
af2: r.a_prime*256+flags2,
bc2: r.b_prime*256+r.c_prime,
de2: r.d_prime*256+r.e_prime,
hl2: r.h_prime*256+r.l_prime,
i: r.i,
r: r.r,
im: r.imode,
iff1: r.iff1,
iff2: r.iff2
};
return regs;
}
/**
* Returns the register data in the Z80Registers format.
*/
public getRegisterData(): Uint16Array {
const r=this.getAllRegisters();
// Convert regs
const slots=this.memory.getSlots()||[];
const regData=Z80RegistersClass.getRegisterData(
r.pc, r.sp,
r.af, r.bc, r.de, r.hl,
r.ix, r.iy,
r.af2, r.bc2, r.de2, r.hl2,
r.i, r.r, r.im,
slots
);
return regData;
}
/**
* Returns the register, opcode and sp contents data,
*/
public getHistoryData(): Uint16Array {
// Get registers
const regData=this.getRegisterData();
// Add opcode and sp contents
const startHist=regData.length;
const histData=new Uint16Array(startHist+3);
// Copy registers
histData.set(regData);
// Store opcode (4 bytes)
const z80=this.z80;
const pc=z80.pc;
const opcodes=this.memory.getMemory32(pc);
histData[startHist]=opcodes&0xFFFF;
histData[startHist+1]=opcodes>>>16;
// Store sp contents (2 bytes)
const sp=z80.sp;
const spContents=this.memory.getMemory16(sp);
histData[startHist+2]=spContents;
// return
return histData;
}
/**
* Returns the size the serialized object would consume.
*/
public getSerializedSize(): number {
// Create a MemBuffer to calculate the size.
const memBuffer=new MemBuffer();
// Serialize object to obtain size
this.serialize(memBuffer);
// Get size
const size=memBuffer.getSize();
return size;
}
/**
* Converts the Z80 flags object into a number.
*/
protected revConvertFlags(flags: number): {
S: number,
Z: number,
Y: number,
H: number,
X: number,
P: number,
N: number,
C: number
} {
const f={
S: (flags>>>7)&0x01,
Z: (flags>>>6)&0x01,
Y: (flags>>>5)&0x01,
H: (flags>>>4)&0x01,
X: (flags>>>3)&0x01,
P: (flags>>>2)&0x01,
N: (flags>>>1)&0x01,
C: flags&0x01,
};
return f;
}
/**
* Serializes the object.
*/
public serialize(memBuffer: MemBuffer) {
// Save all registers etc.
const r=this.getAllRegisters();
// Store
memBuffer.write16(r.pc);
memBuffer.write16(r.sp);
memBuffer.write16(r.af);
memBuffer.write16(r.bc);
memBuffer.write16(r.de);
memBuffer.write16(r.hl);
memBuffer.write16(r.ix);
memBuffer.write16(r.iy);
memBuffer.write16(r.af2);
memBuffer.write16(r.bc2);
memBuffer.write16(r.de2);
memBuffer.write16(r.hl2);
// Also the 1 byte data is stored in 2 bytes for simplicity:
memBuffer.write8(r.i);
memBuffer.write8(r.r);
memBuffer.write8(r.im);
memBuffer.write8(r.iff1);
memBuffer.write8(r.iff2);
// Additional
const s=this.z80.getState();
memBuffer.write8(Number(s.halted));
memBuffer.write8(Number(s.do_delayed_di));
memBuffer.write8(Number(s.do_delayed_ei));
//memBuffer.write8(s.cycle_counter);
// Additional state
memBuffer.writeNumber(this.remainingInterruptTstates);
memBuffer.writeNumber(this.cpuTstatesCounter);
}
/**
* Deserializes the object.
*/
public deserialize(memBuffer: MemBuffer) {
// Store
let r=new Object() as any;
r.pc=memBuffer.read16();
r.sp=memBuffer.read16();
const af=memBuffer.read16();
r.a=af>>>8;
r.flags=this.revConvertFlags(af&0xFF);
const bc=memBuffer.read16();
r.b=bc>>>8;
r.c=bc&0xFF;
const de=memBuffer.read16();
r.d=de>>>8;
r.e=de&0xFF;
const hl=memBuffer.read16();
r.h=hl>>>8;
r.l=hl&0xFF;
r.ix=memBuffer.read16();
r.iy=memBuffer.read16();
const af2=memBuffer.read16();
r.a_prime=af2>>>8;
r.flags_prime=this.revConvertFlags(af2&0xFF);
const bc2=memBuffer.read16();
r.b_prime=bc2>>>8;
r.c_prime=bc2&0xFF;
const de2=memBuffer.read16();
r.d_prime=de2>>>8;
r.e_prime=de2&0xFF;
const hl2=memBuffer.read16();
r.h_prime=hl2>>>8;
r.l_prime=hl2&0xFF;
// Also the 1 byte data is stored in 2 bytes for simplicity:
r.i=memBuffer.read8();
r.r=memBuffer.read8();
r.imode=memBuffer.read8();
r.iff1=memBuffer.read8();
r.iff2=memBuffer.read8();
// Additional
r.halted=(memBuffer.read8()!=0);
r.do_delayed_di=(memBuffer.read8()!=0);
r.do_delayed_ei=(memBuffer.read8()!=0);
r.cycle_counter=0;
// Restore all registers etc.
const z80=this.z80;
z80.setState(r);
// Additional state
this.remainingInterruptTstates = memBuffer.readNumber();
this.cpuTstatesCounter = memBuffer.readNumber();
// Reset statistics
this.cpuLoadTstates=0;
this.cpuWithHaltTstates=0;
this.cpuLoad = 1.0; // Start with full load
}
}
|
fe4032d4c0269c9d9b2f6722ce8b8c718ef30122
|
TypeScript
|
KJStrand/ngl
|
/src/buffer/mapped-buffer.ts
| 3.046875
| 3
|
/**
* @file Mapped Buffer
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
import { getUintArray } from '../utils'
import { calculateCenterArray, serialArray } from '../math/array-utils'
import Buffer, { BufferParameters, BufferData } from './buffer'
export type MappingType = 'v2'|'v3'
/**
* Mapped buffer. Sends mapping attribute to the GPU and repeats data in
* others attributes. Used to render imposters.
* @interface
*/
abstract class MappedBuffer extends Buffer {
index: Uint32Array|Uint16Array
constructor (mappingType: MappingType, data: BufferData, params: Partial<BufferParameters> = {}) {
super(data, params)
this.index = getUintArray(this.indexSize, this.attributeSize)
this.makeIndex()
this.initIndex(this.index)
this.addAttributes({
'mapping': { type: mappingType, value: null }
})
this.setAttributes({ primitiveId: serialArray(this.size) })
}
abstract get mapping (): Float32Array
abstract get mappingIndices (): Uint32Array|Uint16Array
abstract get mappingIndicesSize (): number
abstract get mappingSize (): number
abstract get mappingItemSize (): number
get attributeSize () {
return this.size * this.mappingSize
}
get indexSize () {
return this.size * this.mappingIndicesSize
}
addAttributes (attributes: any) {
const nullValueAttributes: any = {}
for (const name in attributes) {
const a = attributes[ name ]
nullValueAttributes[ name ] = {
type: a.type,
value: null
}
}
super.addAttributes(nullValueAttributes)
}
getAttributeIndex (dataIndex: number) {
return dataIndex * 3 * this.mappingSize
}
setAttributes (data: any) { // TODO
if (data && !data.position && data.position1 && data.position2) {
data.position = calculateCenterArray(data.position1, data.position2)
}
const size = this.size
const mappingSize = this.mappingSize
const attributes = this.geometry.attributes as any // TODO
let a, d, itemSize, array, n, i, j
for (const name in data) {
if (name === 'index' || name === 'picking') continue
d = data[ name ]
a = attributes[ name ]
itemSize = a.itemSize
array = a.array
for (let k = 0; k < size; ++k) {
n = k * itemSize
i = n * mappingSize
for (let l = 0; l < mappingSize; ++l) {
j = i + (itemSize * l)
for (let m = 0; m < itemSize; ++m) {
array[ j + m ] = d[ n + m ]
}
}
}
a.needsUpdate = true
}
}
makeMapping () {
const size = this.size
const mapping = this.mapping
const mappingSize = this.mappingSize
const mappingItemSize = this.mappingItemSize
const attributes = this.geometry.attributes as any // TODO
const aMapping = attributes.mapping.array
for (let v = 0; v < size; v++) {
aMapping.set(mapping, v * mappingItemSize * mappingSize)
}
}
makeIndex () {
const size = this.size
const mappingSize = this.mappingSize
const mappingIndices = this.mappingIndices
const mappingIndicesSize = this.mappingIndicesSize
const index = this.index
for (let v = 0; v < size; v++) {
const ix = v * mappingIndicesSize
const it = v * mappingSize
index.set(mappingIndices, ix)
for (let s = 0; s < mappingIndicesSize; ++s) {
index[ ix + s ] += it
}
}
}
}
export default MappedBuffer
|
49f1c4dc4d6b1255d260b657036a05e4b431e0c3
|
TypeScript
|
14923523/test-cases-3d
|
/assets/cases/ui/17.sprite-atlas/TS/Test.ts
| 2.609375
| 3
|
import { _decorator, Component, Label, Sprite, EditBox, SpriteFrame, Vec3, find } from "cc";
const { ccclass, property } = _decorator;
@ccclass("Test")
export class Test extends Component {
@property({type:EditBox})
public editbox: EditBox = null!;
@property({type:SpriteFrame})
public sf: SpriteFrame = null!;
@property({type:SpriteFrame})
public sea: SpriteFrame = null!;
@property({type:SpriteFrame})
public lake: SpriteFrame = null!;
@property({type:SpriteFrame})
public mountain: SpriteFrame = null!;
private tipLabel: Label = null!;
private showLabel: Label = null!;
private _sprite: Sprite = null!;
private _label:string='替换成功';
start () {
const canvas = find('Canvas');
this.tipLabel = canvas?.getChildByName('Label-1')?.getComponent(Label)!;
this.showLabel = canvas?.getChildByName('Label-2')?.getComponent(Label)!;
this._sprite = this.node.getComponent(Sprite)!;
}
test(name:string){
this._sprite.changeSpriteFrameFromAtlas(name);
}
button(){
this.tipLabel.node.setPosition(0, 1000, 0);
}
button1(){
this.test(this.editbox.string);
if (this._sprite.spriteFrame !== null) {
this.showLabel.string = this._label + ' ' + this.editbox.string;
}
if (this._sprite.spriteAtlas === null) {
this.showLabel.string = "替换失败" + this.editbox.string;
}
if (this._sprite.spriteAtlas != null && this._sprite.spriteFrame == null) {
this.showLabel.string = "请输入正确的名字";
}
this.tipLabel.node.setPosition(0, 1000, 0);
}
button2(){
this._sprite.spriteAtlas = null;
this.showLabel.string = '清除图集';
this._label = '替换失败';
}
button3(name:string){
this.name = this.editbox.string;
if (this.name == 'tree') {
this._sprite.spriteFrame = this.sf;
this.showLabel.string = '更换图片 tree';
}
if (this.name == 'sea') {
this._sprite.spriteFrame = this.sea;
this.showLabel.string = '更换图片 sea';
}
if (this.name == 'lake') {
this._sprite.spriteFrame = this.lake;
this.showLabel.string = '更换图片 lake';
}
if (this.name == 'mountain') {
this._sprite.spriteFrame = this.mountain;
this.showLabel.string = '更换图片 mountain';
}
if (this.name != 'mountain' && this.name != 'lake' && this.name != 'sea' && this.name != 'tree') {
this.showLabel.string = '请输入正确的名字';
}
}
button4(){
this.tipLabel.node.position = new Vec3(90, 72, 0);
}
}
|
da988d8a94a5d682592909ff671494d35c33a37d
|
TypeScript
|
deepshikha02/Learn-Angular
|
/basics/src/app/directives/directives.component.ts
| 2.6875
| 3
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-directives',
templateUrl: './directives.component.html',
styleUrls: ['./directives.component.css']
})
export class DirectivesComponent implements OnInit {
constructor() { }
ngOnInit() {
}
// STRUCTURAL DIRECTIVES
/* Structural Directives help in removing/adding elements to the DOM.
There are 3 main structural Directives :
1. ngIf
2. ngSwitch
3. ngFor
ngIf and ngSwitch directives render html elements based on some condition.
ngFor renders a list of html elements.
*/
// A property can also be bound to the ngIf directive
public ngIfValue = false;
/**
* ngIf also has an else block.
*/
public ngIfCondition =false;
// ngSwitch directive
public ngSwitchColor = "pink";
// ngFor directive
public ngForArray = ["red","blue","green","yellow"];
}
|
3614ac303e841cdcada08531d14ff8eae837ffc9
|
TypeScript
|
alissonkruger/sudokuAngular
|
/src/app/services/sudoku.service.ts
| 2.8125
| 3
|
import { Injectable } from '@angular/core';
import { sudoku } from "../../assets/sudoku.js";
@Injectable({
providedIn: 'root'
})
export class SudokuService {
constructor() { }
// Gero novo jogo Sudoku
public newSudokuGame(difficulty){
var game;
if(difficulty != 0){
game = sudoku.generate(difficulty);
}
else{
game = '.................................................................................';
}
return {
'array': this.gameArrayOrder(game.split('')),
'string': game
};
}
// Testo unidade nas regras Sudoku
public ruleTests(place, unit, game){
var ret = false;
if(this.horizontalRules(place, unit, game)){
ret = true;
}
if(this.verticalRules(place, unit, game)){
ret = true;
}
if(this.frameRules(place, unit, game)){
ret = true;
}
return ret;
}
// Soluciona jogo Sudoku
public gameSolution(game){
try{
return this.gameArrayOrder(sudoku.solve(game).split(''));
}
catch{
return false;
}
}
// Converto array padrão para array de implementação nos quadros do Sudoku
private gameArrayOrder(game){
var gameOrder = [];
for (let index = 0; index < game.length; index++) {
if(game[index] == '.'){
game[index] = '';
}
}
gameOrder[0] = [];
gameOrder[0][0] = game[0];
gameOrder[0][1] = game[1];
gameOrder[0][2] = game[2];
gameOrder[0][3] = game[9];
gameOrder[0][4] = game[10];
gameOrder[0][5] = game[11];
gameOrder[0][6] = game[18];
gameOrder[0][7] = game[19];
gameOrder[0][8] = game[20];
gameOrder[1] = [];
gameOrder[1][0] = game[3];
gameOrder[1][1] = game[4];
gameOrder[1][2] = game[5];
gameOrder[1][3] = game[12];
gameOrder[1][4] = game[13];
gameOrder[1][5] = game[14];
gameOrder[1][6] = game[21];
gameOrder[1][7] = game[22];
gameOrder[1][8] = game[23];
gameOrder[2] = [];
gameOrder[2][0] = game[6];
gameOrder[2][1] = game[7];
gameOrder[2][2] = game[8];
gameOrder[2][3] = game[15];
gameOrder[2][4] = game[16];
gameOrder[2][5] = game[17];
gameOrder[2][6] = game[24];
gameOrder[2][7] = game[25];
gameOrder[2][8] = game[26];
//---
gameOrder[3] = [];
gameOrder[3][0] = game[27];
gameOrder[3][1] = game[28];
gameOrder[3][2] = game[29];
gameOrder[3][3] = game[36];
gameOrder[3][4] = game[37];
gameOrder[3][5] = game[38];
gameOrder[3][6] = game[45];
gameOrder[3][7] = game[46];
gameOrder[3][8] = game[47];
gameOrder[4] = [];
gameOrder[4][0] = game[30];
gameOrder[4][1] = game[31];
gameOrder[4][2] = game[32];
gameOrder[4][3] = game[39];
gameOrder[4][4] = game[40];
gameOrder[4][5] = game[41];
gameOrder[4][6] = game[48];
gameOrder[4][7] = game[49];
gameOrder[4][8] = game[50];
gameOrder[5] = [];
gameOrder[5][0] = game[33];
gameOrder[5][1] = game[34];
gameOrder[5][2] = game[35];
gameOrder[5][3] = game[42];
gameOrder[5][4] = game[43];
gameOrder[5][5] = game[44];
gameOrder[5][6] = game[51];
gameOrder[5][7] = game[52];
gameOrder[5][8] = game[53];
//---
gameOrder[6] = [];
gameOrder[6][0] = game[54];
gameOrder[6][1] = game[55];
gameOrder[6][2] = game[56];
gameOrder[6][3] = game[63];
gameOrder[6][4] = game[64];
gameOrder[6][5] = game[65];
gameOrder[6][6] = game[72];
gameOrder[6][7] = game[73];
gameOrder[6][8] = game[74];
gameOrder[7] = [];
gameOrder[7][0] = game[57];
gameOrder[7][1] = game[58];
gameOrder[7][2] = game[59];
gameOrder[7][3] = game[66];
gameOrder[7][4] = game[67];
gameOrder[7][5] = game[68];
gameOrder[7][6] = game[75];
gameOrder[7][7] = game[76];
gameOrder[7][8] = game[77];
gameOrder[8] = [];
gameOrder[8][0] = game[60];
gameOrder[8][1] = game[61];
gameOrder[8][2] = game[62];
gameOrder[8][3] = game[69];
gameOrder[8][4] = game[70];
gameOrder[8][5] = game[71];
gameOrder[8][6] = game[78];
gameOrder[8][7] = game[79];
gameOrder[8][8] = game[80];
return gameOrder;
}
// Teste Horizontal de regras Sudoku
private horizontalRules(place, unit, game){
var PlaceInit;
var PlaceEnd;
if(place == 0 || place == 1 || place == 2){
PlaceInit = 0;
PlaceEnd = 2;
}
if(place == 3 || place == 4 || place == 5){
PlaceInit = 3;
PlaceEnd = 5;
}
if(place == 6 || place == 7 || place == 8){
PlaceInit = 6;
PlaceEnd = 8;
}
var UnitInit;
var UnitEnd;
if(unit == 0 || unit == 1 || unit == 2){
UnitInit = 0;
UnitEnd = 2;
}
if(unit == 3 || unit == 4 || unit == 5){
UnitInit = 3;
UnitEnd = 5;
}
if(unit == 6 || unit == 7 || unit == 8){
UnitInit = 6;
UnitEnd = 8;
}
for (let placeKey = PlaceInit; placeKey <= PlaceEnd; placeKey++) {
if(place != placeKey){
for (let unitKey = UnitInit; unitKey <= UnitEnd; unitKey++) {
if(game[place][unit] == game[placeKey][unitKey]){
return true;
}
}
}
}
}
// Teste Vertical de regras Sudoku
private verticalRules(place, unit, game){
var PlaceLoop;
if(place == 0 || place == 3 || place == 6){
PlaceLoop = [0,3,6];
}
if(place == 1 || place == 4 || place == 7){
PlaceLoop = [1,4,7];
}
if(place == 2 || place == 5 || place == 8){
PlaceLoop = [2,5,8];
}
var UnitLoop;
if(unit == 0 || unit == 3 || unit == 6){
UnitLoop = [0,3,6];
}
if(unit == 1 || unit == 4 || unit == 7){
UnitLoop = [1,4,7];
}
if(unit == 2 || unit == 5 || unit == 8){
UnitLoop = [2,5,8];
}
for (let index = 0; index <= 2; index++) {
var placeKey = PlaceLoop[index];
if(place != placeKey){
for (let index2 = 0; index2 <= 2; index2++) {
var unitKey = UnitLoop[index2];
if(game[place][unit] == game[placeKey][unitKey]){
return true;
}
}
}
}
}
// Testa Quadro de regras Sudoku
private frameRules(place, unit, game){
for (let unitKey = 0; unitKey < game[place].length; unitKey++) {
if(unit != unitKey){
if(game[place][unit] == game[place][unitKey]){
return true;
}
}
}
}
}
|
99c1521fa58fedfb3092a66a9a5c8ddd3bbd078c
|
TypeScript
|
chiyuCoder/myclass
|
/func/num.ts
| 3.171875
| 3
|
export function strToInt(str:string, whenNaN:number = 0): number {
let num = parseInt(str);
if (isNaN(num)) {
return whenNaN;
}
return num;
}
export function strToNum(str:string, whenNaN: number = 0): number {
let num = parseFloat(str);
if (isNaN(num)) {
return whenNaN;
}
return num;
}
export function strToPreciseNum(str: string, precise: number = 2): string {
return parseFloat(str).toFixed(precise);
}
export function rand(min: number, max: number = 0): number {
if (min > max) {
let tmp = max;
max = min;
min = tmp;
}
return Math.floor(Math.random() * (max - min) + min);
}
|
1b0a5762b68a0880e1989dcf68e56f64046c3012
|
TypeScript
|
Zackwn/ezOrders
|
/src/@types/index.d.ts
| 2.703125
| 3
|
import { ISocketIO } from '../providers/socket/ISocketIO'
declare global {
namespace Express {
interface Request {
socketIo: ISocketIO
}
}
type Channels = 'newOrder' | 'changeOrderStatus'
type Status = 'PENDING' | 'DONE' | 'CANCELED'
/**
* @param operator SQL Comparison Operators and "LIKE" Operator, default value is "="
*/
type FindOptions<Entity> = {
where?: {
[key in keyof Entity]?: {
operator?: string = "="
value: Entity[key]
}
}
select?: Array<keyof Entity>
}
type UpdateOptions<Entity> = {
[key in keyof Entity]?: Entity[key]
}
}
|
33a35019842cca722fc5b0eb50ce5393dda63d70
|
TypeScript
|
iCShopMgr/EZ_Start_Kit_for_MakeCode_NL
|
/main.ts
| 2.515625
| 3
|
//% weight=0 color=#B3203E icon="\uf118" block="EZ Start Kit"
namespace ezstartkit {
/*
===EZ Start Kit : ButtonAB===
*/
led.enable(false)
pins.setPull(DigitalPin.P5, PinPullMode.PullNone)
pins.setPull(DigitalPin.P11, PinPullMode.PullNone)
export enum Button_read {
//% block="A"
read1 = 1,
//% block="B"
read2 = 2,
//% block="A+B"
read3 = 3
}
//% weight=12
//% blockId=ButtonAB block="Button %br push?"
export function buttonAB(br: Button_read = 1): boolean {
if (br == 1) {
if (pins.digitalReadPin(DigitalPin.P5) == 0 && pins.digitalReadPin(DigitalPin.P11) == 1) {
return true
}
else {
return false
}
}
else if (br == 2){
if (pins.digitalReadPin(DigitalPin.P5) == 1 && pins.digitalReadPin(DigitalPin.P11) == 0) {
return true
}
else {
return false
}
}
else {
if (pins.digitalReadPin(DigitalPin.P5) == 0 && pins.digitalReadPin(DigitalPin.P11) == 0) {
return true
}
else {
return false
}
}
}
/*
===EZ Start Kit : DHT11===
*/
export enum DHT_Data {
//% block="Temp"
data1 = 1,
//% block="Humid"
data2 = 2,
}
let DHT_count = 0
let DHT_value = 0
let DHT_out = 0
let DHT_Temp = 0
let DHT_Humid = 0
function Ready(): number {
pins.digitalWritePin(DigitalPin.P16, 0)
basic.pause(20)
pins.digitalWritePin(DigitalPin.P16, 1)
DHT_count = input.runningTimeMicros()
while (pins.digitalReadPin(DigitalPin.P16) == 1) {
if (input.runningTimeMicros() - DHT_count > 100) {
return 0
}
}
DHT_count = input.runningTimeMicros()
while (pins.digitalReadPin(DigitalPin.P16) == 0) {
if (input.runningTimeMicros() - DHT_count > 100) {
return 0
}
}
DHT_count = input.runningTimeMicros()
while (pins.digitalReadPin(DigitalPin.P16) == 1) {
if (input.runningTimeMicros() - DHT_count > 100) {
return 0
}
}
return 1
}
function ReadData() {
DHT_value = 0
if (Ready() == 1) {
for (let k = 0; k < 24; k++) {
DHT_out = 0
while (pins.digitalReadPin(DigitalPin.P16) == 0) {
DHT_out += 1
if (DHT_out > 100) {
break
}
}
DHT_count = input.runningTimeMicros()
DHT_out = 0
while (pins.digitalReadPin(DigitalPin.P16) == 1) {
DHT_out += 1
if (DHT_out > 100) {
break
}
}
if (input.runningTimeMicros() - DHT_count > 40) {
DHT_value = DHT_value + (1 << (23 - k));
DHT_Temp = (DHT_value & 0x0000ffff)
DHT_Humid = (DHT_value >> 16)
}
}
}
else {
pins.digitalWritePin(DigitalPin.P16, 1)
}
}
//% weight=11
//% blockId=DHT11 block="DHT11 get %dh"
export function dht11(dh: DHT_Data = 1): number {
ReadData()
basic.pause(100)
if(dh == 1) {
return DHT_Temp
}
else {
return DHT_Humid
}
}
/*
===EZ Start Kit : IR===
*/
//% weight=10
//% blockId=IR block="Enable IR"
export function enIR() :void{
pins.onPulsed(DigitalPin.P8, PulseValue.Low, function () {
readir.push(pins.pulseDuration())
})
pins.onPulsed(DigitalPin.P8, PulseValue.High, function () {
readir.push(pins.pulseDuration())
})
pins.setEvents(DigitalPin.P8, PinEventType.Pulse)
pins.setPull(DigitalPin.P8, PinPullMode.PullUp)
}
let readir: number[] = []
readir = []
let Pnumber = 0
let IRREAD: Action;
let Reading = false
control.inBackground(function () {
while(true) {
if (Reading == true) {
if (readir[0] > 30000) {
if (readir.length > 65) {
let one_data = 0
pause(10)
for (let i = 0; i < readir.length; i++) {
if (readir[one_data] > 1000 && readir[one_data] < 2000) {
Pnumber += 1
}
else {
Pnumber = 0
}
if (Pnumber == 8) {
one_data += 2
break
}
one_data += 2
}
Pnumber = 0
for (let i = 0; i < 8; i++) {
if (readir[one_data] > 1000) {
Pnumber += (1 << (7 - i))
}
one_data += 2
}
readir = []
pause(40)
if (Reading) {
IRREAD()
}
}
}
else {
readir = []
}
}
basic.pause(1)
}
})
//% weight=10
//% blockId=IR_read block="IR Read"
export function irRead(): number {
return Pnumber
}
//% weight=10
//% blockId=IR_remote block="IR Remote(NEC)" blockInlineInputs=true
export function irRemote(add: Action): void {
IRREAD = add
Reading = true
}
/*
===EZ Start Kit : LED===
*/
export enum LED_write {
//% block="Red"
write1 = 1,
//% block="Yellow"
write2 = 2,
//% block="Green"
write3 = 3
}
//% weight=9
//% blockId=LED_control block="LED %choose set velue %brightness |(0~1023)"
export function led_control(choose: LED_write = 1, brightness: number): void {
if (choose == 1) {
pins.analogWritePin(AnalogPin.P13, brightness)
}
else if (choose == 2){
pins.analogWritePin(AnalogPin.P14, brightness)
}
else {
pins.analogWritePin(AnalogPin.P15, brightness)
}
}
/*
===EZ Start Kit : OLED===
*/
let font: number[] = [];
font[0] = 0x0022d422; font[1] = 0x0022d422; font[2] = 0x0022d422; font[3] = 0x0022d422;
font[4] = 0x0022d422; font[5] = 0x0022d422; font[6] = 0x0022d422; font[7] = 0x0022d422;
font[8] = 0x0022d422; font[9] = 0x0022d422; font[10] = 0x0022d422; font[11] = 0x0022d422;
font[12] = 0x0022d422; font[13] = 0x0022d422; font[14] = 0x0022d422; font[15] = 0x0022d422;
font[16] = 0x0022d422; font[17] = 0x0022d422; font[18] = 0x0022d422; font[19] = 0x0022d422;
font[20] = 0x0022d422; font[21] = 0x0022d422; font[22] = 0x0022d422; font[23] = 0x0022d422;
font[24] = 0x0022d422; font[25] = 0x0022d422; font[26] = 0x0022d422; font[27] = 0x0022d422;
font[28] = 0x0022d422; font[29] = 0x0022d422; font[30] = 0x0022d422; font[31] = 0x0022d422;
font[32] = 0x00000000; font[33] = 0x000002e0; font[34] = 0x00018060; font[35] = 0x00afabea;
font[36] = 0x00aed6ea; font[37] = 0x01991133; font[38] = 0x010556aa; font[39] = 0x00000060;
font[40] = 0x000045c0; font[41] = 0x00003a20; font[42] = 0x00051140; font[43] = 0x00023880;
font[44] = 0x00002200; font[45] = 0x00021080; font[46] = 0x00000100; font[47] = 0x00111110;
font[48] = 0x0007462e; font[49] = 0x00087e40; font[50] = 0x000956b9; font[51] = 0x0005d629;
font[52] = 0x008fa54c; font[53] = 0x009ad6b7; font[54] = 0x008ada88; font[55] = 0x00119531;
font[56] = 0x00aad6aa; font[57] = 0x0022b6a2; font[58] = 0x00000140; font[59] = 0x00002a00;
font[60] = 0x0008a880; font[61] = 0x00052940; font[62] = 0x00022a20; font[63] = 0x0022d422;
font[64] = 0x00e4d62e; font[65] = 0x000f14be; font[66] = 0x000556bf; font[67] = 0x0008c62e;
font[68] = 0x0007463f; font[69] = 0x0008d6bf; font[70] = 0x000094bf; font[71] = 0x00cac62e;
font[72] = 0x000f909f; font[73] = 0x000047f1; font[74] = 0x0017c629; font[75] = 0x0008a89f;
font[76] = 0x0008421f; font[77] = 0x01f1105f; font[78] = 0x01f4105f; font[79] = 0x0007462e;
font[80] = 0x000114bf; font[81] = 0x000b6526; font[82] = 0x010514bf; font[83] = 0x0004d6b2;
font[84] = 0x0010fc21; font[85] = 0x0007c20f; font[86] = 0x00744107; font[87] = 0x01f4111f;
font[88] = 0x000d909b; font[89] = 0x00117041; font[90] = 0x0008ceb9; font[91] = 0x0008c7e0;
font[92] = 0x01041041; font[93] = 0x000fc620; font[94] = 0x00010440; font[95] = 0x01084210;
font[96] = 0x00000820; font[97] = 0x010f4a4c; font[98] = 0x0004529f; font[99] = 0x00094a4c;
font[100] = 0x000fd288; font[101] = 0x000956ae; font[102] = 0x000097c4; font[103] = 0x0007d6a2;
font[104] = 0x000c109f; font[105] = 0x000003a0; font[106] = 0x0006c200; font[107] = 0x0008289f;
font[108] = 0x000841e0; font[109] = 0x01e1105e; font[110] = 0x000e085e; font[111] = 0x00064a4c;
font[112] = 0x0002295e; font[113] = 0x000f2944; font[114] = 0x0001085c; font[115] = 0x00012a90;
font[116] = 0x010a51e0; font[117] = 0x010f420e; font[118] = 0x00644106; font[119] = 0x01e8221e;
font[120] = 0x00093192; font[121] = 0x00222292; font[122] = 0x00095b52; font[123] = 0x0008fc80;
font[124] = 0x000003e0; font[125] = 0x000013f1; font[126] = 0x00841080; font[127] = 0x0022d422;
let _screen = pins.createBuffer(1025);
let _buf2 = pins.createBuffer(2);
let _buf3 = pins.createBuffer(3);
let _buf4 = pins.createBuffer(4);
let fontsize = 1;
function cmd1(d: number) {
let n = d % 256;
pins.i2cWriteNumber(60, n, NumberFormat.UInt16BE);
}
function cmd2(d1: number, d2: number) {
_buf3[0] = 0;
_buf3[1] = d1;
_buf3[2] = d2;
pins.i2cWriteBuffer(60, _buf3);
}
function cmd3(d1: number, d2: number, d3: number) {
_buf4[0] = 0;
_buf4[1] = d1;
_buf4[2] = d2;
_buf4[3] = d3;
pins.i2cWriteBuffer(60, _buf4);
}
function set_pos(col: number = 0, page: number = 0) {
cmd1(0xb0 | page) // page number
let c = col * (fontsize + 1)
cmd1(0x00 | (c % 16)) // lower start column address
cmd1(0x10 | (c >> 4)) // upper start column address
}
function draw() {
set_pos()
pins.i2cWriteBuffer(60, _screen)
}
//% weight=8
//% blockId="OLED_init" block="OLED init"
export function oled_init() {
cmd1(0xAE) // SSD1306_DISPLAYOFF
cmd1(0xA4) // SSD1306_DISPLAYALLON_RESUME
cmd2(0xD5, 0xF0) // SSD1306_SETDISPLAYCLOCKDIV
cmd2(0xA8, 0x3F) // SSD1306_SETMULTIPLEX
cmd2(0xD3, 0x00) // SSD1306_SETDISPLAYOFFSET
cmd1(0 | 0x0) // line #SSD1306_SETSTARTLINE
cmd2(0x8D, 0x14) // SSD1306_CHARGEPUMP
cmd2(0x20, 0x00) // SSD1306_MEMORYMODE
cmd3(0x21, 0, 127) // SSD1306_COLUMNADDR
cmd3(0x22, 0, 63) // SSD1306_PAGEADDR
cmd1(0xa0 | 0x1) // SSD1306_SEGREMAP
cmd1(0xc8) // SSD1306_COMSCANDEC
cmd2(0xDA, 0x12) // SSD1306_SETCOMPINS
cmd2(0x81, 0xCF) // SSD1306_SETCONTRAST
cmd2(0xd9, 0xF1) // SSD1306_SETPRECHARGE
cmd2(0xDB, 0x40) // SSD1306_SETVCOMDETECT
cmd1(0xA6) // SSD1306_NORMALDISPLAY
cmd2(0xD6, 1) // zoom on
cmd1(0xAF) // SSD1306_DISPLAYON
oled_clear()
fontsize = 1
}
//% weight=7
//% blockId="OLED_show_string" block="OLED show string at x: %x |y: %y|text: %s"
export function oled_showString(x: number, y: number, s: string) {
let col = 0
let p = 0
let ind = 0
for (let n = 0; n < s.length; n++) {
p = font[s.charCodeAt(n)]
for (let i = 0; i < 5; i++) {
col = 0
for (let j = 0; j < 5; j++) {
if (p & (1 << (5 * i + j)))
col |= (1 << (j + 1))
}
ind = (x + n) * 5 * (fontsize + 1) + y * 128 + i * (fontsize + 1) + 1
_screen[ind] = col
if (fontsize)_screen[ind + 1] = col
}
}
set_pos(x * 5, y)
let ind0 = x * 5 * (fontsize + 1) + y * 128
let buf = _screen.slice(ind0, ind + 1)
buf[0] = 0x40
pins.i2cWriteBuffer(60, buf)
}
//% weight=7
//% blockId="OLED_show_number" block="OLED show a Number at x: %x |y: %y|number: %num"
export function oled_showNumber(x: number, y: number, num: number) {
oled_showString(x, y, num.toString())
}
export enum OLED_Size {
//% block="Big"
size1 = 1,
//% block="Small"
size2 = 0
}
//% weight=7
//% blockId="OLED_font_size" block="OLED font size %oled_size"
export function oled_font_size(oled_size: OLED_Size) {
fontsize = (oled_size) ? 1 : 0
cmd2(0xd6, fontsize)
}
//% weight=7
//% blockId="OLED_clera" block="OLED clear"
export function oled_clear() {
_screen.fill(0)
_screen[0] = 0x40
draw()
}
/*
===EZ Start Kit : Photoresistor===
*/
//% weight=6
//% blockId="Photoresistor" block="Photoresistor"
export function photoresistor(): number {
return pins.analogReadPin(AnalogPin.P1)
}
/*
===EZ Start Kit : Relay===
*/
export enum ON_OFF {
//% block="ON"
switch1 = 1,
//% block="OFF"
switch2 = 2
}
//% weight=5
//% blockId=Relay_control block="Relay %ON_OFF"
export function relay_control(sw: ON_OFF = 1): void {
if (sw == 1) {
pins.digitalWritePin(DigitalPin.P9, 1);
}
else {
pins.digitalWritePin(DigitalPin.P9, 0);
}
}
/*
===EZ Start Kit : Variable_Resistor===
*/
//% weight=3
//% blockId="Variable_Resistor" block="Variable Resistor"
export function variable_resistor(): number {
let reverl = Math.map(pins.analogReadPin(AnalogPin.P2), 1, 1023, 1023, 0)
return Math.round(reverl)
}
}
|
5930d83d4a6cb086a048799fcd0cb2b842e55c15
|
TypeScript
|
aishimeth2135/Toram_Grimoire
|
/src/lib/Character/Stat/StatBase.ts
| 3
| 3
|
import Grimoire from '@/shared/Grimoire'
import { isNumberString, lastChar } from '@/shared/utils/string'
import { StatTypes } from './enums'
interface StatShowData {
result: string
title: string
value: string
tail: string
}
type StatValue = number | string
class StatBase {
static sortStats = function (stats: Stat[], type = 'simple') {
if (type === 'simple') {
stats.sort((itema, itemb) => itema.base.order - itemb.base.order)
}
return stats
}
readonly baseId: string
readonly text: string
readonly hasMultiplier: boolean
readonly order: number
constantDisplayFormat: string
multiplierDisplayFormat: string
hidden: boolean
devOnly: boolean
constructor(
baseId: string,
text: string,
hasMultiplier: boolean,
order: number
) {
this.baseId = baseId
this.text = text
this.hasMultiplier = hasMultiplier
this.order = order
this.constantDisplayFormat = '$t$s$v$u'
this.multiplierDisplayFormat = '$t$s$v$u'
this.hidden = false
this.devOnly = false
}
title(type: StatTypes): string {
if (type === StatTypes.Constant) {
if (this.hasMultiplier || lastChar(this.text) === '%') {
return this.text
}
const unit = this.constantDisplayFormat.includes('$u') ? '%' : ''
return this.text + unit
}
if (type === StatTypes.Multiplier || type === StatTypes.Total) {
return this.text + '%'
}
console.warn('[StatBase.title] invalid type')
return this.text
}
show(type: StatTypes, value: StatValue): string {
const calc =
(typeof value === 'string' && isNumberString(value)) ||
typeof value === 'number'
if (typeof value !== 'number' && calc) {
value = parseFloat(value)
}
const handleFormula = (formula: string, unit: string) => {
const isPos = typeof value !== 'number' || value >= 0
const sign = isPos ? '+' : ''
formula = formula.split('::')[isPos ? 0 : 1] || formula
let res = formula
.replace('$t', this.text)
.replace('$u', unit)
.replace('$s', sign)
if (typeof value === 'number') {
res = res
.replace('$v', (calc ? Math.floor(value) : value).toString())
.replace(/\$(\d+)d/, (match, p1) =>
(value as number).toFixed(parseInt(p1, 10))
)
}
return res
}
switch (type) {
case StatTypes.Constant:
return handleFormula(
this.constantDisplayFormat,
this.hasMultiplier ? '' : '%'
)
case StatTypes.Multiplier:
return handleFormula(this.multiplierDisplayFormat, '%')
case StatTypes.Total:
return handleFormula(
Grimoire.i18n.t('common.Stat.type-total', { text: '$t$s$v$u' }),
'%'
)
}
}
getShowData(type: StatTypes, value: StatValue): StatShowData {
let title = '',
tail = ''
if (type === StatTypes.Constant) {
title = this.text
if (!this.hasMultiplier && this.constantDisplayFormat.includes('$u')) {
tail = '%'
}
} else if (type === StatTypes.Multiplier) {
title = this.text
tail = this.multiplierDisplayFormat.includes('$u') ? '%' : ''
} else if (type === StatTypes.Total) {
title = Grimoire.i18n.t('common.Stat.type-total', { text: this.text })
tail = '%'
}
return {
result: this.show(type, value),
title,
value: typeof value === 'number' ? value.toString() : value,
tail,
}
}
createStat(type: StatTypes, value: number): Stat {
if (!this.hasMultiplier && type === StatTypes.Multiplier) {
type = StatTypes.Constant
}
return new Stat(this, type, value)
}
createStatComputed(type: StatTypes, value: string): StatComputed {
if (!this.hasMultiplier && type === StatTypes.Multiplier) {
type = StatTypes.Constant
}
return new StatComputed(this, type, value)
}
checkBoolStat(type?: StatTypes) {
type = type || StatTypes.Constant
return type === StatTypes.Constant && this.constantDisplayFormat === '$t'
}
statId(type: StatTypes) {
const typeShorthand = {
[StatTypes.Constant]: '',
[StatTypes.Multiplier]: '%',
[StatTypes.Total]: '~',
}[type]
return `${this.baseId}${typeShorthand}`
}
}
abstract class StatElementBase {
readonly base: StatBase
readonly type: StatTypes
/**
* @readonly
*/
statId: string
abstract value: StatValue
abstract clone(): StatElementBase
constructor(base: StatBase, type: StatTypes) {
this.base = base
this.type = type
this.statId = this.base.statId(this.type)
}
get valueId() {
return `${this.statId}_${this.value}`
}
get isBoolStat() {
return this.base.checkBoolStat(this.type)
}
get title() {
return this.base.title(this.type)
}
get baseId() {
return this.base.baseId
}
show(value?: StatValue) {
return this.base.show(this.type, value ?? this.value)
}
showValue(value?: StatValue) {
const showData = this.base.getShowData(this.type, this.value)
value = value ?? showData.value
const pretext = typeof value !== 'number' || value >= 0 ? '+' : ''
return `${pretext}${value}${showData.tail}`
}
getShowData() {
return this.base.getShowData(this.type, this.value)
}
/**
* If baseId and type are equal, return true.
* (value do not have to be equal)
*/
equals(stat: StatElementBase): boolean {
return stat.base === this.base && stat.type === this.type
}
}
class Stat extends StatElementBase {
value: number
constructor(base: StatBase, type: StatTypes, value: number = 0) {
super(base, type)
this.value = value
}
add(value: number): number {
this.value += value
return this.value
}
clone(): Stat {
return this.base.createStat(this.type, this.value)
}
}
class StatComputed extends StatElementBase {
value: string
constructor(base: StatBase, type: StatTypes, value: string = '') {
super(base, type)
this.value = value
}
clone(): StatComputed {
return this.base.createStatComputed(this.type, this.value)
}
toStat(value: number): Stat {
return new Stat(this.base, this.type, value)
}
}
export { Stat, StatComputed, StatBase, StatElementBase }
export type { StatValue }
|
5a466dc5622dbf3662cb7031c6bd582c04c81e50
|
TypeScript
|
angular-schule/ngrx-duplicated-code
|
/projects/03-example-with-reduceReducers/src/app/store/book.reducer.ts
| 2.8125
| 3
|
import { createReducer, on } from '@ngrx/store';
import reduceReducers from 'reduce-reducers';
import { Action, ActionReducer } from '@ngrx/store';
import { SubmittableItem, Status, combineSomeReducer } from 'projects/shared/api-adapter';
import { Book } from 'projects/shared/book';
import { authorsApiAdapter, booksApiAdapter, thumbnailsApiAdapter } from './book.adapter';
import { decrementCounter, incrementCounter } from './book.actions';
export const bookFeatureKey = 'book';
export interface State {
books: SubmittableItem<Book[]>;
authors: SubmittableItem<string[]>;
thumbnails: SubmittableItem<string[]>;
counter: number;
}
export const initialState: State = {
books: booksApiAdapter.getInitialState(),
authors: authorsApiAdapter.getInitialState(),
thumbnails: thumbnailsApiAdapter.getInitialState(),
counter: 1
};
// counter: regular reducer for demonstration
export const counterReducer = createReducer(
initialState,
on(incrementCounter, state => ({
...state,
counter: state.counter + 1
})),
on(decrementCounter, state => ({
...state,
counter: state.counter - 1
})),
);
// the normal `combineReducers` always overrides not defined properties
/*
export const adapterReducer = combineReducers({
books: booksApiAdapter.getReducer(),
authors: authorsApiAdapter.getReducer(),
thumbnails: thumbnailsApiAdapter.getReducer(),
counter: s => s // this will be lost!
});
*/
// ... but our own `combineSomeReducer` will ignore the counter
export const adapterReducer = combineSomeReducer({
books: booksApiAdapter.getReducer(),
authors: authorsApiAdapter.getReducer(),
thumbnails: thumbnailsApiAdapter.getReducer()
// no counter here!
}) as unknown as ActionReducer<State, Action>; // counter is indeed missing, so we have to force the type here
export const reducer = reduceReducers(initialState, counterReducer, adapterReducer);
|
82a3f3c78189f5aa0e9bcd1aa3fc96a906813e0b
|
TypeScript
|
msheila1/ipea-web
|
/src/store/criminal/index.ts
| 2.53125
| 3
|
import { GetterTree, MutationTree, ActionTree, ActionContext } from 'vuex';
import { Criminal } from '@/models';
import { PessoasService } from '@/services';
export enum Types {
MODAL = 'list_all',
MODAL_SUCCESS = 'list_all_success',
NO_RESULT = 'no_result',
CLEAR = 'clear',
FAILURE = 'failure',
}
export interface State {
loading: boolean;
id: string;
pessoaId: string;
modal: Criminal;
error?: Error;
}
export const initialState: State = {
loading: false,
id: '',
pessoaId: '',
modal: new Criminal(),
error: undefined,
};
export const getters: GetterTree<State, any> = {
modal: (state) => state.modal,
error: (state) => state.error,
loading: (state) => state.loading,
};
export const mutations = {
[Types.MODAL](state: State, { id, pessoaId }) {
state.id = id;
state.pessoaId = pessoaId;
state.loading = true;
state.error = undefined;
},
[Types.MODAL_SUCCESS](state: State, { data }) {
state.loading = false;
state.modal = { ...data };
state.error = undefined;
},
[Types.NO_RESULT](state: State) {
state.loading = false;
state.id = '';
state.pessoaId = '';
state.modal = new Criminal();
state.error = undefined;
},
[Types.FAILURE](state: State, { error }) {
state.loading = false;
state.id = '';
state.pessoaId = '';
state.error = error;
},
} as MutationTree<State>;
export const actions = {
async findById(store: ActionContext<State, any>, { id, pessoaId }) {
try {
store.commit(Types.MODAL, { id, pessoaId });
const data = await PessoasService.findCriminalById(id, pessoaId).toPromise();
if (data) {
store.commit(Types.MODAL_SUCCESS, { data });
} else {
store.commit(Types.NO_RESULT);
}
return data;
} catch (error) {
store.commit(Types.FAILURE, { error });
}
},
async clear(store: ActionContext<State, any>): Promise<void> {
store.commit(Types.CLEAR);
},
} as ActionTree<State, any>;
export default {
namespaced: true,
state: initialState,
getters,
mutations,
actions,
};
|
b079377bff73ad5f4e9784c86ca12bfa6a46c682
|
TypeScript
|
juliandavidmr/SAT
|
/src/providers/service-sensores.ts
| 2.546875
| 3
|
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Storage } from '@ionic/storage';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import * as constants from './constants';
/*
Generated class for the Sensores provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
export interface ResponseData {
Altura: Number
Descripcion: string
Descripcion1: string
FK_idEstacion: Number
FK_idTipoSensor: Number
Icono: string
Latitud: string
Longitud: string
Maximo: Number
Minimo: Number
Nombre: string
NombreSensor: string
NombreTipoSensor: string
Referencia: string
idEstacion: Number
idSensor: Number
idTipoSensor: Number
// Atributos no propios del api
ultimo: Number
}
@Injectable()
export class ServiceSensores {
constructor(
public http: Http,
public storage: Storage
) {
console.log('Hello Sensores Provider');
}
/**
* Obtiene el ultimo dato registrado por un sensor
* @param idSensor
*/
getLast(idSensor: Number): Promise<Number> {
return new Promise((resolve, reject) => {
this.getDataSensor(idSensor).then(res => {
return resolve(res.length != 0 ? res[0].Dato : 0)
}).catch(err => resolve(0));
})
}
/**
* Obtiene los datos capturados por un sensor
* @param idSensor
*/
getDataSensor(idSensor: Number): Promise<any[]> {
return new Promise((resolve) => this.http.get(constants.URL_API_SENSORES_GET_DATA(idSensor))
.map(res => res.json())
.subscribe((data = []) => {
return resolve(data);
}))
}
/**
* Obtiene el listado de sensores
*/
getListSensores(): Promise<ResponseData[]> {
return new Promise((resolve) => this.http.get(constants.URL_API_SENSORES)
.map(res => res.json())
.subscribe((data: ResponseData[] = []) => {
this.setLocaldata(data, constants.KEY_SENSORES);
return resolve(data);
}, err => {
// console.log("Error:", err);
this.getLocaldata(constants.KEY_SENSORES).then(res => resolve(res))
}))
}
/**
* Obtiene el listado de sensores asignados a una estación
* @param id_estacion
*/
getListSensoresByEstacion(id_estacion: Number): Promise<ResponseData[]> {
return new Promise((resolve) => this.http.get(constants.URL_API_SENSORES_BY_ESTACION(id_estacion))
.map(res => res.json())
.subscribe((data: ResponseData[] = []) => {
// this.setLocaldata(data, );
return resolve(data);
}, err => {
// console.log("Error:", err);
// this.getLocaldata().then(res => resolve(res))
}))
}
/**
* Almacena los datos de sensores en local
* @param data
*/
private setLocaldata(data: ResponseData[], key: string) {
this.storage.ready().then(() => {
this.storage.set(key, data);
});
}
/**
* Obtiene los datos de sensores en local
*/
private getLocaldata(key: string) {
return this.storage.get(key);
}
}
|
242646ab0f628c4e4b9047d131bea9bcfa2397e9
|
TypeScript
|
AmrAhmedAli/moviesapp-frontend
|
/src/actions/moviesListActions.ts
| 2.640625
| 3
|
import axios from "axios";
import { Dispatch } from "redux";
import {
MoviesListDispatchTypes,
MOVIES_FAIL,
MOVIES_LOADING,
MOVIES_SUCCESS,
} from "./moviesListActionTypes";
export const GetMoviesList =
() => async (dispatch: Dispatch<MoviesListDispatchTypes>) => {
try {
dispatch({
type: MOVIES_LOADING,
});
const res = await axios.get("https://moviesbackendapp.herokuapp.com");
dispatch({
type: MOVIES_SUCCESS,
payload: res.data,
});
} catch (e) {
dispatch({
type: MOVIES_FAIL,
});
}
};
export const GetMyMoviesList =
(token?: string) => async (dispatch: Dispatch<MoviesListDispatchTypes>) => {
try {
dispatch({
type: MOVIES_LOADING,
});
if (token === null || token === "" || token === undefined) {
dispatch({
type: MOVIES_FAIL,
errMsg: "Token Authorization Fail",
});
}
axios.defaults.headers.common["Authorization"] = "Token " + token;
const res = await axios.get(
"https://moviesbackendapp.herokuapp.com/movies/"
);
dispatch({
type: MOVIES_SUCCESS,
payload: res.data,
});
} catch (e) {
dispatch({
type: MOVIES_FAIL,
errMsg: "Sorry, Cannot get Your List!",
});
}
};
|
3206d000a2bef1195511031a5463b0795639d7f6
|
TypeScript
|
qwerty-is-my-best-pass/dasreda
|
/src/useDefferedLogStrings.ts
| 3.0625
| 3
|
import {useState, useRef, useMemo} from 'react'
import { createTimerChain } from './utils';
/**
* Здесь странность в том что первый аргумент deferredStringPush - функция, а интуитивно ждешь строку
* Но т.к. это решение сложнее чем со строкой и при этом у меня нет ни контекста, ни каких-то принятых норм
* Ниже я просто оберну в немного странный декоратор
*
* Всё в кучу собрано - потому что кейс специфичный, не особо расширяемый, писать решение под целый класс задач или дробить не вижу смысла
* Если бы был контекст - возможно сделал бы иначе
*/
type deferredStringPush = (stringGenerator: () => string, time: number) => void
type deferredStringPushWOCallback = (string: string, time: number) => void
type useDefferedLogStringsInterface = [Array<string>, deferredStringPush, ()=>void]
export default function useDefferedLogStrings():useDefferedLogStringsInterface{
const [loggerStrings, setLoggerStrings] = useState<string[]>([])
const [timerChainPush, stopChain] = useMemo(createTimerChain,[])
const mutableLoggerStrings = useRef<string[]>([]).current
function addString(string: string):void {
mutableLoggerStrings.push(string)
setLoggerStrings([...mutableLoggerStrings])
}
function deferredStringPush(stringGenerator: () => string, time: number): void{
function callback(): void{
addString(stringGenerator())
}
timerChainPush(callback, time)
}
function reset(): void{
stopChain()
setLoggerStrings([])
mutableLoggerStrings.splice(0, mutableLoggerStrings.length)
}
return [loggerStrings, deferredStringPush, reset]
}
//вот он, мой декоратор
export function useDefferedLogStringsWOCallback():[Array<string>, deferredStringPushWOCallback, ()=>void]{
const [loggerStrings, deferredStringPush, reset] = useDefferedLogStrings()
function deferredStringPushWOCallback (string: string, time: number): void {
const stringGenerator = () => (string)
deferredStringPush(stringGenerator, time)
}
return [loggerStrings, deferredStringPushWOCallback, reset]
}
|
01cf631dbbb74739400b1eb7ad331385a1d8d7e1
|
TypeScript
|
danielrpg/third-cass-typescript
|
/app5.ts
| 3.578125
| 4
|
class Employee {
public empName: string;
protected empCode: number;
constructor(name: string, code: number) {
this.empName = name;
this.empCode = code;
}
}
class SalesEmployee extends Employee {
private address: string;
constructor(name: string, code: number, address: string) {
super(name, code);
this.address = address;
}
getFullInfo(): string {
return `Name: ${this.empName} - Code: ${this.empCode} - ${this.address}`;
}
}
let salesEmp = new SalesEmployee('Jhon Due', 123456, 'Calle Achazo!!');
let fullInfo = salesEmp.getFullInfo();
console.log(fullInfo);
|
ee098b55fd41a92ff1f9c60b319aee119e6fdc8a
|
TypeScript
|
manuelroemer/stumatch-backend
|
/src/middlewares/validateRequestBody.ts
| 2.9375
| 3
|
import { RequestHandler } from 'express';
import { BaseSchema, ValidationError } from 'yup';
import { BadRequestError } from '../dtos/apiErrors';
import { asyncRequestHandler } from '../utils/asyncRequestHandler';
const baseValidationErrorMessage = `Validation failed. The request body had an invalid format.`;
/**
* A middleware for validating request bodys using the `yup` library.
* On failed validation, responds with a Bad Request error composed of the validation errors.
* @param schema The `yup` schema instance to be used for validation.‚
*/
export function validateRequestBody(schema: BaseSchema): RequestHandler {
return asyncRequestHandler(async (req, _res, next) => {
try {
await schema.validate(req.body, { abortEarly: false });
req.body = schema.cast(req.body, { stripUnknown: true });
next();
} catch (e) {
if (e instanceof ValidationError) {
throw new BadRequestError(baseValidationErrorMessage + ` Errors: ${formatErrorsForMessage(e.errors)}`);
} else {
throw new BadRequestError(baseValidationErrorMessage);
}
}
});
}
function formatErrorsForMessage(errors: Array<string>) {
const errorsWithDots = errors.map((e) => (e.endsWith('.') ? e : e + '.'));
return errorsWithDots.join(' ');
}
|
0d90de2f0deaec6bf8575bdd383c1f78c6750bf8
|
TypeScript
|
Ahornzweig/EIA2
|
/A3/A3.ts
| 2.75
| 3
|
/*Aufgabe: Aufgabe 3
Name: Sarah Lnnqvist
Matrikel: 259116
Datum: 10.11.2018
Hiermit versichere ich, dass ich diesen Code selbst geschrieben habe. Er wurde nicht kopiert und auch nicht diktiert.
*/
namespace A3 {
document.addEventListener("DOMContentLoaded", (uno));
function instalListener(): void {
document.getElementById("Nachzieh").addEventListener("click", clickDraw);
document.addEventListener("keydown", spaceDraw);
let button: HTMLButtonElement = <HTMLButtonElement>document.getElementById("button");
button.addEventListener("click", clickSort);
document.getElementById("Hand").addEventListener("click", placeOnPile);
}
instalListener();
let hand: string[] = [];
let pile: string[] = [];
let allCards: string[] = ["r0", "r1", "r1", "r2", "r2", "r3", "r3", "r4", "r4", "r5", "r5", "r6", "r6", "r7", "r7", "r8", "r8", "r9", "r9", "rR", "rR", "rA", "rA", "r+2", "r+2",
"g0", "g1", "g1", "g2", "g2", "g3", "g3", "g4", "g4", "g5", "g5", "g6", "g6", "g7", "g7", "g8", "g8", "g9", "g9", "gR", "gR", "gA", "gA", "g+2", "g+2",
"b0", "b1", "b1", "b2", "b2", "b3", "b3", "b4", "b4", "b5", "b5", "b6", "b6", "b7", "b7", "b8", "b8", "b9", "b9", "bR", "bR", "bA", "bA", "b+2", "b+2",
"y0", "y1", "y1", "y2", "y2", "y3", "y3", "y4", "y4", "y5", "y5", "y6", "y6", "y7", "y7", "y8", "y8", "y9", "y9", "yR", "yR", "yA", "yA", "y+2", "y+2",
"z+4", "z+4", "z+4", "z+4", "zWahl", "zWahl", "zWahl", "zWahl"];
//math.random
function getRandom(_maxNum: number): number {
return Math.floor(Math.random() * Math.floor(_maxNum));
}
function uno(): void {
let handCards: number = parseInt(prompt("Wie viele Karten willst du? (max 10)"));
if (handCards > 10) {
handCards = 10;
}
for (let i: number = 0; i < handCards; i++) {
let maxNumber: number = allCards.length;
let randomNum: number = getRandom(maxNumber);
let card: string = allCards.splice(randomNum, 1)[0];
hand.push(card);
}
createCards(hand);
}
function createCards(_values: string[]): void {
for (let i: number = 0; i < _values.length; i++) {
let color: string = _values[i].substr(0, 1);
if (color == "r") {
color = "#ff0000";
}
if (color == "g") {
color = "#00ff00";
}
if (color == "b") {
color = "#0000ff";
}
if (color == "y") {
color = "#ffff00";
}
if (color == "z") {
color = "#000000";
}
let value: string = _values[i].substr(1);
let div: HTMLDivElement = document.createElement("div");
document.getElementById("Hand").appendChild(div);
div.setAttribute("class", "inHand");
div.setAttribute("id", "a" + i);
document.getElementById("a" + i).innerHTML += value;
let s: CSSStyleDeclaration = div.style;
s.backgroundColor = color;
if (color == "#000000" || color == "#0000ff") {
s.color = "white";
}
}
}
//Nachziehen
function draw(_cards: number): void {
if (allCards.length > 0) {
for (let i: number = 0; i < _cards; i++) {
let maxNumber: number = allCards.length;
let randomNum: number = getRandom(maxNumber);
let card: string = allCards.splice(randomNum, 1)[0];
hand.push(card);
}
}
}
function clickDraw(): void {
draw(1);
setupHand();
createCards(hand);
instalListener();
}
function spaceDraw(_event: KeyboardEvent): void {
let keyCode: number = _event.keyCode;
if (keyCode == 32) {
clickDraw();
}
}
//Sortieren
function clickSort(): void {
hand.sort();
setupHand();
createCards(hand);
instalListener();
}
//Ablegen
function placeOnPile(_event: Event): void {
console.log(_event);
let handCards: HTMLElement = document.getElementById("Hand");
let domCard: HTMLElement = <HTMLElement>_event.target;
if (domCard != handCards) {
let index: number;
let domAttribute: string = domCard.getAttribute("id");
domAttribute = domAttribute.substr(1);
index = parseInt(domAttribute);
let card: string = hand.splice(index, 1)[0];
pile.push(card);
setupHand();
createCards(hand);
setupPile();
createPile(pile);
instalListener();
}
}
function createPile(_values: string[]): void {
for (let i: number = 0; i < _values.length; i++) {
let color: string = _values[i].substr(0, 1);
if (color == "r") {
color = "#ff0000";
}
if (color == "g") {
color = "#00ff00";
}
if (color == "b") {
color = "#0000ff";
}
if (color == "y") {
color = "#ffff00";
}
if (color == "z") {
color = "#000000";
}
let value: string = _values[i].substr(1);
let div: HTMLDivElement = document.createElement("div");
document.getElementById("Ablage").appendChild(div);
div.setAttribute("class", "onPile");
div.setAttribute("id", "b" + i);
document.getElementById("b" + i).innerHTML += value;
let s: CSSStyleDeclaration = div.style;
s.backgroundColor = color;
s.zIndex = "0" + i;
if (color == "#000000" || color == "#0000ff") {
s.color = "white";
}
}
}
//hand leeren
function setupHand(): void {
let node: HTMLElement = document.getElementById("Hand");
node.innerHTML = "Hand";
}
//ablage leeren
function setupPile(): void {
let node: HTMLElement = document.getElementById("Ablage");
node.innerHTML = "Ablage";
}
}
|
53e18367bbf6d64d19ced883cb813de265172dda
|
TypeScript
|
mrvillage/rift-boltz
|
/src/services/prices.ts
| 2.59375
| 3
|
import { Request, Response } from "express";
import supabase from "../supabase";
type Trade = {
date: string;
nation_id: number;
amount: number;
price: number;
total_value: number;
};
type Resource = {
avg_price: number;
market_index: string;
highest_buy: Trade;
lowest_buy: Trade;
};
interface Price {
[key: string]: {
datetime: string;
market_index: string;
resource: Resource;
credit: Resource;
coal: Resource;
oil: Resource;
uranium: Resource;
lead: Resource;
iron: Resource;
bauxite: Resource;
gasoline: Resource;
munitions: Resource;
steel: Resource;
aluminum: Resource;
food: Resource;
};
}
const prices = async (req: Request, res: Response): Promise<void> => {
try {
const { data, error } = await supabase
.from<Price>("prices")
.select()
.order("datetime", { ascending: false })
.limit(1);
if (error) {
console.error(error.toString());
throw Error("500");
}
if (data) {
const keys = Object.keys(data[0]);
const final: Price = { ...data[0] };
delete keys[0];
for (const key of keys) {
if (!key) {
continue;
}
// @ts-ignore
const res = JSON.parse(data[0][key]);
final[key] = {
// @ts-ignore
avg_price: Number(res.avgprice),
highest_buy: {
date: res.highestbuy.date,
nation_id: Number(res.highestbuy.nationid),
amount: Number(res.highestbuy.amount),
price: Number(res.highestbuy.price),
total_value: Number(res.highestbuy.totalvalue),
},
lowest_buy: {
date: res.lowestbuy.date,
nation_id: Number(res.lowestbuy.nationid),
amount: Number(res.lowestbuy.amount),
price: Number(res.lowestbuy.price),
total_value: Number(res.lowestbuy.totalvalue),
},
};
}
// @ts-ignore
final.market_index = Number(
// @ts-ignore
JSON.parse(data[0].credit).marketindex.replace(",", "")
);
res.status(200).json({ success: true, data: final });
return;
}
throw Error("500");
} catch (error) {
res.status(500).json({ success: false, error: "Internal Server Error" });
throw error;
}
};
export default prices;
|
20b798ed914b9826f4c754b23af12ffb383e5e73
|
TypeScript
|
d-theo/Grulirogue2
|
/src/game/utils/matrix.ts
| 3.171875
| 3
|
import * as _ from 'lodash';
export function matrixMap<T,U>(c: T[][], f:(x: T) => U): U[][] {
const res: U[][] = [];
for (const i of c) {
const line = [];
for (const el of i) {
line.push(f(el));
}
res.push(line)
}
return res;
}
export function matrixForEach<T>(c: T[][], f:(x: T) => void): void {
for (const i of c) {
for (const el of i) {
f(el);
}
}
}
export function matrixFilter<T>(c: T[][], f:(x: T) => boolean): T[] {
const res : T[] = [];
for (const i of c) {
for (const el of i) {
if (f(el)) {
res.push(el);
}
}
}
return res;
}
export function matrixFlatten<T>(c: T[][]): T[] {
const res = [];
for (let x = 0; x < c.length; x++) {
for (let y = 0; y < c[0].length ; y++) {
res.push(c[y][x]);
}
}
return res;
}
|
2fb3dc26f9217ae017b0e31ac0122d5483dec1cb
|
TypeScript
|
Khongchai/lineman-wongnai-coding-challenges
|
/web/src/utils/removeDuplicatesFromArray.ts
| 3.046875
| 3
|
export default function removeDuplicatesFromArray(array: any[]): any[] {
const filteredArray = [];
const hashCheck = [];
for (let i = 0, length = array.length; i < length; i++) {
const indexedItem = hashCheck[array[i]];
if (!indexedItem) {
hashCheck[array[i]] = true;
filteredArray.push(array[i]);
}
}
return filteredArray;
}
|
b47334eb4662339e3e87001e41da5a75caab8410
|
TypeScript
|
qfl1ck32/bluelibs
|
/packages/x/src/models/defs.ts
| 3.0625
| 3
|
export enum ModelRaceEnum {
GRAPHQL_TYPE = "graphql-type",
CLASSLIKE = "class-like",
INTERFACE = "interface",
GRAPHQL_INPUT = "graphql-input",
}
export enum GenericFieldTypeEnum {
STRING = "string",
BOOLEAN = "boolean",
FLOAT = "float",
INT = "integer",
DATE = "date",
OBJECT = "object",
ID = "id",
MODEL = "model",
ENUM = "enum",
}
export interface IFieldBaseSignature {
type: GenericFieldTypeEnum | string;
isOptional?: boolean;
/**
* This states whether the field is an array or not
*/
isMany?: boolean;
}
export interface IGenericFieldSubModel {
/**
* How is the name called?
* @example UserProfile
*/
name: string;
fields?: IGenericField[];
/**
* "embed" means that it starts defining the model directly in the superclass
* "outside" means that it's outside the model, it can be in another file, package, or locally etc.
*/
storage: "embed" | "outside";
/**
* This represents whether the model is situated in the same file. Most of the times it isn't. If the model isn't local, fields can be optional.
*/
local?: boolean;
/**
* If the type is model, the name represents the model name, modelReferenceBundle means a different bundle
* The models get imported from collections
* @example DocumentsBundle
*/
referenceBundle?: string;
/**
* This is for when the import is done absolutely import { Model }
* @example "@root/types"
* @example "@bluelibs/security-bundle"
*/
absoluteImport?: string;
/**
* When dealing with inputs, we treat "enums" as external models. However,
* this can break validation, because for external models we don't do this.
* By specifying this as true, we say: It's an external model, but perform enum-like validation on it.
*/
isEnumAlias?: boolean;
/**
* This refers to when you have a specific type of model that is an interface
*/
isInterface?: boolean;
}
export type EnumConfigType = {
/**
* The id which identifies it in the code, prefer capitalisation: IN_PROGRESS
*/
id: string;
/**
* The value, if left empty it will default to the id
*/
value?: string;
/**
* How is this presented to the client, sometimes the label can be different from id and value. If missing it will default to the value.
*/
label?: string;
/**
* Describe the comment of the enum
*/
description?: string;
};
export interface IGenericField extends IFieldBaseSignature {
name: string;
/**
* Information about what this field does
*/
description?: string;
/**
* The default value of this field. This should be JSON-compatible. If it relates an `enum` it should be the `enum` identifier.
*/
defaultValue?: any;
/**
* Whether to render in typescript/graphql
*/
ignoreTypeScript?: boolean;
ignoreGraphQL?: boolean;
enumValues?: EnumConfigType[];
/**
* When type is unknown or model, we generate the model.
*/
model?: IGenericFieldSubModel;
/**
* If left undefined, it will behave based on model it's in
* If it is `false` and the model has yup validation, it won't validate it
*/
yupValidation?: boolean;
}
export type EnumConfigExtractResult = {
className: string;
elements: EnumConfigType[];
importFrom: string;
};
|
3b7f9346fa1355ebdac6e3af2e0d3077858201d9
|
TypeScript
|
HealthML/StyleGAN2-Hypotheses-Explorer
|
/client/src/logic/actions/switchImage.ts
| 2.6875
| 3
|
// switch image
// - style view
// -> nothing (only local update)
// - result view
// -> generate all styles + ratings new
import { displayedStyles, SpriteMapImage } from "../stores/displayed";
import { activeGenerator } from "../stores/generator";
import { selectedImage } from "../stores/selectedImage";
import { copyStyle } from "../tools/copyStyle";
import { Action } from "./action";
export class SwitchImageAction extends Action<[SpriteMapImage]> {
private makeImageStyleDisplayable(image: SpriteMapImage) {
const generator = activeGenerator.get();
const styles = displayedStyles.get();
const imageStyle = image.style.style.styleArray;
if (!generator) {
throw new Error("No generator selected");
} else if (!imageStyle) {
throw new Error("Image has invalid or non existing style");
} else {
let changes: boolean = false;
for (let layer = 0; layer < generator.computedLayerCount; layer++) {
const layerStyles = styles[layer];
const layerImageStyle = imageStyle[layer];
const style1Index = layerStyles.findIndex(
(style) => style.id === layerImageStyle.style1
);
const style2Index = layerStyles.findIndex(
(style) => style.id === layerImageStyle.style2
);
if (style1Index === -1 || style1Index === style2Index) {
throw new Error("Image uses invalid style");
} else {
if (style2Index >= 0) {
let upperIndex = Math.max(style1Index, style2Index);
let lowerIndex = Math.min(style1Index, style2Index);
if (upperIndex - lowerIndex > 1) {
const [movingStyle] = layerStyles.splice(upperIndex, 1);
layerStyles.splice(lowerIndex + 1, 0, movingStyle);
changes = true;
}
}
}
}
if (changes) {
displayedStyles.set(styles);
}
}
}
protected async beforeCollect(image: SpriteMapImage) {
this.makeImageStyleDisplayable(image);
selectedImage.set(image);
}
protected async collectChangesResultView(
image: SpriteMapImage
): ReturnType<Action["collectChangesResultView"]> {
const generator = activeGenerator.get();
const styles = displayedStyles.get();
if (!generator) {
throw new Error("No generator selected");
} else if (!styles) {
throw new Error("No styles shown");
} else {
const imageStyle = image.style;
const changes = await this.collectChangesStyleView();
for (let layer = 0; layer < generator.computedLayerCount; layer++) {
for (const shownStyle of styles[layer]) {
shownStyle.style = copyStyle(imageStyle);
shownStyle.style.style.styleArray![layer] = {
style1: shownStyle.id,
};
changes.images.push(shownStyle);
changes.ratings.push(shownStyle);
}
}
return changes;
}
}
protected async collectChangesStyleView(): ReturnType<
Action["collectChangesStyleView"]
> {
return {
images: [],
ratings: [],
};
}
}
|
3073db62c4f4d29a8f499315625fec799f4bdd74
|
TypeScript
|
Jesus/rc-coffee-chats
|
/src/crons/matchify/__tests__/create-suitor-acceptor-pool.test.ts
| 2.84375
| 3
|
import { createSuitorAcceptorPool } from '../create-suitor-acceptor-pool';
describe('createSuitorAcceptorPool(): ', () => {
/**
* case 1:
* given even pool --> should not be a fallback person
*
* case 2:
* given odd pool --> should be a fallback person
*
* case 3:
* each suitor's priorities should include every person in the acceptor pool
* each acceptor's priority should include every person in the suitor pool
*/
/////////////////////
// EVEN # of Matches
////////////////////
it('should not return a fallback person for even # of users to match', () => {
const usersToMatch = [
{ email: 'allison', prevMatches: [] },
{ email: 'bob', prevMatches: [] },
{ email: 'chris', prevMatches: [] },
{ email: 'dan', prevMatches: [] }
];
const fallBackUser = {
email: 'fallback',
prevMatches: []
};
const { suitors, acceptors, fallBackMatch } = createSuitorAcceptorPool(
// @ts-ignore
usersToMatch,
fallBackUser
);
expect(suitors.size).toBe(Math.floor(usersToMatch.length / 2));
expect(acceptors.size).toBe(Math.floor(usersToMatch.length / 2));
expect(fallBackMatch).toBeNull();
});
/////////////////////
// ODD # of Matches
////////////////////
it('should return a fallback person for odd # of users to match', () => {
const usersToMatch = [
{ email: 'allison', prevMatches: [] },
{ email: 'bob', prevMatches: [] },
{ email: 'chris', prevMatches: [] }
];
const fallBackUser = {
email: 'fallback',
prevMatches: []
};
const { suitors, acceptors, fallBackMatch } = createSuitorAcceptorPool(
// @ts-ignore
usersToMatch,
fallBackUser
);
expect(suitors.size).toBe(Math.floor(usersToMatch.length / 2));
expect(acceptors.size).toBe(Math.floor(usersToMatch.length / 2));
expect(fallBackMatch).not.toBeNull();
});
it('should include a priority list for each suitor that includes users from acceptor pool', () => {
const usersToMatch = [
{ email: 'allison', prevMatches: [] },
{ email: 'bob', prevMatches: [] },
{ email: 'chris', prevMatches: [] },
{ email: 'dan', prevMatches: [] }
];
const fallBackUser = {
email: 'fallback',
prevMatches: []
};
const { suitors, acceptors, fallBackMatch } = createSuitorAcceptorPool(
// @ts-ignore
usersToMatch,
fallBackUser
);
// TEST: check that each priority list for suitor, includes everyone from acceptor map
suitors.forEach(suitor => {
expect(suitor.priority.length).toBe(acceptors.size);
// === DEBUGGING ===
// console.log('Suitor:', suitor.data.email);
// console.log(JSON.stringify(suitor.priority));
suitor.priority.forEach(prefAcceptor => {
expect(acceptors.has(prefAcceptor)).toBe(true);
});
});
// TEST: check that each priority list for acceptor, includes everyone from suitor map
acceptors.forEach(acceptor => {
expect(acceptor.priority.length).toBe(suitors.size);
// === DEBUGGING ===
// console.log('Acceptor:', acceptor.data.email);
// console.log(JSON.stringify(acceptor.priority));
acceptor.priority.forEach(prefSuitor => {
expect(suitors.has(prefSuitor)).toBe(true);
});
});
});
xit('should priorities users that one has not met with yet', () => {});
});
|
c85f2e59803ae4a3226af76fee66bb98d594c8a4
|
TypeScript
|
prynix/vscode-pxplus
|
/src/features/pxplusGlobals.ts
| 2.625
| 3
|
/* --------------------------------------------------------------------------------------------
* Copyright (c) Rick Mathers. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
export interface IParameter{
parameter: string;
description?: string;
}
export interface ISignature{
signature: string;
description?: string;
parameters: Array<IParameter>
}
export interface IEntry {
description?: string;
signatures?: Array<ISignature>;
}
export interface IEntries { [name: string]: IEntry; }
export const globalvariables: IEntries = {
$this: {
description: 'Refers to the current object',
},
};
export const compiletimeconstants: IEntries = {
TRUE: {
},
FALSE: {
},
NULL: {
},
};
export const keywords: IEntries = {
SETESC:{
description:"\n 1. Subroutine Interrupt-Handler: SETESC stmtref " +
"\n 1. Subprogram Interrupt-Handler: SETESC prog_name$" +
"\n 1. Interrupt Process On/Off: SETESC {ON | OFF}" +
"\n 1. Enable/Disable for Range: SETESC {DISABLE | ENABLE}" +
"\n 1. Return Current Program: SETESC READ x$" +
"\n **where**" +
"\n *prog_name$* Name of generic interrupt-handling program. Define it once per session." +
"\n *stmtref* Program line number or statement label to which to transfer control." +
"\n *x$* Name of the current SETESC program."
}
}
|
a1e25480bd279a6b75a6b9a34d4993f402ec1329
|
TypeScript
|
green-fox-academy/JialinWang1JS
|
/week-02/day-03/BinarySearch.ts
| 4.09375
| 4
|
let array: number[] = [1, 45, 6, 12, 13, 11, 25, 98, 778, 612450, 2674, 32165, 564, 65, 865]
// 1 6 45 12
function BubbleSort(array): number[] {
for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length; j++) {
if (array[i] > array[j]) {
let temp = array[i]
array[i] = array[j]
array[j] = temp
}
}
}
return array
}
function BinarySearchRecursion(array: number[], value: number): number {
let middleNum = Math.floor((array.length) / 2)
console.log(array, middleNum)
if (array[middleNum] === value) return array[middleNum]
if (array[middleNum] > value) return BinarySearchRecursion(array.slice(0, middleNum - 1), value)
if (array[middleNum] < value) return BinarySearchRecursion(array.slice(middleNum - 1, array.length), value)
}
console.log(BubbleSort(array))
console.log(BinarySearchRecursion(BubbleSort(array), 32165))
function BinarySearchIterate(array: number[], value: number): number {
while (array.length) {
let middleNum = Math.floor((array.length) / 2)
console.log(array, middleNum)
if (array[middleNum] === value) return array[middleNum]
if (array[middleNum] > value) array = array.slice(0, middleNum - 1)
else if (array[middleNum] < value) array = array.slice(middleNum + 1, array.length)
}
return -1
}
BubbleSort(array)
console.log(array)
console.log(BinarySearchIterate(BubbleSort(array), 321651))
|
3af6881f8ff8eefe02bb462190c2d59048000360
|
TypeScript
|
Divan5841/widget
|
/src/utils/helpers.ts
| 2.59375
| 3
|
import moment from "moment";
import 'moment/locale/ru'
export const setupMoment = () => {
moment.locale('ru')
}
export const getRangeArray = (start: number, end: number): number[] =>
Array(end - start + 1)
.fill(0)
.map((_, idx) => start + idx)
export const isEmpty = (arr: any[]) => arr.length === 0
|
82bf775fe3fddd568f55b353c6b20e48f818da7a
|
TypeScript
|
broerjuang/umbrella
|
/packages/vectors/src/internal/templates.ts
| 2.953125
| 3
|
import type { Fn, FnU2 } from "@thi.ng/api";
import type { Template } from "../api";
type HOFTpl = Fn<string, Template>;
type HOFTpl2 = FnU2<string, Template>;
/** @internal */
// prettier-ignore
export const MATH: HOFTpl = (op) => ([o, a, b]) => `${o}=${a}${op}${b};`;
/** @internal */
// prettier-ignore
export const MATH_N: HOFTpl = (op) => ([o, a]) => `${o}=${a}${op}n;`;
/** @internal */
// prettier-ignore
export const MATH2: HOFTpl2 = (op1, op2) => ([o, a, b, c]) => `${o}=(${a}${op1}${b})${op2}${c};`;
/** @internal */
// prettier-ignore
export const MATH2_N: HOFTpl2 = (op1, op2) => ([o, a, b]) => `${o}=(${a}${op1}${b})${op2}n;`;
/** @internal */
// prettier-ignore
export const MATH2A_N: HOFTpl2 = (op1, op2) => ([o, a, b]) => `${o}=(${a}${op1}n)${op2}${b};`;
/** @internal */
// prettier-ignore
export const SIGNED: HOFTpl = (op) => ([o, a, b]) => `${o}=(${a}${op}${b})|0;`;
/** @internal */
// prettier-ignore
export const UNSIGNED: HOFTpl = (op) => ([o, a, b]) => `${o}=(${a}${op}${b})>>>0;`;
/** @internal */
// prettier-ignore
export const SIGNED_N: HOFTpl = (op) => ([o, a]) => `${o}=(${a}${op}n)|0;`;
/** @internal */
// prettier-ignore
export const UNSIGNED_N: HOFTpl = (op) => ([o, a]) => `${o}=(${a}${op}n)>>>0;`;
/** @internal */
// prettier-ignore
export const FN = (op="op"): Template => ([o, a]) => `${o}=${op}(${a});`;
/** @internal */
// prettier-ignore
export const FN2 = (op="op"): Template => ([o, a, b]) => `${o}=${op}(${a},${b});`;
/** @internal */
// prettier-ignore
export const FN3 = (op="op"): Template => ([o, a, b, c]) => `${o}=${op}(${a},${b},${c});`;
/** @internal */
// prettier-ignore
export const FN5 = (op = "op"): Template => ([o, a, b, c, d, e]) => `${o}=${op}(${a},${b},${c},${d},${e});`;
/** @internal */
// prettier-ignore
export const FN_N = (op="op"): Template => ([o, a]) => `${o}=${op}(${a},n);`;
/** @internal */
export const DOT: Template = ([a, b]) => `${a}*${b}`;
/** @internal */
export const DOT_G: Template = ([a, b]) => `s+=${a}*${b};`;
/** @internal */
export const SET: Template = ([o, a]) => `${o}=${a};`;
/** @internal */
export const SET_N: Template = ([a]) => `${a}=n;`;
/** @internal */
export const MIX: Template = ([o, a, b, c]) => `${o}=${a}+(${b}-${a})*${c};`;
/** @internal */
export const MIX_N: Template = ([o, a, b]) => `${o}=${a}+(${b}-${a})*n;`;
|
2752b551d706c4a16299e9f9b948db30114ac9e0
|
TypeScript
|
andersonmiyahira/SOVARRB
|
/src/APP/src/app/telas-gerais/visualizar-arquivo/models/log-arquivo.ts
| 2.796875
| 3
|
export class LogArquivoResponse {
idArquivo: number;
nomeArquivo: string;
resultado: Array<LogArquivo>;
headerSucesso: Array<LogArquivo>;
headerErro: Array<LogArquivo>;
detalheSucesso: Array<LogArquivo>;
detalheErro: Array<LogArquivo>;
trailerSucesso: Array<LogArquivo>
trailerErro: Array<LogArquivo>;
}
export class LogArquivo {
tipo: number;
mensagem: string;
ehValido: boolean;
}
export class ResultadoProcessadoResponse {
resultado: Array<LogArquivo>;
get headerSucesso(): Array<LogArquivo>{
if(this.resultado == null) return new Array<LogArquivo>();
return this.resultado.filter(_ => _.tipo == 1 && _.ehValido);
}
get headerErro(): Array<LogArquivo>{
if(this.resultado == null) return new Array<LogArquivo>();
return this.resultado.filter(_ => _.tipo == 1 && !_.ehValido);
}
get detalheSucesso(): Array<LogArquivo>{
if(this.resultado == null) return new Array<LogArquivo>();
return this.resultado.filter(_ => _.tipo == 2 && _.ehValido);
}
get detalheErro(): Array<LogArquivo>{
if(this.resultado == null) return new Array<LogArquivo>();
return this.resultado.filter(_ => _.tipo == 2 && !_.ehValido);
}
get trailerSucesso(): Array<LogArquivo>{
if(this.resultado == null) return new Array<LogArquivo>();
return this.resultado.filter(_ => _.tipo == 3 && _.ehValido);
}
get trailerErro(): Array<LogArquivo>{
if(this.resultado == null) return new Array<LogArquivo>();
return this.resultado.filter(_ => _.tipo == 3 && !_.ehValido);
}
}
|
ad31cb0c0f377f1d579517dfefd200eea4c79926
|
TypeScript
|
t5w0rd/tStarship
|
/src/base/Skill.ts
| 3.078125
| 3
|
class Skill {
ship: HeroShip;
power: number;
level :number = 1;
public constructor(power: number) {
this.power = power;
}
public cast(): boolean {
if (!this.ship.isEnergyFull()) {
return false;
}
if (this.ship.energy < this.power) {
return false;
}
this.ship.addEnergy(-this.power);
this.onCast();
return true;
}
// override
protected onCast(): void {
}
public levelUp(num: number=1, sound: boolean=true): void {
if (num === 0) {
return;
}
for (let i=0; i<num; i++) {
this.level++;
this.onLevelUp();
}
if (sound) {
tutils.playSound("GunPowerup_mp3");
}
}
// override
protected onLevelUp(): void {
}
}
|
e1b20788abe360eae34155c943504f846b010ae0
|
TypeScript
|
HappyCodeDay/ng2Shoppers
|
/client/app/core/product.service.ts
| 2.546875
| 3
|
import { Injectable } from '@angular/core';
import { Product } from '../../app/core/product';
import { CartService } from '../../app/core/cart.service';
import { PRODUCTS } from '../../app/data/mock-products';
@Injectable()
export class ProductService{
private cartItems: Product[] = [];
constructor(private cartService: CartService){
}
getProducts(){
console.log('product service get products');
console.log(PRODUCTS.length);
// return PRODUCTS;
return Promise.resolve(PRODUCTS);
}
getProduct(id: number){
return Promise.resolve(this.getProducts().then(products => products.find(product => product.id === id)));
}
add_to_user_cart(product: Product){
console.log("adding to cart - 1");
if(!this.cartItems.find(x => x.id == product.id))
{
this.cartItems.push(product);
}
else{
var curQty = this.cartItems.find(x => x.id == product.id).quantity;
this.cartItems.find(x => x.id == product.id).quantity = curQty+1;
}
}
remove_from_user_cart(product: Product){
console.log("removing from cart - 1");
if(!this.cartItems.find(x => x.id == product.id))
{
console.log('item not in the cart');
}
else{
this.cartItems.splice(this.cartItems.findIndex(x => x.id == product.id),1);
}
}
get_products_from_user_cart(){
console.log('items in cart - ' + this.cartItems.length);
return Promise.resolve(this.cartItems);
}
}
|
3ec27baf3f75c13f42620330876e9ea8570003f7
|
TypeScript
|
breslavsky/serialize
|
/src/serializers/serializer.ts
| 2.5625
| 3
|
export interface Serializer<T extends Object> {
serialize(model: T, additionalInfo?: any): Object | null;
deserialize(json: Object, additionalInfo?: any): T | null;
}
|
5e17f2f84fa91dd370084c7f6ee8b90b5e97f0c3
|
TypeScript
|
kirianchelo/owge
|
/game-frontend/src/app/service/resource-manager.service.ts
| 2.828125
| 3
|
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { ResourcesEnum } from '../shared-enum/resources-enum';
import { UserPojo } from '../shared-pojo/user.pojo';
/**
* Thi service contains the logged in user resources <br />
* It keeps the interface synced (adding resources each second) <br />
*
*
* @author Kevin Guanche Darias
*/
@Injectable()
export class ResourceManagerService {
public get currentPrimaryResource(): BehaviorSubject<number> {
return this._currentPrimaryResourceFloor;
}
public get currentSecondaryResource(): BehaviorSubject<number> {
return this._currentSecondaryResourceFloor;
}
public get currentEnergy(): Observable<number> {
return this._currentEnergyFloor.asObservable();
}
public get currentMaxEnergy(): BehaviorSubject<number> {
return this._currentMaxEnergyFloor;
}
private _intervalId: number;
private _currentPrimaryResource: number;
private _currentPrimaryResourcePerSecond: number;
private _currentSecondaryResource: number;
private _currentSecondaryResourcePerSecond: number;
private _currentEnergy: number;
private _currentMaxEnergy: number;
private _lastDate: Date;
private _currentPrimaryResourceFloor: BehaviorSubject<number> = new BehaviorSubject(0);
private _currentSecondaryResourceFloor: BehaviorSubject<number> = new BehaviorSubject(0);
private _currentEnergyFloor: BehaviorSubject<number> = new BehaviorSubject(0);
private _currentMaxEnergyFloor: BehaviorSubject<number> = new BehaviorSubject(0);
constructor() {
}
/**
*
* @param {UserPojo} userPojo
* @author Kevin Guanche Darias
*/
public startHandling(userPojo?: UserPojo) {
this.stopHandling();
this._lastDate = new Date();
if (userPojo) {
this._setResources(userPojo);
}
this._intervalId = window.setInterval(() => {
const currentDate: Date = new Date();
this._currentPrimaryResource = this._calculateSum(
currentDate,
this._lastDate,
this._currentPrimaryResourcePerSecond,
this._currentPrimaryResource
);
this._currentPrimaryResourceFloor.next(Math.floor(this._currentPrimaryResource));
this._currentSecondaryResource = this._calculateSum(
currentDate,
this._lastDate,
this._currentSecondaryResourcePerSecond,
this._currentSecondaryResource
);
this._currentSecondaryResourceFloor.next(Math.floor(this._currentSecondaryResource));
this._lastDate = currentDate;
}, 1000);
}
public stopHandling() {
window.clearInterval(this._intervalId);
this._intervalId = null;
}
/**
* Will add value to resource count
*
* @param {ResourcesEnum} resourceType Type of resource (primary,secondary ...)
* @param {number} value Number to add
*
* @author Kevin Guanche Darias
*/
public addResources(resourceType: ResourcesEnum, value: number): void {
switch (resourceType) {
case ResourcesEnum.PRIMARY:
this._currentPrimaryResource += value;
this._currentPrimaryResource = this._currentPrimaryResource < 0 ? 0 : this._currentPrimaryResource;
break;
case ResourcesEnum.SECONDARY:
this._currentSecondaryResource += value;
this._currentSecondaryResource = this._currentSecondaryResource < 0 ? 0 : this._currentSecondaryResource;
break;
case ResourcesEnum.CONSUMED_ENERGY:
this._currentEnergy += value;
this._currentEnergyFloor.next(Math.floor(this._currentEnergy));
break;
default:
throw new Error('Unexpected type ' + resourceType);
}
}
/**
* Will substract value to resource count
*
* @param {ResourcesEnum} resourceType Type of resource (primary,secondary ...)
* @param {number} value Number to substract
*
* @author Kevin Guanche Darias
*/
public minusResources(resourceType: ResourcesEnum, value: number): void {
this.addResources(resourceType, value * -1);
}
private _setResources(userPojo: UserPojo) {
this._setPrimaryValue(userPojo.primaryResource);
this._setSecondaryValue(userPojo.secondaryResource);
this._currentPrimaryResourcePerSecond = userPojo.computedPrimaryResourceGenerationPerSecond;
this._currentSecondaryResourcePerSecond = userPojo.computedSecondaryResourceGenerationPerSecond;
this._currentEnergy = userPojo.consumedEnergy;
this._currentMaxEnergy = userPojo.maxEnergy;
this._currentEnergyFloor.next(Math.floor(this._currentEnergy));
this._currentMaxEnergyFloor.next(Math.floor(this._currentMaxEnergy));
}
private _setPrimaryValue(value: number): void {
this._currentPrimaryResource = value;
this._currentPrimaryResourceFloor.next(Math.floor(this._currentPrimaryResource));
}
private _setSecondaryValue(value: number): void {
this._currentSecondaryResource = value;
this._currentSecondaryResourceFloor.next(Math.floor(this._currentSecondaryResource));
}
/**
* calculates the new value using the date diff and the value per second<br />
* <b>WARNING!: To avoid float madness ensure that atleast there is a interval of 500ms</b>
*
* @param {Date} present datetime representing now
* @param {Date} past datetime represents the last time value was update
* @param {number} perSecondValue Value to increase each second
* @param {number} value current Value
* @returns {number} The new value for the given resource
* @author Kevin Guanche Darias
*/
private _calculateSum(present: Date, past: Date, perSecondValue: number, value: number): number {
let retVal = value;
const difference: number = (present.getTime() - past.getTime()) / 1000;
retVal += (difference * perSecondValue);
return retVal;
}
}
|
3209912b3a0919f23808e5d5ef33fabca007a795
|
TypeScript
|
guiflr/stock-control
|
/src/repositories/ingredient/IngredientCurrentStockRepository.ts
| 2.5625
| 3
|
import {
IIngredientCurrentStock,
IIngredientCurrentStockDTO,
} from "./IIngredientCurrentStockRepository";
import IngredientCurrentStock from "../../database/schemas/IngredientCurrentStockSchema";
class IngredientCurrentStockRepository implements IIngredientCurrentStock {
async create({
quantity,
ingredient_id,
}: IIngredientCurrentStockDTO): Promise<IIngredientCurrentStockDTO> {
const currentStock = await IngredientCurrentStock.create({
quantity,
ingredient_id,
});
return currentStock;
}
async findByIngredientId(
ingredient_id: string
): Promise<IIngredientCurrentStockDTO> {
const currentStock = await IngredientCurrentStock.findOne({
ingredient_id,
});
return currentStock;
}
async updateByIngredientId({
quantity,
ingredient_id,
}: IIngredientCurrentStockDTO): Promise<IIngredientCurrentStockDTO> {
const currentStock = await IngredientCurrentStock.findOneAndUpdate(
{
ingredient_id,
},
{ quantity }
);
return currentStock;
}
}
export { IngredientCurrentStockRepository };
|
9d6133cf59a0dc93ce9fe628560ac34ef7e1b333
|
TypeScript
|
ivanv88/ghTrending
|
/src/app/model/dateRange.model.ts
| 2.640625
| 3
|
export interface IDateRange {
view: 'Today' | 'This week' | 'This month',
value: 'daily' | 'weekly' | 'monthly'
}
|
916a72b64c0f1e6b9fef9fd7da448b165cd283ea
|
TypeScript
|
mister-what/ex-patterns
|
/test/pattern/parentCapturing.test.ts
| 2.78125
| 3
|
/* eslint-disable no-unused-vars */
/* eslint-disable no-unused-expressions */
import { expect } from 'chai';
import { match, _, A, B, C } from '../../src';
describe('the match function: parent capturing', () => {
it('should be able to capture parent matches', () => {
const pattern = A({ user: B });
const value = { user: 'Amelie' };
const [status, matches] = match(pattern, value);
expect(status).to.be.true;
expect(matches).to.deep.equal({ A: { user: 'Amelie' }, B: 'Amelie' });
});
it('should not match if there are conflicting parent captures', () => {
const pattern = [B, B({ user: A })];
const value = [{ user: 'Amelie' }, { user: 'Jules' }];
const [status, matches] = match(pattern, value);
expect(status).to.be.false;
expect(matches).to.deep.equal({});
});
it('should resolve non-conflicting parent captures', () => {
const pattern = [B, B({ user: A })];
const value = [{ user: 'Amelie' }, { user: 'Amelie' }];
const [status, matches] = match(pattern, value);
expect(status).to.be.true;
expect(matches).to.deep.equal({ B: { user: 'Amelie' }, A: 'Amelie' });
});
it('should not match if there are conflicting nested parent captures', () => {
const pattern = [B, B({ user: A({ nickname: C }) })];
const names = { nickname: 'Ami', name: 'Amelie' };
const user = { user: names };
const value = [user, { names: { ...names, nickname: 'Amy' } }];
const [status, matches] = match(pattern, value);
expect(status).to.be.false;
expect(matches).to.deep.equal({ });
});
it('should perform nested parent captures', () => {
const pattern = [B, B({ user: A({ nickname: C }) })];
const names = { nickname: 'Ami', name: 'Amelie' };
const user = { user: names };
const value = [user, user];
const [status, matches] = match(pattern, value);
expect(status).to.be.true;
expect(matches).to.deep.equal({ B: user, A: names, C: 'Ami' });
});
it('should work with arrays', () => {
const pattern = A([1, 2, B]);
const value = [1, 2, 3];
const [status, matches] = match(pattern, value);
expect(status).to.be.true;
expect(matches).to.deep.equal({ A: [1, 2, 3], B: 3 });
});
});
|
e56297d36a72223c4c144f0b0ea90a33527b0cf7
|
TypeScript
|
JayKay24/coding_challenges
|
/algo_expert/max_path_sum_in_binary_tree.ts
| 3.8125
| 4
|
class BinaryTree {
value: number;
left: BinaryTree | null;
right: BinaryTree | null;
constructor(value: number) {
this.value = value;
this.left = null;
this.right = null;
}
}
export function maxPathSum(tree: BinaryTree) {
let maxSum = -Infinity;
const traversePostOrder = (node: BinaryTree) => {
let left: number = node.left
? Math.max(0, traversePostOrder(node.left))
: 0;
let right: number = node.right
? Math.max(0, traversePostOrder(node.right))
: 0;
maxSum = Math.max(maxSum, left + right + node.value);
return Math.max(left, right) + node.value;
};
traversePostOrder(tree);
return maxSum;
}
const binTree = new BinaryTree(1);
binTree.left = new BinaryTree(2);
binTree.right = new BinaryTree(3);
binTree.left.left = new BinaryTree(4);
binTree.left.right = new BinaryTree(5);
binTree.right.left = new BinaryTree(6);
binTree.right.right = new BinaryTree(7);
let res = maxPathSum(binTree);
console.log(res);
|
aee700e19d0c19aee0ba0279dcdefbdc71c5d0c7
|
TypeScript
|
judoaseeta/bitfetch
|
/src/core/lib/entities/cryptoArticle.ts
| 2.65625
| 3
|
interface RawCryptoArticle {
id: string;
guid: string;
published_on: number;
imageurl: string;
title: string;
url: string;
source: string;
body: string;
categories: string;
upvotes: string;
downvotes: string;
lang: string;
source_info: {
name: string;
lang: string;
img: string;
}
}
export interface RawCryptoArticleResp {
Type: number;
Message: string;
Promoted: any[];
Data: RawCryptoArticle[]
RateLimit: {};
HasWarning: boolean;
}
class CryptoArticle {
private _id: string;
private _guid: string;
private _published_on: Date;
private _imageUrl: string;
private _title: string;
private _url: string;
private _source: string;
private _body: string;
private _categories: string[];
private _source_info: {
name: string;
lang: string;
img: string;
}
private _timestamp: number;
constructor(rawData: RawCryptoArticle) {
this._id = rawData.id;
this._guid = rawData.guid;
this._timestamp = rawData.published_on;
this._published_on = new Date(rawData.published_on * 1000);
this._url = rawData.url;
this._imageUrl = rawData.imageurl;
this._title = rawData.title;
this._source = rawData.source;
this._body = rawData.body;
this._categories = rawData.categories.split('|');
this._source_info = rawData.source_info;
}
get id() {
return this._id;
}
get guid() {
return this._guid;
}
get publishedOn() {
return this._published_on;
}
get imageUrl() {
return this._imageUrl;
}
get title() {
return this._title;
}
get url() {
return this._url;
}
get source() {
return this._source;
}
get body() {
return this._body;
}
get categories() {
return this._categories;
}
get sourceInfo() {
return this._source_info;
}
get timeStamp() {
return this._timestamp;
}
}
export default CryptoArticle;
|
65905582c377463f334ae3cfaebd47276bef15f7
|
TypeScript
|
iphuongtt/learn-loopback-4
|
/src/services/greeting.service.ts
| 3.1875
| 3
|
import {Getter, config} from '@loopback/context';
import {extensions, extensionPoint} from '@loopback/core';
import chalk from 'chalk';
import { GREETER_EXTENSION_POINT_NAME, Greeter } from '../types';
/**
* Options for the greeter extension point
*/
export interface GreetingServiceOptions {
color: string;
}
/**
* An extension point for greeters that can greet in different languages
*/
@extensionPoint(GREETER_EXTENSION_POINT_NAME)
export class GreetingService {
constructor(
/**
* Inject a getter function to fetch greeters (bindings tagged with
* `{extensionFor: GREETER_EXTENSION_POINT_NAME}`)
*/
@extensions()
private getGreeters: Getter<Greeter[]>,
@config() // Sugar for @inject('services.GreetingService.options', {optional: true})
public readonly options?: GreetingServiceOptions,
) {}
/**
* Find a greeter that can speak the given language
* @param language - Language code for the greeting
*/
async findGreeter(language: string): Promise<Greeter | undefined> {
// Get the latest list of greeters
const greeters = await this.getGreeters();
// Find a greeter that can speak the given language
return greeters.find(g => g.language === language);
}
/**
* Greet in the given language
* @param language - Language code
* @param name - Name
*/
async greet(language: string, name: string): Promise<string> {
let greeting = '';
const greeter = await this.findGreeter(language);
console.log(greeter)
if (greeter) {
greeting = greeter.greet(name);
} else {
// Fall back to English
greeting = `Hello, ${name}!`;
}
if (this.options && this.options.color) {
greeting = chalk.keyword(this.options.color)(greeting);
}
return greeting;
}
}
|
c59d0cbcddb33694be4b0eb9a09c83578f275796
|
TypeScript
|
annaojdowska/kiohub
|
/kiohub-client/src/app/ui-elements/spinner/updatable-spinner.ts
| 3.015625
| 3
|
import { SpinnerComponent } from './spinner.component';
export abstract class UpdatableSpinner extends SpinnerComponent {
// list of successfully uploaded elements' names
succesList: string[] = [];
// list of badly uploaded elements' names
failedList: string[] = [];
// updatable info string to display in a view
infoString = '';
// how many elements to upload
elementsToSave: number;
// how many elements had been already uploaded
savedElements: number;
// ex. "trwa dodawanie załączników" / "rozpoczęto pobieranie plików"
currentlyBeingSavedText: string;
// ex. "zapisano następujące załączniki:" / "pobrano pliki:"
savedElementsText: string;
// ex. "nie udało się zapisać tych załączników: " / "wystąpił problem z plikami:"
failedElementsText: string;
// actions taken when update has been completed
protected abstract onUpdateCompleted();
// initialize inherited elements
protected abstract setInheritedElements();
// set view, on which element is being updated
protected abstract setViewComponent(view);
beginUpload(view, attachmentsToSave: number, infoString: string) {
this.setViewComponent(view);
this.savedElements = 0;
this.elementsToSave = attachmentsToSave;
this.succesList = [];
this.failedList = [];
this.infoString = infoString;
this.setDisplay(true);
this.updateSpinner();
}
resetSpinner() {
this.savedElements = null;
this.elementsToSave = null;
this.succesList = [];
this.failedList = [];
this.infoString = '';
}
addSuccess(successedElementName: string) {
this.succesList.push(successedElementName);
this.savedElements++;
this.updateSpinner();
}
addFail(failedElementName: string) {
this.failedList.push(failedElementName);
this.savedElements++;
this.updateSpinner();
}
updateSpinner() {
if (this.isUpdateCompleted()) {
this.updateInfoText();
this.onUpdateCompleted();
} else {
this.updateInfoText();
}
}
protected updateInfoText() {
// ex. trwa dodawanie załączników (zapisano 1 z 3)
this.text = this.infoString + this.currentlyBeingSavedText + ' (zapisano ' + this.savedElements + ' z ' + this.elementsToSave + '). ';
if (this.succesList.length > 0) {
// ex. zapisano załączniki: [lista]
this.text += '\n' + this.savedElementsText + ' ' + this.valueUtils.formatStringArrayToView(this.succesList) + '. ';
}
if (this.failedList.length > 0) {
// ex. wystąpiły problemy z zapisaniem załaczników: [lista]
this.text += '\n' + this.valueUtils.formatStringArrayToView(this.failedList) + '. ';
}
}
protected isUpdateCompleted() {
return this.elementsToSave === this.savedElements;
}
}
|
3c1e2ed0fb3f4f75d4179adbe38c08265de497e9
|
TypeScript
|
Nobuyukigo/comptes-pwa
|
/src/utils/models.ts
| 2.625
| 3
|
export type Category =
| 'restaurant'
| 'alimentation'
| 'loisirs'
| 'shopping'
| 'divers';
export interface Debt {
summary: string;
value: number;
}
export interface Distribution {
percentage: number;
key: Category;
svg?: {
fill: string;
};
value: number;
}
export interface Expense {
id: string;
category: Category;
cost: number;
date: string;
details: string;
type: TypeOfExpense;
whoPaid: string;
sharedWith?: string;
}
export interface ExpensesSortedByMonth {
[key: string]: Expense[];
}
export interface Friend {
id: string;
name: string;
avatar: string;
}
export interface Group {
[key: string]: boolean;
}
export interface MonthTotal {
month: string;
shared: number;
personal: number;
}
export interface ScreenProps {
user?: User;
expenses?: Expense[];
selectedMonth: string;
disconnect(): void;
// double check if we can better specify handleMonthSelection type
handleMonthSelection(): void;
}
export type TypeOfExpense = 'personnelle' | 'partagée' | 'avance';
export interface User {
id?: string;
name?: string;
avatar?: string;
friend?: Friend;
group?: Group;
}
export interface UserWithFriend extends User {
friend: Friend;
group: Group;
}
|
11f524296e27585f5aca9c083c61fdb9d4f37e81
|
TypeScript
|
supaflyENJOY/srcds-rcon-controller
|
/src/utils/ip-resolver.ts
| 2.59375
| 3
|
import * as isLocal from 'is-local-ip';
import * as myLocalIp from 'my-ip';
import * as myPublicIp from 'public-ip';
export default (ip : string) : Promise<string> => {
if(isLocal(ip)) {
return Promise.resolve(myLocalIp());
}
return myPublicIp.v4();
}
|
564abc82b5866d26a83fb3f1ad51524270efc771
|
TypeScript
|
hfxiang93/vue3-admin
|
/src/utils/index.ts
| 3.140625
| 3
|
/*
* @Author: shen
* @Date: 2021-01-20 10:13:02
* @LastEditors: shen
* @LastEditTime: 2021-01-31 16:23:55
* @Description:
*/
import { AnyFunction } from '@/types'
/**
* @description 延迟方法,异步函数
* @param {number} delay 延迟的时间,单位 毫秒
* @returns
*/
export const sleep = async (delay: number) => {
return new Promise((resolve) => setTimeout(resolve, delay))
}
export function rafThrottle<T extends AnyFunction<any>>(fn: T): AnyFunction<void> {
let locked = false
return (...args: any[]) => {
if (locked) return
locked = true
window.requestAnimationFrame(() => {
fn.apply(this, args)
locked = false
})
}
}
/**
* @description 驼峰转中横线
* @param {string} str
* @returns
*/
export function humpToMidline(str: string) {
return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}
/**
* @description 中横线转驼峰
* @param {string} str
* @returns
*/
export function midlinetoHump(str: string) {
return str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
}
|
7f1c1a6f66a84514845d7131c0a5c6a72703525f
|
TypeScript
|
devpt-org/estirador
|
/src/internals/databases/simple-entity/simple-entity.repository.ts
| 2.578125
| 3
|
import {
Class,
ConcreteClass,
} from '@app/shared/internals/utils/types/classes-types';
import { AuditContext } from 'src/internals/auditing/audit-context';
import {
AbstractRepository,
DeepPartial,
EntityManager,
FindOperator,
} from 'typeorm';
import { SimpleEntity } from './simple.entity';
import { generateUniqueUUID } from '../../utils/generate-unique-uuid';
type WhereObject<Entity extends SimpleEntity> = {
[K in keyof Entity]?:
| (Entity[K] extends {
id: number | string;
}
? Entity[K] | Entity[K]['id']
: never)
| Entity[K]
| FindOperator<Entity[K]>;
};
export type Where<Entity extends SimpleEntity> =
| WhereObject<Entity>
| Array<WhereObject<Entity>>;
type FindOptionsBase<Entity extends SimpleEntity> = {
withDeleted?: boolean;
order?: {
[K in keyof Entity]?: 'ASC' | 'DESC' | 1 | -1;
};
};
export interface FindOneOptions<Entity extends SimpleEntity>
extends FindOptionsBase<Entity> {
where: Where<Entity>;
}
export interface FindOptions<Entity extends SimpleEntity>
extends FindOptionsBase<Entity> {
where?: Where<Entity>;
skip: number;
}
export abstract class SimpleEntityRepository<
Entity extends SimpleEntity,
FieldsOmittedBeforePersistence extends keyof Entity = never,
> extends AbstractRepository<Entity> {
_EntityCreationAttributes!: Omit<
Entity,
keyof SimpleEntity | FieldsOmittedBeforePersistence | 'toJSON'
>;
findOne(
query: FindOneOptions<Entity>,
options?: Partial<{ manager: EntityManager }>,
): Promise<Entity | undefined> {
const repository = options?.manager
? options.manager.getRepository<Entity>(this.repository.target)
: this.repository;
return repository.findOne(query);
}
async find(
query: FindOptions<Entity>,
options?: Partial<{ manager: EntityManager }>,
) {
const repository = options?.manager
? options.manager.getRepository<Entity>(this.repository.target)
: this.repository;
const limit = 50;
const results = await repository.findAndCount({
...query,
take: limit,
});
return {
limit,
total: results[1],
rows: results[0],
};
}
async create(
entityLikeObject: this['_EntityCreationAttributes'],
auditContext: AuditContext,
options?: Partial<{ manager?: EntityManager }>,
): Promise<Entity> {
const repository = options?.manager
? options.manager.getRepository<Entity>(this.repository.target)
: this.repository;
const _entityLikeObject = {
...entityLikeObject,
} as Partial<Entity>;
_entityLikeObject.id = generateUniqueUUID();
const EntityClass = this.repository.target as ConcreteClass<
Partial<Entity>
>;
const entity = new EntityClass();
for (const _k of Object.keys(_entityLikeObject)) {
const key = _k as keyof Partial<Entity>;
entity[key] = _entityLikeObject[key];
}
await repository.save(entity as DeepPartial<Entity>);
return entity as Entity;
}
async save(
entity: Entity,
auditContext: AuditContext,
options?: Partial<{ manager?: EntityManager }>,
): Promise<void> {
const EntityClass = this.repository.target as Class;
if (!(entity instanceof EntityClass)) {
throw new Error();
}
const repository = options?.manager
? options.manager.getRepository<Entity>(this.repository.target)
: this.repository;
await repository.save(entity as unknown as DeepPartial<Entity>);
}
async remove(
entity: Entity,
auditContext: AuditContext,
manager?: EntityManager,
): Promise<void> {
const EntityClass = this.repository.target as Class;
if (!(entity instanceof EntityClass)) {
throw new Error();
}
const repository = manager
? manager.getRepository<Entity>(EntityClass)
: this.repository;
if (this.repository.metadata.deleteDateColumn) {
await repository.softRemove(entity as unknown as DeepPartial<Entity>);
} else {
await repository.remove(entity);
}
}
}
|
5986ad3ed7160582da707d0a22c6a96bb8d05613
|
TypeScript
|
NoQuarterTeam/tails
|
/src/templates/service.ts
| 2.671875
| 3
|
import { capitalize } from "@noquarter/utils"
export const ServiceTemplate = (name: string) => {
const capitalName = capitalize(name)
return `import { Service } from "typedi"
import { ${capitalName} } from "./${name}.entity"
import { ${capitalName}Repository } from "./${name}.repository"
@Service()
export class ${capitalName}Service {
constructor(private readonly ${name}Repository: ${capitalName}Repository) {}
async create(data: Partial<${capitalName}>): Promise<${capitalName}> {
const ${name} = await ${capitalName}.create(data).save()
return ${name}
}
async update(${name}Id: string, data: Partial<${capitalName}>): Promise<${capitalName}> {
const ${name} = await this.${name}Repository.findById(${name}Id)
Object.assign(${name}, data)
await ${name}.save()
return ${name}
}
async destroy(${name}Id: string): Promise<boolean> {
const ${name} = await this.${name}Repository.findById(${name}Id)
await ${name}.remove()
return true
}
}
`
}
|
f74a957d0ce573865fc439ef6e8152c47f63d6ce
|
TypeScript
|
SsooloomM/Adwarlak
|
/front-end/src/app/models/StoreProduct.ts
| 2.6875
| 3
|
import { Product } from './product';
import { Store } from './store';
export class StoreProduct {
private product: Product;
private store: Store;
private id: number;
private views: number;
private solds: number;
private available: number;
private price: number;
constructor(){
}
/**
* Getter $id
* @return {number}
*/
public get $id(): number {
return this.id;
}
/**
* Setter $id
* @param {number} value
*/
public set $id(value: number) {
this.id = value;
}
/**
* Getter $views
* @return {number}
*/
public get $views(): number {
return this.views;
}
/**
* Setter $views
* @param {number} value
*/
public set $views(value: number) {
this.views = value;
}
/**
* Getter $solds
* @return {number}
*/
public get $solds(): number {
return this.solds;
}
/**
* Setter $solds
* @param {number} value
*/
public set $solds(value: number) {
this.solds = value;
}
/**
* Getter $available
* @return {number}
*/
public get $available(): number {
return this.available;
}
/**
* Setter $available
* @param {number} value
*/
public set $available(value: number) {
this.available = value;
}
/**
* Getter $price
* @return {number}
*/
public get $price(): number {
return this.price;
}
/**
* Setter $price
* @param {number} value
*/
public set $price(value: number) {
this.price = value;
}
/**
* Getter $store
* @return {Store}
*/
public get $store(): Store {
return this.store;
}
/**
* Setter $store
* @param {Store} value
*/
public set $store(value: Store) {
this.store = value;
}
/**
* Getter $product
* @return {Product}
*/
public get $product(): Product {
return this.product;
}
/**
* Setter $product
* @param {Product} value
*/
public set $product(value: Product) {
this.product = value;
}
setData(Data): void{
this.id = Data.id;
this.views = Data.views;
this.solds = Data.solds;
this.price = Data.price;
this.available = Data.available;
this.store = Data.store;
this.product = Data.product;
}
}
|
25c23c8623c59eb82d30eb71cffb969ac7a2feca
|
TypeScript
|
demo-source/wasaby-controls
|
/Controls/_input/Base/InputUtil.ts
| 3.28125
| 3
|
import {ISelection, ISplitValue} from '../resources/Types';
export interface IInputData {
oldValue: string;
oldSelection: ISelection;
newValue: string;
newPosition: number;
}
/**
* Get split by entered string.
* @param {String} oldValue Values in the field before changing it.
* @param {String} newValue Values in the field after changing it.
* @param {Number} caretPosition Carriage position in the field after changing value.
* @param {Controls/_input/Base/Types/Selection.typedef} selection Selection in the field before changing value.
* @param {Controls/_input/Base/Types/InputType.typedef} inputType Type of changing value in the field.
* @return {Controls/_input/Base/Types/SplitValue.typedef}
*/
export function split(oldValue: string, newValue: string, caretPosition: number, selection, inputType: InputType): ISplitValue {
const selectionLength = selection.end - selection.start;
const afterInsertedValue: string = newValue.substring(caretPosition);
const beforeInsertedValue: string = inputType === 'insert'
? oldValue.substring(0, oldValue.length - afterInsertedValue.length - selectionLength)
: newValue.substring(0, caretPosition);
const insertedValue: string = newValue.substring(beforeInsertedValue.length, newValue.length - afterInsertedValue.length);
const deletedValue: string = oldValue.substring(beforeInsertedValue.length, oldValue.length - afterInsertedValue.length);
const result: ISplitValue = {
before: beforeInsertedValue,
insert: insertedValue,
delete: deletedValue,
after: afterInsertedValue
};
/**
* We can determine the correct split value only if there were user actions.
* If the value has been changed due to auto-complete, then user actions was not.
* Then the split value will be incorrect. In this case, return the split value for auto-complete.
*/
return isCorrectlySplit(result, oldValue, newValue) ? result : getSplitForAutoComplete(oldValue, newValue);
}
function isCorrectlySplit(split: ISplitValue, oldValue: string, newValue: string): boolean {
return split.before + split.delete + split.after === oldValue &&
split.before + split.insert + split.after === newValue;
}
function getSplitForAutoComplete(oldValue: string, newValue: string): ISplitValue {
return {
before: '',
insert: newValue,
delete: oldValue,
after: ''
};
}
|
bc6c9def016089e176cbbd26e1fb57662e0749fe
|
TypeScript
|
IronOnet/codebases
|
/codebases/coursera.org/static/bundles/promotions/utils/abandonedCartPromoUtils.ts
| 2.59375
| 3
|
import localStorage from 'js/lib/coursera.store';
import logger from 'js/app/loggerSingleton';
import user from 'js/lib/user';
import moment from 'moment';
import { stringKeyToTuple } from 'js/lib/stringKeyTuple';
type AbandonCartPromoData = {
userId?: number;
expiresAt?: number;
promoCode: string;
productType?: string;
productId?: string;
productSku?: string;
};
const LOCAL_STORAGE_KEY = 'abandonedCartPromoData';
export const getPromotionDataFromQuery = (query: {
userId?: string;
timestamp?: string;
edocomorp?: string; // Make promo code more cryptic since it's user facing
productSku?: string;
productId?: string;
}): AbandonCartPromoData | null => {
// We expect at least a promo code
if (!query || !query.edocomorp || !query.userId || !query.timestamp) {
return null;
}
const { productSku, edocomorp, productId } = query;
const userId = parseInt(query.userId, 10);
const timestamp = parseInt(query.timestamp, 10);
const expiresAt = moment(timestamp).add(14, 'days').valueOf();
const productType = productSku && stringKeyToTuple(productSku)[0];
return {
userId,
expiresAt,
promoCode: edocomorp,
productType,
productId,
productSku,
};
};
export const clearAbandonedCartPromotionFromStorage = () => {
localStorage.remove(LOCAL_STORAGE_KEY);
};
export const saveAbandonedCartPromoDataToStorage = (promoData: AbandonCartPromoData) => {
if (typeof window === 'undefined') {
logger.error('Attempted to save abandoned cart promo to local storage in a server context');
return;
}
const base64String = btoa(JSON.stringify(promoData));
localStorage.set(LOCAL_STORAGE_KEY, base64String);
};
export const loadAbandonedCartPromoDataFromStorage = (): AbandonCartPromoData | typeof undefined => {
const base64String = localStorage.get(LOCAL_STORAGE_KEY);
try {
return JSON.parse(atob(base64String));
} catch (err) {
return undefined;
}
};
export const isValidAbandonedCartPromotion = (userId: number, expiresAt: number) => {
return user.get().id === userId && new Date(expiresAt) > new Date();
};
|
a02b6cfdc3e0eb4c81188c6e5745a334e1ddc2f8
|
TypeScript
|
TimeToogo/ff-proxy
|
/client/node/tests/tcp-to-ff-socket.test.ts
| 2.875
| 3
|
import { FfClient, FfRequestOptions } from "../src/client";
import { TcpToFfSocket } from "../src";
describe("TcpToFfSocket", () => {
it("Calls FfClient.sendRequest with correct options", async () => {
const mockClient = ({
sendRequest: jest.fn().mockReturnValue(new Promise(() => {}))
} as any) as FfClient;
const socket = new TcpToFfSocket(mockClient, {
https: true
});
const request = "GET / HTTP/1.1\nHost: google.com\n\n";
socket.write(request);
expect(mockClient.sendRequest).toHaveBeenCalledTimes(1);
expect(mockClient.sendRequest).toBeCalledWith({
https: true,
request: Buffer.from(request, "utf-8")
} as FfRequestOptions);
});
it("Write callback is called after successful FfClient request", async () => {
let resolveSendRequest: Function, rejectSendRequest: Function;
const promise = new Promise((res, rej) => {
resolveSendRequest = res;
rejectSendRequest = rej;
});
const mockClient = ({
sendRequest: jest.fn().mockReturnValue(promise)
} as any) as FfClient;
const socket = new TcpToFfSocket(mockClient, {
https: true
});
let callback = jest.fn();
socket.write("GET / HTTP/1.1\nHost: google.com\n\n", undefined, callback);
resolveSendRequest!();
// Wait for event handlers to fire
await new Promise(resolve => setTimeout(resolve, 1));
expect(callback).toBeCalledTimes(1);
expect(callback).toBeCalledWith();
});
it("Passes FfClient error to callback", async () => {
let resolveSendRequest: Function, rejectSendRequest: Function;
const promise = new Promise((res, rej) => {
resolveSendRequest = res;
rejectSendRequest = rej;
});
const mockClient = ({
sendRequest: jest.fn().mockReturnValue(promise)
} as any) as FfClient;
const socket = new TcpToFfSocket(mockClient, {
https: true
});
let callback = jest.fn();
socket._write("GET / HTTP/1.1\nHost: google.com\n\n", "utf-8", callback);
rejectSendRequest!(new Error("some error"));
// Wait for event handlers to fire
await new Promise(resolve => setTimeout(resolve, 1));
expect(callback).toBeCalledTimes(1);
expect(callback).toBeCalledWith(new Error("some error"));
});
it("Hangs up socket without mockResponse", async () => {
let resolveSendRequest: Function, rejectSendRequest: Function;
const promise = new Promise((res, rej) => {
resolveSendRequest = res;
rejectSendRequest = rej;
});
const mockClient = ({
sendRequest: jest.fn().mockReturnValue(promise)
} as any) as FfClient;
const socket = new TcpToFfSocket(mockClient, {
https: true
});
const socketEvents = {
data: [] as any[],
ended: false
};
socket.addListener("data", chunk => {
socketEvents.data.push(chunk);
});
socket.addListener("end", () => {
socketEvents.ended = true;
});
socket.write("GET / HTTP/1.1\nHost: google.com\n\n");
resolveSendRequest!();
// Wait for event handlers to fire
await new Promise(resolve => setTimeout(resolve, 1));
expect(socketEvents.data).toEqual([]);
expect(socketEvents.ended).toEqual(true);
});
it("Sends correct mockResponse with string", async () => {
let resolveSendRequest: Function, rejectSendRequest: Function;
const promise = new Promise((res, rej) => {
resolveSendRequest = res;
rejectSendRequest = rej;
});
const mockClient = ({
sendRequest: jest.fn().mockReturnValue(promise)
} as any) as FfClient;
const socket = new TcpToFfSocket(mockClient, {
https: true,
mockResponse: "HTTP/1.1 200 OK\n\n\n"
});
const dataCallback = jest.fn();
socket.addListener("data",dataCallback);
socket.write("GET / HTTP/1.1\nHost: google.com\n\n");
socket.bufferSize
resolveSendRequest!();
// Wait for event handlers to fire
await new Promise(resolve => setTimeout(resolve, 1));
expect(dataCallback).toBeCalledTimes(1);
expect(dataCallback).toBeCalledWith(Buffer.from("HTTP/1.1 200 OK\n\n\n"));
});
it("Sends correct mockResponse with Buffer", async () => {
let resolveSendRequest: Function, rejectSendRequest: Function;
const promise = new Promise((res, rej) => {
resolveSendRequest = res;
rejectSendRequest = rej;
});
const mockClient = ({
sendRequest: jest.fn().mockReturnValue(promise)
} as any) as FfClient;
const socket = new TcpToFfSocket(mockClient, {
https: true,
mockResponse: Buffer.from("HTTP/1.1 200 OK\n\n\n")
});
const dataCallback = jest.fn();
socket.addListener("data",dataCallback);
socket.write("GET / HTTP/1.1\nHost: google.com\n\n");
resolveSendRequest!();
// Wait for event handlers to fire
await new Promise(resolve => setTimeout(resolve, 1));
expect(dataCallback).toBeCalledTimes(1);
expect(dataCallback).toBeCalledWith(Buffer.from("HTTP/1.1 200 OK\n\n\n"));
});
it("Sends correct mockResponse with number (status code)", async () => {
let resolveSendRequest: Function, rejectSendRequest: Function;
const promise = new Promise((res, rej) => {
resolveSendRequest = res;
rejectSendRequest = rej;
});
const mockClient = ({
sendRequest: jest.fn().mockReturnValue(promise)
} as any) as FfClient;
const socket = new TcpToFfSocket(mockClient, {
https: true,
mockResponse: 201
});
const dataCallback = jest.fn();
socket.addListener("data",dataCallback);
socket.write("GET / HTTP/1.1\nHost: google.com\n\n");
resolveSendRequest!();
// Wait for event handlers to fire
await new Promise(resolve => setTimeout(resolve, 1));
expect(dataCallback).toBeCalledTimes(1);
expect(dataCallback).toBeCalledWith(Buffer.from("HTTP/1.1 201 Created\n\n\n"));
});
});
|
fb79016b9141be3fb3e55a2e8c94baf005e72657
|
TypeScript
|
RGPosadas/Mull
|
/apps/mull-api/src/app/auth/auth.guard.spec.ts
| 2.515625
| 3
|
import { createMock } from '@golevelup/nestjs-testing';
import { ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { ROUTE_ARGS_METADATA } from '@nestjs/common/constants';
import jwt from 'jsonwebtoken';
import { authenticatedSubscription, AuthenticatedUser, AuthGuard } from './auth.guard';
jest.mock('jsonwebtoken');
const mockedJwt = jwt as jest.Mocked<typeof jwt>;
describe('AuthGuards', () => {
describe('AuthGuard', () => {
let guard;
beforeEach(() => {
guard = new AuthGuard();
});
it('AuthGuard', () => {
expect(guard).toBeDefined();
});
it('should return true with auth', () => {
const context = createMock<ExecutionContext>();
context.switchToHttp().getNext.mockReturnValue({
req: {
headers: {
authorization: 'auth',
},
},
});
mockedJwt.verify.mockImplementation(() => true);
expect(guard.canActivate(context)).toBeTruthy();
});
it('should return false with invalid auth', () => {
const context = createMock<ExecutionContext>();
context.switchToHttp().getNext.mockReturnValue({
req: {
headers: {
authorization: '',
},
},
});
mockedJwt.verify.mockImplementation(() => false);
expect(guard.canActivate(context)).toBe(false);
});
it('should throw exception with invalid header', () => {
const context = createMock<ExecutionContext>();
context.switchToHttp().getNext.mockReturnValue({
req: {
headers: {},
},
});
mockedJwt.verify.mockImplementation(() => false);
expect(() => guard.canActivate(context)).toThrow('Unauthorized');
});
});
// This testing methodology for param decorators was found on the nestjs github repo
// https://github.com/nestjs/nest/issues/1020
/* eslint-disable @typescript-eslint/ban-types, @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function */
describe('Auth Param Decorator', () => {
function getParamDecoratorFactory(decorator: Function) {
class Test {
public test(@decorator() value) {}
}
const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, Test, 'test');
return args[Object.keys(args)[0]].factory;
}
it('should return userId with auth', () => {
const context = createMock<ExecutionContext>();
context.switchToHttp().getNext.mockReturnValue({
req: {
headers: {
authorization: 'auth',
},
},
});
const mockUserId = 1;
mockedJwt.verify.mockImplementation(() => {
return { id: mockUserId };
});
const factory = getParamDecoratorFactory(AuthenticatedUser);
const result = factory(null, context);
expect(result).toBe(mockUserId);
});
it('should throw exception with invalid accesstoken', () => {
const context = createMock<ExecutionContext>();
context.switchToHttp().getNext.mockReturnValue({
req: {
headers: {
authorization: '',
},
},
});
mockedJwt.verify.mockImplementation(() => {
throw new Error();
});
const factory = getParamDecoratorFactory(AuthenticatedUser);
expect(() => factory(null, context)).toThrow('Unauthorized');
});
it('should throw exception with invalid header', () => {
const context = createMock<ExecutionContext>();
context.switchToHttp().getNext.mockReturnValue({
req: {
headers: {},
},
});
const factory = getParamDecoratorFactory(AuthenticatedUser);
expect(() => factory(null, context)).toThrow('Unauthorized');
});
});
describe('authenticatedSubscription', () => {
it('it should authenticate a valid token', () => {
mockedJwt.verify.mockImplementation(() => {
return;
});
const result = authenticatedSubscription('abc123');
expect(result).toBeTruthy();
});
it('it should throw exception with invalid token', () => {
mockedJwt.verify.mockImplementation(() => {
throw new UnauthorizedException('Unauthorized');
});
expect(() => authenticatedSubscription('abc321')).toThrow('Unauthorized');
});
});
});
|
bf793c3a91fc7fbd5f3ed6a3f4592d556f06e67a
|
TypeScript
|
dietmarw/search
|
/src/lib/Store.ts
| 2.96875
| 3
|
import { ImpactIndex } from './Index';
import { SubState, Observable } from './State';
// This class represents the storage of all state information for the
// application. Each of these states is represented by an instance of
// SubState which provides an interface which is essentially read only
// and can be passed as a property to a Component (which then links
// that to an internal state).
class Store {
public index: SubState<ImpactIndex>;
public term: SubState<string>;
constructor(public source?: string) {
if (!source) {
// Use the local version, if it exists, to avoid the need
// for a network connection.
this.source = "./impact_index.json";
}
this.index = new SubState(null);
this.term = new SubState("");
}
updateTerm(s: string) {
this.term.update(s);
}
load() {
return $.get(this.source)
.then((result: ImpactIndex) => {
console.log("Loaded index from ", this.source);
this.index.update(result);
}, (e) => {
var remote = "http://impact.github.io/impact_index.json";
// If we get here, there was an error. So now let's try
// a public version of impact_index.json (requires a
// network connection).
console.log("Failed to load index from ", this.source);
console.log("Now tring to load from ", remote);
return $.get(remote)
.then((result: ImpactIndex) => {
console.log("Loaded index from ", remote);
this.index.update(result);
}, (e) => {
console.error("Unable to load index file from ", this.source,
" or ", remote);
})
});
/*
return $.get(this.source, (result: ImpactIndex) => {
console.log("Loaded index from ", this.source);
this.index.update(result);
}, (e) => {
var remote = "http://impact.github.io/impact_index.json";
// If we get here, there was an error. So now let's try
// a public version of impact_index.json (requires a
// network connection).
console.log("Failed to load index from ", this.source);
console.log("Now tring to load from ", remote);
return $.get(remote, (result: ImpactIndex) => {
console.log("Loaded index from ", remote);
this.index.update(result);
}, (e) => {
console.error("Unable to load index file from ", this.source, " or ", remote);
})
})
*/
}
}
export = Store;
|
499181e4dfd3c89dc6ae9adb1298b669eae1f090
|
TypeScript
|
cyberbobjr/rogue-game-angular
|
/src/app/core/classes/base/game-monster-class.ts
| 2.578125
| 3
|
import {JsonMonster, JsonMonsterClass} from '../../interfaces/json-interfaces';
import {Utility} from '../utility';
import {Sprite} from './sprite';
import {Weapon} from '../gameObjects/weapon';
import {GameObjectFactory} from '../../factories/game-object-factory';
export class GameMonsterClass {
get weapons(): Array<Weapon> {
const weapons: Array<Weapon> = [];
this._jsonMonster.weapons.forEach((weaponId: string) => {
weapons.push(GameObjectFactory.getInstance()
.getWeaponById(weaponId));
});
return weapons;
}
get id(): string {
return this._jsonMonster.id;
}
get name(): string {
return this._jsonMonster.name;
}
get ac(): number {
return this._jsonMonster.ac;
}
get strength(): number {
return this._jsonMonster.abilities.strength;
}
get dexterity(): number {
return this._jsonMonster.abilities.dexterity;
}
get constitution(): number {
return this._jsonMonster.abilities.constitution;
}
get intelligence(): number {
return this._jsonMonster.abilities.intelligence;
}
get wisdom(): number {
return this._jsonMonster.abilities.wisdom;
}
get charisma(): number {
return this._jsonMonster.abilities.charisma;
}
get hp(): number {
return this._jsonMonster.hp.mul * Utility.rolldice(this._jsonMonster.hp.dice) + this._jsonMonster.hp.bonus;
}
get gp(): number {
return Utility.rolldice(this._jsonMonster.gp.dice);
}
get sprite(): Sprite {
return new Sprite(this._jsonMonster.sprite.character, this._jsonMonster.sprite.color);
}
get size(): string {
return this._jsonMonster.size;
}
get speed(): number {
return this._jsonMonster.speed;
}
get frequency(): number {
return this._jsonMonster.frequency;
}
constructor(private _jsonMonster: JsonMonsterClass) {
}
toJSON(): any {
return this._jsonMonster;
}
}
|
d2b426d59b590659a24cc769d157bf9e1c233ef3
|
TypeScript
|
alexroutledge/angular-memoize-pipe-example
|
/src/app/memoize.pipe.ts
| 2.671875
| 3
|
import { Injector, Pipe, PipeTransform } from '@angular/core';
import { memoize, bind, MemoizedFunction, isUndefined, keys } from 'lodash';
import { FibonacciPipe } from './fibonacci.pipe';
@Pipe({
name: 'memoize'
})
export class MemoizePipe implements PipeTransform {
private readonly PIPES: {[key: string]: Pipe} = {
fibonacci: FibonacciPipe
};
private cache: Map<string, MemoizedFunction> = new Map();
constructor(public injector: Injector) {
keys(this.PIPES).forEach((key: string) => {
this[key] = this.injector.get(this.PIPES[key]);
});
}
public transform(value: string, token: string): string | number {
const instance = this[token];
if (isUndefined(this.cache.get(token))) {
this.cache.set(token, memoize(
bind(instance.transform, instance)
));
}
return this.cache.get(token)(value);
}
}
|
2a606bcea415f16d8364469dafd95b0f11887b63
|
TypeScript
|
thetinyspark/texture-packer
|
/test/service/FileService.spec.ts
| 2.796875
| 3
|
import { createCanvas } from "canvas";
import FileService from "../../lib/core/service/FileService";
describe('FileService test suite',
()=>{
const currentFile = __filename;
const service = new FileService();
const tmpPath = __dirname+"/tmp/";
const subPath = tmpPath+"sub/";
const jsonPath = tmpPath+"john.doe.json";
const imgPath = tmpPath+"john.doe.png";
const jsonData = JSON.stringify({name:"John Doe"});
const canvas = createCanvas(100,100);
beforeEach(
()=>{
service.mkDir(subPath);
}
);
afterEach(
()=>{
service.rmDir(tmpPath);
}
);
it('should be able to instanciate a new FileService',
()=>{
expect(service).toBeTruthy();
});
it('should be able to tell if a specific file exists or not',
()=>{
expect(service.fileExists(currentFile)).toBeTrue();
});
it('should write a json file into the specific path',
()=>{
service.writeJSON(jsonData, jsonPath );
expect(service.fileExists(jsonPath)).toBeTrue();
});
it('should write an image from a canvas into the specific path',
()=>{
service.writeImage(canvas, imgPath );
expect( service.fileExists(imgPath) ).toBeTrue();
});
it('should remove a file into the specific path',
()=>{
service.writeJSON(jsonData, jsonPath );
service.removeFile(jsonPath);
expect(service.fileExists(jsonPath)).toBeFalse();
});
it('should create a directory recursively',
()=>{
expect(service.fileExists(subPath)).toBeTrue();
});
it('should remove a directory',
()=>{
service.rmDir(subPath);
expect(service.fileExists(subPath)).toBeFalse();
})
it('should list all the files into a specific directory',
()=>{
service.writeJSON(jsonData, jsonPath);
expect(service.readDir(tmpPath)).toContain(jsonPath);
});
it('should list all files in a specific directory, recursively',
()=>{
service.writeJSON(jsonData, jsonPath);
const files = service.readDir(tmpPath, true);
expect(files).toContain(jsonPath);
});
it('should remove a non empty folder',
()=>{
service.writeJSON(jsonData, jsonPath);
service.rmDir(tmpPath);
expect(service.fileExists(tmpPath)).toBeFalse();
});
})
|
2caeeab97b41bb470f92dee35b50ede43071d80b
|
TypeScript
|
fakoua/soxa
|
/src/helpers/isAbsoluteURL.ts
| 3.484375
| 3
|
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
const isAbsoluteURL = function (url: string): boolean {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
export { isAbsoluteURL }
|
bbfa1ab9536665e6d3260c193fb1ede4c8448516
|
TypeScript
|
nafsar/templateForms-version7
|
/src/app/app.component.ts
| 2.515625
| 3
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
emails = ['', 'naser@angular.io', 'templateFormat@angular.io', 'test@gm.com',
'', 'form@uiux.bi'];
model = new Data('Earth', this.emails[0], 'Angular Template Driven Forms');
submitted = false;
title = 'name';
emailAddress = 'Email Address';
text = 'Message';
emailAddressRes = ''; titleRes = ''; textRes = '';
onSubmit(result) {
this.titleRes = result.name;
this.emailAddressRes = result.myEmails;
this.textRes = result.textMessage;
this.submitted = true;
}
}
export class Data {
constructor(
public name: string,
public myEmails?: string,
public textMessage?: string
) { }
}
|
21fa18e39545116602637a0b0734fffb34119abf
|
TypeScript
|
paiboon15721/refinitiv-test
|
/question-two/src/app/filter.pipe.ts
| 2.6875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(xs: string[] | null, term: string): string[] {
const lowerTerm = term.toLowerCase();
return xs
? xs.filter((x) => x.toLowerCase().indexOf(lowerTerm) !== -1)
: [];
}
}
|
ade1bc31a6b9908af57b8f05d6fbbfa0b0fe0544
|
TypeScript
|
green-fox-academy/Galicz555
|
/week-03/day-4/farm.ts
| 3.5625
| 4
|
import { animal } from '../day-3/animal'
class Farm {
private _list: animal[];
private _slots: number;
public currentNumAnimals: number = 0;
constructor(slots: number = 10, listOfAnimals?: animal[]) {
this._slots = slots
if (listOfAnimals) {
this._list = listOfAnimals;
} else { this._list = [] };
}
public breed(): void {
if (this.currentNumAnimals <= this._slots) {
this._list.push(new animal);
this.currentNumAnimals++;
console.log("Bred a new for you!")
}
console.log(this.currentNumAnimals);
}
public returnList() {
return this._list
}
public slaughter(): void {
// let fedStatus = [];
// let chosen = []
// for (let i = 0; i < this._list.length; i++) {
// fedStatus.push(this._list[i].hunger);
// }
// fedStatus.reduce(function (a, b) {
// if (a > b) {
// return b;
// }
// });
// for (let i = 0; i < this._list.length; i++) {
// if (this._list[i].hunger === fedStatus[0]) {
// this._list.slice(i);
// chosen.push(this._list[i]);
// }
// }
// for(let i = 0; i < this._list.length; i++){
// if(this._list[i].hunger >){
// this._list.slice(this._list_slice[i])
// }
// console.log('New meat for dinner!! ' + chosen[0]);
// delete chosen[0];
// if(this._list.length > 0){
// let lowestHunger: number;
// let fullestAnimal: number;
// for(let i: number = 0; i < this._list.length; i++){
// if (i = 0){
// lowestHunger = this._list[i].hunger;
// fullestAnimal = i;
// console.log(lowestHunger);
// console.log(fullestAnimal);
// }
// if (this._list[i].hunger < lowestHunger){
// lowestHunger = this._list[i].hunger;
// fullestAnimal = i;
// }
// }
// this._list.splice(fullestAnimal, 1);
// }
// }
}
}
let Ranch = new Farm(10);
Ranch.breed();
Ranch.breed();
Ranch.breed();
console.log(Ranch.returnList());
Ranch.returnList()[0].play();
console.log(Ranch.returnList()[0])
Ranch.slaughter();
console.log(Ranch.returnList());
|
d353ea6ebbe28a6e0d7c512ef4194da25e0992db
|
TypeScript
|
annavlz/minesweeper
|
/app/jspm_packages/npm/rx@3.1.0/ts/core/linq/observable/delaywithselector.ts
| 3.40625
| 3
|
/// <reference path="../../observable.ts" />
module Rx {
export interface Observable<T> {
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
delayWithSelector(delayDurationSelector: (item: T) => ObservableOrPromise<number>): Observable<T>;
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
delayWithSelector(subscriptionDelay: Observable<number>, delayDurationSelector: (item: T) => ObservableOrPromise<number>): Observable<T>;
}
}
(function() {
var o: Rx.Observable<string>;
o.delayWithSelector(x => Rx.Observable.timer(x.length));
o.delayWithSelector(Rx.Observable.timer(1000), x => Rx.Observable.timer(x.length));
o.delayWithSelector(x => Rx.Observable.timer(x.length).toPromise());
});
|
89a70551d80f1ce39d40f1bc0350b42f90389fb6
|
TypeScript
|
ericrkuo/BE-hackcamp
|
/src/main/entity/Nutrition.ts
| 3.015625
| 3
|
import {Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn} from "typeorm";
import {Dish} from "./Dish";
@Entity()
export class Nutrition {
constructor(name: string, value: number, unit: string) {
this.name = name;
this.value = value;
this.unit = unit;
}
@PrimaryGeneratedColumn('uuid')
id: string;
/*
* ManyToOne bidirectional relationship between Nutrition and Dish
* On delete cascade on foreign key dishId
* Nutrition is the owning side of this association, contains column dishId
* */
@ManyToOne(() => Dish, (dish) => dish.nutritions, {
nullable: false,
onDelete: 'CASCADE',
})
@JoinColumn()
dish: Dish
@Column()
name: string;
@Column()
value: number
@Column()
unit: string
}
|
1e5309a1d1211134c8e89d2866e581f19cd2da8c
|
TypeScript
|
kennysng/node-jql-core
|
/src/core/task.ts
| 3.046875
| 3
|
import { CancelablePromise } from '@kennysng/c-promise'
import { JQL } from 'node-jql'
import uuid = require('uuid/v4')
import EventEmitter from 'wolfy87-eventemitter'
import { TaskError } from '../utils/error/TaskError'
/**
* Status function
*/
export type TaskFn<T> = (task: Task) => CancelablePromise<T>
/**
* Represent a task
*/
export class Task<T = any> extends EventEmitter {
/**
* Task ID
*/
public readonly id = uuid()
/**
* Task that can be canceled
*/
public readonly promise: CancelablePromise<T>
/**
* Start time of the task
*/
public readonly startFrom = Date.now()
/**
* Task status
*/
public statusCode = StatusCode.PREPARING
/**
* @param jql [JQL]
* @param fn [Function] Create Promise from task
*/
constructor(public readonly jql: JQL, fn: TaskFn<T>) {
super()
this.promise = fn(this)
}
/**
* Change task status
* @param statusCode [StatusCode]
*/
public status(statusCode: StatusCode): Task<T> {
if (this.statusCode.valueOf() > statusCode.valueOf()) {
throw new TaskError(`Status code cannot roll back from ${StatusCode[this.statusCode]} to ${StatusCode[statusCode]}`)
}
this.emit(StatusCode[statusCode].toLocaleLowerCase())
return this
}
// @override
public toString(): string {
return this.jql ? this.jql.toString() : `Task#${this.id}`
}
}
/**
* Definition of the status code
*/
export enum StatusCode {
/**
* e.g. Pre-compiling
*/
PREPARING,
/**
* e.g. Waiting for databases or tables
*/
WAITING,
/**
* Processing
*/
RUNNING,
/**
* e.g. Releasing databases or tables
*/
ENDING,
/**
* Result returned
*/
COMPLETED,
}
|
0431b9988c4be874a0c5ebbd71d5fe036bde910c
|
TypeScript
|
TomokiMiyauci/coin-monitor
|
/api/src/bot/rate.ts
| 2.515625
| 3
|
import admin from 'firebase-admin'
import type { ServiceAccount } from 'firebase-admin/lib/credential'
import { NowRequest, NowResponse } from '@vercel/node'
import { factory } from '../rate'
const createApp = (
cert: ServiceAccount = {
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY!.replace(/\\n/g, '\n')
}
): admin.app.App => {
if (admin.apps.length === 0) {
admin.initializeApp({
credential: admin.credential.cert(cert)
})
}
return admin.app()
}
const postRate = async ({ query }: NowRequest, res: NowResponse) => {
const { pair, market, path } = query
if (
Array.isArray(pair) ||
!pair ||
Array.isArray(market) ||
!market ||
Array.isArray(path) ||
!path
) {
return res.status(400).send('Invalid Parameters')
}
const getRate = factory(market)
const date = new Date()
const result = await getRate(pair).catch(async () => {
return await getRate(pair)
})
if (!result) {
console.error('Error')
return
}
const rate = mapper(market, result)
if (!rate) return
await saveRate({ date, pair, rate, market, collectionPath: path })
return res.status(200).send('OK')
}
const mapper = <T extends 'coincheck' | 'zaif'>(
market: T,
data: T extends 'coincheck'
? { rate: number }
: T extends 'zaif'
? { last_price: number }
: never
): number => {
switch (market) {
case 'coincheck': {
return data.rate
}
case 'zaif': {
return data.last_price
}
}
}
export default postRate
const saveRate = ({
rate,
date,
pair,
market,
collectionPath
}: {
rate: number
date: Date
pair: string
market: string
collectionPath: string
}) => {
return createApp()
.firestore()
.collection('markets')
.doc(market)
.collection('pairs')
.doc(pair)
.collection(collectionPath)
.add({
value: rate,
date
})
}
|
4414eff238dee6df8b9997a90e03c827b70e275d
|
TypeScript
|
toystars/football-simulator
|
/src/utils/validators/__tests__/pitch-validators.util.spec.ts
| 2.9375
| 3
|
import { validatePitch } from '../pitch-validators.util';
import { IPitch, PitchDimensionsLength, PitchDimensionsWidth, PitchTurfType, PitchValidationError } from '../../../types';
const draftPitch: IPitch = { length: 0, width: 0 };
describe('Pitch Validator', () => {
it('should throw PitchValidationError on empty pitch', () => {
expect(() => validatePitch({} as any)).toThrow(PitchValidationError);
});
it('should throw PitchValidationError on invalid pitch length', () => {
const testPitch: IPitch = { ...draftPitch };
expect(() => validatePitch(testPitch)).toThrow(PitchValidationError);
});
it('should throw PitchValidationError on invalid pitch width', () => {
const testPitch: IPitch = { ...draftPitch, length: PitchDimensionsLength.Min };
expect(() => validatePitch(testPitch)).toThrow(PitchValidationError);
});
it('should throw PitchValidationError on pitch with invalid turf type', () => {
const testPitch: any = {
length: PitchDimensionsLength.Min,
width: PitchDimensionsWidth.Min,
turfType: 'CONCRETE'
};
expect(() => validatePitch(testPitch)).toThrow(PitchValidationError);
});
it('should return true for valid pitch', () => {
const testPitch: any = {
length: PitchDimensionsLength.Min,
width: PitchDimensionsWidth.Min,
turfType: PitchTurfType.Grass
};
expect(validatePitch(testPitch)).toBeTruthy();
});
});
|
8df8e028db425862854a84dcfd0b573cce6cac77
|
TypeScript
|
dearamy/dagger-online
|
/server/tests/worldTests.ts
| 2.609375
| 3
|
/// <reference path='../src/types' />
import chai = require('chai');
var should = chai.should();
var expect = chai.expect;
import _ = require('lodash');
import World = require('../src/gameServer/models/World');
import Zone = require('../src/gameServer/models/Zone');
import GameObject = require('../src/gameServer/models/GameObject');
import User = require('../src/gameServer/models/User');
import Player = require('../src/gameServer/models/Player');
import ZoneTemplate = require('../src/gameServer/templates/ZoneTemplate');
describe('World', () => {
it('Should update tick', () => {
var world = new World();
var ticksToDo = 5;
var startingTick = world.tick;
for (var i = 0; i < ticksToDo; i++) {
world.updateTick(100);
}
world.tick.should.equal(ticksToDo + startingTick);
});
it('Should add and remove Player', () => {
var world = new World();
var user = new User(0, 'Dummy');
var player = new Player(0, user);
// Add player
world.containsPlayer(player).should.equal(false);
world.addPlayer(player);
world.containsPlayer(player).should.equal(true);
// Remove player
world.removePlayer(player);
world.containsPlayer(player).should.equal(false);
});
it ('Should generate unique instance ids', () => {
var world = new World();
var idList = new Array<number>();
for(var i =0; i < 100; i++) {
var newId = world.generateInstanceId();
_.include(idList, newId).should.be.false;
idList.push(newId);
}
});
it('Should get zone by name', () => {
var zoneTemplate: ZoneTemplate = _.cloneDeep(require('../data/maps/world.json'));
zoneTemplate.name = "SuperUnexistingName";
var zone = new Zone(zoneTemplate);
var world = new World();
world.addZone(zone);
should.exist(world.getZoneByName("SuperUnexistingName"));
});
});
|
a924abe24fb3895c35e14803d21b563419611cd9
|
TypeScript
|
JirkaDellOro/Computergrafik.Online
|
/docs/assets/dist/interactions/05-Aufloesung-Ausgabe/Aufloesung-eines-Monitors/main.ts
| 2.515625
| 3
|
let rangeInput: HTMLInputElement;
let rangeValue: number;
let currWidth: number;
let difference: number;
let maxHeight: number = 2800;
let img: HTMLDivElement;
window.addEventListener("load", main);
function main(): void {
rangeInput = document.getElementById("rangeIP") as HTMLInputElement;
rangeValue = parseFloat(rangeInput.value);
img = document.getElementById("imgcontainer") as HTMLDivElement;
}
function zoom(): void {
console.log(img.style.backgroundSize = 100 * rangeValue + "%");
}
function updateSlider(_r: HTMLInputElement) {
currWidth = img.clientWidth;
let rangeNewValue: number = parseFloat(_r.value);
if (rangeNewValue > rangeValue) {
difference = (rangeNewValue - rangeValue);
rangeValue = rangeNewValue;
zoom();
}
else if (rangeNewValue < rangeValue) {
difference = (rangeValue - rangeNewValue);
rangeValue = rangeNewValue;
zoom();
}
console.log(rangeValue);
}
|
b8e0bbc4562245e4515fa6419a9f549774d0a868
|
TypeScript
|
origami-team/geogami
|
/src/app/services/language.service.ts
| 2.609375
| 3
|
import { TranslateService } from '@ngx-translate/core';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
const LNG_KEY = 'SELECTED_LANGUAGE';
const lngs = ['de', 'en'];
@Injectable({
providedIn: 'root'
})
export class LanguageService {
selected = '';
constructor(private translate: TranslateService, private storage: Storage) { }
setInitialAppLangauge() {
// 1. check if lang have been stored
// 2. check if device default lang can be fetched and it's one of the supported language
// 3. use german as a default lang
this.storage.get(LNG_KEY).then(val => {
if (val) {
this.setLanguage(val);
this.selected = val
} else {
let langauge = this.translate.getBrowserCultureLang(); // Get browser lang
if (lngs.includes((langauge.toLowerCase().slice(0, 2)))) {
this.translate.setDefaultLang(langauge.toLowerCase().slice(0, 2));
this.selected = langauge.toLowerCase().slice(0, 2);
} else {
this.setLanguage('de') // german is the default lang if browser lang is not supported
}
}
//this.storage.clear()
});
}
getLangauges() {
return [
{ value: 'de', img: '🇩🇪', text: 'Deutsch' },
{ value: 'en', img: '🇺🇸', text: 'English' },
//{ value: 'pt', img: '🇵🇹' },
];
}
setLanguage(lng) {
this.translate.use(lng);
this.selected = lng;
this.storage.set(LNG_KEY, lng)
}
}
|
2b209fd4dbd839044a84880e2adaa5953ab2756e
|
TypeScript
|
jotauribe/ABank
|
/src/app/store/loan-request-form/reducers.ts
| 2.671875
| 3
|
import { Client } from '../../models/client.model';
import * as LoanRequestActions from './actions';
export interface State {
clients: Client[];
response: string;
loanAmount: number;
wasSuccessful: boolean;
wasSubmitted: boolean;
}
const initialState: State = {
clients: [],
response: 'NOT PROCESSED',
loanAmount: 0,
wasSuccessful: false,
wasSubmitted: false
};
export function reducer(
state = initialState,
action: LoanRequestActions.Actions
) {
console.log('ON LOAN-REQUEST REDUCER ', action);
switch (action.type) {
case LoanRequestActions.SAVE_EMPLOYMENT_INFO:
return {
...state,
wasSubmitted: true
};
case LoanRequestActions.SAVE_EMPLOYMENT_INFO_DONE:
return {
...state,
response: action.payload.response,
loanAmount: action.payload.loanAmount,
wasSubmitted: false,
wasSuccessful: true
};
case LoanRequestActions.SAVE_EMPLOYMENT_INFO_FAILED:
return {
...state,
wasSubmitted: true,
wasSuccessful: false
};
default:
return state;
}
}
|
8e6145dfaf52d0b26a93ee4e95f2f2778a7f8533
|
TypeScript
|
zbiju/adverity-etl
|
/src/api/ApiClient.test.ts
| 2.53125
| 3
|
import { DataEntry, DataEntryAPI } from '../models/DataEntry';
import { extractDatasourcesAndCampaigns, getData, mapData } from './ApiClient';
const fs = require('fs');
describe('API', () => {
let loadedData: DataEntryAPI[];
let mappedData: DataEntry[];
beforeAll(async () => {
const file = fs.createReadStream('./mocks/fake.csv');
loadedData = await getData(file);
mappedData = mapData(loadedData);
});
it('correctly parses data to get filters', () => {
const filters = extractDatasourcesAndCampaigns(mappedData);
expect(filters.campaigns).not.toBeNull();
expect(filters.datasources).not.toBeNull();
expect(filters.campaigns).toHaveLength(3);
expect(filters.datasources).toHaveLength(3);
});
});
|
fd6fb8434caf289a7f17b5b0103001dac33f8808
|
TypeScript
|
automerge/hypermerge
|
/src/Actor.ts
| 2.59375
| 3
|
import { Change } from 'automerge'
import { ID, ActorId, DiscoveryId, encodeActorId } from './Misc'
import Queue from './Queue'
import * as Block from './Block'
import * as Keys from './Keys'
import Debug from './Debug'
import FeedStore, { FeedId, Feed } from './FeedStore'
const log = Debug('Actor')
export type ActorMsg = ActorFeedReady | ActorSync | Download
interface ActorSync {
type: 'ActorSync'
actor: Actor
}
interface ActorFeedReady {
type: 'ActorFeedReady'
actor: Actor
feed: Feed
writable: boolean
}
interface Download {
type: 'Download'
actor: Actor
time: number
size: number
index: number
}
interface ActorConfig {
keys: Keys.KeyBuffer
notify: (msg: ActorMsg) => void
store: FeedStore
}
export class Actor {
id: ActorId
dkString: DiscoveryId
changes: Change[] = []
private q: Queue<(actor: Actor) => void>
private notify: (msg: ActorMsg) => void
private store: FeedStore
constructor(config: ActorConfig) {
const { publicKey } = config.keys
const dk = Keys.discoveryKey(publicKey)
const id = encodeActorId(publicKey)
this.id = id
this.store = config.store
this.notify = config.notify
this.dkString = Keys.encode(dk)
this.q = new Queue<(actor: Actor) => void>('repo:actor:Q' + id.slice(0, 4))
this.getOrCreateFeed(Keys.encodePair(config.keys)).then((feed) => {
feed.ready(() => this.onFeedReady(feed))
})
}
// Note: on Actor ready, not Feed!
onReady = (cb: (actor: Actor) => void) => {
this.q.push(cb)
}
writeChange(change: Change) {
const feedLength = this.changes.length
const ok = feedLength + 1 === change.seq
log(`write actor=${this.id} seq=${change.seq} feed=${feedLength} ok=${ok}`)
this.changes.push(change)
this.onSync()
this.store.append(this.id, Block.pack(change))
}
close() {
return this.store.closeFeed(this.id)
}
private async getOrCreateFeed(keys: Keys.KeyPair) {
let feedId: FeedId
if (keys.secretKey) {
feedId = await this.store.create(keys as Required<Keys.KeyPair>)
} else {
feedId = keys.publicKey as FeedId
}
return this.store.getFeed(feedId)
}
private onFeedReady = async (feed: Feed) => {
this.notify({ type: 'ActorFeedReady', actor: this, writable: feed.writable, feed })
feed.on('close', this.onClose)
if (!feed.writable) {
feed.on('download', this.onDownload)
feed.on('sync', this.onSync)
}
let hasData = false
let sequenceNumber = 0
const data = await this.store.stream(this.id)
data.on('data', (chunk) => {
this.parseBlock(chunk, sequenceNumber)
sequenceNumber += 1
hasData = true
})
data.on('end', () => {
this.q.subscribe((f) => f(this))
if (hasData) this.onSync()
})
}
private onDownload = (index: number, data: Uint8Array) => {
this.parseBlock(data, index)
const time = Date.now()
const size = data.byteLength
this.notify({ type: 'Download', actor: this, index, size, time })
}
private onSync = () => {
log('sync feed', ID(this.id))
this.notify({ type: 'ActorSync', actor: this })
}
private onClose = () => {
this.close()
}
private parseBlock(data: Uint8Array, index: number) {
const change: Change = Block.unpack(data) // no validation of Change
this.changes[index] = change
log(`block xxx idx=${index} actor=${ID(change.actor)} seq=${change.seq}`)
}
}
|
6769d1f4c30c3c8ad042d153bf2293f08fa10e92
|
TypeScript
|
250391Ivan/Ejercicio-Angular-5
|
/src/app/carros/carros.component.ts
| 2.546875
| 3
|
//Este componente se encarga de realizr mis funciones que voy a utilizar el las vistas y las tuberias.
import { Component, OnInit } from '@angular/core';
import { NgModule } from '@angular/core';
//se importa el nombre del servicio
import { PeticionesService } from '../services/peticiones.service';
@Component({
selector: 'app-carros',
templateUrl: './carros.component.html',
styleUrls: ['./carros.component.css'],
providers:[PeticionesService]
})
export class CarrosComponent implements OnInit {
// se declaran las variables a utilizar
public nombre:any;
public color:any;
public resultado:Array<any>;
public id_new:any;
public det_monedas:Array<any>;
public bandera:any;
public fecha:any;
public bandera_lista:any;
constructor(
private _peticionesService:PeticionesService
) {
}
//al cargar la pagina me trae el primer json y lo almaceno en una variable tipo array para poder manipularlo
ngOnInit() {
this._peticionesService.getDatos().subscribe(
result =>{
console.log(result['data']);
this.resultado=result['data'];
},
error =>{
var err =' ALGO SALIO MAL';
console.log(err);
}
);
}
//Cuando selecciono un tipo de moneda le paso el id para obtener los detalles del segundo metodo del json
//Encontre que para los id pares no siempre se tienen detalles
//Quise agregar una validacion para cuando no se tuviera info se enviara un json comentando esta detalle
//por falta de tiempo ya no lo pude implementar
id_moneda(id) {
console.log('-- click moneda---');
console.log(id);
this.bandera=true;
this.bandera_lista=true;
this.fecha = Date.now();
console.log(this.fecha);
this._peticionesService.getDetalles().subscribe(
result =>{
console.log(result['data'][id]);
this.det_monedas=result['data'][id];
},
error =>{
var err =' error en los datos';
console.log(err);
}
);
;
}
return(){
this.bandera_lista=false;
}
}
|
5b8e6d99f6b4444de55bddc613cb0f2e1518606e
|
TypeScript
|
WooodHead/codelab.ai
|
/libs/backend/src/core/domain/AggregateRoot.ts
| 2.765625
| 3
|
import { AggregateRoot as NestjsAggregateRoot } from '@nestjs/cqrs'
import { Type, classToPlain, plainToClass } from 'class-transformer'
import { ClassType } from 'class-transformer/ClassTransformer'
import { TransformBoth } from '../../common/TransformBoth'
import { BaseTypeOrm } from '../../infrastructure/persistence/typeorm/entity/BaseTypeOrm'
import { ValueObjectProps } from './ValueObject'
import { NOID } from './valueObject/NOID'
import { UUID } from './valueObject/UUID'
export abstract class AggregateRoot<
P extends ValueObjectProps = ValueObjectProps,
ID extends UUID | NOID = UUID
> extends NestjsAggregateRoot {
@Type(() => UUID)
@TransformBoth(UUID)
declare id: ID
constructor(props: P) {
super()
Object.assign(this, props)
}
toPlain() {
return classToPlain(this)
}
abstract toPersistence(): BaseTypeOrm
/**
* @typeparam T Domain class of model
* @typeparam M TypeOrm class of model
*
* @param this Domain class
* @param typeOrmModel
*/
// static hydrate<T, Props extends ValueObjectProps>(
// this: new (props: Props) => T,
// props: Props,
// ): T {
// const { id, ...restProps } = props
// if (id === undefined) {
// return plainToClass(this, restProps)
// }
// return plainToClass(this, props)
// }
static hydrate<T extends AggregateRoot, V>(cls: ClassType<T>, obj: V): T {
return plainToClass(cls, obj)
}
static hydrateArray<T extends AggregateRoot, V>(
cls: ClassType<T>,
obj: Array<V>,
): Array<T> {
return plainToClass(cls, obj)
}
}
|
15ebddc9fae6f88620630279467f827d37bee23e
|
TypeScript
|
steveperkins/co-forage
|
/src/models/SearchParams.ts
| 3.078125
| 3
|
/**
* API search parameters. Clients can search for product inventory state reports by
* location (geocoordinate or geohash) and radius, a known store (storeId), and
* either a barcode or start of a product's generic name (category).
*
* If `storeId` is provided, all other geolocation attributes are ignored.
* If `geohash` is provided, `lat` and `lng` are ignored but `radius` is respected.
* If `barcode` is provided, `genericName` is ignored.
*/
export class SearchParams {
/**
* User's position latitude
*/
lat: string
/**
* User's position longitude
*/
lng: string
/**
* User's geocoordinate as a geohash. Required only if lat and lng are not provided.
*/
geohash: string
radius: number = 1 // radius in miles
/**
* Barcode to search for. One of barcode or genericName is required.
*/
barcode: string
/**
* Optional prefix for searching product generic names
*/
genericName: string
/**
* Optional store ID. If a store ID is provided, lat/lng, geohash, and radius are ignored.
*/
storeId: number
}
|
501e0d8831b2bd8b44ab88fb00642d35296d9b12
|
TypeScript
|
KeesCBakker/hubot-command-mapper
|
/src/entities/parameters/ChoiceParameter.ts
| 3.5
| 4
|
import { ParameterBase } from "./ParameterBase"
import { escapeRegExp } from "../../utils/regex"
/**
* Parameter that has a fixed set of values. Remember all values
* are not case sensitive.
*
* @export
* @class ChoiceParameter
* @extends {ParameterBase}
*/
export class ChoiceParameter extends ParameterBase {
/**
* Will only capture the choices.
*
* @readonly
* @memberof ChoiceParameter
*/
public get regex() {
return `${this.values.map(v => escapeRegExp(v)).join("|")}`
}
/**
* Creates an instance of ChoiceParameter.
* @param {string} name The name of the parameter. Can be used to identify the parameter value as well.
* @param {string[]} values The array of possible values.
* @param {any} [defaultValue=null] When a value is given, the parameter becomes optional.
* @memberof ChoiceParameter
*/
constructor(
name: string,
public values: string[],
public defaultValue: string = null
) {
super(name, defaultValue)
}
}
|
06fa76aadfb5cf32c5e08f9a30eb20fc70bbc2c9
|
TypeScript
|
cgronseth/SPToolBox
|
/src/spt.storage.ts
| 2.953125
| 3
|
import { SPData } from "./sharepoint/spt.sharepoint.entities";
export interface IListItemLight {
ID: number;
Author: string;
Editor: string;
Created: Date;
Modified: Date;
File?: {
FilePath: string;
FileName: string;
Length: number;
}
ItemData?: SPData[];
}
export interface ICopyPasteInstruction {
site: string;
listId: string;
listType: number;
items?: IListItemLight[];
}
/**
* Storage helper class that deals with webextension storage API and exposes "simple to use" functions for common usage
*/
export class WebExStorage {
private static readonly storageKeyInfo = "sptStorageCyPInfo";
private static readonly storageKeyData = "sptStorageCyPData";
/**
* Retrieve info of C&P Instuctions
*/
public static info(): Promise<ICopyPasteInstruction> {
return new Promise<ICopyPasteInstruction>((resolve, reject) => {
try {
browser.storage.local.get(this.storageKeyInfo).then((result: any) => {
if (result[this.storageKeyInfo]) {
resolve({
site: result[this.storageKeyInfo].site,
listId: result[this.storageKeyInfo].listId,
listType: result[this.storageKeyInfo].listType
});
}
resolve(null);
}, (e) => {
reject("Error in Storage.Info: " + e);
});
} catch (e) {
reject("Exception in Storage.Info: " + e);
}
});
}
/**
* Read and Delete C&P Items from storage
*/
public static get(): Promise<ICopyPasteInstruction> {
return new Promise<ICopyPasteInstruction>((resolve, reject) => {
try {
let getPromiseInfo = new Promise<any>((resolve, reject) => {
browser.storage.local.get(this.storageKeyInfo).then((result) => {
resolve((result[this.storageKeyInfo]) ? result[this.storageKeyInfo] as any : {});
}, (e) => { reject("Error al leer storage list id: " + e) });
});
let getPromiseData = new Promise<IListItemLight[]>((resolve, reject) => {
browser.storage.local.get(this.storageKeyData).then((result) => {
resolve((result[this.storageKeyData]) ? result[this.storageKeyData] as unknown as IListItemLight[] : []);
}, (e) => { reject("Error al leer storage data: " + e) });
});
Promise.all([getPromiseInfo, getPromiseData]).then((resultados) => {
resolve({
site: resultados[0].site,
listId: resultados[0].listId,
listType: resultados[0].listType,
items: resultados[1]
});
}, (e) => {
reject("Error in Storage.Get promise all: " + e);
}).finally(() => {
// Delete storage used
this.clear();
});
} catch (e) {
reject("Exception in Storage.Get: " + e);
}
});
}
/**
* Delete storage entries used in this application
*/
public static clear(): Promise<void> {
return new Promise<void>((resolve, reject) => {
try {
let promiseClearBatch: Promise<void>[] = [
browser.storage.local.remove(this.storageKeyInfo),
browser.storage.local.remove(this.storageKeyData)
];
Promise.all(promiseClearBatch).then(() => {
resolve();
}, (e) => {
reject("Error in Storage.Clear promise all: " + e);
});
} catch (e) {
reject("Exception in Storage.Clear: " + e);
}
});
}
/**
* Save C&P Items to storages
* @param cpInstruction
*/
public static set(cpInstruction: ICopyPasteInstruction): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
try {
let info: any = {
[this.storageKeyInfo]: {
site: cpInstruction.site,
listId: cpInstruction.listId,
listType: cpInstruction.listType
}
};
browser.storage.local.set(info).then(() => {
let data: any = {
[this.storageKeyData]: cpInstruction.items
};
browser.storage.local.set(data).then(() => {
resolve(true);
}, (e) => {
reject("Error al escribir Items en storage: " + e);
});
}, (e) => {
reject("Error al escribir Info en storage: " + e);
});
} catch (e) {
reject("Exception in Storage.Set: " + e);
}
});
}
public static size(): Promise<number> {
let items: string[] = [this.storageKeyInfo, this.storageKeyData];
return new Promise<number>((resolve) => {
browser.storage.local.get(items).then((result) => {
resolve(JSON.stringify(result).length);
});
});
}
}
|
84629c0d4b44c2d4b63697737817dfc8c39cf2b8
|
TypeScript
|
PennOhio/uniswap-v3-simulator
|
/src/util/LiquidityMath.ts
| 2.71875
| 3
|
import JSBI from "jsbi";
import { NEGATIVE_ONE, ZERO, MaxUint128 } from "../enum/InternalConstants";
import assert from "assert";
export abstract class LiquidityMath {
static addDelta(x: JSBI, y: JSBI): JSBI {
assert(JSBI.lessThanOrEqual(x, MaxUint128), "OVERFLOW");
assert(JSBI.lessThanOrEqual(y, MaxUint128), "OVERFLOW");
if (JSBI.lessThan(y, ZERO)) {
const negatedY = JSBI.multiply(y, NEGATIVE_ONE);
assert(JSBI.greaterThanOrEqual(x, negatedY), "UNDERFLOW");
return JSBI.subtract(x, negatedY);
} else {
assert(JSBI.lessThanOrEqual(JSBI.add(x, y), MaxUint128), "OVERFLOW");
return JSBI.add(x, y);
}
}
}
|
ebfce70f5652a46048c84a9db161b9e0f2cbd371
|
TypeScript
|
TrumanGao/trumangao-utils
|
/src/utils/cryptoJs.ts
| 3.0625
| 3
|
import cryptoJS from "crypto-js";
export class CryptoJS {
key: cryptoJS.lib.WordArray;
iv: cryptoJS.lib.WordArray;
constructor(key: string, iv: string) {
this.key = cryptoJS.enc.Utf8.parse(key);
this.iv = cryptoJS.enc.Utf8.parse(iv);
}
/**
* AES 加密
*/
aesEncrypt(message: string | cryptoJS.lib.WordArray) {
const ciphertext = cryptoJS.AES.encrypt(message, this.key, {
iv: this.iv,
}).toString();
return encodeURIComponent(ciphertext);
}
/**
* AES 解密
*/
aesDecrypt(ciphertext: string | cryptoJS.lib.CipherParams) {
const bytes = cryptoJS.AES.decrypt(ciphertext, this.key, {
iv: this.iv,
}).toString(cryptoJS.enc.Utf8);
return decodeURIComponent(bytes);
}
/**
* HmacSHA1 加密
* @param message — The message to hash.
* @param key — The secret key.
*/
HmacSHA1Encode(message: string | cryptoJS.lib.WordArray) {
return cryptoJS.HmacSHA1(message, this.key).toString();
}
/**
* 生成随机数
* @param nBytes — The number of random bytes to generate.
*/
getRandom(nBytes: number) {
const wordArray = cryptoJS.lib.WordArray.random(nBytes);
return cryptoJS.enc.Hex.stringify(wordArray);
}
}
|
a890871fade0c1265c358b7cd34fd4f6a2f591ad
|
TypeScript
|
Sts0mrg0/encodable
|
/packages/encodable/test/typeGuards/Scale.test.ts
| 2.890625
| 3
|
import {
scaleLinear,
scaleOrdinal,
scaleTime,
scaleLog,
scaleThreshold,
scaleQuantize,
scaleQuantile,
} from 'd3-scale';
import { isTimeScale, isContinuousScale, isDiscretizingScale } from '../../src/typeGuards/Scale';
import { StringLike } from '../../src/types';
describe('type guards', () => {
describe('isContinuousScale(scale, type)', () => {
it('returns true if type is one of the continuous scale types', () => {
expect(isContinuousScale(scaleLinear<number>(), 'linear')).toBeTruthy();
});
it('returns false otherwise', () => {
expect(isContinuousScale(scaleOrdinal<StringLike, string>(), 'ordinal')).toBeFalsy();
});
});
describe('isDiscretizingScale(scale, type)', () => {
it('returns true if type is one of the discretizing scale types', () => {
expect(
isDiscretizingScale<number>(scaleThreshold<string | number | Date, number>(), 'threshold'),
).toBeTruthy();
expect(isDiscretizingScale<number>(scaleQuantize<number>(), 'quantize')).toBeTruthy();
expect(isDiscretizingScale<number>(scaleQuantile<number>(), 'quantile')).toBeTruthy();
});
it('returns false otherwise', () => {
expect(isDiscretizingScale(scaleLinear<number>(), 'linear')).toBeFalsy();
});
});
describe('isTimeScale(scale, type)', () => {
it('returns true if type is one of the time scale types', () => {
expect(isTimeScale(scaleTime<number>(), 'time')).toBeTruthy();
expect(isTimeScale(scaleTime<number>(), 'utc')).toBeTruthy();
});
it('returns false otherwise', () => {
expect(isTimeScale(scaleLinear<number>(), 'linear')).toBeFalsy();
expect(isTimeScale(scaleLog<number>(), 'log')).toBeFalsy();
});
});
});
|
a5854fb653abe710d005d65c16bd4f03d61e7094
|
TypeScript
|
daxingyou/Racing
|
/H5/Client/src/MyUI/Welfare/Components/OnlineItemRender.ts
| 2.546875
| 3
|
namespace MyUI.Welfare {
/**
* 在线奖励列表项
*/
export class OnlineItemRender extends ui.Welfare.Components.OnlineItemRenderUI {
private mNeedTime: number; // 领奖需要的在线时间(秒)
private mCurGetState: RewardState; // 当前领奖状态
private mGetGoodsStopIdx: number; // 抽到的物品所在列表的索引
private mLoopNumOfTimes: number; // 列表转动的次数
private mFrameMoveDist: number; // 列表每帧移动的距离
constructor() {
super();
this._goodsList.vScrollBarSkin = "";
this._goodsList.scrollBar.mouseWheelEnable = false;
this._goodsList.scrollBar.touchScrollEnable = false;
this._progTime.visible = false;
this._imgState.visible = false;
this._txtState.text = "";
this.mCurGetState = RewardState.Invalid;
}
/** @override */
public destroy(destroyChild?: boolean) {
super.destroy(destroyChild);
}
/**
* 设置领奖需要的在线时间
* @param nTime 时间(分钟)
*/
public setNeedTime(nTime: number) {
this.mNeedTime = nTime * 60;
this._txtTime.text = Global.String.Format(ConfigLoca.UI_Time_Format_OnlyMinute, nTime);
}
/**
* 设置奖励道具列表
* @param aGoodsIds 道具Id列表
*/
public setGoodsList(aGoodsIds: number[]) {
// 多加一个道具到列表的末位,为了列表转动时的效果更真实(在转到最后的时候会把列表突然拉到头,会从最后一个道具突然切换成第一个道具)
const aNewGoodsIds = aGoodsIds.concat(aGoodsIds[0]);
this._goodsList.array = aNewGoodsIds;
}
/**
* 设置已经在线的时间
* @param nTime 时间(秒)
* @returns true=可以领奖、false=不可领奖
*/
public setOnlineTime(nTime: number): boolean {
if (nTime < this.mNeedTime) {
this.curGetState = RewardState.Not;
this._progTime.value = nTime / this.mNeedTime;
return false;
} else {
this.curGetState = RewardState.Can;
return true;
}
}
/**
* 设置已经在线的时间,用于客户端时间Tick更新调用
* @param nTime 时间(秒)
* @returns true=可以领奖、false=不可领奖
*/
public setOnlineTimeWithTicks(nTime: number): boolean {
if (this.mCurGetState === RewardState.Had) {
return false;
}
return this.setOnlineTime(nTime);
}
/**
* 设置抽到的物品Id
* @param nGoodsId 道具Id
*/
public setGetGoodsId(nGoodsId: number) {
const nIdIdx = this._goodsList.array.findIndex(element => element === nGoodsId);
Global.Log.Assert(nIdIdx !== -1, `error!!! online item goods(${nGoodsId}) not found.`);
this._goodsList.scrollTo(nIdIdx);
this.curGetState = RewardState.Had;
}
/**
* 设置抽到的物品Id,并播放抽奖动画
* @param nGoodsId 道具Id
*/
public setGetGoodsIdWithAnimation(nGoodsId: number) {
this.mGetGoodsStopIdx = this._goodsList.array.findIndex(element => element === nGoodsId);
Global.Log.Assert(this.mGetGoodsStopIdx !== -1, `error!!! animation online item goods(${this.mGetGoodsStopIdx}) not found.`);
// this.mGetGoodsStopIdx = (this._goodsList.array.length * Math.random()) | 0; // 测试时随机转动停止
this.mLoopNumOfTimes = 0;
this.afterOneLoopComplete();
}
/**
* 物品转动动画
*/
public onFrameMove(): boolean {
this._goodsList.scrollBar.value += this.mFrameMoveDist;
const nStartIdx = this._goodsList.startIndex;
if (this.mLoopNumOfTimes > 6 && nStartIdx === this.mGetGoodsStopIdx) {
this._goodsList.scrollTo(this.mGetGoodsStopIdx);
this.curGetState = RewardState.Had;
return true;
}
if (nStartIdx === this._goodsList.length - 1) {
this.afterOneLoopComplete();
}
return false;
}
/**
* 一圈转动完成后
*/
private afterOneLoopComplete() {
this._goodsList.scrollBar.value = 0;
this.mLoopNumOfTimes++;
if (this.mLoopNumOfTimes < 4) { // 快速转三圈
this.mFrameMoveDist = 20;
} else if (this.mLoopNumOfTimes < 6) { // 中速转两圈
this.mFrameMoveDist = 10;
} else if (this.mLoopNumOfTimes === 6) { // 最后一圈慢速
this.mFrameMoveDist = 5;
}
}
/**
* 设置当前领奖状态
*/
private set curGetState(value: RewardState) {
if (this.mCurGetState !== value) {
this.mCurGetState = value;
value === RewardState.Not && this.updateNotGetState();
value === RewardState.Can && this.updateCanGetState();
value === RewardState.Had && this.updateHadGetState();
}
}
/**
* 更新未领取状态
*/
private updateNotGetState() {
this._progTime.visible = true;
this._imgState.visible = false;
this._txtState.text = "";
}
/**
* 更新可领取状态
*/
private updateCanGetState() {
this._progTime.visible = false;
this._imgState.visible = true;
this._imgState.skin = Global.getWelfareAtlasImgPath("online_state_can");
this._txtState.text = ConfigLoca.UI_Welfare_Reward_CanExtract;
this._txtState.color = "#afdcff";
}
/**
* 更新已领取状态
*/
private updateHadGetState() {
this._progTime.visible = false;
this._imgState.visible = true;
this._imgState.skin = Global.getWelfareAtlasImgPath("online_state_had");
this._txtState.text = ConfigLoca.UI_Reward_HadGet;
this._txtState.color = "#536f90";
}
}
}
|