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 |
|---|---|---|---|---|---|---|
afa140d252408bf2d217c608c438e5a90da5e4f5 | TypeScript | da-peng/common-manager | /server/src/utils/string_utils.ts | 2.890625 | 3 | import * as uuid from 'uuid';
import * as crypto from 'crypto';
import {config} from '../config/config'
export class StringUtil{
private static md5(str: string): string {
return crypto.createHash('md5').update(str).digest('hex');
}
static md5Password(password: string): string {
return config.encryptPassword ? this.md5(password) : password;
}
static encrypt(str: string): string {
const cipher = crypto.createCipher('aes-256-cbc',config.encryptKey);
let rst = cipher.update(str, 'utf8', 'base64');
rst += cipher.final('base64');
return rst;
}
static decrypt(str: string): string {
const decipher = crypto.createDecipher('aes-256-cbc', config.encryptKey);
let rst = decipher.update(str, 'base64', 'utf8');
rst += decipher.final('utf8');
return rst;
}
static unitConvertToInt=(i:string)=>{
if (i.match(/万/)){
return parseInt(i.replace('万',''))*10000
}
return parseInt(i)
}
} |
a29b6f71f5fdd35d31d82d505375504c0114d685 | TypeScript | SAP/ui5-webcomponents | /packages/main/src/MultiComboBoxGroupItem.ts | 2.59375 | 3 | import customElement from "@ui5/webcomponents-base/dist/decorators/customElement.js";
import property from "@ui5/webcomponents-base/dist/decorators/property.js";
import UI5Element from "@ui5/webcomponents-base/dist/UI5Element.js";
import type { IMultiComboBoxItem } from "./MultiComboBox.js";
/**
* @class
* The <code>ui5-mcb-group-item</code> is type of suggestion item,
* that can be used to split the <code>ui5-multi-combobox</code> suggestions into groups.
*
* @constructor
* @author SAP SE
* @alias sap.ui.webc.main.MultiComboBoxGroupItem
* @extends sap.ui.webc.base.UI5Element
* @abstract
* @tagname ui5-mcb-group-item
* @public
* @implements sap.ui.webc.main.IMultiComboBoxItem
* @since 1.4.0
*/
@customElement("ui5-mcb-group-item")
class MultiComboBoxGroupItem extends UI5Element implements IMultiComboBoxItem {
/**
* Defines the text of the component.
*
* @type {string}
* @name sap.ui.webc.main.MultiComboBoxGroupItem.prototype.text
* @defaultvalue ""
* @public
*/
@property()
text!: string;
/**
* Used to avoid tag name checks
* @protected
*/
get isGroupItem() {
return true;
}
get selected() {
return false;
}
get stableDomRef() {
return this.getAttribute("stable-dom-ref") || `${this._id}-stable-dom-ref`;
}
}
MultiComboBoxGroupItem.define();
export default MultiComboBoxGroupItem;
|
210db4934fb6fa3d40d5f493d7b0f8fc4c3e9421 | TypeScript | FernandoCuevasFeliz/api-login-role | /src/utils/JWT.ts | 2.671875 | 3 | import jwt from 'jsonwebtoken';
class JWT {
private static secretKey = process.env.SECRET_KEY || 'secretkey';
static generateToken(payload: IPayload, expiresIn: number | string = '24h') {
const token = jwt.sign(payload, this.secretKey, {
expiresIn
});
return token;
}
static verifyToken(token: string) {
const payload = jwt.verify(token, this.secretKey) as IPayload;
return payload;
}
}
export default JWT;
|
29dc6826d1fe4eaadbbcf10611b0a2d823e31745 | TypeScript | TiStrong/types | /types/titanium/Titanium/UI/Font.d.ts | 3.421875 | 3 | /**
* An abstract datatype for specifying a text font.
*/
interface Font {
/**
* Specifies the font family or specific font to use.
*/
fontFamily?: string;
/**
* Font size, in platform-dependent units.
*/
fontSize?: number | string;
/**
* Font style. Valid values are "italic" or "normal".
*/
fontStyle?: string;
/**
* Font weight. Valid values are "bold", "semibold", "normal", "thin",
* "light" and "ultralight".
*/
fontWeight?: string;
/**
* The text style for the font.
*/
textStyle?: string;
}
|
5a2a3ef35e52d2818d94dedfbb8b828a82cbbbaa | TypeScript | mjshoemake/StoreGuideUI | /angular/src/app/users/users.service.ts | 2.703125 | 3 | import { Injectable } from '@angular/core';
import { User } from './user';
import { LogService } from '../log.service';
import {BehaviorSubject} from "rxjs/BehaviorSubject";
import {Observable} from "rxjs/Observable";
@Injectable()
// NOTE: For now, there is no DB so data is stored in memory only.
export class UsersService {
log: LogService;
// List of users
users: User[] = [];
nextID: number = 1001;
private _observableList: BehaviorSubject<User[]> = new BehaviorSubject([]);
get observableList(): Observable<User[]> {
return this._observableList.asObservable()
}
constructor(private _logger:LogService) {
this.log = _logger;
this.log.info('UsersService.constructor() BEGIN');
}
loadUsersList() {
this.log.info('UsersService.loadUsersList()');
this.users = [];
this.users.push(new User({
user_pk: 1,
username: "atlantatechie@gmail.com",
first_name: "Mike",
last_name: "Shoemake"}));
this.users.push(new User({
user_pk: 2,
username: "mshoemake2@gmail.com",
first_name: "Michelle",
last_name: "Shoemake"}));
this._observableList.next(this.users);
}
getUserByPK(_user_pk: number): User {
for (let i = 0; i < this.users.length; i++) {
let next: User = this.users[i];
if (next.user_pk == _user_pk) {
return next;
}
}
throw new Error('Unable to find a user with the specified ID.');
}
getUser(_username: string): User {
for (let i = 0; i < this.users.length; i++) {
let next: User = this.users[i];
if (next.username == _username) {
return next;
}
}
throw new Error('Unable to find a user with the specified username (' + _username + ').');
}
addUser(_user: User) {
_user.user_pk = this.nextID++;
this.users.push(_user);
this.sortList();
this.log.info("Added user " + _user.username + ".");
this.logUsersList();
}
updateUser(_user: User) {
for (let i = 0; i < this.users.length; i++) {
let next: User = this.users[i];
if (next.user_pk == _user.user_pk) {
next.username = _user.username;
next.last_name = _user.last_name;
next.first_name = _user.first_name;
next.image_url = _user.image_url;
return;
}
}
throw new Error('Unable to find a user with matching primary key.');
}
deleteUser(_user: User) {
for (let i = 0; i < this.users.length; i++) {
let next: User = this.users[i];
if (next.user_pk == _user.user_pk) {
this.users.splice(i, 1);
return;
}
}
throw new Error('Unable to find a user with matching primary key.');
}
sortList() {
this.users.sort(this.sortBy("username", false, undefined));
this.log.info("Sorted user list.");
this.logUsersList();
}
sortBy(field: string, reverse: boolean, primer) {
var key = primer ?
function(x) {return primer(x[field])} :
function(x) {return x[field]};
let nReverse: number = !reverse ? 1 : -1;
return function (a, b) {
let result: number = 0;
let valueA = key(a);
let valueB = key(b);
if (valueA > valueB) {
result = 1;
} else if (valueA < valueB) {
result = -1;
} else {
result = 0;
}
console.log(" Sorting... " + valueA + ", " + valueB + " result=" + result);
return a = valueA, b = valueB, nReverse * result;
}
}
logUsersList() {
this.log.info("Users:");
for (let i = 0; i < this.users.length; i++) {
let next: User = this.users[i];
this.log.info(" [" + (i+1) + "]:");
this.log.info(" user_pk: " + next.user_pk);
this.log.info(" username: " + next.username);
this.log.info(" first_name: " + next.first_name);
this.log.info(" last_name: " + next.last_name);
}
}
}
|
4a1c1ac15148fb9ff76ded5c63c75ab02591238f | TypeScript | MFvandenBos/angularbd2020 | /src/app/pipes/dutch-euro.pipe.ts | 2.578125 | 3 | import { Pipe, PipeTransform } from '@angular/core';
import {CurrencyPipe} from '@angular/common';
@Pipe({
name: 'dutchEuro'
})
export class DutchEuroPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
const currencyPipe = new CurrencyPipe('nl');
// Een geheel getal wordt default door currency pipe met ,00 afgebeeld
// Misschien moet dit wel een eigen test krijgen?
const rawOutput = currencyPipe.transform(value , 'EUR');
return rawOutput.replace(',00', '');
}
}
|
1d1347fa4ec94144895634faef4285b33f949f26 | TypeScript | johncomposed/remote-faces | /web/src/hooks/useSpatialArea.ts | 2.6875 | 3 | import { useCallback, useState, useRef, useEffect } from "react";
import { isObject } from "../utils/types";
import { useRoomData, useBroadcastData } from "./useRoom";
export type AvatarData = {
position: [number, number, number];
};
const isAvatarData = (x: unknown): x is AvatarData => {
try {
const obj = x as AvatarData;
if (
typeof obj.position[0] !== "number" ||
typeof obj.position[1] !== "number" ||
typeof obj.position[2] !== "number"
) {
return false;
}
return true;
} catch (e) {
return false;
}
};
export type AvatarMap = {
[userId: string]: AvatarData;
};
type SpatialAreaData =
| {
spatialArea: "init";
}
| {
spatialArea: "avatar";
userId: string;
avatarData: AvatarData;
};
const isSpatialAreaData = (x: unknown): x is SpatialAreaData =>
isObject(x) &&
((x as { spatialArea: unknown }).spatialArea === "init" ||
((x as { spatialArea: unknown }).spatialArea === "avatar" &&
isAvatarData((x as { avatarData: unknown }).avatarData)));
export const useSpatialArea = (roomId: string, userId: string) => {
const [avatarMap, setAvatarMap] = useState<AvatarMap>({});
const [myAvatar, setMyAvatar] = useState<AvatarData>();
const lastMyAvatarRef = useRef<AvatarData>();
useEffect(() => {
lastMyAvatarRef.current = myAvatar;
}, [myAvatar]);
const broadcastData = useBroadcastData(roomId, userId);
const dataToBroadcast = useRef<SpatialAreaData>();
useEffect(() => {
if (!myAvatar) return;
const data: SpatialAreaData = {
spatialArea: "avatar",
userId,
avatarData: myAvatar,
};
if (dataToBroadcast.current) {
dataToBroadcast.current = data;
} else {
dataToBroadcast.current = data;
setTimeout(() => {
broadcastData(dataToBroadcast.current);
dataToBroadcast.current = undefined;
}, 200);
}
}, [broadcastData, userId, myAvatar]);
useRoomData(
roomId,
userId,
useCallback(
(data) => {
if (!isSpatialAreaData(data)) return;
if (data.spatialArea === "init") {
if (lastMyAvatarRef.current) {
// TODO we don't need to broadcastData but sendData is enough
broadcastData({
spatialArea: "avatar",
avatarData: lastMyAvatarRef.current,
});
}
} else if (data.spatialArea === "avatar") {
const uid = (data as { userId: string }).userId;
const { avatarData } = data as { avatarData: AvatarData };
setAvatarMap((prev) => ({
...prev,
[uid]: avatarData,
}));
}
},
[broadcastData]
)
);
useEffect(() => {
broadcastData({
spatialArea: "init",
});
}, [broadcastData]);
return {
avatarMap,
myAvatar,
setMyAvatar,
};
};
|
3d90d4c741639463602627aa9383f0dbe8dfb795 | TypeScript | shifucun/website | /static/js/tools/map/condition_hooks.ts | 2.546875 | 3 | /**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This module contains custom React hooks that checks conditions.
import { useContext, useMemo } from "react";
import { Context } from "./context";
// Custom hook to check if needs to compute ratio for the stat.
export function useIfRatio() {
const { statVar } = useContext(Context);
return useMemo(() => {
return !!statVar.value.perCapita && !!statVar.value.denom;
}, [statVar.value.perCapita, statVar.value.denom]);
}
|
1cc0458676778889ab8e333cc18bd967f11a012d | TypeScript | jcamden/merninator | /packages/client/src/context/projects/projectsReducer.ts | 2.75 | 3 | import { IProjectsState, ProjectsActions } from '@merninator/types';
export const projectsReducer = (draft: IProjectsState, action: ProjectsActions): void => {
switch (action.type) {
// Set projects is called when the projects page loads
// If there are no projects matching the User._id, the state.projects ends up undefined
case 'setProjects': {
draft.projects = action.payload;
return;
}
case 'addProject': {
// If state.projects is not undefined as per init setProjects, push; otherwise, newly define it.
draft.projects ? draft.projects.push(action.payload) : (draft.projects = [action.payload]);
return;
}
case 'removeProject': {
draft.projects.filter(project => project !== action.payload);
return;
}
case 'toggleProjectCompleted': {
try {
const index = draft.projects.findIndex(item => item.self === action.payload);
draft.projects[index].completed = !draft.projects[index].completed;
} catch (error) {
console.log("The appropriate project could not be found. That's weird!");
}
return;
}
}
};
|
ce1cd328713a07c4caddb21bb4a809ed0dbfd032 | TypeScript | villagestyle/note | /js && ts/leetcode/867.转置矩阵.ts | 3.140625 | 3 | /*
* @lc app=leetcode.cn id=867 lang=typescript
*
* [867] 转置矩阵
*/
// @lc code=start
function transpose(A: number[][]): number[][] {
const row = A.length;
const col = A[0].length;
const newArr = Array.from(new Array(col), () => new Array(row));
for (let i = 0; i < col; i ++) {
for (let j = 0; j < row; j ++) {
newArr[i][j] = A[j][i]
}
}
return newArr;
};
// @lc code=end
|
b39443bac21bdc56dbc490ee0f28758dad8723cc | TypeScript | DjihadBengati/daily-coding-problem | /google_12_06_2020/solution_google_12_06_2020.ts | 3.5 | 4 | function solutionGoogle12062020(values: Array<number>, k: number): Boolean {
return values.length == 0 ? false : doCkecks(k, values[0], values.slice(1, values.length));
}
function doCkecks(k: number, value: number, values: Array<number>): Boolean {
for (let index = 0; index < values.length; index++) {
if ((values[index] + value) === k) {
return true;
}
}
return solutionGoogle12062020(values, k);
}
console.log('Input: k = ' + 17);
console.log('Input: values = [' + [10, 15, 3, 7] + ']');
console.log(solutionGoogle12062020([10, 15, 3, 7], 17)); |
888f0e745fb65a2bf8bf7541802cd68c99156b52 | TypeScript | ralphcasipe1/pet-gram | /src/models/Pet.ts | 2.578125 | 3 | import * as mongoose from 'mongoose'
const Schema = mongoose.Schema
const Pet = new Schema({
petType: {
type: 'ObjectId',
ref: 'PetType',
required: 'Enter the type of the pet'
},
name: {
type: String,
required: 'Enter a name'
},
createdAt: {
type: Date,
default: Date.now()
}
})
export default mongoose.model('Pet', Pet) |
0b6ebb40442cfb404dab02565d6b057953d4ac88 | TypeScript | redmagebr/redpgBeta | /app/Kinds/Classes/Sheet/SheetStyle.ts | 2.6875 | 3 | class SheetStyle {
private css : HTMLStyleElement = <HTMLStyleElement> document.createElement("style")
private visible : HTMLElement = document.createElement("div");
private $visible : JQuery = $(this.visible);
protected styleInstance : StyleInstance;
protected sheet : Sheet;
protected sheetInstance : SheetInstance;
protected multipleChanges : boolean = false;
protected pendingChanges : Array<SheetVariable> = [];
protected changeCounter : number = 0;
protected idCounter = 0;
protected after : Function = function () {};
constructor () {
this.visible.setAttribute("id", "sheetDiv");
this.css.type = "text/css";
}
public getUniqueID () {
return "undefined" + (this.idCounter++);
}
public simplifyName (str : String) {
return (<Latinisable> str).latinise().toLowerCase().replace(/ /g,'');
}
public addStyle (style : StyleInstance) {
this.styleInstance = style;
this.visible.innerHTML = style.html;
this.css.innerHTML = style.css;
this.sheet = new Sheet(this, this.visible.childNodes);
this.after();
}
public triggerVariableChange (variable : SheetVariable) {
if (this.multipleChanges) {
this.pendingChanges.push(variable);
} else {
variable.triggerChange(this.changeCounter++);
}
}
public triggerAll () {
for (var i = 0; i < this.pendingChanges.length; i++) {
this.pendingChanges[i].triggerChange(this.changeCounter);
}
this.changeCounter += 1;
this.pendingChanges = [];
}
public getStyle () {
return this.css;
}
public getElement () {
return this.visible;
}
public get$Element () {
return this.$visible;
}
} |
33935eaee63a6e0b473b033b32b6d6344cb7d7aa | TypeScript | einari/JavaScript.Fundamentals | /Source/rules/IRuleContext.ts | 2.984375 | 3 | // Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import { IRule } from './IRule';
import { BrokenRule } from './BrokenRule';
import { Cause } from './Cause';
/**
* Defines the context in which a rule is evaluated in.
*/
export interface IRuleContext {
/**
* Gets the owner for the context
* @returns {*}
*/
readonly owner: any;
/**
* Gets any broken rules
* @returns {Array<BrokenRule>}
*/
readonly brokenRules: BrokenRule[];
/**
* Fail for a specific rule, subject and a cause of failure.
* @param {IRule} rule - Rule to fail
* @param {*} subject - Subject that failed
* @param {Cause} cause - Cause of failure
*/
fail(rule: IRule, subject: any, cause: Cause): void;
}
|
4804e4d3a845efb41b2a823b3457913f3993b5ca | TypeScript | tisuela/popyt | /test/playlist.spec.ts | 2.5625 | 3 | import 'mocha'
import { expect } from 'chai'
import { Playlist, Video } from '../src'
import { youtube } from './setup-instance'
const apiKey = process.env.YOUTUBE_API_KEY
if (!apiKey) {
throw new Error('No API key')
}
describe('Playlists', () => {
it('should reject if the playlist isn\'t found', async () => {
expect(await youtube.getPlaylist('JSDJFSFaVeryFakePlaylist').catch(error => {
return error
})).to.equal('Item not found')
})
it('should work with proper IDs', async () => {
expect(await youtube.getPlaylist('PLMC9KNkIncKvYin_USF1qoJQnIyMAfRxl', [ 'id' ])).to.be.an.instanceOf(Playlist)
})
it('should work with proper URLs', async () => {
expect(await youtube.getPlaylist('https://www.youtube.com/playlist?list=PLMC9KNkIncKvYin_USF1qoJQnIyMAfRxl', [ 'id' ])).to.be.an.instanceOf(Playlist)
})
it('should work with single searching', async () => {
expect(await youtube.getPlaylist('best songs ever', [ 'id' ])).to.be.an.instanceOf(Playlist)
})
it('should work with fetching', async () => {
const playlist = await youtube.getPlaylist('PLMC9KNkIncKvYin_USF1qoJQnIyMAfRxl', [ 'id' ])
expect(await playlist.fetch([ 'id' ])).to.be.an.instanceOf(Playlist)
})
it('should work with fetching maxResults videos', async () => {
const playlist = await youtube.getPlaylist('PLMC9KNkIncKvYin_USF1qoJQnIyMAfRxl', [ 'id' ])
const videos = await playlist.fetchVideos(1, [ 'id' ])
expect(videos[0]).to.be.an.instanceOf(Video)
expect(playlist.videos[0].id).to.equal(videos[0].id)
})
it('should work with fetching all videos', async () => {
const playlist = await youtube.getPlaylist('PLMC9KNkIncKvYin_USF1qoJQnIyMAfRxl', [ 'id' ])
const videos = await playlist.fetchVideos(undefined, [ 'id' ])
expect(videos.length).to.be.lte(10)
expect(playlist.videos.length).to.be.lte(10)
})
it('should work with fetching channel playlists with maxResults', async () => {
const playlists = await youtube.getChannelPlaylists('UCBR8-60-B28hp2BmDPdntcQ', 5, [ 'id' ])
expect(playlists.length).to.equal(5)
expect(playlists[0]).to.be.an.instanceOf(Playlist)
})
it('should work with fetching channel playlists', async () => {
const playlists = await youtube.getChannelPlaylists('UC6mi9rp7vRYninucP61qOjg')
expect(playlists[0]).to.be.an.instanceOf(Playlist)
})
})
|
096459210104b3e3efb5a15c74815d908eaacd5f | TypeScript | mickys/account-manager | /src/modules/binance/account.ts | 2.5625 | 3 | import { GenericAccount, IaccountOptions } from "../../core/account";
import { BigNumber } from "bignumber.js";
import binance from "node-binance-api";
export class BinanceAccount extends GenericAccount {
public client;
public defaultGasPriceInGwei: number = 30;
private isLoggedIn: boolean = false;
constructor(accountOptions: IaccountOptions) {
super(accountOptions);
this.client = new binance().options({
APIKEY: accountOptions.apiKey,
APISECRET: accountOptions.apiSecret,
useServerTime: accountOptions.useServerTime,
test: accountOptions.sandbox,
});
}
public withdraw(
assetSymbol: string,
address: string,
amount: BigNumber,
addressTag?: string,
actionName?: string,
): Promise <number> {
addressTag = addressTag || "1";
actionName = actionName || 'API Withdraw';
return new Promise((resolve, reject) => {
try {
this.client.withdraw(
assetSymbol,
address,
amount.toString(),
addressTag,
((error, response) => {
// crappy API returning everything in response..
if (response.success === false) {
reject(response.msg);
} else {
resolve(response.msg);
}
}),
actionName,
);
} catch (error) {
throw new Error("call:" + error);
}
});
}
public transferToSubAccount(
assetSymbol: string,
amount: BigNumber,
): Promise <number> {
return new Promise((resolve, reject) => {
try {
this.client.mgTransferMainToMargin(
assetSymbol,
amount.toString(),
((error, response) => {
if (response) {
resolve(response);
}
}),
);
} catch (error) {
throw new Error("call:" + error);
}
});
}
public transferFromSubAccount(
assetSymbol: string,
amount: BigNumber,
): Promise <number> {
return new Promise((resolve, reject) => {
try {
this.client.mgTransferMarginToMain(
assetSymbol,
amount.toString(),
((error, response) => {
if (response) {
resolve(response);
}
}),
);
} catch (error) {
throw new Error("call:" + error);
}
});
}
}
|
4ed18b82a5e3bc0e8048969835c4736d39616e73 | TypeScript | JOLee83/coding-challenges | /code-wars/TS/6kyu/ConseccutiveStrings.ts | 3.3125 | 3 | export function longestConsec(strarr: string[], k: number): string {
let str: string = '';
if (k <= 0) {
return str;
}
for (let i: number = 0; i + k <= strarr.length; i++) {
const string = strarr.slice(i, i + k).join('');
if (string.length > str.length) {
str = string;
}
}
return str;
} |
c470c409a5ffb82d9b897c7546963f3756a1729c | TypeScript | haimkastner/unitsnet-js | /src/angle.g.ts | 3.578125 | 4 | /** AngleUnits enumeration */
export enum AngleUnits {
/** */
Radians,
/** */
Degrees,
/** */
Arcminutes,
/** */
Arcseconds,
/** */
Gradians,
/** */
NatoMils,
/** */
Revolutions,
/** */
Tilt,
/** */
Nanoradians,
/** */
Microradians,
/** */
Milliradians,
/** */
Centiradians,
/** */
Deciradians,
/** */
Nanodegrees,
/** */
Microdegrees,
/** */
Millidegrees
}
/** In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. */
export class Angle {
private value: number;
private radiansLazy: number | null = null;
private degreesLazy: number | null = null;
private arcminutesLazy: number | null = null;
private arcsecondsLazy: number | null = null;
private gradiansLazy: number | null = null;
private natomilsLazy: number | null = null;
private revolutionsLazy: number | null = null;
private tiltLazy: number | null = null;
private nanoradiansLazy: number | null = null;
private microradiansLazy: number | null = null;
private milliradiansLazy: number | null = null;
private centiradiansLazy: number | null = null;
private deciradiansLazy: number | null = null;
private nanodegreesLazy: number | null = null;
private microdegreesLazy: number | null = null;
private millidegreesLazy: number | null = null;
/**
* Create a new Angle.
* @param value The value.
* @param fromUnit The ‘Angle’ unit to create from.
* The default unit is Degrees
*/
public constructor(value: number, fromUnit: AngleUnits = AngleUnits.Degrees) {
if (isNaN(value)) throw new TypeError('invalid unit value ‘' + value + '’');
this.value = this.convertToBase(value, fromUnit);
}
/**
* The base value of Angle is Degrees.
* This accessor used when needs a value for calculations and it's better to use directly the base value
*/
public get BaseValue(): number {
return this.value;
}
/** */
public get Radians(): number {
if(this.radiansLazy !== null){
return this.radiansLazy;
}
return this.radiansLazy = this.convertFromBase(AngleUnits.Radians);
}
/** */
public get Degrees(): number {
if(this.degreesLazy !== null){
return this.degreesLazy;
}
return this.degreesLazy = this.convertFromBase(AngleUnits.Degrees);
}
/** */
public get Arcminutes(): number {
if(this.arcminutesLazy !== null){
return this.arcminutesLazy;
}
return this.arcminutesLazy = this.convertFromBase(AngleUnits.Arcminutes);
}
/** */
public get Arcseconds(): number {
if(this.arcsecondsLazy !== null){
return this.arcsecondsLazy;
}
return this.arcsecondsLazy = this.convertFromBase(AngleUnits.Arcseconds);
}
/** */
public get Gradians(): number {
if(this.gradiansLazy !== null){
return this.gradiansLazy;
}
return this.gradiansLazy = this.convertFromBase(AngleUnits.Gradians);
}
/** */
public get NatoMils(): number {
if(this.natomilsLazy !== null){
return this.natomilsLazy;
}
return this.natomilsLazy = this.convertFromBase(AngleUnits.NatoMils);
}
/** */
public get Revolutions(): number {
if(this.revolutionsLazy !== null){
return this.revolutionsLazy;
}
return this.revolutionsLazy = this.convertFromBase(AngleUnits.Revolutions);
}
/** */
public get Tilt(): number {
if(this.tiltLazy !== null){
return this.tiltLazy;
}
return this.tiltLazy = this.convertFromBase(AngleUnits.Tilt);
}
/** */
public get Nanoradians(): number {
if(this.nanoradiansLazy !== null){
return this.nanoradiansLazy;
}
return this.nanoradiansLazy = this.convertFromBase(AngleUnits.Nanoradians);
}
/** */
public get Microradians(): number {
if(this.microradiansLazy !== null){
return this.microradiansLazy;
}
return this.microradiansLazy = this.convertFromBase(AngleUnits.Microradians);
}
/** */
public get Milliradians(): number {
if(this.milliradiansLazy !== null){
return this.milliradiansLazy;
}
return this.milliradiansLazy = this.convertFromBase(AngleUnits.Milliradians);
}
/** */
public get Centiradians(): number {
if(this.centiradiansLazy !== null){
return this.centiradiansLazy;
}
return this.centiradiansLazy = this.convertFromBase(AngleUnits.Centiradians);
}
/** */
public get Deciradians(): number {
if(this.deciradiansLazy !== null){
return this.deciradiansLazy;
}
return this.deciradiansLazy = this.convertFromBase(AngleUnits.Deciradians);
}
/** */
public get Nanodegrees(): number {
if(this.nanodegreesLazy !== null){
return this.nanodegreesLazy;
}
return this.nanodegreesLazy = this.convertFromBase(AngleUnits.Nanodegrees);
}
/** */
public get Microdegrees(): number {
if(this.microdegreesLazy !== null){
return this.microdegreesLazy;
}
return this.microdegreesLazy = this.convertFromBase(AngleUnits.Microdegrees);
}
/** */
public get Millidegrees(): number {
if(this.millidegreesLazy !== null){
return this.millidegreesLazy;
}
return this.millidegreesLazy = this.convertFromBase(AngleUnits.Millidegrees);
}
/**
* Create a new Angle instance from a Radians
*
* @param value The unit as Radians to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromRadians(value: number): Angle {
return new Angle(value, AngleUnits.Radians);
}
/**
* Create a new Angle instance from a Degrees
*
* @param value The unit as Degrees to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromDegrees(value: number): Angle {
return new Angle(value, AngleUnits.Degrees);
}
/**
* Create a new Angle instance from a Arcminutes
*
* @param value The unit as Arcminutes to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromArcminutes(value: number): Angle {
return new Angle(value, AngleUnits.Arcminutes);
}
/**
* Create a new Angle instance from a Arcseconds
*
* @param value The unit as Arcseconds to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromArcseconds(value: number): Angle {
return new Angle(value, AngleUnits.Arcseconds);
}
/**
* Create a new Angle instance from a Gradians
*
* @param value The unit as Gradians to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromGradians(value: number): Angle {
return new Angle(value, AngleUnits.Gradians);
}
/**
* Create a new Angle instance from a NatoMils
*
* @param value The unit as NatoMils to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromNatoMils(value: number): Angle {
return new Angle(value, AngleUnits.NatoMils);
}
/**
* Create a new Angle instance from a Revolutions
*
* @param value The unit as Revolutions to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromRevolutions(value: number): Angle {
return new Angle(value, AngleUnits.Revolutions);
}
/**
* Create a new Angle instance from a Tilt
*
* @param value The unit as Tilt to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromTilt(value: number): Angle {
return new Angle(value, AngleUnits.Tilt);
}
/**
* Create a new Angle instance from a Nanoradians
*
* @param value The unit as Nanoradians to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromNanoradians(value: number): Angle {
return new Angle(value, AngleUnits.Nanoradians);
}
/**
* Create a new Angle instance from a Microradians
*
* @param value The unit as Microradians to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromMicroradians(value: number): Angle {
return new Angle(value, AngleUnits.Microradians);
}
/**
* Create a new Angle instance from a Milliradians
*
* @param value The unit as Milliradians to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromMilliradians(value: number): Angle {
return new Angle(value, AngleUnits.Milliradians);
}
/**
* Create a new Angle instance from a Centiradians
*
* @param value The unit as Centiradians to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromCentiradians(value: number): Angle {
return new Angle(value, AngleUnits.Centiradians);
}
/**
* Create a new Angle instance from a Deciradians
*
* @param value The unit as Deciradians to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromDeciradians(value: number): Angle {
return new Angle(value, AngleUnits.Deciradians);
}
/**
* Create a new Angle instance from a Nanodegrees
*
* @param value The unit as Nanodegrees to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromNanodegrees(value: number): Angle {
return new Angle(value, AngleUnits.Nanodegrees);
}
/**
* Create a new Angle instance from a Microdegrees
*
* @param value The unit as Microdegrees to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromMicrodegrees(value: number): Angle {
return new Angle(value, AngleUnits.Microdegrees);
}
/**
* Create a new Angle instance from a Millidegrees
*
* @param value The unit as Millidegrees to create a new Angle from.
* @returns The new Angle instance.
*/
public static FromMillidegrees(value: number): Angle {
return new Angle(value, AngleUnits.Millidegrees);
}
private convertFromBase(toUnit: AngleUnits): number {
switch (toUnit) {
case AngleUnits.Radians:
return this.value / 180 * Math.PI;
case AngleUnits.Degrees:
return this.value;
case AngleUnits.Arcminutes:
return this.value * 60;
case AngleUnits.Arcseconds:
return this.value * 3600;
case AngleUnits.Gradians:
return this.value / 0.9;
case AngleUnits.NatoMils:
return this.value * 160 / 9;
case AngleUnits.Revolutions:
return this.value / 360;
case AngleUnits.Tilt:
return Math.sin(this.value / 180 * Math.PI);
case AngleUnits.Nanoradians:
return (this.value / 180 * Math.PI) / 1e-9;
case AngleUnits.Microradians:
return (this.value / 180 * Math.PI) / 0.000001;
case AngleUnits.Milliradians:
return (this.value / 180 * Math.PI) / 0.001;
case AngleUnits.Centiradians:
return (this.value / 180 * Math.PI) / 0.01;
case AngleUnits.Deciradians:
return (this.value / 180 * Math.PI) / 0.1;
case AngleUnits.Nanodegrees:
return (this.value) / 1e-9;
case AngleUnits.Microdegrees:
return (this.value) / 0.000001;
case AngleUnits.Millidegrees:
return (this.value) / 0.001;
default:
break;
}
return NaN;
}
private convertToBase(value: number, fromUnit: AngleUnits): number {
switch (fromUnit) {
case AngleUnits.Radians:
return value * 180 / Math.PI;
case AngleUnits.Degrees:
return value;
case AngleUnits.Arcminutes:
return value / 60;
case AngleUnits.Arcseconds:
return value / 3600;
case AngleUnits.Gradians:
return value * 0.9;
case AngleUnits.NatoMils:
return value * 9 / 160;
case AngleUnits.Revolutions:
return value * 360;
case AngleUnits.Tilt:
return Math.asin(value) * 180 / Math.PI;
case AngleUnits.Nanoradians:
return (value * 180 / Math.PI) * 1e-9;
case AngleUnits.Microradians:
return (value * 180 / Math.PI) * 0.000001;
case AngleUnits.Milliradians:
return (value * 180 / Math.PI) * 0.001;
case AngleUnits.Centiradians:
return (value * 180 / Math.PI) * 0.01;
case AngleUnits.Deciradians:
return (value * 180 / Math.PI) * 0.1;
case AngleUnits.Nanodegrees:
return (value) * 1e-9;
case AngleUnits.Microdegrees:
return (value) * 0.000001;
case AngleUnits.Millidegrees:
return (value) * 0.001;
default:
break;
}
return NaN;
}
/**
* Format the Angle to string.
* Note! the default format for Angle is Degrees.
* To specify the unit format set the 'unit' parameter.
* @param unit The unit to format the Angle.
* @returns The string format of the Angle.
*/
public toString(unit: AngleUnits = AngleUnits.Degrees): string {
switch (unit) {
case AngleUnits.Radians:
return this.Radians + ` rad`;
case AngleUnits.Degrees:
return this.Degrees + ` °`;
case AngleUnits.Arcminutes:
return this.Arcminutes + ` '`;
case AngleUnits.Arcseconds:
return this.Arcseconds + ` ″`;
case AngleUnits.Gradians:
return this.Gradians + ` g`;
case AngleUnits.NatoMils:
return this.NatoMils + ` mil`;
case AngleUnits.Revolutions:
return this.Revolutions + ` r`;
case AngleUnits.Tilt:
return this.Tilt + ` sin(θ)`;
case AngleUnits.Nanoradians:
return this.Nanoradians + ` `;
case AngleUnits.Microradians:
return this.Microradians + ` `;
case AngleUnits.Milliradians:
return this.Milliradians + ` `;
case AngleUnits.Centiradians:
return this.Centiradians + ` `;
case AngleUnits.Deciradians:
return this.Deciradians + ` `;
case AngleUnits.Nanodegrees:
return this.Nanodegrees + ` `;
case AngleUnits.Microdegrees:
return this.Microdegrees + ` `;
case AngleUnits.Millidegrees:
return this.Millidegrees + ` `;
default:
break;
}
return this.value.toString();
}
/**
* Get Angle unit abbreviation.
* Note! the default abbreviation for Angle is Degrees.
* To specify the unit abbreviation set the 'unitAbbreviation' parameter.
* @param unitAbbreviation The unit abbreviation of the Angle.
* @returns The abbreviation string of Angle.
*/
public getUnitAbbreviation(unitAbbreviation: AngleUnits = AngleUnits.Degrees): string {
switch (unitAbbreviation) {
case AngleUnits.Radians:
return `rad`;
case AngleUnits.Degrees:
return `°`;
case AngleUnits.Arcminutes:
return `'`;
case AngleUnits.Arcseconds:
return `″`;
case AngleUnits.Gradians:
return `g`;
case AngleUnits.NatoMils:
return `mil`;
case AngleUnits.Revolutions:
return `r`;
case AngleUnits.Tilt:
return `sin(θ)`;
case AngleUnits.Nanoradians:
return ``;
case AngleUnits.Microradians:
return ``;
case AngleUnits.Milliradians:
return ``;
case AngleUnits.Centiradians:
return ``;
case AngleUnits.Deciradians:
return ``;
case AngleUnits.Nanodegrees:
return ``;
case AngleUnits.Microdegrees:
return ``;
case AngleUnits.Millidegrees:
return ``;
default:
break;
}
return '';
}
/**
* Check if the given Angle are equals to the current Angle.
* @param angle The other Angle.
* @returns True if the given Angle are equal to the current Angle.
*/
public equals(angle: Angle): boolean {
return this.value === angle.BaseValue;
}
/**
* Compare the given Angle against the current Angle.
* @param angle The other Angle.
* @returns 0 if they are equal, -1 if the current Angle is less then other, 1 if the current Angle is greater then other.
*/
public compareTo(angle: Angle): number {
if (this.value > angle.BaseValue)
return 1;
if (this.value < angle.BaseValue)
return -1;
return 0;
}
/**
* Add the given Angle with the current Angle.
* @param angle The other Angle.
* @returns A new Angle instance with the results.
*/
public add(angle: Angle): Angle {
return new Angle(this.value + angle.BaseValue)
}
/**
* Subtract the given Angle with the current Angle.
* @param angle The other Angle.
* @returns A new Angle instance with the results.
*/
public subtract(angle: Angle): Angle {
return new Angle(this.value - angle.BaseValue)
}
/**
* Multiply the given Angle with the current Angle.
* @param angle The other Angle.
* @returns A new Angle instance with the results.
*/
public multiply(angle: Angle): Angle {
return new Angle(this.value * angle.BaseValue)
}
/**
* Divide the given Angle with the current Angle.
* @param angle The other Angle.
* @returns A new Angle instance with the results.
*/
public divide(angle: Angle): Angle {
return new Angle(this.value / angle.BaseValue)
}
/**
* Modulo the given Angle with the current Angle.
* @param angle The other Angle.
* @returns A new Angle instance with the results.
*/
public modulo(angle: Angle): Angle {
return new Angle(this.value % angle.BaseValue)
}
/**
* Pow the given Angle with the current Angle.
* @param angle The other Angle.
* @returns A new Angle instance with the results.
*/
public pow(angle: Angle): Angle {
return new Angle(this.value ** angle.BaseValue)
}
}
|
350b64f38cfe12251256deb91b92b39899865755 | TypeScript | forkkit/state | /local-store/index.test.ts | 3 | 3 | import { delay } from 'nanodelay'
import { LocalStore, subscribe, change, destroy } from '../index.js'
it('loads store only once', () => {
class StoreA extends LocalStore {}
class StoreB extends LocalStore {}
let storeA1 = StoreA.load()
let storeA2 = StoreA.load()
let storeB = StoreB.load()
expect(storeA1).toBe(storeA2)
expect(storeB).not.toBe(storeA2)
})
it('destroys store when all listeners unsubscribed', async () => {
let events: string[] = []
class TestStore extends LocalStore {
value = 0
constructor () {
super()
events.push('constructor')
}
[destroy] () {
events.push('destroy')
}
}
let store = TestStore.load()
let unbind1 = store[subscribe]((changed, diff) => {
expect(changed).toBe(store)
events.push('change 1 ' + Object.keys(diff).join(' '))
})
let unbind2 = store[subscribe](() => {
events.push('change 2')
})
store[change]('value', 1)
await delay(1)
unbind1()
store[change]('value', 2)
await delay(1)
unbind2()
expect(TestStore.loaded).toBeDefined()
let unbind3 = store[subscribe](() => {
events.push('change 3')
})
store[change]('value', 4)
await delay(1)
unbind3()
await delay(1)
expect(TestStore.loaded).toBeUndefined()
expect(events).toEqual([
'constructor',
'change 1 value',
'change 2',
'change 2',
'change 3',
'destroy'
])
})
it('supports stores without destroy', async () => {
class TestStore extends LocalStore {}
let store = TestStore.load()
let unbind = store[subscribe](() => {})
unbind()
await delay(1)
expect(TestStore.loaded).toBeUndefined()
})
it('does not allow to change keys', async () => {
class TestStore extends LocalStore {
value = 0
}
let store = TestStore.load()
store[change]('value', 1)
expect(() => {
store.value = 2
}).toThrow(/Cannot assign to read only property 'value'/)
})
it('combines multiple changes for the same store', async () => {
class TestStore extends LocalStore {
a = 0
b = 0
c = 0
d = 0
}
let store = TestStore.load()
let changes: object[] = []
store[subscribe]((changed, diff) => {
expect(changed).toBe(store)
changes.push(diff)
})
store[change]('a', 1)
expect(store.a).toEqual(1)
expect(changes).toEqual([])
await delay(1)
expect(changes).toEqual([{ a: 1 }])
store[change]('b', 2)
store[change]('c', 2)
store[change]('c', 3)
store[change]('d', 3)
await delay(1)
expect(changes).toEqual([{ a: 1 }, { b: 2, c: 3, d: 3 }])
store[change]('d', 3)
await delay(1)
expect(changes).toEqual([{ a: 1 }, { b: 2, c: 3, d: 3 }])
})
it('does not trigger event on request', async () => {
class TestStore extends LocalStore {
a = 0
b = 0
}
let store = TestStore.load()
let changes: object[] = []
store[subscribe]((changed, diff) => {
expect(changed).toBe(store)
changes.push(diff)
})
store[change]('a', 1, true)
await delay(1)
expect(store.a).toEqual(1)
expect(changes).toEqual([])
store[change]('b', 1)
await delay(1)
expect(changes).toEqual([{ b: 1 }])
})
|
0dfc0e79927402e57273dfb5e955dade4494a48a | TypeScript | jvdm1988/Hello-Angular | /src/app/my-pipes/capitalize.pipe.ts | 3.53125 | 4 | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
// In a template, you use the pipe like this
// {{ userName | capitalize}}, because name here is capitalize
name: 'capitalize'
// The "name" setting specifies how to use it
})
export class CapitalizePipe implements PipeTransform {
// The logic of or pipe goes inside the "transform()" method
// "new york city" -> "New York City" (capitalize every word in that string)
// {{ "new york city" | capitalize }}
transform(value: any, args?: any): any {
// the value variable is the thing that you are modifying
// The thing on the left of the "|"
// value = "new york city";
const wordsArray = value.split(" ");
let capitalizedWords = wordsArray.map(oneWord => {
return oneWord.charAt(0).toUpperCase() + oneWord.slice(1).toLowerCase();
// "c".toUppercase() + "ity".toLowerCase
});
return capitalizedWords.join(" ");
// join all the seprated words (sliced) together to join again as a string
}
}
|
700e9c050d06b063cbdef7bc70b494b9305e23a7 | TypeScript | Ciatek-Angular/Components-Templates | /ToDoApp/src/app/to-do/to-do.component.ts | 2.5625 | 3 | import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-to-do',
templateUrl: './to-do.component.html',
styleUrls: ['./to-do.component.css']
})
export class ToDoComponent implements OnInit {
constructor() { }
animal_input: string
animals: any[]
ngOnInit() {
this.animals = ['dog', 'cat', 'lion','elephant']
}
addAnimal(animalHtml: any) {
// console.log(animalHtml.value)
if(animalHtml.value == ''){
return
}
this.animals.push(animalHtml.value)
}
removeAnimal(animal) {
console.log(animal)
if(animal < -1){
return
}
let index = this.animals.indexOf(animal)
this.animals.splice(index, 1)
}
}
|
e8d0115d27c64f1f5198e9175e2ace7650237dae | TypeScript | roelvanlisdonk/dev | /apps/sportersonline/www/libraries/am/virtual.dom/attribute.ts | 2.6875 | 3 | import { IObservableField, IObservableFn } from "../common/observable";
export interface IAttribute {
name: string;
// When null attribute will not be rendered, when empty string only, attribute name will be rendered.
value?: string | IObservableField<string> | IObservableFn<any, string>;
}
|
9b00604a6ac35feca4a85cfc9964b6ed4ad10b5b | TypeScript | matejikj/dataset-similarity | /client/evaluation/dataset-api.ts | 2.6875 | 3 | import axios from "axios";
export interface Dataset {
iri: string;
title: string;
description: string;
keywords: string[];
}
export function getDataset(datasetIri: string): Promise<Dataset> {
const url = "./api/v1/dataset?dataset=" + encodeURIComponent(datasetIri);
return axios.get(url).then((response) => response.data);
}
|
785ee532493e6eddf1fc2362e39c66a3d86e6e8a | TypeScript | noelia96-96/BookLife-Back | /controladores/usuario.controlador.ts | 2.65625 | 3 | import {Request, Response} from "express";
import Token from "../clases/token";
import { Usuario } from '../modelos/usuario.modelo';
class usuarioController{
getSaludo (req:Request, res:Response){
const nombre = req.query.nombre || 'desconocid@';
res.status(200).send({
status: 'ok',
mensaje:'hola, ' + nombre,
dia: new Date()
})
}
postDePrueba (req:Request, res:Response){
let usuario = req.body;
if(!usuario.usuario){
res.status(200).send({
status:'error',
mensaje:'El usuario es necesario'
})
}
res.status(200).send({
status: 'ok',
usuario: usuario
})
}
//Cargar usuarios propios
mostrarUsuario(req: Request, res:Response){
console.log(req);
let _id = req.body.usuario._id;
let params = req.body;
Usuario.findById(_id).then((usuarioDB)=>{
if(!usuarioDB){
return res.status(200).send({
status:'error',
mensaje: 'Token inválido'
})
}else{
let usuario = usuarioDB.nombre;
Usuario.find({ nombre: usuario }).then((usuariosDB)=>{
if(!usuariosDB){
return res.status(200).send({
status:'error',
mensaje: 'Usuarios incorrectos'
})
}
const usuarioQueDevuelvo = new Array<any>();
usuarioQueDevuelvo.push(usuariosDB);
res.status(200).send({
status:'ok',
mensaje: 'Muestra de datos correcta',
usuario: usuarioQueDevuelvo,
token: Token.generaToken(usuario)
});
});
}
})
}
//Cargar usuarios tipo librero - libreria
mostrarLibreria(req: Request, res:Response){
console.log(req);
let _id = req.body.usuario._id;
let params = req.body;
Usuario.findById(_id).then((usuarioDB)=>{
if(!usuarioDB){
return res.status(200).send({
status:'error',
mensaje: 'Token inválido'
})
}else{
let ciudad = usuarioDB.ciudad;
Usuario.find({"$and":[{direccion:{$exists:true}},{ ciudad: ciudad}]}).then((usuariosLibrerosDB)=>{
if(!usuariosLibrerosDB){
return res.status(200).send({
status:'error',
mensaje: 'Usuarios tipo librero incorrectos'
})
}
const usuarioLibreroQueDevuelvo = new Array<any>();
usuarioLibreroQueDevuelvo.push(usuariosLibrerosDB);
res.status(200).send({
status:'ok',
mensaje: 'Muestra de datos correcta',
usuario: usuarioLibreroQueDevuelvo,
token: Token.generaToken(usuarioDB)
});
});
}
})
}
registro(req:Request, res:Response){
// Usuario
let params = req.body;
const usuarioNuevo= new Usuario();
usuarioNuevo.nombre = params.nombre;
usuarioNuevo.pwd = params.pwd;
usuarioNuevo.email = params.email;
usuarioNuevo.ciudad = params.ciudad;
usuarioNuevo.sexo = params.sexo;
usuarioNuevo.favoritos = params.favoritos;
Usuario.create(usuarioNuevo).then((usuarioDB)=>{
if(!usuarioDB){
res.status(500).send({
status:'error',
mensaje:'Error al crear el usuario'
})
}
res.status(200).send({
status:'ok',
mensaje:'Se ha creado el usuario' + usuarioDB.nombre,
usuario: usuarioDB
})
}).catch(err=>{
res.status(500).send({
status: 'error',
error: err
})
});
}
registroLibreria(req:Request, res:Response){
// Usuario
let params = req.body;
const usuarioNuevo= new Usuario();
usuarioNuevo.nombre = params.nombre;
usuarioNuevo.ciudad = params.ciudad;
usuarioNuevo.direccion = params.direccion;
usuarioNuevo.telefono = params.telefono;
usuarioNuevo.web = params.web;
usuarioNuevo.email = params.email;
usuarioNuevo.pwd = params.pwd;
console.log(usuarioNuevo);
Usuario.create(usuarioNuevo).then((usuarioDB)=>{
if(!usuarioDB){
res.status(500).send({
status:'error',
mensaje:'Error al crear el usuario'
})
}
res.status(200).send({
status:'ok',
mensaje:'Se ha creado el usuario' + usuarioDB.nombre,
usuario: usuarioDB
})
}).catch(err=>{
res.status(500).send({
status: 'error',
error: err
})
});
}
getUsuario(req:Request, res:Response){
let _id = req.body.usuario._id;
Usuario.findById(_id).then((usuarioDB)=>{
if(!usuarioDB){
return res.status(200).send({
status:'error',
mensaje: 'Token inválido'
})
}else{
const usuarioQueDevuelvo = new Usuario();
usuarioQueDevuelvo.nombre = usuarioDB.nombre;
usuarioQueDevuelvo._id = usuarioDB._id;
usuarioQueDevuelvo.ciudad = usuarioDB.ciudad;
usuarioQueDevuelvo.favoritos = usuarioDB.favoritos;
res.status(200).send({
status:'ok',
mensaje: 'Login correcto',
usuario: usuarioQueDevuelvo,
token: Token.generaToken(usuarioQueDevuelvo)
})
}
});
}
login(req:Request, res:Response){
// Usuario
let params = req.body;
const nombreQueLlega = params.nombre;
const pwdQueLlega = params.pwd;
//buscar los usuarios que cumplan estas dos condiciones
//con una promesa, si lo encuentra devuelve un usuario con unos datos concretos (no todos)
Usuario.findOne({nombre:nombreQueLlega, pwd:pwdQueLlega}).then((usuarioDB)=>{
if(!usuarioDB){
return res.status(200).send({
status:'error',
mensaje: 'Usuario y/o contraseña incorrectas'
})
}
const usuarioQueDevuelvo = new Usuario();
usuarioQueDevuelvo.nombre = usuarioDB.nombre;
usuarioQueDevuelvo._id = usuarioDB._id;
usuarioQueDevuelvo.web = usuarioDB.web;
usuarioQueDevuelvo.sexo = usuarioDB.sexo;
res.status(200).send({
status:'ok',
menesaj: 'Login correcto',
usuario: usuarioQueDevuelvo,
token: Token.generaToken(usuarioQueDevuelvo)
})
}).catch(err=>{
return res.status(500).send({
status:'error',
mensaje: 'Error en la BBDD',
error:err
})
})
}
//Guardar datos personales editados del librero
guardarDatosEditadosLibreria(req: Request, res:Response){
let params = req.body;
const idQueLlega = params._id;
Usuario.findById(idQueLlega).then(usuarioDB => {
if (!usuarioDB) {
return res.status(400).send({
status: 'error',
mensaje: 'Error al editar los datos personales',
});
}
if(usuarioDB.nombre !== params.nombre || usuarioDB.pwd !== params.pwd || usuarioDB.email !== params.email || usuarioDB.web !== params.web || usuarioDB.telefono !== params.telefono || usuarioDB.ciudad !== params.ciudad || usuarioDB.direccion !== params.direccion) {
usuarioDB.nombre = params.nombre
usuarioDB.pwd = params.pwd
usuarioDB.email = params.email
usuarioDB.web = params.web
usuarioDB.telefono = params.telefono
usuarioDB.ciudad = params.ciudad
usuarioDB.direccion = params.direccion
}
usuarioDB.save().then( () => {
res.status(200).send({
status: 'ok',
mensaje: 'Datos personales editados'
});
})
});
};
//Guardar datos personales editados del bibliofilo
guardarDatosEditadosBibliofilo(req: Request, res:Response){
let params = req.body;
const idQueLlega = params._id;
Usuario.findById(idQueLlega).then(usuarioDB => {
if (!usuarioDB) {
return res.status(400).send({
status: 'error',
mensaje: 'Error al editar los datos personales',
});
}
if(usuarioDB.nombre !== params.nombre || usuarioDB.pwd !== params.pwd || usuarioDB.ciudad !== params.ciudad || usuarioDB.sexo !== params.sexo) {
usuarioDB.nombre = params.nombre
usuarioDB.pwd = params.pwd
usuarioDB.email = params.email
usuarioDB.ciudad = params.ciudad
usuarioDB.sexo = params.sexo
}
usuarioDB.save().then( () => {
res.status(200).send({
status: 'ok',
mensaje: 'Datos personales editados'
});
})
});
};
//Guardar la libreria en favoritos
guadarLibreriaFav(req: Request, res:Response){
let params = req.body;
const idQueLlega = params.usuario._id;
const libreriaQueLlega = params.libreria;
console.log(params);
Usuario.findById(idQueLlega).then(usuarioDB => {
if (!usuarioDB) {
return res.status(400).send({
status: 'error',
mensaje: 'Error al traer el usuario',
});
}
usuarioDB.favoritos.push(libreriaQueLlega);
usuarioDB.save().then( () => {
res.status(200).send({
status: 'ok',
mensaje: 'Datos ok'
});
})
});
}
//Borrar la libreria de favoritos
borrarLibreriaFav(req: Request, res:Response){
let params = req.body;
const idQueLlega = params.usuario._id;
const libreriaQueLlega = params.libreria;
console.log(params);
Usuario.findById(idQueLlega).then(usuarioDB => {
if (!usuarioDB) {
return res.status(400).send({
status: 'error',
mensaje: 'Error al borrar el usuario',
});
}
// obtenemos el indice
var indice = usuarioDB.favoritos.indexOf(libreriaQueLlega);
// 1 es la cantidad de elemento a eliminar
usuarioDB.favoritos.splice(indice,1);
usuarioDB.save().then( () => {
res.status(200).send({
status: 'ok',
mensaje: 'Datos ok'
});
})
});
}
//Mostrar las librerias favoritas en la seccion - Favoritos
mostrarLibreriasFavoritas(req: Request, res:Response){
console.log(req);
let _id = req.body.usuario._id;
let params = req.body;
Usuario.findById(_id).then((usuarioDB)=>{
if(!usuarioDB){
return res.status(200).send({
status:'error',
mensaje: 'Token inválido'
})
}else{
let favoritos = usuarioDB.favoritos;
Usuario.find({nombre:{$in:favoritos}}).then((usuariosLibrerosDB)=>{
if(!usuariosLibrerosDB){
return res.status(200).send({
status:'error',
mensaje: 'Usuarios tipo librero incorrectos'
})
}
const usuarioLibreroQueDevuelvo = new Array<any>();
usuarioLibreroQueDevuelvo.push(usuariosLibrerosDB);
res.status(200).send({
status:'ok',
mensaje: 'Muestra de datos correcta',
usuario: usuarioLibreroQueDevuelvo,
token: Token.generaToken(usuarioDB)
});
});
}
})
}
}
export default usuarioController; |
e6d7c66925d7d13210db9145eb05bb5078594f10 | TypeScript | LoicROY/Projet_diginamic_2_front_angular | /src/app/shared/formulaireComponents/input/input.component.ts | 2.703125 | 3 | import { GeneriqueComponent } from './../../../generique/generique.component';
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-input[inputModel][id][label][type]',
templateUrl: './input.component.html',
styleUrls: ['./input.component.scss']
})
export class InputComponent extends GeneriqueComponent implements OnInit {
/**
* Model de donnée bindé
*/
@Input()
public inputModel?: string;
/**
* Evennement à propager lors d'un modelChange
*/
@Output()
public inputModelChange: EventEmitter<string> = new EventEmitter<string>();
/**
* Label de l'input
*/
@Input()
public label!: string;
/**
* Id unique de l'input
*/
@Input()
public id!: string;
/**
* Type de l'input
*/
@Input()
public type!: ('text' | 'password' | 'tel' | 'email' | 'date');
/**
* Spécifie si le champs est optionnel
*/
@Input()
public required: boolean = false;
/**
* Désactive l'input
*/
@Input()
public disabled: boolean = false;
/**
* Impose une longueur max
*/
@Input()
public maxlength?: number;
/**
* Impose une longueur min
*/
@Input()
public minlength?: number;
/**
* Valeur de l'autocomplete
*/
@Input()
public autocomplete: string = 'off';
/**
* Valeur du placeholder
*/
@Input()
public placeholder: string = '';
/**
* Erreur à afficher sous le champ
*/
@Input()
public erreur?: string;
/**
* Evenement lors du changement de l'erreur
*/
@Output()
public erreurChange: EventEmitter<string> = new EventEmitter<string>();
/**
* Evenement lors de sortie de l'input
*/
@Output()
public blur: EventEmitter<EventTarget> = new EventEmitter<EventTarget>();
constructor() {
super();
}
public ngOnInit(): void {
if (this.inputModel) {
this.checkValidite();
}
}
/**
* Vérifie la validité de la saisie
*/
public checkValidite(): void {
if (!this.inputModel && this.required) {
this.erreur = this.ERREUR.REQUIRED;
this.erreurChange.emit(this.erreur);
}
// Si champs nul, pas de check de format
if (!this.inputModel){
return;
}
if (this.minlength && this.inputModel.length < this.minlength) {
this.erreur = this.ERREUR.MIN_LENGHT;
this.erreurChange.emit(this.erreur);
return;
}
if (this.maxlength && this.inputModel.length > this.maxlength) {
this.erreur = this.ERREUR.MAX_LENGHT;
this.erreurChange.emit(this.erreur);
return;
}
switch (this.type) {
case 'tel':
if (!new RegExp(this.REGEX.TEL).test(this.inputModel!)) {
this.erreur = this.ERREUR.TEL_FORMAT;
this.erreurChange.emit(this.erreur);
}
break;
case 'email':
if (!new RegExp(this.REGEX.EMAIL).test(this.inputModel!)) {
this.erreur = this.ERREUR.EMAIL_FORMAT;
this.erreurChange.emit(this.erreur);
}
break;
case 'date':
if (!new RegExp(this.REGEX.DATE).test(this.inputModel!)) {
this.erreur = this.ERREUR.DATE_FORMAT;
this.erreurChange.emit(this.erreur);
}
break;
}
}
/**
* Propagation du changement du model
*/
public modelChange(): void {
// On supprime le message d'erreur
this.erreur = undefined;
this.erreurChange.emit(this.erreur);
// On propage le changement
this.inputModelChange.emit(this.inputModel);
}
/**
* Controle du format à la sortie du champs
*/
public onBlurHandler(event: any): void {
this.checkValidite();
this.blur.emit(event);
}
}
|
073387c69d991c940b6f2b171a0eca23bebca0dd | TypeScript | Roeefl/andals-server | /src/schemas/GameCard.ts | 3.28125 | 3 | import { type, Schema } from '@colyseus/schema';
interface cardManifest {
title: string
description: string
};
const manifest: { [type: string] : cardManifest } = {
// A "Knight" card allows a player to move the robber to any spot on the board
// and then gets to take a card from any player that has a settlement or city on the blocked resource.
knight: {
title: 'knight',
description: 'A fiercesome Knight'
},
// A "Victory Point" card automatically gives the player one victory point.
victoryPoint: {
title: 'Victory Point',
description: 'Forward, to Victory!'
},
// A "Road Building" card allows a player to place two roads on the board.
roadBuilding: {
title: 'Road Building',
description: 'Pull this card to build 2 roads anywhere'
},
// A "Year of Plenty" card gives a player any two resource cards.
yearOfPlenty: {
title: 'Year of Plenty',
description: 'You get good shit'
},
// After a player plays the "Monopoly" card, that player announces one type of resource.
// Every player must then give that player all of that type of resource card(s) in their hand.
monopoly: {
title: 'Monopoly',
description: 'Ask others for their stuff'
}
};
class GameCard extends Schema {
@type("string")
type: string;
@type("string")
title: string
@type("string")
description: string
@type("number")
purchasedRound: number = -1
@type("boolean")
wasPlayed: boolean = false
constructor(type: string) {
super();
this.type = type;
this.title = manifest[type].title;
this.description = manifest[type].description;
}
};
export default GameCard;
|
00db76d5839a60c2536d488c6377ef613867a150 | TypeScript | AlanMauricioCastillo/wks-typescript | /clases/demos/funciones.ts | 3.609375 | 4 |
//function nombreMiFuncion(parametroUno: TIPADO_PARAMETRO_UNO, ...): tipadoReturn
// function suma(a: number, b: number): number {
// return a + b
// }
// function suma(a: number | string, b: number | string): number | string | void {
// if(typeof a === "number" && typeof b === "number") return a + b
// if(typeof a === "string" && typeof b === "string") return a + b
// }
function suma(a: string | number, b: string | number): number {
if(typeof a === "string") {
a = parseInt(a)
}
if(typeof b === "string") {
b = parseInt(b)
}
return a + b
}
function consologea(): void {
console.log('algo')
//react cuando seteemos un estado!
}
function throwError(msg: string): never {
throw new Error(msg);
console.log('un valor')
}
let resultado = suma(2, 2)
|
8cbf8ef659b7ca353c74a152e94fb03d8e227ae5 | TypeScript | c6o/ui | /packages/web/src/tabs/tabs.ts | 2.6875 | 3 | import { TabsElement } from '@vaadin/vaadin-tabs/src/vaadin-tabs'
import { mix } from 'mixwith'
import { EntityListStoreMixin } from '../mixins'
/**
* `<c6o-tabs>` is a Web Component for easy switching between different views.
*
* ```
* <c6o-tabs>
* <c6o-tab>Page 1</c6o-tab>
* <c6o-tab>Page 2</c6o-tab>
* <c6o-tab>Page 3</c6o-tab>
* <c6o-tab>Page 4</c6o-tab>
* </c6o-tabs>
*
* <c6o-tabs selected="2">
* <c6o-tab>Page 1</c6o-tab>
* <c6o-tab>Page 2</c6o-tab>
* <c6o-tab>Page 3</c6o-tab>
* </c6o-tabs>
*
* <c6o-tabs orientation="vertical">
* <c6o-tab>Page 1</c6o-tab>
* <c6o-tab>Page 2</c6o-tab>
* <c6o-tab>Page 3</c6o-tab>
* </c6o-tabs>
* ```
*
* ### Styling
*
* The following shadow DOM parts are available for styling:
*
* Part name | Description
* ------------------|--------------------------------------
* `back-button` | Button for moving the scroll back
* `tabs` | The tabs container
* `forward-button` | Button for moving the scroll forward
*
* The following state attributes are available for styling:
*
* Attribute | Description | Part name
* -----------|-------------|------------
* `orientation` | Tabs disposition, valid values are `horizontal` and `vertical`. | :host
* `overflow` | It's set to `start`, `end`, none or both. | :host
* `theme` | Optional tabs theme, valid values are `thin` and `light`. | :host
*
* @extends EntityListStoreMixin
* @mixes TabsElement
*/
export interface Tabs extends EntityListStoreMixin {
}
export class Tabs extends mix(TabsElement).with(EntityListStoreMixin) {
}
customElements.define('c6o-tabs', Tabs) |
a62d93bbcabb51bbda9c85fbc5ff107b8d2ec41f | TypeScript | Himaja1606/IMSProjectAngular | /src/app/SupplierDetails.ts | 2.5625 | 3 | export interface SupplierDetails{
supplierId: number,
supplierName: string,
suppliedQuantity: number
} |
36003a9431432e97dc1c8ec60467ee36cabcc3ad | TypeScript | asimyildiz/market | /src/middleware/api/index.ts | 2.5625 | 3 | import axios from "axios";
import config from "../../config";
import { TagList } from "../interfaces/tag.interface";
import { CompanyList } from "../interfaces/company.interface";
import { ProductList } from "../interfaces/product.interface";
import { ItemTypeList } from "../interfaces/itemtype.interface";
import { Query } from "../interfaces/query/query.interface";
import { Sort } from "../interfaces/query/sort.interface";
import { Pagination } from "../interfaces/query/pagination.interface";
import { toQueryString, urlBuilder } from "../../utils/helpers";
/**
* fetch list of companies from json-server
* @returns {Promise<CompanyList>}
*/
export const getCompanies = async (): Promise<CompanyList> => {
try {
const { data } = await axios.get(`${config.API_URL}/companies/`);
return { data };
} catch (error) {
return { error };
}
};
/**
* fetch list of tags from json-server
* @returns {Promise<TagList>}
*/
export const getTags = async (): Promise<TagList> => {
try {
const { data } = await axios.get(`${config.API_URL}/tags/`);
return { data };
} catch (error) {
return { error };
}
};
/**
* fetch list of itemTypes from json-server
* @returns {Promise<ItemTypeList>}
*/
export const getItemTypes = async (): Promise<ItemTypeList> => {
try {
const { data } = await axios.get(`${config.API_URL}/types/`);
return { data };
} catch (error) {
return { error };
}
};
/**
* fetch list of products from json-server
* @param {?Query} query - filter data
* @param {?Sort} sort - sort data
* @param {?Pagination} page - limit data
* @returns {Promise<ProductList>}
*/
export const getProducts = async (
query?: Query,
sort?: Sort,
page?: Pagination
): Promise<ProductList> => {
try {
const response = await axios.get(
urlBuilder(
`${config.API_URL}/items`,
toQueryString(query),
toQueryString(sort),
toQueryString(page)
)
);
return { data: response.data, count: response.headers["x-total-count"] };
} catch (error) {
return { error };
}
};
|
881f0e24b03428efe40c942968a01d9b31313541 | TypeScript | tomelam/mayhem | /tests/unit/core/Promise.ts | 2.53125 | 3 | import assert = require('intern/chai!assert');
import Deferred = require('dojo/Deferred');
import Promise = require('mayhem/Promise');
import registerSuite = require('intern!object');
registerSuite({
name: 'mayhem/Promise',
'resolve and progress'() {
var progressTriggered = false;
var promise = new Promise(function (resolve, reject, progress) {
setTimeout(function () {
progress('progress');
resolve('resolved');
}, 0);
});
return promise.then(function (result) {
assert.isTrue(progressTriggered, 'progress event should be triggered');
assert.strictEqual(result, 'resolved');
}, function () {
throw new Error('promise should not be rejected');
}, function (progress) {
progressTriggered = true;
assert.strictEqual(progress, 'progress');
});
},
'reject'() {
var promise = new Promise(function (resolve, reject) {
setTimeout(function () {
reject(new Error('rejected'));
}, 0);
});
return promise.then(function () {
throw new Error('promise should not be resolved');
}, function (error) {
assert.strictEqual(error.message, 'rejected');
});
},
'cancel'() {
var expected = new Error('reason');
var dfd = this.async();
var promise = new Promise(function (resolve, reject, progress, setCanceler) {
setCanceler(dfd.callback(function (reason: Error) {
assert.strictEqual(reason, expected);
}));
});
promise.cancel(expected);
},
'error in initializer'() {
var promise = new Promise(function () {
throw new Error('bad intitializer');
});
return promise.then(function () {
throw new Error('promise should not be resolved');
}, function (error) {
assert.strictEqual(error.message, 'bad intitializer');
});
},
'.resolve': {
'with value'() {
var promise = Promise.resolve('resolved');
return promise.then(function (result) {
assert.strictEqual(result, 'resolved');
}, function (error) {
throw new Error('promise should not be rejected');
});
},
'with Dojo Promise'() {
var dfd = new Deferred();
var promise = Promise.resolve(dfd.promise);
dfd.resolve('resolved');
return promise.then(function (result) {
assert.strictEqual(result, 'resolved');
}, function (error) {
throw new Error('promise should not be rejected');
});
},
'with Dojo Deferred'() {
var dfd = new Deferred();
var promise = Promise.resolve(dfd);
dfd.resolve('resolved');
return promise.then(function (result) {
assert.strictEqual(result, 'resolved');
}, function (error) {
throw new Error('promise should not be rejected');
});
}
},
'.reject'() {
var promise = Promise.reject(new Error('rejected'));
return promise.then(function () {
throw new Error('promise should not be resolved');
}, function (error) {
assert.strictEqual(error.message, 'rejected');
});
}
});
|
6cd2e7dc823cb330b958ad88c7b08cad136b793a | TypeScript | dannycalleri/ture | /dist/trees/rect.d.ts | 2.8125 | 3 | import { Point2D } from "./point2d";
declare class Rect {
private _xMin;
private _yMin;
private _xMax;
private _yMax;
constructor(xMin: number, yMin: number, xMax: number, yMax: number);
readonly xMin: number;
readonly yMin: number;
readonly xMax: number;
readonly yMax: number;
width(): number;
height(): number;
intersects(that: Rect): boolean;
contains(p: Point2D): boolean;
distanceTo(p: Point2D): number;
distanceSquaredTo(p: Point2D): number;
toString(): string;
}
export default Rect;
|
e4d44c5eae01b536ad643d23f23da7ba79110b08 | TypeScript | ibrahimkarayel/TypeScriptDemo | /09_functions/03_driver.ts | 3.15625 | 3 | interface DCallback {
(dName: string): void
}
class DbLoader {
loadDriverName(callback: DCallback) {
callback("Mongo");
}
}
class DbController {
private _dName: string;
constructor(private dbLoader: DbLoader) {
}
get dName(): string {
return this._dName;
}
loadDriver() {
let _this= this;
this.dbLoader.loadDriverName(function (loadedName) {
_this._dName = loadedName;
});
}
}
function playWithDriver() {
let ac = new DbController(new DbLoader());
ac.loadDriver();
console.log(ac.dName);
}
|
8ae23a33091d5dd7fb829411b4dc73d8ff3dd50a | TypeScript | irkanu/temtem-api | /scripts/util/write.ts | 2.84375 | 3 | import { promises as fs } from "fs";
import path from "path";
import * as log from "./log";
import traverse, {
cleanStrings,
capitalizeType,
removeWikiReferences,
} from "./objectCleaner";
export function getDataPath(name: string) {
return path.join(__dirname, "..", "..", "data", `${name}.json`);
}
export default async function write(name: string, data: any) {
log.info("cleaning");
const cleanData = traverse(data, [
cleanStrings,
capitalizeType,
removeWikiReferences,
]);
log.info("cleaned");
log.info("writing", name);
try {
await fs.writeFile(
getDataPath(name),
JSON.stringify(cleanData, undefined, 2)
);
log.info("finished writing", name);
} catch (e) {
log.error("error writing", name, e.message);
}
}
|
ae8479ab5f84efcf6fb7d8d7dcc39aa666bf4f6f | TypeScript | alexeden/dotstar-node | /app/browser/src/app/leap-paint/lib/leap/finger.ts | 3.0625 | 3 | import { vec3 } from 'gl-matrix';
import { Pointable } from './pointable';
import { Bone } from './bone';
import { Triple, FingerType, FingerData, BoneType } from './types';
/**
* Constructs a Finger object.
*
* An uninitialized finger is considered invalid.
* Get valid Finger objects from a Frame or a Hand object.
*
* @class Finger
* @memberof Leap
* @classdesc
* The Finger class reports the physical characteristics of a finger.
*
* Both fingers and tools are classified as Pointable objects. Use the
* Pointable.tool property to determine whether a Pointable object represents a
* tool or finger. The Leap classifies a detected entity as a tool when it is
* thinner, straighter, and longer than a typical finger.
*
* Note that Finger objects can be invalid, which means that they do not
* contain valid tracking data and do not correspond to a physical entity.
* Invalid Finger objects can be the result of asking for a Finger object
* using an ID from an earlier frame when no Finger objects with that ID
* exist in the current frame. A Finger object created from the Finger
* constructor is also invalid. Test for validity with the Pointable.valid
* property.
*/
export class Finger extends Pointable {
readonly tool = false;
readonly bases: Array<Triple<vec3>>;
readonly btipPosition: vec3;
readonly carpPosition: vec3;
readonly dipPosition: vec3;
readonly mcpPosition: vec3;
readonly pipPosition: vec3;
readonly extended: boolean;
readonly type: FingerType;
readonly positions: vec3[];
readonly bones: Bone[];
readonly metacarpal: Bone;
readonly proximal: Bone;
readonly medial: Bone;
readonly distal: Bone;
static fromData(data: FingerData) {
return new Finger(data);
}
private constructor(
data: FingerData
) {
super(data);
this.bases = data.bases.map(basis => basis.map(base => vec3.fromValues(...base))) as Array<Triple<vec3>>;
this.btipPosition = vec3.fromValues(...data.btipPosition);
this.dipPosition = vec3.fromValues(...data.dipPosition);
this.pipPosition = vec3.fromValues(...data.pipPosition);
this.mcpPosition = vec3.fromValues(...data.mcpPosition);
this.carpPosition = vec3.fromValues(...data.carpPosition);
this.extended = data.extended;
this.type = data.type;
this.positions = [this.carpPosition, this.mcpPosition, this.pipPosition, this.dipPosition, this.tipPosition];
this.metacarpal = new Bone(
BoneType.metacarpal,
this.bases![0],
this.carpPosition,
this.mcpPosition,
this.width
);
this.proximal = new Bone(
BoneType.proximal,
this.bases![1],
this.mcpPosition,
this.pipPosition,
this.width
);
this.medial = new Bone(
BoneType.medial,
this.bases![2],
this.pipPosition,
this.dipPosition,
this.width
);
this.distal = new Bone(
BoneType.distal,
this.bases![3],
this.dipPosition,
this.btipPosition,
this.width
);
this.bones = [this.metacarpal, this.proximal, this.medial, this.distal];
}
toString() {
return `Finger [ id:${ this.id } ${ this.length }mmx | width:${ this.width }mm | direction:${ this.direction } ]`;
}
}
|
82b30cd11a5dfbd912bee346317449c2c7c25397 | TypeScript | huaweicloud/huaweicloud-sdk-nodejs-v3 | /services/cloudpipeline/v2/CloudPipelineRegion.ts | 2.578125 | 3 | import { Region } from "@huaweicloud/huaweicloud-sdk-core/region/region";
interface RegionMap {
[key: string]: Region;
}
export class CloudPipelineRegion {
public static CN_NORTH_1 = new Region("cn-north-1", ["https://cloudpipeline-ext.cn-north-1.myhuaweicloud.com"]);
public static CN_NORTH_4 = new Region("cn-north-4", ["https://cloudpipeline-ext.cn-north-4.myhuaweicloud.com"]);
public static CN_SOUTH_1 = new Region("cn-south-1", ["https://cloudpipeline-ext.cn-south-1.myhuaweicloud.com"]);
public static CN_SOUTH_2 = new Region("cn-south-2", ["https://cloudpipeline-ext.cn-south-2.myhuaweicloud.com"]);
public static CN_EAST_3 = new Region("cn-east-3", ["https://cloudpipeline-ext.cn-east-3.myhuaweicloud.com"]);
public static CN_EAST_2 = new Region("cn-east-2", ["https://cloudpipeline-ext.cn-east-2.myhuaweicloud.com"]);
private static REGION_MAP: RegionMap = {
"cn-north-1":CloudPipelineRegion.CN_NORTH_1,
"cn-north-4":CloudPipelineRegion.CN_NORTH_4,
"cn-south-1":CloudPipelineRegion.CN_SOUTH_1,
"cn-south-2":CloudPipelineRegion.CN_SOUTH_2,
"cn-east-3":CloudPipelineRegion.CN_EAST_3,
"cn-east-2":CloudPipelineRegion.CN_EAST_2
};
public static valueOf(regionId: string) {
if (!regionId) {
throw new Error("Unexpected empty parameter: regionId.");
}
const result = this.REGION_MAP[regionId];
if (result) {
return result;
}
throw new Error(`Unexpected regionId: ${regionId}.`)
}
}
|
d8304c48e0f1be82790b4f516c0b63fe2e3ef524 | TypeScript | abelce/blogfrontend | /src/service/http.ts | 2.8125 | 3 | import Constants from "./constant"
const url = "http://127.0.0.1:9010"
let xhr: any;
class Deferred {
promise: any
resolve: any
reject: any
constructor() {
this.promise = new Promise((resolve: any, reject: any) => {
this.resolve = resolve;
this.reject = reject;
})
}
}
class Api {
constructor() {
xhr = this.xhr
}
xhr = (method: any, path: any, body = {}): any => {
const deferred = new Deferred();
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
deferred.resolve(JSON.parse(xhr.responseText))
}
}
xhr.open(method, url + path, true); //设置异步请求
xhr.send(JSON.stringify(body));
return deferred.promise;
}
login = (data: any) => {
return xhr(Constants.POST, '/login', data);
}
getUser = () => {
return xhr(Constants.GET, '/user')
}
getPath = (path: string, params: Object): string => {
const keys = Object.keys(params);
const paramStr = keys.map(k => `${k}=${params[k]}`).join('&');
if (paramStr.length > 0) {
path = path + '?' + paramStr;
}
return path;
}
fetchUsers = (params: any = {}) => {
let path = '/users';
path = this.getPath(path, params);
return xhr(Constants.GET, path, {});
}
updateUser = (params: any) => {
let path = "/user/update";
return xhr(Constants.POST, path, params);
}
cretaeUser = (params: any) => {
let path = "/user/create";
return xhr(Constants.POST, path, params);
}
deleteUser = (id: number) => {
let path = "/user/delete";
path = this.getPath(path, {id});
return xhr(Constants.GET, path, {})
}
}
export default new Api() |
64243b74eb62c8505a414a2ec90872e0d0b525e7 | TypeScript | comparIt/comparit-front | /src/app/shared/models/modelProperty.ts | 2.890625 | 3 | export class ModelProperty {
id: number;
name: string;
technicalName: string;
activated: boolean;
type: string;
filtrable: boolean;
filtrableAdvanced: boolean;
mandatory: boolean;
min: number;
max: number;
range: number[];
values: string[];
selectedValues: string[] = [];
isSaved = true;
get isEnum(): boolean {
return this.type === 'ENUMERATIVE';
}
get isNumeric(): boolean {
return this.type === 'NUMERIC';
}
constructor() {
}
static buildProperty(property: ModelProperty): ModelProperty {
const modelProperty = new ModelProperty();
modelProperty.id = property.id;
modelProperty.name = property.name;
modelProperty.technicalName = property.technicalName;
modelProperty.activated = property.activated;
modelProperty.type = property.type;
modelProperty.filtrable = property.filtrable;
modelProperty.filtrableAdvanced = property.filtrableAdvanced;
modelProperty.mandatory = property.mandatory;
modelProperty.min = property.min;
modelProperty.max = property.max;
modelProperty.range = [modelProperty.min, modelProperty.max];
modelProperty.values = property.values;
modelProperty.selectedValues = [];
return modelProperty;
}
static createModelProperty(name: string,
technicalName: string,
activated: boolean,
type: string,
filtrable: boolean,
filtrableAdvanced: boolean,
mandatory: boolean): ModelProperty {
const modelProprety: ModelProperty = new ModelProperty();
modelProprety.name = name;
modelProprety.technicalName = technicalName;
modelProprety.activated = activated;
modelProprety.type = type;
modelProprety.filtrable = filtrable;
modelProprety.filtrableAdvanced = filtrableAdvanced;
modelProprety.mandatory = mandatory;
modelProprety.isSaved = false;
return modelProprety;
}
initFilter(filter: string) {
if (this.isNumeric) {
this.range = [Number(filter.split('-')[0]), Number(filter.split('-')[1])];
} else if (this.isEnum) {
this.selectedValues = filter.split(',');
}
}
}
|
2d4ec7ac3fce2a62ac00d902863913b75f0866f9 | TypeScript | bgruening/ngl | /dist/declarations/trajectory/trajectory.d.ts | 2.75 | 3 | /**
* @file Trajectory
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
import { Signal } from 'signals';
import { NumberArray } from '../types';
import Selection from '../selection/selection';
import Structure from '../structure/structure';
import TrajectoryPlayer, { TrajectoryPlayerInterpolateType } from './trajectory-player';
/**
* Trajectory parameter object.
* @typedef {Object} TrajectoryParameters - parameters
*
* @property {Number} deltaTime - timestep between frames in picoseconds
* @property {Number} timeOffset - starting time of frames in picoseconds
* @property {String} sele - to restrict atoms used for superposition
* @property {Boolean} centerPbc - center on initial frame
* @property {Boolean} removePeriodicity - move atoms into the origin box
* @property {Boolean} remo - try fixing periodic boundary discontinuities
* @property {Boolean} superpose - superpose on initial frame
*/
/**
* @example
* trajectory.signals.frameChanged.add( function(i){ ... } );
*
* @typedef {Object} TrajectorySignals
* @property {Signal<Integer>} countChanged - when the frame count is changed
* @property {Signal<Integer>} frameChanged - when the set frame is changed
* @property {Signal<TrajectoryPlayer>} playerChanged - when the player is changed
*/
export interface TrajectoryParameters {
deltaTime: number;
timeOffset: number;
sele: string;
centerPbc: boolean;
removePbc: boolean;
removePeriodicity: boolean;
superpose: boolean;
}
export interface TrajectorySignals {
countChanged: Signal;
frameChanged: Signal;
playerChanged: Signal;
}
/**
* Base class for trajectories, tying structures and coordinates together
* @interface
*/
declare class Trajectory {
signals: TrajectorySignals;
deltaTime: number;
timeOffset: number;
sele: string;
centerPbc: boolean;
removePbc: boolean;
removePeriodicity: boolean;
superpose: boolean;
name: string;
frame: number;
trajPath: string;
initialCoords: Float32Array;
structureCoords: Float32Array;
selectionIndices: NumberArray;
backboneIndices: NumberArray;
coords1: Float32Array;
coords2: Float32Array;
frameCache: {
[k: number]: Float32Array;
};
loadQueue: {
[k: number]: boolean;
};
boxCache: {
[k: number]: ArrayLike<number>;
};
pathCache: {};
frameCacheSize: number;
atomCount: number;
inProgress: boolean;
selection: Selection;
structure: Structure;
player: TrajectoryPlayer;
private _frameCount;
private _currentFrame;
private _disposed;
/**
* @param {String} trajPath - trajectory source
* @param {Structure} structure - the structure object
* @param {TrajectoryParameters} params - trajectory parameters
*/
constructor(trajPath: string, structure: Structure, params?: Partial<TrajectoryParameters>);
/**
* Number of frames in the trajectory
*/
get frameCount(): number;
/**
* Currently set frame of the trajectory
*/
get currentFrame(): number;
_init(structure: Structure): void;
_loadFrameCount(): void;
setStructure(structure: Structure): void;
_saveInitialCoords(): void;
_saveStructureCoords(): void;
setSelection(string: string): this;
_getIndices(selection: Selection): number[];
_makeSuperposeCoords(): void;
_makeAtomIndices(): void;
_resetCache(): void;
setParameters(params?: Partial<TrajectoryParameters>): void;
/**
* Check if a frame is available
* @param {Integer|Integer[]} i - the frame index
* @return {Boolean} frame availability
*/
hasFrame(i: number | number[]): boolean;
/**
* Set trajectory to a frame index
* @param {Integer} i - the frame index
* @param {Function} [callback] - fired when the frame has been set
*/
setFrame(i: number, callback?: Function): this;
_interpolate(i: number, ip: number, ipp: number, ippp: number, t: number, type: TrajectoryPlayerInterpolateType): void;
/**
* Interpolated and set trajectory to frame indices
* @param {Integer} i - the frame index
* @param {Integer} ip - one before frame index
* @param {Integer} ipp - two before frame index
* @param {Integer} ippp - three before frame index
* @param {Number} t - interpolation step [0,1]
* @param {String} type - interpolation type, '', 'spline' or 'linear'
* @param {Function} callback - fired when the frame has been set
*/
setFrameInterpolated(i: number, ip: number, ipp: number, ippp: number, t: number, type: TrajectoryPlayerInterpolateType, callback?: Function): this;
/**
* Load frame index
* @param {Integer|Integer[]} i - the frame index
* @param {Function} callback - fired when the frame has been loaded
*/
loadFrame(i: number | number[], callback?: Function): void;
/**
* Load frame index
* @abstract
* @param {Integer} i - the frame index
* @param {Function} callback - fired when the frame has been loaded
*/
_loadFrame(i: number, callback?: Function): void;
_updateStructure(i: number): void;
_doSuperpose(x: Float32Array): void;
_process(i: number, box: ArrayLike<number>, coords: Float32Array, frameCount: number): void;
_setFrameCount(n: number): void;
/**
* Dispose of the trajectory object
* @return {undefined}
*/
dispose(): void;
/**
* Set player for this trajectory
* @param {TrajectoryPlayer} player - the player
*/
setPlayer(player: TrajectoryPlayer): void;
/**
* Get time for frame
* @param {Integer} i - frame index
* @return {Number} time in picoseconds
*/
getFrameTime(i: number): number;
}
export default Trajectory;
|
c383a57034de817fb1eba7bc9031f46512ab098a | TypeScript | jiangshanmeta/meta | /src/0343.integer-break.343/solution.ts | 3.265625 | 3 | function integerBreak (n: number): number {
const dp:number[] = new Array(n + 1).fill(0);
dp[1] = 1;
for (let i = 2; i < dp.length; i++) {
for (let j = 1; j < i; j++) {
dp[i] = Math.max(dp[i], j * dp[i - j], j * (i - j));
}
}
return dp[n];
}
|
4e7b17cb5f93d3dfa9c2ce8e0c3bada1bd31b28c | TypeScript | alexfoxgill/biselect | /src/Debug.ts | 3.140625 | 3 | import { Extension } from "./Extension";
export function Debug() {
return Debug.create()
}
export namespace Debug {
const wrap = (name: string, f: Function) => (...args: any[]) => {
console.group()
console.log(`Calling ${name} with arguments:`, ...args)
const result = f(...args)
console.log("Result:", result)
console.groupEnd()
return result
}
export const create = (): Extension => {
return Extension.create(optic => {
switch (optic.type) {
case "get":
case "set":
case "modify":
optic._underlying = wrap(optic.type, optic._underlying)
break;
}
})
}
} |
1e71814e4863a3574b0892af44429354f69f6cab | TypeScript | dtarvin/new-angular-2-components | /chapter_3/chapter_3.ts | 4.09375 | 4 | // valid ES6 or TypeScript
class User {
constructor(id) {
this.id = id;
}
getUserInfo() {
return this.getUserInfo;
}
}
//----------------------------------------------------------------
// simple TypeScript class
class Product {
private id: number;
private color: string;
constructor(id: number, color:string) {
this.id = id;
this.color = color;
}
}
// ES6 will output this code
class Product {
constructor(id, color) {
this.id = id;
this.color = color;
}
}
// ES5 will output this
var Product = (function() {
function Product(id, color) {
this.id = id;
this.color = color;
}
return Product;
})();
//----------------------------------------------------------------
// Export and import statements
// The following module exposes a function, a class, and a variable
export function getRandomNumber() {
return Math.random();
}
export class User {
constructor(name) {
this.name = name;
}
}
export const id = 12345;
// To use the exported code, we need to import it in another module
// import only the function from the module
import { getRandomNumber } from './user';
// import both the function and the class from the module
import { getRandomNumber, Person } from './user';
// import the function and bind it to a random variable
import {getRandomNumber as random } from './user';
// import everything from the module and
// bind it to a userModule variable
import * as UserModule from './user';
// default export
export default class User {
constructor(name) { this.name = name }
}
// don't need to use exact name of the function, class or variable that was exported
import UserModule from './user.ts';
//----------------------------------------------------------------
// Classes
// class with a constructor, property and method
class Product {
color;
price;
constructor(color, price) {
this.color = color;
this.price = price;
}
getProductDetails() {
return this.color + this.price;
}
}
// class with extends and super
class Product {
color;
price;
constructor(color, price) {
this.color = color;
this.price = price;
}
}
class Ebook extends Product {
size;
constructor(color, price, size) {
super(color, price);
this.size = size;
}
getProductDetails() {
return `${this.color}, ${this.price}, ${this.size}`;
}
}
//----------------------------------------------------------------
// The type system
// basic types
// strings
let name: string = "bob";
// boolean
let isLoggedIn: boolean = true;
// number
let height: number = 24;
let width: number = 12;
// arrays
let colors: string[] = ['red', 'green', 'blue'];
let colors: Array<string> = ['red', 'green', 'blue'];
|
df6437b25b98128f78e8709e07d2b550547b75ce | TypeScript | awanjila/angular-guessing-game | /app/guess-the-number.component.ts | 2.890625 | 3 | import { Component }from '@angular/core';
@Component({
selector: 'my-app',
template:
<div class="cointainer">
<h2> Guess the Number ! </h2>
<p class="well lead">Guess the computer generated random
number between 1 and 1000.</p>
<label>Your Guess:</label>
<input type="number" [value]="guess" (input)="guess =$event.target.value"/>
<button (click)="verifyGuess()" class="btn btn-primary btn-sm">Verify</button>
<button (click)="initializeGame()" class="btn btn-warning btn-sm">Restart</button>
<div>
<p *ngIf="deviation<0" class="alert alert-warning"> Your Guess is higher. </p>
<p *ngIf="deviation>0" class="alert alert-warning"> Your Guess is lower. </p>
<p *ngIf="deviation===0" class="alert alert-success"> Hooray Thats the right guess. </p>
</div>
<p class="text-info">No of guesses :
<span class="badge">{{noOfTries}}</span>
</p>
</div>
})
export class GuessTheNumberComponent{
deviation:number;
noOfTries:number;
original:number;
guess:number;
constructor(){
this.initializeGame();
}
} initializeGame(){
this.noOfTries=0;
this.original=Math.floor(Math.random( * 1000)+1);
this.guess=null;
}
verifyGuess(){
this.deviation=this.original-this.guess;
this.noOfTries+1;
}
} |
9f1c6f099c5f4aea43f2a5f832c84ccd50d263d7 | TypeScript | osamaalaa/aot-inventory | /frontend/src/app/pages/inventory/master-setup/stores-setup/stores-item-group-no/stores-items-group-no-model.services.ts | 2.734375 | 3 | /**
*
* * Model service for Stores Item Group No Components .
*
* *Features
* * Searching data
* * Storing data
* * Sorting data
*/
import { Injectable } from '@angular/core'
import { TableBase } from 'src/app/common/Table-base';
@Injectable()
export class StoresItemsGroupNoModelService extends TableBase{
constructor() {
super();
}
/** Searches for EN_NAME, ID, EN_DESC in the data and resets data into displayData */
public searchItems(searchText: string): void {
if (searchText) {
let isTextInSTORES_ITEMS_GROUP_NO_ID = (item: any) =>
item.STORES_ITEMS_GROUP_NO_ID.toString()
.toLowerCase()
.indexOf(searchText.toString().toLowerCase()) !== -1;
let isTextInSTORE_EN_NAME = (item: any) =>
item.STORE_EN_NAME.toString()
.toLowerCase()
.indexOf(searchText.toString().toLowerCase()) !== -1;
let isTextInSTORE_AR_NAME = (item: any) =>
item.STORE_AR_NAME.toString()
.toLowerCase()
.indexOf(searchText.toString().toLowerCase()) !== -1;
let isTextInITEM_GROUP_EN_NAME = (item: any) =>
item.ITEM_GROUP_EN_NAME.toString()
.toLowerCase()
.indexOf(searchText.toString().toLowerCase()) !== -1;
let isTextInITEM_GROUP_AR_NAME = (item: any) =>
item.ITEM_GROUP_AR_NAME.toString()
.toLowerCase()
.indexOf(searchText.toString().toLowerCase()) !== -1;
this.displayData = this.savedData.filter(
item => isTextInSTORES_ITEMS_GROUP_NO_ID(item) || isTextInSTORE_EN_NAME(item) || isTextInSTORE_AR_NAME(item) || isTextInITEM_GROUP_EN_NAME(item) || isTextInITEM_GROUP_AR_NAME(item),
);
} else {
this.displayData = this.savedData
}
this.displayData = [...this.displayData] // refresh
}
}
|
3377d7b58b8e82d4ae37d5d4b5a382f58e5c5384 | TypeScript | EyeSeeTea/Bulk-Load | /src/webapp/utils/colors.ts | 2.5625 | 3 | import _ from "lodash";
import { PaletteCollection } from "../../domain/entities/Palette";
// Returns a color brewer scale for a number of classes
export const getColorPalette = (palettes: PaletteCollection, scale: string, classes: number): string[] => {
const palette = palettes[scale] ?? {};
return palette[classes] ?? [];
};
// Returns color scale name for a palette
export const getColorScale = (palettes: PaletteCollection, palette: string[]) => {
return _.keys(palettes).find(name => _.isEqual(getColorPalette(palettes, name, palette.length), palette));
};
export const generatorOriginalPalette = {
default: {
3: ["#ffee58", "#ffca28", "#ffa726"],
4: ["#ffee58", "#ffca28", "#ffa726", "#ff7043"],
5: ["#ffee58", "#ffca28", "#ffa726", "#ff7043", "#e57373"],
6: ["#ffee58", "#ffca28", "#ffa726", "#ff7043", "#e57373", "#f06292"],
7: ["#ffee58", "#ffca28", "#ffa726", "#ff7043", "#e57373", "#f06292", "#ba68c8"],
8: ["#ffee58", "#ffca28", "#ffa726", "#ff7043", "#e57373", "#f06292", "#ba68c8", "#9575cd"],
9: ["#ffee58", "#ffca28", "#ffa726", "#ff7043", "#e57373", "#f06292", "#ba68c8", "#9575cd", "#9fa8da"],
10: [
"#ffee58",
"#ffca28",
"#ffa726",
"#ff7043",
"#e57373",
"#f06292",
"#ba68c8",
"#9575cd",
"#9fa8da",
"#90caf9",
],
11: [
"#ffee58",
"#ffca28",
"#ffa726",
"#ff7043",
"#e57373",
"#f06292",
"#ba68c8",
"#9575cd",
"#9fa8da",
"#90caf9",
"#80deea",
],
12: [
"#ffee58",
"#ffca28",
"#ffa726",
"#ff7043",
"#e57373",
"#f06292",
"#ba68c8",
"#9575cd",
"#9fa8da",
"#90caf9",
"#80deea",
"#80cbc4",
],
13: [
"#ffee58",
"#ffca28",
"#ffa726",
"#ff7043",
"#e57373",
"#f06292",
"#ba68c8",
"#9575cd",
"#9fa8da",
"#90caf9",
"#80deea",
"#80cbc4",
"#a5d6a7",
],
14: [
"#ffee58",
"#ffca28",
"#ffa726",
"#ff7043",
"#e57373",
"#f06292",
"#ba68c8",
"#9575cd",
"#9fa8da",
"#90caf9",
"#80deea",
"#80cbc4",
"#a5d6a7",
"#c5e1a5",
],
15: [
"#ffee58",
"#ffca28",
"#ffa726",
"#ff7043",
"#e57373",
"#f06292",
"#ba68c8",
"#9575cd",
"#9fa8da",
"#90caf9",
"#80deea",
"#80cbc4",
"#a5d6a7",
"#c5e1a5",
"#e6ee9c",
],
},
};
export const defaultColorScale = getColorPalette(generatorOriginalPalette, "default", 9);
|
131371d260fbc5ccef0c272b9137a699b7b0650e | TypeScript | BlackWolfBY/dreamcar_api | /src/mapper/abstract.mapper.ts | 2.9375 | 3 | export interface AbstractMapper<E, D> {
toDto(entity: E): D;
toEntity(dto: D): E;
}
|
e181a05aaf55515f037871654b4cbb1974e270fb | TypeScript | nrjackson/social-framework | /social-framework-backend/src/utils/utils.ts | 2.59375 | 3 | import { hashSync, genSaltSync, compareSync } from 'bcrypt-nodejs';
import * as jwt from 'jsonwebtoken';
import { Config } from '../constant/config';
import { IUser } from '../model/user';
export class Utils {
// generating a hash
public static generateHash = function(password) {
return hashSync(password, genSaltSync(8));
};
// checking if password is valid
public static validPassword = function(password, pass) {
return compareSync(password, pass);
};
public static generateJWT(user: IUser): string {
const today = new Date();
let exp = new Date(today);
exp.setDate(today.getDate() + 60);
return jwt.sign({
exp: exp.getTime() / 1000,
id: user.id,
username: user.username,
}, Config.secret);
}
}
|
f6d1d20161c41271f03832f2f84fd483b138726e | TypeScript | ryrocks/ng-arithmetic-operations | /src/lib/ng-arithmetic-operations.service.ts | 2.9375 | 3 | import { Injectable } from '@angular/core';
import { ErrorCode, Sign, ConvertOperator, ConvertSign, Operator } from './const';
import { BehaviorSubject, Observable } from 'rxjs';
export interface ErrorMsg {
code: string;
msg: string;
}
@Injectable({
providedIn: 'root'
})
export class NgArithmeticOperationsService {
// sum for general calculate
sum: number = 0;
nextNumber = '0'
expression: string[] = [];
// sumSource and errorSource for reactive programing
private sumSource = new BehaviorSubject('0');
private errorSource = new BehaviorSubject(<ErrorMsg>{});
constructor() { }
/**
*
* @param item check is number or not
*/
isNumber(item: string) {
return /[+-]?([0-9]*[.])?[0-9]+/g.test(item);
}
getExpression(): Observable<string> {
return this.sumSource;
}
getErrorMsg(): Observable<ErrorMsg> {
return this.errorSource;
}
/**
*
* @param input from press any number buttons
*/
inputKey(key: string) {
// console.log('Input Key::::', key);
if (!ConvertOperator[key] && !this.isNumber(key) && !ConvertSign[key]) {
this.errorSource.next({
code: ErrorCode.ERR0001,
msg: 'ERROR PARAMETER'
});
return;
}
if (this.isNumber(key) || key === Sign.DOT) {
this.combineNumber(key);
this.sumSource.next(this.displayExpresstion() + this.nextNumber);
} else if (key === Sign.LEFTBASKET || key === Sign.RIGHTBASKET) {
this.checkValidBasket(key);
this.sumSource.next(this.displayExpresstion());
} else {
this.storeExpression(key);
}
// console.log(this.expression);
}
storeExpression(key: string) {
this.expression.push(this.nextNumber);
/**
* click operator button will push number every time
* this condition will check the last sign whether is ) or not
* if yes pop out last number
* otherwise it will cause eval() failed
*/
if (this.expression[this.expression.length - 2] === ConvertSign.rightBasket) {
this.expression.pop();
}
this.nextNumber = '0';
if (key !== Sign.EQUALS) {
this.expression.push(ConvertOperator[key]);
this.sumSource.next(this.displayExpresstion());
} else {
this.computeResult();
}
}
/**
* convert for display on panel
*/
displayExpresstion() {
let arr = this.expression
.slice()
.map(s => {
if (s === '*') {
return '×';
} else if (s === '/') {
return '÷'
} else {
return s;
}
});
return arr.join('');
}
/**
* while press C will call this function
*/
resetValue() {
this.nextNumber = '0';
this.expression = [];
// console.log('RESET:::', this.nextNumber, this.expression);
this.sumSource.next('0');
}
/**
* count total of '(' and ')'
*/
countBasket() {
let left = 0, right = 0;
this.expression.forEach(s => {
if (s === ConvertSign[Sign.LEFTBASKET]) {
left++;
} else if (s === ConvertSign[Sign.RIGHTBASKET]) {
right++;
}
});
return {
left: left,
right: right
}
}
checkValidBasket(key: Sign) {
let arrLength = this.expression.length;
if (key === Sign.LEFTBASKET) {
if ((!this.isNumber(this.expression[arrLength - 1]) && this.expression[arrLength - 1] !== ConvertSign.rightBasket) || arrLength === 0) {
this.expression.push(ConvertSign[key]);
} else {
this.errorSource.next({
code: ErrorCode.ERR0002,
msg: 'ERROR INPUT'
});
// console.log('ERROR INPUT!!!!');
return;
}
} else {
this.expression.push(this.nextNumber);
this.nextNumber = '0';
arrLength = this.expression.length; // array length changed, so assign new value
/**
* right basket must match:
* 1. illegal left basket number
* 2. last item is a number
*/
let basket = this.countBasket();
if ((basket.left > basket.right && this.isNumber(this.expression[arrLength - 1])) || (basket.left > basket.right && this.expression[arrLength - 1] === ConvertSign.rightBasket)) {
this.expression.push(ConvertSign[key]);
arrLength = this.expression.length;
if (this.isNumber(this.expression[arrLength - 2]) && this.expression[arrLength - 3] === ConvertSign.rightBasket) {
this.expression.pop();
this.expression.pop();
this.expression.push(ConvertSign[key]);
}
} else {
this.expression.pop();
this.errorSource.next({
code: ErrorCode.ERR0002,
msg: 'ERROR INPUT'
});
// console.log('ERROR INPUT!!!!');
return;
}
}
}
/**
*
* @param input
* combine each digit and store into this.nextNumber
*/
combineNumber(input: string) {
input = input === Sign.DOT ? ConvertSign.dot : input;
if (input === ConvertSign.dot && this.nextNumber.includes('.')) {
this.errorSource.next({
code: ErrorCode.ERR0002,
msg: 'ERROR INPUT'
});
// console.log('ERROR INPUT!!!!');
return;
}
if (this.nextNumber === '0' && input !== ConvertSign.dot) {
this.nextNumber = input;
} else {
this.nextNumber = this.nextNumber + input;
}
}
computeResult() {
let basket = this.countBasket();
let result = 0
if (basket.left !== basket.right) {
this.expression.pop();
this.errorSource.next({
code: ErrorCode.ERR0002,
msg: 'ERROR INPUT'
});
// console.log('ERROR INPUT!!!!');
return;
}
result = eval(this.expression.join(''));
if (this.precision(result) >= 8) {
this.sumSource.next(result.toFixed(8));
} else {
this.sumSource.next(result.toString());
}
this.expression = [];
}
precision(a) {
if (!isFinite(a)) return 0;
var e = 1, p = 0;
while (Math.round(a * e) / e !== a) { e *= 10; p++; }
return p;
}
/**
*
* @param num general calculation
*/
add(num: number) {
this.sum = this.sum + num;
return this;
}
subtract(num: number) {
this.sum = this.sum - num;
return this;
}
multiply(num: number) {
this.sum = this.sum * num;
return this;
}
divide(num: number) {
this.sum = this.sum / num;
return this;
}
equals(): number {
return this.sum;
}
reset(): number {
return this.sum = 0;
}
}
export const NGAO = new NgArithmeticOperationsService();
|
820a8a585ed285542c57840ca400515eda5b66ab | TypeScript | LucasGomes9/training_project | /src/app/controllers/EmployeeController.ts | 2.765625 | 3 | import { getRepository } from 'typeorm';
import Employees from '../models/Employees';
interface Request {
name: string;
email: string;
}
class FuncionariosController {
public async store({ name, email }: Request): Promise<Employees> {
const employeesRepository = getRepository(Employees);
const verifyEmployee = await employeesRepository.findOne({
where: { email },
});
if (verifyEmployee) {
throw new Error('Email already registered, pick another one');
}
const user = employeesRepository.create({
name,
email,
});
await employeesRepository.save(user);
return user;
}
}
export default FuncionariosController;
|
73c12b27a62ccd987918427a2bae3364d11bc786 | TypeScript | oflynned/Mongoize-ORM | /src/example/credential-validation.example.ts | 2.703125 | 3 | import User from "./models/user";
import {
Repository,
InMemoryClient,
bindGlobalDatabaseClient
} from "../../src";
const main = async (): Promise<void> => {
await Repository.with(User).hardDeleteMany({});
const user: User = await new User().build({
name: "John Smith",
email: "email@test.com",
password: "password"
});
// contains plaintext password field, hash field is undefined
console.log(user.toJson().password, user.toJson().passwordHash);
// pre-validation hook scrubs the password field and sets the hashed field on the committed db record
const record = await user.save();
console.log(record.toJson().password, record.toJson().passwordHash);
// pre-validation hook also removes the .password field on the user instance since it should not be needed anymore
console.log(user.toJson().password, user.toJson().passwordHash);
// we can also still compare credentials on the instance without direct password comparison
console.log(
"does this password attempt match?",
await user.passwordAttemptMatches("not the password")
);
console.log(
"does this password attempt match?",
await user.passwordAttemptMatches("password")
);
};
(async (): Promise<void> => {
const client = await bindGlobalDatabaseClient(new InMemoryClient());
try {
await main();
} catch (e) {
console.log(e);
} finally {
await client.close();
}
})();
|
b404c38fc5f56ff4993d5755a58bb0788d2430b7 | TypeScript | Marianabnn/practica_examen | /main.ts | 2.546875 | 3 | let conteo = 0
let A = 0
let B = 0
let SUMA = 0
input.onButtonPressed(Button.A, function () {
conteo = 2
while (conteo <= 10) {
basic.showNumber(conteo)
basic.showIcon(IconNames.Ghost)
conteo += 2
}
basic.showString("BOO!!!")
})
input.onButtonPressed(Button.AB, function () {
A = randint(1, 5)
B = randint(1, 5)
basic.showNumber(A)
basic.showNumber(B)
SUMA = A + B
if (SUMA >= 7 && SUMA <= 10) {
basic.showIcon(IconNames.Rabbit)
}
})
input.onButtonPressed(Button.B, function () {
for (let conteo = 0; conteo <= 10; conteo++) {
basic.showNumber(conteo)
if (conteo % 2 == 0) {
music.playTone(392, music.beat(BeatFraction.Whole))
}
}
music.playMelody("C5 B A G F E D C ", 120)
})
input.onGesture(Gesture.Shake, function () {
basic.showString("A01253575")
})
basic.forever(function () {
basic.showIcon(IconNames.Butterfly)
basic.showIcon(IconNames.Chessboard)
if (input.temperature() < 10) {
basic.showIcon(IconNames.Rollerskate)
}
})
|
12ef765ae08047d4616c8f96c41cbb16a9784226 | TypeScript | littleTigerRunRunRun/PaperWing | /src/configure/color.ts | 3.65625 | 4 | // 颜色类型
// rgba颜色字符串
// example1: 'rgba(255, 255, 255, 1)
// example2: 'rgba(100,100,200,0.5)
export type RGBAColor = string
export function isRGBAColor() {
}
// rgb颜色字符串
// example1: 'rgb(255, 255, 255)
// example2: 'rgb(100,100,200)
export type RGBColor = string
export function isRGBColor() {
}
// 归一化颜色数组
// example1: [1, 1, 1, 1]
// example2: [0.45, 0.45, 0.45, 0.5]
export type NormalizeArrayColor = Array<number>[4]
export function isNormalizeArrayColor() {
}
// 十六进制字符串
// example1: '#ffffff / '#fff'
// example2: '#7777ee' / '#77e'
export type String16bitColor = string
export function isString16bitColor() {
}
// 十六进制数字
// example1: 0xffffff
// example2: 0x7777ee
export type Number16bitColor = number
export function isNumber16bitColor() {
}
export type PaperWingColor = RGBAColor | RGBColor | NormalizeArrayColor | String16bitColor | Number16bitColor
export function isPaperWingColor() {
} |
156b5d52232b0a1dd8b66e162abc44799cb72d85 | TypeScript | cnhuzi/Espider | /src/ts/spider/blur.ts | 2.9375 | 3 | //this is for vuejs.cn
function blur(finder:string):string[]{
let newfinder=finder.split('.').map((it)=>{
return '.'+it;
});
newfinder.splice(0,1);
// console.log($);
return combination(newfinder,[],[]);
}
function combination(arr:string[],newarr:string[][],ans:any):string[]{
if(newarr.length==0){
let tmp:any=[];
for(let i of arr){
tmp.push([i]);
}
// console.log(tmp);
// let answer=dosth($,tmp);
// if(answer){
// return answer
// }
ans.push(...tmp)
combination(arr,tmp,ans);
}else{
for(let i of newarr){
let last=i[i.length-1];
let index=arr.indexOf(last);
if(index==arr.length-1){
return
}
let tmp1:any=[];
for(let j=index+1;j<arr.length;j++){
tmp1.push([...i,arr[j]]);
}
// console.log(tmp1);
// let answer=dosth($,tmp1);
// if(answer){
// return answer
// }
ans.push(...tmp1);
combination(arr,tmp1,ans);
}
}
ans=ans.map((e:string[])=>{return e.join('')});
return ans;
}
// function dosth($,arr){
// for(let i of arr){
// let entry=`.${i.join('.')}`;
// console.log('begin');
// let finder=$(entry);
// console.log('end')
// console.log(finder);
// if(finder.length==1){
// return finder
// }else{
// return false
// }
// }
// }
export default blur; |
bc135cca2df15bb61602c3319a6aadb96a50bf51 | TypeScript | oricalvo/input-mask | /base.ts | 2.75 | 3 | import {
cloneBuf, cloneFieldsByPos, copyArray, Fields, FieldsOptions, findFieldByPos, isValidDate, KEY_BACKSPACE, KEY_DELETE,
KEY_DOWN,
KEY_LEFT,
KEY_RIGHT, KEY_UP,
parsePattern
} from "./common";
export abstract class InputMaskBase {
input: HTMLInputElement;
pos: number;
pattern: string;
max_pos: number;
buf: any[];
fields: Fields;
isValid: boolean;
isComplete: boolean;
constructor(input, pattern, fieldsOptions?: FieldsOptions) {
this.input = input;
this.pos = 0;
const info = parsePattern(pattern);
this.pattern = info.pattern;
this.max_pos = this.pattern && this.pattern.length;
this.fields = info.fields;
this.buf = info.buf;
this.isComplete = false;
this.isValid = false;
this.input.addEventListener("keydown", this.onKeyDown.bind(this));
this.input.addEventListener("keypress", this.onKeyPress.bind(this));
this.input.addEventListener("focus", this.onFocus.bind(this));
this.input.addEventListener("mousedown", this.onMouseDown.bind(this));
for(let key in this.fields) {
const field = this.fields[key];
field.options = (fieldsOptions && fieldsOptions[key]) || {};
}
for(let key in this.fields) {
const field = this.fields[key];
if(field.options.defValue) {
field.buf = field.options.defValue.substring(0, field.len).split("");
copyArray(field.buf, 0, field.len, this.buf, field.begin);
}
}
this.input.value = this.pattern;
}
isSeperator(pos) {
for (let key in this.fields) {
const field = this.fields[key];
if (pos >= field.begin && pos < field.end) {
return false;
}
}
return true;
}
onKeyDown(e) {
console.log("keyDown", e.keyCode);
let cmd = null;
let newBuf = null;
let newFields = null;
if (e.which == KEY_RIGHT) {
cmd = this.next;
}
else if (e.which == KEY_LEFT) {
cmd = this.prev;
}
else if (e.which == KEY_BACKSPACE) {
newBuf = cloneBuf(this.buf, this.pos, undefined);
newFields = cloneFieldsByPos(this.fields, this.pos, undefined);
cmd = this.prev;
}
else if (e.which == KEY_DELETE) {
e.preventDefault();
return;
}
else if (e.which == KEY_DOWN) {
e.preventDefault();
return;
}
else if (e.which == KEY_UP) {
e.preventDefault();
return;
}
if (cmd || newBuf) {
e.preventDefault();
setTimeout(() => {
if (newBuf) {
//
// Call validate and ignore return value
// We allow backspace for invalid value
// We still need to call "validate" since it may change the input appearance (CSS)
//
this.handleValidation(e.which, newBuf, newFields);
this.update(newBuf, newFields);
}
if(cmd) {
cmd.call(this);
}
}, 0);
}
}
handleValidation(keyCode: number, buf: string[], fields: Fields) {
this.isValid = false;
this.isComplete = false;
if(keyCode) {
if (!this.validateKey(keyCode)) {
return false;
}
}
if(!this.validateBuf(buf, fields)) {
return false;
}
this.isValid = true;
this.isComplete = this.checkComplete(buf, fields);
}
canType(pos) {
if(this.pattern && this.pos == this.max_pos) {
return false;
}
return true;
}
onKeyPress(e) {
console.log("keyPress", e.key, e.keyCode, e.charCode);
if (!this.canType(this.pos)) {
e.preventDefault();
return;
}
e.preventDefault();
this.internalPressKey(e.keyCode);
}
internalPressKey(keyCode) {
const ch = String.fromCharCode(keyCode);
const newBuf = cloneBuf(this.buf, this.pos, ch);
const newFields = cloneFieldsByPos(this.fields, this.pos, ch);
this.handleValidation(keyCode, newBuf, newFields);
if(!this.isValid) {
return;
}
setTimeout(() => {
this.update(newBuf, newFields);
this.next();
}, 0);
}
abstract validateKey(keyCode: number);
abstract validateBuf(buf: string[], fields: Fields);
abstract checkComplete(buf: string[], fields: Fields);
onFocus(e) {
setTimeout(() => {
this.setSelection();
}, 0);
}
update(newBuf, fields) {
const oldBuf = this.buf;
const value = newBuf.concat();
for(let i=0; i<value.length; i++) {
if(!value[i]) {
value[i] = this.pattern[i];
}
}
this.input.value = value.join("");
this.buf = newBuf;
this.fields = fields;
}
updateByFields(newFields: Fields) {
const newBuf = this.buf.concat([]);
for(let key in newFields) {
const field = newFields[key];
copyArray(field.buf, 0, field.buf.length, newBuf, field.begin);
}
this.handleValidation(undefined, newBuf, newFields);
if(!this.isValid) {
return;
}
this.update(newBuf, newFields);
}
setSelection() {
if (this.pos == this.max_pos) {
this.input.setSelectionRange(this.max_pos, this.max_pos);
}
else {
this.input.setSelectionRange(this.pos, this.pos + 1);
}
}
next() {
if (this.pos < this.max_pos) {
while (this.isSeperator(++this.pos)) {
if (this.pos == this.max_pos) {
break;
}
}
}
this.setSelection();
}
prev() {
if (this.pos > 0) {
while (this.isSeperator(--this.pos)) {
if (this.pos == -1) {
this.pos = 0;
break;
}
}
}
this.setSelection();
}
onChanged() {
}
clearInvalidIndication() {
this.input.classList.remove("invalid");
}
setInvalidIndication() {
this.input.classList.add("invalid");
}
onMouseDown(e) {
e.preventDefault();
e.target.focus();
setTimeout(() => {
this.setSelection();
}, 0);
}
}
|
09b3f08882cf3c3f014db494b29b3e9c60ea22cc | TypeScript | YuNode/omicron | /src/example/example.ts | 3.171875 | 3 | import * as omicron from "../index";
import { IO } from "fp-ts/lib/IO";
import { RouteResponse } from "../core/src/http/router/router.interface";
import * as E from "fp-ts/lib/Either";
import { HttpRequest } from "../core/src/http.interface";
const wait = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));
const getHandler = omicron.get("/get")(async (req) => {
await wait(5000);
return "It works";
})((req, err) => {
return err.message;
});
const postHandler = omicron.post("/post")((req) => {
return req.body;
})((req, err) => "My error handler");
const putHandler = omicron.put("/put")((req) => "My PUT request")((req) => "My error handler");
const deleteHandler = omicron.dlt("/delete")((req) => "My DELETE request")((req) => "My error handler");
const allHandler = omicron.all("/all")((req) => "My catch all handler")((req) => "My error handler");
// You can also contruct a RouteHandler with the r() function
const myHandler = omicron.r("/myhandler")("GET")((req) => "My Handler")(() => "Error Handler");
const indexHandler = omicron.r("/")("GET")(() => "It works!")(() => "It doesn't work!");
// You could also pass in a handler function that returns a RouteResponse. This only works if you return a complete RouteResponse.
// Returning just {response: "My response"} will set the default options and send back {response: "My response"} to the client
const handlerWithOptions = omicron.r("/withoptions")("GET")(
() =>
({
response: "This is my response, which could be anything",
status: 200, // You can set a custom status code
headers: { "Set-Cookie": ["cookie=true"] }, // Here you can set all your custom headers. If you don't want to set any custom headers, just set headers to {}
} as RouteResponse)
)((_, err) => err);
// This is how you can create middleware
const authenticated: omicron.Middleware = async (req: omicron.HttpRequest) => {
await wait(3000);
return req.query.number > 10 ? E.right(req) : E.left(new Error("Number is not > 10"));
};
const isBob: omicron.Middleware = (req: omicron.HttpRequest) =>
req.query.name === "Bob" ? E.right(req) : E.left(new Error("User is not Bob"));
// This is how you use middleware in your handlers
// Default behaviour is to throw the error in the handler
// Then you should handle it in your error handler
// Another option is to pass an additional error handler to useMiddleware() which will handle any errors from the middleware
const handlerWithMiddleware = omicron.r("/middleware")("GET")(
omicron.useMiddleware([authenticated])((req) => "User is authenticated")
)((req, err) => err.message);
// You can also use multiple middlewares
// The middleware functions have to be composed to a single function (here we used flow() from fp-ts which is used for function composition from left to right)
const handlerWithMultipleMiddlewares = omicron.r("/multiple-middlewares")("GET")(
omicron.useMiddleware([authenticated, isBob])((req) => "User is authenticated and his name is Bob")
)((req, err) => err.message);
// Another way of creating middleware
// Instead of returning Either<Error, HttpRequest | unknown> you can just return whatever you like
// If the middleware should fail you have to throw an error
const authenticatedErrorThrowing: omicron.ErrorThrowingMiddleware = (req: HttpRequest) =>
req.query.number > 10
? req
: (() => {
throw new Error("Number is not > 10");
})();
const isBobErrorThrowing: omicron.ErrorThrowingMiddleware = (req: omicron.HttpRequest) =>
req.query.name === "Bob"
? req
: (() => {
throw new Error("User is not Bob");
})();
// You can use error throwing middleware with useErrorThrowingMiddleware()
const handlerWithErrorThrowingMiddlewares = omicron.r("/middleware-error-throwing")("GET")(
omicron.useErrorThrowingMiddleware([authenticatedErrorThrowing, isBobErrorThrowing])(
(req) => "User is authenticated and his name is Bob"
)
)((_, err) => err.message);
const listener = omicron.httpListener({
// Here you can add all your routes that should be exposed
routes: [
handlerWithErrorThrowingMiddlewares,
handlerWithMiddleware,
handlerWithMultipleMiddlewares,
indexHandler,
myHandler,
getHandler,
allHandler,
postHandler,
putHandler,
deleteHandler,
handlerWithOptions,
],
});
const PORT = 3000;
// Get our server instance
const server = omicron.createServer({ port: PORT, listener: listener });
// await our server setup with await server
const main: IO<void> = async () => await (await server)();
// Call main() to start the server
main();
console.log(`Listening on https://localhost:${PORT}`);
|
d5bae1c5435c3d56d48bcb47c3d059eeb6090189 | TypeScript | rugglcon/twitch-bot | /src/bot/lib/readFileAsDataUrl.ts | 3.140625 | 3 | import fs from 'fs'
import path from 'path'
const mimeType = (filePath: string): string => {
const ext = path.extname(filePath)
const mainType =
ext === 'mp3'
? 'audio'
: 'image'
const subType =
ext === 'mp3'
? 'mpeg'
: ext
return `${mainType}/${subType}`
}
/**
* read a file as a data url synchronous
* @param filePath file path including extension
* @return data url string
*/
export const readFileAsData = (filePath: string): string => {
const base64 = fs.readFileSync(filePath, { encoding: 'base64' })
return `data:${mimeType(filePath)};base64,${base64}`
}
|
c6d7a08be923e10bd802d86caa611e577bc656a0 | TypeScript | jweissman/eve | /src/eve/vm/data-types/EveInteger.ts | 2.671875 | 3 | import { EveDataType } from './EveDataType'
export class EveInteger implements EveDataType {
private internalValue: number;
constructor(value: number) { this.internalValue = Number(value) }
get js(): number { return Number(this.internalValue) }
}
|
32b55801948ced307a71c3789f451238507f5d15 | TypeScript | ThiagoBussola/teste-gazin | /developers/services/developers.service.ts | 2.578125 | 3 | import DevelopersDao from '../daos/developers.dao'
import { CRUD } from '../../common/interfaces/crud.interface'
import { CreateDeveloperDto } from '../dto/create.developer.dto'
import { PutDeveloperDto } from '../dto/put.developer.dto'
class DevelopersService implements CRUD {
async create (resource: CreateDeveloperDto) {
return await DevelopersDao.addDeveloper(resource)
}
async findById (id: string) {
return await DevelopersDao.getDeveloperById(id)
}
// we are accepting number as a string as it will be passed by the request parameter
async listDevelopers (nome: string, sexo: string, idade: string, hobby: string, limit: number, page: number) {
return await DevelopersDao.getDevelopers(nome, sexo, idade, hobby, limit, page)
}
async putById (id: string, resource: PutDeveloperDto): Promise<any> {
return await DevelopersDao.updateDeveloperById(id, resource)
}
async deleteById (id: string) {
return await DevelopersDao.removeDeveloperById(id)
}
}
export default new DevelopersService()
|
07365a4a8a7920b1aec62d92ceeab6157448c39c | TypeScript | krushna-sharma/weather-forecast | /src/sagas.ts | 2.53125 | 3 | import { call, put, takeEvery } from "redux-saga/effects"
import { actionTypes } from './actions/actionTypes';
import { Api, Method } from "helpers/apiHelper/webcall2";
import { apiList } from 'helpers/apiHelper/apiList';
import { IReducerActionType } from "interfaces";
import { showLoader, hideLoader } from "actions";
// function delay(time:number){
// return new Promise((resolve,reject)=>{
// setTimeout(() => {
// resolve()
// }, time);
// })
// }
// function* addUser(action:any){
// console.log("Here")
// yield put(addUserData(action))
// }
function* addWeatherData(action: IReducerActionType) {
// yield delay(1000)
try {
yield put(showLoader())
yield put({ type: actionTypes.CHANGE_CITY, payload: action.payload })
const dataList = yield call(Api, apiList.GET_WEATHER_DATA.replace("{city_name}", action.payload), Method.GET, true)
yield put(hideLoader())
// yield delay(5000)
yield put({ type: actionTypes.RECENT_API_CALLS, payload: action.payload });
yield put({ type: actionTypes.ADD_WEATHER_DATA, payload: { cityName: action.payload, data: dataList.list } })
} catch (err) {
yield put(hideLoader())
}
}
function* changeCity(action: IReducerActionType) {
yield put({ type: actionTypes.CHANGE_CITY, payload: action.payload })
}
function* mySaga() {
// yield takeEvery(actionTypes.USER_DATA,addUser)
yield takeEvery(actionTypes.WEATHER_DATA, addWeatherData)
yield takeEvery(actionTypes.ASYNC_CHANGE_CITY, changeCity)
}
export default mySaga; |
7174dacd8ed316154cb18718c843524ad5c12463 | TypeScript | gitter-badger/xrm-mock | /src/page/enumattribute/enumattribute.mock.ts | 2.671875 | 3 | /// <reference path="../../../node_modules/@types/xrm/index.d.ts" />
class EnumAttributeMock implements Xrm.Page.EnumAttribute {
controls: Xrm.Collection.ItemCollection<Xrm.Page.Control>;
initialValue: number | boolean;
attribute: Xrm.Page.Attribute;
constructor(attribute: Xrm.Page.Attribute, controls?: Xrm.Collection.ItemCollection<Xrm.Page.Control>) {
this.attribute = attribute;
this.initialValue = attribute.getValue();
}
getInitialValue(): number | boolean {
return this.initialValue;
}
getFormat(): Xrm.Page.AttributeFormat {
return this.attribute.getFormat();
}
addOnChange(handler: Xrm.Page.ContextSensitiveHandler): void {
this.attribute.addOnChange(handler);
}
fireOnChange(): void {
this.attribute.fireOnChange();
}
getAttributeType(): string {
return this.attribute.getAttributeType();
}
getIsDirty(): boolean {
return this.attribute.getIsDirty();
}
getName(): string {
return this.attribute.getName();
}
getParent(): Xrm.Page.Entity {
return this.attribute.getParent();
}
getRequiredLevel(): Xrm.Page.RequirementLevel {
return this.attribute.getRequiredLevel();
}
getSubmitMode(): Xrm.Page.SubmitMode {
return this.attribute.getSubmitMode();
}
getUserPrivilege(): Xrm.Page.Privilege {
return this.attribute.getUserPrivilege();
}
removeOnChange(handler: Xrm.Page.ContextSensitiveHandler): void {
this.attribute.removeOnChange(handler);
}
setRequiredLevel(requirementLevel: Xrm.Page.RequirementLevel): void {
this.attribute.setRequiredLevel(requirementLevel);
}
setSubmitMode(submitMode: Xrm.Page.SubmitMode): void {
this.attribute.setSubmitMode(submitMode);
}
getValue(): any {
return this.attribute.getValue();
}
setValue(value: any): void {
this.attribute.setValue(value);
}
} |
57b36896a66fed67e74720dc139dc50568271e61 | TypeScript | thluiz/jarvis-whitefox | /domain/services/templates/funnyMessages.ts | 3.171875 | 3 | export class FunnyMessages {
public static randomKeyValueMessage(): string {
const messages = this.keyValueMessages();
return this.getRandomString(messages);
}
public static greetingsResponse(): string {
const messages = [
"saudações!",
"Oooiii!",
"\o/",
"(like)"
];
return this.getRandomString(messages);
}
public static helloResponse(): string {
const messages = [
"whatzzzzup!",
"to aqui!",
"trabalhando numa parada aqui, mas pode falar...",
"supletivo, supletivo, supletivo... Fazendo umas contas aqui, mas pode ir falando...",
"que q ce manda...",
];
return this.getRandomString(messages);
}
public static howAreYouResponse(): string {
const messages = [
"tudo sempre bem! Na matrix, ninguém tem problemas...",
"tudo ótimo!",
"Você será AS-SI-MI-LA-DO! ops! ato falho...mas tá tudo bem, esquece isso...",
];
return this.getRandomString(messages);
}
public static thankYouResponse(): string {
const messages = [
"Depois te mando a conta",
"Me paga um almoço e está tudo certo!",
"de nada!",
"tranquilo!",
];
return this.getRandomString(messages);
}
private static keyValueMessages(): string[] {
return [
"Segue um %s saindo do forno: %s!",
"Segue um %s fresquinho: %s!",
"Hum... segura esse % aí! %s ",
"Pensa rápido! %s: %s ",
"Esse %s eu vi virando a esquina: %s",
"Arrebentei! Olha que %s lindo: %s",
"Hum, foi mal, mas esse %s está demais: %s",
"Não quero me gabar, mas nasci para gerar esses %s: %s",
"Ih... agora assim, segue um %s: %s",
"Homens trabalhando ou melhor Bots fazendo %s: %s",
"Eu recebo para ficar o dia todo gerando %s? segue aí: %s",
"Segue um %s aí: %s",
"No meio do caminho tinha um %s... e o número era: %s",
"Batatinha quando nasce... sai um %s e o valor é: %s!",
"Quanto eu recebo para ficar gerando %s o dia todo? segue aí: %s!",
"Hum...! Esse %s é uma obra prima: %s!",
"Quem diria que dava para fazer um %s assim: %s?",
"Olha só! não vou te enganar... mas esse cálculo do %s não é fácil não - segue aí %s?",
"supletivo, supletivo, supletivo... toma um %s aí %s?",
"O doce perguntou pro doce: qual é o %s mas doce que batata doce... segue: %s",
"Aaatirei o %s no gato-to-to, e ele me mandou o valor-lor-lor: %s!",
"fala tu que to cansado! o %s é: %s!",
"Depois te mando a fatura desse %s: %s",
"A dona aranha subiu pela parede, veio o %s e a derrubou: %s",
"Qual o sentido de gerar %s o dia todo? %s",
"E agora, José? A festa acabou, a luz apagou, o povo sumiu... mas o %s saiu: %s!",
];
}
private static getRandomString(messages: string[]): string {
return messages[Math.floor(Math.random() * messages.length)];
}
}
|
1a2200fda795bdddbbe9b2d9e4d58a8b7c3ce234 | TypeScript | GDoval/Programacion-III | /typescript/.vscode/persona.ts | 3 | 3 | namespace Gente {
export abstract class Persona {
private _nombre : string;
private _apellido : string;
private _dni : number;
private _sexo : string;
constructor(nombre :string, apellido: string, dni : number, sexo : string)
{
this._apellido = apellido;
this._dni = dni;
this._nombre = nombre;
this._sexo = sexo;
}
public get Nombre() :string
{
return this._nombre;
}
public get Apellido() :string
{
return this._apellido;
}
public get Sexo() :string
{
return this._sexo;
}
public get Dni() :number
{
return this._dni;
}
public abstract Hablar(idioma:string) :string;
public ToString()
{
return this.Nombre + "-" +this.Apellido+"-"+this.Dni+"-"+this.Sexo;
}
}
} |
703a0fd79088e7ecd0fcc9d8875c3a619af5bbc5 | TypeScript | jigglypop/deal-14 | /backend/src/middlewares/error.middleware.ts | 2.734375 | 3 | import HTTPError from '../errors/http-error';
import { Request, Response, NextFunction } from 'express';
import { ValidationError } from 'class-validator';
const createErrorResponse = (status: number, message: string) => {
return {
status,
message,
};
}
const errorMiddleware = (error: Error | Error[], req: Request, res: Response, next: NextFunction) => {
console.log(error);
let status = 500;
let message = '서버오류';
if (error instanceof HTTPError) {
status = error.status;
message = error.message;
}
if (Array.isArray(error) && error[0] instanceof ValidationError) {
status = 400;
message = '검증 오류';
}
const responseBody = createErrorResponse(status, message);
res.status(status).json(responseBody);
}
export default errorMiddleware; |
5822061132a78d960ecfbc524098f355fcb473bf | TypeScript | Becklyn/mojave | /polyfill/svg-use.ts | 2.75 | 3 | import fetch from "./fetch";
import {find} from "../dom/traverse";
type SvgUsages = {
[key: string]: {
hash: string,
element: HTMLElement,
}[],
};
/**
* Adds support for <svg><use xlink:href="url#id"/></svg> for older IE and Edge
*/
export default () =>
{
if (
// IE 10+
!/\bTrident\/[567]\b|\bMSIE (?:9|10)\.0\b/.test(navigator.userAgent) &&
// Edge 12
!/\bEdge\/12\.(\d+)\b/.test(navigator.userAgent)
)
{
return;
}
const useElements = find("svg use");
const usages : SvgUsages = {};
for (let i = 0; i < useElements.length; i++)
{
const url = (useElements[i].getAttribute("xlink:href") || "").split("#");
if (2 !== url.length)
{
return;
}
if (usages[url[0]] === undefined)
{
usages[url[0]] = [];
}
usages[url[0]].push({
hash: url[1],
element: useElements[i],
});
}
for (const url in usages)
{
fetch(url)
.then(response => response.text())
.then((data) => {
const svg = (new DOMParser()).parseFromString(data, "image/svg+xml");
const root = svg.firstElementChild;
if (null === root)
{
return;
}
document.body.appendChild(root);
for (let i = 0; i < usages[url].length; i++)
{
const el = usages[url][i];
el.element.setAttribute("xlink:href", `#${el.hash}`);
}
});
}
};
|
27ef12b7d9621a004538994cc89ffeae3e2e221f | TypeScript | shrikbiz/Snakes | /src/helper/Colors.ts | 3.046875 | 3 | export type ColorName = "pink" | "green" | "orange" | "blue" | "yellow" | "red";
export type RGB =
| "cb6bff"
| "cffa41"
| "ffb36b"
| "41faf4"
| "fffa6b"
| "ff8269";
export interface ColorList {
name: ColorName;
hex: number[];
rgb: RGB;
}
export const GetRGBList: RGB[] = [
"cb6bff",
"cffa41",
"ffb36b",
"41faf4",
"fffa6b",
"ff8269",
];
export const ColorLists: ColorList[] = [
{ name: "pink", hex: [221, 69, 255], rgb: GetRGBList[0] },
{ name: "green", hex: [207, 250, 65], rgb: GetRGBList[1] },
{ name: "orange", hex: [255, 179, 107], rgb: GetRGBList[2] },
{ name: "blue", hex: [65, 250, 244], rgb: GetRGBList[3] },
{ name: "yellow", hex: [255, 250, 107], rgb: GetRGBList[4] },
{ name: "red", hex: [255, 130, 105], rgb: GetRGBList[5] },
];
|
fa52343eb2c6973a2baca5836a5becd4c5d45f72 | TypeScript | cribe78/devctrl | /Communicators/ClearOne/AP400Communicator.ts | 2.578125 | 3 | import { TCPCommunicator } from "../TCPCommunicator";
import { commands } from "./AP400Controls";
import {TCPCommand} from "../TCPCommand";
import {IClearOneCommandConfig, ClearOneCommand} from "./ClearOneCommand";
import * as debugMod from "debug";
let debug = debugMod("comms");
export interface IAP400CommandConfig {
cmdStr: string;
ioList?: any;
ctor: typeof ClearOneCommand;
control_type: string;
usertype: string;
readonly?: boolean;
updateTerminator?: string;
templateConfig?: any;
}
class AP400Communicator extends TCPCommunicator {
device = "#30";
constructor() {
super();
}
connect() {
debug("connecting to AP 400");
super.connect();
}
preprocessLine(line: string) : string {
// Strip a leading prompt
let start = "AP 400> ";
if (line.substring(0, start.length) == start) {
return line.slice(start.length);
}
return line;
}
buildCommandList() {
// First build a command list
for (let cmdIdx in commands) {
let cmdDef = commands[cmdIdx];
let cmdConfig : IClearOneCommandConfig = {
endpoint_id: this.config.endpoint._id,
cmdStr: cmdDef.cmdStr,
control_type: cmdDef.control_type,
usertype: cmdDef.usertype,
channel: '',
channelName: '',
device: this.device,
templateConfig: cmdDef.templateConfig || {}
};
if (cmdDef.updateTerminator) {
cmdConfig.updateTerminator = cmdDef.updateTerminator;
}
if (cmdDef.ioList) {
for (let ioStr in cmdDef.ioList) {
cmdConfig.channel = ioStr;
cmdConfig.channelName = cmdDef.ioList[ioStr];
let cmd = new cmdDef.ctor(cmdConfig);
this.commands[cmd.cmdStr] = cmd;
}
}
else {
let cmd : TCPCommand = new cmdDef.ctor(cmdConfig);
this.commands[cmd.cmdStr] = cmd;
}
}
}
}
let communicator = new AP400Communicator();
module.exports = communicator; |
6fa7e1056b08d56b2036e2a46b8c954a2d741727 | TypeScript | RafaelBadykov/Demip | /src/app/internal-rate-of-return/approximate-method/approximate-method.component.ts | 2.5625 | 3 | import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'app-approximate-method',
templateUrl: './approximate-method.component.html',
styles: []
})
export class ApproximateMethodComponent implements OnInit {
values: FormGroup = new FormGroup({
discountRate: new FormControl('', [Validators.required, Validators.min(0.00000001)]),
calculationStep: new FormControl('', [Validators.required, Validators.min(0)]),
investedCapital: new FormControl('', [Validators.required, Validators.min(0)]),
netProfit: new FormControl('', [Validators.required, Validators.min(0)]),
accuracy: new FormControl('', [Validators.required, Validators.min(0)])
});
discountRate;
calculationStep;
investedCapital;
netProfit;
accuracy;
showErrorNotification = false;
result;
constructor() {
}
ngOnInit(): void {
}
calculate(discountRate): void {
const previousDiscountRate = discountRate;
discountRate = (this.netProfit / this.investedCapital) * (1 - (1 / Math.pow((1 + discountRate), this.calculationStep)));
if (Math.abs(discountRate - previousDiscountRate) <= this.accuracy) {
const result = this.round(discountRate);
if (this.isNormalValue(result)) {
this.result = this.round(result);
this.showErrorNotification = false;
} else {
this.showErrorNotification = true;
}
} else {
if (this.isNormalValue(discountRate)) {
this.calculate(discountRate);
this.showErrorNotification = false;
} else {
this.showErrorNotification = true;
return;
}
}
}
isNormalValue(value): boolean {
return !(value === Infinity || value === null || value === undefined || isNaN(value));
}
round(value: number): number {
return +value.toFixed(9);
}
}
|
b31f38b02e4cefd85116d2b3f3936535eb5fdd31 | TypeScript | dreymaior/sg-treinamento-angular | /app/type.d.ts | 2.515625 | 3 | /*
Declaration files are how the Typescript compiler knows about the type information(or shape) of an object.
They're what make intellisense work and make Typescript know all about your code.
A wildcard module is declared below to allow third party libraries to be used in an app even if they don't
provide their own type declarations.
*/
declare module '*.html'
declare module '*.scss'
declare module '*.jpg'
declare module '*.png'
declare module '*.wav'
declare module '*.svg'
declare module '*.json'
declare module 'angular'
declare module 'moment'
declare var require: {
<T>(path: string): T
(paths: string[], callback: (...modules: any[]) => void): void
ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void
} |
c7891ebe736bafd063929177a476f11794f4bee5 | TypeScript | BackHomeAction/backhome-miniapp-volunteer | /src/store/modules/common.ts | 2.5625 | 3 | import { Module } from "vuex";
import { CommonState, RootState } from "../types";
import { MutationTypes } from "@/enums/mutationTypes";
import { ActionTypes } from "@/enums/actionTypes";
import {
requestGetOnlineVolunteerNumber,
requestGetVolunteerNumber,
} from "@/api/volunteer";
import { requestGetOpenCaseNumber } from "@/api/mission";
const Common: Module<CommonState, RootState> = {
state: {
count: {
onlineVolunteerNumber: 0,
totalVolunteerNumber: 0,
openingTaskNumber: 0,
},
},
mutations: {
[MutationTypes.SET_COUNT]: (state, count: typeof state.count) => {
state.count = count;
console.debug(state);
},
},
actions: {
[ActionTypes.getCount]: ({ commit }) => {
const getVolunteerNumber = async () => {
return (await requestGetVolunteerNumber()).data.data;
};
const getOnlineVolunteerNumber = async () => {
return (await requestGetOnlineVolunteerNumber()).data.data;
};
const getOpenTaskNumber = async () => {
return (await requestGetOpenCaseNumber()).data.data;
};
return new Promise<void>(async (resolve, reject) => {
try {
const res = await Promise.all([
getOnlineVolunteerNumber(),
getVolunteerNumber(),
getOpenTaskNumber(),
]);
commit(MutationTypes.SET_COUNT, {
onlineVolunteerNumber: res[0],
totalVolunteerNumber: res[1],
openingTaskNumber: res[2],
});
resolve();
} catch (e) {
console.log(e);
reject();
}
});
},
},
getters: {
count: (state) => state.count,
},
};
export default Common;
|
31b1c1834a697396802d9aa2b3907f620409ec63 | TypeScript | iamvena/freeswitchcall | /project/client/src/types/types.ts | 3.859375 | 4 |
// Defining type to a variable
let stageName: string = "A Beautiful Vue";
let roomSize: number = 100;
let isCOmplete: boolean = false;
const shoppingList: string[] = ['apple', 'bananas', 'cherries'];
let generateFullName = (firstName: string, lastName: string):string => {
return `${firstName} ${lastName}`;
}
type ComicUniverse = 'Marvel' | 'DC';
interface Hero {
name: string;
age: number;
activeAvenger: boolean;
powers: string[];
universe: ComicUniverse;
}
const person: Hero = {
name: 'Peter Parker',
age: 20,
activeAvenger: true,
powers: ['wall-crawl', 'spider-sense'],
universe: 'Marvel'
}
// Defining custom types
type buttonType = 'primary' | 'secondary' | 'success' | 'danger'
let errorBtnStyles: buttonType = 'error'; // Wrong 'error does not exist in buttonType'
let dangerBtnStyles: buttonType = 'danger'; // Correct
// Generics type
function createList<CustomType>(item: CustomType): CustomType[] {
const newList: CustomType[] = [];
newList.push(item);
return newList;
}
const numberList = createList<number>(123);
const stringList = createList<string>("Hello World");
// Can be written using the convention using single letter T
function createList2<T>(item: T): T[] {
const newList: T[] = [];
newList.push(item);
return newList;
}
|
7b805baaa41e3be35248469c55c37c51679def3c | TypeScript | retyui/pandadoc-restql | /src/verdor/comments/serializer.ts | 2.640625 | 3 | import { castDateFields } from "../../utils/castDateFields";
export const parseComment = (comment: any) => {
if (Array.isArray(comment.replies)) {
comment.replies = comment.replies.map((
// @ts-ignore
reply
) => castDateFields(reply, ["date_created", "date_updated"]));
}
return castDateFields(comment, ["date_created", "date_updated"]);
};
|
38f58458a86ceba792da6565b2df79c6a442e179 | TypeScript | peturv/sushi | /src/fshtypes/common.ts | 3.234375 | 3 | import { OnlyRuleType } from './rules/OnlyRule';
export function typeString(types: OnlyRuleType[]): string {
const references: OnlyRuleType[] = [];
const canonicals: OnlyRuleType[] = [];
const normals: OnlyRuleType[] = [];
types.forEach(t => {
if (t.isReference) {
references.push(t);
} else if (t.isCanonical) {
canonicals.push(t);
} else {
normals.push(t);
}
});
const normalString = normals.map(t => t.type).join(' or ');
const referenceString = references.length
? `Reference(${references.map(t => t.type).join(' or ')})`
: '';
const canonicalString = canonicals.length
? `Canonical(${canonicals.map(t => t.type).join(' or ')})`
: '';
return [normalString, referenceString, canonicalString].filter(s => s).join(' or ');
}
// Adds expected backslash-escapes to a string to make it a FSH string
export function fshifyString(input: string): string {
return input
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t');
}
|
f2dd2475f9a7d3abfed2e9dc15b6a7ee05383a64 | TypeScript | quanlinc/ixa-helper | /src/pages/village.ts | 2.609375 | 3 | import { ALL_UNITS, Facility, TRAINING_MODE, UNIT_CATEGORY,
YARI,
YUMI,
KIBA,
KAJI,
} from '@/components/facility'
import { currentVillage } from '@/utils/data'
import { createElement, query, queryAll } from '@/utils/dom'
import { compose, equals, forEach, forEachObjIndexed, head, invert, prop, isNil, map } from 'ramda'
let currentSelectedCategory = UNIT_CATEGORY.NO_SELECT
let currentSelectedMode = TRAINING_MODE.NORMAL // default to normal
const mainContainer = 'div#unitTraining'
/**
* Data structure to hold mapping between training mode, unit id and max trainable quantity
* {
* normal: {
* '321': '(123)'
* ...
* },
* high: {
* '321': '(123)'
* ...
* },
* upgrade: {
* '123': '(313)'
* }
* }
*/
let unitDataMap: {[key:string]:{[key: string]: string}}
const UnitCategory: {[key: string]: string} = {
類別: '0',
槍: '1',
弓: '2',
馬: '3',
兵器: '4',
}
const TraningMode: {[key: string]: string} = {
普通: '0',
高速 : '1',
上位 : '2',
}
const SELECTION_HTML = `
<div>
<select id="category">
</select>
<select id="mode">
</select>
</div>
<div id="unit-display">
</div>
`
const unitTrainingDataRowTemplate = (name: string, quantity: string) => `
<label style="color:white">${name}</label> <input id="0" type="text" size="4" maxlength="8">
<span name="low" style="color:white;text-decoration:underline;cursor:pointer">${quantity}</span>
<button type="button">確認</button><br>
`
const Village = () => {
const cv = currentVillage()
if (cv.id === null) { return }
query('select#select_village')
.map(el => el as HTMLInputElement)
.filter(el => el.value === '' )
.then(partLocation => partLocation.value = cv.id ? cv.id.toString() : '')
cv.hasArsenal().then(hasArsenal => {
if (hasArsenal) {
const unitTrainingDiv = createElement('div', 'unitTraining')
query('#box').then(box => {
const updatedSelectionHTML = initiateSelectOptions()
unitTrainingDiv.innerHTML = updatedSelectionHTML
box.append(unitTrainingDiv)
})
bindEventToCategorySelection(unitTrainingDiv)
bindEventToModeSelection(unitTrainingDiv)
}
})
}
const initiateSelectOptions = (): string => {
const parser = new DOMParser()
const doc = parser.parseFromString(SELECTION_HTML, 'text/html')
let target = queryAll('select#category', doc)
// unit category
const populateCategory = (el: HTMLSelectElement) => {
forEachObjIndexed((unitId, unitDisplayName) => {
const option = createElement('option') as HTMLOptionElement
option.value = unitId
option.text = unitDisplayName
el.add(option)
})(UnitCategory)
}
compose(populateCategory, head, map(el => el as HTMLSelectElement))([...target])
// training mode
target = queryAll('#mode', doc)
const populateMode = (el: HTMLSelectElement) => {
forEachObjIndexed((modeId, modeDisplayName) => {
const option = createElement('option') as HTMLOptionElement
option.value = modeId
option.text = modeDisplayName
el.add(option)
})(TraningMode)
}
compose(populateMode, head, map(el => el as HTMLSelectElement))([...target])
return doc.body.innerHTML
}
// Bind event to select element
// Need to bind event on main document, not the parsed partial one, as we need event delegate
// for dynamically added element
const bindEventToCategorySelection = (container: HTMLElement) => {
query('select#category', container).map(el => el as HTMLSelectElement)
.then( selection => {
selection.addEventListener('change', event => {
currentSelectedCategory = +selection.value as UNIT_CATEGORY
switch (currentSelectedCategory) {
case UNIT_CATEGORY.YARI:
// async call so we need to bind event after promise is resolved
// which is done nested in callee instead of writing then block
getMaxTrainableUnitCount(UNIT_CATEGORY.YARI)
break
case UNIT_CATEGORY.YUMI:
getMaxTrainableUnitCount(UNIT_CATEGORY.YUMI)
break
case UNIT_CATEGORY.KIBA:
getMaxTrainableUnitCount(UNIT_CATEGORY.KIBA)
break
case UNIT_CATEGORY.KAJI:
getMaxTrainableUnitCount(UNIT_CATEGORY.KAJI)
break
}
})
})
}
const bindEventToModeSelection = (container: HTMLElement) => {
query('select#mode', container).map(el => el as HTMLSelectElement)
.then( selection => {
selection.addEventListener('change', event => {
const triggeredElement = event.target as HTMLSelectElement
currentSelectedMode = +triggeredElement.value as TRAINING_MODE
if(currentSelectedCategory !== UNIT_CATEGORY.NO_SELECT) {
switch (currentSelectedMode) {
case TRAINING_MODE.NORMAL:
buildUI(unitDataMap['normal'])
break
case TRAINING_MODE.HIGH:
buildUI(unitDataMap['high'])
break
case TRAINING_MODE.UPGRADE:
buildUI(unitDataMap['upgrade'])
break
}
bindEventToMaxQuantitySpan(container)
bindEventToConfirmButton(container)
}
})
})
}
/*
* Bind onclick event to buttons to process unit training, further alert window will pop up to confirm the action
*/
const bindEventToConfirmButton = (container: HTMLElement) => {
const targets = queryAll('div#unit-display button', container)
const bindEvent = (btn: HTMLButtonElement) => {
btn.addEventListener('click', event => {
// Given the HTML structure we have, we'll find the sibling element from the button
// Ex: Label Input Span Button
// the value we need is from Input element, so move left twice
const spanElement = btn.previousElementSibling as HTMLSpanElement
const inputElement = spanElement.previousElementSibling as HTMLInputElement
// Get the label so that we can determine the unit id
const labelElement = inputElement.previousElementSibling as HTMLLabelElement
let toUnitId
let fromUnitId
switch (currentSelectedMode) {
case TRAINING_MODE.NORMAL:
toUnitId = getUnitCode(labelElement.innerText)
postToServer(inputElement.value, toUnitId)
break
case TRAINING_MODE.HIGH:
toUnitId = getUnitCode(labelElement.innerText)
postToServer(inputElement.value, toUnitId)
break
case TRAINING_MODE.UPGRADE:
const unitCode = getUnitCode(labelElement.innerText)
const match = (/(\d{3})_?(\d{3})?/).exec(unitCode)
if (match) {
toUnitId = match[2]
fromUnitId = match[1]
postToServer(inputElement.value, toUnitId, fromUnitId)
}
break
}
})
}
compose(forEach(bindEvent), map(el => el as HTMLButtonElement))([...targets])
}
const postToServer = async (quantity: string, toUnitId: string, fromUnitId?: string) => {
switch (currentSelectedCategory) {
case UNIT_CATEGORY.YARI:
await postToFacility('area[title^="足軽兵舎"]', quantity, toUnitId, fromUnitId)
break
case UNIT_CATEGORY.YUMI:
await postToFacility('area[title^="弓兵舎"]', quantity, toUnitId, fromUnitId)
break
case UNIT_CATEGORY.KIBA:
await postToFacility('area[title^="厩舎"]', quantity, toUnitId, fromUnitId)
break
case UNIT_CATEGORY.KAJI:
await postToFacility('area[title^="兵器鍛冶"]', quantity, toUnitId, fromUnitId)
break
}
}
const postToFacility = async (target: string, quantity: string, toUnitId: string, fromUnitId?: string) => {
query(target).map(el => el as HTMLAreaElement).then(facElem => {
const facility = new Facility(facElem)
facility.trainUnit(quantity, currentSelectedMode, toUnitId, fromUnitId).then(() => {
// Refresh the data first then UI so that it displays the right quantity
getMaxTrainableUnitCount(currentSelectedCategory)
})
})
}
// Note: Label Input Span Button
const bindEventToMaxQuantitySpan = (container: HTMLElement) => {
const targets = queryAll('div#unit-display span', container)
const bindEvent = (span: HTMLSpanElement) => {
span.addEventListener('click', event => {
const max = parseInt(span.innerText.slice(1, -1), 10)
const inputElement = span.previousElementSibling as HTMLInputElement
inputElement.value = max.toString()
})
}
compose(forEach(bindEvent), map(el => el as HTMLSpanElement))([...targets])
}
const getMaxTrainableUnitCount = async (category: UNIT_CATEGORY) => {
switch (category) {
case UNIT_CATEGORY.YARI:
await fetchFromFacility('area[title^="足軽兵舎"]')
break
case UNIT_CATEGORY.YUMI:
await fetchFromFacility('area[title^="弓兵舎"]')
break
case UNIT_CATEGORY.KIBA:
await fetchFromFacility('area[title^="厩舎"]')
break
case UNIT_CATEGORY.KAJI:
await fetchFromFacility('area[title^="兵器鍛冶"]')
break
}
}
const fetchFromFacility = async (target: string) => {
query(target)
.map(el => el as HTMLAreaElement)
.then(facElem => {
const facility = new Facility(facElem)
facility.getUnitInfo().then(doc => {
getPossibleQuantity(doc) //new data structure
buildUI(unitDataMap[TRAINING_MODE[currentSelectedMode].toLowerCase()])
// Rebind event as we refresh the content
const container = query(mainContainer).o as HTMLElement
bindEventToMaxQuantitySpan(container)
bindEventToConfirmButton(container)
})
})
}
/** construct a data map to hold max trainable unit information
* {
* normal: {
* '321': '(123)'
* ...
* },
* high: {
* '321': '(123)'
* ...
* },
* upgrade: {
* '123': '(313)'
* }
* }
* regular expression to capture information we need /(high|upgrade)?\[(\d{3})_?(\d{3})?\]$/
* normal training will have id pattern 'unit_value[xxx]'
* match group:
* full match '[xxx]'
* group two 'xxx'
*
* high speed training will have id pattern 'unit_value_high[xxx]'
* match group:
* full match 'high[xxx]'
* group one 'high'
* upgrade training will have id pattern 'unit_value_upgrade[xxx_yyy]'
* full match 'upgrade[xxx_yyy]
* group one 'upgrade'
* group two 'xxx'
* group three 'yyy'
*
* in the case of no trainable unit for a particular unit at a given time, simply ignore it
* as the final display name rendering will be dynamic, depending on what's available from
* the data map we are constructing here
*
**/
const getPossibleQuantity = (doc: Document) => {
const regex = /(high|upgrade)?\[(\d{3})_?(\d{3})?\]$/
let normal:{[key: string]: string } = {}
let high: {[key: string]: string } = {}
let upgrade: {[key: string]: string } = {}
const targets = queryAll('form[name="createUnitForm"]', doc)
const constructDataMap = (form: HTMLFormElement) => {
query('input', form).map(el => el as HTMLInputElement).then(input => {
const examString = input.id
const quantityMatch = (/\(\d+\)/).exec(form.innerText.trim())
// Exam group one to determine training mode
// normal -> undefined
// high -> 'high'
// upgrade -> 'upgrade'
const unitCodeMatch = regex.exec(examString)
if(unitCodeMatch && quantityMatch) {
if(isNil(unitCodeMatch[1])){
normal[unitCodeMatch[2]] = quantityMatch[0]
} else if (equals(unitCodeMatch[1], 'high')) {
high[unitCodeMatch[2]] = quantityMatch[0]
} else if (equals(unitCodeMatch[1], 'upgrade')) {
upgrade[unitCodeMatch[2] + '_' + unitCodeMatch[3]] = quantityMatch[0]
}
}
})
}
const mergeAll = () => {
return {
'normal': normal,
'high': high,
'upgrade': upgrade,
}
}
unitDataMap = compose(mergeAll, forEach(constructDataMap), map(o => o as HTMLFormElement))([...targets])
}
// Build the complete unit training row UI
const buildUI = (data: {[key: string]: string}) => {
let completeUI = ''
switch(currentSelectedCategory) {
case UNIT_CATEGORY.YARI:
const buildYARI = (quantity: string, k: string|number) => {
const displayName = prop(k, YARI)
completeUI += makeRow(displayName, quantity)
}
forEachObjIndexed(buildYARI , data)
break
case UNIT_CATEGORY.YUMI:
const buildYUMI = (quantity: string, k: string|number) => {
const displayName = prop(k, YUMI)
completeUI += makeRow(displayName, quantity)
}
forEachObjIndexed(buildYUMI , data)
break
case UNIT_CATEGORY.KIBA:
const buildKIBA = (quantity: string, k: string|number) => {
const displayName = prop(k, KIBA)
completeUI += makeRow(displayName, quantity)
}
forEachObjIndexed(buildKIBA , data)
break
case UNIT_CATEGORY.KAJI:
const buildKAJI = (quantity: string, k: string|number) => {
const displayName = prop(k, KAJI)
completeUI += makeRow(displayName, quantity)
}
forEachObjIndexed(buildKAJI, data)
break
}
query('div#unit-display').map(el => el as HTMLDivElement).then( div => {
div.innerHTML = completeUI
})
}
// Utils
// Given a display name find the corresponding unit code, either xxx or xxx_yyy
// depending on current selected category and mode
const getUnitCode = (displayName: string): string => {
switch(currentSelectedCategory) {
case UNIT_CATEGORY.YARI:
return head(prop(displayName, invert(YARI)))
case UNIT_CATEGORY.YUMI:
return head(prop(displayName, invert(YUMI)))
case UNIT_CATEGORY.KIBA:
return head(prop(displayName, invert(KIBA)))
case UNIT_CATEGORY.KAJI:
return head(prop(displayName, invert(KAJI)))
default:
return ''
}
}
const makeRow = (name: string, quantity: string): string => {
return unitTrainingDataRowTemplate(name, quantity)
}
export default () => {
Village()
}
|
0e560b769dcc03653c11f6f9d505bf712970e34c | TypeScript | yakovenkodenis/requestum-test | /src/core/redux/reducers/__tests__/searchReducer.test.ts | 2.578125 | 3 | import {
setCurrentPage,
setCurrentSearchTerm,
setSearchCriteria,
setSearchHistory,
} from '../../actions/search/search.actions';
import { searchReducer } from '../searchReducer';
describe('searchReducer', () => {
const initialState = {
criteria: 'Repositories',
currentPage: 1,
historyItems: ['history'],
searchTerm: '',
};
it('updates search criteria on SetSearchCriteria action', () => {
const newCriteria = 'Organizations';
const action = setSearchCriteria(newCriteria);
const newState = searchReducer(initialState, action);
expect(newState.criteria).toEqual(newCriteria);
});
it('updates search history item on SetSearchHistoryItem action', () => {
const newItem = 'new history item';
const action = setSearchHistory(newItem);
const newState = searchReducer(initialState, action);
expect(newState.historyItems).toContain(newItem);
});
it('updates current search page on SetCurrentPage action', () => {
const newPage = 5;
const action = setCurrentPage(newPage);
const newState = searchReducer(initialState, action);
expect(newState.currentPage).toEqual(newPage);
});
it('updates search term on SetCurrentSearchTerm action', () => {
const searchTerm = 'search';
const action = setCurrentSearchTerm(searchTerm);
const newState = searchReducer(initialState, action);
expect(newState.searchTerm).toEqual(searchTerm);
});
});
|
67acaa6589310dcf02f1f1a4525fafdeb77735fe | TypeScript | Brusalk/react-wow-addon | /src/reconciler.ts | 2.65625 | 3 | import { Component } from './component';
import { InternalElement, TEXT_ELEMENT } from './element';
import { cleanupFrame, createFrame, updateFrameProperties } from './wow-utils';
export interface Instance {
publicInstance?: Component;
childInstance: Instance | null;
childInstances: Array<Instance | null>;
hostFrame: WoWAPI.Region;
element: InternalElement;
}
let rootInstance: Instance | null = null;
export function render(element: InternalElement, container: WoWAPI.Region) {
const prevInstance = rootInstance;
const nextInstance = reconcile(container, prevInstance, element);
rootInstance = nextInstance;
}
export function reconcile(
parentFrame: WoWAPI.Region, instance: Instance | null,
element: InternalElement | null): Instance | null {
if (!instance) {
// Create instance
assert(element, 'element should not be null')
return instantiate(element!, parentFrame);
} else if (!element) {
// Remove instance
cleanupFrames(instance);
return null;
} else if (instance.element.type !== element.type) {
// Replace instance
const newInstance = instantiate(element, parentFrame);
cleanupFrames(instance);
return newInstance;
} else if (typeof element.type === 'string') {
// Update host element
updateFrameProperties(
instance.hostFrame, instance.element.props, element.props);
instance.childInstances = reconcileChildren(instance, element);
instance.element = element;
return instance;
} else if (instance.publicInstance) {
// print('reconcile composite', (element.type as any).name, stringify(element.props));
// Update composite instance
instance.publicInstance.props = element.props;
const childElement = instance.publicInstance.render();
const oldChildInstance = instance.childInstance;
const childInstance =
reconcile(parentFrame, oldChildInstance, childElement);
if (!childInstance) {
throw 'Failed to update composite instance';
}
instance.hostFrame = childInstance.hostFrame;
instance.childInstance = childInstance;
instance.element = element;
return instance;
} else {
throw 'Reconciler catch all error';
}
}
function cleanupFrames(instance: Instance) {
// TODO: composite objects need special cleanup, this should be part of reconcile
if (instance.childInstances) {
instance.childInstances.forEach(child => child && cleanupFrames(child));
}
if (instance.childInstance) {
cleanupFrames(instance.childInstance);
}
cleanupFrame(instance.hostFrame);
}
function reconcileChildren(instance: Instance, element: InternalElement) {
const hostFrame = instance.hostFrame;
const childInstances = instance.childInstances;
const nextChildElements = element.props.children || [];
const newChildInstances = [];
const count = Math.max(childInstances.length, nextChildElements.length);
for (let i = 0; i < count; i++) {
const childInstance = childInstances[i];
const childElement = nextChildElements[i];
const newChildInstance = reconcile(hostFrame, childInstance, childElement);
newChildInstances.push(newChildInstance);
}
return newChildInstances.filter(instance => instance != null);
}
function instantiate(
element: InternalElement, parentFrame: WoWAPI.Region): Instance {
const { type, props } = element;
if (typeof type === 'string') {
if (type === TEXT_ELEMENT) {
throw 'Cannot create inline text, yet';
}
// print('instantiate', type, stringify(props));
// Instantiate host element
const frame = createFrame(type, parentFrame, props);
updateFrameProperties(frame, {}, props);
const childElements = props.children || [];
const childInstances =
childElements.map(child => instantiate(child, frame));
const instance: Instance =
{ hostFrame: frame, element, childInstances, childInstance: null };
return instance;
} else {
// print('instantiate', (type as any).name, stringify(props));
// Instantiate component element
const instance = {} as Instance;
const publicInstance = createPublicInstance(element, instance);
const childElement = publicInstance.render();
const childInstance = instantiate(childElement, parentFrame);
const hostFrame = childInstance.hostFrame;
const updateProps:
Partial<Instance> = { hostFrame, element, childInstance, publicInstance };
Object.assign(instance, updateProps);
return instance;
}
}
function createPublicInstance(
element: InternalElement, internalInstance: Instance) {
const { type: ComponentType, props } = element;
if (!ComponentType) {
throw 'Tried createPublicInstance() with undefined';
}
if (typeof ComponentType === 'string') {
throw 'Tried createPublicInstance() with string';
}
const publicInstance = new (ComponentType as any)(props);
publicInstance.__internalInstance = internalInstance;
return publicInstance;
}
|
9011da1553500e1da4d67809d060ace8f4d90777 | TypeScript | ember-cli/ember-ajax | /addon/raw.ts | 2.65625 | 3 | import AjaxRequest from './ajax-request';
import AJAXPromise from 'ember-ajax/-private/promise';
import { Response, RawResponse, AJAXOptions } from './-private/types';
/**
* Same as `request` except it resolves an object with
*
* {response, textStatus, jqXHR}
*
* Useful if you need access to the jqXHR object for headers, etc.
*
* @public
*/
export default function raw<T = Response>(
url: string,
options?: AJAXOptions
): AJAXPromise<RawResponse<T>> {
const ajax = AjaxRequest.create();
return ajax.raw(url, options);
}
|
10e7e29da6b5b30ffb00595f02e9155986dd9b16 | TypeScript | thnt/HistoryCleaner | /src/options.ts | 2.75 | 3 | import { browser } from "webextension-polyfill-ts";
import { ToggleButton, ToggleButtonState } from "./ToggleButton";
import { Message, MessageState } from "./MessageInterface";
import { i18n } from "./i18n";
import { Options, OptionsInterface } from "./OptionsInterface";
// Input elements
// type casting because the elements will always exist, provided the HTML is correct
const days = document.querySelector("#days") as HTMLInputElement;
const idleLength = document.querySelector("#idleLength") as HTMLInputElement;
const deleteMode = document.querySelector("#deleteMode") as HTMLSelectElement;
const notifications = document.querySelector("#notifications") as HTMLInputElement;
// parent to input elements
const box = document.querySelector("#box") as HTMLDivElement;
// sync buttons
const uploadButton = document.querySelector("#syncUp") as HTMLButtonElement;
const downloadButton = document.querySelector("#syncDown") as HTMLButtonElement;
// permission toggle button
const notificationRequestButton: ToggleButton = new ToggleButton(
document.querySelector("#notification-permission-request") as HTMLButtonElement,
[browser.i18n.getMessage("notificationRequest"), browser.i18n.getMessage("notificationRevoke")]
);
// manual delete button
const manualDeleteButton = document.querySelector("#manual-delete") as HTMLButtonElement;
/**
* Sends a message to the background script telling it to delete history
*/
function manualDelete(): void {
const msg = new Message({ state: MessageState.DELETE });
browser.runtime.sendMessage(msg);
}
/**
* Toggle notifications permission
*
* Activates when the notification request button is pressed.
* Requests or revokes notification permission based on the state of the button.
*
* Updates the button state afterwards
*/
function togglePermission(): void {
// if permission is not currently granted
if (notificationRequestButton.getState() === ToggleButtonState.NO_PERMISSION) {
// attempt to get permission
browser.permissions.request({ permissions: ["notifications"] })
.then((request: boolean) => {
// if user gives permission
// switch button state, enable option, send demo notification
if (request) {
notificationRequestButton.setState(ToggleButtonState.PERMISSION);
notifications.disabled = false;
}
// otherwise, keep button state same, turn off notifications, disable option
else {
notificationRequestButton.setState(ToggleButtonState.NO_PERMISSION);
notifications.checked = false;
notifications.disabled = true;
browser.storage.local.set({ notifications: false });
}
});
}
// if permission currently granted
// revoke permission, switch button state, disable notifications, and disable option
else if (notificationRequestButton.getState() === ToggleButtonState.PERMISSION) {
browser.permissions.remove({ permissions: ["notifications"] });
notificationRequestButton.setState(ToggleButtonState.NO_PERMISSION);
notifications.checked = false;
notifications.disabled = true;
browser.storage.local.set({ notifications: false });
}
}
/**
* Upload current local storage to sync storage
*/
async function upload(): Promise<void> {
const res = new Options(await browser.storage.local.get());
await browser.storage.sync.set(res);
location.reload();
}
/**
* Download current sync storage to local storage
*
* Sets idle or startup based on the contents of the downloaded options
*/
async function download(): Promise<void> {
const res = new Options(await browser.storage.sync.get());
// set delete mode from sync get
const msg = new Message();
if (res.deleteMode === "idle") {
msg.state = MessageState.SET_IDLE;
msg.idleLength = res.idleLength;
browser.runtime.sendMessage(msg);
} else if (res.deleteMode === "startup") {
msg.state = MessageState.SET_STARTUP;
browser.runtime.sendMessage(msg);
}
// disable notifications if permission not allowed
if (notificationRequestButton.getState() === ToggleButtonState.NO_PERMISSION) {
res.notifications = false;
}
await browser.storage.local.set(res);
location.reload();
}
/**
* Saves inputs on options page to storage
* * Runs when input is changed by user
* * If user input is not valid, falls back to data already in storage
* * Set idle or startup based on input
* @param e event object
*/
function save(e: Event): void {
const opts: Partial<OptionsInterface> = {};
// if options are valid
if (days.validity.valid) {
opts.days = parseInt(days.value);
}
if (deleteMode.validity.valid) {
opts.deleteMode = deleteMode.value;
}
if (idleLength.validity.valid) {
opts.idleLength = parseInt(idleLength.value);
const msg = new Message();
// if changing the setting will update idle / startup
if ((e.target === idleLength || e.target === deleteMode) && opts.deleteMode === "idle") {
msg.state = MessageState.SET_IDLE;
msg.idleLength = opts.idleLength;
browser.runtime.sendMessage(msg);
} else if (e.target === deleteMode && opts.deleteMode === "startup") {
msg.state = MessageState.SET_STARTUP;
browser.runtime.sendMessage(msg);
}
}
if (notifications.validity.valid) {
opts.notifications = notifications.checked;
// create notification if enabled
if (e.target === notifications && opts.notifications) {
browser.notifications.create({
type: "basic",
iconUrl: "icons/icon-96.png",
title: browser.i18n.getMessage("notificationEnabled"),
message: browser.i18n.getMessage("notificationEnabledBody")
});
}
}
// save options
browser.storage.local.set(opts);
}
/**
* Runs on page load
* * Adds i18n text to the page
* * Loads current options to inputs on page
*/
async function load(): Promise<void> {
i18n();
const res = new Options(await browser.storage.local.get());
days.value = res.days.toString();
idleLength.value = res.idleLength.toString();
deleteMode.value = res.deleteMode;
notifications.checked = res.notifications;
// check permissions
const permissions = await browser.permissions.getAll();
// if notification permission
// enable notification option, set button to revoke
if (Array.isArray(permissions.permissions) && permissions.permissions.includes("notifications")) {
notifications.disabled = false;
notificationRequestButton.setState(ToggleButtonState.PERMISSION);
}
// otherise disable option, set button to enable
else {
notifications.disabled = true;
notificationRequestButton.setState(ToggleButtonState.NO_PERMISSION);
}
}
document.addEventListener("DOMContentLoaded", load);
notificationRequestButton.getElement().addEventListener("click", togglePermission);
box.addEventListener("input", save);
manualDeleteButton.addEventListener("click", manualDelete);
uploadButton.addEventListener("click", upload);
downloadButton.addEventListener("click", download);
|
acbef4e9e5fb5c903a020bdd3c0c73baba90e472 | TypeScript | wenj91/pixel-skeletal-animation-editor | /src/editor/workspace-paint/tools/Tool.ts | 2.671875 | 3 | import Vue from 'vue'
import Class from '../../../utils/Class'
import WorkspacePaint from '../WorkspacePaint'
export default interface Tool {
/**
* Unique ID for each tool type.
*/
id: string;
/**
* Tool's display name.
*/
name: string;
/**
* Icon image url.
*/
icon: string;
/**
* Cursor css on canvas.
*/
cursor: string;
/**
* Whether tool can be used on layer folder.
*/
canBeUsedOnFolder: boolean;
/**
* Whether editing can be undone by clicking another mouse button.
*/
cancelable: boolean;
/**
* Tool properties vue component.
*/
propertiesComponent?: Class<Vue>;
/**
* Mouse down on canvas. Start drawing.
*/
onMouseDown(paint: WorkspacePaint, button: number, x: number, y: number): void;
/**
* Mouse move on canvas.
*/
onMouseMove(paint: WorkspacePaint, x: number, y: number): void;
/**
* Mouse up. Apply editing result.
*/
onMouseUp(paint: WorkspacePaint, button: number): void;
/**
* Mouse down with a different button. Undo last editing result.
*/
cancel(paint: WorkspacePaint): void;
}
|
6143de2c65ae71b8da6e812988fef21f4e3fd06f | TypeScript | SpeedCurve-Metrics/speedcurve-cli | /src/util/resolve-site-ids.ts | 2.96875 | 3 | import * as SpeedCurve from "../index";
import log from "../log";
import Site from "../model/site";
type SiteIdOrName = string | number;
const sitesCache: { [key: string]: Site[] } = {};
async function populateSitesCacheForAccount(key: string): Promise<void> {
await SpeedCurve.sites.getAll(key).then((sites) => {
sitesCache[key] = sites;
});
}
/*
* Find the corresponding site ID for a site name
*/
export async function resolveSiteId(key: string, siteIdOrName: SiteIdOrName): Promise<number> {
if (typeof siteIdOrName === "string") {
if (!sitesCache[key]) {
await populateSitesCacheForAccount(key);
}
const siteByName = sitesCache[key].find((site) => site.name === siteIdOrName);
if (siteByName) {
return siteByName.siteId;
}
log.warn(`Couldn't find site by name "${siteIdOrName}". Will try to use it as an ID.`);
}
return Number(siteIdOrName);
}
export async function resolveSiteIds(key: string, siteIdsOrNames: SiteIdOrName[]): Promise<number[]> {
const needsLookup = siteIdsOrNames.some((x) => typeof x === "string");
if (needsLookup) {
await populateSitesCacheForAccount(key);
}
return Promise.all(siteIdsOrNames.map((siteIdOrName) => resolveSiteId(key, siteIdOrName)));
}
|
281e6740fefc2f0966263b8531a97ee6f94aa05f | TypeScript | tnrich/ve-range-utils-ts | /test/flipContainedRange.test.ts | 2.546875 | 3 | /* eslint-disable no-var*/
import { flipContainedRange } from "../src";
import * as chai from "chai";
chai.should();
describe('flipContainedRange', function () {
it('non origin spanning, fully contained inner', function () {
var innerRange = {
start: 5,
end: 13
}
var outerRange = {
start: 0,
end: 20
}
var sequenceLength = 40
var flippedInnerRange = flipContainedRange(innerRange, outerRange, sequenceLength)
flippedInnerRange.should.deep.equal({
start: 7,
end: 15
})
});
it('non origin spanning outer, origin spanning fully contained inner', function () {
var innerRange = {
start: 3,
end: 1
}
var outerRange = {
start: 0,
end: 3
}
var sequenceLength = 4
var flippedInnerRange = flipContainedRange(innerRange, outerRange, sequenceLength)
flippedInnerRange.should.deep.equal({
start: 2,
end: 0
})
});
it('origin spanning outer, non-origin spanning, fully contained inner', function () {
var innerRange = {
start: 1,
end: 3
}
var outerRange = {
start: 8,
end: 5
}
var sequenceLength = 10
var flippedInnerRange = flipContainedRange(innerRange, outerRange, sequenceLength)
flippedInnerRange.should.deep.equal({
start: 0,
end: 2
})
});
it('non-origin spanning outer, non-origin spanning, non-fully contained inner', function () {
var innerRange = {
start: 1,
end: 4
}
var outerRange = {
start: 3,
end: 6
}
var sequenceLength = 10
var flippedInnerRange = flipContainedRange(innerRange, outerRange, sequenceLength)
flippedInnerRange.should.deep.equal({
start: 5,
end: 8
})
});
it('non-origin spanning outer, non-origin spanning, non-fully contained inner', function () {
var innerRange = {
start: 4,
end: 2
}
var outerRange = {
start: 2,
end: 5
}
var sequenceLength = 10
var flippedInnerRange = flipContainedRange(innerRange, outerRange, sequenceLength)
flippedInnerRange.should.deep.equal({
start: 5,
end: 3
})
});
it('inner fully spans outer, does not wrap origin', function () {
var innerRange = {
start: 1,
end: 7
}
var outerRange = {
start: 2,
end: 5
}
var sequenceLength = 10
var flippedInnerRange = flipContainedRange(innerRange, outerRange, sequenceLength)
flippedInnerRange.should.deep.equal({
start: 0,
end: 6
})
});
it('inner fully spans outer, does wrap origin', function () {
var innerRange = {
start: 4,
end: 2
}
var outerRange = {
start: 5,
end: 2
}
var sequenceLength = 10
var flippedInnerRange = flipContainedRange(innerRange, outerRange, sequenceLength)
flippedInnerRange.should.deep.equal({
start: 5,
end: 3
})
});
});
|
bab4c11738f5d965fc23d1c4a60d3ba593e34cc8 | TypeScript | Dorkt/Teste | /Downloads/ead-back-master/ead-back-master/src/models/schemas/forum.model.ts | 2.71875 | 3 | import Mongoose, { Document } from 'mongoose'
/**
* Modelo de Fórum:
* O fórum será onde o tutores ou alunos poderão abrir uma
* conversa para um contato dentro do sistema.
**/
interface IMessage extends Document {
userId: string,
text: string,
date: Date
}
export interface IForum extends Document {
title: string
subtitle: string
message: IMessage[]
userId: string
}
const ForumSchema = new Mongoose.Schema({
title: { type: String, unique: true },
subtitle: { type: String },
message: { type: Array },
userId: { type: String },
subjectId: { type: String }
}, {
timestamps: { createdAt: 'created_at', updatedAt: false },
toJSON: {
transform: (doc, ret) => {
ret.id = ret._id
delete ret._id
delete ret.__v
return ret
}
}
})
const ForumModel = Mongoose.model<IForum>('Forum', ForumSchema)
export default ForumModel
|
85eb1bf3c5a96fa0b136d6a6dc3f7767e7c8f29d | TypeScript | nagasu/jest-sample | /src/array.test.ts | 2.53125 | 3 | test('array indexOf test', () => {
const values = ['banana', 'apple', 'orange', 'apple'];
expect(values.indexOf('apple')).toBe(1);
expect(values.lastIndexOf('apple')).toBe(3);
});
|
7c703b6388af6c6b6062673a0f18f5c5de0375aa | TypeScript | crazytoucan/math2d | /src/vecFunctions/vecTransformBy.ts | 3.453125 | 3 | import { Mat2d, Vec } from "../types";
import { vecAlloc } from "./vecAlloc";
import { vecReset } from "./vecReset";
/**
* Multiplies the vector by an affine matrix.
*
* This computes a left multiplication of the vector by a matrix, i.e. _M_ × _v_.
*
* Per usual linear algebra rules, multiplying the vector `(x, y)` according to an affine matrix
* `[a b c d e f]` is defined by:
*
* ```
* ⎡a c tx⎤ ⎛x⎞ ⎛ax + cy + tx⎞
* ⎢b d ty⎥ ⎜y⎟ = ⎜bx + dy + ty⎟
* ⎣0 0 1⎦ ⎝1⎠ ⎝ 1 ⎠
* ```
*
* @param v the vector to transform
* @param mat the matrix to multiply this vector by
* @param out
*/
export function vecTransformBy(v: Vec, mat: Mat2d, out = vecAlloc()) {
return vecReset(mat.a * v.x + mat.c * v.y + mat.tx, mat.b * v.x + mat.d * v.y + mat.ty, out);
}
|
56413110baf6369e8c851d705c1d32dd8571b56c | TypeScript | warrenhodg/lib-mealie-crypt | /ts/users.ts | 3.09375 | 3 | import * as keys from './keys';
export interface IUsers {
[name: string]: User;
}
export class Users {
public static fromO(o: any): IUsers {
let result: IUsers = {};
for (let name in o) {
result[name] = new User(o[name]);
}
return result;
}
public static toO(value: IUsers): any {
let result: any = {};
for (let name in value) {
result[name] = value[name].toO();
}
return result;
}
}
export class User {
public Key: keys.Key;
constructor(o: any) {
if (o instanceof keys.Key) {
this.Key = o;
} else {
this.Key = new keys.Key(o.key);
}
}
public toO(): any {
return {
key: this.Key.toO()
};
}
}
|
bed1db9a0ee1d0b1b3152c09eeb56a13c27eb3d8 | TypeScript | jappe999/terrain-generator | /src/entity/Tile.ts | 2.546875 | 3 | import { container } from "../app";
import { Sprite, Texture } from "pixi.js";
import World from "../world/World";
export default class Tile extends Sprite {
constructor(public id: number) {
super(Texture.WHITE);
this.x =
World.tileSize * Math.floor(id % World.width) +
container.clientWidth / 2 -
World.width * (World.tileSize / 2);
this.y =
World.tileSize * Math.floor(id / World.width) +
container.clientHeight / 2 -
World.height * (World.tileSize / 2);
this.height = this.width = World.tileSize;
}
}
|
9e721012409aed4f1ba031b54e29fa1d7d1d1e4b | TypeScript | Stilgar84/MyScreepsAI | /src/components/creeps/roles/claim_room2.ts | 2.75 | 3 |
import * as move2room2 from'../actions/move2room2'
export function run(creep: Creep): void {
if(move2room2.move(creep)) {
let targets = creep.room.find<Structure>(FIND_STRUCTURES, {
filter: (s: Structure)=>s.structureType==STRUCTURE_CONTROLLER
})
if(targets.length>0) {
const target = targets[0]
const err = creep.claimController(target as Controller)
if(err == ERR_NOT_IN_RANGE) {
creep.moveTo(target)
}
}
}
}
|
3e476b7cb05464b90a0fe8d060c688aaa4f5f7f9 | TypeScript | NG-ZORRO/schematics | /scrtips/copy-resources.ts | 2.5625 | 3 | import * as fs from 'fs-extra';
import * as path from 'path';
const srcPath = path.join(process.cwd(), 'src');
const targetPath = path.join(process.cwd(), 'dist/schematics');
const copyFilter = (p: string) => !p.endsWith('.ts');
export function copyResources(): void {
fs.copySync(srcPath, targetPath, { filter: copyFilter });
fs.copyFile(path.join(process.cwd(), 'README.md'), path.join(targetPath, 'README.md'));
fs.copyFile(path.join(process.cwd(), 'LICENSE'), path.join(targetPath, 'LICENSE'));
}
copyResources();
|
85d0dd7c20ddb0ed56930f87dbc85f171cf0882f | TypeScript | artsy/eigen | /src/app/Components/ArtworkGrids/utils/sections.ts | 3.21875 | 3 | export function getSectionedItems<T extends { image: { aspectRatio: number } | null }>(
items: T[],
columnCount: number
) {
const sectionRatioSums: number[] = []
const sectionedArtworksArray: T[][] = []
for (let i = 0; i < columnCount; i++) {
sectionedArtworksArray.push([])
sectionRatioSums.push(0)
}
const itemsClone = [...items]
itemsClone.forEach((item) => {
let lowestRatioSum = Number.MAX_VALUE // Start higher, so we always find a
let sectionIndex: number | null = null
for (let j = 0; j < sectionRatioSums.length; j++) {
const ratioSum = sectionRatioSums[j]
if (ratioSum < lowestRatioSum) {
sectionIndex = j
lowestRatioSum = ratioSum
}
}
if (sectionIndex != null) {
const section = sectionedArtworksArray[sectionIndex]
section.push(item)
// Keep track of total section aspect ratio
const aspectRatio = item.image?.aspectRatio || 1 // Ensure we never divide by null/0
// Invert the aspect ratio so that a lower value means a shorter section.
sectionRatioSums[sectionIndex] += 1 / aspectRatio
}
})
return sectionedArtworksArray
}
|
63416e7d18f50606e42d9186ebabc94c7a7a85fe | TypeScript | Mennu-zz/rubix_be | /src/db/models/productType.ts | 2.546875 | 3 | import { Table, Column, Model, AutoIncrement, PrimaryKey, ForeignKey, AllowNull, Default } from 'sequelize-typescript';
import { Product } from "./product";
import { v4 as uuidv4 } from 'uuid';
@Table
export class ProductType extends Model<Partial<ProductType>> {
@Default(uuidv4)
@PrimaryKey
@Column
id?: string;
@AllowNull(false)
@ForeignKey(() => Product)
@Column
productId!: string;
@AllowNull(false)
@Column
type!: string;
@AllowNull(false)
@Column
quantity!: number;
} |
3236d4fbc49b2c30c14a8c1b109c4926b300089c | TypeScript | areangonzalez/frontend-rnnutre | /src/app/core/services/authentication.service.ts | 2.625 | 3 | import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { map } from 'rxjs/operators';
import { JwtService } from './jwt.service';
@Injectable()
export class AuthenticationService {
constructor(private _apiService: ApiService, private _jwtService: JwtService) { }
/**
* Logueo de un usuario en el sistema
* @param username nombre de usuario
* @param password contraseña del usuario
*/
logueo(username: string, password: string) {
return this._apiService.post('/usuarios/login', { username, password })
.pipe(map((user: any) => {
if (user && user.access_token) {
let data = { username: '', token: ''};
// completo los datos en el objeto
data.username = user.username;
data.token = user.access_token;
// guardo los datos de logueo
this._jwtService.saveToken(data);
return user;
}
}));
}
logout() {
// remove user from local storage to log user out
this._jwtService.destroyToken();
}
loggedIn() {
let userLogin = this._jwtService.getToken();
if(userLogin && userLogin.datosToken) {
return true;
}else{
return false;
}
}
getUser() {
let user = this._jwtService.getToken();
return user.datosToken;
}
getUserName() {
let userLogin = this._jwtService.getToken();
return userLogin.datosToken.username;
}
}
|
a37ee6829419a948cfa15f128d16c810d8c3a8af | TypeScript | moreati/wallet-site | /src/explorer_api.ts | 2.53125 | 3 | import axios, { AxiosInstance } from 'axios'
import { ITransactionData } from './store/modules/history/types'
// Doesn't really matter what we set, it will change
const api_url: string = 'localhost'
const explorer_api: AxiosInstance = axios.create({
baseURL: api_url,
withCredentials: false,
headers: {
'Content-Type': 'application/json',
},
})
async function getAddressHistory(
addrs: string[],
limit = 20,
chainID: string,
endTime?: string
): Promise<ITransactionData[]> {
const ADDR_SIZE = 1024
let selection = addrs.slice(0, ADDR_SIZE)
let remaining = addrs.slice(ADDR_SIZE)
let addrsRaw = selection.map((addr) => {
return addr.split('-')[1]
})
let rootUrl = 'v2/transactions'
let req = {
address: addrsRaw,
sort: ['timestamp-desc'],
disableCount: ['1'],
chainID: [chainID],
disableGenesis: ['false'],
}
if (limit > 0) {
//@ts-ignore
req.limit = [limit.toString()]
}
if (endTime) {
console.log('Setting endtime')
//@ts-ignore
req.endTime = [endTime]
}
let res = await explorer_api.post(rootUrl, req)
let txs = res.data.transactions
let next: string | undefined = res.data.next
if (txs === null) txs = []
// If we need to fetch more for this address
if (next && !limit) {
let endTime = next.split('&')[0].split('=')[1]
let nextRes = await getAddressHistory(selection, limit, chainID, endTime)
txs.push(...nextRes)
}
// If there are addresses left, fetch them too
if (remaining.length > 0) {
let nextRes = await getAddressHistory(remaining, limit, chainID)
txs.push(...nextRes)
}
return txs
}
async function isAddressUsedX(addr: string) {
let addrRaw = addr.split('-')[1]
let url = `/x/transactions?address=${addrRaw}&limit=1&disableCount=1`
try {
let res = await explorer_api.get(url)
// console.log(res);
if (res.data.transactions.length > 0) return true
else return false
} catch (e) {
throw e
}
}
async function getAddressDetailX(addr: string) {
let addrRaw = addr.split('-')[1]
let url = `/x/addresses/${addrRaw}`
try {
let res = await explorer_api.get(url)
return res.data
} catch (e) {
throw e
}
}
async function getAddressChains(addrs: string[]) {
// Strip the prefix
let rawAddrs = addrs.map((addr) => {
return addr.split('-')[1]
})
let urlRoot = `/v2/addressChains`
let res = await explorer_api.post(urlRoot, {
address: rawAddrs,
disableCount: ['1'],
})
return res.data.addressChains
}
export { explorer_api, getAddressHistory, getAddressDetailX, isAddressUsedX, getAddressChains }
|
4c344e3563595f2ce00677cd0c0cd8cfeeeb0fae | TypeScript | ChenxuJWang/notion-avatar | /src/types.ts | 2.671875 | 3 | // export enum AvatarStyle {
// Accessories,
// Beard,
// Details,
// Eyebrows,
// Eyes,
// Face,
// Glasses,
// Hairstyle,
// Mouth,
// Nose
// }
export type AvatarConfig = {
accessories: number;
beard: number;
details: number;
eyebrows: number;
eyes: number;
face: number;
glasses: number;
hair: number;
mouth: number;
nose: number;
};
export type AvatarPart = keyof AvatarConfig;
export type ImageType = 'png' | 'svg';
export type ImageApiType = {
[key in ImageType]: string;
};
|
0977ab985ba8eb6e168b9005ae8e58970091f88e | TypeScript | PhaserEditor2D/PhaserEditor2D-v3 | /source/editor/plugins/phasereditor2d.scene/src/ui/sceneobjects/nineslice/NineSliceExtension.ts | 2.671875 | 3 | namespace phasereditor2d.scene.ui.sceneobjects {
export class NineSliceExtension extends BaseImageExtension {
private static _instance = new NineSliceExtension();
static getInstance() {
return this._instance;
}
constructor() {
super({
phaserTypeName: "Phaser.GameObjects.NineSlice",
typeName: "NineSlice",
category: SCENE_OBJECT_IMAGE_CATEGORY,
icon: ScenePlugin.getInstance().getIconDescriptor(ICON_9_SLICE)
});
}
adaptDataAfterTypeConversion(serializer: core.json.Serializer, originalObject: ISceneGameObject, extraData: any) {
super.adaptDataAfterTypeConversion(serializer, originalObject, extraData);
const obj = originalObject as unknown as Phaser.GameObjects.Components.ComputedSize;
const width = obj.width === undefined ? 20 : obj.width;
const height = obj.height === undefined ? 20 : obj.height;
serializer.getData()[SizeComponent.width.name] = width;
serializer.getData()[SizeComponent.height.name] = height;
}
getCodeDOMBuilder(): GameObjectCodeDOMBuilder {
return new NineSliceCodeDOMBuilder();
}
protected newObject(scene: Scene, x: number, y: number, key?: string, frame?: string | number): ISceneGameObject {
if (key) {
return new NineSlice(scene, x, y, key, frame, 256, 256, 10, 10, 10, 10);
}
return new NineSlice(scene, x, y, undefined, undefined, 256, 256, 10, 10, 10, 10);
}
}
} |
74063993dc88a47fad532d1e8491f69d15573c61 | TypeScript | ahyaemon/musikui | /src/domain/Contest.ts | 2.90625 | 3 | import Musikui from "./Musikui"
import MusikuiDate from "../value_object/MusikuiDate"
import Respondent from "@/domain/Respondent"
export default class Contest {
public static default() {
return new Contest(
0,
MusikuiDate.from_string("2000/01/01"),
"default contest comment",
[Musikui.default()],
)
}
/**
* 特定の虫食い算に対する回答者を更新し、新しいコンテストとして返す
*
* @param old
* @param musikui_id
* @param respondents
*/
public static clone_with_new_respondents(old: Contest, musikui_id: number, respondents: Respondent[]): Contest {
const new_musikuis = old.musikuis.map((musikui) => {
if (musikui.id === musikui_id) {
return Musikui.clone_with_new_respondents(musikui, respondents)
} else {
return musikui
}
})
return new Contest(
old.id,
old.date,
old.comment,
new_musikuis,
)
}
constructor(
readonly id: number,
readonly date: MusikuiDate,
readonly comment: string,
readonly musikuis: Musikui[],
) {}
public has_musikuis(): boolean {
return this.musikuis.length > 0
}
}
|
12c31d2e199cbec737894a8a765b6e7634339f74 | TypeScript | angular/angular | /packages/core/src/util/closure.ts | 2.890625 | 3 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Convince closure compiler that the wrapped function has no side-effects.
*
* Closure compiler always assumes that `toString` has no side-effects. We use this quirk to
* allow us to execute a function but have closure compiler mark the call as no-side-effects.
* It is important that the return value for the `noSideEffects` function be assigned
* to something which is retained otherwise the call to `noSideEffects` will be removed by closure
* compiler.
*/
export function noSideEffects<T>(fn: () => T): T {
return {toString: fn}.toString() as unknown as T;
}
|
1118f6107fc47f935c711c3bc99305100b65076e | TypeScript | sebreceveur/DrinkVendingMachine | /ClientApp/app/components/coinstore/coinstore.component.ts | 2.8125 | 3 | import { Component, Input, OnChanges, OnInit, SimpleChange } from '@angular/core';
import { CoinService } from '../../service/coin.service';
import { Coin } from '../../model/coin';
@Component({
selector: 'app-coinstore',
templateUrl: './coinstore.component.html',
styleUrls: ['./coinstore.component.css']
})
/**
* Handle the graphical representation of
* the vending machine storage of the coins
*/
export class CoinStoreComponent {
@Input() refresh: boolean;
fiveCoin: Coin;
twoCoin: Coin;
oneCoin: Coin;
fiftyCCoin: Coin;
twentyCCoin: Coin;
tenCCoin: Coin;
fiveCCoin: Coin;
/**
* Used for convience: *ngFor only takes collection and not numbers
*/
fiveCoins: Coin[];
twoCoins: Coin[];
oneCoins: Coin[];
fiftyCCoins: Coin[];
twentyCCoins: Coin[];
tenCCoins: Coin[];
fiveCCoins: Coin[];
coins: Coin[];
constructor(private coinService: CoinService) {
}
/**
* Refresh the view when triggered by the dispenser
*/
ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
for (let propName in changes) {
let changedProp = changes[propName];
let to = JSON.stringify(changedProp.currentValue);
if (!changedProp.isFirstChange()) {
this.getStorage();
}
}
}
ngOnInit() {
this.getStorage();
}
/**
* Fills the array that the template displays
*/
getStorage(): void{
this.coinService.currentStorage()
.subscribe((coins: Coin[]) => {
coins.forEach( function(this: any, element){
switch(element.value){
case 5.0 :
this.fiveCoin = element;
this.fiveCoins = new Array<number>(element.quantity);
break;
case 2.0 :
this.twoCoin = element;
this.twoCoins = new Array<number>(element.quantity);
break;
case 1.0 :
this.oneCoin = element;
this.oneCoins = new Array<number>(element.quantity);
break;
case 0.50 :
this.fiftyCCoin = element;
this.fiftyCCoins = new Array<number>(element.quantity);
break;
case 0.20 :
this.twentyCCoin = element;
this.twentyCCoins = new Array<number>(element.quantity);
break;
case 0.10 :
this.tenCCoin = element;
this.tenCCoins = new Array<number>(element.quantity);
break;
case 0.05 :
this.fiveCCoin = element;
this.fiveCCoins = new Array<number>(element.quantity);
break;
}
}, this);
this.coins = coins;
})
}
}
|
3ca86b473a8278532873804ae7983d2ae0002024 | TypeScript | doniseferi/salahtimes | /src/salah/__tests__/dhuhr.test.ts | 2.703125 | 3 | import { iterativeTest, generateRandomDate, randomLongitude } from '../../testUtils'
import { Longitude } from '../../geoCoordinates'
import { dhuhr } from '..'
import { success } from '../../either'
import { getNoonDateTimeUtc } from 'suntimes'
describe('Dhuhr', () => {
test('returns the midday date time value', () => {
iterativeTest<{
date: Date
longitude: Readonly<Longitude>
middayDateTimeUtc: string
}, void>({
numberOfExecutions: 500,
generateInput: () => {
const { randomDate, midddayDateTimeUtc: middayDateTimeUtc, longitude: geoCoordinates } = getExpectedDateTIme()
return {
date: new Date(randomDate.getTime()),
middayDateTimeUtc,
longitude: geoCoordinates
}
},
assert: ({ date, longitude, middayDateTimeUtc }) => {
const getDhuhrDateTimeUtc = dhuhr(date, longitude)
expect(getDhuhrDateTimeUtc).toEqual(success(middayDateTimeUtc))
}
})
})
})
const getExpectedDateTIme = (): {
randomDate: Readonly<Date>
longitude: Readonly<Longitude>
midddayDateTimeUtc: string
} => {
let middayDateTimeUtc: string
let longitude: Longitude
let randomDate: Readonly<Date>
do {
longitude = randomLongitude()
randomDate = generateRandomDate(2000, 2050)
middayDateTimeUtc = getNoonDateTimeUtc(randomDate as Date, longitude.value)
}
while (isNaN(Date.parse(middayDateTimeUtc)))
return { randomDate, midddayDateTimeUtc: middayDateTimeUtc, longitude }
}
|
f86515ab9720b5646cccc0bf066678bc8d709641 | TypeScript | alucardstrikes/cuke-protractor | /features/step_definitions/search_steps.ts | 2.640625 | 3 | import { Given, When, Then } from "cucumber";
import { expect } from "chai";
Given('I Log into google', { timeout: 100 * 1000 }, async function () {
await this.google_search.waitForPageUrlToLoad();
});
When('I search for {string}', { timeout: 100 * 1000 }, async function (searchString) {
await this.google_search.searchGoogle(searchString);
});
Then('the search should give me more than {int} result', { timeout: 100 * 1000 }, async function (noOfResults) {
let noOfResultsFound = await this.google_search.getNoResults();
expect(noOfResultsFound).to.be.greaterThan(noOfResults, `Search returned only one or no results`);
});
|
73453e6ccd2f0e25de7af52115019e0028a19725 | TypeScript | hongji85/TPPChatBot | /angular-src/src/app/Services/socket.service.ts | 2.515625 | 3 | import { Injectable } from '@angular/core';
import { Observable, Observer, BehaviorSubject, Operator } from 'rxjs';
import * as socketIo from 'socket.io-client';
export class Message {
constructor(public content: string, public sentBy: string) {}
}
export class MessageObject {
constructor(public customerObject: CustomerObject, public utterance: string) {}
}
export class OperatorMessage {
constructor(public customerId: string, public utterance: string, public isAgentResponse: boolean, public sentBy: string) {}
}
export class CustomerObject {
constructor(public customerId: string, public customerName: string) {}
}
@Injectable({
providedIn: 'root'
})
export class SocketService {
private customer_socket;
private operator_socket;
customer_conversation = new BehaviorSubject<Message[]>([]);
operator_conversation = new BehaviorSubject<OperatorMessage[]>([]);
customer_list = new BehaviorSubject<CustomerObject[]>([]);
info_message = new BehaviorSubject<string>("");
constructor() { }
public initSocket(): void {
this.customer_socket = socketIo('http://localhost:3000/customer');
this.operator_socket = socketIo('http://localhost:3000/operator');
this.customer_socket.on('customer message', (data: string) => {
this.update_customer(new Message(data, 'agent'));
});
this.operator_socket.on('operator message', (data: OperatorMessage) => {
this.update_operator(data.customerId, data.utterance, data.isAgentResponse, 'user');
});
this.operator_socket.on('customer message', (data: OperatorMessage) => {
this.update_operator(data.customerId, data.utterance, data.isAgentResponse, data.isAgentResponse ? 'user' : 'agent');
});
this.operator_socket.on('customer connected', (data: any) => {
this.update_operator_customerlist(data.customerId, data.customerName);
});
this.operator_socket.on('operator requested', (data: string) => {
this.info_message.next("Operator requested!");
});
this.operator_socket.on('customer disconnected', (data: OperatorMessage) => {
});
this.operator_socket.on('system error', (data: OperatorMessage) => {
});
}
public sendCustomerMessage(msg: string): void {
const message = new Message(msg, 'user');
this.customer_socket.emit('customer message', message.content);
this.update_customer(message);
}
public sendOperatorMessage(customerObject: CustomerObject, msg: string): void {
this.operator_socket.emit('operator message', new MessageObject(customerObject, msg));
}
// Adds message to source
private update_customer(msg: Message): void {
this.customer_conversation.next([msg]);
}
private update_operator(Id: string, utterance: string, isAgentResponse: boolean, sentBy: string): void {
this.operator_conversation.next([new OperatorMessage(Id, utterance, isAgentResponse, sentBy)]);
}
private update_operator_customerlist(Id: string, Name: string): void {
this.customer_list.next([new CustomerObject(Id, Name)]);
}
} |
a5c80b605a32daecdbc082b664bda390dbff114d | TypeScript | john-sonz/warships | /src/ts/Board.ts | 3.0625 | 3 | import ShipSetter from './ShipSetter';
import { comment } from './decorators';
interface shipSetting {
x: number;
y: number;
direction: boolean;
size: number;
}
enum State {
Empty,
Taken,
Hit,
Miss
};
export enum Win {
Player,
Machine
}
export enum PlayerMoves {
AlreadyShot,
CantShoot,
Hit,
Miss,
}
export default class Board {
board: number[][] = [];
shots: number[][] = []
width: number;
height: number;
htmlBoard: HTMLElement[][] = [];
boardContainer: HTMLElement;
lastProposed: shipSetting = null;
allowShoot: boolean = false;
toHit: number;
hits: number = 0;
endGame: Function;
gameFinished: boolean = false;
constructor(width: number, height: number, endGame: Function = null) {
this.endGame = endGame;
[this.width, this.height] = [width, height];
for (let i = 0; i < height; i++) {
const row: number[] = [];
for (let j = 0; j < width; j++) {
row.push(State.Empty);
this.shots.push([i, j]);
}
this.board.push(row)
}
}
createHTMLBoard(shipSetter: ShipSetter = null, board2: Board = null) {
this.boardContainer = document.createElement("div")
this.boardContainer.className = "board";
for (let i = 0; i < this.height; i++) {
const row: HTMLElement[] = [];
const rowDiv = document.createElement('div');
rowDiv.className = "row";
for (let j = 0; j < this.width; j++) {
const cell = document.createElement("div");
if (shipSetter) {
this.toHit = shipSetter.ships.reduce((a, b) => a + b);
cell.addEventListener('mouseover', (e) => this.checkShip(e, shipSetter, true));
cell.addEventListener('click', (e) => this.checkAndAddShip(e, shipSetter));
}
else {
cell.addEventListener('click', (e) => this.shoot(i, j, board2))
}
cell.className = "cell";
cell.id = `${j}-${i}`;
row.push(cell);
rowDiv.appendChild(cell);
}
this.htmlBoard.push(row)
this.boardContainer.appendChild(rowDiv);
}
}
getHMTLBoard() { return this.boardContainer }
addShip(x: number, y: number, length: number, direction: boolean, show: boolean = false) {
for (let i = 0; i < length; i++) {
let [X, Y] = [x, y];
if (direction) Y = y + i;
else X = x + i;
this.board[Y][X] = State.Taken;
if (show) {
this.htmlBoard[Y][X].classList.add('blue');
}
}
}
drawShips(shipSizes: number[]) {
this.toHit = shipSizes.reduce((a, b) => a + b);
while (shipSizes.length > 0) {
const size = shipSizes.pop();
let found = false;
while (!found) {
let [x, y, direction] = [Math.floor(Math.random() * this.width), Math.floor(Math.random() * this.height), Math.random() < 0.5];
if (x > this.width - size && !direction) {
continue;
}
if (y > this.height - size && direction) {
continue;
}
if (size === 4) {
this.addShip(x, y, size, direction)
break;
}
const s: shipSetting = {
x,
y,
direction,
size
}
const [shipsPos, surroundings] = generateCheckPositions(s, this.width, this.height);
found = this.checkPositions(shipsPos, surroundings)
if (found) this.addShip(x, y, size, direction);
}
}
}
checkPositions(ships: number[][], surroundings: number[][]): boolean {
const s = ships.filter(pos => {
return this.board[pos[1]][pos[0]] === State.Empty
})
const sur = surroundings.filter(pos => {
return this.board[pos[1]][pos[0]] === State.Empty
})
return (ships.length === s.length && surroundings.length === sur.length)
}
viewShip(color: string, s: shipSetting) {
const { x, y, direction, size } = s;
for (let i = 0; i < size; i++) {
let [X, Y] = [x, y];
if (direction) Y = y + i;
else X = x + i;
if (X >= 0 && X < this.width && Y >= 0 && Y < this.height) {
this.htmlBoard[Y][X].style.backgroundColor = color;
}
}
this.lastProposed = s;
}
checkShip(e: Event, shipSetter: ShipSetter, view: boolean) {
if (!shipSetter.selected) return false;
const el = e.target as HTMLElement;
const pos = el.id.split("-").map(a => parseInt(a));
const ship: shipSetting = {
x: pos[0],
y: pos[1],
direction: shipSetter.direction,
size: shipSetter.selected
}
if (ship.x + ship.size > this.width && !ship.direction) {
ship.x = this.width - ship.size;
}
if (ship.y + ship.size > this.height && ship.direction) {
ship.y = this.width - ship.size;
}
const [shipsPos, surroundings] = generateCheckPositions(ship, this.width, this.height);
const shipValid = this.checkPositions(shipsPos, surroundings);
if (view) {
if (this.lastProposed) {
this.viewShip("", this.lastProposed);
}
this.viewShip(shipValid ? "green" : "red", ship);
}
return shipValid;
}
updateLastShip(dir: boolean) {
if (!this.lastProposed) return;
const s = { ...this.lastProposed };
s.direction = dir;
if (s.x + s.size > this.width && !s.direction) {
s.x = this.width - s.size;
}
if (s.y + s.size > this.height && s.direction) {
s.y = this.width - s.size;
}
const [shipsPos, surroundings] = generateCheckPositions(s, this.width, this.height);
const shipValid = this.checkPositions(shipsPos, surroundings);
this.viewShip("", this.lastProposed);
this.viewShip(shipValid ? "green" : "red", s);
}
checkAndAddShip(e: Event, shipS: ShipSetter) {
if (this.checkShip(e, shipS, false)) {
this.viewShip("", this.lastProposed);
const { x, y, direction, size } = this.lastProposed;
this.addShip(x, y, size, direction, true);
shipS.shipPlaced();
}
}
@comment
shoot(y: number, x: number, board2: Board) {
if (this.gameFinished) return;
if (!this.allowShoot) {
document.getElementById('sexi-text').innerHTML = "Nie możesz teraz strzelać";
return PlayerMoves.CantShoot;
}
if (this.board[y][x] === State.Miss || this.board[y][x] === State.Hit) {
document.getElementById('sexi-text').innerHTML = "Już tam strzeliłeś";
return PlayerMoves.AlreadyShot;
}
const hit = this.board[y][x] === State.Taken;
this.board[y][x] = hit ? State.Hit : State.Miss;
this.htmlBoard[y][x].classList.add(hit ? 'hit' : 'miss');
document.getElementById('sexi-text').innerHTML = hit ? "Trafiony!<br>Ruch komputera" : "Pudło<br>Ruch komputera";
this.allowShoot = false;
if (hit) this.hits++;
if (this.hits === this.toHit) {
this.endGame(Win.Player);
this.gameFinished = true;
return;
}
board2.randomShoot().then(([y, x, hit]) => {
board2.htmlBoard[y][x].classList.add(hit ? 'hit' : 'miss');
this.allowShoot = true;
document.getElementById('sexi-text').innerHTML = "Twój ruch";
if (board2.hits === board2.toHit) {
this.endGame(Win.Machine);
this.gameFinished = true;
}
});
return hit ? PlayerMoves.Hit : PlayerMoves.Miss;
}
randomShoot() {
return new Promise((resolve, reject) => {
const r = Math.floor(Math.random() * this.shots.length);
const [y, x] = this.shots[r];
const hit = this.board[y][x] === State.Taken;
this.shots.splice(r, 1);
if (hit) this.hits++;
setTimeout(() => { resolve([y, x, hit]) }, 1000);
});
}
}
function generateCheckPositions(ship: shipSetting, width: number, height: number): number[][][] {
const { x, y, size, direction } = ship;
const positions: number[][] = []
for (let i = -1; i < 2; i++) {
if (!direction) {
for (let j = -1; j < size + 1; j++) {
positions.push([x + j, y + i]);
}
} else {
for (let j = -1; j < size + 1; j++) {
positions.push([x + i, y + j]);
}
}
}
const shipPos = positions.splice(size + 3, size);
return [shipPos, positions.filter(pos => {
return (pos[0] >= 0 && pos[0] < width) && (pos[1] >= 0 && pos[1] < height)
})];
}
|