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
|
|---|---|---|---|---|---|---|
abb2f75b862ccbe560e89aa5b6c928148774d75c
|
TypeScript
|
nabil-bourziz/ng-ib-2020
|
/demonstration/src/app/todo/todo-form-reactive/todo-form-reactive.component.ts
| 2.625
| 3
|
import { Component, EventEmitter, Output } from '@angular/core';
import { AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Todo } from '../models';
@Component({
selector: 'app-todo-form-reactive',
templateUrl: './todo-form-reactive.component.html',
styleUrls: ['./todo-form-reactive.component.scss']
})
export class TodoFormReactiveComponent {
@Output()
create = new EventEmitter<Todo>();
// Creation manuelle du formulaire (il vaut mieux utiliser le form-builder).
// FormGroup (objet), FormArray (tableau), FormControl (valeur atomique) <|-- AbstractControl.
// form = new FormGroup({
// name: new FormControl(null, [Validators.required, Validators.minLength(3)]),
// finished: new FormControl(false),
// endedAt: new FormControl()
// });
form = this.fb.group({
// name: this.fb.control(null, [Validators.required, Validators.minLength(3)]),
name: [null, [Validators.required, Validators.minLength(3)]],
finished: false,
endedAt: null
});
constructor(private readonly fb: FormBuilder) { }
get name(): AbstractControl {
return this.form.controls.name;
}
onSubmit(event: Event): void {
event.preventDefault();
this.create.emit(this.form.value);
this.form.reset({ name: null, finished: false, endedAt: null });
}
}
|
c1c015a501984f941310502d136e9fa8e0a4efe3
|
TypeScript
|
feirm/app
|
/src/class/account.ts
| 2.6875
| 3
|
import { DB } from "./db";
import { EncryptedAccount, SignedAuthenticationToken, AuthenticationToken, EncryptedKey, EncryptedAccountV2 } from "@/models/account";
import { ArgonType, hash } from "argon2-browser";
import { ModeOfOperation, utils } from "aes-js";
import { SignKeyPair, sign } from "tweetnacl";
import bufferToHex from "@/lib/bufferToHex";
import hexStringToBytes from "@/lib/hexStringToBytes";
// Different account key types
enum Keys {
Identity = "identity",
Encryption = "enc",
}
class Account extends DB {
// Properties (these are to be used for in-memory)
public username: string;
public rootKey: Uint8Array;
// Set the account root key
setRootKey(rootKey: Uint8Array) {
this.rootKey = rootKey;
}
// Get the account root key
getRootKey(): Uint8Array {
return this.rootKey;
}
// Generate an encrypted account
async generateAccount(
username: string,
password: string,
pin: string
): Promise<EncryptedAccount> {
// Generate 16 random bytes of salt.
// This is to be used when stretching the password.
const salt = window.crypto.getRandomValues(new Uint8Array(16));
// Derive the stretched key from the password to be used for encryption
const secretKey = await hash({
pass: password,
salt: salt,
type: ArgonType.Argon2id,
hashLen: 32,
});
// The account root key, as the name implies, is the root of the account.
// It is important that this key never leaves the device.
// If a key is compromised, the user account can never be secure.
const rootKey = window.crypto.getRandomValues(new Uint8Array(32));
// Using the root key, every account has an identity (signing) keypair produced from it.
// This keypair is used for authentication such as signing tokens in order to grant
// authorized access to resources/services provided by Feirm.
const identityKeypair = await this.deriveIdentityKeypair(rootKey);
// We need the public key of this keypair to verify signatures
const identityPublicKey = bufferToHex(identityKeypair.publicKey);
// Generate 16 bytes of salt to be used for account root key encryption.
const rootKeySalt = window.crypto.getRandomValues(new Uint8Array(16));
// The current implementation relies on cryptography methods provided by the aes-js module.
// To reduce the dependency on third-party libraries, this should eventually be replaced to use
// the Web Crypto API.
// This web application currently uses AES256-CBC.
// Create a new cipher and encrypt the rootkey
const aesCbc = new ModeOfOperation.cbc(secretKey.hash, rootKeySalt);
const rootKeyCiphertext = aesCbc.encrypt(rootKey);
// Construct the encrypted account object to be returned.
const account: EncryptedAccount = {
username: username,
pin: pin,
rootPasswordSalt: bufferToHex(salt),
rootPublicKey: identityPublicKey,
encryptedRootKey: {
cipherText: bufferToHex(rootKeyCiphertext),
iv: bufferToHex(rootKeySalt),
},
token: {
id: "",
signature: ""
}
};
return account;
}
// Derive stretched password from existing values (plaintext password and salt)
// The password is returned as Uint8Array
async derivePassword(password: string, salt: string): Promise<Uint8Array> {
// Reconstruct the stretched key from parameter values
const secretKey = await hash({
pass: password,
salt: hexStringToBytes(salt),
type: ArgonType.Argon2id,
hashLen: 32
});
return secretKey.hash;
}
// Decrypt an account to return the root key
async decryptAccount(secretKey: Uint8Array, account: EncryptedAccount): Promise<Uint8Array> {
// Attempt to decrypt the account root key
// Convert the salt to a format that is AES cipher friendly
const salt = utils.hex.toBytes(account.encryptedRootKey.iv).slice(0, 16);
// Create the AES256-CBC decipher and decrypt the root key
const aesCbc = new ModeOfOperation.cbc(secretKey, salt);
try {
const rootKey = aesCbc.decrypt(utils.hex.toBytes(account.encryptedRootKey.cipherText));
return rootKey;
} catch (e) {
throw new Error(e);
}
}
// Derive an identity (signing) keypair from account root
async deriveIdentityKeypair(
accountRootKey: Uint8Array
): Promise<SignKeyPair> {
// It isn't sensible to use the same key for multiple use cases, so we
// should derive a signing "key" which is used as the seed to produce
// a full ed25519 signing keypair.
const identityKeyString = bufferToHex(accountRootKey) + Keys.Identity;
const identityKey = await window.crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(identityKeyString)
);
// Derive signing keypair from seed
const identityKeypair = sign.keyPair.fromSeed(new Uint8Array(identityKey));
return identityKeypair;
}
// Sign an authentication token using identity keypair
async signAuthenticationToken(keypair: SignKeyPair, token: AuthenticationToken): Promise<SignedAuthenticationToken> {
// Construct a new signed authentication token from the token passed as a parameter
const signedToken = {
id: token.id
} as SignedAuthenticationToken;
// Sign the nonce in the token provided as parameter
const nonce = new TextEncoder().encode(token.nonce);
const signature = sign.detached(nonce, keypair.secretKey);
// Update the signed token with a signature and return it
signedToken.signature = bufferToHex(signature);
return signedToken;
}
// Save an encrypted account to IndexedDB
async saveAccountToIDB(account: EncryptedAccountV2): Promise<void> {
await this.account.add(account, account.uid);
}
// Fetch an encrypted account from IndexedDB by username.
// It is likely the account username will be stored in LocalStorage
// but this method is handy to have just in case of multi-account
// support in the future.
async fetchAccountFromIDB(username: string): Promise<EncryptedAccountV2> {
const accounts = await this.account.toArray()
if (accounts.length === 0) {
return {} as EncryptedAccountV2;
}
const account = await this.account.get(username);
return account!;
}
// ===================
// ACCOUNTS v2
// ===================
// Generate a new encrypted key for V2
async generateAccountV2(password: string): Promise<EncryptedKey> {
// Generate 16 random bytes of salt.
// This is to be used when stretching the password.
const salt = window.crypto.getRandomValues(new Uint8Array(16));
// Derive the stretched key from the password to be used for encryption
const secretKey = await hash({
pass: password,
salt: salt,
type: ArgonType.Argon2id,
hashLen: 32,
});
// The account root key, as the name implies, is the root of the account.
// It is important that this key never leaves the device.
// If a key is compromised, the user account can never be secure.
const rootKey = window.crypto.getRandomValues(new Uint8Array(32));
// Generate 16 bytes of salt to be used for account root key encryption.
const rootKeySalt = window.crypto.getRandomValues(new Uint8Array(16));
// The current implementation relies on cryptography methods provided by the aes-js module.
// To reduce the dependency on third-party libraries, this should eventually be replaced to use
// the Web Crypto API.
// This web application currently uses AES256-CBC.
// Create a new cipher and encrypt the rootkey
const aesCbc = new ModeOfOperation.cbc(secretKey.hash, rootKeySalt);
const rootKeyCiphertext = aesCbc.encrypt(rootKey);
// Construct and return the new account payload
const account: EncryptedKey = {
key: bufferToHex(rootKeyCiphertext),
iv: bufferToHex(rootKeySalt),
salt: bufferToHex(salt)
}
return account;
}
// Decrypt an account to return the root key
async decryptAccountV2(secretKey: Uint8Array, account: EncryptedAccountV2): Promise<Uint8Array> {
// Attempt to decrypt the account root key
// Convert the salt to a format that is AES cipher friendly
const salt = utils.hex.toBytes(account.encrypted_key.iv).slice(0, 16);
// Create the AES256-CBC decipher and decrypt the root key
const aesCbc = new ModeOfOperation.cbc(secretKey, salt);
try {
const rootKey = aesCbc.decrypt(utils.hex.toBytes(account.encrypted_key.key));
return rootKey;
} catch (e) {
throw new Error(e);
}
}
}
// Exports
export default new Account();
|
f38bd5dc46437d0e34e302556a8ce5dbaf07b996
|
TypeScript
|
Cicko/ore-ui
|
/packages/@react-facet/core/src/facet/createFacet.spec.ts
| 2.734375
| 3
|
import 'react'
import { defaultEqualityCheck } from '../equalityChecks'
import { NO_VALUE } from '../types'
import { createFacet } from './createFacet'
describe('equalityChecks', () => {
describe('with defaultEqualityCheck', () => {
it('fires for object values, since it can be mutated', () => {
const update = jest.fn()
const initialValue = {}
const mock = createFacet({ initialValue, equalityCheck: defaultEqualityCheck })
mock.observe(update)
expect(update).toHaveBeenCalledTimes(1)
expect(update).toHaveBeenCalledWith(initialValue)
update.mockClear()
mock.set(initialValue)
expect(update).toHaveBeenCalledTimes(1)
expect(update).toHaveBeenCalledWith(initialValue)
})
it('fires for array values, since it can be mutated', () => {
const update = jest.fn()
const initialValue: string[] = []
const mock = createFacet({ initialValue, equalityCheck: defaultEqualityCheck })
mock.observe(update)
expect(update).toHaveBeenCalledTimes(1)
expect(update).toHaveBeenCalledWith(initialValue)
update.mockClear()
mock.set(initialValue)
expect(update).toHaveBeenCalledTimes(1)
expect(update).toHaveBeenCalledWith(initialValue)
})
it('does not fire for string', () => {
const update = jest.fn()
const initialValue = 'string'
const mock = createFacet({ initialValue, equalityCheck: defaultEqualityCheck })
mock.observe(update)
expect(update).toHaveBeenCalledTimes(1)
expect(update).toHaveBeenCalledWith(initialValue)
update.mockClear()
mock.set(initialValue)
expect(update).toHaveBeenCalledTimes(0)
})
it('does not fire for boolean', () => {
const update = jest.fn()
const initialValue = true
const mock = createFacet({ initialValue, equalityCheck: defaultEqualityCheck })
mock.observe(update)
expect(update).toHaveBeenCalledTimes(1)
expect(update).toHaveBeenCalledWith(initialValue)
update.mockClear()
mock.set(initialValue)
expect(update).toHaveBeenCalledTimes(0)
})
it('does not fire for number', () => {
const update = jest.fn()
const initialValue = 1
const mock = createFacet({ initialValue, equalityCheck: defaultEqualityCheck })
mock.observe(update)
expect(update).toHaveBeenCalledTimes(1)
expect(update).toHaveBeenCalledWith(initialValue)
update.mockClear()
mock.set(initialValue)
expect(update).toHaveBeenCalledTimes(0)
})
it('fires if the primitive value changed', () => {
const update = jest.fn()
const initialValue = 'initial'
const mock = createFacet({ initialValue, equalityCheck: defaultEqualityCheck })
mock.observe(update)
expect(update).toHaveBeenCalledTimes(1)
expect(update).toHaveBeenCalledWith(initialValue)
update.mockClear()
const newValue = 'new value'
mock.set(newValue)
expect(update).toHaveBeenCalledTimes(1)
expect(update).toHaveBeenCalledWith(newValue)
})
})
})
it('multiple observes, one is cleaned up', () => {
const updateOne = jest.fn()
const updateTwo = jest.fn()
const initialValue = 'initial'
const mock = createFacet({ initialValue })
mock.observe(updateOne)
const unsubscribe = mock.observe(updateTwo)
expect(updateOne).toHaveBeenCalledTimes(1)
expect(updateOne).toHaveBeenCalledWith(initialValue)
expect(updateTwo).toHaveBeenCalledTimes(1)
expect(updateTwo).toHaveBeenCalledWith(initialValue)
updateOne.mockClear()
updateTwo.mockClear()
unsubscribe()
const newValue = 'new value'
mock.set(newValue)
expect(updateOne).toHaveBeenCalledTimes(1)
expect(updateOne).toHaveBeenCalledWith(newValue)
expect(updateTwo).toHaveBeenCalledTimes(0)
})
it('supports unsubscribing as events are firing', () => {
const updateOne = jest.fn()
const mock = createFacet<string>({ startSubscription: () => () => {}, initialValue: NO_VALUE })
const unsubscribeOne = mock.observe(updateOne)
const updateTwo = jest.fn().mockImplementation(() => {
unsubscribeOne()
})
const updateThree = jest.fn()
mock.observe(updateTwo)
mock.observe(updateThree)
const newValue = 'new value'
mock.set(newValue)
expect(updateOne).toHaveBeenCalledTimes(1)
expect(updateTwo).toHaveBeenCalledTimes(1)
expect(updateThree).toHaveBeenCalledTimes(1)
})
describe('cleanup', () => {
it('keeps the value if no startSubscription is provided (useful for local facets)', () => {
const value = 'test-value'
const mock = createFacet<string>({ initialValue: NO_VALUE })
// setup our first listener and write a value to the facet
const firstListener = jest.fn()
const firstSubscription = mock.observe(firstListener)
mock.set(value)
// verify we get the value
expect(mock.get()).toBe(value)
// removing the only subscription, should still keep the value
firstSubscription()
expect(mock.get()).toBe(value)
})
it('calls the cleanup function and resets the value when the last listener is removed', () => {
const value = 'test-value'
const initialValue = 'initial-value'
const cleanup = jest.fn()
const startSubscription = jest.fn().mockImplementation((update) => {
update(value)
return cleanup
})
const mock = createFacet<string>({ startSubscription, initialValue })
expect(startSubscription).not.toBeCalled()
expect(mock.get()).toBe(initialValue)
const firstListener = jest.fn()
const firstSubscription = mock.observe(firstListener)
// given it is the first listener, it requests the facet from the startSubscription
expect(startSubscription).toBeCalledTimes(1)
expect(cleanup).not.toHaveBeenCalled()
expect(mock.get()).toBe(value)
const secondListener = jest.fn()
const secondSubscription = mock.observe(secondListener)
// on a second listener, it should not call it again
expect(startSubscription).toBeCalledTimes(1)
expect(cleanup).not.toHaveBeenCalled()
expect(mock.get()).toBe(value)
// removing the first subscription, should not call the cleanup
firstSubscription()
expect(cleanup).not.toHaveBeenCalled()
expect(mock.get()).toBe(value)
// removing the second (and final) subscription, should call the cleanup
secondSubscription()
expect(cleanup).toBeCalledTimes(1)
expect(mock.get()).toBe(initialValue)
})
})
it('prevents calling listeners if a setter returns NO_VALUE', () => {
const facet = createFacet({ initialValue: 10 })
const cleanupMock = jest.fn()
const listenerMock = jest.fn().mockReturnValue(cleanupMock)
facet.observe(listenerMock)
// after observing it, the listener is called once with the initial value (but not the cleanup)
expect(listenerMock).toHaveBeenCalledTimes(1)
expect(listenerMock).toHaveBeenCalledWith(10)
expect(cleanupMock).not.toHaveBeenCalled()
listenerMock.mockClear()
listenerMock.mockClear()
cleanupMock.mockClear()
facet.set(() => NO_VALUE)
// after using a setter callback to return NO_VALUE, the previous cleanup should be called, but not the listener again
expect(listenerMock).not.toHaveBeenCalled()
expect(cleanupMock).toHaveBeenCalledTimes(1)
})
|
b43071bdd062bcbed25471a546029f0ba33e3efc
|
TypeScript
|
fireb1001/neonest
|
/src/types/tag.type.ts
| 2.578125
| 3
|
export type Tag = {
id: string;
name: string;
related: Array<any>;
};
export class TagDto {
id: string;
name: string;
constructor(data) {
Object.assign(this, data);
}
}
|
1b8b58aa1a14fe08a2adb8b9aaafe630cfed3b82
|
TypeScript
|
infuerno/okta-auth-js
|
/lib/idx/remediators/AuthenticatorVerificationData.ts
| 2.6875
| 3
|
import { Base, RemediationValues } from './Base';
export interface AuthenticatorVerificationDataValues extends RemediationValues {
authenticators?: string[];
}
export class AuthenticatorVerificationData extends Base {
values: AuthenticatorVerificationDataValues;
map = {
'authenticator': ['authenticator']
};
canRemediate() {
// TODO: check if authenticator exist in values
return this.remediation.value
.some(({ name }) => name === 'authenticator');
}
mapAuthenticator() {
const authenticatorVal = this.remediation.value
.find(({ name }) => name === 'authenticator').form.value;
return {
id: authenticatorVal
.find(({ name }) => name === 'id').value,
enrollmentId: authenticatorVal
.find(({ name }) => name === 'enrollmentId').value,
methodType: 'sms',
};
}
getValues(): AuthenticatorVerificationDataValues {
return {};
}
}
|
b99d4709d97142a94b6434c097f1afa9a03fccce
|
TypeScript
|
imcj/EventLogging
|
/eventlogging.js/src/TrackingEvent/ExceptionEvent.ts
| 2.625
| 3
|
import TrackingEvent from "./TrackingEvent";
export default class ExceptionTrackingEvent extends TrackingEvent {
message: Event | string;
url: string;
lineNumber: number;
columnNumber: number;
error: Error;
stack: string;
public constructor(message: Event | string,
url: string,
lineNumber: number,
columnNumber: number,
error: Error,
stack: string) {
super();
this.message = message;
this.url = url;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.error = error;
this.stack = stack;
this.trackingEventType = 'ExceptionTrackingEvent';
}
}
|
253cdb79f6e01393a50ca3899c9a6daf4dc782fb
|
TypeScript
|
Blurlingite/jotto-redux
|
/src/actions/index.ts
| 3.578125
| 4
|
import axios from "axios";
import { getLetterMatchCount } from "../helpers";
import { ThunkDispatch } from "redux-thunk";
import { AppState } from "../App";
export const actionTypes = {
CORRECT_GUESS: "CORRECT_GUESS",
GUESS_WORD: "GUESS_WORD",
SET_SECRET_WORD: "SET_SECRET_WORD",
};
// type guessedWordType = { guessedWord: string; letterMatchCount: number };
// interface AppState {
// secretWord: string;
// success: boolean;
// guessedWords: guessedWordType[];
// }
/**
* @function guessWord
* @param {string} guessedWord - Guessed word.
* @returns {function} - Redux Thunk function.
*/
// TODO: find out how to type this action creator (Redux Thunk)
export const guessWord = (guessedWord: string) => {
// this is possible b/c of Redux Thunk middleware
// It lets us dispatch more than 1 action at once by returning a function
// it may be fine to leave dispatch's type as any, since it's Redux Thunk's function & not one I made: https://github.com/reduxjs/redux-thunk/blob/master/test/typescript.ts
// For Redux Thunk's getState(), you just need a function that uses your defined state, so be sure
// to use '() =>' before your state
return function (
dispatch: ThunkDispatch<AppState, undefined, any>,
getState: () => AppState
) {
const secretWord = getState().secretWord;
const letterMatchCount = getLetterMatchCount(guessedWord, secretWord);
// add to the guessedWords array in the state
dispatch({
type: actionTypes.GUESS_WORD,
guessedWord: { guessedWord, letterMatchCount },
});
// if the guessed word matches the secret word, tell the successReducer to
// update the success in state from false to true
if (guessedWord === secretWord) {
dispatch({
type: actionTypes.CORRECT_GUESS,
});
}
};
};
export const getSecretWord = () => {
return (dispatch: ThunkDispatch<AppState, undefined, any>) => {
// make sure to put a return before the axios call in this case so
// that this function doesn't complete before the asynchroncity is complete
// the 'response' variable in .then() is being declared for the first time there, so you
// can name it what you like. Whatever you name it, the response that axios gets will
// be what the 'response' variable equals
return axios.get("http://localhost:3030").then((response) => {
dispatch({
type: actionTypes.SET_SECRET_WORD,
secretWord: response.data, // axios stores the stuff from the response (in this case the secretWord) in .data of the response object
});
});
};
};
|
e97a2fa5e0f96c6fb297f94c490ecdb8e845eb51
|
TypeScript
|
codsen/codsen
|
/packages/string-character-is-astral-surrogate/src/main.ts
| 3.578125
| 4
|
// high surrogate goes first, low goes second
function isHighSurrogate(something: string | undefined): boolean {
// [\uD800-\uDBFF]
if (typeof something === "string") {
if (something.length === 0) {
return false;
}
// \uD800 charCode is 55296
// \uDBFF charCode is 56319
return something.charCodeAt(0) >= 55296 && something.charCodeAt(0) <= 56319;
}
if (something === undefined) {
return false;
}
throw new TypeError(
`string-character-is-astral-surrogate/isHighSurrogate(): the input is not string but ${typeof something}`,
);
}
function isLowSurrogate(something: string | undefined): boolean {
// [\uDC00-\uDFFF]
if (typeof something === "string") {
if (something.length === 0) {
return false;
}
// \uDC00 charCode is 56320
// \uDFFF charCode is 57343
return something.charCodeAt(0) >= 56320 && something.charCodeAt(0) <= 57343;
}
if (something === undefined) {
return false;
}
throw new TypeError(
`string-character-is-astral-surrogate/isLowSurrogate(): the input is not string but ${typeof something}`,
);
}
export { isHighSurrogate, isLowSurrogate };
|
e2b8abf5317dd3335b1af05a2ecc6b8072dd8cfb
|
TypeScript
|
stephaniaoz/otherProyects
|
/typescriptPrueba/coche.ts
| 3.734375
| 4
|
class Coche{
public color: string;
public modelo: string;
public velocidad: number;
constructor(modelo:any = null){
this.color = "Blanco";
this.velocidad = 0;
if(modelo == null){
this.modelo = "BMW Generico";
}else{
this.modelo = modelo;
}
}
public getColor(){
return this.color;
}
public setColor(color: string){
this.color = color;
}
public acelerar(){
this.velocidad++;
}
public frenar(){
this.velocidad--;
}
public getVelocidad():number{
return this.velocidad;
}
public getModelo(){
return this.modelo;
}
public setModelo(modelo){
this.modelo = modelo;
}
}
var coche = new Coche("Renault Clio");
coche.setColor("ROJO");
coche.acelerar();
coche.acelerar();
coche.acelerar();
console.log("modelo del coche 1 es: " + coche.getModelo());
console.log("color del coche 1 es: " + coche.getColor());
console.log("velocidad del coche 1 es: " + coche.getVelocidad());
coche.frenar();
console.log("velocidad del coche 1 despues de frenar es: " + coche.getVelocidad());
//interfaces:
/*
interface CocheBase{
getModelo():string;
getVelocidad():number;
}
class Coche implements CocheBase{
public getModelo(){
return this.modelo;
}
public getVelocidad():number{
return this.velocidad;
}
}
*/
/*
var coche_dos = new Coche();
var coche_tres = new Coche();
coche_dos.setColor("AZUL");
coche_tres.setColor("VERDE");
console.log("color del coche 2 es: " + coche_dos.getColor());
console.log("color del coche 3 es: " + coche_tres.getColor());
*/
|
f342bbfe241c92ca7c5c2a24363f7ee4d0109145
|
TypeScript
|
xDeaa/myExpress
|
/lib/router/index.ts
| 2.796875
| 3
|
import {IncomingMessage, ServerResponse} from 'http';
import { parse } from 'querystring';
interface Route {
method: string,
url: string,
callback: Function,
regex: RegExp | null
}
export default class Router {
public readonly routes: Route[] = [];
newRoute(route:Route) {
if (route.method === "ALL") {
for (let method of ["GET","POST","PUT","DELETE"]) {
this.routes.push({method, url: route.url, callback: route.callback, regex: route.regex});
}
} else {
this.routes.push(route);
}
}
navigate(req: IncomingMessage, res: ServerResponse) {
const { method, url } : IncomingMessage = req;
const request: Request = req;
const response = this.handleResponse(res);
const matchRoute = this.routes.find((route) => {
if (route.method !== req.method && route.method !== "ALL") { return false }
const matcher = url.match(route.regex)
const isMatched = matcher && matcher.length > 0
if (!isMatched && route.url !== req.url) { return false }
request.params = {}
if (isMatched) {
request.params = matcher.groups
}
request.query = {}
return true
});
if(matchRoute) {
matchRoute.callback(req, response);
} else {
res.write("404 not found");
res.end();
}
}
handleResponse(res: ServerResponse) {
const json = (item: any) => {
res.write(JSON.stringify(item));
res.end();
}
const send = (content: string): void => {
res.write(content);
res.end();
}
return Object.assign({},{json,send},res);
}
}
|
32a4def6da11befd9d812e548225508fe04ddb0c
|
TypeScript
|
ingamartinez/store-cart
|
/src/app/Models/product.model.ts
| 2.546875
| 3
|
import { Image } from './image.model';
import { Price } from './price.model';
export class Product{
availableForPickup: boolean;
code: number;
description: string;
images: Image[];
manufacturer: string;
name: string;
price: Price;
constructor(availableForPickup: boolean,
code: number,
description: string,
images: Image[],
manufacturer: string,
name: string,
price: Price) {
this.code = code;
this.description = description;
this.images = images;
this.manufacturer = manufacturer;
this.name = name;
this.price = price;
}
}
|
65e1f217d3de4bb8270baad0f1192ed9b26d4cdc
|
TypeScript
|
diegoshakan/typescript_poo
|
/Atividade2/exe1.ts
| 3.34375
| 3
|
let nomes: string[] = ['Bruno', 'Elaine', 'José', 'Matheus', 'Maria', 'Alana', 'Erika',
'Alison', 'Lucas', 'Rickson', 'Beatriz', 'Alberto', 'Renata', 'Sayonara'];
console.log('Inicialmente, há', nomes.length, 'nomes na lista.');
//Nº 1.a - Insira dois nomes na lista.
nomes.push('Eduardo', 'Mônica');
//Nº 1.b - Obtenha a quantidade de nomes adicionados.
console.log('Há na lista', nomes.length, 'nomes, após inserção.');
//Nº 1.c - Remova o terceiro nome da lista.
delete nomes[2];
//Nº 1.d - Realize uma busca por um nome qualquer e diga qual é a sua posição na lista.
console.log('O nome Maria está na posição', nomes.lastIndexOf('Maria'),
'da lista de nomes.');
///Nº 1.e - Conte quantos nomes começam com a letra "A".
let count: number = 0;
for(let i in nomes){
if (nomes[i][0] === 'A'){
count +=1;
}
}
console.log('Há na lista', count, 'nomes que começam com a letra A.');
let qtd: number = 0;
nomes.forEach(n => {
if (n.charAt(0) === 'A'){
qtd += 1;
}
});
console.log(qtd);
/*// Outro modo de se achar um nome que começa com uma letra específica.
for (let i in nomes){
if (nomes[i].charAt(0) === 'A'){
qtd += 1;
}
}
console.log(qtd);*/
|
31ff4fdeadf3aa8a997b321f06f21a17d3a447d9
|
TypeScript
|
javii42/LAB_4
|
/SalaDeJuegos/src/app/clases/juego.ts
| 2.671875
| 3
|
export abstract class Juego {
public nombre = 'Sin Nombre';
public jugador: string;
public gano = false;
constructor(nombre?: string, gano?: boolean,jugador?:string) {
if (nombre)
this.nombre = nombre;
if (gano)
this.gano = gano;
if(jugador)
this.jugador=jugador;
else
this.jugador= "natalia natalia";
}
public abstract verificar():boolean;
public guardarDatos(){
var partidas = JSON.parse(localStorage.getItem('partidas'));
if(partidas == null){
var partidasAux = [{
"jugador": "javier@gmail.com",
"juego": "Adivina el número",
"resultado":false
},
{
"jugador": "pepe@gmail.com",
"juego": "Anagrama",
"resultado":false
},
{
"jugador": "roberto@gmail.com",
"juego": "Atrapalos",
"resultado":true
},
{
"jugador": "javier@gmail.com",
"juego": "Piedra Papel Tijera",
"resultado":true
},
{
"jugador": "javier@gmail.com",
"juego": "Piedra Papel Tijera",
"resultado":false
},];
localStorage.setItem('partidas', JSON.stringify(partidasAux));
partidas = partidasAux;
}
partidas.push({"jugador":this.jugador,"juego":this.nombre,"resultado":this.gano});
localStorage.setItem('partidas',JSON.stringify(partidas));
console.log(partidas);
}
public retornarAyuda() {
return "NO hay Ayuda definida";
}
}
|
017aaa87c7e6d7f9d482ca8e6a37d4e45b7e6c28
|
TypeScript
|
StanixGames/nature-game
|
/src/utils/QuadTree.ts
| 3.046875
| 3
|
import Rect from './Rect';
import Node from './Node';
class QuadTree {
public root: Node;
constructor(bounds: Rect, maxDepth: number, maxChildren: number) {
this.root = new Node(bounds, 0, maxDepth, maxChildren);
}
public clear(): void {
this.root.clear();
}
public insert(itemOrList: any | any[]): void {
if (itemOrList instanceof Array) {
this._insertItemlist(itemOrList);
return;
}
this.root.insert(itemOrList);
}
public retrieve(item: any): Node[] | any[] {
return this.root.retrieve(item).slice(0);
}
private _insertItemlist(itemList: any[]): void {
for (let i = 0; i < itemList.length; i++) {
this.root.insert(itemList[i]);
}
}
}
export default QuadTree;
|
5667ead737e83ccdc7bd3253c14dded575ce8295
|
TypeScript
|
S-YC/WebFront
|
/src/store/modules/login/loginR.ts
| 2.640625
| 3
|
import {
AsyncThunk,
createAsyncThunk,
createSlice,
PayloadAction,
} from "@reduxjs/toolkit";
import { AxiosResponse } from "axios";
import { RootState } from "..";
import Http, { IRes } from "../../net/Http";
// 이름 설정
const name = "login";
/**
* 저장될 유저 정보 인터페이스 설정
*/
export interface ILogin {
reqId: string;
id?: string;
uname?: string;
}
/**
* 서버 통신 시 회원가입 정보
*/
export interface IUserFetc {
email: string;
pwd: string;
nickname: string;
agmkEmail: boolean;
agmkSmsLms: boolean;
}
export interface IResSign {
token: string;
key: string;
}
/**
* 비동기 함수를 생성 pending, fulfilled, rejected 를 실행되게
*/
export const fetchSign: AsyncThunk<
IRes<IResSign>,
IUserFetc,
{ state: RootState }
> = createAsyncThunk<IRes<IResSign>, IUserFetc, { state: RootState }>(
`${name}/fetchSign`,
async (params: IUserFetc, thunkApi) => {
try {
return sign(params);
} catch (err) {
// 통신 실패 처리
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return thunkApi.rejectWithValue(err);
}
}
);
/**
* SSR 일때 통신하기 위한 함수
* @param params IUserFetc
* @returns
*/
export const sign: (param: IUserFetc) => Promise<IRes<IResSign>> = async (
params: IUserFetc
): Promise<IRes<IResSign>> => {
const res: AxiosResponse<IRes<IResSign>> = await Http.post(
"/sign/signup",
params
);
return res.data;
};
/**
* 이메일 Select
// */
export const fetchisEmailSelect: AsyncThunk<
IRes<IResSign>,
{ email: string },
{ state: RootState }
> = createAsyncThunk<IRes<IResSign>, { email: string }, { state: RootState }>(
`${name}/fetchIsEmail`,
async (params: { email: string }, thunkApi) => {
try {
return isEmailSelect(params);
} catch (err) {
// 통신 실패 처리
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return thunkApi.rejectWithValue(err);
}
}
);
export const isEmailSelect: (param: {
email: string;
}) => Promise<IRes<IResSign>> = async (params: {
email: string;
}): Promise<IRes<IResSign>> => {
const res: AxiosResponse<IRes<IResSign>> = await Http.post(
"/login/isEmailSelect",
params
);
return res.data;
};
/**
* 닉네임 중복검사
// */
export const fetchIsnickName: AsyncThunk<
IRes<IResSign>,
{ nickname: string },
{ state: RootState }
> = createAsyncThunk<
IRes<IResSign>,
{ nickname: string },
{ state: RootState }
>(`${name}/fetchIsnickName`, async (params: { nickname: string }, thunkApi) => {
try {
return isnickName(params);
} catch (err) {
// 통신 실패 처리
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return thunkApi.rejectWithValue(err);
}
});
export const isnickName: (param: {
nickname: string;
}) => Promise<IRes<IResSign>> = async (params: {
nickname: string;
}): Promise<IRes<IResSign>> => {
const res: AxiosResponse<IRes<IResSign>> = await Http.post(
"/sign/isnickName",
params
);
return res.data;
};
// data 를 관리하는 reducer 설정
const userSlice = createSlice({
name,
initialState: { reqId: "", id: "" } as ILogin,
reducers: {
signAction(state: ILogin, action: PayloadAction<ILogin>) {
return { ...state, ...action.payload };
},
},
extraReducers: builder => {
// pending 액션을 통해 상태를 변화 시키기 위한 등록
// 서버 통신하기전 호출되는 함수
// 회원가입
builder.addCase(fetchSign.pending, (state: ILogin, action) => {
return { ...state, reqId: action.meta.requestId };
});
// 이메일 중복검사
builder.addCase(fetchisEmailSelect.pending, (state: ILogin, action) => {
return { ...state, reqId: action.meta.requestId };
});
// 닉네임 중복검사
builder.addCase(fetchIsnickName.pending, (state: ILogin, action) => {
return { ...state, reqId: action.meta.requestId };
});
// fulfilled 액션을 통해 상태를 변화 시키기 위한 등록
// 서버 통신후 성공 하면 호출되는 함수
// 회원가입
builder.addCase(fetchSign.fulfilled, (state: ILogin, { payload }) => {
if (payload.result) {
console.log(payload.result);
return;
} else {
console.log(payload.data);
}
});
// 이메일 Select
builder.addCase(
fetchisEmailSelect.fulfilled,
(state: ILogin, { payload }) => {
if (payload.result) {
// console.log(payload);
return;
} else {
console.log(payload.data);
}
}
);
// 닉네임 중복검사
builder.addCase(fetchIsnickName.fulfilled, (state: ILogin, { payload }) => {
if (payload.result) {
// console.log(payload);
return;
} else {
console.log(payload.data);
}
});
// rejected 액션을 통해 상태를 변화 시키기 위한 등록
// 서버 통신이 실패 했을때 호출되는 함수
builder.addCase(fetchSign.rejected, (state: ILogin, action) => {
console.log("실패", state, action);
});
},
});
/**
* CSR 에서 쓰는 액션들
*/
export const { signAction } = userSlice.actions;
// data 를 관리하는 reducer 기본 반환 설정
export default userSlice.reducer;
|
d9c68173590c5a43afe0d13decf97e21de4bb0d7
|
TypeScript
|
DreamLarva/learn-typescript
|
/文章/有泛型的类的继承的一个问题.ts
| 3.8125
| 4
|
import * as CSS from "csstype";
/*
interface StylesObject<P extends object = {}> extends Styles {
// ^~~~~~~~~~~^ error
foo: (props: P) => void;
}
type Styles<P extends object = {}> = {
foo: (props: P) => void;
};
*/
/*
报错
'{}' is assignable to the constraint of type 'P' (a), but 'P' could be instantiated
with a different subtype of constraint 'object' (b).
问题
1. StylesObject 兼容 Styles ,或者说 是 Styles 的子类型
2. 当写了 extends Styles, 我们没有设置 Styles 的泛型, 所以 P 初始化为 默认的 {} 类型
3. StylesObject<P> 希望 继承 Styles<{}>, 但是这两者 不兼容
* */
/*
{
const myStylesObject: StylesObject<{ foo: string }> = {foo(){}};
const styles: Styles<{}> = myStylesObject; // error: incompatible
}
*/
/*
In principle, StylesObject allows any argument type,
that extends constraint object (default = {} not important here).
And Styles<{}> would be compatible to object. This is what error part (a) says.
But what, if P is a more narrow subtype of object,
like myStylesObject in above code?
It wouldn't work anymore. This is what error part (b) says.
子类型 和 父类型 同时有泛型时
我觉得 意思就是 出现 父子类型 泛型 协变
* */
/**
* 解决办法 1
* 使用 交叉类型 拓展
* */
{
type StylesFn<P extends object> = (
props: P
) => CSS.Properties<JssValue<P>> | number | string;
type JssValue<P extends object> =
| string
| number
| Array<string | number>
| StylesFn<P>;
type StylesObject<K extends string = any, P extends object = {}> = Styles<K, P> & {
[x: string]: CSS.Properties<JssValue<P>> | Styles<K, P>;
}
type Styles<K extends string = any, P extends object = {}> = {
[x in K]: CSS.Properties<JssValue<P>> | StylesObject<any, P> | StylesFn<P>
};
}
/**
* 办法 2
*
* 但是这个例子写的有问题
* */
/*{
type StylesFn<P extends object> = (
props: P
) => CSS.Properties<JssValue<P>> | number | string;
type JssValue<P extends object> =
| string
| number
| Array<string | number>
| StylesFn<P>;
interface StylesObject<K extends string = any, P extends object = {}>
extends Styles<K, P> {
[x: string]: CSS.Properties<JssValue<P>> | Styles<K, P>;
}
type Styles<K extends string = any, P extends object = {}> = {
[x in K]: CSS.Properties<JssValue<P>> | StylesObject<any, P> | StylesFn<P>
};
}*/
export {};
|
ea0e5254169904e60597d47c1159e518d43aa739
|
TypeScript
|
PeanutQAQ/swr
|
/src/utils/resolve-args.ts
| 2.578125
| 3
|
import { useContext } from 'react'
import { defaultConfig } from './config'
import { SWRConfigContext } from './config-context'
import { mergeConfigs } from './merge-config'
import { normalize } from './normalize-args'
import { mergeObjects } from './helper'
// It's tricky to pass generic types as parameters, so we just directly override
// the types here.
export const withArgs = <SWRType>(hook: any) => {
return (((...args: any) => {
// Normalize arguments.
const [key, fn, _config] = normalize<any, any>(args)
// Get the default and inherited configuration.
const fallbackConfig = mergeObjects(
defaultConfig,
useContext(SWRConfigContext)
)
// Merge configurations.
const config = mergeConfigs(fallbackConfig, _config)
// Apply middleware
let next = hook
const { use } = config
if (use) {
for (let i = use.length; i-- > 0; ) {
next = use[i](next)
}
}
return next(key, fn || config.fetcher, config)
}) as unknown) as SWRType
}
|
f87c4797546526cb320b5d25f103e4b3dd2b22c9
|
TypeScript
|
AxiataADA/superset-ui
|
/packages/superset-ui-core/test/time-format/factories/createMultiFormatter.test.ts
| 2.71875
| 3
|
import createMultiFormatter from '@superset-ui/core/src/time-format/factories/createMultiFormatter';
describe('createMultiFormatter()', () => {
describe('creates a multi-step formatter', () => {
const formatter = createMultiFormatter({
id: 'my_format',
useLocalTime: true,
});
it('formats millisecond', () => {
expect(formatter(new Date(2018, 10, 20, 11, 22, 33, 100))).toEqual('.100');
});
it('formats second', () => {
expect(formatter(new Date(2018, 10, 20, 11, 22, 33))).toEqual(':33');
});
it('format minutes', () => {
expect(formatter(new Date(2018, 10, 20, 11, 22))).toEqual('11:22');
});
it('format hours', () => {
expect(formatter(new Date(2018, 10, 20, 11))).toEqual('11 AM');
});
it('format first day of week', () => {
expect(formatter(new Date(2018, 10, 18))).toEqual('Nov 18');
});
it('format other day of week', () => {
expect(formatter(new Date(2018, 10, 20))).toEqual('Tue 20');
});
it('format month', () => {
expect(formatter(new Date(2018, 10))).toEqual('November');
});
it('format year', () => {
expect(formatter(new Date(2018, 0))).toEqual('2018');
});
});
});
|
be73076cb609a8c3f00b5c174d901ea73a2b0d15
|
TypeScript
|
pmviva/ng-dragon-slayer
|
/src/app/modules/game/store/game.state.ts
| 2.75
| 3
|
import { Game } from '@game/models/game.model';
import { GameConstants } from '@game/models/game-constants.model';
/**
* Defines the game state interface.
*/
export interface GameState {
/**
* Defines the game of the game state.
*/
game: Game;
}
/**
* Defines the initial game state.
*/
export const initialGameState: GameState = {
/**
* Defines the game of the initial game state.
*/
game: {
/**
* Defines the running status of the initial game state.
*/
running: false,
/**
* Defines the dragon character of the initial game state.
*/
dragon: {
/**
* Defines the health of the dragon character of the initial game state.
*/
health: GameConstants.MAX_DRAGON_HEALTH,
/**
* Defines the name of the dragon character of the initial game state.
*/
name: GameConstants.DEFAULT_DRAGON_NAME
},
/**
* Defines the player character of the initial game state.
*/
player: {
/**
* Defines the health of the player character of the initial game state.
*/
health: GameConstants.MAX_PLAYER_HEALTH,
/**
* Defines the name of the player character of the initial game state.
*/
name: GameConstants.DEFAULT_PLAYER_NAME
},
/**
* Defines the message list of the initial game state.
*/
messageList: []
}
};
|
9fe9e2e47a7c2b3d83430ac141372f05c765d287
|
TypeScript
|
Nemet360/slicer-ui
|
/cli/utils/initializeColors.ts
| 2.984375
| 3
|
const skinColor = { r : 255/255, g : 224/255, b : 189/255 };
const greyMatterColor = { r : 0.925, g : 0.5, b : 0.5 };
export const initializeColors = (length, datatypeCode ) => {
const rgb = [];
const color = datatypeCode==4 ? skinColor : greyMatterColor;
for(let i = 0; i < length; i++){
rgb.push(color.r, color.g, color.b);
}
return rgb;
}
|
311a33e0292d6887be09e1ad64cf489fb798cb5b
|
TypeScript
|
who0sy/pyright
|
/server/src/analyzer/symbol.ts
| 3.09375
| 3
|
/*
* symbol.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* Represents an association between a name and the type
* (or multiple types) that the symbol is associated with
* in the program.
*/
import { DiagnosticTextRange } from '../common/diagnostic';
import StringMap from '../common/stringMap';
import { ParseNode } from '../parser/parseNodes';
import { InferredType, TypeSourceId } from './inferredType';
import { Type, TypeCategory } from './types';
export enum SymbolCategory {
Variable,
Import,
Parameter,
Function,
Method,
Class,
Module
}
export interface Declaration {
// Category of this symbol (function, variable, etc.).
// Used by hover provider to display helpful text.
category: SymbolCategory;
// The node that contains the definition.
node: ParseNode;
// Declared type (if specified) of the symbol.
declaredType?: Type;
// The file and range within that file that
// contains the declaration.
path: string;
range: DiagnosticTextRange;
}
export class Symbol {
// Inferred type of the symbol.
inferredType: InferredType = new InferredType();
// Information about the node that declared the value -
// i.e. where the editor will take the user if "show definition"
// is selected. Multiple declarations can exist for variables,
// properties, and functions (in the case of @overload).
declarations?: Declaration[];
// Type currently bound to the name as analyzer progresses through
// the code flow. Can be UnboundType.
currentType: Type;
// Indicates that the type is conditionally bound (e.g. inside of an
// if statement). Used during analysis to determine how and whether to
// merge types. For example, if both parts of an if/else statement
// conditionally set a value, the combination of the two is unconditional.
// This is used only in temporary scopes.
isConditional?: boolean;
constructor(currentType: Type, typeSourceId: TypeSourceId) {
this.currentType = currentType;
this.addInferredType(currentType, typeSourceId);
}
// Returns true if inferred type changed.
setCurrentType(currentType: Type, typeSourceId: TypeSourceId): boolean {
this.currentType = currentType;
return this.addInferredType(currentType, typeSourceId);
}
// Returns true if inferred type changed.
addInferredType(type: Type, typeSourceId: TypeSourceId): boolean {
if (type.category !== TypeCategory.Unbound) {
return this.inferredType.addSource(type, typeSourceId);
}
return false;
}
addDeclaration(declaration: Declaration) {
if (this.declarations) {
// See if this node was already identified as a declaration. If so,
// replace it. Otherwise, add it as a new declaration to the end of
// the list.
let declIndex = this.declarations.findIndex(decl => decl.node === declaration.node);
if (declIndex >= 0) {
this.declarations[declIndex] = declaration;
} else {
this.declarations.push(declaration);
}
} else {
this.declarations = [declaration];
}
}
}
// Maps names to symbol information.
export class SymbolTable extends StringMap<Symbol> {}
|
66c33af511e0036853a212a2ddb860ba2283b55e
|
TypeScript
|
hrozan/utfpr-final-paper
|
/legacy/server/src/config/index.ts
| 2.625
| 3
|
import Debug from "debug"
const debug = Debug("app:config")
export enum Env {
dev,
prod,
test,
}
export type Index = {
port: number
databaseName?: string
databaseUri: string
jwtKey: string
env: Env
brokerCredential: string
}
const getEnvVar = (envVar: unknown) : string=> {
if (envVar !== undefined) return envVar as string
throw new Error("fail to load config in production")
}
const parseNodeEnv = (nodeEnv: string | undefined): Env => {
switch (nodeEnv) {
case "production":
return Env.prod
case "development":
return Env.dev
default:
return Env.dev
}
}
export let config: Index
const nodeEnv = parseNodeEnv(process.env.NODE_ENV)
if (nodeEnv === Env.prod) {
debug("production")
const { env } = process
config = {
brokerCredential: getEnvVar(env.BROKER_CREDENTIAL),
databaseUri: getEnvVar(env.MONGO_URL),
env: nodeEnv,
jwtKey: getEnvVar(env.JWT_KEY),
port: parseInt(getEnvVar(env.PORT)),
}
} else {
debug("development")
const databaseName = process.env.DB_NAME || "FinalPaper"
config = {
brokerCredential: process.env.BROKER_CREDENTIAL || "user.pass123",
databaseName,
databaseUri: process.env.MONGO_URL || `mongodb://localhost:27017/${databaseName}`,
env: parseNodeEnv(process.env.NODE_ENV || "development"),
jwtKey: process.env.JWT_KEY || "test-key",
port: parseInt(process.env.PORT || "3000", 10),
}
}
|
f37371d244ffc59bfb7b620522b4b6e629c4fa8d
|
TypeScript
|
Ewo-team/ewo-next
|
/src/engine/Characters/CharacterTools.ts
| 2.5625
| 3
|
/**
* @module Engine.Characters
* Characters
* @preferred
*/
import { capitalizeFirstLetter } from '@engine/Helpers';
import { IStateServer } from '@engine/reducers';
import { GradeTemplate, Plans, Races } from '@engine/resources';
import {
Character,
CharacterDatabase,
CharacterFrontend,
CharacterLimitedFrontend,
CharacterPosture,
CharacterStates,
Classes,
Genre,
} from '@models';
import { Store } from 'redux';
const levelHpModifier = 1;
const levelRegenHpModifier = 1;
const levelSpeedModifier = 1;
const levelRegenSpeedModifier = 1;
const levelDexterityModifier = 1;
const levelStrengthModifier = 1;
const levelAgilityModifier = 1;
const levelRegenAgilityModifier = 1;
const levelInsightModifier = 1;
const levelMagicModifier = 1;
export class CharactersTools {
public static factory = (values?: Partial<CharacterDatabase>): Character => {
const character: Partial<Character> = {};
if (values !== undefined) {
if (values.maps !== undefined) {
character.position = { plan: Plans[values.maps] } as any; // @TODO
}
CharactersTools.properties.forEach((property) => {
if (values[property] !== undefined) {
character[property] = values[property];
} else if (CharactersTools.defaultValues[property] !== undefined) {
character[property] = CharactersTools.defaultValues[property];
}
});
} else {
CharactersTools.properties.forEach((property) => {
if (CharactersTools.defaultValues[property] !== undefined) {
character[property] = CharactersTools.defaultValues[property];
}
});
}
return CharactersTools.updateCharacter(character as Character);
}
public static findCharacter = (iMat: number | string, store: Store<IStateServer>): Character => {
const mat = typeof iMat === 'string' ? Number(iMat) : iMat;
return store.getState().Characters.find(c => c.mat === mat);
}
public static currentCharacter = (mat, store: Store<IStateServer>): Character | null => {
const character = store.getState().Characters.find(c => c.mat === mat);
if (character !== undefined) {
return character;
}
return null;
}
// public static hydrater = (source: CharacterDatabase): Character => CharactersTools.factory(source);
public static serializer = (source: Character): CharacterDatabase => {
const json: Partial<CharacterDatabase> = {
mat: source.mat,
name: source.name,
race: source.race,
};
if (source.position) {
json.maps = source.position.plan.id;
}
CharactersTools.properties.forEach(property => {
json[property] = source[property];
});
return json as CharacterDatabase;
}
public static toFrontEnd = (source: Character): CharacterFrontend => {
const dest: CharacterFrontend = Object.assign({}, source) as any;
if (source.position) {
dest.coord = {
x: source.position.coord.x,
y: source.position.coord.y,
plan: source.position.plan.id,
};
}
delete (dest as any).position;
return dest;
}
public static toFrontEndLimited = (source: Character): CharacterLimitedFrontend => {
const character = CharactersTools.toFrontEnd(source);
return {
genre: character.genre,
grade: character.grade,
mat: character.mat,
name: character.name,
race: character.race,
xp: character.xp,
};
}
public static updateCharacter(character: Character): Character {
const race = Races[character.race];
// tslint:disable-next-line: no-parameter-reassignment
character = CharactersTools.updateBuffs(character);
character.maxHp =
(character.levelHp * levelHpModifier) + race.template.hp + GradeTemplate(character.grade).hp;
character.hp = character.maxHp + character.modifHp;
character.maxRegenHp =
(character.levelRegenHp * levelRegenHpModifier) + race.template.regenHp + GradeTemplate(character.grade).regenHp;
character.regenHp = character.maxRegenHp + character.modifRegenHp;
character.maxSpeed =
(character.levelSpeed * levelSpeedModifier) + race.template.speed + GradeTemplate(character.grade).speed;
character.speed = character.maxSpeed + character.modifSpeed;
character.maxRegenSpeed =
(character.levelRegenSpeed * levelRegenSpeedModifier) + race.template.regenSpeed + GradeTemplate(character.grade).regenSpeed;
character.regenSpeed = character.maxRegenSpeed + character.modifRegenSpeed;
character.dexterity =
(character.levelDexterity * levelDexterityModifier) + race.template.dexterity + GradeTemplate(character.grade).dexterity;
character.currentDexterity = character.dexterity + character.modifDexterity;
character.strength =
(character.levelStrength * levelStrengthModifier) + race.template.strength + GradeTemplate(character.grade).strength;
character.currentStrength = character.strength + character.modifStrength;
character.insight =
(character.levelInsight * levelInsightModifier) + race.template.insight + GradeTemplate(character.grade).insight;
character.currentInsight = character.insight + character.modifInsight;
character.maxAgility =
(character.levelAgility * levelAgilityModifier) + race.template.agility + GradeTemplate(character.grade).agility;
character.agility = character.maxAgility + character.modifAgility;
character.maxRegenAgility =
(character.levelRegenAgility * levelRegenAgilityModifier) + race.template.regenAgility + GradeTemplate(character.grade).regenAgility;
character.regenAgility = character.maxRegenAgility + character.modifRegenAgility;
character.magic =
(character.levelMagic * levelMagicModifier) + race.template.magic + GradeTemplate(character.grade).magic;
character.currentMagic = character.magic + character.modifMagic;
return character;
}
private static readonly properties = [
'mat',
'name',
'race',
'grade',
'classes',
'genre',
'motd',
'minutes',
'owner',
'posture',
'xp',
'ep',
'buffs',
'maps',
'currentHp',
'levelHp',
'levelRegenHp',
'currentSpeed',
'levelSpeed',
'levelRegenSpeed',
'levelDexterity',
'levelStrength',
'levelInsight',
'currentAgility',
'levelAgility',
'levelRegenAgility',
'levelMagic',
];
private static readonly defaultValues: Partial<Character> = {
grade: {
major: 0,
minor: 0,
},
race: 'te',
classes: Classes.Base,
genre: Genre.Other,
motd: '',
owner: 0,
posture: CharacterPosture.Default,
xp: 0,
ep: 0,
buffs: [],
currentHp: 1,
levelHp: 0,
levelRegenHp: 0,
currentSpeed: 0,
levelSpeed: 0,
levelRegenSpeed: 0,
levelDexterity: 0,
levelStrength: 0,
levelInsight: 0,
currentAgility: 0,
levelAgility: 0,
levelRegenAgility: 0,
levelMagic: 0,
};
private static updateBuffs(character: Character): Character {
const bmDefault = {
[CharacterStates.Agility]: 0,
[CharacterStates.Dexterity]: 0,
[CharacterStates.Hp]: 0,
[CharacterStates.Insight]: 0,
[CharacterStates.Magic]: 0,
[CharacterStates.RegenAgility]: 0,
[CharacterStates.RegenHp]: 0,
[CharacterStates.RegenSpeed]: 0,
[CharacterStates.Speed]: 0,
[CharacterStates.Strength]: 0,
};
const buffCalc = character.buffs.reduce(
(total, buff) => {
total[buff.operation][buff.state] += buff.value;
return total;
},
{
bonus: bmDefault,
malus: bmDefault,
});
Object.keys(buffCalc.bonus).forEach(s => {
// s = CharacterStates
const bonus = buffCalc.bonus[s];
const malus = buffCalc.malus[s];
const modif = bonus - malus;
const state = capitalizeFirstLetter(s);
const stateBonus = `bonus${state}`;
const stateMalus = `malus${state}`;
const stateModif = `modif${state}`;
character[stateBonus] = bonus;
character[stateMalus] = malus;
character[stateModif] = modif;
});
return character;
}
}
|
d7b116c16c0283edbc243b62f897304b910749bf
|
TypeScript
|
project-300/npm-common-types
|
/src/functions/map.ts
| 2.640625
| 3
|
import { Coords, Place } from '../interfaces';
export function GetMidpoint(a: Place, b: Place): Coords {
return {
latitude: (a.latitude + b.latitude) / 2,
longitude: (a.longitude + b.longitude) / 2
}
};
|
ee9fe8ae80c8494ef6d288ae4996d277c3e4aad6
|
TypeScript
|
qianbin/express-toolbox
|
/src/index.ts
| 2.734375
| 3
|
import { RequestHandler, Router } from 'express'
import Http = require('http')
/**
*
* @export
* @class HttpError
*/
export class HttpError extends Error {
constructor(public readonly status: number, message?: string) {
super(message || Http.STATUS_CODES[status])
this.name = Http.STATUS_CODES[status]
}
}
/**
* Wrap a request handler that might return promise, to handle promise error
*
* @export
* @param handler the handler to be wrapped
* @returns wrapped request handler
*/
export function try$(handler: RequestHandler): RequestHandler {
return async (req, res, next) => {
try {
await handler(req, res, next)
} catch (e) {
next(e)
}
}
}
/**
* Hang a router until some tasks done
*
* @export
* @param router
* @returns
*/
export function hang(router: Router) {
let initDone = false;
router.use((req, res, next) => {
if (initDone)
return next();
// response service unavailable
next(new HttpError(503, 'Under initalizing'))
})
return {
until(task: Function) {
(async () => {
try {
await task()
initDone = true
} catch (e) {
console.error("Failed to initialize:", e);
process.exit(1);
}
})()
}
}
}
|
e77614642c7008bdc5bc459cd2191007aee43f03
|
TypeScript
|
cdnjs/cdnjs
|
/ajax/libs/tom-select/1.1.2/types/contrib/microevent.d.ts
| 3.015625
| 3
|
/**
* MicroEvent - to make any js object an event emitter
*
* - pure javascript - server compatible, browser compatible
* - dont rely on the browser doms
* - super simple - you get it immediatly, no mistery, no magic involved
*
* @author Jerome Etienne (https://github.com/jeromeetienne)
*/
export default class MicroEvent {
_events: {};
on(event: any, fct: any): void;
off(event: any, fct: any, ...args: any[]): boolean;
trigger(event: any, ...args: any[]): void;
}
|
d3f35b651f147b574cdb1dc3f2da8f24a9bb0076
|
TypeScript
|
vps2124/AllAngularConcept
|
/src/app/calculator.service.ts
| 2.796875
| 3
|
import { Injectable } from '@angular/core';
@Injectable()
export class CalculatorService {
constructor() {
console.log("Calculator Service created....");
}
add(a:number,b:number):number
{
return a+b;
}
sub(a:number,b:number):number
{
return a-b;
}
mul(a:number,b:number):number
{
return a*b;
}
div(a:number,b:number):number
{
return a/b;
}
mod(a:number,b:number):number
{
return a%b;
}
}
|
2b2271ff743057362bc914e546646d3cebaa8731
|
TypeScript
|
typeioc/typeioc
|
/src/exceptions/argument-error.ts
| 3.125
| 3
|
import { ApplicationError } from './application-error.js'
import { setPrototypeOf } from './common.js'
/**
* Represents argument error. It is thrown when the argument value does not
* comply with the method specification
* @public
*/
export class ArgumentError extends ApplicationError {
/**
* @internal
*/
_argumentName: string
get argumentName() {
return this._argumentName
}
/**
* Constructor
* @param argumentName - argument name
* @param params - optional additional information about the error
* @returns - an instance of ArgumentError
*/
constructor (argumentName: string, params?: { message?: string, data?: {} }) {
super(params)
setPrototypeOf(this, ArgumentError.prototype)
this.name = 'Argument Error'
this._argumentName = argumentName
}
}
|
fc95993a5ded834f802657c68c3d79e12fdbfe6d
|
TypeScript
|
YasminElbahar/Eia2Aufgaben
|
/Endaufgabe_EIA2/scripts/Team.ts
| 3.375
| 3
|
abstract class Team {
protected color: string;
protected formation: string;
protected teamList: Array<Player>;
protected targetGoal: Point2D;
constructor(color: string, formation: string) {
this.color = color;
this.formation = formation;
this.teamList = this.generateTeamList(formation);
}
public drawPlayers(canvas: HTMLCanvasElement) {
this.teamList.forEach(player => player.drawPlayer(canvas, this.color));
}
public updatePlayerPositions(ball: Ball) {
this.teamList.forEach(player =>
player.updatePosition(ball, this.targetGoal, this.teamList)
);
}
protected abstract generateTeamList(formation: string): Array<Player>;
protected generatePlayerParams(formation: string) {
let positions = Formation.resolveFormation(formation);
return positions.map(position => {
let speed = Math.floor(Math.random() * 10) + 15;
let power = Math.floor(Math.random() * 30) + 30;
return { "speed": speed, "power": power, "position": position }
});
}
}
enum UserTeamStatus { Idle, Waiting, Shooting };
class UserTeam extends Team {
private status: UserTeamStatus;
private ball: Ball;
constructor(color: string, formation: string) {
super(color, formation);
this.targetGoal = new Point2D(1235, 350);
this.status = UserTeamStatus.Idle;
this.setShootingHandler();
}
updatePlayerPositions(ball: Ball) {
this.teamList.forEach(player => {
player.setShootingOff();
player.updatePosition(ball, this.targetGoal, this.teamList);
});
}
public isWaiting() { return this.status === UserTeamStatus.Waiting; }
public isShooting() { return this.status !== UserTeamStatus.Idle; }
public waitForUserToShoot(ball: Ball) {
this.status = UserTeamStatus.Waiting;
this.ball = ball;
}
protected generateTeamList(formation: string): Array<Player> {
return super.generatePlayerParams(formation).map((params, idx) =>
new UserPlayer(params.speed, params.power, this, params.position, idx+1)
);
}
private setShootingHandler() {
this.setMouseHandler();
this.setKeyBoardHandler();
}
private setMouseHandler() {
document.getElementById("gameField").addEventListener('click', event => {
this.handlerHelper(this.getClickOnCanvas(event));
});
}
private setKeyBoardHandler() {
document.body.addEventListener('keyup', event => {
if (event.code === 'Space') this.handlerHelper(this.targetGoal);
});
}
private handlerHelper(target: Point2D) {
if (this.isWaiting()) {
let shootingPower = parseInt((<HTMLInputElement>document.getElementById('power')).value);
this.ball.setTarget(target, shootingPower);
this.updateShootingStatus();
document.getElementById('message').innerText = `Home team has the ball`;
}
}
private getClickOnCanvas(event: MouseEvent) {
let rect = document.getElementById("gameField").getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
return new Point2D(x, y);
}
private updateShootingStatus() {
this.status = UserTeamStatus.Shooting;
setTimeout(() => { this.status = UserTeamStatus.Idle; }, 600);
}
}
class ComputerTeam extends Team {
constructor(color: string, formation: string) {
super(color, formation);
this.targetGoal = new Point2D(15, 350);
}
protected generateTeamList(formation: string): Array<Player> {
return super.generatePlayerParams(formation).map(params => new ComputerPlayer(
params.speed, params.power, this, this.reversePosition(params.position)
));
}
private reversePosition(position: Point2D) {
return new Point2D(1240 - position.getX(), position.getY());
}
}
|
7791dea1811108fcc6fee0500965ebc6d8a39f38
|
TypeScript
|
redwoodjs/redwood
|
/packages/structure/src/x/path.ts
| 2.90625
| 3
|
import { existsSync } from 'fs'
import { basename, normalize, sep } from 'path'
export function directoryNameResolver(dirName: string): string | undefined {
dirName = normalize(dirName)
const parts = dirName.split(sep)
const pp = parts[parts.length - 1]
parts.push(pp)
const extensions = ['.js', '.jsx', '.ts', '.tsx']
const pathNoExt = parts.join(sep)
for (const ext of extensions) {
const path = pathNoExt + ext
if (existsSync(path)) {
return path
}
}
}
export function followsDirNameConvention(filePath: string): boolean {
filePath = normalize(filePath)
const ending = basenameNoExt(filePath) + sep + basename(filePath)
return filePath.endsWith(ending)
}
export function basenameNoExt(path: string): string {
path = normalize(path)
const parts = basename(path).split('.')
if (parts.length > 1) {
parts.pop()
}
return parts.join('.')
}
export function isLayoutFileName(f: string): boolean {
f = normalize(f)
return basenameNoExt(f).endsWith('Layout')
}
export function isCellFileName(f: string): boolean {
f = normalize(f)
return basenameNoExt(f).endsWith('Cell')
}
|
1512c5b0ed2e137322589cdb8608b19c63f07179
|
TypeScript
|
AdinoWayne/VuMucDiThu
|
/code/medium/86-partition-list.ts
| 3.6875
| 4
|
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function partition(head: ListNode | null, x: number): ListNode | null {
let ptr = head;
let less = new ListNode();
let greater = new ListNode();
const startPtrOfLess = less;
const startPtrOfGreater = greater;
let basePtr;
let nextPtr;
while(ptr) {
nextPtr = ptr.next;
if (ptr.val < x) {
less.next = ptr;
less = ptr;
} else {
greater.next = ptr;
greater = ptr;
}
ptr.next = null;
ptr = nextPtr;
}
less.next = startPtrOfGreater.next;
return startPtrOfLess.next;
};
|
7de0238fa27ef3410d9d8480752835cdc9df6d8b
|
TypeScript
|
YahorAlve/angular_udemi
|
/observables-start/src/app/user/user.component.ts
| 2.71875
| 3
|
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { UserService } from '../user.service';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
id: number;
constructor(private route: ActivatedRoute, private service: UserService) { }
ngOnInit() {
/* This is an observer (subscriber) and observable is params Data source and it has anonymus function subscribe which
accepts functions as parametrs. And it can accept 3 function : 1 one for working with data comes back, second
for work with an error (error handeling), third one is completion of observable (e.g. http request observable) */
this.route.params
.subscribe(
(params: Params) => {
this.id = +params['id'];
}
);
}
/* As it was mentioned Subject is obsever and observable at the same time and here we are using part of observable
which is genrating some action, and in app module we will use observer part of Subject. In other words it is just another
way to create own observable and looks very similar to EvntEmitter which is actially build on Subject. */
/* Mentor advised that it is a good alternative to EventEmitter and better use the Subject than event listener. */
onActivate() {
this.service.userActivated.next(this.id);
}
}
|
f64905d7ab13e72ab9f1cb351110697a0bd40da6
|
TypeScript
|
albert-team/spiderman
|
/src/modules/dup-filter/dup-filter.interface.ts
| 3.40625
| 3
|
/**
* Duplicate filter
*/
export interface DuplicateFilter<T> {
/**
* Add an item to the filter
*/
add(item: T): void
/**
* Check if an item already exists in the filter
*/
exists(item: T): boolean
}
|
4dc40d36543fd980b435f5b30986c730dd6e0a86
|
TypeScript
|
CS506-Oversight/autorack-front
|
/src/state/ingredient/data.ts
| 3.015625
| 3
|
import {NamedData} from '../base/data';
export enum MeasureType {
VOLUME,
MASS,
}
export type Measure = {
name: string,
type: MeasureType,
// `L` for volume; `g` for mass
equivalentMetric: number,
}
export enum VolumeMeasure {
ML = 'ml',
TBSP = 'tbsp',
CUP = 'cup',
FL_OZ = 'fl. oz',
}
export const volumeMeasureData: { [key in VolumeMeasure]: Measure } = {
[VolumeMeasure.ML]: {
name: VolumeMeasure.ML,
equivalentMetric: 0.001,
type: MeasureType.VOLUME,
},
[VolumeMeasure.TBSP]: {
name: VolumeMeasure.TBSP,
equivalentMetric: 0.0147868,
type: MeasureType.VOLUME,
},
[VolumeMeasure.CUP]: {
name: VolumeMeasure.CUP,
equivalentMetric: 0.236588,
type: MeasureType.VOLUME,
},
[VolumeMeasure.FL_OZ]: {
name: VolumeMeasure.FL_OZ,
equivalentMetric: 0.0295735,
type: MeasureType.VOLUME,
},
};
export enum MassMeasure {
G = 'g',
LB = 'lb',
OZ = 'oz',
}
export const massMeasureData: { [key in MassMeasure]: Measure } = {
[MassMeasure.G]: {
name: MassMeasure.G,
equivalentMetric: 1,
type: MeasureType.MASS,
},
[MassMeasure.LB]: {
name: MassMeasure.LB,
equivalentMetric: 453.592,
type: MeasureType.MASS,
},
[MassMeasure.OZ]: {
name: MassMeasure.OZ,
equivalentMetric: 28.3495,
type: MeasureType.MASS,
},
};
export const measureData: { [key in MassMeasure | VolumeMeasure]: Measure } = {
...volumeMeasureData,
...massMeasureData,
};
export const getMeasureOfSameCategory = (measure: Measure): Array<Measure> => {
if (measure.name in volumeMeasureData) {
return Object.values(volumeMeasureData);
}
if (measure.name in massMeasureData) {
return Object.values(massMeasureData);
}
return [];
};
export const defaultMeasure = measureData.g;
/**
* Ingredient data.
*/
export type Ingredient = NamedData & {
currentStock: number,
measure: Measure,
currentStockEquivalent: number,
capacity: number,
capacityMeasure: Measure,
capacityEquivalent: number,
}
export const ensureIngredientValid = <T extends Ingredient>(ingredient: T): T => {
const newIngredient = {...ingredient};
if (newIngredient.measure.type !== newIngredient.capacityMeasure.type) {
// Ingredient capacity measurement type must = ingredient in-stock measurement type
newIngredient.capacityMeasure = getMeasureOfSameCategory(newIngredient.measure)[0];
}
// Calculate equivalents & check for capacity
const capacityEquivalent = Math.round(
newIngredient.capacity * newIngredient.capacityMeasure.equivalentMetric * 10000,
);
let stockEquivalent = Math.round(
newIngredient.currentStock * newIngredient.measure.equivalentMetric * 10000,
);
stockEquivalent = Math.min(stockEquivalent, capacityEquivalent);
// Update ingredient state
newIngredient.currentStock = stockEquivalent / newIngredient.measure.equivalentMetric / 10000;
newIngredient.currentStockEquivalent = stockEquivalent / 10000;
newIngredient.capacityEquivalent = capacityEquivalent / 10000;
return newIngredient;
};
/**
* ID that means the ingredient is to be newly added.
*/
export const newIngredientId = '(new)';
|
c58853b3303af048ba9852da3224c9ea59826760
|
TypeScript
|
rafaelThi/loan_books_back_end
|
/src/Repositories/TokenUserRepository.ts
| 2.734375
| 3
|
import { EntityRepository, Repository } from 'typeorm';
import TokenUser from '../models/TokenUser';
@EntityRepository(TokenUser)
class UserTokenRepository extends Repository<TokenUser> {
public async findByToken(token: string): Promise<TokenUser | undefined> {
const userToken = await this.findOne({
where: { token },
});
return userToken || undefined;
}
public async generate(id_user: string): Promise<TokenUser> {
const userToken = this.create({
id_user,
});
// criando a instancia da classe, por isso não precisa do await aqui
await this.save(userToken);
// usar o await aqui pq aqui ocorre o salvamento no banco
return userToken;
}
}
export default UserTokenRepository;
|
9f09481b8578e7d01deca4f4e20c1653a0bd6e6c
|
TypeScript
|
prabutdr/typescript-refresh
|
/mapped-types.ts
| 3.328125
| 3
|
type ReadonlyNew<T> = {
readonly [K in keyof T]: T[K] | null;
};
type PartialNew<T> = {
[K in keyof T]?: T[K];
}
interface MappedTypeObj {
name: string,
age: number,
weight?: number
}
type ReadonlyNewMappedTypeObj = ReadonlyNew<MappedTypeObj>;
type PartialNewMappedTypeObj = PartialNew<MappedTypeObj>;
type Nullable<T> = { [P in keyof T]: T[P] | null };
type NullableMappedTypeObj = Nullable<MappedTypeObj>;
// Some part of lib now
type ReadonlyMappedTypeObj = Readonly<MappedTypeObj>;
type ReadonlyPerson = Readonly<Person>;
type PartialMappedTypeObj = Partial<MappedTypeObj>;
// type Required<T> = { [P in keyof T]-?: T[P] };
type RequiredMappedTypeObj = Required<MappedTypeObj>;
// type Pick<T, K extends keyof T> = { [P in K]: T[P] }
type PickMappedTypeObj = Pick<MappedTypeObj, 'age'>;
|
2c30ef08c1a130ec45449a950611d8f1937a1075
|
TypeScript
|
sueddeutsche/editron
|
/src/utils/createProxy.ts
| 2.59375
| 3
|
import { Foxy, Options, handler } from "@technik-sde/foxy";
const defaultOptions = {
handlers: [
handler.unsplash,
handler.image,
handler.video
]
};
export default function createProxy(options: Options|Foxy = {}): Foxy {
if (options.constructor.name === "Foxy") {
return options as Foxy;
}
const o = { ...defaultOptions, ...options };
if (Array.isArray(o.handlers)) {
return new Foxy(o);
}
throw new Error(`Failed initializing proxy from: ${JSON.stringify(options)}`);
}
|
927849963c7bd1d9d869e413c0c248da3b044aed
|
TypeScript
|
lucbories/mathlang
|
/src/tests/unit/vmachine/bitarray.test.ts
| 2.875
| 3
|
/// <reference path="../../../../node_modules/assemblyscript/std/portable/index.d.ts" />
import * as mocha from 'mocha';
import * as chai from 'chai';
const expect = chai.expect;
import BitArray from '../../../vmachine/assemblyscript/assembly/runtime/bitarray';
describe('VM BitArray', () => {
const MEMORY_BYTES:i32 = 3;
it('VM Memory: bits array fill with ones or zeros' , () => {
let i:i32;
const ba1:BitArray = new BitArray(MEMORY_BYTES);
// FILL WITH ONES
ba1.fill_with_ones();
// console.log('fill_with_ones', ba1.to_string());
for(i = 0 ; i < 24 ; i++) {
// console.log('fill_with_ones at [' + i + ']=', ba1.get_at(i) );
expect( ba1.get_at(i) ).is.true;
}
// FILL WITH ZEROS
ba1.fill_with_zeros();
// console.log('fill_with_zeros', ba1.to_string());
for(i = 0 ; i < 24 ; i++) {
// console.log('fill_with_zeros at [' + i + ']=' + (ba1.get_at(i) ? '1' : '0') );
expect( ba1.get_at(i) ).is.false;
}
} );
it('VM Memory: bits array fill at' , () => {
let i:i32;
const ba1:BitArray = new BitArray(MEMORY_BYTES);
// FILL AT
ba1.set_one_at(7);
// console.log('set_one_at(7)', ba1.to_string());
for(i = 0 ; i < 6 ; i++) {
// console.log('set_one_at(7) at [' + i + ']=' + (ba1.get_at(i) ? '1' : '0') );
expect( ba1.get_at(i), 'set_one_at(7):false? at [' + i + ']' ).is.false;
}
// console.log('set_one_at(7) at [6]=' + (ba1.get_at(6) ? '1' : '0') );
expect( ba1.get_at(7) ).is.true;
for(i = 8 ; i < 24 ; i++) {
expect( ba1.get_at(i), 'set_one_at(7):false? at [' + i + ']' ).is.false;
}
} );
it('VM Memory: bits array fill in ranges' , () => {
let i:i32;
const ba1:BitArray = new BitArray(MEMORY_BYTES);
// FILL WITH ONES IN RANGE (0-7)
ba1.fill_with_zeros();
// console.log('fill_with_ones', ba1.to_string());
ba1.set_one_in_range(0, 7);
// console.log('set_one_in_range(0, 7)', ba1.to_string());
for(i = 0 ; i < 24 ; i++) {
if (i >= 0 && i <= 7) {
expect( ba1.get_at(i), 'set_one_in_range(0, 7):true? at [' + i + ']' ).is.true;
} else {
expect( ba1.get_at(i), 'set_one_in_range(0, 7):false? at [' + i + ']' ).is.false;
}
}
// FILL WITH ONES IN RANGE (3-7)
ba1.fill_with_zeros();
// console.log('fill_with_ones', ba1.to_string());
ba1.set_one_in_range(3, 7);
// console.log('set_one_in_range(3, 7)', ba1.to_string());
for(i = 0 ; i < 24 ; i++) {
if (i >= 3 && i <= 7) {
expect( ba1.get_at(i), 'set_one_in_range(3, 7):true? at [' + i + ']' ).is.true;
} else {
expect( ba1.get_at(i), 'set_one_in_range(3, 7):false? at [' + i + ']' ).is.false;
}
}
// FILL WITH ONES IN RANGE (0-11)
ba1.fill_with_zeros();
// console.log('fill_with_ones', ba1.to_string());
ba1.set_one_in_range(0, 11);
// console.log('set_one_in_range(0, 11)', ba1.to_string());
for(i = 0 ; i < 24 ; i++) {
if (i >= 0 && i <= 11) {
expect( ba1.get_at(i), 'set_one_in_range(0, 11):true? at [' + i + ']' ).is.true;
} else {
expect( ba1.get_at(i), 'set_one_in_range(0, 11):false? at [' + i + ']' ).is.false;
}
}
// FILL WITH ONES IN RANGE (7-21)
ba1.fill_with_zeros();
// console.log('fill_with_ones', ba1.to_string());
ba1.set_one_in_range(7, 21);
// console.log('set_one_in_rang(7, 21)', ba1.to_string());
for(i = 0 ; i < 24 ; i++) {
if (i >= 7 && i <= 21) {
expect( ba1.get_at(i), 'set_one_in_rang(7, 21):true? at [' + i + ']' ).is.true;
} else {
expect( ba1.get_at(i), 'set_one_in_rang(7, 21):false? at [' + i + ']' ).is.false;
}
}
// FILL WITH ONES IN RANGE (7-23)
ba1.fill_with_zeros();
// console.log('fill_with_ones', ba1.to_string());
ba1.set_one_in_range(7, 23);
// console.log('set_one_in_rang(7, 23)', ba1.to_string());
for(i = 0 ; i < 24 ; i++) {
if (i >= 7 && i <= 23) {
expect( ba1.get_at(i), 'set_one_in_rang(7, 23):true? at [' + i + ']' ).is.true;
} else {
expect( ba1.get_at(i), 'set_one_in_rang(7, 23):false? at [' + i + ']' ).is.false;
}
}
// FILL WITH ONES IN RANGE (22-23)
ba1.fill_with_zeros();
// console.log('fill_with_ones', ba1.to_string());
ba1.set_one_in_range(22, 23);
// console.log('set_one_in_rang(22, 23)', ba1.to_string());
for(i = 0 ; i < 24 ; i++) {
if (i >= 22 && i <= 23) {
expect( ba1.get_at(i), 'set_one_in_rang(22, 23):true? at [' + i + ']' ).is.true;
} else {
expect( ba1.get_at(i), 'set_one_in_rang(22, 23):false? at [' + i + ']' ).is.false;
}
}
} );
} );
|
f918c42470ca12daa654e2ee8ffba5df91a8693c
|
TypeScript
|
foray1010/Popup-my-Bookmarks
|
/src/popup/components/keyBindings/KeyBindingsContext.ts
| 2.640625
| 3
|
import constate from 'constate'
import * as React from 'react'
import useListener from 'use-typed-event-listener'
import type { WindowId } from '../../constants/windows.js'
import type { KeyBindingEventCallback, KeyDefinition } from './types.js'
function useActiveWindowState() {
const [activeWindowQueue, setActiveWindowQueue] = React.useState<
ReadonlySet<WindowId>
>(new Set())
const appendActiveWindowId = React.useCallback((windowId: WindowId) => {
setActiveWindowQueue((prevState) => {
const newState = new Set(prevState)
newState.add(windowId)
return newState
})
}, [])
const removeActiveWindowId = React.useCallback((windowId: WindowId) => {
setActiveWindowQueue((prevState) => {
const newState = new Set(prevState)
newState.delete(windowId)
return newState
})
}, [])
return {
activeWindowId: Array.from(activeWindowQueue).at(-1),
appendActiveWindowId,
removeActiveWindowId,
}
}
function useKeyBindingsPerWindowState() {
const [keyBindingsPerWindow, setKeyBindingsPerWindow] = React.useState<
ReadonlyMap<
WindowId,
ReadonlyArray<
Readonly<{
key: KeyDefinition
callback: KeyBindingEventCallback
}>
>
>
>(new Map())
type AddOrRemoveListener = (
meta: Readonly<{ key: KeyDefinition; windowId: WindowId }>,
callback: KeyBindingEventCallback,
) => void
const addListener: AddOrRemoveListener = React.useCallback(
({ key, windowId }, callback) => {
setKeyBindingsPerWindow((prevState) => {
const keyBindings = prevState.get(windowId)
const updatedKeyBindings = [...(keyBindings ?? []), { callback, key }]
return new Map(prevState).set(windowId, updatedKeyBindings)
})
},
[],
)
const removeListener: AddOrRemoveListener = React.useCallback(
({ key, windowId }, callback) => {
setKeyBindingsPerWindow((prevState) => {
const keyBindings = prevState.get(windowId)
if (!keyBindings) return prevState
const updatedKeyBindings = keyBindings.filter((keyBinding) => {
return (
keyBinding.callback !== callback ||
keyBinding.key.toString() !== key.toString()
)
})
return new Map(prevState).set(windowId, updatedKeyBindings)
})
},
[],
)
return {
keyBindingsPerWindow,
addListener,
removeListener,
}
}
function useKeyBindingsState() {
const activeWindowState = useActiveWindowState()
const keyBindingsPerWindowState = useKeyBindingsPerWindowState()
return {
...activeWindowState,
...keyBindingsPerWindowState,
}
}
function useKeyBindings() {
const state = useKeyBindingsState()
useListener(document, 'keydown', (evt) => {
const { keyBindingsPerWindow, activeWindowId } = state
if (!activeWindowId) return
const keyBindings = keyBindingsPerWindow.get(activeWindowId)
if (!keyBindings) return
const matchedKeyBindings = keyBindings
.filter((keyBinding) => {
return keyBinding.key instanceof RegExp
? keyBinding.key.test(evt.key)
: keyBinding.key === evt.key
})
.reverse()
matchedKeyBindings.forEach((keyBinding) => {
keyBinding.callback(evt)
})
})
return state
}
export const [KeyBindingsProvider, useKeyBindingsContext] =
constate(useKeyBindings)
|
49374403747f9ac0ed5a08bc464cfef0e850fa47
|
TypeScript
|
arshad-m/angular-basic
|
/src/app/services/basic.service.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
/* if we comment out @Injectable we need to specify under Providers array so that it might be available in all module class
NullInjectorError: No provider for BasicService! */
@Injectable({
// will be availble for all components of applications
// we can provide for particular component as well
providedIn: 'root'
})
export class BasicService {
constructor() { }
serviceCheck(){
console.log("here in service check");
}
}
|
3675016b8c4a28cf380e291b7961da2368ec14e7
|
TypeScript
|
blaart/cloud-sdk-js
|
/packages/openapi-generator/src/parser/parameters.spec.ts
| 2.71875
| 3
|
import { createRefs } from '../../test/test-util';
import {
filterDuplicateParams,
parseParameters,
renameEquallyNamedParams
} from './parameters';
describe('parseParameters', () => {
it('returns empty array if there are no parameters', async () => {
expect(parseParameters({}, await createRefs())).toEqual([]);
});
it('parses inline parameters', async () => {
const anyParamNoSchema = { in: 'query', name: 'anyParamNoSchema' };
const anyParamWithSchema = {
in: 'query',
name: 'anyParamWithSchema',
schema: {}
};
const stringParam = {
in: 'query',
name: 'stringParam',
schema: { type: 'string' }
};
const numberParam = {
in: 'query',
name: 'numberParam',
schema: { type: 'integer' }
};
const enumStringParam = {
in: 'query',
name: 'enumStringParam',
schema: {
type: 'string',
enum: ['value1', 'value2']
}
};
const enumNumberParam = {
in: 'query',
name: 'enumNumberParam',
schema: {
type: 'integer',
enum: [1, 2]
}
};
const enumBooleanParam = {
in: 'query',
name: 'enumBooleanParam',
schema: {
type: 'boolean',
enum: ['true', 'false']
}
};
expect(
parseParameters(
{
parameters: [
anyParamNoSchema,
anyParamWithSchema,
stringParam,
numberParam,
enumStringParam,
enumNumberParam,
enumBooleanParam
]
},
await createRefs()
)
).toStrictEqual([
{ ...anyParamNoSchema, type: 'any' },
{ ...anyParamWithSchema, type: 'any' },
{ ...stringParam, type: 'string' },
{ ...numberParam, type: 'number' },
{ ...enumStringParam, type: "'value1' | 'value2'" },
{ ...enumNumberParam, type: '1 | 2' },
{ ...enumBooleanParam, type: 'boolean' }
]);
});
it('parses referenced parameters', async () => {
const referencedParam = { in: 'query', name: 'referencedParam' };
const parameterSchema = { $ref: '#/components/schemas/parameterSchema' };
const referencedParamWithReferencedSchema = {
in: 'query',
name: 'referencedParamWithReferencedSchema',
schema: parameterSchema
};
expect(
parseParameters(
{
parameters: [
{
$ref: '#/components/parameters/referencedParam'
},
{
$ref:
'#/components/parameters/referencedParamWithReferencedSchema'
}
]
},
await createRefs({
parameters: { referencedParam, referencedParamWithReferencedSchema },
schemas: { parameterSchema }
})
)
).toStrictEqual([
{ ...referencedParam, type: 'any' },
{ ...referencedParamWithReferencedSchema, type: 'any' }
]);
});
});
describe('filterDuplicateParams', () => {
it('removes duplicates from parameters, keeping the last elements only', () => {
const queryParam1 = {
name: 'param1',
in: 'query'
};
const queryParam2 = {
name: 'param2',
in: 'query'
};
const pathParam1 = {
name: 'param1',
in: 'path'
};
const queryParam1Replacement = {
name: 'param1',
in: 'query',
format: 'uuid'
};
expect(
filterDuplicateParams([
queryParam1,
queryParam2,
queryParam1Replacement,
pathParam1
])
).toStrictEqual([queryParam2, queryParam1Replacement, pathParam1]);
});
});
describe('renameEquallyNamedParams', () => {
it('renames parameters', () => {
expect(
renameEquallyNamedParams([
{
name: 'name',
in: 'query'
},
{
name: 'name',
in: 'path'
}
])
).toStrictEqual([
{
name: 'name',
in: 'query'
},
{
name: 'name2',
in: 'path'
}
]);
});
});
|
93d7e3a1a9fccf9933089ae59b5826b91bbe4205
|
TypeScript
|
gabrielvv/ng7-toystore-base
|
/src/app/store/toys/toys.reducer.ts
| 2.921875
| 3
|
import { Action } from "redux";
import { TOY } from './toys.actions'
import { Toy } from '../../models/toy'
import { ActionSequence } from "protractor";
/**
* toysReducer
*
* state :
* { toys: toys array }
*/
export function toysReducer(state : ToyState = defaultToysState, action: any) {
switch(action.type) {
case TOY.GET_TOYS:
return {
...state,
toys: state.toys.length ? state.toys : action.toys
}
case TOY.SELECT_TOY:
return {
...state,
toys: state.toys.map(t => {
if (t.title === action.toy.title) {
t.selected = !t.selected
}
return t
})
}
}
return state;
}
export const defaultToysState : ToyState = {
toys: [],
}
export interface ToyState {
toys: Toy[]
}
|
589c142a51fe5a99a0558cd69b08b399ebb7b00f
|
TypeScript
|
manfredsteyer/2017_08_30
|
/src/app/model/flights/flights.state.ts
| 2.59375
| 3
|
import { Flight } from '../../entities/flight';
export interface FlightsState {
flights: Flight[];
statistics: FlightsStatistics;
}
export interface FlightsStatistics {
countDelayed: number;
countInTime: number;
}
export const initFlightsState: FlightsState = {
flights: [],
statistics: {
countDelayed: 0,
countInTime: 0
}
}
|
06917c89f8b4fa922dd845d4b75efb679cf4ee9c
|
TypeScript
|
Zorbing/node-lgsdk
|
/src/lcd/ffi-lib.ts
| 2.609375
| 3
|
import * as ffi from 'ffi';
import * as ref from 'ref';
import * as ArrayType from 'ref-array';
import * as wchar_t from 'ref-wchar';
import { libPath } from '../path';
import { LOGI_LCD, BITMAP_LENGTH_COLOR, BITMAP_LENGTH_MONO } from './constants';
const byte = ref.types.uchar;
const byteArray = ArrayType<number>(byte);
const wchar_string = wchar_t.string;
interface LcdLib
{
LogiLcdInit: Function;
LogiLcdIsConnected: Function;
LogiLcdIsButtonPressed: Function;
LogiLcdUpdate: Function;
LogiLcdShutdown: Function;
// Monochrome LCD functions
LogiLcdMonoSetBackground: Function;
LogiLcdMonoSetText: Function;
// Color LCD functions
LogiLcdColorSetBackground: Function;
LogiLcdColorSetTitle: Function;
LogiLcdColorSetText: Function;
}
export const lcdLib: LcdLib = ffi.Library(libPath('lcd'), {
'LogiLcdInit': ['bool', [wchar_string /*friendlyName*/, 'int' /*lcdType*/]],
'LogiLcdIsConnected': ['bool', ['int' /*lcdType*/]],
'LogiLcdIsButtonPressed': ['bool', ['int' /*button*/]],
'LogiLcdUpdate': ['void', []],
'LogiLcdShutdown': ['void', []],
// Monochrome LCD functions
'LogiLcdMonoSetBackground': ['bool', [byteArray /*monoBitmap[]*/]],
'LogiLcdMonoSetText': ['bool', ['int' /*lineNumber*/, wchar_string /*text*/]],
// Color LCD functions
'LogiLcdColorSetBackground': ['bool', [byteArray /*colorBitmap[]*/]],
'LogiLcdColorSetTitle': ['bool', [wchar_string /*text*/, 'int' /*red = 255*/, 'int' /*green = 255*/, 'int' /*blue = 255*/]],
'LogiLcdColorSetText': ['bool', ['int' /*lineNumber*/, wchar_string /*text*/, 'int' /*red = 255*/, 'int' /*green = 255*/, 'int' /*blue = 255*/]],
});
export function isButtonValid(button: number)
{
return isButtonValidForColor(button) || isButtonValidForMono(button);
}
export function isButtonValidForMono(button: number)
{
return button === LOGI_LCD.mono.buttons['0']
|| button === LOGI_LCD.mono.buttons['1']
|| button === LOGI_LCD.mono.buttons['2']
|| button === LOGI_LCD.mono.buttons['3']
;
}
export function isButtonValidForColor(button: number)
{
return button === LOGI_LCD.color.buttons['left']
|| button === LOGI_LCD.color.buttons['right']
|| button === LOGI_LCD.color.buttons['ok']
|| button === LOGI_LCD.color.buttons['cancel']
|| button === LOGI_LCD.color.buttons['up']
|| button === LOGI_LCD.color.buttons['down']
|| button === LOGI_LCD.color.buttons['menu']
;
}
export function isValidColorBitmapLength(bitmap: number[])
{
return bitmap.length === BITMAP_LENGTH_COLOR;
}
export function isValidMonoBitmapLength(bitmap: number[])
{
return bitmap.length === BITMAP_LENGTH_MONO;
}
export function isValidBitmapValues(bitmap: number[])
{
return bitmap.every((byte) => (byte & 255) === byte);
}
|
142b06f5141e08399c1ec4d78f792ae1704487d6
|
TypeScript
|
zmoog/dickbott
|
/scripts/dialogflow/FulfillmentHandler.ts
| 2.546875
| 3
|
import { FulfillmentRequest, FulfillmentResponse } from "../dialogflow/Types";
import { IntentDispatcher } from "../core/dispatcher/IntentDispatcher";
import { inject, injectable } from "inversify";
import { assignIn } from "lodash";
@injectable()
export class FulfillmentHandler {
constructor( @inject("IntentDispatcher") private intentDispatcher: IntentDispatcher) { }
async handle(event: FulfillmentRequest): Promise<FulfillmentResponse> {
if (!event.result.metadata.intentName) {
console.log("No intent specified.");
return {};
}
try {
let intentName = event.result.metadata.intentName;
let entities = assignIn({}, event.result.parameters);
entities.originalRequest = event.originalRequest;
let slackMessage = await this.intentDispatcher.dispatch<any, any>(
intentName,
entities);
let fulfillmentResponse = {
speech: slackMessage.text,
displayText: slackMessage.text,
data: {
slack: slackMessage
}
};
return fulfillmentResponse;
} catch (error) {
console.error(error);
console.log("FulfillmentHandler: event %j", event);
return {
speech: `D'oh! Something went wrong (${error}).`,
displayText: `D'oh! Something went wrong (${error}).`
};
}
}
}
|
418c14680cd4c697dec8c064c793a7472f9ffb9f
|
TypeScript
|
IflameI/react-spotify-clone
|
/src/redux/actions/browse.ts
| 2.671875
| 3
|
import { Dispatch } from 'redux';
import { browseActionType, browseActions } from '../../types/browse';
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
export const setLoaded = (payload: boolean): browseActions => {
return {
type: browseActionType.SET_LOADED,
payload,
};
};
export const fetchBrowseSuccess = (browse: any): browseActions => {
return {
type: browseActionType.FETCH_BROWSE_SUCCESS,
browse,
};
};
export const fetchBrowseError = (): browseActions => {
return {
type: browseActionType.FETCH_BROWSE_ERROR,
};
};
export const fetchBrowse = (accessToken: string) => (dispatch: Dispatch<browseActions>) => {
const request = new Request('https://api.spotify.com/v1/browse/featured-playlists', {
headers: new Headers({
Authorization: 'Bearer ' + accessToken,
}),
});
fetch(request)
.then((res) => {
return res.json();
})
.then((res) => {
dispatch(fetchBrowseSuccess(res.playlists));
})
.catch((err) => {
dispatch(fetchBrowseError());
});
};
|
ec8c4392461ee9a8c5a98139444b216f131a889c
|
TypeScript
|
BitskiCo/bitski-node
|
/tests/provider-manager.test.ts
| 2.609375
| 3
|
import { ProviderManager } from '../src/index';
test('it successfully creates a provider', () => {
expect.assertions(2);
const manager = new ProviderManager('foo', 'bar');
const provider = manager.getProvider({networkName: 'rinkeby', disableBlockTracking: true});
expect(provider).toBeDefined();
expect(provider.clientId).toBe('foo');
});
test('it can pass additional headers', () => {
expect.assertions(2);
const manager = new ProviderManager('foo', 'bar');
const provider = manager.getProvider({networkName: 'rinkeby', disableBlockTracking: true, additionalHeaders: { 'x-foo': 'bar' }});
expect(provider).toBeDefined();
// @ts-ignore
expect(provider.headers['x-foo']).toBe('bar');
});
test('it returns a provider from the cache when one exists', () => {
expect.assertions(2);
const manager = new ProviderManager('foo', 'bar');
const dummyProvider = {};
// @ts-ignore
manager.cachedProviders.set('"rinkeby"', dummyProvider);
const provider = manager.getProvider({networkName: 'rinkeby', disableBlockTracking: true});
expect(provider).toBeDefined();
expect(provider).toBe(dummyProvider);
});
|
767558254698de218e61c4c6c059d68977139eee
|
TypeScript
|
pocketfi/web
|
/src/reducers/transactionReducer.ts
| 2.5625
| 3
|
import {
FOUND_TRANSACTIONS,
FOUND_TRANSACTIONS_BY_CATEGORY,
PLACES_RECEIVED,
REQUEST_ERROR,
TRANSACTION_CREATED,
TRANSACTION_DELETED,
TRANSACTION_FAIL,
TRANSACTION_MESSAGE,
TRANSACTION_SUCCESS,
TRANSACTION_UPDATED,
TransactionActionTypes,
TRANSACTIONS_RECEIVED
} from '../actions/types/TransactionActionTypes'
import {Transaction} from '../types/Transaction'
export interface TransactionReducerState {
transactions: Transaction[]
foundTransactions: Transaction[] | null
transactionsFoundByCategory: Transaction[]
err: any
places: string[]
}
const initialState = {
transactions: [],
foundTransactions: null,
transactionsFoundByCategory: [],
err: '',
places: []
}
export default (state: TransactionReducerState = initialState, action: TransactionActionTypes) => {
switch (action.type) {
case TRANSACTION_SUCCESS:
return {
...state
}
case TRANSACTION_FAIL:
return {
...state
}
case TRANSACTIONS_RECEIVED:
return {
...state,
transactions: action.transactions
}
case TRANSACTION_CREATED:
return {
...state,
transactions: [...state.transactions, action.transaction]
}
case TRANSACTION_UPDATED:
return {
...state,
transactions: state.transactions.map((transaction: Transaction) =>
transaction.id === action.transaction.id ? action.transaction : transaction
)
}
case TRANSACTION_DELETED:
return {
...state,
transactions: state.transactions.filter((transaction) => action.transaction.id !== transaction.id)
}
case FOUND_TRANSACTIONS:
return {
...state,
foundTransactions: action.transactions,
}
case FOUND_TRANSACTIONS_BY_CATEGORY:
return {
...state,
transactionsFoundByCategory: action.transactions,
}
case TRANSACTION_MESSAGE:
return {
...state,
msg: action.msg
}
case PLACES_RECEIVED:
return {
...state,
places: action.places
}
case REQUEST_ERROR:
return {
...state,
err: action.err
}
default:
return state
}
}
|
17ddb119945966f5f0d1451c4530c01491013093
|
TypeScript
|
ShravikaReddyPollapalli/capstone
|
/six.ts
| 3.65625
| 4
|
class Test {
color: string;
constructor(color:string){
this.color = color;
}
display():void {
console.log(this.color);
}
}
class Test1 extends Test {
price : number;
constructor(price:number,color:string){
super(color);
this.price = price;
}
display(): void {
console.log(this.price);
super.display();
}
}
let obj1 = new Test1(1000,"red");
obj1.display();
|
8a8ddf06a50de8398bd678ab3e6ea34b5701117b
|
TypeScript
|
thinceller/channel-name-list
|
/src/app/modules/ChannelModule.ts
| 2.53125
| 3
|
import Axios from 'axios';
import { Action, Dispatch } from 'redux';
import { ThunkDispatch } from 'redux-thunk';
import { db } from '../firebase';
import FluxAction, { MyThunkDispatch } from './FluxAction';
import { Channel } from '../models';
import config from '../config';
import { State, uiModule } from '../modules';
export type ChannelModuleState = {
channels: Channel[],
editingChannel: Channel,
};
class ChannelModule {
// ===========================================================================
// action types
// ===========================================================================
actionType = {
getAllChannels: 'GET_ALL_CHANNELS',
createNewChannel: 'CREATE_NEW_CHANNEL',
fetchChannelData: 'UPDATE_CHANNEL_DATA',
updateChannelData: 'UPDATE_CHANNEL_DATA',
setEditingChannel: 'SET_EDITING_CHANNEL',
updateEditingChannel: 'UPDATE_EDITING_CHANNEL',
};
// ===========================================================================
// initial state
// ===========================================================================
state: ChannelModuleState = {
channels: [],
editingChannel: Channel.createEmpty(),
};
// ===========================================================================
// action creators
// ===========================================================================
getAllChannels = () => (dispatch: Dispatch<Action>, getState: () => State) => {
const promise: Promise<Channel[]> = new Promise((resolve, reject) => {
if (getState().channel.channels.length !== 0) { resolve(); }
db.collection('channels')
.get()
.then(res => {
let channels: Channel[] = [];
res.forEach(doc => {
const document = doc.data();
const channel = Channel.createEmpty();
channel.id = document.id;
channel.number = document.number | 0;
channel.image = document.image || '';
channel.name = document.name || '';
channel.liverName = document.liverName || '';
channel.liverPhonetic = document.liverPhonetic || '';
channels = channels.concat(channel);
});
// .orderByでソートするとnumberが0のドキュメントを除外して取得してしまうので
// JSで直接ソートアルゴリズムを挟んでる
channels.sort((a, b) => a.number - b.number);
dispatch(FluxAction.createPlaneSuccess(
this.actionType.getAllChannels,
{ channels },
));
resolve(channels);
})
.catch(err => reject(err));
});
return promise;
}
createNewChannel = (id: string) => (dispatch: MyThunkDispatch) => {
dispatch(uiModule.toggleLoading());
const promise: Promise<Channel> = new Promise((resolve, reject) => {
db.collection('channels')
.doc(id)
.set({ id })
.then(() => {
const newChannel = Channel.createEmpty();
newChannel.id = id;
dispatch(FluxAction.createPlaneSuccess(
this.actionType.createNewChannel,
{ channel: newChannel },
));
dispatch(uiModule.toggleLoading());
resolve(newChannel);
})
.catch(err => {
dispatch(uiModule.toggleLoading());
reject(err);
});
});
return promise;
}
fetchChannelData = (
channel: Channel,
) => (
dispatch: MyThunkDispatch,
) => {
const promise: Promise<void> = new Promise(async (resolve, reject) => {
const url = `${config.lambdaEndpoint}?id=${channel.id}`;
const res = await Axios.get(url, { headers: { 'Content-Type': 'application/json' } });
const clonedChannel = channel.clone();
clonedChannel.name = res.data.body.channelTitle;
clonedChannel.image = res.data.body.image;
dispatch(FluxAction.createPlaneSuccess(
this.actionType.fetchChannelData,
{ channel: clonedChannel },
));
const channelRef = db.collection('channels').doc(channel.id);
channelRef
.update({
name: clonedChannel.name,
image: clonedChannel.image,
})
.then(() => {
resolve();
})
.catch(err => {
console.error(err);
reject(err);
});
});
return promise;
}
updateChannelData = () => (
dispatch: ThunkDispatch<State, undefined, Action>,
getState: () => State,
) => {
dispatch(uiModule.toggleLoading());
const promise = new Promise((resolve, reject) => {
const channel = getState().channel.editingChannel;
dispatch(FluxAction.createPlaneSuccess(
this.actionType.updateChannelData,
{ channel },
));
const channelRef = db.collection('channels').doc(channel.id);
channelRef
.update({
id: channel.id,
number: channel.number,
liverName: channel.liverName,
liverPhonetic: channel.liverPhonetic,
})
.then(() => {
dispatch(uiModule.toggleLoading());
resolve();
})
.catch(err => {
console.error(err);
dispatch(uiModule.toggleLoading());
reject(err);
});
});
return promise;
}
setEditingChannel = (
channel: Channel | null,
) => (
dispatch: Dispatch<Action>,
) => {
const promise = new Promise((resolve) => {
dispatch(FluxAction.createPlaneSuccess(
this.actionType.setEditingChannel,
{ editingChannel: channel },
));
resolve();
});
return promise;
}
updateEditingChannel = (channel: Channel) => (dispatch: Dispatch<Action>) => {
const promise = new Promise((resolve) => {
dispatch(FluxAction.createPlaneSuccess(
this.actionType.updateEditingChannel,
{ editingChannel: channel },
));
resolve();
});
return promise;
}
// ===========================================================================
// reducer
// ===========================================================================
reducer = (state: ChannelModuleState = this.state, action: FluxAction): ChannelModuleState => {
switch (action.type) {
case this.actionType.getAllChannels:
case this.actionType.setEditingChannel:
case this.actionType.updateEditingChannel:
return Object.assign({}, state, action.payload);
case this.actionType.createNewChannel:
case this.actionType.fetchChannelData:
case this.actionType.updateChannelData:
return Object.assign(
{},
state,
{
channels: replaceChannel(state.channels, action.payload.channel),
},
);
default:
return state;
}
}
}
function replaceChannel(stateChannels: Channel[], updatedChannel: Channel) {
const updatedChannels = stateChannels.slice();
const updatedChannelIndex = updatedChannels.findIndex(channel => {
return channel.id === updatedChannel.id;
});
if (updatedChannelIndex > -1) {
updatedChannels.splice(updatedChannelIndex, 1, updatedChannel);
} else {
updatedChannels.push(updatedChannel);
}
return updatedChannels;
}
export default new ChannelModule();
|
6e1c4daba935208104461ef8e38117005978f81f
|
TypeScript
|
soumyo123-prog/angular-intro
|
/src/app/components/recipie/recipie.model.ts
| 2.890625
| 3
|
export class Recipie {
name: string;
description: string;
imageUrl: string;
constructor(name: string, description: string, imageUrl: string) {
this.name = name;
this.description = description;
this.imageUrl = imageUrl;
}
}
|
02f59798dfc355b5f3c9425a65b7e05bb3ec51bf
|
TypeScript
|
pspeter3/ethereal-vtt
|
/src/core/VirtualTableTop.ts
| 2.625
| 3
|
import { Application, Graphics } from "pixi.js";
import { Viewport } from "pixi-viewport";
/**
* VirtualTableTop contains the logic for the virtual table top.
*/
export class VirtualTableTop {
private app: Application;
private viewport: Viewport;
/**
* Construct the VirtualTableTop.
* @param container The HTMLElement that contains the application.
*/
constructor(container: HTMLElement) {
this.app = new Application({ resizeTo: window });
container.appendChild(this.app.view);
const worldWidth = 2048;
const worldHeight = 2048;
this.viewport = new Viewport({
screenWidth: window.innerWidth,
screenHeight: window.innerHeight,
worldWidth,
worldHeight,
interaction: this.app.renderer.plugins.interaction,
});
this.app.stage.addChild(this.viewport);
this.viewport
.drag()
.pinch()
.wheel()
.clampZoom({ minScale: 0.25, maxScale: 1 });
const graphics = new Graphics();
graphics.beginFill(0xeceff4);
graphics.drawRect(0, 0, worldWidth, worldHeight);
graphics.endFill();
graphics.lineStyle(4, 0xd8dee9);
const cell = 64;
for (let i = 0; i <= worldWidth; i += cell) {
graphics.moveTo(i, 0);
graphics.lineTo(i, worldHeight);
graphics.moveTo(0, i);
graphics.lineTo(worldWidth, i);
}
graphics.closePath();
graphics.cacheAsBitmap;
this.viewport.addChild(graphics);
window.addEventListener("resize", this.onResize);
}
/**
* Destroys the application.
*/
destroy(): void {
this.app.destroy();
window.removeEventListener("resize", this.onResize);
}
private onResize = () => {
this.viewport.resize(window.innerWidth, window.innerHeight);
};
}
|
a302e5c8d1633b5d22dd6e1bc78129e426db6536
|
TypeScript
|
nguyer/aws-sdk-js-v3
|
/clients/browser/client-dynamodb-browser/types/_GlobalSecondaryIndexInfo.ts
| 2.796875
| 3
|
import {
_KeySchemaElement,
_UnmarshalledKeySchemaElement
} from "./_KeySchemaElement";
import { _Projection, _UnmarshalledProjection } from "./_Projection";
import {
_ProvisionedThroughput,
_UnmarshalledProvisionedThroughput
} from "./_ProvisionedThroughput";
/**
* <p>Represents the properties of a global secondary index for the table when the backup was created.</p>
*/
export interface _GlobalSecondaryIndexInfo {
/**
* <p>The name of the global secondary index.</p>
*/
IndexName?: string;
/**
* <p>The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> <note> <p>The partition key of an item is also known as its <i>hash attribute</i>. The term "hash attribute" derives from DynamoDB' usage of an internal hash function to evenly distribute data items across partitions, based on their partition key values.</p> <p>The sort key of an item is also known as its <i>range attribute</i>. The term "range attribute" derives from the way DynamoDB stores items with the same partition key physically close together, in sorted order by the sort key value.</p> </note>
*/
KeySchema?: Array<_KeySchemaElement> | Iterable<_KeySchemaElement>;
/**
* <p>Represents attributes that are copied (projected) from the table into the global secondary index. These are in addition to the primary key attributes and index key attributes, which are automatically projected. </p>
*/
Projection?: _Projection;
/**
* <p>Represents the provisioned throughput settings for the specified global secondary index. </p>
*/
ProvisionedThroughput?: _ProvisionedThroughput;
}
export interface _UnmarshalledGlobalSecondaryIndexInfo
extends _GlobalSecondaryIndexInfo {
/**
* <p>The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> <note> <p>The partition key of an item is also known as its <i>hash attribute</i>. The term "hash attribute" derives from DynamoDB' usage of an internal hash function to evenly distribute data items across partitions, based on their partition key values.</p> <p>The sort key of an item is also known as its <i>range attribute</i>. The term "range attribute" derives from the way DynamoDB stores items with the same partition key physically close together, in sorted order by the sort key value.</p> </note>
*/
KeySchema?: Array<_UnmarshalledKeySchemaElement>;
/**
* <p>Represents attributes that are copied (projected) from the table into the global secondary index. These are in addition to the primary key attributes and index key attributes, which are automatically projected. </p>
*/
Projection?: _UnmarshalledProjection;
/**
* <p>Represents the provisioned throughput settings for the specified global secondary index. </p>
*/
ProvisionedThroughput?: _UnmarshalledProvisionedThroughput;
}
|
958c0cc7d1885c4bfb75711848bd242de820744a
|
TypeScript
|
chrisnrick/botbuilder-js
|
/libraries/botbuilder-dialogs-adaptive/src/input/confirmInput.ts
| 2.609375
| 3
|
/**
* @module botbuilder-dialogs-adaptive
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import * as Recognizers from '@microsoft/recognizers-text-choice';
import { Activity } from 'botbuilder-core';
import { DialogContext, Choice, ListStyle, ChoiceFactoryOptions, ChoiceFactory, recognizeChoices } from 'botbuilder-dialogs';
import { InputDialog, InputState } from './inputDialog';
import { ChoiceSet } from './choiceSet';
import { StringExpression, ObjectExpression, ArrayExpression, EnumExpression } from 'adaptive-expressions';
export class ConfirmInput extends InputDialog {
/**
* Default options for rendering the choices to the user based on locale.
*/
private static defaultChoiceOptions: { [locale: string]: { choices: (string | Choice)[], options: ChoiceFactoryOptions } } = {
'es-es': { choices: ['Sí', 'No'], options: { inlineSeparator: ', ', inlineOr: ' o ', inlineOrMore: ', o ', includeNumbers: true } },
'nl-nl': { choices: ['Ja', 'Nee'], options: { inlineSeparator: ', ', inlineOr: ' of ', inlineOrMore: ', of ', includeNumbers: true } },
'en-us': { choices: ['Yes', 'No'], options: { inlineSeparator: ', ', inlineOr: ' or ', inlineOrMore: ', or ', includeNumbers: true } },
'fr-fr': { choices: ['Oui', 'Non'], options: { inlineSeparator: ', ', inlineOr: ' ou ', inlineOrMore: ', ou ', includeNumbers: true } },
'de-de': { choices: ['Ja', 'Nein'], options: { inlineSeparator: ', ', inlineOr: ' oder ', inlineOrMore: ', oder ', includeNumbers: true } },
'ja-jp': { choices: ['はい', 'いいえ'], options: { inlineSeparator: '、 ', inlineOr: ' または ', inlineOrMore: '、 または ', includeNumbers: true } },
'pt-br': { choices: ['Sim', 'Não'], options: { inlineSeparator: ', ', inlineOr: ' ou ', inlineOrMore: ', ou ', includeNumbers: true } },
'zh-cn': { choices: ['是的', '不'], options: { inlineSeparator: ', ', inlineOr: ' 要么 ', inlineOrMore: ', 要么 ', includeNumbers: true } }
};
/**
* The prompts default locale that should be recognized.
*/
public defaultLocale?: StringExpression;
/**
* Style of the "yes" and "no" choices rendered to the user when prompting.
*
* @remarks
* Defaults to `ListStyle.auto`.
*/
public style: EnumExpression<ListStyle> = new EnumExpression<ListStyle>(ListStyle.auto);
/**
* Additional options passed to the `ChoiceFactory` and used to tweak the style of choices
* rendered to the user.
*/
public choiceOptions?: ObjectExpression<ChoiceFactoryOptions> = new ObjectExpression();
/**
* Custom list of choices to send for the prompt.
*/
public confirmChoices?: ObjectExpression<ChoiceSet>;
/**
* The expression of output format.
*/
public outputFormat: StringExpression;
protected onComputeId(): string {
return `ConfirmInput[${ this.prompt && this.prompt.toString() }]`;
}
protected async onRecognizeInput(dc: DialogContext): Promise<InputState> {
// Recognize input if needed
let input: any = dc.state.getValue(InputDialog.VALUE_PROPERTY);
if (typeof input !== 'boolean') {
// Find locale to use
const activity: Activity = dc.context.activity;
const locale = activity.locale || this.defaultLocale.getValue(dc.state) || 'en-us';
// Recognize input
const results: any = Recognizers.recognizeBoolean(input, locale);
if (results.length > 0 && results[0].resolution) {
input = results[0].resolution.value;
dc.state.setValue(InputDialog.VALUE_PROPERTY, !!input);
if (this.outputFormat) {
const value = this.outputFormat.getValue(dc.state);
dc.state.setValue(InputDialog.VALUE_PROPERTY, value);
}
return InputState.valid;
} else {
// Fallback to trying the choice recognizer
const confirmChoices = (this.confirmChoices && this.confirmChoices.getValue(dc.state)) || ConfirmInput.defaultChoiceOptions[locale].choices;
const choices = ChoiceFactory.toChoices(confirmChoices);
const results = recognizeChoices(input, choices);
if (results.length > 0) {
input = results[0].resolution.index == 0;
dc.state.setValue(InputDialog.VALUE_PROPERTY, input);
} else {
return InputState.unrecognized;
}
}
}
return InputState.valid;
}
protected async onRenderPrompt(dc: DialogContext, state: InputState): Promise<Partial<Activity>> {
// Determine locale
let locale: string = dc.context.activity.locale || this.defaultLocale.getValue(dc.state);
if (!locale || !ConfirmInput.defaultChoiceOptions.hasOwnProperty(locale)) {
locale = 'en-us';
}
locale = locale.toLowerCase(); // to match format 'en-US'
// Format choices
const confirmChoices = (this.confirmChoices && this.confirmChoices.getValue(dc.state)) || ConfirmInput.defaultChoiceOptions[locale].choices;
const choices = ChoiceFactory.toChoices(confirmChoices);
// Format prompt to send
const prompt = await super.onRenderPrompt(dc, state);
const channelId: string = dc.context.activity.channelId;
const choiceOptions: ChoiceFactoryOptions = (this.choiceOptions && this.choiceOptions.getValue(dc.state)) || ConfirmInput.defaultChoiceOptions[locale].options;
const style = this.style.getValue(dc.state)
return Promise.resolve(this.appendChoices(prompt, channelId, choices, style, choiceOptions));
}
}
|
de41b477663472cffb16007db143913d68f53433
|
TypeScript
|
rakesh4ui347/TYPESCRIPT
|
/08_ES6_Destructing/08_app.ts
| 4.09375
| 4
|
/*
---------------------------------------------------------------------------------
6. Destructing
---------------------------------------------------------------------------------
This is one of the powerful feature in ES6, where in instead of adding a single value
to a variable from an array, we can do it all by once.
*/
// Usage of Destructing to assign each variable of an array to other vars
let student:Array<any> = ['Rajan',25,'Engineering'];
let [ stdName , stdAge , stdCourse] = student;
console.log(`Name : ${stdName} Age : ${stdAge} Course : ${stdCourse}`);
// Usage of Destructing to exchange the values of two vars
let a = 10;
let b = 20;
[b , a] = [a , b];
console.log(`a : ${a} b : ${b}`);
// Usage of Destructing to assign each variable of an Object to other vars
let employee = {
eName : 'John',
age : 35,
desg : 'Manager'
};
// Normal way
//let empName = employee.eName;
//let empAge = employee.age;
//let empDesg = employee.desg;
// Destructing
let {eName:empName , age:empAge , desg:empDesg } = employee;
console.log(` Name : ${empName} Age: ${empAge} Desg: ${empDesg}`);
|
3553dde3c74ef4b620a10bdb51caf50600b6e583
|
TypeScript
|
andreslopezma/Spotify-App-Angular
|
/src/app/services/spotify.service.ts
| 2.5625
| 3
|
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
// el HttpClient nos deja hacer peticiones por htpp
// HttpHeaders nos permite modificar los Headres de la peticion
import { HttpClient, HttpHeaders, HttpHeaderResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class SpotifyService {
constructor( private http: HttpClient ) {
console.log('Servicio listo para usar');
}
getQuery( query: string ) {
// aca podemos modificar y agregar los headers que necesita la api de spotify
const headers = new HttpHeaders({
'Authorization' : 'Bearer BQCsO6p-ALi08QNBIr7ihH4b5o85F9dfBFZF0M5UB08GMbiatgMpkWK-wLyKSglwVzu6Fs0q1xcLtXkRApE'
});
const url = `https://api.spotify.com/v1/${query}`;
return this.http.get(url, { headers });
}
getNewReleases() {
return this.getQuery('browse/new-releases')
.pipe( map ( ( data: any ) => {
return data.albums.items;
} ) );
}
getArtistas(termino: string) {
// la funcion map sire para poder modelar los datos y que en el componente se puede leer los datos de una forma mucho mas limpia
return this.getQuery(`search?q=${ termino }&type=artist&limit=20`)
.pipe ( map ( ( data: any ) => {
return data.artists.items;
} ) );
}
getArtista(id: string) {
// la funcion map sire para poder modelar los datos y que en el componente se puede leer los datos de una forma mucho mas limpia
return this.getQuery(`artists/${ id }`)
.pipe ( map ( ( data: any ) => {
return data;
} ) );
}
gettopTracks(id: string) {
// la funcion map sire para poder modelar los datos y que en el componente se puede leer los datos de una forma mucho mas limpia
return this.getQuery(`artists/${ id }/top-tracks?country=us`)
.pipe ( map ( ( data: any ) => {
return data.tracks;
} ) );
}
}
|
ddaeda098d70df63033d81dc7a0d8556ce10632d
|
TypeScript
|
InmediaGR/vue3-tailwind2
|
/src/composable/useSize.ts
| 2.671875
| 3
|
import { computed, ref } from 'vue'
export type ISize = "xs" | "sm" | "md" | "lg"
const useSize = (props: { size: ISize, full: boolean, circle: boolean }) => {
let sizes = {
xs: 'h-4 w-8 text-sm',
sm: 'px-3 h-6 ',
md: 'px-4 h-8 ',
lg: 'px-8 h-12 text-xl',
full: " w-full",
}
let circleBtnSizes = {
xs: 'h-4 w-4',
sm: 'h-6 h-6 ',
md: 'h-8 w-8 ',
lg: 'h-12 w-12',
}
const classes = computed(() => props.full ? sizes[props.size || 'md']+' w-full' : ` ${sizes[props.size || 'md']} ${props.circle ? circleBtnSizes[props.size || 'md'] + ' rounded-full' : ''}`)
return { classes }
}
export default useSize;
|
530637135ffb445fa4f5295dc3df0ec3e454cc47
|
TypeScript
|
medusajs/medusa
|
/packages/admin-ui/src/node/utils/validate-args.ts
| 2.59375
| 3
|
import { CustomWebpackConfigArgs } from "../types"
import { logger } from "./logger"
function validateArgs(args: CustomWebpackConfigArgs) {
const { options } = args
if (options.path) {
if (!options.path.startsWith("/")) {
logger.panic(
"'path' in the options of `@medusajs/admin` must start with a '/'"
)
}
if (options.path !== "/" && options.path.endsWith("/")) {
logger.panic(
"'path' in the options of `@medusajs/admin` cannot end with a '/'"
)
}
if (typeof options.path !== "string") {
logger.panic(
"'path' in the options of `@medusajs/admin` must be a string"
)
}
}
}
export { validateArgs }
|
fb595b7bf9dadd95afc739ee4aa19dc8ecce2e2e
|
TypeScript
|
slipkinem/jsTest
|
/validator/validator.ts
| 2.671875
| 3
|
/**
* Created by slipkinem on 1/22/2018 at 2:46 PM.
* Copyright © 2016, PuKang Health Maintenance Co.
*/
window.onload = main
// window.validate = {}
const assert = (condition: boolean, message: string) => {
if (!condition) {
console.error('[data-validator]' + message)
}
}
const $ = (el: string) => document.querySelector(el)
const addClass = (el: Element, className: string) => {
if (el.className.indexOf(className) === -1) {
el.className = el.className + ' ' + className
}
}
const removeClass = (el: Element, className: string) => {
if (el.className.indexOf(className) === -1) return
let cls = el.className.split(' ')
cls.splice(cls.indexOf(className), 1)
el.className = cls.join(' ')
}
function main () {
let lsData = {
username: '',
password: '',
rePassword: '',
email: '',
tel: ''
}
let rules = {
username: {
required: true
}
}
let $validate = document.querySelectorAll('[data-validate]')[0]
let $validateItems = $validate.querySelectorAll('[data-prop]')
;[].map.call($validateItems, (item) => {
let prop = item.getAttribute('data-prop')
let $input: HTMLInputElement = item.getElementsByTagName('input')[0]
let $content = item.getElementsByClassName('ls-form-item__content')[0]
$input.addEventListener('blur', () => {
let $message = document.createElement('div')
$message.className = 'ls-form-item__message'
if (rules[prop] && rules[prop].required) {
if ($input.value === '') {
$message.innerText = rules[prop].message || `${prop} is required`
$content.appendChild($message)
item.className = item.className + ' ' + 'error'
} else {
$content.lastChild.style.display = 'none'
removeClass(item, 'error')
addClass(item, 'success')
}
}
})
})
}
// class validator {
// data: any
// rules: object[]
//
// constructor (data: any) {
// this.data = data
// this.setValidate()
// }
//
// setValidate () {
//
// }
//
//
// }
|
d0d9dc283ac1e77a8269c762cfd30f6a5c9bc123
|
TypeScript
|
Zubs/TypeScriptIntro
|
/docs/src/classes/invoice.ts
| 3
| 3
|
// Import Interface
import { HasFormatter } from "../interfaces/hasFormatter.js"
// Create the Invoice class
export class Invoice implements HasFormatter {
// Map properties to inputs
constructor(private client: string, private details: string, private amount: number) {}
format (): string {
return `${ this.client } owes ₦${ this.amount } for ${ this.details }`;
}
}
|
e7ad13465caaa8e16dcabbdf9d36360b381b7c66
|
TypeScript
|
leonmaks/module5_homework
|
/src/task_04.ts
| 3.3125
| 3
|
// Задание 4
// Записать в переменную случайное целое число в диапазоне [0; 100]. Используйте объект Math.
const task_04 = () => {
const randInt = (max: number): number => (
Math.floor(Math.random() * max)
)
console.log(randInt(100))
console.log(randInt(100))
console.log(randInt(100))
console.log(randInt(100))
console.log(randInt(100))
console.log(randInt(100))
console.log(randInt(100))
console.log(randInt(100))
console.log(randInt(100))
console.log(randInt(100))
}
task_04()
|
afd42f988d7034ac3a74c0812cfd4c960ec732c8
|
TypeScript
|
nancyyhong/IxJS
|
/src/iterable/pipe/takelast.ts
| 2.609375
| 3
|
import { MonoTypeOperatorFunction } from '../../interfaces';
import { IterableX } from '../../iterable/iterablex';
import { TakeLastIterable } from '../takelast';
export function takeLast<TSource>(count: number): MonoTypeOperatorFunction<TSource> {
return function takeLastOperatorFunction(source: Iterable<TSource>): IterableX<TSource> {
return new TakeLastIterable<TSource>(source, count);
};
}
|
9d58294f008bef5fdd83400a44493f63b5eeb18c
|
TypeScript
|
project-MyTin/Back-end_IceBear
|
/src/data/usecases/db-add-routine.ts
| 2.71875
| 3
|
import { AddRoutine } from "../../domain/usecases";
import { AddRoutineRepository, LoadMotionRepository } from "../protocols/repository";
export class DbAddRoutine implements AddRoutine {
constructor(
private readonly motionRepository: LoadMotionRepository,
private readonly routineRepository: AddRoutineRepository
) {}
async add(data: AddRoutine.Params): Promise<boolean> {
let motionInRoutine = [];
for(const motion of data.motions) {
let result = await this.motionRepository.loadMotion({ id: motion.motion_id + "" });
if(!result) { return false; }
const { motion_id, motion_time, numOfMotion } = motion;
const { name: motion_name, file: motion_file, parts: motion_parts } = result;
let motionDetail = {
motion_id,
motion_name,
motion_file,
motion_time,
numOfMotion,
motion_parts,
};
motionInRoutine.push(motionDetail);
}
// 가져온 정보를 추가하여 루틴 컬렉션에 루틴 등록
await this.routineRepository.addRoutine({
...(data),
file: data.fileName,
motions: motionInRoutine,
break_time: data.breakTime,
});
return true;
// motion 테이블에서 나머지 정보 가져오기
// const motionList = data.motions.map(async (motion) => {
// return await this.motionRepository.loadMotion({ id: motion.motionId + "" });
// });
// map 함수는 async/await 를 지원하지않으므로 for문을 사용하여 실행한다.
}
}
|
bc503460219c79ae8515bce1ace1efdafa89c6fd
|
TypeScript
|
vinod0354/goalshaper-web-live
|
/src/app/pipes/searchPipe.ts
| 2.703125
| 3
|
import { Injectable, Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'searchpipe'
})
@Injectable()
export class SearchPipe implements PipeTransform {
// transform(items: any[], field: string, value: string): any[] {
// if (!items) return [];
// if (field == 'all') {
// //return items.filter((item) => Object.keys(item).some((k) => item[k].includes(value.toLowerCase())));
// return items.filter((it) => {
// return JSON.stringify(it).toLowerCase().includes(value);
// });
// } else {
// return items.filter((it) => it[field].includes(value));
// }
// }
/* New Filter */
transform(items: any, filter: any): any {
if (filter && Array.isArray(items)) {
let filterKeys = Object.keys(filter);
return items.filter((item) => {
return filterKeys.some((keyName) => {
//var re = new RegExp(args, 'gi'); //'gi' for case insensitive and can use 'g' if you want the search to be case sensitive.
//return value.replace(re, "<mark>" + args + "</mark>");
//let searchValue = new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] === '';
return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] === '';
});
});
} else {
return items;
}
}
}
|
8313c385703fbcac9f0a17cdfc7a45d263d30f2a
|
TypeScript
|
unbyte/icarus
|
/src/provider/common/atom.ts
| 2.640625
| 3
|
import { Node, Options, unescapeEntity } from 'xml'
import {
CardMsgHeaderTemplate,
CardMsgModule,
createCardMessage,
Message,
useButton,
useField,
useMDText,
useModuleContent,
useText,
} from '../../bot/msg.ts'
import { TaskMeta } from '../../bot/task.ts'
import { createCommonProvider, Option, Store } from '../provider.ts'
import { fetchXML, removeTags } from '../util.ts'
export interface AtomArticle {
title: string
url: string
author: string
summary: string
updatedTime: string
publishedTime: string
}
export interface AtomSource {
url: string
name: string
theme?: CardMsgHeaderTemplate
xmlParseOptions?: Partial<Options>
nodeToArticle?(node: Node): AtomArticle
articleToMessageBody?(article: AtomArticle): CardMsgModule[]
}
export interface AtomOption extends Option {
}
export interface AtomMeta extends TaskMeta, AtomSource {
nodeToArticle(node: Node): AtomArticle
articleToMessageBody(article: AtomArticle): CardMsgModule[]
}
export const useAtom = createCommonProvider<AtomSource, AtomOption, AtomMeta>(
initializer,
runner,
)
function initializer(
sources: AtomSource[],
option?: AtomOption,
): AtomMeta[] {
return sources.map(source => {
return {
theme: CardMsgHeaderTemplate.PURPLE,
interval: 60,
debug: false,
nodeToArticle: defaultAtomNodeToArticle,
articleToMessageBody: defaultAtomArticleToMessageBody,
...source,
...option,
}
})
}
const idStoreKey = 'ID'
async function runner(
meta: AtomMeta,
store: Store,
): Promise<Message[]> {
const root = await fetchXML(meta.url, {}, meta.xmlParseOptions)
if (!root) return []
const articles = root.find(['feed', 'entry'])
if (!articles.length) throw new Error('fail to fetch articles')
let newArticles: Node[]
if (meta.debug) {
newArticles = articles.slice(0, 1)
} else {
// get cached id
const lastUpdateID: string = store.get(idStoreKey)
store.set(idStoreKey, articles[0]?.getChild('id')?.getValue(''))
// set cache and return empty msg for the first time
if (!lastUpdateID) return []
const lastUpdateIdx = articles.findIndex(
item => item.getChild('id')?.getValue('') === lastUpdateID,
)
if (lastUpdateIdx === -1) throw new Error('fail to compare newer article')
newArticles = articles.slice(0, lastUpdateIdx)
}
// generate message
return newArticles.map(node =>
createCardMessage(
{
header: {
template: meta.theme,
title: useText(meta.name),
},
elements: meta.articleToMessageBody(meta.nodeToArticle(node)),
},
)
)
}
function defaultAtomNodeToArticle(node: Node): AtomArticle {
return {
title: node.getChild('title')?.getValue('') || '',
url: node.getChild('link')?.getAttr('href') as string || '',
author: node.getChild('author')?.getChild('name')?.getValue('') || '',
summary: removeTags(
unescapeEntity(
node.getChild('content')?.getValue('').substr(0, 600) || '',
).match(/<p>([\s\S]+?)<\/p>/)?.[1] || '',
),
publishedTime: node.getChild('published')?.getValue('') || '',
updatedTime: node.getChild('updated')?.getValue('') || '',
}
}
function defaultAtomArticleToMessageBody(
article: AtomArticle,
): CardMsgModule[] {
return [
useModuleContent({
text: useMDText(`**${article.title}**`),
fields: [
useField(useMDText('')), // for margin
useField(useMDText(`**Authors**: ${article.author}`)),
useField(useMDText('')), // for margin
useField(useMDText(`**Summary**: \n${article.summary}`)),
useField(useMDText('')), // for margin
],
extra: useButton(useText('Read Article'), {
url: article.url,
}),
}),
]
}
|
ffa66711fbe74582df205626b375d558fa0fda57
|
TypeScript
|
ashok1863/Angular-login-and-authentication
|
/src/app/Login/authentication.service.ts
| 2.5625
| 3
|
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { Token } from './token';
import 'rxjs/add/operator/map'
@Injectable()
export class AuthenticationService {
public token: Token
constructor(private http: Http, private router: Router,) {
// set token if saved in local storage
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.token;
}
login(username: string, password: string): Observable<boolean> {
//this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
let url = 'http://localhost:63938/api/Authenticate';
// let url = '/Home/Authenticate?username' + username+'&password'+password;
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify({ username: username, password: password });
return this.http.post(url, body, options)
.map((response: Response) => {
// login successful if there's a jwt token in the response
// let token = response.json() && response.json().token;
if (response.json() == true) {
var _token = this.createToken(username);
if (_token) {
// set token property
this.token = _token;
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ username: username, token: _token }));
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
}
});
}
createToken(username: string): Token {
this.token = new Token();
var today = new Date();
this.token.Username = username;
this.token.TokenType = "bearer";
this.token.IssuedAt = today;
this.token.ExpiresIn = 20;
this.token.ExpiresAt = new Date(today.setMinutes(today.getMinutes() + this.token.ExpiresIn));
this.token.AccessToken = Guid.newGuid();
return this.token;
}
logout(): void {
// clear token remove user from local storage to log user out
this.token = null;
localStorage.removeItem('currentUser');
}
isAuthorized(): boolean {
if (this.token && !this.isTokenExpired()) {
return true;
} else {
return false;
}
}
isTokenExpired(): boolean {
let duration = this._getMinutesBetweenDates(this.token.ExpiresAt);
if (duration >= 0 && duration <= this.token.ExpiresIn) {
var today = new Date();
this.token.ExpiresAt = new Date(today.setMinutes(today.getMinutes() + this.token.ExpiresIn));
return false;
}
else {
this.token = null;
localStorage.removeItem('currentUser');
this.router.navigate(['/login']);
return true;
}
}
_getMinutesBetweenDates(expiryDate: Date): number {
var diff = new Date(expiryDate).getTime() - new Date().getTime();
return (diff / 60000);
}
}
class Guid {
static newGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}
|
10d6c9438931c288fcac1a105bc9c7aed552825e
|
TypeScript
|
6ebeng/real-estate-crm
|
/src/components/AccountListTable/types.ts
| 2.796875
| 3
|
interface TableProps {
accountSummaries: AccountSummary[];
onSelectRow: (accountEmail: string) => void;
displayPage: number;
onClickNext: () => void;
onClickPrev: () => void;
}
interface TableRowProps {
email: string;
lastLogin: string;
onClick: () => void;
}
interface AccountSummary {
accountEmail: string,
lastLogin: string,
accountType: 'client' | 'agent',
}
interface Account {
email: string,
firstName: string,
lastName: string,
phone: string,
}
interface AgentAccount extends Account {
type: 'agent',
licenseId: string,
brokerage: string,
brokerageAddress: string,
brokeragePhone: string
}
interface ClientAccount extends Account {
type: 'client',
}
export default TableProps;
export type { TableRowProps, AccountSummary, AgentAccount, ClientAccount } ;
|
90216615ff63d54f7319ca80c53e6b9589b9c293
|
TypeScript
|
mattmccray/tilt
|
/src/helpers/urlFor.ts
| 2.5625
| 3
|
import { useSite } from "../core/hooks.js";
import { Page } from "../core/types.js";
export function urlFor(page: Page | string, fullURL = false): string {
let path = typeof page === 'string' ? page : page.filepath
const { url = '' } = useSite()
path = path.endsWith('index.html')
? '/' + path.replace('index.html', '')
: '/' + path
return fullURL
? url + path
: path
}
export default urlFor
|
bc2452aedc98ef70796ad2baa49e6322df6fd758
|
TypeScript
|
mykytagit516/angular-monitoring
|
/src/app/services/event.service.ts
| 2.78125
| 3
|
import { EventEmitter,
Injectable,
OnDestroy
} from '@angular/core';
export interface IEventListenr extends OnDestroy {
ngOnDestroy(): void;
}
@Injectable()
export class EventService {
private listeners = <any>{};
private subject = new EventEmitter();
private eventObserver = this.subject.asObservable();
constructor() {
this.eventObserver.subscribe(({name, args}) => {
if (this.listeners[name]) {
for (const listener of this.listeners[name]) {
listener.callback(args);
}
}
});
}
public registerEvent(eventName: string, eventListener: IEventListenr, callback: any) {
if (!this.listeners[eventName]) {
this.listeners[eventName] = [];
}
let eventExist = false;
for (const listener of this.listeners[eventName]) {
if (listener.eventListener.constructor.name === eventListener.constructor.name) {
eventExist = true;
break;
}
}
if (!eventExist) {
this.listeners[eventName].push({eventListener, callback});
}
}
public unregisterEvent(eventName: string, eventListener: IEventListenr) {
if (this.listeners[eventName]) {
for (let i = 0; i < this.listeners[eventName].length; i++) {
if (this.listeners[eventName][i].eventListener.constructor.name === eventListener.constructor.name) {
this.listeners[eventName].splice(i, 1);
break;
}
}
}
}
emit(name: string, ...args: any[]) {
this.subject.next({name, args});
}
}
|
f0bb7880ee05c91af0915f767f30ad160f74cf36
|
TypeScript
|
drjkelly/week-1-duck-and-car
|
/main.ts
| 2.71875
| 3
|
sprites.onOverlap(SpriteKind.Player, SpriteKind.Enemy, function (sprite, otherSprite) {
Car.destroy(effects.spray, 200)
info.changeLifeBy(-1)
})
let Car: Sprite = null
let Duck = sprites.create(img`
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . b 5 5 b . . .
. . . . . . b b b b b b . . . .
. . . . . b b 5 5 5 5 5 b . . .
. b b b b b 5 5 5 5 5 5 5 b . .
. b d 5 b 5 5 5 5 5 5 5 5 b . .
. . b 5 5 b 5 d 1 f 5 d 4 f . .
. . b d 5 5 b 1 f f 5 4 4 c . .
b b d b 5 5 5 d f b 4 4 4 4 b .
b d d c d 5 5 b 5 4 4 4 4 4 4 b
c d d d c c b 5 5 5 5 5 5 5 b .
c b d d d d d 5 5 5 5 5 5 5 b .
. c d d d d d d 5 5 5 5 5 d b .
. . c b d d d d d 5 5 5 b b . .
. . . c c c c c c c c b b . . .
`, SpriteKind.Player)
scene.setBackgroundColor(9)
controller.moveSprite(Duck)
Duck.setStayInScreen(true)
info.setLife(5)
game.onUpdateInterval(2000, function () {
Car = sprites.create(img`
. . . . . . . . . . . . . . . .
. . . . . . 2 2 2 2 2 2 2 2 . .
. . . . . 2 c 2 2 2 2 2 2 4 2 .
. . . . 2 c c 2 2 2 2 2 2 4 c 2
. . d 2 4 c c 2 4 4 4 4 4 4 c c
. d 2 2 4 c b e e e e e e e 2 c
. 2 2 2 4 b e e b b b e b b e 2
. 2 2 2 2 2 e b b b b e b b b e
. 2 2 2 2 e 2 2 2 2 2 e 2 2 2 e
. 2 d d 2 e f e e e f e e e e e
. d d 2 e e e f e e f e e e e e
. e e e e e e e f f f e e e e e
. e e e e f f f e e e e f f f f
. . . e f f f f f e e f f f f f
. . . . f f f f . . . . f f f .
. . . . . . . . . . . . . . . .
`, SpriteKind.Enemy)
Car.setPosition(160, randint(0, 120))
Car.setVelocity(-100, 0)
})
|
b8473a66a2421dc8db50c5cf08ef077bf51881bd
|
TypeScript
|
alxrdev/apply-api
|
/tests/unit/modules/jobs/useCases/CreateJobeUseCase.spec.ts
| 2.734375
| 3
|
import { AppError } from '@errors/index'
import { CreateJobDTO } from '@modules/jobs/dtos'
import { Job } from '@modules/jobs/entities'
import FakeJobRepository from '@modules/jobs/repositories/fake/FakeJobRepository'
import IJobRepository from '@modules/jobs/repositories/IJobRepository'
import { CreateJobUseCase } from '@modules/jobs/useCases'
import { User } from '@modules/users/entities'
import { UserNotFoundError } from '@modules/users/errors'
import FakeUserRepository from '@modules/users/repositories/fake/FakeUserRepository'
import IUserRepository from '@modules/users/repositories/IUserRepository'
const makeDto = (fields = {}) : CreateJobDTO => {
const data = { userId: '1', title: 'My first job', description: 'this is my first job', salary: 1200.00, jobType: 'Full-time', state: 'ES', city: 'São Mateus', ...fields }
const dto = new CreateJobDTO()
return Object.assign(dto, data)
}
let userRepository: IUserRepository
let jobRepository: IJobRepository
const makeSut = () : CreateJobUseCase => new CreateJobUseCase(jobRepository, userRepository)
describe('Test the CreateJobUseCase class', () => {
beforeAll(async () => {
userRepository = new FakeUserRepository()
userRepository.create(User.builder()
.withId('1')
.withName('John Doe')
.withEmail('user@email.com')
.withRole('employer')
.withAvatar('avatar.jpg')
.withPassword('password')
.withHeadline('my headline')
.build()
)
jobRepository = new FakeJobRepository(userRepository)
})
it('Should throw an AppError when a required field is not provided', async () => {
const createJobUseCase = makeSut()
const dto = makeDto({ title: '' })
await expect(createJobUseCase.execute(dto)).rejects.toThrowError(AppError)
})
it('Should throw an AppError when invalid field is provided', async () => {
const createJobUseCase = makeSut()
const dto = makeDto({ jobType: 'invalid' })
await expect(createJobUseCase.execute(dto)).rejects.toThrowError(AppError)
})
it('Should throw an UserNotFoundError when the user not exists', async () => {
const createJobUseCase = makeSut()
const spyFindById = jest.spyOn(userRepository, 'findById')
const dto = makeDto({ userId: '2' })
await expect(createJobUseCase.execute(dto)).rejects.toThrowError(UserNotFoundError)
expect(spyFindById).toHaveBeenCalled()
})
it('Should return the created job', async () => {
const createJobUseCase = makeSut()
const spyFindById = jest.spyOn(userRepository, 'findById')
const spyCreate = jest.spyOn(jobRepository, 'create')
const dto = makeDto()
const job = await createJobUseCase.execute(dto)
expect(job).toBeInstanceOf(Job)
expect(job.title).toBe(dto.title)
expect(job.description).toBe(dto.description)
expect(job.salary).toBe(dto.salary)
expect(job.jobType).toBe(dto.jobType)
expect(job.address.state).toBe(dto.state)
expect(job.address.city).toBe(dto.city)
expect(spyFindById).toHaveBeenCalled()
expect(spyCreate).toHaveBeenCalled()
})
})
|
708e29b12fca16e458b1eacde4b3816eedaa9ef5
|
TypeScript
|
marcoshenriquedesousa/fight-guide
|
/src/controller/personagem.ts
| 2.578125
| 3
|
import { BaseControlador } from "./base";
import { Request } from 'express'
import { Personagem } from "../entity/personagem";
export class PersonagemController extends BaseControlador<Personagem> {
constructor() {
super(Personagem)
}
async salvarPersonagem(requisicao: Request){
const _personagem = <Personagem>requisicao.body
super.isRequired(_personagem.nome, 'falta o parametro: nome')
super.isRequired(_personagem.sobreNome, 'falta o parametro: sobreNome')
super.isRequired(_personagem.imagem, 'falta o parametro: imagem')
super.isRequired(_personagem.jogo, 'falta o parametro: jogo')
return super.salvar(_personagem)
}
}
|
69c27d077386eb3879c9299cd91b26f0ec96db34
|
TypeScript
|
ibednorz/dzial-iii-szachy
|
/src/tests/queensCanAttackHorizontally.test.ts
| 3.171875
| 3
|
import { QueensAttack } from "../queensAttack";
describe("(5 points) - Returning possibility of a horizontal attack by queens", () => {
[
{
queens: new QueensAttack({ white: [1, 7], black: [1, 5] }),
},
{
queens: new QueensAttack({ white: [3, 2], black: [3, 6] }),
},
{
queens: new QueensAttack({ white: [5, 2], black: [5, 6] }),
},
{
queens: new QueensAttack({ white: [7, 6], black: [7, 2] }),
},
{
queens: new QueensAttack({ white: [4, 2], black: [4, 1] }),
},
].map((testCase) => {
it(`[${testCase.queens.white}] / [${testCase.queens.black}] queens can attack each other horizontally`, () => {
expect(testCase.queens.queenCanAttack()).toEqual(true);
});
});
});
|
d084a4a8e3c59a1914824dde33ba0298e9e8ef98
|
TypeScript
|
lml-dom/lml-js
|
/src/output/string-output/html-output.ts
| 2.984375
| 3
|
import { TEXT_BLOCK_ELEMENTS } from '../../const';
import { DOMNode } from '../../dom-node';
import { OutputConfig } from '../../output-config';
import { StringOutput } from '../string-output';
/**
* Parses DOMNode[] to HTML string
*/
export class HTMLOutput extends StringOutput {
constructor(nodes: DOMNode[], config?: OutputConfig) {
super(nodes, config);
if (this.config.minify) {
this.config.indentation = '';
}
}
public cdata(node: DOMNode): string {
return `${this.indentation(node)}<![CDATA[${this.textChild(node).data}]]>${this.lf}`;
}
public comment(node: DOMNode): string {
if (this.config.minify) {
return '';
}
const str = `${this.indentation(node)}<!-- ${this.indentMultilineData(node).trim()} -->`;
return this.wrapLines(str, this.indentation(node, 1)) + '\n';
}
public directive(node: DOMNode): string {
return `<${node.data}>${this.lf}`;
}
public element(node: DOMNode): string {
const indentation = this.indentation(node);
const childIndentation = indentation + this.config.indentation;
const parts = [`${indentation}<${node.name}`, ...this.attributesString(node)];
parts[parts.length - 1] += '>';
const tag = this.multilineTag(parts, childIndentation);
if (node.name === 'textarea') {
return `${tag}${this.textChild(node).data}</${node.name}>${this.lf}`;
} else if (TEXT_BLOCK_ELEMENTS.includes(node.name)) {
const src = this.indentMultilineData(this.textChild(node), false);
if (src) {
if (src.indexOf('\n') === -1) {
const oneLine = `${tag}${src}</${node.name}>`;
if (oneLine.length <= this.config.lineWrap) {
return `${oneLine}${this.lf}`;
}
}
return `${tag}${this.lf}${childIndentation}${src}${this.lf}${indentation}</${node.name}>${this.lf}`;
}
return `${tag}</${node.name}>${this.lf}`;
}
const content = node.children.map((child) => this[child.type](child)).join('');
const closingTag = content || !DOMNode.voidTags.includes(node.name) ? `</${node.name}>` : '';
if (content) {
if (!this.config.minify && node.children.length === 1 && !node.children[0].children.length) {
const trimmed = content.substring(childIndentation.length, content.length - 1);
if (trimmed.indexOf('\n') === -1) {
const oneLine = `${tag}${trimmed}${closingTag}`;
if (oneLine.length <= this.config.lineWrap) {
return `${oneLine}\n`;
}
}
}
return `${tag}${this.lf}${content}${indentation}${closingTag}${this.lf}`;
}
return `${tag}${closingTag}${this.lf}`;
}
public text(node: DOMNode): string {
if (this.config.minify) {
return node.data.trim();
}
const indentation = this.indentation(node);
return this.wrapLines(`${indentation}${this.indentMultilineData(node).trim()}`, indentation) + '\n';
}
/**
* Line-feed (enter) character in normal, or empty string minification mode
*/
private get lf(): string {
return this.config.minify ? '' : '\n';
}
}
|
392533bb83dd3f712154dde0c1f68055c73cce6a
|
TypeScript
|
yudhistira-arya/typescript-knowledge-sharing
|
/05_01_rxjs/timer-operator.ts
| 2.59375
| 3
|
import {timer} from "rxjs";
export function simpleTimer() {
// first emit after 100ms delay then emit every 200ms after that.
const observable = timer(99, 200);
observable.subscribe(value => {
console.log(`first-subscriber: ${value}`);
});
}
|
a5445bb88e42f90fc282fa8b6291cf3c103a96e9
|
TypeScript
|
im-cuttlefish/react-leaper
|
/src/internal/UnmountedLeaper.ts
| 2.640625
| 3
|
import { useEffect, useState, ReactElement } from "react";
import { Motion, Style } from "../types";
export interface Props {
remove: Motion;
initial: Style;
noticeAnimationEnd: () => void;
children: (style: Style) => ReactElement;
}
export const UnmountedLeaper = (props: Props) => {
const [style, setStyle] = useState(props.initial);
useEffect(() => {
const generator = props.remove(props.initial);
let frameID = 0;
let passed = performance.now();
const frame = (progress: number) => {
frameID = requestAnimationFrame(frame);
const delta = progress - passed;
passed = progress;
const { value, done } = generator.next(delta);
setStyle({ ...style, ...value });
if (done) {
cancelAnimationFrame(frameID);
props.noticeAnimationEnd();
return;
}
};
frameID = requestAnimationFrame(frame);
}, []);
const { children } = props;
return children(style);
};
|
86f0bd058a811fb84899f26ba3e030bdd3a6f016
|
TypeScript
|
nmyers322/identity-secret-react
|
/src/app/stores/IdStore.ts
| 2.671875
| 3
|
import { observable, action } from 'mobx';
import { IdModel } from 'app/models/IdModel';
export class IdStore {
constructor() {
this.ids = [];
}
@observable public ids: Array<IdModel>;
@action
addId = (id: string) : void => {
this.ids.push(new IdModel(id));
}
@action
deleteId = (id: IdModel) : void => {
let newIds = [...this.ids];
newIds = newIds.filter((checkId: IdModel) => (checkId.id !== id.id));
this.ids = newIds;
}
@action
reloadIds = (ids: string[]) : void => {
this.ids = ids.map((id: string) => (new IdModel(id)));
}
}
export default IdStore;
|
c6629e7cccbdf60778a2f8925a2df79c7d468365
|
TypeScript
|
melnaeem/SOLID
|
/O/correct.ts
| 3.890625
| 4
|
interface IQuestion extends IQuestionWithDescription{
printChoices: Function;
}
interface IQuestionWithDescription {
description: string;
printDescription: Function;
}
class QuestionWithDescription implements IQuestionWithDescription {
description: string;
constructor(description: string) {
this.description = description;
}
printDescription() {
console.log(this.description);
}
}
class BooleanQuestion extends QuestionWithDescription implements IQuestion {
constructor(description: string) {
super(description);
}
printChoices() {
console.log('1. True');
console.log('3. False');
}
}
class MultiChoiceQuestion extends QuestionWithDescription implements IQuestion {
options: string[];
constructor(description: string, options: string[]) {
super(description);
this.options = options;
}
printChoices() {
this.options.forEach((option, index) => {
console.log(`${index + 1}. ${option}`);
});
}
}
class TextQuestion extends QuestionWithDescription implements IQuestion {
constructor(description: string) {
super(description);
}
printChoices() {
console.log('Answer: __________________');
}
}
class RangeQuestion extends QuestionWithDescription implements IQuestion {
constructor(description: string) {
super(description);
}
printChoices() {
console.log('Minimum: __________________');
console.log('Maximum: __________________');
}
}
function printAllQuestions(questions: IQuestion[]) {
questions.forEach(question => {
question.printDescription();
question.printChoices();
console.log('');
});
}
const Questions: IQuestion[] = [
new BooleanQuestion('This is a true/false question'),
new MultiChoiceQuestion(
'What is your favourite language?',
['HTML', 'CSS', 'JS', 'Python']
),
new TextQuestion('Describe your favourite JS feature'),
new RangeQuestion('What is the speed limit in your city?')
];
printAllQuestions(Questions);
|
fda6c7ee11e82890b489b2efa2eb0214efbc64cd
|
TypeScript
|
blteblte/scroll-date
|
/src/app/helpers.ts
| 3.140625
| 3
|
// export function getDateElalSearchFormat(date: Date): string {
// const dd = date.getDate()
// const mIx = date.getMonth()
// const yyyy = date.getFullYear()
// const mArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Dec']
// return `${dd}/${mArr[mIx]}/${yyyy}`
// }
export function parseDate(dateStr: string) {
try {
return new Date(dateStr)
} catch (e) {
return new Date()
}
}
export function getDateISOFormat(date: Date): string {
if (date == null) { return '' }
const dd = date.getDate()
const mm = date.getMonth() + 1
const yyyy = date.getFullYear()
return `${yyyy}-${mm < 10 ? `0${mm}` : mm}-${dd < 10 ? `0${dd}` : dd}`
}
export function isDatesEqual(date1: Date | string, date2: Date | string) {
if (date1 === undefined) { return false }
if (date2 === undefined) { return false }
let date1Type: 'string' | 'date'
let date2Type: 'string' | 'date'
if (typeof date1 === 'string' || date1 instanceof String) {
date1Type = 'string'
} else {
date1Type = 'date'
}
if (typeof date2 === 'string' || date2 instanceof String) {
date2Type = 'string'
} else {
date2Type = 'date'
}
if (date1Type === 'date' && date2Type === 'date') {
return getDateISOFormat(date1 as Date) === getDateISOFormat(date2 as Date)
} else if (date1Type === 'date' && date2Type === 'string') {
return getDateISOFormat(date1 as Date) === date2
} else if (date1Type === 'string' && date2Type === 'date') {
return date1 === getDateISOFormat(date2 as Date)
} else {
return date1 === date2
}
}
export function camelCaseToDash(myStr) {
return myStr.replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();
}
export function getDatePickerPlaceholderDate(date: Date) {
if (date === null) { return '' }
const dd = date.getDate()
const mm = date.getMonth() + 1
const yyyy = date.getFullYear()
return `${dd < 10 ? `0${dd}` : dd}/${mm < 10 ? `0${mm}` : mm}/${yyyy}`
}
export function isDateObjectValid(d) {
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d.getTime())) { // d.valueOf() could also work
return false
} else {
return true
}
} else {
return false
}
}
export function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
|
866d0aec334fe78ac8c39f08f2b2c2000b747bc9
|
TypeScript
|
phani-rajbn/Angular11Training
|
/src/app/Pipes/emp-filter.pipe.ts
| 3.234375
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { Employee } from '../Entities/employee';
@Pipe({
name: 'empfilter'
})
//filter is a method in js that can be used on arrays to filter the elements based on the criteria based as lambda expression.
export class EmpFilterPipe implements PipeTransform {
transform(employees: Employee[], filterCriteria: string): Employee[] {
if(filterCriteria == undefined) return employees;
return employees.filter((emp) => emp.empName.toLowerCase().includes(filterCriteria.toLowerCase()));
}
}
//Pipes or filters provide a mechanism to format the data that U want to use in the user interface of the application. It is simply a class with a directive called Pipe which takes an object info about the name that U want to give to the pipe. name is the way to use the pipe in the application
//Pipe classes implement an interface called PipeTransform which gives one and only one function called transform. transform method provides the functionality on how UR data needs to be transformed while using it in the User interface.
//Input for the pipe comes as first arg, 2nd arg will be any custom conditions or criteria and it can add on to any no of critierias, and finally returns a specific kind of data. In the example able, input will be an array of employees, criteria will be the filter based on name, returns a nested list of employees filtered based on the criteria.
//Pipes are not just for filtering, its job is to transform the input to the specific output which U can appy in ur user interface.
//U generate the pipe using the ng command:
//ng generate pipe Pipes/EmpFilter --skip-tests
|
d2d4f3044881381f229abae410e30e64c896c59a
|
TypeScript
|
future4code/Isabela-Silveira
|
/semana18/aula52/services-backend/src/service/adressManager.ts
| 2.75
| 3
|
import axios from "axios";
import { adress } from "../types/types";
export async function getAddressMyCep(cep: string): Promise<adress> {
try {
const result = await axios.get(`https://viacep.com.br/ws/${cep}/json/`)
const myAddress: adress = {
street: result.data.logradouro,
neighbourhood: result.data.bairro,
city: result.data.localidade,
state: result.data.uf
}
return myAddress
} catch (error) {
throw new Error(error.message)
}
}
|
0e367c5548507e857195b5254a3dfce26379636c
|
TypeScript
|
DWitteveen/Tic-Tac-Toe-BE-only
|
/src/game/gameEdit.ts
| 3.859375
| 4
|
//board in default state
export const defaultBoard = [
['o', 'o', 'o'],
['o', 'o', 'o'],
['o', 'o', 'o']
]
//array for given colors
export const colorsList = ["red", "blue", "green", "yellow", "magenta"]
//a function that returns the number of changes between boards (movecounter)
//use to check if if there are made more moves than 1
export const moves = (board1, board2) =>
board1
.map((row, y) => row.filter((cell, x) => board2[y][x] !== cell))
.reduce((a, b) => a.concat(b))
.length
//pick a random color from colorList using Math.floor Math.random
//Math.floor generates an rendom number 0 -1
// *.lenght of the colorlist (total amount)(if you use a number and you udate your
//collor list you have to update your function aswell)
//Math.floor get it to be a whole number
export const color = () => {
return colorsList[Math.floor(Math.random() * colorsList.length)]
}
|
e9dde93795cbc7c5f59ff952763a3b34de568b79
|
TypeScript
|
framer/motion
|
/packages/framer-motion/src/animation/generators/__tests__/spring.test.ts
| 2.515625
| 3
|
import { ValueAnimationOptions } from "../../types"
import { spring } from "../spring"
import { animateSync } from "../../animators/js/__tests__/utils"
describe("spring", () => {
test("Runs animations with default values ", () => {
expect(animateSync(spring({ keyframes: [0, 1] }), 200)).toEqual([
0, 1, 1, 1, 1, 1, 1, 1,
])
})
test("Underdamped spring", () => {
expect(
animateSync(
spring({
keyframes: [100, 1000],
stiffness: 300,
restSpeed: 10,
restDelta: 0.5,
}),
200
)
).toEqual([100, 1343, 873, 1046, 984, 1005, 998, 1001, 1000])
})
test("Velocity passed to underdamped spring", () => {
const settings: ValueAnimationOptions<number> = {
keyframes: [100, 1000],
stiffness: 300,
restSpeed: 10,
restDelta: 0.5,
}
const noVelocity = animateSync(spring(settings), 200)
const velocity = animateSync(
spring({ ...settings, velocity: 1000 }),
200
)
expect(noVelocity).not.toEqual(velocity)
})
test("Critically damped spring", () => {
expect(
animateSync(
spring({
keyframes: [100, 1000],
stiffness: 100,
damping: 20,
restSpeed: 10,
restDelta: 0.5,
}),
200
)
).toEqual([100, 635, 918, 984, 997, 1000])
})
test("Velocity passed to critically spring", () => {
const settings = {
keyframes: [100, 1000],
stiffness: 100,
damping: 20,
restSpeed: 10,
restDelta: 0.5,
}
const noVelocity = animateSync(spring(settings), 200)
const velocity = animateSync(
spring({ ...settings, velocity: 1000 }),
200
)
expect(noVelocity).not.toEqual(velocity)
})
test("Overdamped spring", () => {
expect(
animateSync(
spring({
keyframes: [100, 1000],
stiffness: 300,
damping: 100,
restSpeed: 10,
restDelta: 0.5,
}),
200
)
).toEqual([
100, 499, 731, 855, 922, 958, 977, 988, 993, 996, 998, 999, 999,
1000,
])
})
test("Overdamped spring with very high stiffness/damping", () => {
expect(
animateSync(
spring({
keyframes: [100, 1000],
stiffness: 1000000,
damping: 10000000,
restDelta: 1,
restSpeed: 10,
}),
200
)
).toEqual([100, 1000])
})
test("Velocity passed to overdamped spring", () => {
const settings = {
keyframes: [100, 1000],
stiffness: 300,
damping: 100,
restSpeed: 10,
restDelta: 0.5,
}
const noVelocity = animateSync(spring(settings), 200)
const velocity = animateSync(
spring({ ...settings, velocity: 1000 }),
200
)
expect(noVelocity).not.toEqual(velocity)
})
test("Spring defined with bounce and duration is same as just bounce", () => {
const settings = {
keyframes: [100, 1000],
bounce: 0.1,
}
const withoutDuration = animateSync(spring(settings), 200)
const withDuration = animateSync(
spring({ ...settings, duration: 800 }),
200
)
expect(withoutDuration).toEqual(withDuration)
// Check duration order of magnitude is correct
expect(withoutDuration.length).toBeGreaterThan(4)
})
})
|
ce2d4352095d3072d5eccf4bb96bfbdd67af2c07
|
TypeScript
|
houkanshan/LD40
|
/src/index.ts
| 2.609375
| 3
|
import './style'
import * as $ from 'jquery'
import './libs/turn'
import PubSub from 'pubsub-js'
import Menu from './menu'
import Order from './order'
import Friend from './friend'
import Player from './player'
import Waiter from './waiter'
import { delay } from './utils'
import chooseConversation from './dialogText'
import { ConversationType } from './enums'
const body = $(document.body)
function startGame() {
if (body.hasClass('on')) { return }
body.addClass('on')
const game = new Game()
game.start()
setTimeout(function () {
body.addClass('hide-loading-layer')
}, 1010)
}
class Game {
beginTime: Date
level: number
nextLevel: number
passingRate: number
passedCount: number
menu: Menu
order: Order
player: Player
friend: Friend
waiter: Waiter
speakers: Array<Player|Friend|Waiter>
start() {
PubSub.subscribe('menu', (t, d) => console.log(t, d))
PubSub.subscribe('order', (t, d) => console.log(t, d))
this.beginTime = new Date()
this.level = 1
this.nextLevel = 1
this.passingRate = 0
this.passedCount = 0
this.menu = new Menu({ level: this.level })
this.order = new Order({ beginTime: this.beginTime })
this.player = new Player()
this.friend = new Friend()
this.waiter = new Waiter()
this.speakers = [this.player, this.friend, this.waiter]
debugger
this.startConversation(ConversationType.START)
PubSub.subscribe('menu.dish.select', (t, dish) => {
const passed = this.judge(dish)
this.startConversation(ConversationType.DISH, dish, passed).then(() => {
if (passed) {
this.order.addOrder(dish)
}
}).then(() => {
if (this.nextLevel === 5) {
this.end()
} else if (this.level !== this.nextLevel) {
this.setLevel(this.nextLevel)
}
})
})
PubSub.subscribe('menu.page.turned', (t, pageNum) => {
if (pageNum >= 3 + 7 + 2 && this.level === 1) {
this.passedCount = 1
this.setLevel(2)
}
})
}
end() {
console.log('end')
}
setLevel(level) {
this.level = level
this.nextLevel = level
this.menu.setLevel(level)
this.passingRate = 0
console.log('level upgraded: ', level)
// PubSub.publish('level.updated', level)
}
passingRateIncrementMap = [
1, // level 0 does not exist.
0.2,
0.15,
0.10,
0.05,
]
judge(dish) {
if (dish.pungency > 2) { return false }
const passed = Math.random() < this.passingRate
if (passed) {
this.passedCount += 1
if (this.passedCount >= 1 && this.level < 2) {
this.nextLevel = 2
} else if (this.passedCount >= 2 && this.level < 3) {
this.nextLevel = 3
} else if (this.passedCount >= 3 && this.level < 4) {
this.nextLevel = 4
} else if (this.passedCount >= 6) {
this.nextLevel = 5
}
} else {
this.passingRate += this.passingRateIncrementMap[this.level]
}
return passed
}
startConversation(type: ConversationType, dish?, passed?: boolean) {
this.menu.stop()
const dialog = chooseConversation(type, dish, this.level, passed)
return dialog.reduce((prev, { speakerIndex, text }) => {
return prev.then(() => this.speakers[speakerIndex].dialog.say(text))
}, $.Deferred().resolve())
.then(() => {
this.menu.resume()
})
}
}
// Not in use.
// function startMainScene() {
// PubSub.subscribe('menu.dish.help', (t, dish) => {
// player.askDish(dish)
// .then(delay(1000))
// .then(() => waiter.explainDish(dish))
// })
// setTimeout(function waiterNag() {
// if (
// !friend.dialog.isSaying &&
// !player.dialog.isSaying &&
// !waiter.dialog.isSaying
// ) {
// waiter.nag()
// }
// setTimeout(waiterNag, 10000 + Math.random() * 5000)
// }, 2000)
// }
if (document.readyState === 'complete') {
setTimeout(startGame, 500)
} else {
window.onload = startGame
setTimeout(startGame, 5000)
}
|
8daf4d4e6906bc16d7e2f2ee0500ae7a959e3190
|
TypeScript
|
CrispusDH/protractor-lite
|
/lib/core/by/locator.ts
| 3.25
| 3
|
import { By as wdBy, ByHash, WebDriver, WebElement } from 'selenium-webdriver';
/**
* Selenium webdriver's location strategy.
*/
export type WebDriverLocator = wdBy | ByHash | Function;
/**
* Protractor's location strategy.
*/
export interface ProtractorLocator {
findElementsOverride: (driver: WebDriver|WebElement,
using: WebElement) => Promise<WebElement[]>;
row?: (index: number) => Locator;
column?: (index: string) => Locator;
toString?: () => string;
}
export type Locator = ProtractorLocator | WebDriverLocator;
/**
* Returns if the locator is a Protractor locator
* @param locator a locator that is either a Protractor or WebDriver Locator
*/
export function isProtractorLocator(
locator: Locator): locator is ProtractorLocator {
const typeFindElementsOverride = typeof(locator as any).findElementsOverride;
return locator && (typeFindElementsOverride === 'function');
}
|
05a486143818378ce743176d27778f7341145243
|
TypeScript
|
vvj-rares/renderfarm.js-client
|
/src/lib/Scene.ts
| 2.53125
| 3
|
"use strict";
import { Object3D as threejsObject3D } from "three";
import { PerspectiveCamera as threejsPerspectiveCamera } from "three";
import { IObject3D } from "./interface/IObject3D";
import { IScene } from "./interface/IScene";
import { Camera } from "./Camera";
const axios = require("axios");
//this is a client to 3ds max scene
class Scene implements IScene {
private _baseUrl: string;
private _sessionGuid: string;
private _maxNodeName: string;
public constructor(baseUrl: string, sessionGuid: string) {
this._baseUrl = baseUrl;
this._sessionGuid = sessionGuid;
}
public New(): Promise<IScene> {
return new Promise(function(resolve, reject) {
reject(); // todo: implement it
}.bind(this));
}
public Open(maxSceneFilename: string): Promise<IScene> {
return new Promise(function(resolve, reject) {
axios.post(`${this._baseUrl}/scene`, {
session: this._sessionGuid,
scene_filename: maxSceneFilename,
})
.then(function (response: any) {
if (response.data && response.data.id) {
this._sceneRootNode = response.data.id;
resolve(this);
} else if (response.data && response.data.error) {
reject(response.data.error);
} else {
console.log(response.data);
reject({ message: "failed to handle server response", response: response.data });
}
}.bind(this))
.catch(function (err: any) {
if (err.response && err.response.data && err.response.data.error) {
reject(err.response.data.error);
} else if (err.message) {
reject(err.message);
} else {
reject(err);
}
}.bind(this)); // end of axios.post promise
}.bind(this));
}
public SaveAs(maxSceneFilename: string): Promise<IScene> {
return new Promise(function(resolve, reject) {
reject(); // todo: implement it
}.bind(this));
}
public Close(): Promise<any> {
return new Promise(function(resolve, reject) {
reject(); // todo: implement it
}.bind(this));
}
public Create(obj: threejsObject3D): Promise<IObject3D<threejsObject3D>> {
if (obj.type === "PerspectiveCamera") return this.PostCamera(obj as unknown as threejsPerspectiveCamera);
}
public Read(maxNodeName: string): Promise<IObject3D<threejsObject3D>> {
return new Promise<IObject3D<threejsObject3D>>(function(resolve, reject) {
reject();
}.bind(this));
}
public Update(obj: threejsObject3D, maxNodeName: string | undefined): Promise<IObject3D<threejsObject3D>> {
return new Promise<IObject3D<threejsObject3D>>(function(resolve, reject) {
reject();
}.bind(this));
}
public Delete(obj: threejsObject3D, maxNodeName: string | undefined): Promise<IObject3D<threejsObject3D>> {
return new Promise<IObject3D<threejsObject3D>>(function(resolve, reject) {
reject();
}.bind(this));
}
private PostCamera(obj: threejsPerspectiveCamera): Promise<IObject3D<threejsPerspectiveCamera>> {
return new Promise<IObject3D<threejsPerspectiveCamera>>(function(resolve, reject) {
new Camera(`${this._baseUrl}/scene/${this._sceneGuid}`, this._sessionGuid, obj).Post()
.then(function(camera: IObject3D<threejsPerspectiveCamera>){
resolve(camera);
}.bind(this)).catch(function(err){
reject(err);
}.bind(this));
return;
}.bind(this));
}
}
export { Scene };
|
f9bab3aa2529c1132310c71e1f9184cccb7d9a26
|
TypeScript
|
webdev0415/Estack-backend
|
/src/auth/local.strategy.ts
| 2.71875
| 3
|
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PublicUserDto } from '../users/dto/public-user.dto';
/** passport local strategy - for email and password check */
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
/**
* LocalStrategy
* @param {AuthService} authService - inject auth service
*/
constructor(private readonly authService: AuthService) {
super({
usernameField: 'email',
passwordField: 'password',
});
}
/**
* validate - email and password
* @param {string} email - user email
* @param {string} password - user password
* @returns {Promise<PublicUserDto>} - valid user data
*/
validate(email: string, password: string): Promise<PublicUserDto> {
return this.authService.validateUser(email, password);
}
}
|
c37700ae79fed9f70cea4aaac8a1449a28e198b6
|
TypeScript
|
thaivan1437/Staff-Manager
|
/helpers/date.ts
| 2.90625
| 3
|
export const convertDateFormat = (dateObject: Date) => {
let dateNow = new Date();
if (dateObject) {
dateNow = dateObject;
}
let month = `${(dateNow.getMonth() + 1)}`;
let day = `${dateNow.getDate()}`;
const year = dateNow.getFullYear();
if (month.length < 2) {
month = `0${month}`;
}
if (day.length < 2) {
day = `0${day}`;
}
return `${day}-${month}-${year}`;
};
|
4a931aad41e8543ea5f38c979be26627351ac205
|
TypeScript
|
swollio/swollio-backend
|
/src/workflows/athlete/getAthleteWorkout.ts
| 2.953125
| 3
|
import db from "../../utilities/database"
interface ExerciseAssignment {
assignment_id: number
exercise_id: number
name: string
weight_scheme: string
rep_count: number[]
}
/**
* Gets the list of exercise assignments for the workout with given id
* @param workoutId The id of the workout we want the exercise assignments of
*/
export default async function getAthleteWorkout(
workoutId: number
): Promise<ExerciseAssignment[]> {
try {
const workout = await db["assignments.filter_by_workout"]([workoutId])
return workout.rows as ExerciseAssignment[]
} catch (err) {
console.log(err)
throw new Error(
"Get Athlete Workout Error: Could not get Athlete Workout"
)
}
}
|
dd9f50733c4f0cfb5344bbff6951db995fe45eb8
|
TypeScript
|
kborkowska/front-gog-solution
|
/src/store/selectors.ts
| 2.640625
| 3
|
import { StoreState } from "../common/interfaces";
import { StateEntities, OwnershipState } from "../common/consts";
export const entitySelector = (entity: StateEntities) => (state: StoreState) =>
state.get(entity);
export const idSelector = (entity: StateEntities) => (
state: StoreState,
id: string
) => state.get(entity).find((entry: any) => entry.get("id") === id);
export const inCartSelector = (entity: StateEntities) => (state: StoreState) =>
state
.get(entity)
.filter((entry: any) => entry.get("state") === OwnershipState.InCart);
|
bb54d45f5f414debc73dfa7748bda92f5fa59512
|
TypeScript
|
naile/bolaget-frontend
|
/app/src/services/Change.ts
| 2.765625
| 3
|
export class Change {
public static Make(dto: any): Change {
return new Change(dto.name, dto.oldValue, dto.newValue);
}
constructor(public name: string, public oldValue: string, public newValue: string) { }
}
|
46abc8f3b98c0359a837e492af0e7c38e358c956
|
TypeScript
|
Smile-shop/JQZ
|
/wx-mall/src/filters/format-unit.ts
| 3.125
| 3
|
// 头部添加单位
export function padStartUnit(data: number | string, unit: string): string | number {
if (data != null) {
if (unit) {
return unit.concat(String(data));
}
return data;
}
return '';
}
// 尾部添加单位
export function padEndUnit(data: number | string, unit: string): string | number {
if (data != null) {
if (unit) {
return String(data).concat(unit);
}
return data;
}
return '';
}
|
2872d65d6fdb6aaca087716b1c259ff9871e3179
|
TypeScript
|
pablo-01/Tech-Reads
|
/client/src/app/_forms/input-text/input-text.component.ts
| 2.59375
| 3
|
import { Component, Input, OnInit, Self } from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
////
// Control value accesor, interface, allows a bridhe between DOM and angular forms
// Accessing the form controls from registration component
////
@Component({
selector: 'app-input-text',
templateUrl: './input-text.component.html',
styleUrls: ['./input-text.component.css']
})
export class InputTextComponent implements ControlValueAccessor {
@Input() label: string; // passing
@Input() type: 'text'; // for field types, initalize with text
// Inject control
// @Self - ensured local injection
constructor(@Self() public ngControl: NgControl) {
this.ngControl.valueAccessor = this; // acces to control in this component
}
// 3 required methods
writeValue(obj: any): void {
}
registerOnChange(fn: any): void {
}
registerOnTouched(fn: any): void {
}
}
|
e8e6ae534fbde36cde0d2ec89fb2244e26ba42e6
|
TypeScript
|
zakdim/angular4-book-examples
|
/01-ts-es6/03-ts-destructing/func-destr.ts
| 2.984375
| 3
|
'use strict';
function f(options) {
console.log(options.x);
}
f({x:1}); // 1
function f2({x}) {
console.log(x); // refer to x directly
}
f2({x:1}); // 1
// With default values
function f3({x=0}) {
console.log(x); // refer to x directly
}
f3({}); // 1
|
96242e359e44be5a6ed1fe0bfc7e5f9bdbd95f89
|
TypeScript
|
Nairobi-Crew/ARCND
|
/src/Store/reducers/oauth/oauth.ts
| 2.90625
| 3
|
import { EOAuthState } from './types';
export interface IOAuthReducer {
serviceID: string
redirectUrl: string
state: EOAuthState
}
export const defaultOAuthReducer: IOAuthReducer = {
serviceID: '',
redirectUrl: '',
state: EOAuthState.UNKNOWN,
};
export type OAuthAction = {
type: string
payload?: string
}
export function oauthReducer(state: IOAuthReducer = defaultOAuthReducer, action: OAuthAction): IOAuthReducer {
switch (action.type) {
case EOAuthState.SET_ID:
return { ...state, serviceID: action.payload as string };
case EOAuthState.SET_URL:
return { ...state, redirectUrl: action.payload as string, state: EOAuthState.REDIRECT };
case EOAuthState.UNKNOWN:
return { ...state, state: EOAuthState.UNKNOWN, serviceID: '' };
case EOAuthState.OAUTH_DONE:
return { ...state, state: EOAuthState.OAUTH_DONE };
default:
return state;
}
}
|
5283a6e3be04af441b93ef72a5a0e501f54e302e
|
TypeScript
|
bretkikehara/karma-webdriverio-launcher
|
/src/driver-manager.ts
| 2.53125
| 3
|
import { parseRemoteConfig, ReporterConfig, parseReporterConfig } from './config';
import { parseCommand } from './commands';
// NOTE: need to use requires b/c webdriverio typescripts definitions are broken.
var { remote } = require('webdriverio');
const errDriverManagerNotAvailable = new Error('driver manager not available');
const errDriverNotAvailable = new Error('driver not available');
export type Driver = any;
export type BrowserID = number|string;
function getBrowserID(browserID: BrowserID): string {
return '' + browserID;
}
class DriverManager {
private DRS: { [key: string]: Promise<Driver> } = {};
private cfg: ReporterConfig;
init(browserID: BrowserID, args: any, config?: any) {
if (!this.cfg) {
this.cfg = parseReporterConfig(config);
}
if (this.DRS) {
this.DRS[getBrowserID(browserID)] = remote(parseRemoteConfig(args));
}
}
del(browserID: BrowserID): Promise<boolean> {
if (!this.DRS) {
return Promise.reject(errDriverManagerNotAvailable);
}
return this.get(browserID).then((driver: Driver) => {
return driver.deleteSession().then(() => {
(this.DRS[getBrowserID(browserID)] as any) = undefined;
return true;
}, () => {
return false;
});
});
}
get(browserID: BrowserID): Promise<Driver> {
if (!this.DRS) {
return Promise.reject(errDriverManagerNotAvailable);
}
const driver = this.DRS[getBrowserID(browserID)];
if (!driver) {
return Promise.reject(errDriverNotAvailable);
}
return driver;
}
execCommand(browserID: BrowserID, payload: string): Promise<any> {
return this.get(browserID).then((driver: Driver) => {
const cmd = parseCommand(payload);
if (cmd.valid) {
try {
if (this.cfg[cmd.action]) {
return Promise.resolve(this.cfg[cmd.action](driver, cmd));
}
} catch(e) {
return Promise.reject(e);
}
return Promise.reject(new Error('action not defined'));
}
return Promise.reject(new Error('action was invalid'));
});
}
}
export const driverManager = new DriverManager();
|
9619554d3f77deb2e250a717ad70c41fe1f1188b
|
TypeScript
|
gijoona/sm-backend
|
/src/category/category.service.ts
| 2.53125
| 3
|
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize";
import { Category } from "./models/category.model";
@Injectable()
export class CategoryService {
constructor(@InjectModel(Category) private categoryModel: typeof Category) {}
async findAll(): Promise<Category[]> {
return this.categoryModel.findAll();
}
findOne(code: string): Promise<Category> {
return this.categoryModel.findOne({
where: {
code,
}
})
}
async create(category: Category): Promise<Category> {
return this.categoryModel.create(category);
}
async createList(categorys: Category[]): Promise<Category[]> {
return this.categoryModel.bulkCreate(categorys);
}
async update(category: Category): Promise<[number, Category[]]> {
return this.categoryModel.update(category, { where: { code: category.code } });
}
async delete(code: string): Promise<void> {
const category = await this.findOne(code);
await category.destroy();
}
}
|
220513ddd56a025334a9bc7c825400401ce0147e
|
TypeScript
|
azlam-abdulsalam/sfpowerscripts
|
/packages/sfp-cli/src/types/SfpProjectConfig.ts
| 2.96875
| 3
|
import { WorkItem } from './WorkItem';
export class SfpProjectConfig {
name?: string;
defaultBranch?: string;
defaultDevHub?: string;
defaultPool?: string;
workItems?: any;
repoProvider?: string;
public getWorkItemGivenBranch(branch: string): WorkItem {
if (this.workItems) {
for (const id of Object.keys(this.workItems)) {
if (this.workItems[id]['branch']?.toLowerCase() === branch.toLowerCase()) return this.workItems[id];
}
} else return undefined;
}
/**
* De-serialize JSON object into SfpProjectConfig
* @param jsonObj
* @returns
*/
static toInstance(jsonObj: any): SfpProjectConfig {
if (typeof jsonObj !== 'object') throw new Error('toInstance takes an object as an input');
const sfpProjectConfig = new SfpProjectConfig();
for (var propName in jsonObj) {
sfpProjectConfig[propName] = jsonObj[propName];
}
return sfpProjectConfig;
}
/**
* Checks whether instance of SfpProjectConfig is valid
* @returns
*/
public static isValid(sfpProjectConfig: SfpProjectConfig): boolean {
return !!sfpProjectConfig.name;
}
}
|
34a3d7e89439fad77c47ba141c1ae665745c5be4
|
TypeScript
|
artziom/PongPongWebGL
|
/src/scripts/Entity.ts
| 3.375
| 3
|
import * as PIXI from "pixi.js";
import {Vector2D} from "./utils/Vector2D";
export class Entity {
private readonly container: PIXI.Container;
private readonly name: string;
private readonly speed: number;
private readonly isMoving: {
up: boolean;
down: boolean;
left: boolean;
right: boolean;
}
private readonly startPosition: Vector2D;
constructor(name: string, speed: number, position: Vector2D, size: Vector2D) {
this.name = name;
this.speed = speed;
this.isMoving = {
down: false,
up: false,
left: false,
right: false
};
this.container = new PIXI.Container();
const ball = new PIXI.Graphics();
ball.beginFill(0xFFFFFF);
ball.drawRect(0, 0, size.x, size.y);
ball.endFill();
this.container.position.set(position.x, position.y);
this.startPosition = position;
this.container.addChild(ball);
}
public getName():string{
return this.name;
}
public getContainer(): PIXI.Container {
return this.container;
}
public setPosition(x: number, y: number): void {
this.container.position.set(x, y);
}
public getPosition() {
return this.container.position;
}
public setMove(direction: "up" | "down" | "left" | "right", isMoving: boolean) {
this.isMoving[direction] = isMoving;
}
public resetPosition(): void{
this.setPosition(this.startPosition.x, this.startPosition.y);
}
public getMove(): {
up: boolean;
down: boolean;
left: boolean;
right: boolean;
}{
return this.isMoving;
}
public getNextBounds(): PIXI.Rectangle {
const velocity = new Vector2D(0, 0);
if (this.isMoving.up) {
velocity.y = -this.speed;
}
if (this.isMoving.down) {
velocity.y = this.speed;
}
if (this.isMoving.left) {
velocity.x = -this.speed;
}
if (this.isMoving.right) {
velocity.x = this.speed;
}
const rect = new PIXI.Rectangle();
rect.x = this.getPosition().x + velocity.x;
rect.y = this.getPosition().y + velocity.y;
rect.width = this.getBounds().width;
rect.height = this.getBounds().height;
return rect;
}
public update(): void {
const velocity = new Vector2D(0, 0);
if (this.isMoving.up) {
velocity.y = -this.speed;
}
if (this.isMoving.down) {
velocity.y = this.speed;
}
if (this.isMoving.left) {
velocity.x = -this.speed;
}
if (this.isMoving.right) {
velocity.x = this.speed;
}
this.setPosition(this.getPosition().x + velocity.x, this.getPosition().y + velocity.y);
}
public getBounds(){
return this.container.getBounds();
}
}
|
bf7d9bcab6abdd72e21a4d453cf443d40c299ba1
|
TypeScript
|
ahrjarrett/monorail
|
/dist/sharedHelpers/fp-ts-ext/Record.d.ts
| 3.28125
| 3
|
import { Ord } from 'fp-ts/lib/Ord';
/**
* Retrieves the keys of an object while retaining keyof type information
*/
export declare const keys: <A extends Record<string, unknown>, K extends keyof A>(x: A) => K[];
export declare const values: <A extends Record<string, unknown>, V extends A[keyof A]>(x: A) => V[];
/**
* Retrieves the value of a given property key from an object (curried)
*/
export declare const prop: <A extends Record<string, unknown>, K extends keyof A>(k: K) => (obj: A) => A[K];
/**
* Omits the key-value pairs from an object associated with the provided keys
*/
export declare const omit: <A extends Record<string, unknown>, K extends keyof A>(rec: A, ks: K[]) => { [P in Exclude<keyof A, K>]: A[P]; };
/**
* Picks the key-value pairs from an object associated with the provided keys
*/
export declare const pick: <A extends Record<string, unknown>, K extends keyof A>(rec: A, ks: K[]) => { [P in K]: A[P]; };
export declare const sortRecords: <S extends Record<K, A>, K extends keyof S & string, A extends S[K]>(ord: Ord<S>) => <T extends S>(data: T[]) => T[];
/**
* Type guard for `Record<PropertyKey, T>` from `object`
*/
export declare const isRecord: <T = unknown>(x: unknown) => x is Record<string | number | symbol, T>;
/**
* Check if a record is *not* empty
*/
export declare const isNotEmpty: <K extends string | number | symbol, T>(r: Record<K, T>) => boolean;
|