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
|
|---|---|---|---|---|---|---|
7bc11136cef9ff5fe073d5b8ab825d114e3fe7ad
|
TypeScript
|
ORCID/orcid-angular
|
/src/app/shared/pipes/contributors-pipe/contributors.pipe.ts
| 2.546875
| 3
|
import { Pipe, PipeTransform } from '@angular/core'
import { Contributor } from 'src/app/types'
import { RolesAndSequences } from '../../../types/common.endpoint'
import {
Role,
ContributionRoles,
_LEGACY_ContributionRoles,
} from '../../../types/works.endpoint'
@Pipe({
name: 'contributorsPipe',
})
export class ContributorsPipe implements PipeTransform {
transform(contributor: Contributor, args?: any): string {
let value = ''
if (contributor) {
if (
contributor.rolesAndSequences !== undefined &&
contributor.rolesAndSequences.length > 0
) {
contributor.rolesAndSequences.forEach((roleAndSequence, index) => {
value = this.addRoleAndSequence(
value,
roleAndSequence,
contributor.rolesAndSequences.length,
index
)
})
} else {
if (contributor.contributorRole && contributor.contributorRole.value) {
value = this.getContributionRoleByKey(
contributor.contributorRole.value.toLowerCase()
).translation
}
if (
contributor.contributorSequence &&
contributor.contributorSequence.value
) {
value =
this.addColon(value) +
contributor.contributorSequence.value.toLowerCase()
}
}
if (value?.length > 0) {
value = '(' + value
if (contributor?.orcid || contributor?.contributorOrcid?.path) {
if (!value.endsWith(', ')) {
value = value + ','
}
} else {
value = value + ')'
}
}
}
return value
}
private addComma(str: string): string {
if (str?.length > 0) {
return str + ', '
}
return str
}
private addColon(str: string): string {
if (str?.length > 0) {
return str + ': '
}
return str
}
private addRoleAndSequence(
value: string,
roleAndSequence: RolesAndSequences,
length: number,
index: number
): string {
const sequence = roleAndSequence?.contributorSequence?.toLowerCase()
const roleKey = roleAndSequence?.contributorRole?.toLowerCase()
let role = roleKey
if (roleKey) {
role = this.getContributionRoleByKey(role)?.translation
}
if (role && sequence) {
return (
value +
this.addColon(role) +
(length - 1 === index ? sequence : this.addComma(sequence))
)
} else if (sequence && !role) {
return this.addSingleValue(value, sequence, length, index)
} else if (role && !sequence) {
return this.addSingleValue(value, role, length, index)
}
return value
}
private addSingleValue(
value: string,
roleSequence: string,
length: number,
index: number
): string {
return length - 1 === index
? value + roleSequence
: value + this.addComma(roleSequence)
}
private getContributionRoleByKey(key: string): Role {
return (
ContributionRoles.find((role) => role.key === key) ||
_LEGACY_ContributionRoles.find((role) => role.key === key)
)
}
}
|
61062bc7ca75a4866084b77edafd999b51f9974e
|
TypeScript
|
Shin-Ogata/fieldwork
|
/packages/extension/template-bridge/tests/unit/tools.ts
| 2.53125
| 3
|
import {
TemplateResult,
html,
render,
} from '@cdp/extension-template';
import { dom, DOM } from '@cdp/dom';
export { DOM };
const body = document.body;
class TestCustomElement extends HTMLElement {
private readonly _root: ShadowRoot;
constructor() {
super();
this._root = this.attachShadow({ mode: 'open' });
// this._root.innerHTML = `<div class="shadow-div"></div>`;
}
get root(): ShadowRoot {
return this._root;
}
}
customElements.define('test-custom', TestCustomElement);
function createTestElementsFromTemplate(): HTMLElement[] {
const divs = dom.utils.elementify(`<div id="d1" class="test-dom"></div>`);
return divs;
}
function prepareTestElements(divs?: HTMLElement[]): HTMLElement[] {
divs = divs ?? createTestElementsFromTemplate();
const fragment = document.createDocumentFragment();
for (const div of divs) {
fragment.appendChild(div);
}
body.appendChild(fragment);
return divs;
}
function cleanupTestElements(): void {
const divs = body.querySelectorAll('.test-dom');
for (const div of divs) {
body.removeChild(div);
}
}
export function prepare(): DOM {
prepareTestElements();
const $dom = dom('#d1');
const createCustom = (): TemplateResult => html`<test-custom class="custom"></test-custom>`;
render(createCustom(), $dom[0]);
return dom(($dom.find('.custom')[0] as TestCustomElement).root) as unknown as DOM;
}
export function cleanup(): void {
cleanupTestElements();
}
export const stripExpressionMarkers = (html: string): string => html.replace(/<!--\?lit\$[0-9]+\$-->|<!--\??-->|lit\$[0-9]+\$/g, '');
export const innerHTML = (dom: DOM): string => stripExpressionMarkers(dom[0].innerHTML).trim();
|
e686548751f24f5a407e9a4c4ac712ff4ae2f8de
|
TypeScript
|
pnpm/pnpm
|
/config/matcher/src/index.ts
| 3.34375
| 3
|
import escapeStringRegexp from 'escape-string-regexp'
type Matcher = (input: string) => boolean
type MatcherWithIndex = (input: string) => number
export function createMatcher (patterns: string[] | string): Matcher {
const m = createMatcherWithIndex(Array.isArray(patterns) ? patterns : [patterns])
return (input) => m(input) !== -1
}
interface MatcherFunction {
match: Matcher
ignore: boolean
}
export function createMatcherWithIndex (patterns: string[]): MatcherWithIndex {
switch (patterns.length) {
case 0: return () => -1
case 1: return matcherWhenOnlyOnePatternWithIndex(patterns[0])
}
const matchArr: MatcherFunction[] = []
let hasIgnore = false
let hasInclude = false
for (const pattern of patterns) {
if (isIgnorePattern(pattern)) {
hasIgnore = true
matchArr.push({ ignore: true, match: matcherFromPattern(pattern.substring(1)) })
} else {
hasInclude = true
matchArr.push({ ignore: false, match: matcherFromPattern(pattern) })
}
}
if (!hasIgnore) {
return matchInputWithNonIgnoreMatchers.bind(null, matchArr)
}
if (!hasInclude) {
return matchInputWithoutIgnoreMatchers.bind(null, matchArr)
}
return matchInputWithMatchersArray.bind(null, matchArr)
}
function matchInputWithNonIgnoreMatchers (matchArr: MatcherFunction[], input: string): number {
for (let i = 0; i < matchArr.length; i++) {
if (matchArr[i].match(input)) return i
}
return -1
}
function matchInputWithoutIgnoreMatchers (matchArr: MatcherFunction[], input: string): number {
return matchArr.some(({ match }) => match(input)) ? -1 : 0
}
function matchInputWithMatchersArray (matchArr: MatcherFunction[], input: string): number {
let matchedPatternIndex = -1
for (let i = 0; i < matchArr.length; i++) {
const { ignore, match } = matchArr[i]
if (ignore) {
if (match(input)) {
matchedPatternIndex = -1
}
} else if (matchedPatternIndex === -1 && match(input)) {
matchedPatternIndex = i
}
}
return matchedPatternIndex
}
function matcherFromPattern (pattern: string): Matcher {
if (pattern === '*') {
return () => true
}
const escapedPattern = escapeStringRegexp(pattern).replace(/\\\*/g, '.*')
if (escapedPattern === pattern) {
return (input: string) => input === pattern
}
const regexp = new RegExp(`^${escapedPattern}$`)
return (input: string) => regexp.test(input)
}
function isIgnorePattern (pattern: string): boolean {
return pattern.startsWith('!')
}
function matcherWhenOnlyOnePatternWithIndex (pattern: string): MatcherWithIndex {
const m = matcherWhenOnlyOnePattern(pattern)
return (input) => m(input) ? 0 : -1
}
function matcherWhenOnlyOnePattern (pattern: string): Matcher {
if (!isIgnorePattern(pattern)) {
return matcherFromPattern(pattern)
}
const ignorePattern = pattern.substring(1)
const m = matcherFromPattern(ignorePattern)
return (input) => !m(input)
}
|
26febc7d590e758ca2a1818c2ac25420d9c05a40
|
TypeScript
|
xi-cygni/wits-currency-trading-platform
|
/src/logic/helpers/generatePrice.ts
| 2.875
| 3
|
export const generatePrice = (oldPrice: number, volatility: number = .1): number => {
const rnd = Math.random();
let changePercent = 2 * volatility * rnd;
if (changePercent > volatility) {
changePercent -= (2 * volatility);
}
return Math.max(0, oldPrice * (1 + changePercent));
};
|
41b29668559de4b3d23cb0aeceab7dbf4b85311b
|
TypeScript
|
brainthinks/reddit-service-backend
|
/src/lib/schemas/fields.ts
| 2.515625
| 3
|
import {
SchemaField,
SchemaFields,
} from '../../types';
export const RecordAuditFields: SchemaFields = {
actor: {
name: 'actor',
title: 'Actor',
description: 'user who took the action',
type: 'reference',
reference: 'User',
required: true,
},
at: {
name: 'at',
title: 'At',
description: 'time at which the action was taken',
type: 'timestamp',
required: true,
},
message: {
name: 'message',
title: 'Audit Message',
description: 'plain text field with a message regarding the action',
type: 'string',
required: true,
},
};
export const CreatedAtField: SchemaField = {
name: 'createdAt',
title: 'Created At',
description: 'when the record was created and by whom',
type: 'fields',
fields: RecordAuditFields,
required: true,
};
export const UpdatedAtField: SchemaField = {
name: 'updatedAt',
title: 'Updated At',
description: 'when the record was last updated and by whom',
type: 'fields',
fields: RecordAuditFields,
required: true,
};
|
9cd48ec32c2daf56cf85ee3b41f0f1e79094566d
|
TypeScript
|
portabled/portabled
|
/persistence/tests/dom/base64Encoding.ts
| 2.625
| 3
|
namespace tests.dom.base64Encoding {
export function generateTests() {
return {
parseBase64,
parseBase64Star
};
/*
fileContentBase64: data(' /path.txt [base64]\nYmFzZTY0', '/path.txt', 'base64'),
fileContentBase64Star: data(' /path.txt [base64]\n*YmFzZTY0', '/path.txt', 'base64')
*/
function parseBase64() {
var html = '<!doctype html>'+
'<html><head><title>Dummy page</title></head>'+
'<body>'+
'<!-- total 12Mb, saved 4 Apr 2016 -->'+
'<!-- /path.txt [base64]\nYmFzZTY0-->'+
'</body>'+
'</html>';
var dt = persistence.parseHTML(html);
assert.equal(1024*1024*12, dt.totals.size);
assert.equal(1459724400000, dt.totals.timestamp);
assert.equal(1, dt.files.length);
assert.equal('/path.txt', dt.files[0].path);
assert.equal('base64', dt.files[0].content);
}
function parseBase64Star() {
var html = '<!doctype html>'+
'<html><head><title>Dummy page</title></head>'+
'<body>'+
'<!-- total 12Mb, saved 4 Apr 2016 -->'+
'<!-- /path.txt [base64]\n*YmFzZTY0-->'+
'</body>'+
'</html>';
var dt = persistence.parseHTML(html);
assert.equal(1024*1024*12, dt.totals.size);
assert.equal(1459724400000, dt.totals.timestamp);
assert.equal(1, dt.files.length);
assert.equal('/path.txt', dt.files[0].path);
var expectedContentStr = 'base64';
var expectedContent: number[] = [];
for (var i = 0; i < expectedContentStr.length; i++) {
expectedContent.push(expectedContentStr.charCodeAt(i));
}
var actualContent: number[] = [];
var actualContentSrc = dt.files[0].content;
for (var i = 0; i < actualContentSrc.length; i++) {
actualContent.push(actualContentSrc[i] as any);
}
assert.equal(expectedContent.join(','), actualContent.join(','));
}
}
}
|
afd4f4ce3590bd7ea405e1ef84c6e9262fb7759d
|
TypeScript
|
Happy-Ferret/firefox-addons-sdk.d.ts
|
/src/app.ts
| 2.625
| 3
|
/// <reference path="../ts.d/node.d.ts"/>
export = AsdkTypedApp;
import fs = require('fs');
import event = require('events');
import os = require('os');
import cluster = require('cluster');
import path = require('path');
/**
*
*/
class AsdkTypedApp extends event.EventEmitter {
private running: boolean = false;
private nextWorker: number = 0;
private pendingItems: number = 0; // Items, pending processing
private outputFile: number = -1;
/**
* Initializes the instance with given SDK path, output path,
* number of worker processes, and a timeout (in milliseconds) to start
* those workers up.
*/
constructor(private sdkpath: string,
private outpath: string,
private workers: number = os.cpus.length,
private workersOnlineTimeoutMs: number = 1000) {
super();
if(!fs.existsSync(this.sdkpath)) {
throw "'" + this.sdkpath + "' does not exist";
}
this.on('start-processing', this.process.bind(this));
}
run(): void {
var onlineWorkers: number = 0;
if(this.running) {
return;
}
cluster.setupMaster({
exec: './js/worker.js',
args: [this.sdkpath],
silent: true
});
setTimeout(() => {
if(onlineWorkers > 0) {
// At least some came up online, continuing then
this.emit('start-processing');
} else {
this.emit('end', {type: 'error', data: 'Failed to start workers'});
}
}, this.workersOnlineTimeoutMs);
cluster.on('online', () => ++onlineWorkers);
cluster.on('disconnect', (w) => {
--onlineWorkers;
if(onlineWorkers <= 0) {
this.emit('end', {type: 'error', data: 'All workers exited.'});
}
});
// Spawn workers
for(var i = 0; i < this.workers; ++i) {
cluster.fork().on('worker-result',
this.workerReturnedResult.bind(this));
}
}
private process(): void {
// Open/create output file
fs.open(this.outpath, 'w', (err, fd) => {
if(err) {
this.emit('end', {
type: 'error',
data: 'Failed to open output file: ' + this.outpath
});
return;
}
this.outputFile = fd;
this.processDir(this.sdkpath);
});
// Signal workers to start processing
Object.keys(cluster.workers).forEach((id) => cluster.workers[id].send({
type: 'start-processing'
}));
}
private processDir(dir: string): void {
fs.readdir(dir, (err, files) => {
var i: number, fullName: string;
if(err) {
this.emit('error', {data: err});
return;
}
for(i = 0; i < files.length; ++i) {
fullName = path.resolve(dir, files[i]);
fs.stat(fullName, (err, stats) => {
if(stats.isDirectory()) {
this.processDir(fullName);
return;
}
++this.pendingItems;
this.getWorker().send({type: 'errand', fileName: fullName});
});
}
});
}
private workerReturnedResult(result: {err: string; result: NodeBuffer}): void {
--this.pendingItems;
if(result.err) {
this.emit('error', {data: 'Worker returned error: ' + result.err});
} else {
fs.writeSync(this.outputFile, result.result, 0,
result.result.length, null);
}
if(this.pendingItems <= 0) {
fs.closeSync(this.outputFile);
this.emit('end');
}
}
private getWorker(): cluster.Worker {
var workerIds = Object.keys(cluster.workers);
if(this.nextWorker >= workerIds.length) {
this.nextWorker = 0;
}
return cluster.workers[this.nextWorker++];
}
}
|
71bd0e87049ad195d1253689a1246f0b4767dcdf
|
TypeScript
|
thruthesky/firebase-backend
|
/functions/src/modules/user/user.router.ts
| 2.796875
| 3
|
// import * as admin from 'firebase-admin';
// import { Request, Response } from 'express';
import * as E from '../core/error';
import { Base } from './../core/base';
import { User, USER_DATA, USER_REGISTER } from './user';
import { ROUTER_RESPONSE } from '../core/core';
import { Library as _ } from './../library/library';
export class UserRouter extends User {
constructor() {
super();
return;
}
/**
* Returns false if there is no error.
* Otherwise ErrorObject will be returned.
*
* @todo validate more on user data.
*/
validateUserData(p: USER_DATA): ROUTER_RESPONSE | boolean {
/// User's UID is not acceptable for real production site.
/// It is only available with unit-test.
if (p.uid !== void 0) {
if (this.checkUIDFormat(p.uid)) return this.error(this.checkUIDFormat(p.uid));
}
/**
* Check gender format.
*/
if (p.gender !== void 0 && p.gender) {
if (p.gender !== 'M' && p.gender !== 'F') return this.error(E.WRONG_GENDER);
}
return false;
}
/**
*
* This registers(creates) a user authenticatoin whose `uid` is same as email address.
*
*
* @return ROUTER_RESPONSE
*
* - On success, `uid` that is same as the user's email will be returned in `data` field of the response.
*/
async register(): Promise<any> {
// @todo check email, password, name, etc.
const user = this.sanitizeData( this.params );
if ( _.isEmpty(user.email) ) return this.error( E.NO_EMAIL );
if ( _.isEmpty(user.password) ) return this.error( E.NO_PASSWORD );
const data: USER_REGISTER = {
uid: user.email, // No good for security. Make it optinal.
email: user.email,
password: user.password
};
if ( user.displayName !== void 0 ) data.displayName = user.displayName;
if ( user.phoneNumber !== void 0 ) data.phoneNumber = user.phoneNumber;
if ( user.photoURL !== void 0 ) data.photoURL = user.photoURL;
return await this.auth.createUser(this.sanitizeData(data))
.then( newUser => {
delete user.password;
this.loginUid = newUser.uid;
Base.params = user;
return this.set();
})
.catch(e => this.error(e));
}
/**
* Creates a doc under users collection.
*
* @desc When a user sets his profile data, it is more likely the user is registering.
* - `set()` will erase all the data in the document and set it.
*
* @desc All the users must register with `Firebase Authentication` and login before this method.
* So, we do not need to do check the user's authencation or login here.
*
* @desc Anonymous users may enter this method.
*
*
*
* @desc This is an interface. It shouldn't have parameters. If you are sure what you are doing, you can call like below.
* @code
* this.loginUid = newUser.uid;
Base.params = user;
return this.set();
*
*/
async set(): Promise<ROUTER_RESPONSE | boolean> {
// console.log("UserRouter::set() collection name: ", this.collectionName );
if (this.isAnonymous()) return this.error(E.ANONYMOUS_CANNOT_EDIT_PROFILE);
//
if (this.validateUserData(this.params)) return this.validateUserData(this.params);
const params = this.hook('user.router.set', this.params);
if (this.isErrorObject(params)) return params;
// console.log("Goint to set with UID: " + this.loginUid);
// console.log("Data: ", this.params);
// new code
return await super.set( params, this.loginUid);
}
/**
* Update user document. It will only update with the properties of input.
*
* @desc User authentication must be done before this method. ( It is done in verifiyUser() )
* @desc You have option to set or update user data.
* - If you are going to update, the user data previously set will be updated and unchanged properties will be remain as they are.
* - If you want to reset the document, then use `set()`
*
* @return this.loginUid
*/
async update(): Promise<ROUTER_RESPONSE | boolean> {
// console.log("UserRouter::update() collection name: ", this.collectionName );
if (this.isAnonymous()) return this.error(E.ANONYMOUS_CANNOT_EDIT_PROFILE);
if (this.validateUserData(this.params)) return this.validateUserData(this.params);
return await super.update(this.hook('user.router.update', this.params), this.loginUid);
}
/**
* Returns user data.
*
* @desc Anonymous may enter this method and get the anonymous data. We allow Anonymous to get data for the basic functionality and activities.
*
* @desc One important notice is that if the document for that `this.loginUid` does not exists,
* whether it is a `wrong uid` or `correct uid` is given,
* it will create a new user documentation for that wrong uid.
* This is because somehow it may happens that user has a record in 'Authentication' but not in 'users' collection.
* There may be an Internet interruption or system rebooting.
*
*/
async get() {
return await super.get();
}
/**
* Deletes a user document/data in users collection.
*
* @desc doc.delete() returns deletion timestamp even if the document is not existing.
*
*
*/
async delete(): Promise<ROUTER_RESPONSE> {
if (this.isAnonymous()) return this.error(E.ANONYMOUS_CANNOT_EDIT_PROFILE);
// if ( ! this.loginUid ) return this.error( E.USER_NOT_LOGIN ); // On Unit Test, it will be set with `uid`
// return await super.delete(this.loginUid); // this will delete the current user
return await super.delete(this.params.uid); // deletes selected user. They can pass their current ID if they want to delete current account.
}
}
|
a6553a9f11f8835ce0cefc0db3dd5f3cbf411eae
|
TypeScript
|
swc-project/swc
|
/crates/swc_ecma_transforms_base/tests/ts-resolver/tsc/computed/property/name/11/output.ts
| 2.671875
| 3
|
var s__2: string;
var n__2: number;
var a__2: any;
var v__2 = {
get [s__2] () {
return 0;
},
set [n__2] (v__4){},
get [s__2 + s__2] () {
return 0;
},
set [s__2 + n__2] (v__7){},
get [+s__2] () {
return 0;
},
set [""] (v__10){},
get [0] () {
return 0;
},
set [a__2] (v__13){},
get [<any>true] () {
return 0;
},
set [`hello bye`] (v__16){},
get [`hello ${a__2} bye`] () {
return 0;
}
};
|
50069f9cf654e7c5eeed3598b32d75a7b971db13
|
TypeScript
|
Log234/AI960-Client
|
/src/app/Layout/LayoutContainer.ts
| 2.515625
| 3
|
import * as io from "socket.io-client";
import { RootState } from "app/reducers";
import { Layout } from "app/Layout/Layout";
import { connect } from "react-redux";
import { LayoutActionTypes } from "app/Layout/LayoutActions";
function mapStateToProps(state: RootState) {
return {};
}
const mapDispatchToProps = (dispatch: any) =>
({
initialize(): void {
console.log(`Connecting...`);
const socket = io.connect("http://localhost:8000");
console.log(`Connected!`);
dispatch({
type: LayoutActionTypes.SetSocket,
socket
});
socket.on('sendPosition', (data: string) => {
console.log(`Position received: ${data}`);
dispatch({
type: LayoutActionTypes.SetPosition,
position: data
});
})
}
});
const LayoutContainer = connect(mapStateToProps, mapDispatchToProps)((Layout) as any);
export default LayoutContainer;
|
d779365a03afe51dd0b6603f59058005329b1210
|
TypeScript
|
JustinStephenson/leetcode-solutions
|
/Typescript/Problems/Valid_Palindrome.ts
| 3.734375
| 4
|
function isPalindrome(s: string): boolean {
s = s.toLowerCase();
s = s.replace(/[^a-zA-Z\d]/g, '');
let result: boolean = true;
let endPointer: number = s.length - 1;
for (let i = 0; i < s.length / 2; i++) {
if (s[i] !== s[endPointer]) {
result = false;
break;
}
endPointer--;
}
return result;
}
|
e5ec82c1a6dd1981eeaa38a3f18bef93758a8489
|
TypeScript
|
jtenner/as-pect
|
/packages/core/src/transform/createAddReflectedValueKeyValuePairsMember.ts
| 3.03125
| 3
|
import {
AssertionKind,
BlockStatement,
ClassDeclaration,
CommonFlags,
FieldDeclaration,
MethodDeclaration,
NodeKind,
ParameterKind,
Range,
Statement,
Token,
TypeNode,
} from "./assemblyscript";
import { createGenericTypeParameter } from "./createGenericTypeParameter";
import { djb2Hash } from "./hash";
/**
* Create a prototype method called __aspectAddReflectedValueKeyValuePairs on a given
* ClassDeclaration dynamically.
*
* @param {ClassDeclaration} classDeclaration - The target classDeclaration
*/
export function createAddReflectedValueKeyValuePairsMember(
classDeclaration: ClassDeclaration,
): MethodDeclaration {
const range = classDeclaration.name.range;
// __aspectAddReflectedValueKeyValuePairs(reflectedValue: i32, seen: Map<usize, i32>, ignore: StaticArray<i64>): void
return TypeNode.createMethodDeclaration(
TypeNode.createIdentifierExpression(
"__aspectAddReflectedValueKeyValuePairs",
range,
),
null,
CommonFlags.PUBLIC |
CommonFlags.INSTANCE |
(classDeclaration.isGeneric ? CommonFlags.GENERIC_CONTEXT : 0),
null,
TypeNode.createFunctionType(
[
// reflectedValue: i32
TypeNode.createParameter(
ParameterKind.DEFAULT,
TypeNode.createIdentifierExpression("reflectedValue", range),
createGenericTypeParameter("i32", range),
null,
range,
),
// seen: Map<usize, i32>
TypeNode.createParameter(
ParameterKind.DEFAULT,
TypeNode.createIdentifierExpression("seen", range),
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("Map", range),
[
createGenericTypeParameter("usize", range),
createGenericTypeParameter("i32", range),
],
false,
range,
),
null,
range,
),
// ignore: i64[]
TypeNode.createParameter(
ParameterKind.DEFAULT,
TypeNode.createIdentifierExpression("ignore", range),
// Array<i64> -> i64[]
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("StaticArray", range),
[createGenericTypeParameter("i64", range)],
false,
range,
),
null,
range,
),
],
// : void
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("void", range),
[],
false,
range,
),
null,
false,
range,
),
createAddReflectedValueKeyValuePairsFunctionBody(classDeclaration),
range,
);
}
/**
* Iterate over a given ClassDeclaration and return a block statement that contains the
* body of a supposed function that reports the key value pairs of a given class.
*
* @param {ClassDeclaration} classDeclaration - The class declaration to be reported
*/
function createAddReflectedValueKeyValuePairsFunctionBody(
classDeclaration: ClassDeclaration,
): BlockStatement {
const body = new Array<Statement>();
const range = classDeclaration.name.range;
const nameHashes = new Array<number>();
// for each field declaration, generate a check
for (const member of classDeclaration.members) {
// if it's an instance member, regardless of access modifier
if (member.is(CommonFlags.INSTANCE)) {
switch (member.kind) {
// field declarations automatically get added
case NodeKind.FIELDDECLARATION: {
const fieldDeclaration = <FieldDeclaration>member;
const hashValue = djb2Hash(member.name.text);
pushKeyValueIfStatement(
body,
member.name.text,
hashValue,
fieldDeclaration.range,
);
nameHashes.push(hashValue);
break;
}
// function declarations can be getters, check the get flag
case NodeKind.METHODDECLARATION: {
if (member.is(CommonFlags.GET)) {
const methodDeclaration = <MethodDeclaration>member;
const hashValue = djb2Hash(member.name.text);
pushKeyValueIfStatement(
body,
member.name.text,
hashValue,
methodDeclaration.range,
);
nameHashes.push(hashValue);
}
break;
}
}
}
}
// call into super first after all the property checks have been added
body.unshift(createIsDefinedIfStatement(nameHashes, range));
return TypeNode.createBlockStatement(body, range);
}
/**
* Create an isDefined() function call with an if statement to prevent calls to
* super where they should not be made.
*
* @param {number[]} nameHashes - The array of property names to ignore in the children
* @param {Range} range - The reporting range of this statement
*/
function createIsDefinedIfStatement(
nameHashes: number[],
range: Range,
): Statement {
// if (isDefined(super.__aspectAddReflectedValueKeyValuePairs))
// super.__aspectAddReflectedValueKeyValuePairs(reflectedValue, seen, StaticArray.concat(ignore, [...] as StaticArray<i64>))
return TypeNode.createIfStatement(
// isDefined(super.__aspectAddReflectedValueKeyValuePairs)
TypeNode.createCallExpression(
TypeNode.createIdentifierExpression("isDefined", range),
null,
[
// super.__aspectAddReflectedValueKeyValuePairs
TypeNode.createPropertyAccessExpression(
TypeNode.createSuperExpression(range),
TypeNode.createIdentifierExpression(
"__aspectAddReflectedValueKeyValuePairs",
range,
),
range,
),
],
range,
),
TypeNode.createBlockStatement(
[
TypeNode.createExpressionStatement(
// super.__aspectAddReflectedValueKeyValuePairs(reflectedValue, seen, StaticArray.concat(ignore, [...] as StaticArray<i64>))
TypeNode.createCallExpression(
TypeNode.createPropertyAccessExpression(
TypeNode.createSuperExpression(range),
TypeNode.createIdentifierExpression(
"__aspectAddReflectedValueKeyValuePairs",
range,
),
range,
),
null,
[
// reflectedValue,
TypeNode.createIdentifierExpression("reflectedValue", range),
// seen,
TypeNode.createIdentifierExpression("seen", range),
// StaticArray.concat(ignore, [...])
TypeNode.createCallExpression(
TypeNode.createPropertyAccessExpression(
TypeNode.createIdentifierExpression("StaticArray", range),
TypeNode.createIdentifierExpression("concat", range),
range,
),
null,
[
TypeNode.createIdentifierExpression("ignore", range),
// [...propNames]
TypeNode.createAssertionExpression(
AssertionKind.AS,
TypeNode.createArrayLiteralExpression(
nameHashes.map((e) =>
TypeNode.createIntegerLiteralExpression(
f64_as_i64(e),
range,
),
),
range,
),
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("StaticArray", range),
[
TypeNode.createNamedType(
TypeNode.createSimpleTypeName("i64", range),
null,
false,
range,
),
],
false,
range,
),
range,
),
],
range,
),
],
range,
),
),
],
range,
),
null,
range,
);
}
/**
* For each key-value pair, we need to perform a runtime check to make sure that this property
* was not overridden in the parent of a given class.
*
* @param {Statement[]} body - The collection of statements for the function body
* @param {string} name - The name of the property
* @param {Range} range - The range for these statements
*/
function pushKeyValueIfStatement(
body: Statement[],
name: string,
hashValue: number,
range: Range,
): void {
body.push(
// if (!ignore.includes("propName")) { ... }
TypeNode.createIfStatement(
TypeNode.createUnaryPrefixExpression(
Token.EXCLAMATION,
// ignore.includes("propName")
TypeNode.createCallExpression(
TypeNode.createPropertyAccessExpression(
TypeNode.createIdentifierExpression("ignore", range),
TypeNode.createIdentifierExpression("includes", range),
range,
),
null,
[
// hashValue
TypeNode.createIntegerLiteralExpression(
f64_as_i64(hashValue),
range,
),
],
range,
),
range,
),
TypeNode.createBlockStatement(
[
createPushReflectedObjectKeyStatement(name, range),
createPushReflectedObjectValueStatement(name, range),
],
range,
),
null,
range,
),
);
}
/**
* Create a function call to __aspectPushReflectedObjectKey to add a key to a given
* reflected value.
*
* @param {string} name - The name of the property
* @param {Range} range - The reange for this function call
*/
function createPushReflectedObjectKeyStatement(
name: string,
range: Range,
): Statement {
// __aspectPushReflectedObjectKey(reflectedValue, Reflect.toReflectedValue("propertyName", seen));
return TypeNode.createExpressionStatement(
TypeNode.createCallExpression(
TypeNode.createIdentifierExpression(
"__aspectPushReflectedObjectKey",
range,
),
null,
[
// reflectedValue
TypeNode.createIdentifierExpression("reflectedValue", range),
// Reflect.toReflectedValue("propertyName", seen)
TypeNode.createCallExpression(
// Reflect.toReflectedValue
TypeNode.createPropertyAccessExpression(
TypeNode.createIdentifierExpression("Reflect", range),
TypeNode.createIdentifierExpression("toReflectedValue", range),
range,
),
null,
[
TypeNode.createStringLiteralExpression(name, range),
TypeNode.createIdentifierExpression("seen", range),
],
range,
),
],
range,
),
);
}
/**
* Create a function call to __aspectPushReflectedObjectValue to add a key to a given
* reflected value.
*
* @param {string} name - The name of the property
* @param {Range} range - The reange for this function call
*/
function createPushReflectedObjectValueStatement(
name: string,
range: Range,
): Statement {
// __aspectPushReflectedObjectValue(reflectedValue, Reflect.toReflectedValue(this.propertyName, seen, ignore.concat([...])));
return TypeNode.createExpressionStatement(
// __aspectPushReflectedObjectValue(reflectedValue, Reflect.toReflectedValue(this.propertyName, seen, ignore.concat([...])))
TypeNode.createCallExpression(
// __aspectPushReflectedObjectValue
TypeNode.createIdentifierExpression(
"__aspectPushReflectedObjectValue",
range,
),
null,
[
// reflectedValue
TypeNode.createIdentifierExpression("reflectedValue", range),
// Reflect.toReflectedValue(this.propertyName, seen))
TypeNode.createCallExpression(
// Reflect.toReflectedValue
TypeNode.createPropertyAccessExpression(
TypeNode.createIdentifierExpression("Reflect", range),
TypeNode.createIdentifierExpression("toReflectedValue", range),
range,
),
null,
[
//this.propertyName
TypeNode.createPropertyAccessExpression(
TypeNode.createThisExpression(range),
TypeNode.createIdentifierExpression(name, range),
range,
),
// seen
TypeNode.createIdentifierExpression("seen", range),
],
range,
),
],
range,
),
);
}
|
f8873a8e155d5f449cd8b4141edc2791ace2206f
|
TypeScript
|
NS-MPaille/todosList
|
/src/app/todo/todo-api.service.ts
| 2.6875
| 3
|
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";
import { delay } from "rxjs/operators";
export interface ITodo {
id: number;
title: string;
description?: string;
completed: boolean;
}
@Injectable({
providedIn: "root",
})
export class TodoApiService {
public todosDb: ITodo[] = [
{
id: 0,
title: "Todo 1",
description: "Todo desc 1",
completed: false,
},
{
id: 1,
title: "Todo 2",
description: "Todo desc 2",
completed: false,
},
{
id: 2,
title: "Todo 3",
description: "Todo desc 3",
completed: false,
},
{
id: 3,
title: "Todo 4",
description: "Todo desc 4",
completed: false,
},
{
id: 4,
title: "Todo 5",
description: "Todo desc 5",
completed: true,
},
{
id: 5,
title: "Todo 6",
description: "Todo desc 6",
completed: true,
},
];
constructor(private http: HttpClient) {}
public getList(): Observable<ITodo[]> {
// return of(this.todosDb).pipe(delay(1000)) //- To test with delay;
return of(this.todosDb);
}
public getTodo(id: number) {
return this.http.get<ITodo>(`todo/${id}`);
}
}
|
fadb913a44f37b1d5be143843c4e5e9145d6e549
|
TypeScript
|
i-codeit/toh-visualize
|
/Server/src/backend.ts
| 3.359375
| 3
|
import { EventInterface } from "./eventInterface";
/**
* Recursive function which saves data (returns) in an array
* depicting the movement of blocks
* @param lenSrc number of blocks
* @param srcTower source Tower
* @param destTower destination tower
* @param auxTower auxilary tower
* @param data array to save data in
*/
export function towerOfHanoi(lenSrc: number, srcTower: string, destTower: string, auxTower: string, data: EventInterface[]) {
// Base cases when length is 0 or 1
if (lenSrc === 0) {
return;
}
else if (lenSrc === 1) {
data.push({blockId: lenSrc, towerFrom: srcTower, towerTo: destTower});
return;
}
towerOfHanoi(lenSrc - 1, srcTower, auxTower, destTower, data);
data.push({blockId: lenSrc, towerFrom: srcTower, towerTo: destTower});
towerOfHanoi(lenSrc - 1, auxTower, destTower, srcTower, data);
}
|
d7574877081f0b97223ae1567096b2c8546093b3
|
TypeScript
|
benforcapita/salad-shop
|
/src/Types/index.ts
| 2.828125
| 3
|
export type StoreType = {
open: boolean;
Items: Array<SaladIngredientsItem>;
amount: number;
}
export type SaladIngredientsItem = {
name: string;
price: number;
amount:number
}
export enum Constants {
OPEN_DRAWER = 'OPEN',
ClOSE_DRAWER = 'ClOSE',
ADD_ITEM = 'ADD',
REMOVE_ITEM = 'REMOVE',
AMOUNT = 'AMOUNT',
}
export type Action =
{ type: Constants.OPEN_DRAWER } |
{ type: Constants.ClOSE_DRAWER } |
{ type: Constants.AMOUNT } |
{ type: Constants.ADD_ITEM,payload:SaladIngredientsItem } |
{ type: Constants.REMOVE_ITEM, payload: number }
|
d409ec058b96526d6695531fec3d7441a3699fd2
|
TypeScript
|
CPqD/inovathon-8
|
/health-front/src/app/services/navigation.service.ts
| 2.625
| 3
|
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
export interface IMenuItem {
id?: string;
title?: string;
description?: string;
type: string; // Possible values: link/dropDown/extLink
name?: string; // Used as display text for item and title for separator type
state?: string; // Router state
icon?: string; // Material icon name
tooltip?: string; // Tooltip text
disabled?: boolean; // If true, item will not be appeared in sidenav.
sub?: IChildItem[]; // Dropdown items
badges?: IBadge[];
active?: boolean;
}
export interface IChildItem {
id?: string;
parentId?: string;
type?: string;
name: string; // Display text
state?: string; // Router state
icon?: string;
sub?: IChildItem[];
active?: boolean;
}
interface IBadge {
color: string; // primary/accent/warn/hex color codes(#fff000)
value: string; // Display text
}
interface ISidebarState {
sidenavOpen?: boolean;
childnavOpen?: boolean;
}
@Injectable({
providedIn: 'root'
})
export class NavigationService {
public sidebarState: ISidebarState = {
sidenavOpen: true,
childnavOpen: false
};
constructor() {
}
defaultMenu: IMenuItem[] = [
{
name: 'Gerenciamento',
description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
type: 'dropDown',
icon: 'i-Check',
sub: [
{ icon: 'i-File-Refresh', name: 'Pendentes', state: '/check-management/outstanding', type: 'link' },
{ icon: 'i-Yes', name: 'Finalizados', state: '/check-management/paid', type: 'link' },
{ icon: 'i-Add', name: 'Novo', state: '/check-management/insert', type: 'link' }
]
}
];
// sets iconMenu as default;
menuItems = new BehaviorSubject<IMenuItem[]>(this.defaultMenu);
// navigation component has subscribed to this Observable
menuItems$ = this.menuItems.asObservable();
// You can customize this method to supply different menu for
// different user type.
// publishNavigationChange(menuType: string) {
// switch (userType) {
// case 'admin':
// this.menuItems.next(this.adminMenu);
// break;
// case 'user':
// this.menuItems.next(this.userMenu);
// break;
// default:
// this.menuItems.next(this.defaultMenu);
// }
// }
}
|
efbf7471f0ede054009197a757b14e7028254aef
|
TypeScript
|
4rtw/sport-wager-front
|
/src/app/shared/services/Utils/custom-operator.ts
| 2.828125
| 3
|
import { defer, Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
export function tapOnce<T>(fn: (value) => void): any {
return (source: Observable<any>) =>
defer(() => {
let first = true;
return source.pipe(
tap<T>((payload) => {
if (first) {
fn(payload);
}
first = false;
})
);
});
}
|
33f183cfce289e3d91f384b4799b432248dfc144
|
TypeScript
|
Solaris5959/Software
|
/src/corner_kick/src/types/state.ts
| 2.609375
| 3
|
/***
* This file specifies the format of the application state
*/
import { ILayer } from './canvas';
import { IROSParam } from './rosParams';
import { IRobotStatus } from './status';
/**
* The application state
*/
export interface IRootState {
canvas: ICanvasState;
thunderbots: IThunderbotsState;
rosParameters: IROSParamState;
ros: IROSState;
robotStatus: IRobotStatusState;
}
/**
* The state object for Canvas
*/
export interface ICanvasState {
layers: { [id: number]: ILayer };
}
/**
* The state object for ROS
*/
export interface IROSState {
status: 'connected' | 'disconnected' | 'error';
errorMessage: string;
}
export interface IThunderbotsState {
playType: string;
playName: string;
tactics: string[];
}
/**
* The ROS settings state
*/
export interface IROSParamState {
[key: string]: IROSParam;
}
/**
* The robot status state
*/
export interface IRobotStatusState {
statuses: { [key: string]: IRobotStatus };
}
|
9ff58d135843f75f684bacba4c19362ff9c9f318
|
TypeScript
|
nknapp/aikido-exam
|
/src/utils/shuffling/shuffle.test.ts
| 2.921875
| 3
|
import { shuffleAndSelect } from "./shuffle";
import shuffle from "lodash/shuffle";
import { Technique } from "../../model/Technique";
import { TechniqueList } from "../../model/TechniqueList";
const mockShuffle = shuffle as jest.MockedFunction<typeof shuffle>;
jest.mock("lodash/shuffle", () => {
return {
__esModule: true,
default: jest.fn(),
};
});
beforeEach(() => {
mockShuffle.mockImplementation((techniques) => techniques);
});
describe("shuffle", () => {
const techniques: TechniqueList = new TechniqueList([
new Technique(["tachi waza", "kata dori", "shiho nage", "ura"]),
new Technique(["suwari waza", "ai hanmi katate dori", "ikkyo", "omote"]),
new Technique(["tachi waza", "kata dori", "irimi nage", "ura"]),
new Technique(["suwari waza", "katate ryote dori", "shiho nage", "ura"]),
new Technique(["suwari waza", "ai hanmi katate dori", "ikkyo", "ura"]),
new Technique(["tachi waza", "kata dori", "shiho nage", "omote"]),
]);
it("shuffles and regroups techniques", () => {
expect(shuffleAndSelect(techniques, { coverage: 1 })).toEqual(
new TechniqueList([
new Technique(["suwari waza", "ai hanmi katate dori", "ikkyo", "omote"]),
new Technique(["suwari waza", "ai hanmi katate dori", "ikkyo", "ura"]),
new Technique(["suwari waza", "katate ryote dori", "shiho nage", "ura"]),
new Technique(["tachi waza", "kata dori", "shiho nage", "ura"]),
new Technique(["tachi waza", "kata dori", "shiho nage", "omote"]),
new Technique(["tachi waza", "kata dori", "irimi nage", "ura"]),
])
);
});
it("only returns the requested coverage of techniques", () => {
expect(shuffleAndSelect(techniques, { coverage: 0.8 })).toEqual(
new TechniqueList([
new Technique(["suwari waza", "ai hanmi katate dori", "ikkyo", "omote"]),
new Technique(["suwari waza", "ai hanmi katate dori", "ikkyo", "ura"]),
new Technique(["suwari waza", "katate ryote dori", "shiho nage", "ura"]),
new Technique(["tachi waza", "kata dori", "shiho nage", "ura"]),
new Technique(["tachi waza", "kata dori", "irimi nage", "ura"]),
])
);
});
});
|
bb4de159f5277f69cb74f42642a613859e27f425
|
TypeScript
|
buroz/web-components-codebase
|
/src/validators/auth.ts
| 2.8125
| 3
|
import { IsNotEmpty, IsEmail, IsString } from "class-validator";
import { RegisterRequest, LoginRequest, ForgotPasswordRequest } from "../_interfaces";
export class AuthLoginForm {
@IsEmail()
public email = "";
@IsNotEmpty({ message: "Please enter your password" })
public password = "";
constructor(request?: LoginRequest) {
if (request) {
this.email = request.email;
this.password = request.password;
}
}
}
export class AuthRegisterForm {
@IsString()
public name = "";
@IsString()
public surname = "";
@IsEmail()
public email = "";
@IsNotEmpty({ message: "Please enter your password" })
public password = "";
@IsNotEmpty({ message: "Please enter your password" })
public passwordAgain = "";
constructor(request?: RegisterRequest) {
if (request) {
this.name = request.name;
this.surname = request.surname;
this.email = request.email;
this.password = request.password;
this.passwordAgain = request.passwordAgain;
}
}
}
export class AuthForgotPasswordForm {
@IsEmail()
public email = "";
constructor(request?: ForgotPasswordRequest) {
if (request) {
this.email = request.email;
}
}
}
|
efac4c8bf3c3a5147461feaab9cedd54da0fedd6
|
TypeScript
|
lukke-dev/tests-with-jest-typescript
|
/src/dip-dependency-inversion/classes/interfaces/customer.spec.ts
| 3.09375
| 3
|
import { IndividualCustomer, EnterpriseCustomer } from './customer';
const createIndividualCustomer = (
firstName: string,
lastName: string,
cpf: string,
): IndividualCustomer => {
return new IndividualCustomer(firstName, lastName, cpf);
};
const createEnterpriseCustomer = (
name: string,
cnpj: string,
): EnterpriseCustomer => {
return new EnterpriseCustomer(name, cnpj);
};
afterEach(() => jest.clearAllMocks());
describe('IndividualCustomer', () => {
it('should have firstName, lastName and cpf', () => {
const sut = createIndividualCustomer('lucas', 'santos', '089.175.989-28');
expect(sut).toHaveProperty('firstName', 'lucas');
expect(sut).toHaveProperty('lastName', 'santos');
expect(sut).toHaveProperty('cpf', '089.175.989-28');
});
it('should have methods to get name and idn for individualCustomer', () => {
const sut = createIndividualCustomer('lucas', 'santos', '089.175.989-28');
expect(sut.getName()).toBe('lucas santos');
expect(sut.getIDN()).toBe('089.175.989-28');
});
});
describe('EnterpriseCustomer', () => {
it('should have name and cnpj', () => {
const sut = createEnterpriseCustomer('EmpresaGigante', '000-33');
expect(sut).toHaveProperty('name', 'EmpresaGigante');
expect(sut).toHaveProperty('cnpj', '000-33');
});
it('shoud have methos to get name and idn for enterpriseCustomer', () => {
const sut = createEnterpriseCustomer('EmpresaGigante', '000-33');
expect(sut.getName()).toBe('EmpresaGigante');
expect(sut.getIDN()).toBe('000-33');
});
});
|
9c521e01c8a72ffa2727649920237f311edad711
|
TypeScript
|
dorshinar/deno-flex
|
/src/args.ts
| 3.234375
| 3
|
import { FlexArgs } from "./types.ts";
/**
* Parse arguments. If args is not an array, or not an array an error is thrown.
* Command name must be separated from the command arguments with "--":
* $ flex start -- Hello
*
* @param args arguments to parse
* @returns parsed arguments.
*/
export function parseArgs(args: string[]): FlexArgs {
if (!Array.isArray(args) || args.length === 0) {
throw new Error("No command specified!");
}
let commandArgs: string[] | undefined;
if (args.length > 0 && args[1] === "--") {
commandArgs = args.slice(2);
}
let flexArgs: FlexArgs = {
command: args[0],
};
if (commandArgs) {
flexArgs = { ...flexArgs, commandArgs };
}
return flexArgs;
}
|
b86f3c7ba50854591738bacdd7978756e9f11c76
|
TypeScript
|
interfacewerk/ng1-decorators
|
/src/decorators/inject.ts
| 2.78125
| 3
|
import {makeInject} from './util';
export function Inject(injected?: string | Object) {
return function (
targetClass: {
constructor: Function & {
injections?: {[injectedString: string] : string},
$inject?: (string | Object)[]
},
},
propertyName: string
) {
injected = injected || propertyName;
targetClass.constructor.injections = targetClass.constructor.injections || {};
targetClass.constructor.injections[makeInject([injected])[0]] = propertyName;
targetClass.constructor.$inject = targetClass.constructor.$inject || [];
targetClass.constructor.$inject.push(injected);
}
}
|
87917faae25b47deb2ca4417a7c98f78a7cf882e
|
TypeScript
|
lywsbcn/Jsocket-ts
|
/jsocketInterface.ts
| 3.09375
| 3
|
/**
* websocket 收到报文后封装的一个数据模型
* 在Jsocket 类中的数据层的基本数据结构
* */
interface JsmInterface {
/**
* 每个请求自动累计一个值,用来判断是否为该请求
* 注意:这个需要服务端的支持
* */
what: number;
/**
* websocket 收到的数据
* 经过 JSON.parse() 处理
* */
original: any;
}
/**
* Jsocket 中回调数据结构
* */
interface JscInterface {
/**
* 该回调所属的对象指针
* */
target: any;
/**
* 默认情况下,回调已经调用将会被删除
* 如果不想被删除,always 设置为true
* */
always: boolean;
/**
* 请求回调
* 当发起请求,服务端回复数据时
* 将会调用该函数
* */
block: (response: any, flag?: number, msg?: string, jsocket?: JsocketInterface) => void;
isLoading?: boolean;
}
/**
*
* */
interface JsEventCallback {
/**
* 该回调所属的对象指针
* */
target: any;
/**
* 默认情况下,回调已经调用将会被删除
* 如果不想被删除,always 设置为true
* */
always: boolean;
/**
* 请求回调
* 当发起请求,服务端回复数据时
* 将会调用该函数
* */
block: (jsocket?: JsocketInterface) => void;
}
/**
* Jsocket 重连接口定义
* */
interface JsconnInterface {
/**是否为用户断开连接 */
userClose: boolean;
/**
* 是否开启重连
* 默认为true;
* */
isReConn: boolean;
/**
* 重连模式
* 0.固定定时模式,每隔reConnInterval秒重连
* 1.累加定时模式,重连的时间是上一次重连时间的2倍
* 当重连时间 大于 reConnIntervalMax 时,
* 重连时间重新从 reConnIntervalMin 开始
*
* 默认为 0;
* */
pattern: number;
/**
* 设置 重连模式
* @param type
*/
setPattern(type: number): void;
/**
* 重连最大的尝试次数
* 如果次数大于该值还未连接成功,则不再重连
* 当 reConnNumber==0 时,表示无限次数重连
*
* 默认为 0;
* */
number: number;
/**
* 当前的重连次数
* 每次开始重连计数+1
* 注意:当连接成功,值重置为 0
* */
currNumber: number;
/**
* 重连间隔时间
* 当reConnPattern==1时,起始值将会被 reConnIntervalMin替换
* 默认为 10000;
* */
interval: number;
/**
* 重连最长间隔时间
* 注意不可以小于 reConnIntervalMin;
* 默认 60;
* */
intervalMax: number;
/**
* 设置 重连最长间隔时间
* @param num
*/
setIntervalMax(num: number): void;
/**
* 当reConnPattern==1时,重连间隔时间的起始时间
* */
intervalMin: number;
/**
* 设置 重连最短时间
* @param num
*/
setIntervalMix(num: number):void;
/**
* 重连定时器
* */
timer: number;
}
/**
* Jsocket 数据源定义
* */
interface JsDataSourceInterface {
/**
* 心跳间隔时间
* */
hbInterval: number;
/**
* 心跳定时器
* */
hbTimer: number;
/**
* 心跳请求包
* */
hbPacket: () => object;
/**
* 设置心跳请求包
* 并启动心跳
* @param packet 心跳请求包
*/
setHbPacket(packet: () => object): void;
/**
* 握手请求包
* */
hsPacket: () => object;
}
/**
* Jsocket 控制台,日志接口定义
* */
interface JslogInterface {
/**
* 服务器标签
* 日志输出时,在前面显示
* */
TAG: string;
/**
* 是否 显示日志
* */
showLog: boolean
/**
* 如果showLog == true
* 请求时 这些action 值不输出
* */
requestFilter: Array<string | number>
/**
* 如果showLog == true
* 回复时, 这些action 值不输出
* */
responseFilter: Array<string | number>
addRequestFilter(...a);
addResponseFilter(...a);
addFilter(...a);
}
/**
* Jsocket 事件模型定义
* */
interface JsEventMInterface {
/**
* websocket 连接成功回调
* */
Connected: Array<JsEventCallback>;
/**
* 添加或者移除 连接成功的回调
* 当 callback ==null 或者未定义时,执行移除操作
* @param target 回调所属对象
* @param callback 回调函数
*/
ConnectAor(target: any, callback?: (jsocket?: JsocketInterface) => void): void;
/**
* websocket 握手成功回调
* */
Handshaked: Array<JscInterface>;
/**
* 添加或者移除 握手成功的回调
* 当 callback ==null 或者未定义时,执行移除操作
* @param target 回调所属对象
* @param callback 回调函数
* @param always 调用后是否不移除 默认:true 表示不移除
*/
HandshakeAor(target: any, callback?: (response: any, flag?: number, msg?: string, jsocket?: JsocketInterface) => void, always?: boolean): void;
/**
* websocket 连接错误回调
* */
Errored: Array<JsEventCallback>;
/**
* 添加或者移除 连接错误的回调
* 当 callback ==null 或者未定义时,执行移除操作
* @param target 回调所属对象
* @param callback 回调函数
*/
ErrorAor(target: any, callback?: (jsocket?: JsocketInterface) => void): void;
/**
* websocket 连接关闭回调
* */
Closed: Array<JsEventCallback>
/**
* 添加或者移除 连接关闭的回调
* 当 callback ==null 或者未定义时,执行移除操作
* @param target 回调所属对象
* @param callback 回调函数
*/
CloseAor(target: any, callback?: (jsocket?: JsocketInterface) => void): void;
/**
* 分组 的 key
* eventMessaged
* eventListener
*
* 默认值为 action
* */
KGroup: string ;
/**
* 回调参数中flag 对应的key
* 默认 flag
* */
KFlag: string;
/**
* 回调参数中msg 对应的key
* 默认 msg
* */
KMsg: string;
/**
* what 参数名称
* 默认 what
* */
KWhat: string;
KAssign: string;
/**
* websocket 收到消息回调
* 该回调不会主动移除
* */
Listener: { [key: string ]: Array<JscInterface> }
/**
* 添加或者移除 收到消息回调
* 该回调不会主动移除
* 当 callback ==null 或者未定义时,执行移除操作
* @param target 回调所属对象
* @param callback 回调函数
*/
//MessageAor(what: number,action: string | number, target: any, callback?: (response: any, flag?: number, msg?: string) => void): void;
/**
* 添加或者移除 收到消息回调
* 该回调会主动移除
* */
Callback: { [key: string]: Array<JscInterface> }
Assign: { [key: string]: JscInterface }
AssignAppend(name, target, callback, isLoading?: boolean);
AssignRemove(name)
/**
* 添加或者移除 收到消息回调
* 该回调会主动移除
* 当 callback ==null 或者未定义时,执行移除操作
* @param target 回调所属对象
* @param callback 回调函数
* @param always always==true,会调用eventMessageAor()
*/
ListenerAor(action: string | number, target: any, callback?: (response: any, flag?: number, msg?: string, jsocket?: JsocketInterface) => void, always?: boolean, isLoading?: boolean): void;
/**移除所有回调事件,不包括Event */
removeAllListener(taget?: any): void
/**移除所有监听事件 */
removeAllEvent(target?: any): void
/**移除所有回调事件,所有监听事件 */
removeAll(target?: any): void
}
interface JsocketInterface {
/**
* websocket 对象
* */
ws: WebSocket
/**
* websocket 连接地址
* */
wsUrl: string;
/**
* 重连配置
* */
conn: JsconnInterface
/**
* 日志配置
* */
log: JslogInterface
/**
* 事件管理
* */
event: JsEventMInterface
/**
* 设置连接地址
* @param host 域名
* @param port 端口
* @param upgroup 协议
*/
setWsUrl(host: string, port?: number, upgroup?: boolean): void;
/**
* 打开websocket 连接
* @param url
*/
open(url?: string): void;
/**
* 关闭websocket连接
* */
close(userClose?: boolean): void;
/**
* 发送请求
* @param taget ==null 表示不添加回调
* @param param 请求的参数
* @param callback 回调
* @param always 回调完成是否删除,默认false表示删除
* @param isLoading 是否显示loading 默认 true
*/
send(taget: any, param: object, callback?: (response: any, flag?: number, msg?: string, jsocket?: JsocketInterface) => void, always?: boolean, isLoading?: boolean): void;
record: {
filter: Array<any>,
request: any,
response: any,
}
addRecordFilter(action: string | number);
addRecordRequst(action, data);
addRecordResponse(action, data);
}
|
77029883b461ddb9d2ad595ceb8a923f969f0d08
|
TypeScript
|
rootulp/exercism
|
/typescript/space-age/space-age.ts
| 3.140625
| 3
|
class SpaceAge {
public seconds: number
private ORBITAL_PERIOD_IN_EARTH_YEARS = Object.freeze({
Mercury: 0.2408467,
Venus: 0.61519726,
Mars: 1.8808158,
Jupiter: 11.862615,
Saturn: 29.447498,
Uranus: 84.016846,
Neptune: 164.79132
})
private SECONDS_IN_EARTH_YEAR = 31557600
constructor(seconds: number) {
this.seconds = seconds
}
private earthYears(): number {
return this.seconds / this.SECONDS_IN_EARTH_YEAR
}
public onEarth(): number {
return SpaceAge.roundToTwoDecimalPlaces(this.earthYears())
}
public onMercury(): number {
return SpaceAge.roundToTwoDecimalPlaces(this.earthYears() / this.ORBITAL_PERIOD_IN_EARTH_YEARS.Mercury)
}
public onVenus(): number {
return SpaceAge.roundToTwoDecimalPlaces(this.earthYears() / this.ORBITAL_PERIOD_IN_EARTH_YEARS.Venus)
}
public onMars(): number {
return SpaceAge.roundToTwoDecimalPlaces(this.earthYears() / this.ORBITAL_PERIOD_IN_EARTH_YEARS.Mars)
}
public onJupiter(): number {
return SpaceAge.roundToTwoDecimalPlaces(this.earthYears() / this.ORBITAL_PERIOD_IN_EARTH_YEARS.Jupiter)
}
public onSaturn(): number {
return SpaceAge.roundToTwoDecimalPlaces(this.earthYears() / this.ORBITAL_PERIOD_IN_EARTH_YEARS.Saturn)
}
public onUranus(): number {
return SpaceAge.roundToTwoDecimalPlaces(this.earthYears() / this.ORBITAL_PERIOD_IN_EARTH_YEARS.Uranus)
}
public onNeptune(): number {
return SpaceAge.roundToTwoDecimalPlaces(this.earthYears() / this.ORBITAL_PERIOD_IN_EARTH_YEARS.Neptune)
}
private static roundToTwoDecimalPlaces(num: number): number {
return Math.round(num * 100) / 100
}
}
export default SpaceAge
|
d1f45058927234e96abb015c334f6b11e6fcf5b9
|
TypeScript
|
pstromberg98/atom-node-debug
|
/lib/v8-protocol/messenger.ts
| 2.8125
| 3
|
import { IResponse } from './interfaces/IResponse';
export default class Messenger {
public events = {};
public callbacks = {};
private seq = 0;
private isOpen = false;
constructor(private socket) {
this.callbacks = {};
socket.onopen = (event) => {
this.isOpen = true;
if (this.events['open']) {
this.events['open'].forEach((cb) => cb());
}
};
socket.onclose = () => {
if (this.events['close']) {
this.events['close'].forEach((cb) => cb());
}
};
socket.onmessage = (message) => {
if (!message) {
return;
}
const data = JSON.parse(message.data);
if (data && this.callbacks[data.id]) {
this.callbacks[data.id](data);
this.callbacks[data.id] = null;
delete this.callbacks[data.id];
}
if (this.events && this.events[data.method]) {
if (this.events[data.method]) {
this.events[data.method].forEach((cb) => cb(data));
}
}
};
}
send(data): Promise<any> {
if (!this.isOpen) {
this.on('open', () => this.send(data)) ;
return;
}
this.seq++;
const seq = this.seq;
data.id = seq;
let outerResolve;
this.callbacks[seq] = (message) => {
if (message) {
outerResolve(message.result);
}
};
this.socket.send(JSON.stringify(data));
return new Promise((resolve, reject) => {
outerResolve = resolve;
});
}
on(event, cb) {
const events = this.events[event];
if (!events) {
this.events[event] = [];
}
this.events[event].push(cb);
}
}
|
de8162168b1ce770da4de0a7e3dd44e3e50a97dc
|
TypeScript
|
Dev-MarkoF/FUDGE
|
/Miscellaneous/Experiments/Jascha/WebEngineCoreStructures/src/Engine/BufferSpecification.ts
| 2.8125
| 3
|
namespace WebEngine{
/**
* Small interface used by Material- and Mesh-classes to store datapullspecifications
* for a WebGLBuffer.
*/
export interface BufferSpecification {
size: number; // The size of the datasample.
dataType: number; // The datatype of the sample (e.g. gl.FLOAT, gl.BYTE, etc.)
normalize: boolean; // Flag to normalize the data.
stride: number; // Number of indices that will be skipped each iteration.
offset: number; // Index of the element to begin with.
}
}
|
a206cb5d9c83a1335b84f53da1bceb6e859ca408
|
TypeScript
|
Nikaple/javascript-obfuscator
|
/src/declarations/threads.d.ts
| 2.53125
| 3
|
declare module 'threads' {
type PostMessage <U> = (data: U) => void;
type SpawnCallback <T, U> = (data: T, postMessage: PostMessage <U>) => void;
type ResponseCallback <U> = (response: U) => void;
class Thread <T, U> {
public killed: boolean;
public send (data: T): Thread <T, U>;
public on (eventType: string, responseCallback: ResponseCallback<U>): Thread <T, U>;
public kill (): void;
}
export function spawn <T, U> (spawnCallback: SpawnCallback <T, U>): Thread <T, U>;
}
|
8e045bd83b9aaf5fa80281a0454ecd6f6e8e71dd
|
TypeScript
|
seanwallawalla-forks/frontend
|
/hassio/src/components/hassio-ansi-to-html.ts
| 2.671875
| 3
|
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
interface State {
bold: boolean;
italic: boolean;
underline: boolean;
strikethrough: boolean;
foregroundColor: null | string;
backgroundColor: null | string;
}
@customElement("hassio-ansi-to-html")
class HassioAnsiToHtml extends LitElement {
@property() public content!: string;
protected render(): TemplateResult | void {
return html`${this._parseTextToColoredPre(this.content)}`;
}
static get styles(): CSSResultGroup {
return css`
pre {
overflow-x: auto;
white-space: pre-wrap;
overflow-wrap: break-word;
}
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
.underline {
text-decoration: underline;
}
.strikethrough {
text-decoration: line-through;
}
.underline.strikethrough {
text-decoration: underline line-through;
}
.fg-red {
color: rgb(222, 56, 43);
}
.fg-green {
color: rgb(57, 181, 74);
}
.fg-yellow {
color: rgb(255, 199, 6);
}
.fg-blue {
color: rgb(0, 111, 184);
}
.fg-magenta {
color: rgb(118, 38, 113);
}
.fg-cyan {
color: rgb(44, 181, 233);
}
.fg-white {
color: rgb(204, 204, 204);
}
.bg-black {
background-color: rgb(0, 0, 0);
}
.bg-red {
background-color: rgb(222, 56, 43);
}
.bg-green {
background-color: rgb(57, 181, 74);
}
.bg-yellow {
background-color: rgb(255, 199, 6);
}
.bg-blue {
background-color: rgb(0, 111, 184);
}
.bg-magenta {
background-color: rgb(118, 38, 113);
}
.bg-cyan {
background-color: rgb(44, 181, 233);
}
.bg-white {
background-color: rgb(204, 204, 204);
}
`;
}
private _parseTextToColoredPre(text) {
const pre = document.createElement("pre");
const re = /\033(?:\[(.*?)[@-~]|\].*?(?:\007|\033\\))/g;
let i = 0;
const state: State = {
bold: false,
italic: false,
underline: false,
strikethrough: false,
foregroundColor: null,
backgroundColor: null,
};
const addSpan = (content) => {
const span = document.createElement("span");
if (state.bold) {
span.classList.add("bold");
}
if (state.italic) {
span.classList.add("italic");
}
if (state.underline) {
span.classList.add("underline");
}
if (state.strikethrough) {
span.classList.add("strikethrough");
}
if (state.foregroundColor !== null) {
span.classList.add(`fg-${state.foregroundColor}`);
}
if (state.backgroundColor !== null) {
span.classList.add(`bg-${state.backgroundColor}`);
}
span.appendChild(document.createTextNode(content));
pre.appendChild(span);
};
/* eslint-disable no-cond-assign */
let match;
// eslint-disable-next-line
while ((match = re.exec(text)) !== null) {
const j = match!.index;
addSpan(text.substring(i, j));
i = j + match[0].length;
if (match[1] === undefined) {
continue;
}
match[1].split(";").forEach((colorCode: string) => {
switch (parseInt(colorCode, 10)) {
case 0:
// reset
state.bold = false;
state.italic = false;
state.underline = false;
state.strikethrough = false;
state.foregroundColor = null;
state.backgroundColor = null;
break;
case 1:
state.bold = true;
break;
case 3:
state.italic = true;
break;
case 4:
state.underline = true;
break;
case 9:
state.strikethrough = true;
break;
case 22:
state.bold = false;
break;
case 23:
state.italic = false;
break;
case 24:
state.underline = false;
break;
case 29:
state.strikethrough = false;
break;
case 30:
// foreground black
state.foregroundColor = null;
break;
case 31:
state.foregroundColor = "red";
break;
case 32:
state.foregroundColor = "green";
break;
case 33:
state.foregroundColor = "yellow";
break;
case 34:
state.foregroundColor = "blue";
break;
case 35:
state.foregroundColor = "magenta";
break;
case 36:
state.foregroundColor = "cyan";
break;
case 37:
state.foregroundColor = "white";
break;
case 39:
// foreground reset
state.foregroundColor = null;
break;
case 40:
state.backgroundColor = "black";
break;
case 41:
state.backgroundColor = "red";
break;
case 42:
state.backgroundColor = "green";
break;
case 43:
state.backgroundColor = "yellow";
break;
case 44:
state.backgroundColor = "blue";
break;
case 45:
state.backgroundColor = "magenta";
break;
case 46:
state.backgroundColor = "cyan";
break;
case 47:
state.backgroundColor = "white";
break;
case 49:
// background reset
state.backgroundColor = null;
break;
}
});
}
addSpan(text.substring(i));
return pre;
}
}
declare global {
interface HTMLElementTagNameMap {
"hassio-ansi-to-html": HassioAnsiToHtml;
}
}
|
7429f33ab2076784e8551642d81cd59667db520a
|
TypeScript
|
gabriellopes00/umbriel
|
/src/modules/senders/useCases/SetDefaultSender/SetDefaultSender.spec.ts
| 2.609375
| 3
|
import { Email } from '@modules/senders/domain/sender/email'
import { Name } from '@modules/senders/domain/sender/name'
import { Sender } from '@modules/senders/domain/sender/sender'
import { InMemorySendersRepository } from '@modules/senders/repositories/in-memory/InMemorySendersRepository'
import { SetDefaultSender } from './SetDefaultSender'
let sendersRepository: InMemorySendersRepository
let setDefaultSender: SetDefaultSender
describe('Set Default Sender', () => {
beforeEach(() => {
sendersRepository = new InMemorySendersRepository()
setDefaultSender = new SetDefaultSender(sendersRepository)
})
it('should be able to set default sender', async () => {
const defaultSender = Sender.create({
name: Name.create('John Doe').value as Name,
email: Email.create('johndoe1@example.com').value as Email,
isDefault: true,
}).value as Sender
const notDefaultSender = Sender.create({
name: Name.create('John Doe').value as Name,
email: Email.create('johndoe2@example.com').value as Email,
isDefault: false,
}).value as Sender
await sendersRepository.create(defaultSender)
await sendersRepository.create(notDefaultSender)
const response = await setDefaultSender.execute({
senderId: notDefaultSender.id,
})
const updatedDefaultSender = await sendersRepository.findById(
defaultSender.id
)
const updatedNotDefaultSender = await sendersRepository.findById(
notDefaultSender.id
)
const currentDefaultSender = await sendersRepository.findDefaultSender()
expect(response.isRight()).toBeTruthy()
expect(updatedDefaultSender.isDefault).toBe(false)
expect(updatedNotDefaultSender.isDefault).toBe(true)
expect(currentDefaultSender.id).toEqual(notDefaultSender.id)
})
})
|
77780eeaabbf4842427294af9ef557d8c965752a
|
TypeScript
|
davidkpiano/RxAnimate
|
/src/utils/mapValues.ts
| 3.15625
| 3
|
export default function mapValues<T, R>(
object: Record<string, T>,
project: (value: T, index: string) => R
): Record<string, R> {
const result: Record<string, R> = {};
Object.keys(object).forEach(key => {
result[key] = project(object[key], key);
});
return result;
}
|
c8c8e5f31c954a343b91f63b70ab2fd05598bb19
|
TypeScript
|
jumodada/date-picker
|
/src/utils/extend.ts
| 2.828125
| 3
|
export function extend<T, U>(sourceObj: T, targetObj: U): T & U {
for (const key in sourceObj) {
// es5
;(targetObj as T & U)[key] = sourceObj[key] as any
}
return targetObj as T & U
}
|
47cac27ce84cd9d658f8ad3389fec434985e8120
|
TypeScript
|
Enhmunh-E/tsparticles
|
/shapes/heart/src/HeartDrawer.ts
| 3
| 3
|
import type { IShapeDrawer } from "tsparticles/Core/Interfaces/IShapeDrawer";
import type { IParticle } from "tsparticles";
export class HeartDrawer implements IShapeDrawer {
draw(context: CanvasRenderingContext2D, particle: IParticle, radius: number) {
const x = -radius;
const y = -radius;
context.moveTo(x, y + radius / 2);
context.quadraticCurveTo(x, y, x + radius / 2, y);
context.quadraticCurveTo(x + radius, y, x + radius, y + radius / 2);
context.quadraticCurveTo(x + radius, y, x + (radius * 3) / 2, y);
context.quadraticCurveTo(x + radius * 2, y, x + radius * 2, y + radius / 2);
context.quadraticCurveTo(x + radius * 2, y + radius, x + (radius * 3) / 2, y + (radius * 3) / 2);
context.lineTo(x + radius, y + radius * 2);
context.lineTo(x + radius / 2, y + (radius * 3) / 2);
context.quadraticCurveTo(x, y + radius, x, y + radius / 2);
}
}
|
438913348b05b1487af868356a812bea0c6e4026
|
TypeScript
|
bohyeon-n/youngint-lesson
|
/src/modules/Pattern4ShapePattern.ts
| 3.078125
| 3
|
// 출력 예시
// ****
// ****
// ****
// ****
import BaseShapePattern from "./BaseShapePattern";
export default class Pattern4ShapePattern extends BaseShapePattern {
constructor(totalNumber: number, shape: string) {
super(totalNumber, shape);
}
protected countShapesInLines = (): number[] => {
const { totalNumber } = this;
return new Array(totalNumber).fill(totalNumber - 1);
};
protected countBlanksInLine = (shapeCount: number, index: number): number => {
return shapeCount - 1;
};
protected combineShapesBlanks = (
index: number,
shapesInLine: string,
blankInLine: string
): string => {
const blankLength = blankInLine.length;
return (
blankInLine.slice(0, blankLength - index) +
shapesInLine +
(index !== 0 ? blankInLine.slice(-index) : "")
);
};
}
|
c1d7d5b8f54961d62bdb5d46a5141d03cd8ebc8c
|
TypeScript
|
bastilavarias/travel-buddy
|
/src/components/profile/model.ts
| 2.8125
| 3
|
import Profile from "../../database/entities/Profile";
import {
IProfileImageSoftDetails,
IProfileModelSaveDetailsPayload,
IProfileModelSaveImageDetailsPayload,
IProfileSoftDetails,
} from "./typeDefs";
import ProfileImage from "../../database/entities/ProfileImage";
import { getRepository } from "typeorm";
const profileModel = {
async saveDetails(input: IProfileModelSaveDetailsPayload): Promise<Profile> {
const { firstName, lastName, nationality, birthDate, sex, imageID } = input;
return await Profile.create({
firstName,
lastName,
nationality,
birthDate,
sex,
image: { id: imageID },
}).save();
},
async updateDetails(
profileID: number,
input: IProfileModelSaveDetailsPayload
) {
const { firstName, lastName, nationality, birthDate, sex } = input;
await Profile.update(
{ id: profileID },
{
firstName,
lastName,
nationality,
birthDate,
sex,
}
);
},
async saveImageDetails(
input: IProfileModelSaveImageDetailsPayload
): Promise<ProfileImage> {
return await ProfileImage.create(input).save();
},
async updateImageDetails(
imageID: number,
input: IProfileModelSaveImageDetailsPayload
) {
const { url, publicID } = input;
await ProfileImage.update(
{ id: imageID },
{
url,
publicID,
}
);
},
async getSoftDetails(profileID: number): Promise<IProfileSoftDetails> {
const foundDetails: IProfileSoftDetails = <IProfileSoftDetails>(
await getRepository(Profile)
.createQueryBuilder("profile")
.select([
"id",
`"firstName"`,
`"lastName"`,
"nationality",
`"birthDate"`,
"sex",
`"imageId" as "imageID"`,
])
.where("profile.id = :id", { id: profileID })
.getRawOne()
);
foundDetails.image = await this.getImageSoftDetails(foundDetails.imageID!);
delete foundDetails.imageID;
return foundDetails!;
},
async getImageSoftDetails(
profileImageID: number
): Promise<IProfileImageSoftDetails> {
return await getRepository(ProfileImage)
.createQueryBuilder("profile_image")
.select(["id", "url", `"publicID"`])
.where("profile_image.id = :id", { id: profileImageID })
.getRawOne();
},
};
export default profileModel;
|
76db77723d013830848805ff91d55659f5171740
|
TypeScript
|
nitreojs/puregram
|
/packages/puregram/src/common/structures/pre-checkout-query.ts
| 2.734375
| 3
|
import { Inspect, Inspectable } from 'inspectable'
import * as Interfaces from '../../generated/telegram-interfaces'
import { Structure } from '../../types/interfaces'
import { User } from './user'
import { OrderInfo } from './order-info'
/** This object contains information about an incoming pre-checkout query. */
@Inspectable()
export class PreCheckoutQuery implements Structure {
constructor (public payload: Interfaces.TelegramPreCheckoutQuery) { }
get [Symbol.toStringTag] () {
return this.constructor.name
}
/** Unique query identifier */
@Inspect()
get id () {
return this.payload.id
}
/** User who sent the query */
@Inspect()
get from () {
return new User(this.payload.from)
}
/** Sender ID */
@Inspect()
get senderId () {
return this.from.id
}
/** Three-letter ISO 4217 currency code */
@Inspect()
get currency () {
return this.payload.currency
}
/**
* Total price in the smallest units of the currency
* (integer, not float/double). For example, for a price of
* `US$ 1.45` pass `amount = 145`. See the `exp` parameter in
* [currencies.json](https://core.telegram.org/bots/payments/currencies.json),
* it shows the number of digits past the decimal point for each currency
* (2 for the majority of currencies).
*/
@Inspect()
get totalAmount () {
return this.payload.total_amount
}
/** Bot specified invoice payload */
@Inspect()
get invoicePayload () {
return this.payload.invoice_payload
}
/** Identifier of the shipping option chosen by the user */
@Inspect({ nullable: false })
get shippingOptionId () {
return this.payload.shipping_option_id
}
/** Order info provided by the user */
@Inspect({ nullable: false })
get orderInfo () {
const { order_info } = this.payload
if (!order_info) {
return
}
return new OrderInfo(order_info)
}
toJSON () {
return this.payload
}
}
|
8502e145171bb3203cad14414685fb7ba627782c
|
TypeScript
|
imclab/three-story-controls
|
/lib/Damper.d.ts
| 3.4375
| 3
|
export interface DamperValues {
/** A value to dampen, set to its initial state */
[key: string]: number | null;
}
export interface DamperProps {
/** Values to be dampened */
values: DamperValues;
/** Multiplier used on each update to approach the target value, should be between 0 and 1, where 1 is no damping */
dampingFactor: number;
/** Amount of permitted error before a value is considered to have 'reached' its target. Defaults to 0.001 */
epsilon?: number;
}
/**
* Damper uses simple linear damping for a given collection of values.
* On every call to update, the damper will approach a given set of target values.
* @example
* ```js
* const damper = new Damper({
* values: {x: 0, y: 0},
* dampingFactor: 0.4
* })
*
* damper.setTarget({ x: 1, y: 100 })
* damper.update() // would generally be called in an animation loop
* const values = damper.getCurrentValues() // values.x = 0.4; values.y = 40
* ```
*/
export declare class Damper {
private dampingFactor;
private epsilon;
private values;
private targetValues;
private deltaValues;
private hasReached;
constructor(props: DamperProps);
/**
* Update the damper, should generally be called on every frame
*/
update(): void;
/**
* Set the target values the damper needs to approach
* @param target DamperValues the damper needs to approach
*/
setTarget(target: DamperValues): void;
/**
* Increment/Decrement a specifc damper target value
* @param key The key of the value to modify
* @param value The amount to modify the target by
*/
addToTarget(key: string, value: number): void;
/**
* Reset all damper values to the fiven number
* @param value Number to reset all damper values to
*/
resetAll(value: number): void;
/**
* Reset damper values as described by the given DamperValues object
* @param values DamperValues object to reset the damper to
*/
resetData(values: DamperValues): void;
/**
* Get the current values
* @returns DamperValues object with the current values of the damper
*/
getCurrentValues(): DamperValues;
/**
* Get the change in values since the last update call
* @returns DamperValues object with the amount the values changed since the last `update()` call
*/
getDeltaValues(): DamperValues;
/**
* Whether the damper has reached its target
* @returns Whether the damper has reached its target (within permissible error range)
*/
reachedTarget(): boolean;
}
//# sourceMappingURL=Damper.d.ts.map
|
91c0de9db0f39608b394ac2cf0d1671612f24a6f
|
TypeScript
|
Rahul-D78/Conduit_Typescript
|
/src/controllers/comments.ts
| 2.9375
| 3
|
import { getRepository } from "typeorm";
import { Article } from "../entities/Article";
import { Comment } from "../entities/Comment";
import { User } from "../entities/User";
import { sanitization } from "../utils/security";
interface CommentData {
body: string,
}
export async function createComment(data: CommentData,slug: string, email: string): Promise<Comment> {
if(!data.body) throw new Error('Comment body is empty please check')
try{
const repo = getRepository(Comment)
const articleRepo = getRepository(Article)
const userRepo = getRepository(User)
const user = await userRepo.findOne(email)
const article = await articleRepo.findOne(slug)
if(!article) throw new Error('Article Not Found')
if(!user) throw new Error('Please Login to Comment')
const comment = await repo.save(new Comment(
data.body,
await sanitization(user as any as User)
))
return comment
}catch(e) {
throw e
}
}
export async function getAllComment(slug: string) {
try {
const repo = getRepository(Comment)
const comments = await repo.findOne(slug)
if(!comments) throw new Error('No comment for this slug exists')
return comments
}catch(e) {
throw e
}
}
export async function updateComment(data: CommentData,slug: string, email: string): Promise<Comment> {
//check for existing
try {
const repo = getRepository(Comment)
const userRepo = getRepository(User)
const comment = await repo.findOne(slug)
const user = await userRepo.findOne(email)
if(!comment) throw new Error("No Comment with this slug exists");
if(typeof data.body != undefined) comment.body = data.body
if(!user) throw new Error('unauthorized to update a comment')
await sanitization(user as unknown as User)
const updatedComment = await repo.save(comment)
return updatedComment
}catch(e) {
throw e
}
}
export async function deleteComment(id: string, email: string) {
try {
const uRepo = getRepository(User)
const user = uRepo.findOne(email)
const repo = getRepository(Comment)
const comment = repo.findOne(id)
if(!comment) throw new Error('Comment does not exists')
if(!user) throw new Error('Unauthorized to delete a comment')
repo.delete(comment as unknown as Comment)
}catch(e) {
throw e
}
}
|
04a0c0face62de48acc9cab20211b8cec79756b4
|
TypeScript
|
JakeGill70/CosmicArk-Advanced
|
/CosmicArkAdvanced/app.ts
| 2.921875
| 3
|
module CosmicArkAdvanced {
/**
* @description The setup for the game context
* @property game {Phaser.game} - The game context used by everything else in the game.
*/
export class MyGame {
game: Phaser.Game;
private static AUTO_SCALING = true; // Debug var
/**
* @description Creates the game context to use with the rest of the game
* @param _elementHook - The html div box that the game context should be created in.
* @param _sizeOfScreen - The size of the window containing the game
* @constructor
*/
constructor(_elementHook) {
// Phaser.AUTO selects either WebGL or canvas (Which ever the browser likes better),
// then places it in the HTML document at 'elementHook' tag.
this.game = new Phaser.Game(800, 450, Phaser.AUTO, _elementHook, {
create: this.create, preload: this.preload
});
}
/**
* @description Loads the assests used in the game.
*/
preload() {
// Backgrounds
this.game.load.image("title", "Graphics/Backgrounds/TitleCard3-4.png");
// Most of the loading will now be done in the "TitleScreenState", which will now double as a loading screen.
// Some things will still need to be preloaded, such as fonts, loading music, and the title screen itself.
// Backgrounds
// this.game.load.image("help", "Graphics/Backgrounds/HelpScreen1.png");
// this.game.load.image("main", "Graphics/Backgrounds/MainMenuScreen2.png");
// this.game.load.image("nightSky","Graphics/Backgrounds/NightSky.png");
// this.game.load.image("city", "Graphics/Backgrounds/CityBackdrop.png");
// this.game.load.image("city1", "Graphics/Backgrounds/City1.png");
// // Sprites
// this.game.load.spritesheet("man", "Graphics/Sprites/walk5_sheet.png", 64, 64, 8);
// this.game.load.image("gun", "Graphics/Sprites/gun1.png");
// this.game.load.image("rope", "Graphics/Sprites/rope3.png");
// this.game.load.spritesheet("ship", "Graphics/Sprites/UFO_Glow.png", 48, 24, 2);
// this.game.load.spritesheet( "bang", "Graphics/Sprites/bang.png", 64, 64, 14);
// // Static Sprites
// this.game.load.image("mothership", "Graphics/Statics/mothership3.png");
// this.game.load.image("hook", "Graphics/Statics/hook2.png");
// this.game.load.image("mine", "Graphics/Statics/Mine3.png");
// this.game.load.image("bullet", "Graphics/Statics/bullet1.png");
// this.game.load.image("planet1", "Graphics/Statics/planet_1.png");
// this.game.load.image("planet2", "Graphics/Statics/planet_2.png");
// this.game.load.image("planet3", "Graphics/Statics/planet_3.png");
// Fonts
// To make a bitmap font, use littera. It is an online flash tool.
this.game.load.image("edo", "Fonts/EdoSZ.png");
this.game.load.bitmapFont("EdoSZ", "Fonts/EdoSZ.png", "Fonts/EdoSZ.xml");
// Audio
// Use game.load.audio for music
this.game.load.audio("ThereminsBeat", "Audio/Music/ThereminsBeatShort.wav");
// Use game.load.audiosprite for SFX
}
/**
* @description Adds the game states to the game context and sets the scaling mode.
*/
create() {
// Add game states
this.game.state.add("gamePlayState", CosmicArkAdvanced.GamePlayState, false);
this.game.state.add("mapSelectState", CosmicArkAdvanced.MapSelectState, false);
this.game.state.add("mainMenuState", CosmicArkAdvanced.MainMenuState, false);
this.game.state.add("helpScreenState", CosmicArkAdvanced.HelpScreenState, false);
this.game.state.add("levelStartState", CosmicArkAdvanced.LevelStartState, false);
this.game.state.add("levelFinishState", CosmicArkAdvanced.LevelFinishState, false);
this.game.state.add("highscoreState", CosmicArkAdvanced.HighscoreState, false);
this.game.state.add("titleScreenState", CosmicArkAdvanced.TitleScreenState, true);
console.log(MyGame.AUTO_SCALING);
console.log(this.game.scale.scaleMode);
if (MyGame.AUTO_SCALING == true) {
if (!this.game.device.desktop) {
this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.game.scale.fullScreenScaleMode = Phaser.ScaleManager.SHOW_ALL;
//have the game centered horizontally
this.game.scale.pageAlignHorizontally = true;
this.game.scale.pageAlignVertically = true;
this.game.scale.startFullScreen(true);
}
}
}
}
/**
* @description global function used to find the difference between to x,y corrdinates
* @param srcX - The source x coordinate
* @param srcY - The source y coordinate
* @param destX - The destination's x coordinate
* @param destY - The destination's y coordinate
*/
function Dist(srcX, srcY, destX, destY) {
return ((srcX - destX) + (srcY - destY));
}
}
/**
@description The javascript COM event that creates the game in the webpage.
*/
window.onload = () => {
var el = document.getElementById('content');
var game = new CosmicArkAdvanced.MyGame(el);
};
|
fdffa5569d0e7d1f6d612eeedbcd3e0544fb3828
|
TypeScript
|
ElSimpatico/react_app_03
|
/src/reducers/reducer-test.ts
| 2.65625
| 3
|
import { TestState } from '../shared/models';
import { TestActions } from '../actions';
import { SET_TEST } from '../actions';
const INIT_TEST_STATE: TestState = {
name: 'testName'
};
export function TestReducer(
state: TestState = INIT_TEST_STATE,
action: TestActions
): TestState {
switch (action.type) {
case SET_TEST:
return {
...state,
...action.payload
};
default:
return state;
}
}
|
b61dfee9a6e0404c474712ecb084ed7bc4161146
|
TypeScript
|
andrescass/miralosmorweb
|
/frontend/src/app/services/lists.service.ts
| 2.65625
| 3
|
import { Injectable } from '@angular/core';
import { ListsComponent } from '../components/lists/lists.component';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ListsService {
constructor(private http: HttpClient){}
private lists: ListModel[] = [];
private list: ListModel;
getLists() {
return this.http.get('http://miralosmorserver.pythonanywhere.com/api/movielists')
.pipe(
map( this.createArray )
);
}
private createArray( listsObj: object){
const lists: ListModel[] = [];
if (listsObj === null) { return []; }
Object.keys( listsObj ).forEach( key => {
const list: ListModel = listsObj[key];
list.id = key;
lists.push( list );
});
return lists;
}
getList(listName: string){
listName = listName.replace(' ', '_');
// Recupero la Lista clickeada por nombre
return this.http.get(`http://miralosmorserver.pythonanywhere.com/api/movielists/${listName}`)
}
searchList( word: string){
let listsArray:ListModel[]=[];
word = word.toLowerCase();
for (let list of this.lists){
let name = list.words.toLowerCase();
if (name.indexOf(word) >= 0) {
listsArray.push(list);
}
}
return listsArray;
}
}
export class ListModel {
id: string;
name: string;
description: string;
link: string;
img: string;
by: string;
words: string;
movies: Movies[];
}
export class Movies{
id: number;
name: string;
year: string;
link: string;
words: string;
}
// export interface Movies{
// name: string;
// url: string;
// }
// export interface List{
// name: string;
// description: string;
// img: string;
// by: string;
// words: string;
// movies: Movies[];
// }
|
cba5c539b148dda5c99d7750a1c450f247dd2fce
|
TypeScript
|
jfouche/covoit
|
/app/typings/webcomponents.d.ts
| 2.5625
| 3
|
interface Document {
registerElement(tagName: string, obj: any): void;
}
interface HTMLElement {
createdCallback(): void;
attributeChangedCallback(attributeName: string, oldValue: any, newValue: any): void;
}
|
e3e1c3c8f13197c261e8b4aedcafbeb26274de92
|
TypeScript
|
spencerjbeckwith/bionicle
|
/src/client/graphics/shader.ts
| 2.65625
| 3
|
import { gl, createShader } from './gl';
/*
How palette swapping works:
You must provide a palette texture to the shader. This is the basis for recoloration. The top row (palette 0) of pixels is your base colors. When drawing an image with those colors present, if the palette index is not set to 0, each occurence of the colors in this first row will instead become the corresponding color in the row of the palette index.
Rows respresent the colors in a palette, while columns represent the same color of different palettes.
For example: in the palette texture, pixel (4,0) is set to RGB 77,0,0.
You draw an image featuring that color.
If your palette index is 0, you'll notice no change.
But say your palette index is set to 1, then all pixels in this image that are of that color instead become whatever color is in the palette texture at pixel (4,1). All colors that aren't matched aren't changed by the shader.
You can change the palette texture (or the atlas, for that matter) freely without needing to worry about updating any irrelevant uniforms.
*/
const vertexSource = `#version 300 es
in vec2 a_position;
in vec2 a_texcoord;
out vec2 v_texcoord;
uniform mat3 u_positionMatrix;
uniform mat3 u_textureMatrix;
void main() {
gl_Position = vec4((u_positionMatrix*vec3(a_position,1.0)).xy,0,1);
v_texcoord = (u_textureMatrix*vec3(a_texcoord,1.0)).xy;
}`;
const fragmentSource = `#version 300 es
precision mediump float;
in vec2 v_texcoord;
out vec4 outputColor;
uniform sampler2D u_atlas;
uniform sampler2D u_palette;
uniform vec4 u_blend;
uniform int u_paletteIndex;
uniform int u_useTexture;
void main() {
if (u_useTexture == 0) {
outputColor = u_blend;
} else {
vec4 color = texture(u_atlas,v_texcoord);
// If we have set a palette...
if (u_paletteIndex > 0) {
// Cycle through each color of the first palette
for (int a = 0; a < textureSize(u_palette,0).x; a++) {
// See if current color matches the one we want to check
if (color == texelFetch(u_palette,ivec2(a,0),0)) {
// Update to swap color
color = texelFetch(u_palette,ivec2(a,u_paletteIndex),0);
break;
}
}
}
// Blend final color
outputColor = color*u_blend;
}
}`;
const vertexShader = createShader(gl.VERTEX_SHADER,vertexSource);
const fragmentShader = createShader(gl.FRAGMENT_SHADER,fragmentSource);
const shaderProgram = gl.createProgram();
if (!shaderProgram) { throw new Error(`Failed to create WebGL program!`);}
gl.attachShader(shaderProgram,vertexShader);
gl.attachShader(shaderProgram,fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram,gl.LINK_STATUS)) {
throw new Error(`Failed to link shader program: ${gl.getProgramInfoLog(shaderProgram)}`);
}
const squareBuffer = gl.createBuffer();
if (!squareBuffer) { throw new Error(`Failed to create square buffer!`);}
const positionBuffer = gl.createBuffer();
if (!positionBuffer) { throw new Error(`Failed to create position buffer!`);}
const textureBuffer = gl.createBuffer();
if (!textureBuffer) { throw new Error(`Failed to create texture buffer!`);}
// Get all our attributes and uniforms.
const positionAttribute = gl.getAttribLocation(shaderProgram,'a_position');
const textureAttribute = gl.getAttribLocation(shaderProgram,'a_texcoord');
const positionMatrixUniform = gl.getUniformLocation(shaderProgram,'u_positionMatrix');
if (!positionMatrixUniform) { throw new Error(`Failed to find u_positionMatrix uniform!`);}
const textureMatrixUniform = gl.getUniformLocation(shaderProgram,'u_textureMatrix');
if (!textureMatrixUniform) { throw new Error(`Failed to find u_textureMatrix uniform!`);}
const atlasSamplerUniform = gl.getUniformLocation(shaderProgram,'u_atlas');
if (!atlasSamplerUniform) { throw new Error(`Failed to find u_atlas uniform!`);}
const paletteSamplerUniform = gl.getUniformLocation(shaderProgram,'u_palette');
if (!paletteSamplerUniform) { throw new Error(`Failed to find u_palette uniform!`);}
const blendUniform = gl.getUniformLocation(shaderProgram,'u_blend');
if (!blendUniform) { throw new Error(`Failed to find u_blend uniform!`);}
const paletteIndexUniform = gl.getUniformLocation(shaderProgram,'u_paletteIndex');
if (!paletteIndexUniform) { throw new Error(`Failed to find u_paletteIndex uniform!`);}
const useTextureUniform = gl.getUniformLocation(shaderProgram,'u_useTexture');
if (!useTextureUniform) { throw new Error(`Failed to find u_useTexture uniform!`);}
const shader : {
vertex: WebGLShader;
fragment: WebGLShader;
program: WebGLProgram;
buffers: {
square: WebGLBuffer;
position: WebGLBuffer;
texture: WebGLBuffer;
};
vao: WebGLVertexArrayObject | null;
attributes: {
position: number;
texture: number;
};
uniforms: {
/** Set via gl.uniformMatrix3fv. Transforms the provided position attributes from clipspace into pixel coordinates. Should be set to a projection using current view width/height, with transformations like translation or scaling applied. With the projection applied, clipspace (0,0) is now the top-left of where the image appears on screen and (1,1) is the bottom-right. */
positionMatrix: WebGLUniformLocation;
/** Set via gl.uniformMatrix3fv. Transforms the provided texture attributes from UVs into pixel coordinates. Should be used to set to a pre-computed matrix that splices the sprite you want to draw out of the atlas. */
textureMatrix: WebGLUniformLocation;
/** Set via gl.uniform1i. Corresponds to a texture location for the atlas texture, by default index 0. */
atlasSampler: WebGLUniformLocation;
/** Set via gl.uniform1i. Corresponds to a texture location for the palette texture, by default index 1. */
paletteSampler: WebGLUniformLocation;
/** Set via gl.uniform4f. Corresponds to an RGBA value to blend the final color by. */
blend: WebGLUniformLocation;
/** Set via gl.uniform1i. If not 0, it will recolor each sprite to the specified row of the palette texture. */
paletteIndex: WebGLUniformLocation;
/** Set via gl.uniform1i. If 0, textures will be not used and the drawing will be the color of the blend. If 1, textures will be used for the sprite as normal. */
useTexture: WebGLUniformLocation;
};
/** Set the clipspace coordinates to use for drawing, in order to draw shapes that are not squares.
* @param positions A Float32Array of clipspace coordinates. Defaults to a unit quad.
*/
setPositions: (positions?: number[]) => void;
/** Set the texture coordinates to use for drawing, in order to draw shapes that are not squares.
* @param positions A float32Array of UV coordinates. Defaults to a unit quad.
*/
setUVs: (positions?: number[]) => void;
} = {
vertex: vertexShader,
fragment: fragmentShader,
program: shaderProgram,
buffers: {
square: squareBuffer,
position: positionBuffer,
texture: textureBuffer,
},
vao: null,
attributes: {
position: positionAttribute,
texture: textureAttribute,
},
uniforms: {
positionMatrix: positionMatrixUniform,
textureMatrix: textureMatrixUniform,
atlasSampler: atlasSamplerUniform,
paletteSampler: paletteSamplerUniform,
blend: blendUniform,
paletteIndex: paletteIndexUniform,
useTexture: useTextureUniform,
},
setPositions: function(positions = unitQuad) {
gl.enableVertexAttribArray(this.attributes.position);
gl.bindBuffer(gl.ARRAY_BUFFER,this.buffers.position);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(positions),gl.DYNAMIC_DRAW);
gl.vertexAttribPointer(this.attributes.position,2,gl.FLOAT,false,0,0);
},
setUVs: function(positions = unitQuad) {
gl.enableVertexAttribArray(this.attributes.texture);
gl.bindBuffer(gl.ARRAY_BUFFER,this.buffers.texture);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(positions),gl.DYNAMIC_DRAW);
gl.vertexAttribPointer(this.attributes.texture,2,gl.FLOAT,false,0,0);
},
};
gl.useProgram(shaderProgram);
const vao = gl.createVertexArray(); // Vertex array object for drawing non-transformed sprites
if (!vao) { throw new Error(`Failed to create new vertex array!`);}
gl.bindVertexArray(vao);
// Load default unit quad into buffer
const unitQuad = [0,0, 0,1, 1,1, 1,1, 1,0, 0,0];
gl.bindBuffer(gl.ARRAY_BUFFER,shader.buffers.square);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(unitQuad),gl.STATIC_DRAW);
// Enable position and texture attributes for this VAO
gl.enableVertexAttribArray(shader.attributes.position);
gl.vertexAttribPointer(shader.attributes.position,2,gl.FLOAT,false,0,0);
gl.enableVertexAttribArray(shader.attributes.texture);
gl.vertexAttribPointer(shader.attributes.texture,2,gl.FLOAT,false,0,0);
gl.bindVertexArray(null);
shader.vao = vao;
export default shader;
|
e4a29d96e092f6b05570b4508b3f87fa4927e2ef
|
TypeScript
|
eqot/json-rpc
|
/src/bearers/Bearer.ts
| 2.578125
| 3
|
import { IframeBearer } from './IframeBearer'
import { WebBearer } from './WebBearer'
import { ReactNativeBearer } from './ReactNativeBearer'
export interface Bearer {
send(message: any | string): void
onReceived(callback: (args: any) => void): void
}
export function generateBearer(webview: any): Bearer {
if (webview) {
return new ReactNativeBearer(webview)
} else if (window === window.parent) {
return new WebBearer()
} else {
return new IframeBearer()
}
}
|
7df5799abd5f60a4a93d3d539b01cf00946ae6a3
|
TypeScript
|
otissv/state-subscriptions
|
/packages/react/src/useSubscribe/storePublish/storePublish.ts
| 2.53125
| 3
|
import { ActionType } from '../../types'
export function storePublish<Store extends Record<string, any>>(store: Store) {
return <Type extends string>(eventType: Type) => (
actions: readonly ActionType[]
): void => store.publish([eventType, actions])
}
|
5f9d70f416f94571ecafd6dae04ccb1807bf6b6a
|
TypeScript
|
Rhadow/nature_of_code
|
/src/experiments/particle.ts
| 2.59375
| 3
|
import * as numjs from 'numjs';
import { ICanvasState } from '../components/Canvas/CanvasInterfaces';
import { ICreature, IEnvironment } from "../elements/ElementInterface";
import { width, height } from '../constants/world';
import ParticleSystem from '../elements/ParticleSystem';
import Repeller from '../elements/Repeller';
const particleForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => {
const gravity: nj.NdArray = numjs.array([0, 0.1]);
let particleSystem: ParticleSystem = <ParticleSystem>creatures[0];
let repeller: Repeller = <Repeller>currentEnvironment[0];
currentEnvironment.forEach((environment: IEnvironment) => {
environment.display(canvasState);
});
particleSystem.addParticle();
particleSystem.applyForceToParticles(gravity);
particleSystem.applyRepeller(repeller);
particleSystem.run(canvasState);
};
export const particleExperiment = {
'label': 'Particle',
'creatures': [new ParticleSystem(numjs.array([width / 2, 80]))],
'environments': [new Repeller(20, numjs.array([width / 2 - 50, height / 3]))],
'forceFunction': particleForceFunction,
'initialForceFunction': () => { }
};
|
2b0d18b54f3c3950cc8cba49087e6002005e9a32
|
TypeScript
|
lboshuizen/frht2011
|
/src/domain/claim.ts
| 2.59375
| 3
|
interface Location {
Description: "industrial area" | "rural area"
}
interface Address {
Location?: Location;
}
interface Party {
Firstname: string;
ClaimIntoxication: boolean;
Address: Address;
}
interface Reference {
Reference: string;
}
interface Object {
Vin: string;
ListPrice: number;
}
interface ObjectsInsured{
Object: Object;
}
interface Policy {
RegularDrivers: Reference[];
ObjectsInsured: ObjectsInsured[]
}
interface Claim {
Policy: Policy;
Address: Address;
TimeOccurred: Date;
PoliceInvolved: boolean;
}
export interface ClaimContainer {
Parties : Record<string,Party>;
Claim: Claim;
}
|
15f6dd24d846e94998e4664c383a4667ebf29b4d
|
TypeScript
|
tangx/vue3-course
|
/src/components/12_hook/comps/hooks/usePoint.ts
| 3.125
| 3
|
import { onMounted, onUnmounted, reactive } from 'vue';
export default function () {
// 设定鼠标坐标
let point = reactive({
x: 0,
y: 0
})
// 方法。
// 必须使用命名方法。 匿名方法将会认为是【两个】独立行为相同的方法。
function savePoint(event: any) {
point.x = event.pageX
point.y = event.pageY
console.log(event.pageX, event.pageY)
}
// 挂载
onMounted(
() => {
console.log("onMounted: usePoint")
window.addEventListener('click', savePoint)
}
)
// 卸载
onUnmounted(
() => {
console.log("onUnmounted: usePoint")
window.removeEventListener('click', savePoint)
}
)
// 返回坐标
return point
}
|
df50133ce3881e30136197dabde61f9ba1956075
|
TypeScript
|
Ediezzle/Angular-Data-binding
|
/src/app/server-element/server-element.component.ts
| 2.53125
| 3
|
import {
Component,
OnInit,
Input,
ViewEncapsulation,
OnChanges,
SimpleChanges,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy,
ViewChild,
ContentChild,
ElementRef
} from "@angular/core";
@Component({
selector: "app-server-element",
templateUrl: "./server-element.component.html",
styleUrls: ["./server-element.component.css"],
encapsulation: ViewEncapsulation.Emulated //Native, ShadowDom, None or Emulated(default)
})
export class ServerElementComponent
implements
OnInit,
OnChanges,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy {
//javascript object is enclosed in curly braces
@Input("srvElement") element: { type: string; name: string; content: string };
//Any directive, component, and element which is part of component template is accessed as ViewChild
@ViewChild("heading") header: ElementRef;
//any element or component which is projected inside <ng-content> is accessed as ContentChild
@ContentChild("paragraphContent") paragraph: ElementRef;
constructor() {
console.log("constructor called");
}
ngOnInit(): void {
//Called after the constructor, initializing input properties, and the first call to ngOnChanges.
//Add 'implements OnInit' to the class.
console.log("ngOnInit called");
console.log("header text content: " + this.header.nativeElement.textContent);
console.log("paragraph content: " + this.paragraph.nativeElement.textContent);
}
ngOnChanges(changes: SimpleChanges): void {
//Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.
//Add '${implements OnChanges}' to the class.
console.log("ngOnChanges called");
console.log(changes);
}
ngDoCheck(): void {
//Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.
//Add 'implements DoCheck' to the class.
console.log("ngDoCheck called");
}
ngAfterContentInit(): void {
//Called after ngOnInit when the component's or directive's content has been initialized.
//Add 'implements AfterContentInit' to the class.
console.log("ngAfterContentInit called");
console.log("paragraph content: " + this.paragraph.nativeElement.textContent);
}
ngAfterContentChecked(): void {
//Called after every check of the component's or directive's content.
//Add 'implements AfterContentChecked' to the class.
console.log("ngAfterContentChecked");
}
ngAfterViewInit(): void {
//Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
//Add 'implements AfterViewInit' to the class.
console.log("ngAfterViewInit");
console.log("header text content: " + this.header.nativeElement.textContent);
}
ngAfterViewChecked(): void {
//Called after every check of the component's view. Applies to components only.
//Add 'implements AfterViewChecked' to the class.
console.log("ngAfterViewChecked");
}
ngOnDestroy(): void {
//Called once, before the instance is destroyed.
//Add 'implements OnDestroy' to the class.
console.log("ngAfterViewChecked");
}
}
|
13c6e04129854726971387bad160940adf01a5be
|
TypeScript
|
bgotink/lit-html-brackets
|
/src/lib/binding.ts
| 3.3125
| 3
|
export interface Binding<T> {
set(value: T): void;
get(): T;
}
interface BindingImpl<T> extends Binding<T> {
__binding: true;
}
export function isBinding(obj: any): obj is Binding<any> {
return obj != null && (obj as BindingImpl<any>).__binding === true;
}
export function bind<O extends object, K extends keyof O>(object: O, property: K): Binding<O[K]> {
return {
__binding: true,
get() {
return object[property];
},
set(value: O[K]) {
object[property] = value;
},
} as BindingImpl<O[K]>;
}
|
29a95d823e0d02843b8ec3be1942f279c9905e81
|
TypeScript
|
fossabot/deno-events
|
/events.ts
| 3.390625
| 3
|
export type Priority = "high" | "normal" | "low";
export type EventResult = "cancelled" | any[];
export type ListenerResult = "cancelled" | any[] | void;
export type Listener = (...args: any[]) => ListenerResult;
export type OpenEventEmitter<T> = EventEmitter<T> | EventEmitter<any>;
export function emitter<T>(): OpenEventEmitter<T>{
return new EventEmitter<T>();
}
export class EventEmitter<T> {
highs = new Map<T, Set<Listener>>();
normals = new Map<T, Set<Listener>>();
lows = new Map<T, Set<Listener>>();
listeners(p: Priority): Map<T, Set<Listener>> | undefined {
if(p === "high") return this.highs;
if(p === "normal") return this.normals;
if(p === "low") return this.lows;
return undefined;
}
on([type, p = "normal"]: [T, Priority?], listener: Listener){
const listeners = this.listeners(p)
if(!listeners) return;
const set = listeners.get(type) ?? new Set();
if(!set.size) listeners.set(type, set)
set.add(listener);
}
off([type, p = "normal"]: [T, Priority?], listener: Listener){
const listeners = this.listeners(p);
if(!listeners) return;
const set = listeners.get(type);
if(set) set.delete(listener);
}
emit(type: T, ...args: any[]): EventResult {
const all = [];
const highs = this.highs.get(type);
if(highs) all.push(...Array.from(highs));
const normals = this.normals.get(type);
if(normals) all.push(...Array.from(normals));
const lows = this.lows.get(type);
if(lows) all.push(...Array.from(lows));
let values = args;
for(const listener of all){
const result = listener(...values);
if(result === "cancelled") return result;
if(Array.isArray(result)) values = result;
}
return values;
}
}
|
d04a0517fb918527a0ef99f97a8bef400a04154a
|
TypeScript
|
PatrickDCullen/beginning-typescript
|
/lesson3/index.ts
| 3.671875
| 4
|
// Literal Type
const flipCoin = () => (Math.random() < 0.5 ? "Head" : "Tail");
console.log(flipCoin());
enum Suit {
HEARTS,
SPADES,
DIAMONDS,
CLUBS,
}
// type Suit = "hearts" | "spades" | "diamonds" | "clubs"; // Literal type with unions
// console.log(Suit.SPADES);
const suitMeaning = (suit: Suit) => {
if (Suit.HEARTS === suit)
return "The clergy and the struggle to achieve inner joy";
if (Suit.SPADES === suit)
return "The warrior class institutionalized into the nobility, and the fractious problems of life";
if (Suit.DIAMONDS === suit)
return "The merchant class and the excitement of wealth creation";
if (Suit.CLUBS === suit) return "The peasantry and achievement through work";
};
console.log(suitMeaning(Suit.CLUBS));
|
87b9ab9469484101468f0ad76789de8e3a16203f
|
TypeScript
|
JoaoptGaino/easy-recipe
|
/src/Controllers/RecipesController.ts
| 2.6875
| 3
|
import { Request, Response } from 'express';
import db from '../database/connections';
export default class RecipesController {
async index(req: Request, res: Response) {
const recipes = await db('recipes').select('*');
if (recipes.length <= 0) {
return res.status(404).json({ message: "Couldn't find anything" });
}
return res.status(200).json(recipes);
}
async create(req: Request, res: Response) {
const { name, ingredients, howto } = req.body;
const recipe = { name, ingredients, howto };
const trx = await db.transaction();
try {
await trx('recipes').insert(recipe);
await trx.commit();
return res.status(201).send();
} catch (err) {
await trx.rollback();
return res.status(400).json({
message: "Internal error"
});
}
}
async search(req: Request, res: Response) {
const filters = req.query;
const name = filters.name as string;
const filteredRecipe = await db('recipes').where('name', 'like', `%${name}%`).select('*');
if (filteredRecipe.length > 0) {
return res.status(200).json(filteredRecipe);
}
return res.status(404).json({
message: "Couldn't find any recipe"
});
}
}
|
a10ba08baa3d3f20de92eac179bafdaae34084de
|
TypeScript
|
stitchfix/flotilla-os
|
/ui/src/helpers/FlotillaClient.ts
| 2.515625
| 3
|
import axios, { AxiosInstance, AxiosError, AxiosResponse } from "axios"
import * as qs from "qs"
import { has, omit, Omit } from "lodash"
import {
HTTPMethod,
CreateTaskPayload,
RequestArgs,
Run,
ListRunParams,
ListRunResponse,
RunLog,
LaunchRequestV2,
Task,
ListTaskResponse,
ListTaskRunsResponse,
UpdateTaskPayload,
ListTaskParams,
ListTaskRunsParams,
ListClustersResponse,
ListGroupsResponse,
ListTagsResponse,
ListRunEventsResponse,
RunLogRaw,
ListTemplateParams,
ListTemplateResponse,
Template,
TemplateExecutionRequest,
ListTemplateHistoryParams,
ListTemplateHistoryResponse,
} from "../types"
interface IInitOpts {
baseURL: string
headers?: object
}
class FlotillaClient {
private axios: AxiosInstance
constructor({ baseURL, headers = {} }: IInitOpts) {
this.axios = axios.create({
baseURL,
headers,
// Note: this is the array format that the Flotilla server accepts.
paramsSerializer: params =>
qs.stringify(params, { arrayFormat: "repeat" }),
})
}
/** Requests a task definition. */
public getTask = ({
definitionID,
}: {
definitionID: string
}): Promise<Task> =>
this.request<Task>({
method: HTTPMethod.GET,
url: `/v6/task/${definitionID}`,
})
/** Requests a task definition by its alias. */
public getTaskByAlias = ({ alias }: { alias: string }): Promise<Task> =>
this.request<Task>({
method: HTTPMethod.GET,
url: `/v6/task/alias/${alias}`,
})
/** Requests a task definition's history. */
public listTaskRuns = ({
definitionID,
params,
}: {
definitionID: string
params: ListTaskRunsParams
}): Promise<ListTaskRunsResponse> =>
this.request<ListTaskRunsResponse>({
method: HTTPMethod.GET,
url: `/v6/task/${definitionID}/history`,
params,
})
/** Requests a list of task definitions. */
public listTasks = ({
params,
}: {
params: ListTaskParams
}): Promise<ListTaskResponse> =>
this.request<ListTaskResponse>({
method: HTTPMethod.GET,
url: `/v6/task`,
params,
})
/** Create a new task definition. */
public createTask = ({ data }: { data: CreateTaskPayload }): Promise<Task> =>
this.request<Task>({
method: HTTPMethod.POST,
url: `/v6/task`,
data,
})
/** Update an existing task definition. */
public updateTask = ({
definitionID,
data,
}: {
definitionID: string
data: UpdateTaskPayload
}): Promise<Task> =>
this.request<Task>({
method: HTTPMethod.PUT,
url: `/v6/task/${definitionID}`,
data,
})
/** Delete an existing task definition. */
public deleteTask = ({
definitionID,
}: {
definitionID: string
}): Promise<any> =>
this.request<any>({
method: HTTPMethod.DELETE,
url: `/v6/task/${definitionID}`,
})
/** Runs a task. */
public runTask = ({
definitionID,
data,
}: {
definitionID: string
data: LaunchRequestV2
}): Promise<Run> => {
const d: Omit<LaunchRequestV2, "owner_id"> = omit(data, "owner_id")
if (has(data, "owner_id")) {
if (d.run_tags) {
d.run_tags["OWNER_ID"] = data.owner_id
} else {
d.run_tags = { OWNER_ID: data.owner_id }
}
}
return this.request<Run>({
method: HTTPMethod.PUT,
url: `/v6/task/${definitionID}/execute`,
data: d,
})
}
/** Requests list of runs. */
public listRun = ({
params,
}: {
params: ListRunParams
}): Promise<ListRunResponse> =>
this.request<ListRunResponse>({
method: HTTPMethod.GET,
url: `/v6/history`,
params,
})
/** Requests a single run. */
public getRun = ({ runID }: { runID: string }): Promise<Run> =>
this.request<Run>({
method: HTTPMethod.GET,
url: `/v6/task/history/${runID}`,
})
/** Requests the logs of a single run. */
public getRunLog = ({
runID,
lastSeen = "",
}: {
runID: string
lastSeen?: string
}): Promise<RunLog> =>
this.request<RunLog>({
method: HTTPMethod.GET,
url: `/v6/${runID}/logs`,
params: { last_seen: lastSeen },
})
/** Requests the logs of a single run. */
public getRunLogRaw = ({ runID }: { runID: string }): Promise<RunLogRaw> =>
this.request<RunLogRaw>({
method: HTTPMethod.GET,
url: `/v6/${runID}/logs`,
params: { raw_text: true },
})
/** Stops an existing run */
public stopRun = ({
definitionID,
runID,
}: {
definitionID: string
runID: string
}): Promise<any> =>
this.request<any>({
method: HTTPMethod.DELETE,
url: `/v6/task/${definitionID}/history/${runID}`,
})
/** Requests available clusters. */
public listClusters = (): Promise<ListClustersResponse> =>
this.request<ListClustersResponse>({
method: HTTPMethod.GET,
url: `/v6/clusters`,
})
/** Requests available groups. */
public listGroups = (): Promise<ListGroupsResponse> =>
this.request<ListGroupsResponse>({
method: HTTPMethod.GET,
url: `/v6/groups`,
params: { offset: 0, limit: 10000 },
})
/** Requests available tags. */
public listTags = (): Promise<ListTagsResponse> =>
this.request<ListTagsResponse>({
method: HTTPMethod.GET,
url: `/v6/tags`,
params: { offset: 0, limit: 10000 },
})
/** Requests available tags. */
public listRunEvents = (runID: string): Promise<ListRunEventsResponse> =>
this.request<ListRunEventsResponse>({
method: HTTPMethod.GET,
url: `/v6/${runID}/events`,
})
/** Requests a list of task definitions. */
public listTemplates = ({
params,
}: {
params: ListTemplateParams
}): Promise<ListTemplateResponse> =>
this.request<ListTemplateResponse>({
method: HTTPMethod.GET,
url: `/v7/template`,
params,
})
/** Requests a task definition. */
public getTemplate = ({
templateID,
}: {
templateID: string
}): Promise<Template> =>
this.request<Template>({
method: HTTPMethod.GET,
url: `/v7/template/${templateID}`,
})
/** Runs a task. */
public runTemplate = ({
templateID,
data,
}: {
templateID: string
data: TemplateExecutionRequest
}): Promise<Run> => {
return this.request<Run>({
method: HTTPMethod.PUT,
url: `/v7/template/${templateID}/execute`,
data,
})
}
/** Requests a task definition's history. */
public listTemplateHistoryByTemplateID = ({
templateID,
params,
}: {
templateID: string
params: ListTemplateHistoryParams
}): Promise<ListTemplateHistoryResponse> =>
this.request<ListTemplateHistoryResponse>({
method: HTTPMethod.GET,
url: `/v7/template/${templateID}/history`,
params,
})
/** Requests a task definition's history. */
public listTemplateHistoryByTemplateName = ({
templateName,
params,
}: {
templateName: string
params: ListTemplateHistoryParams
}): Promise<ListTemplateHistoryResponse> =>
this.request<ListTemplateHistoryResponse>({
method: HTTPMethod.GET,
url: `/v7/template/name/${templateName}/history`,
params,
})
/** Returns a new Promise that sends an HTTP request when invoked. */
private request<T>({ method, url, params, data }: RequestArgs): Promise<T> {
return new Promise((resolve, reject) => {
this.axios
.request({ url, method, params, data })
.then((res: AxiosResponse) => {
resolve(res.data as T)
})
.catch((error: AxiosError) => {
reject(error)
})
})
}
}
export default FlotillaClient
|
7ab3e594f2abc96c12517478d252f660662350b4
|
TypeScript
|
KiaraGrouwstra/typical
|
/src/tuple/Prepend.ts
| 2.890625
| 3
|
import { List } from '../util/List';
import { IncIndex } from './IncIndex';
/**
* Prepend an element to a tuple-like type, returning a numerical object.
* Presumes the list is already zero-indexed, otherwise needs `ZeroIndex`.
*/
export type Prepend<
R extends List<any>,
T
> = { 0: T } & IncIndex<R, 1>;
|
ac09dfb18075ab4b57abdd5cf561add1680dd828
|
TypeScript
|
LisaCao0513/Robot-Simulator-Code
|
/src/config.ts
| 3
| 3
|
'use strict';
import path from 'path';
import * as types from './types';
/**
* Config object
* It consists of configs for:
* Robot class
* Messenger class
* Playground class
*/
//interfaces
export class Config implements types.BaseConfig{
app : types.App;
playground : types.basePlayground;
robotConfig : types.RobotConfig;
messenger : types.baseMessenger;
constructor(){
this.playground = {
startPointX: 0,
startPointY: 0,
lengthX: 6,
lengthY: 6
};
this.app = { root: path.resolve(__dirname) };
this.robotConfig = {
aCommands: ['PLACE', 'MOVE', 'LEFT', 'RIGHT', 'REPORT'],
initialCommands: ['PLACE'],
aDirections: ['NORTH', 'EAST', 'SOUTH', 'WEST']
};
this.messenger = {
oMsgs: {
noInitialCommand: 'Warning! You haven\'t placed the robot on the playground yet. Type "PLACE X, Y, F" {ci} to put a robot on the playground.',
placeRobotFirst: 'Nothing to report - the robot is not on the playground yet. Place it first to begin - PLACE X, Y, F.',
wrongPlace: 'Warning! You cannot place the robot in that square, it can fall. That square is out of the playground.',
wrondDirection: 'Error! No such a direction. Available directions are: {availableDirections}',
noFace: 'Error! No FACE was provided. Correct form is: PLACE X, Y, FACE.',
faceNotString: 'Error! FACE is not a string.',
unknownCommand: 'Error! Command is incorrect or unknown. Available commands are: {availableCommands}',
robotPosition: 'Robot\'s position is: {x}, {y}, {f}',
noNegativeCoordinates: 'Error! No negative X or Y allowed. Try again.',
nonIntCoordinates: 'Warning! X and Y must be integers.',
wrongMove: 'Warning! You cannot move the robot that way, it can fall.',
default: 'Welcome to The Toy Robot game. Start with placing a robot typing PLACE X, Y, F {ci}.',
someCombinedMsg: 'For the {s} of testing: PLACE {x}, {y}, {z} in {country}',
fileNotFound: 'Error! File \'{fileName}\' was not found. Make sure you specified its path correctly.',
welcome: 'Welcome!{eol}Tell the Robot your first command. Begin by placing the Robot on the playground - PLACE X, Y, F {ci}. \'q\' to exit.',
},
oSubs: {
availableDirections: this.robotConfig.aDirections.join(', '),
availableCommands: [this.robotConfig.aCommands.reduce(function(prev,
cur) {
if (prev == 'PLACE')
prev = [prev, 'X, Y, F'].join(' ');
return prev + ' | ' + cur;
}), '.'].join(''),
ci: '(case insensitive, spaces are acceptable instead of commas)',
country: 'AU'
}
}
}
}
|
b793b7538cc5be3db6dd696a27ee064c88a66bcc
|
TypeScript
|
joryphillips/joryphillips.github.io
|
/test/project_list.test.ts
| 2.765625
| 3
|
import { expect } from '@open-wc/testing';
import { listHasSearchValues } from '../src/components/project_list/project_list';
describe('listHasSearchValues', ()=> {
describe('single search value', ()=> {
it('returns false if search value not present', ()=> {
const searchValue = 'boop';
const stringsToSearch = 'boo radley oop';
expect(listHasSearchValues(searchValue, stringsToSearch)).to.be.false;
});
it('returns true if search value is a substring of listed words', ()=> {
const searchValue = 'boop';
const stringsToSearch = 'boo radley boopsies';
expect(listHasSearchValues(searchValue, stringsToSearch)).to.be.true;
});
it('returns true if search value present', ()=> {
const searchValue = 'boop';
const stringsToSearch = 'boo radley boop';
expect(listHasSearchValues(searchValue, stringsToSearch)).to.be.true;
});
it('returns true if search value present in different casing', ()=> {
const searchValue = 'boop';
const stringsToSearch = 'boo radley BOop';
expect(listHasSearchValues(searchValue, stringsToSearch)).to.be.true;
});
});
describe('multiple search values', ()=> {
it('returns true if all search values have matches ', ()=> {
const searchValue = 'radley oop';
const stringsToSearch = 'boo radley grep oop lee';
expect(listHasSearchValues(searchValue, stringsToSearch)).to.be.true;
});
it('returns false if not all search values have matches ', ()=> {
const searchValue = 'radley boop';
const stringsToSearch = 'boo radley grep oop lee';
expect(listHasSearchValues(searchValue, stringsToSearch)).to.be.false;
});
});
});
|
4c701da086e698e4beab6bad1032e54778bf6eab
|
TypeScript
|
dvsherbakov/nau-v
|
/src/features/auth/authReducer.ts
| 2.859375
| 3
|
import { EMAIL_AUTH, FAIL_AUTH, FAIL_REGISTER, FIRST_NAME_AUTH, LAST_NAME_AUTH, LOGIN_AUTH, LOGOUT_AUTH, MY_AUTH, PASSWD_AUTH, REGISTER_AUTH } from './actionTypes'
import { SetEmailAction, AuthActionTypes, SetPasswdAction, LoginAction, FirstnameAction, LastNameAction } from './types'
const initialState = {
email: '',
passwd: '123',
isAuth: false,
isRegistred: null,
firstName: '',
lastName: '',
accepted: 0,
}
export default (state = initialState, action: AuthActionTypes) => {
switch (action.type) {
case LOGIN_AUTH:
case MY_AUTH:
return { ...state, isAuth: true, firstName:(action as LoginAction).payload.firstName, lastName:(action as LoginAction).payload.lastName, email: (action as LoginAction).payload.email, accepted:(action as LoginAction).payload.accepted }
case EMAIL_AUTH:
return { ...state, email: (action as SetEmailAction).email }
case PASSWD_AUTH:
return { ...state, passwd: (action as SetPasswdAction).passwd }
case LOGOUT_AUTH:
case FAIL_AUTH:
return { ...state, isAuth: false }
case FAIL_REGISTER:
return {...state, isRegistred: false}
case REGISTER_AUTH:
return {...state, isRegistred: true, firstName:(action as LoginAction).payload.firstName, lastName:(action as LoginAction).payload.lastName, email: (action as LoginAction).payload.email}
case FIRST_NAME_AUTH:
return {...state, firstName: (action as FirstnameAction).payload}
case LAST_NAME_AUTH:
return {...state, lastName: (action as LastNameAction).payload}
default:
return state
}
}
|
0d5cc68e54c5d69c7a6585e2646ac114b46d9c8c
|
TypeScript
|
jordanmchiu/NaloxZone
|
/src/LocationHandler.ts
| 3.078125
| 3
|
import Pharmacy from "./util/Pharmacy";
import Location from "./util/Location";
import PharmacyManager from "./PharmacyManager";
import { createClient, GoogleMapsClient } from "@google/maps";
import GoogleMapsAPIKey from "./GoogleMapsAPIKey";
declare var Promise: any;
export default class LocationHandler {
private static instance: LocationHandler;
private static RADIUS: number = 6371000; // radius of earth in metres
public static MAX_DISTANCE: number = 10; // maximum km from pharmacy to be considered
// public static DEFAULT_LOCATION = new Location(49.2827, -123.1207, "Vancouver BC");
private PHARMACIES_TO_RETURN: number = 5;
private currLoc: Location;
private geoCoder = GoogleMapsClient;
private constructor() {
this.geoCoder = createClient({
key: GoogleMapsAPIKey.API_KEY,
Promise: Promise
});
this.currLoc = undefined;
}
// TODO: Handle exceptional cases
public static getInstance(): LocationHandler {
if (this.instance === undefined) {
this.instance = new LocationHandler();
}
return this.instance;
}
/**
* Given LocationHandler's current location, returns a list of a maximum of PHARMACIES_TO_RETURN
* pharmacies sorted by increasing distance from current location within 10 km. If trainingNeeded,
* only returns pharmacies that provide overdose training. Otherwise, returns all pharmacies.
* @param {boolean} trainingNeeded Specifies whether only pharmacies providing overdose
* training should be returned
* @returns {Pharmacy[]} List of maximum of PHARMACIES_TO_RETURN pharmacies sorted
* by increasing distance from this.curLoc
*/
public getNearest(trainingNeeded: boolean): Pharmacy[] {
if (this.currLoc === undefined) {
if (!trainingNeeded) {
return PharmacyManager.getInstance().getPharmacies();
} else {
return PharmacyManager.getInstance().getPharmacies().filter((pharmacy) => {
return pharmacy.getTraining();
});
}
} else {
const sortedPharms: Pharmacy[] = this.sortByClosest(this.currLoc);
const closePharms: Pharmacy[] = this.removeFarPharmacies(this.currLoc, sortedPharms);
return this.filterPharmacies(closePharms, trainingNeeded);
}
}
public setCurrLoc(loc: Location) {
if (loc !== null) { this.currLoc = loc; }
}
public getCurrLoc(): Location {
return this.currLoc;
}
/**
* Find distance in meters from a given location to a given pharmacy
* Implementation from CPSC210 (Paul Carter)
* @param {Pharmacy} l Specified location
* @param {Pharmacy} p Specified pharmacy
* @returns {number} Distance in meters
*/
public distanceToPharmacy(l: Location, p: Pharmacy): number {
const lat1: number = l.getLat() / 180.0 * Math.PI;
const lat2: number = p.getLocation().getLat() / 180.0 * Math.PI;
const deltaLon = (p.getLocation().getLon() - l.getLon()) / 180.0 * Math.PI;
const deltaLat = (p.getLocation().getLat() - l.getLat()) / 180.0 * Math.PI;
const a: number = Math.sin(deltaLat / 2.0) * Math.sin(deltaLat / 2.0)
+ Math.cos(lat1) * Math.cos(lat2)
* Math.sin(deltaLon / 2.0) * Math.sin(deltaLon / 2.0);
const c: number = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return c * LocationHandler.RADIUS;
}
/**
* Given a current location, returns a list of pharmacies in PharmacyManager
* ordered from first to last by distance from current location.
*
* Currently uses selection sort since there are few pharmacies. Can use more efficient
* algorithm later.
* @param {Location} l Given location
* @returns {Pharmacy[]} A list of pharmacies in PharmacyManager sorted from
* first to last by distance from given location
*/
public sortByClosest(l: Location): Pharmacy[] {
if (PharmacyManager.getInstance().getPharmacies().length === 0) {
return [];
}
let workingList: Pharmacy[] = PharmacyManager.getInstance().getPharmacies();
for (let i = 0; i < workingList.length; i++) {
let smallest = i;
for (let j: number = i + 1; j < workingList.length; j++) {
if (this.distanceToPharmacy(l, workingList[j]) < this.distanceToPharmacy(l, workingList[smallest])) {
smallest = j;
}
}
let temp: Pharmacy = workingList[i];
workingList[i] = workingList[smallest];
workingList[smallest] = temp;
}
return workingList;
}
/**
* Given a list of pharmacies, remove pharmacies that are more than MAX_DISTANCE km
* away from given location.
* @param {Location} l Given location
* @param {Pharmacy[]} pList Given list of pharmacies to remove
* @returns {Pharmacy[]}
*/
public removeFarPharmacies(l: Location, pList: Pharmacy[]): Pharmacy[] {
let closePharmacies: Pharmacy[] = [];
for (let i = 0; i < pList.length; i++) {
if (this.distanceToPharmacy(l, pList[i]) <= LocationHandler.MAX_DISTANCE * 1000) {
closePharmacies.push(pList[i]);
}
}
return closePharmacies;
}
/**
* Given a sorted list of pharmacies, returns a maximum of PHARMACIES_TO_RETURN from that list.
* If trainingNeeded, only include pharmacies that provide overdose training. Otherwise include
* pharmacies that don't provide overdose training.
* @param {Pharmacy[]} pList
* @param {boolean} trainingNeeded
* @returns {Pharmacy[]}
*/
public filterPharmacies(pList: Pharmacy[], trainingNeeded: boolean): Pharmacy[] {
let filteredPharmacies: Pharmacy[] = [];
let i: number = 0;
for (let idx = 0; idx < pList.length; idx++) {
if (trainingNeeded) {
if (pList[idx].getTraining()) {
filteredPharmacies.push(pList[idx]);
i++;
}
} else {
filteredPharmacies.push(pList[idx]);
i++;
}
if (i >= this.PHARMACIES_TO_RETURN) { break; }
}
return filteredPharmacies;
}
/*
public geocodeLocation(loc: string): Promise<Location> {
return new Promise((resolve, reject) => {
this.geoCoder.geocode({"address": loc}, function(results, status) {
if (status === 'OK') {
resolve(new Location(results[0].geometry.location.lat, results[0].geometry.location.lng, loc));
} else {
reject(new Error("Couldn't find the location " + loc));
}
})
});
}
*/
}
|
30651df043a74d120353ee46a54a99b2c5ae5795
|
TypeScript
|
YancaHernandez/back_movil
|
/src/models/user.shemas.ts
| 2.734375
| 3
|
import * as mongoose from 'mongoose';
import * as bcrypt from 'bcrypt';
export const UserSchema = new mongoose.Schema({
name: {
type: String,
default: 'Admin',
required: [true, 'El nombre es requerido']
},
email:String,
password:String,
type:{
type: String,
default: 'client'
},
created: {
type:Date,
default:Date.now
}
});
UserSchema.pre('save',async function(next:
mongoose.HookNextFunction){
try {
if(!this.isModified('password')){
return next();
}
const hashed = await bcrypt.hash(this['password'],10);
this['password'] = hashed;
return next();
} catch (error) {
return next(error);
}
});
|
3d9e629b73be5b8d916d688df8dd50ffac4e35e7
|
TypeScript
|
labjhipster/nhipster2
|
/src/main/webapp/app/entities/artist/service/artist.service.ts
| 2.53125
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { isPresent } from 'app/core/util/operators';
import { ApplicationConfigService } from 'app/core/config/application-config.service';
import { createRequestOption } from 'app/core/request/request-util';
import { IArtist, getArtistIdentifier } from '../artist.model';
export type EntityResponseType = HttpResponse<IArtist>;
export type EntityArrayResponseType = HttpResponse<IArtist[]>;
@Injectable({ providedIn: 'root' })
export class ArtistService {
public resourceUrl = this.applicationConfigService.getEndpointFor('api/artists');
constructor(protected http: HttpClient, private applicationConfigService: ApplicationConfigService) {}
create(artist: IArtist): Observable<EntityResponseType> {
return this.http.post<IArtist>(this.resourceUrl, artist, { observe: 'response' });
}
update(artist: IArtist): Observable<EntityResponseType> {
return this.http.put<IArtist>(`${this.resourceUrl}/${getArtistIdentifier(artist) as number}`, artist, { observe: 'response' });
}
partialUpdate(artist: IArtist): Observable<EntityResponseType> {
return this.http.patch<IArtist>(`${this.resourceUrl}/${getArtistIdentifier(artist) as number}`, artist, { observe: 'response' });
}
find(id: number): Observable<EntityResponseType> {
return this.http.get<IArtist>(`${this.resourceUrl}/${id}`, { observe: 'response' });
}
query(req?: any): Observable<EntityArrayResponseType> {
const options = createRequestOption(req);
return this.http.get<IArtist[]>(this.resourceUrl, { params: options, observe: 'response' });
}
delete(id: number): Observable<HttpResponse<{}>> {
return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' });
}
addArtistToCollectionIfMissing(artistCollection: IArtist[], ...artistsToCheck: (IArtist | null | undefined)[]): IArtist[] {
const artists: IArtist[] = artistsToCheck.filter(isPresent);
if (artists.length > 0) {
const artistCollectionIdentifiers = artistCollection.map(artistItem => getArtistIdentifier(artistItem)!);
const artistsToAdd = artists.filter(artistItem => {
const artistIdentifier = getArtistIdentifier(artistItem);
if (artistIdentifier == null || artistCollectionIdentifiers.includes(artistIdentifier)) {
return false;
}
artistCollectionIdentifiers.push(artistIdentifier);
return true;
});
return [...artistsToAdd, ...artistCollection];
}
return artistCollection;
}
}
|
ef6e4803c77dd34c4767d45042c26ef94daef35d
|
TypeScript
|
adriansalamon/gymnasiearbete
|
/generator/candidates.ts
| 3.421875
| 3
|
import {Ideology, IdeologyWithProbabilities, IdeologyWithCandidates, Candidate} from './interfaces'
// Creates the parties and assigns them an ideology based on their relative sizes.
export function createCandidates(numberOfCandidates: number, ideologies: Ideology[]): Candidate[] {
const tempIdeologies: IdeologyWithCandidates[] = ideologies.map((ideology) => {
return Object.assign({}, ideology, { numberOfCandidates: 0 })
})
let candidates: Candidate[] = []
const initialNumberOfCandidates = numberOfCandidates
// Loops while not every party has an ideology
while (numberOfCandidates > 0) {
// Loops though all future party indexes
for (let candidateIndex = 0; candidateIndex < initialNumberOfCandidates; candidateIndex++) {
// Loops through all ideologies
for (let ideologyIndex = 0; ideologyIndex < tempIdeologies.length; ideologyIndex++) {
if(numberOfCandidates <= 0) {
break
}
// Current ideology in loop
const ideology = tempIdeologies[ideologyIndex]
//Gets the number of parties that should belong to an ideology
const size = Math.round(initialNumberOfCandidates * ideology.size)
// An ideology needs to have at least one party
if ((size === 0 ? 1 : size) > ideology.numberOfCandidates) {
ideology.numberOfCandidates++
numberOfCandidates--
// Pushes the new party to the array
candidates.push({ ideology: ideologyIndex, size: undefined })
}
}
}
// Solves rounding errors with infinite loops
if (numberOfCandidates === 1) {
tempIdeologies[tempIdeologies.length-1].numberOfCandidates ++
numberOfCandidates--
candidates.push({ ideology: tempIdeologies.length-1, size: undefined })
}
}
// Assigns the sizes of the parties and then returns them
const candidatesWithSizes = assignCandidateSizes(candidates, tempIdeologies)
return candidatesWithSizes
}
// Assigns the probability of the voters within an ideology
export function assignProbabilityToIdeology(ideologies: Ideology[], candidates: Candidate[]): IdeologyWithProbabilities[] {
let result: IdeologyWithProbabilities[] = []
// Loops through each ideology
for (let ideologyIndex = 0; ideologyIndex < ideologies.length; ideologyIndex++) {
let ideology = ideologies[ideologyIndex]
// Maps parties and sets the size according to ideology
const withProbabilities = candidates.map(candidate => {
if (candidate.ideology === ideologyIndex) {
// Increases probability of voting for party aligned with ideology
if (candidate.size) {
return candidate.size * 8 * (ideology.ideologyPower**2)
}
} else {
return candidate.size
}
})
const normalized = normalize(withProbabilities)
// IDK why I have it here. Not needed but who knows. Creates array of 1,2,3...
const candidateList = Array(candidates.length).fill(0).map((val, index) => index)
// Assigns values to ideology
result = [...result, {size: ideology.size, probabilities: normalized, candidates: candidateList}]
//ideologies[ideologyIndex] = Object.assign({}, ideology, {probabilities: normalized, parties: partyList})
}
return result
}
// Assigns relative sizes to all parties based on their ideologies
function assignCandidateSizes(candidates: Candidate[], ideologies: IdeologyWithCandidates[]): Candidate[] {
// Loops through all ideologies
for (let ideologyIndex = 0; ideologyIndex < ideologies.length; ideologyIndex++) {
const ideology = ideologies[ideologyIndex]
// Calculates a distribution of sizes of parties within an ideology
let ideologySizeList = calculateDistribution(ideology.numberOfCandidates, ideology.candidatePower)
// Maps over parties and changes the size if the party ideology matches that of the state of the loop
candidates = candidates.map((candidate) => {
if (candidate.ideology === ideologyIndex) {
// Shifts the size from the array
let shift = ideologySizeList.shift()
const size: number = shift ? shift*ideology.size : 0
// Creates a new object and returns it to the array
const newCandidate = Object.assign({}, candidate, {size})
return newCandidate
} else {
return candidate
}
})
}
return candidates
}
// f(x) = ke^(-kx)
function fx (x: number,k: number): number {
return k*(Math.E**(-k*x))
}
// f(y) = - ln(y/k)/k
function fy (y: number, k: number): number {
return -(Math.log(y/k)/k)
}
// Normalizes an array of numbers so that the sum is 1
function normalize(array: (number | undefined)[]): number[] {
const sum = array.reduce((acc, val) => (acc && val) ? acc + val : 0)
const normalized = array.map(val => (val && sum) ? val/sum : 0)
return normalized
}
// Calculates the distribution of votes as a negative exponential distribution
function calculateDistribution (candidates: number, k:number): number[] {
// Adjusts the constant to change more and set 0.5 as the default
const adjustedK = (k**2)*0.5
// Defines the range of the distribution where y > 0.01
const xLimit = fy(0.01, adjustedK)
const stepSize = xLimit/candidates
const xValues = calculateXValues(candidates,adjustedK,stepSize,0,[])
const normalized = normalize(xValues)
return normalized
}
// Finds x values recursively and returns the result
function calculateXValues(candidates: number, k: number, stepSize: number, x: number, result: number[]):number[] {
if (candidates === 0) {
// Returns result at the end of recursion
return result
} else {
result.push(fx(x, k))
// Recursive call with decremented number of parties and incremented x value
return calculateXValues(candidates-1, k, stepSize, x+stepSize, result)
}
}
|
0a506ac52eb9f8479267b61ef7a0f77588f6ffa3
|
TypeScript
|
Zebradil/DictorClient
|
/src/app/cache.ts
| 2.96875
| 3
|
import { of } from 'rxjs/observable/of';
import { Observable } from 'rxjs/Observable';
import log from './log';
class CacheValue {
data: any;
observable: Observable<any>;
}
interface CacheCollection { [key: string]: CacheValue; }
export class Cacher {
private data: CacheCollection = {};
@log({ logId: 'Cacher.has' })
has(key: string): boolean {
return this.data.hasOwnProperty(key);
}
@log({ logId: 'Cacher.get' })
get(key: string): any {
if (this.has(key)) {
const val = this.data[key];
if (!val) {
return of(val);
}
if (val.data) {
return of(val.data);
} else {
return val.observable;
}
} else {
throw new Error('Key not found.');
}
}
@log({ logId: 'Cacher.setData', showResult: false })
setData(key: string, val: any): void {
this.data[key] = {
data: val,
observable: null,
};
}
@log({ logId: 'Cacher.setObservable', showResult: false })
setObservable(key: string, val: Observable<any>): void {
this.data[key] = {
data: null,
observable: val,
};
}
@log({ logId: 'Cacher.del', showResult: false })
del(key: string): void {
if (this.has(key)) {
delete this.data[key];
} else {
throw new Error('Key not found.');
}
}
}
|
bde665ddb4c2d395feb98a998c6b8115692e8e6a
|
TypeScript
|
kvesskrishna/te-sr-common-20210529
|
/tsintro.ts
| 2.59375
| 3
|
{
console.log("typescript");
let age: number = 90;
let uname: string = "john";
let nums: any[] = [1, 2, 3];
nums.push("w");
let isLogged: boolean = true;
console.log(uname);
}
|
96e01ec29589a6367f5717f6ac96d282a99ceebc
|
TypeScript
|
soufDev/frontend-test
|
/src/Redux/Selectors/index.ts
| 2.515625
| 3
|
import { groupByDate } from "../../utils";
import { IRootState, IActivity } from "../../types";
export const sortedActivitiesSelector = (state: IRootState) =>
Array.from(
groupByDate(
state.entity.activities.filter(
(activity: IActivity) => !activity.is_archived
)
)
);
export const sortedArchivedActivitiesSelector = (state: IRootState) =>
Array.from(
groupByDate(
state.entity.activities.filter(
(activity: IActivity) => activity.is_archived
)
)
);
|
c1897cc2653b6425b5b667d95ac5af6b6b792d10
|
TypeScript
|
lake2/tskoa
|
/src/decorators/Authorized.ts
| 2.859375
| 3
|
import { Controller, Meta } from "../Controller";
import { Class } from "../types";
export function Authorized(target: Class<Controller>): void;
export function Authorized(target: any, key: string, descriptor: PropertyDescriptor): void;
export function Authorized(value?: boolean): any;
export function Authorized(): any {
if (arguments.length === 0) {
return function () {
// @ts-ignore
decorate(...arguments, true);
};
} else if (arguments.length === 1) {
const arg = arguments[0];
if (typeof arg === "boolean") {
return function () {
// @ts-ignore
decorate(...arguments, arg);
};
} else if (typeof arg === "function") {
decorate(arg, true);
} else {
throw new Error("if error");
}
} else if (arguments.length === 3) {
// @ts-ignore
decorate(...arguments, true);
} else {
throw new Error("arguments length error.");
}
}
function decorate(target: any, key: string, descriptor: PropertyDescriptor, authorized?: boolean): void;
function decorate(target: Class<Controller>, authorized: boolean): void;
function decorate(): any {
if (arguments.length <= 2) {
const target: Class<Controller> = arguments[0];
const authorized: boolean | undefined = arguments[1];
let meta: Controller.Meta = target.prototype[Meta];
if (target.prototype[Meta] === undefined) {
meta = target.prototype[Meta] = {
route: "",
requests: {},
};
}
meta.authorized = authorized;
} else {
const target: any = arguments[0];
const key: string = arguments[1];
const authorized: boolean | undefined = arguments[3];
let meta: Controller.Meta = target[Meta];
if (target[Meta] === undefined) {
meta = target[Meta] = {
route: "",
requests: {},
};
}
if (meta.requests[key] === undefined) {
meta.requests[key] = { methods: [], path: "", parameters: [] };
}
meta.requests[key].authorized = authorized;
}
}
|
bebd3af32687efb885d63b9e2c046a2388a96b0e
|
TypeScript
|
valours/roller-coaster
|
/src/utils/parseFile.ts
| 2.8125
| 3
|
import fs from 'fs';
import { Data } from '../main';
export const parseFile = (path: string): Promise<Data> => new Promise((res, rej) => {
try {
const fileContent = fs.readFileSync(path, 'utf8').split('\n')
const [configuration, ...queue] = fileContent;
const [numberPlacesPerTurn, turnsPerDay, queueSize] = configuration.split(' ').map(parseInt);
const result: Data = {
numberPlacesPerTurn,
turnsPerDay,
queueSize,
queue: queue.map(group => parseInt(group, 10)),
}
res(result);
} catch (error) {
rej(error);
}
})
|
fe8533885dd6abf56731cbd6cc814372c1a9e817
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/wuzzy/wuzzy-tests.ts
| 2.890625
| 3
|
import { jarowinkler, levenshtein, ngram, pearson, jaccard, tanimoto } from 'wuzzy';
declare const aString: string;
declare const aStringArr: string[];
declare const bString: string;
declare const bStringArr: string[];
jarowinkler(aString, bString, 0.5);
jarowinkler(aString, bStringArr);
jarowinkler(aStringArr, bString, 0.5);
jarowinkler(aStringArr, bStringArr);
// @ts-expect-error
jarowinkler();
// @ts-expect-error
jarowinkler([1, 2, 3], bStringArr);
levenshtein(aString, bString, { d: 1, i: 0.5, s: 1 });
levenshtein(aString, bStringArr);
levenshtein(aStringArr, bString, { d: 1, i: 0.5, s: 1 });
levenshtein(aStringArr, bStringArr);
// @ts-expect-error
levenshtein();
// @ts-expect-error
levenshtein(aString, bString, { d: 1, i: 0.5 });
// @ts-expect-error
levenshtein([1, 2, 3], bStringArr);
ngram(aString, bString, 0.5);
ngram(aString, bStringArr);
ngram(aStringArr, bString, 0.5);
ngram(aStringArr, bStringArr);
// @ts-expect-error
ngram();
// @ts-expect-error
ngram([1, 2, 3], bStringArr);
pearson({ a: 2.5, b: 1 }, { o: 3.5, e: 6.0 });
// @ts-expect-error
pearson();
// @ts-expect-error
pearson({ a: '2.5', b: '1' }, { o: '3.5', e: '6.0' });
// @ts-expect-error
pearson(aString, bString);
// @ts-expect-error
pearson(aStringArr, bStringArr);
jaccard(aString, bString);
jaccard(aString, bStringArr);
jaccard(aStringArr, bString);
jaccard(aStringArr, bStringArr);
// @ts-expect-error
jaccard();
// @ts-expect-error
jaccard([1, 2, 3], bStringArr);
|
dc62d26ad79b88a5bf3116c337fae781330dcdab
|
TypeScript
|
SophieDel/orion
|
/server/src/backends/concepts/backend.ts
| 2.59375
| 3
|
import {Router, Request, Response} from 'express'
import {
concept_nodesAttribute,
modulesAttribute,
definition_valuesAttribute,
timeseries_valuesAttribute,
labelized_valuesAttribute,
suggestion_valuesAttribute,
} from '../../../../models/db'
import {
sequelize,
ConceptNodes,
ConceptLinks,
ConceptSuggestedLinks,
Modules,
DefinitionValues,
TimeseriesValues,
LabelizedValues,
SuggestionValues,
Datasets,
} from '../../database'
const options = {
raw: true,
logging: false // Change this line if a verbose script is needed.
}
export class ConceptBackend {
public router: Router;
constructor() {
// Create public Router
this.router = Router({mergeParams: true});
this.router.route('/')
.get(async (request: Request, response: Response) => {
// Get flat results (Sequelize normally returns complex Instance objects
// which are later parsed by express when calling response.json()
const nodes = await sequelize
.query(
'SELECT n.*, l.slug_to AS parent FROM concept_nodes n LEFT JOIN concept_links l ON n.slug = l.slug_from',
{
type: sequelize.QueryTypes.SELECT
}
)
response.json({
nodes,
});
})
this.router.route('/:slug')
.get(async (request: Request, response: Response) => {
if (request.params.slug) {
const concept = await this.fetch(request.params.slug)
const enrichedConcept = concept ? await this.enrichConcept(concept) : concept
response.json(enrichedConcept)
} else {
response.status(400)
response.json({
error: 'Concept slug parameter absent from query.'
})
}
})
this.router.route('/bulk')
.post(async (request: Request, response: Response) => {
const results = []
for (let slug in request.body.slugs) {
results.push(await this.fetch(slug))
}
response.json(results)
})
}
private async fetch(slug: string): Promise<any> {
return await ConceptNodes.findOne({
where: {
slug: slug,
},
...options,
});
}
private async enrichConcept(concept: concept_nodesAttribute): Promise<any> {
concept = await this.getModules(concept)
return concept
}
private async getModules(concept: concept_nodesAttribute): Promise<any> {
let modules = await Modules.findAll({
where: {
conceptNodeId: concept.id
},
...options,
})
modules = await Promise.all(
modules.map(this.enrichModule.bind(this))
)
return {
...concept,
modules,
}
}
private async enrichModule(m: modulesAttribute): Promise<any> {
let data: any = []
for (let data_identifier of m.data_identifiers) {
switch (m.type) {
case 'definition':
data.push(await DefinitionValues.findOne({
where: {
slug: data_identifier
},
...options,
}))
break
case 'timeseries':
var info = await Datasets.findOne({
where: {
name: data_identifier
},
...options,
})
var values = await TimeseriesValues.findAll({
where: {
dataset: data_identifier
},
...options,
})
data.push({
info,
values,
})
break
default:
break
}
}
return {
...m,
data,
}
}
}
|
064ec86ffe4d7e3f6953b87986ec4bb3e09bb68e
|
TypeScript
|
lds-ulbra-torres/Apae-Site
|
/client/src/app/pipes/procurar-categoria.pipe.ts
| 2.609375
| 3
|
import { ICategory } from './../../domain/interfaces/ICategory';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'searcher'
})
export class ProcurarCategoriaPipe implements PipeTransform {
transform(items: ICategory[], procuraTexto: string): ICategory[] {
if (!items) return[];
if (!procuraTexto) return items;
console.log(items );
procuraTexto = procuraTexto.toLowerCase();
return items.filter( it => {
return it.name_category.toLowerCase().includes(procuraTexto);
});
}
}
|
821a8a057c2adb5690de2580e599d35e90c2e022
|
TypeScript
|
nkunalic2/CarApp
|
/src/app/signup/step-three/step-three.component.ts
| 2.546875
| 3
|
import { Component, OnInit } from '@angular/core';
import {Router} from "@angular/router";
import {FormGroup} from "@angular/forms";
import {SignupService} from "../signup.service";
/* defining interface for options array */
interface Option {
name: string;
}
@Component({
selector: 'app-step-three',
templateUrl: 'step-three.component.html',
styleUrls: ['step-three.component.css']
})
export class StepThreeComponent implements OnInit {
stepThreeForm: FormGroup;
currentStep= 3;
/* this is a nested form in step 3 form which is displaying if user opted that he is married */
marriageForm: FormGroup;
signupForm:FormGroup;
//options for marriage duration
options: Option []=[
{name:'Less then a year'},
{name:'1-5 years'},
{name:'More then 5 years'}
];
constructor(private singupService: SignupService, private router: Router) {
}
ngOnInit() {
this.signupForm=<FormGroup>this.singupService.signUpForm;
this.stepThreeForm=<FormGroup>this.singupService.signUpForm.controls['stepThreeForm'];
/* setting current step for the progress bar */
this.singupService.setStep(this.currentStep);
this.marriageForm=<FormGroup>this.stepThreeForm.controls['marriageForm'];
}
//navigating to previous step
previousForm() {
this.router.navigate(["signup/step2"]);
}
}
|
e0dace79a0f730e90b92a6b5f1674c256d36a403
|
TypeScript
|
humandetail/linkup
|
/src/config/mahjong.ts
| 2.578125
| 3
|
/*
* @FilePath: \linkup-ts\src\config\mahjong.ts
* @Description: mahjong config
* @Author: humandetail
* @Date: 2021-03-19 22:45:02
* @LastEditors: humandetail
* @LastEditTime: 2021-03-25 23:17:34
*/
import { IMahjongItem } from '../../types';
// 底图素材
export const mahjongPic = './assets/img/mahjong.png';
// 单个元素尺寸
export const singleSize: [number, number] = [60, 75];
// 元素集合
export const mahjongs: IMahjongItem[] = [
// 万
{
name: 'character-one',
label: '一万',
pos: [0, 0]
},
{
name: 'character-two',
label: '二万',
pos: [1, 0]
},
{
name: 'character-three',
label: '三万',
pos: [2, 0]
},
{
name: 'character-four',
label: '四万',
pos: [3, 0]
},
{
name: 'character-five',
label: '五万',
pos: [4, 0]
},
{
name: 'character-six',
label: '六万',
pos: [5, 0]
},
{
name: 'character-seven',
label: '七万',
pos: [6, 0]
},
{
name: 'character-eight',
label: '八万',
pos: [7, 0]
},
{
name: 'character-night',
label: '九万',
pos: [8, 0]
},
// 筒
{
name: 'dot-one',
label: '一筒',
pos: [0, 1]
},
{
name: 'dot-two',
label: '二筒',
pos: [1, 1]
},
{
name: 'dot-three',
label: '三筒',
pos: [2, 1]
},
{
name: 'dot-four',
label: '四筒',
pos: [3, 1]
},
{
name: 'dot-five',
label: '五筒',
pos: [4, 1]
},
{
name: 'dot-six',
label: '六筒',
pos: [5, 1]
},
{
name: 'dot-seven',
label: '七筒',
pos: [6, 1]
},
{
name: 'dot-eight',
label: '八筒',
pos: [7, 1]
},
{
name: 'dot-night',
label: '九筒',
pos: [8, 1]
},
// 条
{
name: 'bamboo-one',
label: '一条',
pos: [0, 2]
},
{
name: 'bamboo-two',
label: '二条',
pos: [1, 2]
},
{
name: 'bamboo-three',
label: '三条',
pos: [2, 2]
},
{
name: 'bamboo-four',
label: '四条',
pos: [3, 2]
},
{
name: 'bamboo-five',
label: '五条',
pos: [4, 2]
},
{
name: 'bamboo-six',
label: '六条',
pos: [5, 2]
},
{
name: 'bamboo-seven',
label: '七条',
pos: [6, 2]
},
{
name: 'bamboo-eight',
label: '八条',
pos: [7, 2]
},
{
name: 'bamboo-night',
label: '九条',
pos: [8, 2]
},
// 字
{
name: 'east-widh',
label: '东风',
pos: [0, 3]
},
{
name: 'south-wind',
label: '南风',
pos: [1, 3]
},
{
name: 'west-wind',
label: '西风',
pos: [2, 3]
},
{
name: 'north-wind',
label: '北风',
pos: [3, 3]
},
{
name: 'red-dragon',
label: '红中',
pos: [4, 3]
},
{
name: 'green-dragon',
label: '发财',
pos: [5, 3]
},
{
name: 'white-dragon',
label: '白板',
pos: [6, 3]
}
];
|
b6d87097a0f7d8fa3d0df5dfec045e75822f27cf
|
TypeScript
|
darrenmce/advent2020
|
/9/index.ts
| 3.25
| 3
|
import { getTextInput } from '../lib/util';
const input = getTextInput(__dirname, 'input.txt');
function parseInput(input: string): number[] {
return input.split('\n').filter(Boolean).map((n) => parseInt(n, 10));
}
function validateNumber(preamble: number[], num: number): boolean {
return preamble.some((x, i) => {
const yIndex = preamble.indexOf(num - x);
return yIndex >= 0 && yIndex !== i;
});
}
function findInvalidNumber(preambleLength: number, numbers: number[]): number {
let set = numbers;
while(set.length > preambleLength) {
if (!validateNumber(set.slice(0, preambleLength), set[preambleLength])) {
return set[preambleLength];
}
set = set.slice(1);
}
return -1;
}
function findContiguousSum(numbers: number[], findSum: number): number[] {
for (let i = 0; i < numbers.length; i++) {
let j = i;
let sum = numbers[i];
const range = [numbers[i]];
while(sum < findSum) {
sum += numbers[++j];
range.push(numbers[j]);
if (sum === findSum) {
return range;
}
}
}
return [];
}
const numbers = parseInput(input);
const part1 = findInvalidNumber(25, numbers);
console.log('part1', part1);
const part2 = findContiguousSum(numbers, part1);
console.log('part2', Math.max(...part2) + Math.min(...part2));
|
0699717e8118772a914a36d707cbd1439b61da92
|
TypeScript
|
ayaz345/momentum2
|
/cli/commands/upgrade/upgrade.command-controller.ts
| 2.796875
| 3
|
import { Command, Injectable } from "../../deps.ts";
import { CommandController } from "../command-controller.interface.ts";
import { UpgradeCommandHandler } from "./upgrade.command-handler.ts";
import { UpgradeCommandParameters } from "./upgrade.command-parameters.ts";
@Injectable({ global: false })
export class UpgradeCommandController implements CommandController {
constructor(
private readonly commandHandler: UpgradeCommandHandler,
) {
}
createCommand(): Command {
const command = new Command("upgrade");
command.alias("u");
command.description("Upgrades the mvf CLI.");
command.arguments("[version]");
command.option(
"-r, --repository-url [repositoryUrl]",
"full URL of the repository to clone",
);
command.action((providedVersion: string, command: Command) => {
let version: string | null = null;
if (providedVersion?.length) {
const providedVersionParts = providedVersion.split(".").map((p) =>
p.trim()
);
if (providedVersionParts.some((p) => isNaN(parseInt(p, 10)))) {
throw new Error("Invalid version format. Expected format: 0.0.8");
}
version = providedVersionParts.join(".");
}
const commandParameters = new UpgradeCommandParameters({
version,
});
return this.commandHandler.handle(commandParameters);
});
return command;
}
}
|
3ea0589ccdd38dbbc4f2f4b7d527dd72833812f4
|
TypeScript
|
dtm0110/read-vietnamese-number
|
/src/Utils.ts
| 3.546875
| 4
|
/**
* Loại bỏ kí tự `char` đầu chuỗi `str`.
* @returns Chuỗi đã thực hiện loại bỏ.
* @param str Chuỗi bất kì.
* @param char Kí tự cần loại bỏ.
*/
function trimLeadingChars(str: string, char: string): string {
if (str === '')
return ''
let pos = 0
while (str[pos] === char[0])
pos++
return str.substring(pos)
}
/**
* Loại bỏ kí tự `char` ở cuối chuỗi `str`.
* @returns Chuỗi đã thực hiện loại bỏ.
* @param str Chuỗi bất kì.
* @param char Kí tự cần loại bỏ.
*/
function trimTrailingChars(str: string, char: string): string {
if (str === '')
return ''
let lastPos = str.length - 1
while (str[lastPos] === char[0])
lastPos--
return str.substring(0, lastPos + 1)
}
export default {
trimLeadingChars, trimTrailingChars
}
|
0c3ae1023777f9de30e54fbc9025319dcafdc99b
|
TypeScript
|
rtwhite10/example-repo
|
/src/OrderPage/context/actions.ts
| 2.5625
| 3
|
// WHY IS ENUM GIVING A ERROR
import moment from 'moment';
export type ACTIONTYPE =
| { type: 'changeTab'; payload: number }
| { type: 'toggleStorePickUp' }
| { type: "changeDate"; payload: moment.Moment };
// enum ActionTypes {
// changeTab
// };
export type Action = {
type: string,
// need to add better typechecking for payload
payload: any
}
|
e7b7a6355ca2a7d5134b9377ff0c4c8987169624
|
TypeScript
|
agui1940/shadowsocks-global
|
/src/reducers/proxyReducer.ts
| 2.703125
| 3
|
import { createAction, createReducer } from "@reduxjs/toolkit";
import uuid from "uuid/v4";
export type Shadowsocks = {
id: string;
host: string;
port: number;
method: string;
password: string;
name?: string;
plugin?: string;
plugin_opts?: string;
regionCode?: string;
};
export type Subscription = {
id: string;
name: string;
url: string;
shadowsockses: Shadowsocks[];
};
export type Socks5 = {
id: string;
regionCode?: string;
host: string;
port: number;
};
export type ProxyState = {
isStarted: boolean;
//Starting or Stopping
isProcessing: boolean;
activeId: string;
shadowsockses: Shadowsocks[];
subscriptions: Subscription[];
socks5s: Socks5[];
};
export const initialProxyState: ProxyState = {
isStarted: false,
isProcessing: false,
activeId: "",
shadowsockses: [],
subscriptions: [],
socks5s: []
};
export const startVpn = createAction("startVpn");
export const stopVpn = createAction("stopVpn");
export const setIsProcessing = createAction(
"setIsProcessing",
(isProcessing: boolean) => ({ payload: { isProcessing } })
);
export const setActiveId = createAction("setActiveId", (id: string) => ({
payload: { id }
}));
export const addProxy = createAction(
"addProxy",
(
proxy:
| { type: "shadowsocks"; config: Omit<Shadowsocks, "id"> }
| { type: "subscription"; config: Omit<Subscription, "id"> }
| { type: "socks5"; config: Omit<Socks5, "id"> }
) => ({
payload: { config: { id: uuid(), ...proxy.config }, type: proxy.type }
})
);
export const updateProxy = createAction(
"updateProxy",
(
proxy:
| { type: "shadowsocks"; config: Shadowsocks }
| { type: "subscription"; config: Subscription }
| { type: "socks5"; config: Socks5 }
) => ({
payload: proxy
})
);
export const deleteProxy = createAction(
"deleteProxy",
(proxy: { type: "shadowsocks" | "subscription" | "socks5"; id: string }) => ({
payload: proxy
})
);
export const proxyReducer = createReducer(initialProxyState, {
[setIsProcessing.type]: (state, action) => ({
...state,
isProcessing: action.payload.isProcessing
}),
[startVpn.type]: state => ({ ...state, isStarted: true }),
[stopVpn.type]: state => ({ ...state, isStarted: false }),
[setActiveId.type]: (state, action) => ({
...state,
activeId: action.payload.id
}),
[addProxy.type]: (state, action) => {
const { type, config } = action.payload;
switch (type) {
case "shadowsocks":
return {
...state,
shadowsockses: [...state.shadowsockses, config]
};
case "subscription":
return {
...state,
subscriptions: [...state.subscriptions, config]
};
default:
return {
...state,
socks5s: [...state.socks5s, config]
};
}
},
[updateProxy.type]: (state, action) => {
const { type, config } = action.payload;
const update = (proxies: { id: string }[], index?: number) => {
const updatedIndex =
index || proxies.findIndex(proxy => proxy.id === config.id);
return [
...proxies.slice(0, updatedIndex),
config,
...proxies.slice(updatedIndex + 1)
];
};
switch (type) {
case "shadowsocks": {
const shadowsocksIndex = state.shadowsockses.findIndex(
proxy => proxy.id === config.id
);
if (shadowsocksIndex === -1) {
const updatedSubscriptionIndex = state.subscriptions.findIndex(
subscription =>
subscription.shadowsockses.some(
shadowsocks => shadowsocks.id === config.id
)
);
const updatingSubscription =
state.subscriptions[updatedSubscriptionIndex];
const updatedSubscription = {
...updatingSubscription,
shadowsockses: update(updatingSubscription.shadowsockses)
};
return {
...state,
subscriptions: [
...state.subscriptions.slice(0, updatedSubscriptionIndex),
updatedSubscription,
...state.subscriptions.slice(updatedSubscriptionIndex + 1)
]
};
}
return {
...state,
shadowsockses: update(state.shadowsockses, shadowsocksIndex)
};
}
case "subscription":
return {
...state,
subscriptions: update(state.subscriptions)
};
default:
return {
...state,
socks5s: update(state.socks5s)
};
}
},
[deleteProxy.type]: (state, action) => {
const { type, id } = action.payload;
switch (type) {
case "shadowsocks": {
const shadowsocksIndex = state.shadowsockses.findIndex(
shadowsocks => shadowsocks.id === id
);
console.log(shadowsocksIndex);
if (shadowsocksIndex === -1) {
const deletedSubscriptionIndex = state.subscriptions.findIndex(
subscription =>
subscription.shadowsockses.some(
shadowsocks => shadowsocks.id === id
)
);
const deletingSubscription =
state.subscriptions[deletedSubscriptionIndex];
const deletedSubscription = {
...deletingSubscription,
shadowsockses: deletingSubscription.shadowsockses.filter(
shadowsocks => shadowsocks.id !== id
)
};
return {
...state,
subscriptions: [
...state.subscriptions.slice(0, deletedSubscriptionIndex),
deletedSubscription,
...state.subscriptions.slice(deletedSubscriptionIndex + 1)
]
};
}
return {
...state,
shadowsockses: state.shadowsockses.filter(
shadowsocks => shadowsocks.id !== id
)
};
}
case "subscription": {
return {
...state,
subscriptions: state.subscriptions.filter(
subscription => subscription.id !== id
)
};
}
default: {
return {
...state,
socks5s: state.socks5s.filter(socks5 => socks5.id !== id)
};
}
}
}
});
|
82ed2fda45f8dda7a65e720ac0dbc55f416a6345
|
TypeScript
|
RicardoMiguel/url-shortener
|
/src/functions/cleanUrls.test.ts
| 2.578125
| 3
|
import * as td from 'testdouble';
import { expect } from 'chai';
import {UrlService} from "../service/urlService";
import cleanUrls from "./cleanUrls";
describe('cleanUrls', function () {
beforeEach(function () {
this.urlService = td.object<UrlService>();
});
afterEach(() => td.reset());
it('should return number of urls cleaned', async function () {
td.when(this.urlService.clean())
.thenResolve(5);
const number = await cleanUrls(this.urlService);
expect(number).to.equal(5);
});
it('should re-throw any error', function () {
td.when(this.urlService.clean())
.thenReject(new Error('Error'));
const promise = cleanUrls(this.urlService);
return expect(promise).to.eventually.rejectedWith(Error);
});
});
|
a0c1282e92fcc8f07a76395202675655eeadfead
|
TypeScript
|
kembek/html-css-js
|
/TS/src/5-interface.ts
| 3.890625
| 4
|
interface Person {
firstName: string;
lastName: string;
age: number;
}
function debugPerson(person: Person) {
console.dir("This person", person);
}
const luke = {
firstName: "Luke",
lastName: "Sky Waker",
age: 21
};
debugPerson(luke);
interface User {
firstName: string;
lastName: string;
age: number;
isActive: boolean;
}
class User {
fullName: string;
constructor(
public firstName: string,
public lastName: string,
public age: number,
public isActive: boolean
) {
this.fullName = `${firstName} ${lastName}`;
}
public greet() {
console.log(this.fullName);
}
}
const obi = new User("Obi", "Van", 30, true);
|
f1c276778b94bcbcc42306be86edfb80ad084f97
|
TypeScript
|
palantir/plottable
|
/src/interactions/pointerInteraction.ts
| 2.84375
| 3
|
/**
* Copyright 2014-present Palantir Technologies
* @license MIT
*/
import { Component } from "../components/component";
import { Point } from "../core/interfaces";
import * as Dispatchers from "../dispatchers";
import * as Utils from "../utils";
import { Interaction } from "./interaction";
export type PointerCallback = (point: Point) => void;
export class Pointer extends Interaction {
private _mouseDispatcher: Dispatchers.Mouse;
private _touchDispatcher: Dispatchers.Touch;
private _overComponent = false;
private _pointerEnterCallbacks = new Utils.CallbackSet<PointerCallback>();
private _pointerMoveCallbacks = new Utils.CallbackSet<PointerCallback>();
private _pointerExitCallbacks = new Utils.CallbackSet<PointerCallback>();
private _mouseMoveCallback = (p: Point, e: MouseEvent) => this._handleMouseEvent(p, e);
private _touchStartCallback = (ids: number[], idToPoint: Point[], e: TouchEvent) => this._handleTouchEvent(idToPoint[ids[0]], e);
protected _anchor(component: Component) {
super._anchor(component);
this._mouseDispatcher = Dispatchers.Mouse.getDispatcher(this._componentAttachedTo);
this._mouseDispatcher.onMouseMove(this._mouseMoveCallback);
this._touchDispatcher = Dispatchers.Touch.getDispatcher(this._componentAttachedTo);
this._touchDispatcher.onTouchStart(this._touchStartCallback);
}
protected _unanchor() {
super._unanchor();
this._mouseDispatcher.offMouseMove(this._mouseMoveCallback);
this._mouseDispatcher = null;
this._touchDispatcher.offTouchStart(this._touchStartCallback);
this._touchDispatcher = null;
}
private _handleMouseEvent(p: Point, e: MouseEvent) {
const insideSVG = this._mouseDispatcher.eventInside(this._componentAttachedTo, e);
this._handlePointerEvent(p, insideSVG);
}
private _handleTouchEvent(p: Point, e: TouchEvent) {
const insideSVG = this._touchDispatcher.eventInside(this._componentAttachedTo, e);
this._handlePointerEvent(p, insideSVG);
}
private _handlePointerEvent(p: Point, insideSVG: boolean) {
const translatedP = this._translateToComponentSpace(p);
const overComponent = this._isInsideComponent(translatedP);
if (overComponent && insideSVG) {
if (!this._overComponent) {
this._pointerEnterCallbacks.callCallbacks(translatedP);
}
this._pointerMoveCallbacks.callCallbacks(translatedP);
} else if (this._overComponent) {
this._pointerExitCallbacks.callCallbacks(translatedP);
}
this._overComponent = overComponent && insideSVG;
}
/**
* Adds a callback to be called when the pointer enters the Component.
*
* @param {PointerCallback} callback
* @return {Interactions.Pointer} The calling Pointer Interaction.
*/
public onPointerEnter(callback: PointerCallback) {
this._pointerEnterCallbacks.add(callback);
return this;
}
/**
* Removes a callback that would be called when the pointer enters the Component.
*
* @param {PointerCallback} callback
* @return {Interactions.Pointer} The calling Pointer Interaction.
*/
public offPointerEnter(callback: PointerCallback) {
this._pointerEnterCallbacks.delete(callback);
return this;
}
/**
* Adds a callback to be called when the pointer moves within the Component.
*
* @param {PointerCallback} callback
* @return {Interactions.Pointer} The calling Pointer Interaction.
*/
public onPointerMove(callback: PointerCallback) {
this._pointerMoveCallbacks.add(callback);
return this;
}
/**
* Removes a callback that would be called when the pointer moves within the Component.
*
* @param {PointerCallback} callback
* @return {Interactions.Pointer} The calling Pointer Interaction.
*/
public offPointerMove(callback: PointerCallback) {
this._pointerMoveCallbacks.delete(callback);
return this;
}
/**
* Adds a callback to be called when the pointer exits the Component.
*
* @param {PointerCallback} callback
* @return {Interactions.Pointer} The calling Pointer Interaction.
*/
public onPointerExit(callback: PointerCallback) {
this._pointerExitCallbacks.add(callback);
return this;
}
/**
* Removes a callback that would be called when the pointer exits the Component.
*
* @param {PointerCallback} callback
* @return {Interactions.Pointer} The calling Pointer Interaction.
*/
public offPointerExit(callback: PointerCallback) {
this._pointerExitCallbacks.delete(callback);
return this;
}
}
|
edab648d30a436fbd5b28acec6787054754c83d2
|
TypeScript
|
yktoo/infopi
|
/src/app/_pipes/time-ago.pipe.ts
| 3.296875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
/**
* Translate the provided date into the 'xxx time ago' string.
*/
@Pipe({
name: 'timeAgo',
})
export class TimeAgoPipe implements PipeTransform {
transform(d: Date | null | undefined): string {
if (!d) {
return '';
}
const seconds = Math.floor((new Date().getTime() - d.getTime()) / 1000);
// Years
let interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + ' years ago';
}
if (interval === 1) {
return 'A year ago';
}
// Months
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + ' months ago';
}
if (interval === 1) {
return 'A month ago';
}
// Days
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + ' days ago';
}
if (interval === 1) {
return 'Yesterday';
}
// Hours
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + ' hours ago';
}
if (interval === 1) {
return 'An hour ago';
}
// Minutes
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + ' minutes ago';
}
if (interval === 1) {
return 'A minute ago';
}
// Less than a minute
return 'Just now';
}
}
|
824e0bd0009c4015cf874d3bb3d26f5ff796aeda
|
TypeScript
|
wjbaker101/permidea
|
/src/frontend/ts/component/TitleTextboxComponent.ts
| 2.53125
| 3
|
import { NoteService } from '../service/NoteService';
import { StateService } from '../service/StateService';
export const TitleTextboxComponent = (elementSelector: string) => {
const titleTextbox: HTMLInputElement
= document.querySelector(elementSelector);
const events = {
onInput(): void {
StateService.getState().currentNote.title = titleTextbox.value;
NoteService.updateNote();
},
};
titleTextbox.addEventListener('input', events.onInput);
titleTextbox.addEventListener('change', events.onInput);
titleTextbox.addEventListener('cut', events.onInput);
titleTextbox.addEventListener('copy', events.onInput);
titleTextbox.addEventListener('paste', events.onInput);
return titleTextbox;
}
|
c08929c6b4eec510eef12009ac3cd0d170cd4c61
|
TypeScript
|
shanushalini011/type-script
|
/src/06_declaration_types/type_assertion.ts
| 3.28125
| 3
|
/*
{
"created_at" : "14 April 2017",
"aim_of_script" : "To represent Type Assertion in TypeScript",
"coded_by" : "Rishikesh Agrawani",
}
*/
var strNum = "1235x";
console.log(typeof strNum)
/*
type_assertion.ts(10,5): error TS2322:
Type 'string' is not assignable to type 'number'.
*/
//var num : number = strNum; /*Uncomment this line to see the above error*/
//or
//var num : number = <number>strNum /*Uncomment this line to see the above error*/
var num : number = <number> <any> strNum;
console.log(typeof num)
console.log((num as number) + 4231)
|
08abf79e9361aeb1f1019ee4ddcbb7d6522ea0e5
|
TypeScript
|
martinbojnansky/sheetspi
|
/backend/src/framework/models.ts
| 2.53125
| 3
|
import { ApiAction } from "../../../api/api";
import { TableQuery } from "../../../api/models";
export type Controller<TPayload> = (action: ApiAction<TPayload>) => unknown;
export interface Repository<T> {
getAll: (query: TableQuery) => T[];
getById: (id: string) => T;
create: (item: T) => T;
delete: (id: string) => void;
}
|
ae0922703686f4b2cf0428aff6cdc5213e0ebc61
|
TypeScript
|
MeasureAuthoringTool/fhir-typescript-models
|
/src/models/fhir/classes/TerminologyCapabilitiesSoftware.ts
| 2.75
| 3
|
/* eslint-disable import/prefer-default-export, import/no-cycle */
import {
BackboneElement,
Extension,
FhirField,
ITerminologyCapabilitiesSoftware,
PrimitiveString,
FhirType
} from "../internal";
@FhirType("TerminologyCapabilitiesSoftware", "BackboneElement")
export class TerminologyCapabilitiesSoftware extends BackboneElement {
static readonly baseType: string = "FHIR.BackboneElement";
static readonly namespace: string = "FHIR";
static readonly typeName: string = "TerminologyCapabilities.Software";
static readonly primaryCodePath: string | null = null;
@FhirField("PrimitiveString")
public name?: PrimitiveString;
@FhirField("PrimitiveString")
public version?: PrimitiveString;
public static parse(
json: ITerminologyCapabilitiesSoftware,
providedInstance: TerminologyCapabilitiesSoftware = new TerminologyCapabilitiesSoftware()
): TerminologyCapabilitiesSoftware {
const newInstance: TerminologyCapabilitiesSoftware = BackboneElement.parse(json, providedInstance);
if (json.name !== undefined) {
newInstance.name = PrimitiveString.parsePrimitive(json.name, json._name);
}
if (json.version !== undefined) {
newInstance.version = PrimitiveString.parsePrimitive(json.version, json._version);
}
return newInstance;
}
public static isTerminologyCapabilitiesSoftware(input?: unknown): input is TerminologyCapabilitiesSoftware {
const castInput = input as TerminologyCapabilitiesSoftware;
return !!input && castInput.getTypeName && castInput.getTypeName() === "TerminologyCapabilitiesSoftware";
}
public toJSON(): ITerminologyCapabilitiesSoftware {
const result: ITerminologyCapabilitiesSoftware = super.toJSON();
if (this.name) {
result.name = this.name.value;
result._name = Extension.serializePrimitiveExtension(this.name);
}
if (this.version) {
result.version = this.version.value;
result._version = Extension.serializePrimitiveExtension(this.version);
}
return result;
}
public clone(): TerminologyCapabilitiesSoftware {
return TerminologyCapabilitiesSoftware.parse(this.toJSON());
}
public getTypeName(): string {
return "TerminologyCapabilitiesSoftware";
}
}
/* eslint-enable import/prefer-default-export, import/no-cycle */
|
0ea21b32baabd53aa5b4299b8c60b0c026bdb32d
|
TypeScript
|
RubyBe/meal-tracker
|
/app/app.component.ts
| 2.734375
| 3
|
// import Component code from angulary library
import { Component, EventEmitter } from 'angular2/core';
import { Meal } from './meal.model';
import { MealListComponent} from './meal-list.component';
// annotation
@Component({
selector: 'my-app',
directives: [MealListComponent],
template: `
<div class = "container jumbotron">
<h1>Downtown Seattle Meal Tracker</h1>
<meal-list
[mealList]="meals"
(onMealSelect)="mealWasSelected($event)">
</meal-list>
</div>
`
})
// class declaration
export class AppComponent {
public meals: Meal[];
constructor() {
this.meals = [
new Meal("Spaghetti", 560, "Meatsauce and chitarra pasta"),
new Meal("Pizza", 480, "Pagliacci's Brooklyn, two slices"),
new Meal("Salad", 295, "Arugula, oil, and vinegar")
];
}
mealWasSelected(clickedMeal: Meal): void {
console.log(clickedMeal.description);
}
}
|
9ac17f1f1b75ffe916dd8898b1a84f00d093103e
|
TypeScript
|
1z2x3c4v5b6n7m8/yesno
|
/commands-old/eval.ts
| 2.765625
| 3
|
import Spark from 'sparkbots'
import Discord from 'discord.js'
const Command = Spark.command("eval")
Command.setLevel(10)
Command.allowDms(true)
Command.setDescription('**Aliases**: none\n**Description**: Evals js code\n**Arguments**: Code to eval (required)\n**Example**: `!!eval message.reply(\'hi\')`')
module.exports = Command;
Command.code = (client, message: Discord.Message) => {
const clean = text => {
if (typeof(text) === "string")
return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203));
else
return text;
}
const {codeBlock} = Discord.Formatters
//
// Trying to prevent people from destroying their computer / bot / discord account.
// Start
if (message.content.split(" ").length <= 1) {
return message.channel.send("<:no:424361302069346304> Umm do you want me to eval nothing? <:thonking:419347836610805760>")
}
const code = message.content.replace(client.config.prefix + "eval", "");
if (code.match(/client.token/gi) && !client.developer) {
return message.channel.send("[Spark] Using this code could give other people access to your bot. If you know what you're doing, you can enable developer mode for this session by typing `" + client.config.prefix + "developer true`. \n**ONLY USE THIS IF YOU KNOW WHAT YOU ARE DOING!!**")
}
if (code.match(/rm -rf \/ --no-preserve-root/gi)) {
return message.channel.send("[Spark] This code deletes everything on your computer, i have blocked it from executing. Please don't use code that you don't understand.")
}
if (code.match(/no-preserve-root/gi) && !client.developer) {
return message.channel.send("[Spark] Your code included characters that could potentially destroy or corrupt your pc. I have stopped execution. | If you know what you're doing, you can enable developer mode for this session by typing `" + client.config.prefix + "developer true`. \n**ONLY USE THIS IF YOU KNOW WHAT YOU ARE DOING!!**")
}
// End
// Trying to prevent people from destroying their computer / bot / discord account.
//
//
// Eval code
// Start
try {
let evaled = eval(code);
//
// Trying to resolve promise if there is one
// Start
if (evaled instanceof Promise) {
message.channel.send("Resolving promise...").then(m => {
var done = false;
var timeout = setTimeout(function() {
m.edit("Couldn't resolve promise in time. :clock2: (20s)")
var done = true;
}, 20000);
evaled.then((x) => {
if (done == true) {
return
}
clearTimeout(timeout)
next(x, m)
done = true;
}).catch(err => {
if (done == true) {
return
}
clearTimeout(timeout)
error(err)
done = true;
})
})
}
// End
// Trying to resolve promise if there is one
//
else {
next(evaled, null)
}
// End
// Eval code
//
function next(evaled, m) {
if (typeof evaled !== "string") {
evaled = require("util").inspect(evaled);
}
console.log(evaled)
if (evaled.length >= 1900) {
evaled = evaled.substring(0, 1900) + " (... character limit reached. | See rest in your console.)"
}
//
// Make sure bot token is not sent to the users in the channel
// Start
var tokendetection = new RegExp(client.token, 'gi')
evaled = evaled.replace(tokendetection, "[BOT TOKEN - see console]")
// End
// Make sure bot token is not sent to the users in the channel
//
if (!m) {
message.channel.send(codeBlock('xl', clean(evaled)));
} else {
m.edit(codeBlock('xl', clean(evaled)));
}
}
} catch (err) {
error(err)
}
function error(err) {
message.channel.send(`\`ERROR\` ${codeBlock('xl', clean(err))}`);
}
}
|
68f8739b9a117c5a6aba1c863b7e4ba51a911e11
|
TypeScript
|
sharvit/patternfly-react
|
/packages/react-catalog-view-extension/src/helpers/util.ts
| 3.09375
| 3
|
import * as React from 'react';
/**
* @param {string} prefix - String to prefix unique ID with
*/
export function getUniqueId(prefix = 'pf') {
const uid =
new Date().getTime() +
Math.random()
.toString(36)
.slice(2);
return `${prefix}-${uid}`;
}
/**
* Returns the given React children prop as a regular array of React nodes.
*
* @param {React.ReactNode} children - Child react node
*/
export const childrenToArray = (children: React.ReactNode) =>
children && React.Children.count(children) > 0 && React.Children.toArray(children);
|
aa4e0b88ec34f2dedc975c9701275167adf7884a
|
TypeScript
|
Unkgod/typescript
|
/pregunta1.ts
| 3.046875
| 3
|
//PREGUNTA # 1
var equip1:string = "Bayern Munich";
var equip2:string = "Borrussia Dortmud";
//Tarea #1
var jugadores1: Array <string> = ['Neuer', 'Pavard', 'Martinez', 'Alaba', 'Davies',
'Kimmich', 'Goretzka', 'Coman', 'Muller', 'Gnarby', 'Lewandowski'];
var jugadores2: Array <string> = ['Burki', 'Schulz', 'Hummels', 'Akanji', 'Hakimi',
'Weigl', 'Witsel', 'Hazard', 'Brandt', 'Sancho', 'Gotze'];
//Tarea #2
var gk: string = jugadores1[0];
var fieldPlayers: Array <string> = jugadores1.slice(1);
console.log(gk)
console.log(fieldPlayers)
//Tarea # 3
var allPlayers: Array <string> = jugadores1.concat(jugadores2);
console.log(allPlayers)
//Tarea #4
var players1Final: Array <string> = jugadores1;
players1Final.push('Thiago', 'Coutinho', 'Perisic');
console.log(players1Final)
//Tarea #5
var equipo1:number = 1.33;
var empate:number = 3.25;
var equipo2:number = 6.5;
//Tarea #6
var printGoals = function (...nam){
var ban:Array <string> = [];
for (let i:number = 0; i < nam.length; i++){
if (ban.includes(nam[i]) == false){
var num:number = 1;
for (let j:number = i+1; j < nam.length; j++){
if (nam[i] == nam[j]){
num = num + 1;
}
}
console.log(nam[i]+ " +"+ num+ " goals")
ban.push(nam[i])
}
}
}
printGoals("Lewandowski", "Gnarby", "Lewandowski", "Hummels", "Hummels", "otro", "Lewandowski");
//Tarea #7
console.log(Math.min(equipo1, equipo2) === equipo1 && "el equipo que tiene las probabilidades de ganar es el: "+ equip1)
console.log(Math.min(equipo1, equipo2) === equipo2 && "el equipo que tiene las probabilidades de ganar es el: "+ equip2)
|
c51fba3f1ab60a8d19662c586e3b85d9b89d8e09
|
TypeScript
|
NeerajVyas/workin--rms
|
/Case-study/rms-angular/src/app/login-form/authentication.service.ts
| 2.703125
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs';
import Links from '../links.module';
export class User{
constructor(
public userId:string,
public userEmail:string,
public userRole:string,
public userName:string,
public userAIStatus:string
) {}
}
/**
* For passing data from one componenet to other component
*
* 1. import { BehaviorSubject } from 'rxjs';
*
* Inside Sevice
* 2. private user = new BehaviorSubject<User>(null);
currentUser = this.user.asObservable();
* 3. Inside Service , Inside get Http
this.updateCurrentUser(userData);
wherever you want to use it, Inside the constructor.
constructor(
private authService: AuthenticationService) {
authService.currentUser.subscribe(user => {
console.log('user,..', user);
})
}
*/
@Injectable()
export class AuthenticationService {
private user = new BehaviorSubject<User>(null);
currentUser = this.user.asObservable();
private tokenGenerated : any;
constructor(private httpClient:HttpClient) { }
authenticate(username, password) {
// this.authenticateUsingJwt(username,password);
//const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ':' + password) });
console.log("authenticate",username);
const authJSON = localStorage.getItem('auth');
console.log(authJSON);
const headers = new HttpHeaders(JSON.parse(authJSON));
/*
return this.httpClient.post<any>('http://localhost:8080/authenticate',{username,password}).pipe(
map( tokenData => {
console.log('called',tokenData)
//this.tokenGenerated=tokenData;
// localStorage.setItem('username','username')
localStorage.setItem('auth', JSON.stringify({ Authorization: 'Bearer' + tokenData }));
return tokenData;
}
)
);
*/
return this.httpClient.get<User>(Links.base+'login/validateLogin?emailId='+username+'',{headers}).pipe(
map(
userData => {
console.log(" --after ")
console.log(userData)
this.updateCurrentUser(userData);
// sessionStorage.setItem('username',username);
// sessionStorage.setItem('auth', JSON.stringify({ Authorization: 'Basic ' + btoa(username + ':' + password) }));
localStorage.setItem('username',username);
// localStorage.setItem('auth', JSON.stringify({ Authorization: 'Basic ' + btoa(username + ':' + password) }));
localStorage.setItem('currentUser', JSON.stringify(userData));
return userData;
}, (response) => response.json()
)
);
}
authenticateUsingJwt(username,password){
//Bearer
var credentials = {
"username" : username,
"password" : password
};
console.log("authenticateJWT",credentials);
console.log(credentials);
return this.httpClient.post<any>(Links.baseAuth,{username,password}).pipe(
map( tokenData => {
console.log('called',tokenData)
//this.tokenGenerated=tokenData;
// localStorage.setItem('username','username')
localStorage.setItem('auth', JSON.stringify({ Authorization: 'Bearer ' + tokenData.token }));
return tokenData;
}
)
);
}
updateCurrentUser(user){
this.user.next(user);
console.log('Value of currebt user updated', user);
}
isUserLoggedIn() {
// let user = sessionStorage.getItem('username')
let user = localStorage.getItem('username')
console.log(user)
console.log("InsideUserLoggedIn")
console.log(!(user === null))
return !(user === null)
}
logOut() {
//sessionStorage.removeItem('username')
//sessionStorage.removeItem('username')
localStorage.removeItem('username')
localStorage.removeItem('auth')
localStorage.clear();
}
}
|
7d15d735a4424d084020c798baeb6e7b4f8b85d6
|
TypeScript
|
Neekky/file_migrate
|
/TypeScript/ts基础部分/poker.ts
| 3.453125
| 3
|
// import { printDeck, createDeck } from "./funcs";
// const deck = createDeck();
// printDeck(deck)
/**
* 扑克牌小练习
* 1.创建一副扑克牌(不包括大小王),打印该扑克牌
* 2.使用枚举创造程序
* 3.使用模块化
* 4.用接口改造程序,加入大小王
* 5.用类改造程序 ,增加洗牌功能
*/
import { Deck } from "./deck"
const deck = new Deck();
deck.shuffle();
console.log("===========洗牌之后===========")
deck.print();
const pokerResult = deck.publish();
console.log("===========发牌之后===========")
console.log('===========玩家1===========')
pokerResult.player1.print()
console.log('===========玩家2===========')
pokerResult.player2.print()
console.log('===========玩家3===========')
pokerResult.player3.print()
console.log('===========桌面剩余牌===========')
pokerResult.left.print()
|
a8ffbd85e6e7475fd31326bb073549ca40711b06
|
TypeScript
|
cyps1000/test-app
|
/src/utils/choice.ts
| 3.203125
| 3
|
/**
* Handles picking a random number from an array
*/
export const choice = (arr: any) => {
const randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
};
|
e014dd395c86cb8532065232b418df894ec44572
|
TypeScript
|
drecocoa/dpainter
|
/src/scripts/Data.ts
| 3.03125
| 3
|
import { LineStore } from './Line';
export class Layer{
name:string="";
alpha:number=1;
data:any={};
}
export class VectorLayer extends Layer{
}
export class Storable{
id:number=0;
layer:number=0;
type:string=this.constructor.name;
//todo!//
static is<T extends Storable>(obj:any,c: new () => T): obj is T{
if(obj.type===undefined)return false;
return c.name==obj.type;
}
}
export class DataStore{
layers: Layer[] = [];
//todo find a better solution
recycledIds:number[] = [];
largestId = 1;
addLayer(layer:Layer ):void{
this.layers.push(layer);
}
removeLayer(layerIndex:number):void{
let delted = this.layers.splice(layerIndex,1);
for (const d of delted) {
Object.keys(d.data).forEach(
k=>Object.keys(d.data[k]).forEach(
kk=>this.recycledIds.push(Number(kk))
)
);
}
}
getAll():Storable[]{
return this.layers.map(l=>(Object.values(l.data).flatMap(d=>Object.values(d)))).reduce((a,b)=>[...a,...b],[]);
}
getAllOfType<T extends Storable>(c: new () => T):T[]{
return this.layers.map(l=>{
if(l.data[c.name]===undefined)return [];
return Object.values(l.data[c.name]) as T[]
}).reduce((a,b)=>[...a,...b],[]);
}
get<T extends Storable>(c: new () => T,id:number):T|undefined{
return this.layers.map(l=>{
if(l.data[c.name]===undefined)return undefined;
return l.data[c.name][id];
}).reduce((a,b)=>a===undefined?b:a);
}
remove<T extends Storable>(value:T,layerIndex:number):void{
if(value.id==0){
return;
}
let d = this.layers[layerIndex].data;
const t = value.constructor.name;
if(d[t] === undefined){
d[t] = {};
return;
}
if(d[t][value.id]){
delete d[t][value.id];
this.recycledIds.push(value.id);
}
}
store<T extends Storable>(value:T,layerIndex:number):void{
if(this.layers.length<=layerIndex){
throw new Error("Layer index out of range");
}
if(value.id==0){
if(this.recycledIds.length>0){
value.id = this.recycledIds.pop() as number;
}else{
value.id = this.largestId++;
}
}
let d = this.layers[layerIndex].data;
const t = value.constructor.name;
if(d[t] === undefined){
d[t] = {};
}
d[t][value.id]=value;
}
}
|
13c0ab8a3d42c7611ea07ec10027329fa4f01953
|
TypeScript
|
njgheorghita/ethpm.js
|
/src/package/resolver/index.ts
| 2.625
| 3
|
/**
* @module "ethpm/package/resolver"
*/
import { IpfsService } from 'ethpm/storage/ipfs';
import { v3 } from 'ethpm/manifests/v3';
import { Package, Sources, SourceWithContent, SourceWithUrls } from 'ethpm/package';
import { URL } from 'url';
interface ResolvedBuildDependencies {
[key: string]: ResolvedPackage;
}
export class Resolver {
public ipfsBackend: IpfsService
constructor(ipfsService: IpfsService) {
this.ipfsBackend = ipfsService
}
async resolve(contentURI: URL) {
const rawManifest = await this.ipfsBackend.read(contentURI)
if (!rawManifest) {
throw new Error("Manifest at " + contentURI + " not found.")
}
const originalPackage = await v3.read(rawManifest)
let sources: Sources = {}
let buildDependencies: ResolvedBuildDependencies = {}
// resolve any content-addressed sources
if (originalPackage.sources) {
for (const sourceId in originalPackage.sources) {
if (Object.prototype.hasOwnProperty.call(originalPackage.sources[sourceId], 'urls')) {
const sourceObject = originalPackage.sources[sourceId] as SourceWithUrls
const source = await this.ipfsBackend.read(sourceObject['urls'][0] as URL)
if (source) {
sources[sourceId] = {
content: source,
type: "solidity", // should be optional
installPath: sourceId // should be optional
}
} else {
throw new Error("No source found at " + originalPackage.sources[sourceId])
}
} else {
const sourceObject = originalPackage.sources[sourceId] as SourceWithContent
sources[sourceId] = {
content: sourceObject['content'],
type: "solidity", // should be optional
installPath: sourceId // should be optional
}
}
}
}
// resolve any build dependencies
if (originalPackage.buildDependencies) {
for (const key in originalPackage.buildDependencies) {
const url = originalPackage.buildDependencies[key]
const pkg = await this.resolve(url)
buildDependencies[key] = pkg
}
}
return new ResolvedPackage(rawManifest, contentURI, originalPackage, buildDependencies, sources)
}
}
export class ResolvedPackage {
public contentURI: URL
public originalPackage: Package
public buildDependencies: ResolvedBuildDependencies
public rawManifest: string
public sources: Sources
constructor(
rawManifest: string,
contentURI: URL,
originalPackage: Package,
buildDependencies: ResolvedBuildDependencies,
sources: Sources
) {
this.rawManifest = rawManifest
this.buildDependencies = buildDependencies
this.contentURI = contentURI
this.originalPackage = originalPackage
this.sources = sources
}
}
|
6bbccfa34869c3948c3f5d47f0533372b0c101b5
|
TypeScript
|
otomad/otomad.github.io
|
/math/turntable/js/money.ts
| 3.03125
| 3
|
'use strict';
/// <reference path="money.d.ts" />
declare var jQuery: (selector: string) => any;
interface Number {
getPrefix(name?: boolean): number | string;
getValidValue(full?: boolean): number;
}
interface Math {
// trunc(n: number): number;
social(n: number): number;
}
interface CSSRule {
style: any;
selectorText: any;
}
interface String {
hyphenToCamelCase(): string;
i(index: number, character?: string | number): string;
replaces(stra: string | string[], strb?: string | string[], sep?: string, caseInsensitive?: boolean): string;
}
interface Document {
Import(src: string, type?: string): void
}
var society: number = 1; //0表示普通加减计算,1表示舍去进位计算,2表示四舍五入进位计算……
var money: any;
(function () {
let resetMoney: symbol = Symbol('resetMoney');
money = class money { //钱对象
type: string;
constructor(type: string) {
this.type = type;
this[resetMoney]();
}
private [resetMoney](): void {
//非法或未定义数值
if (cookie.get(this.type) === null || !isFinite(Number(cookie.get(this.type))))
cookie.set(this.type, 4000);
//超出10个无穷的上限
var amount: number = Number(cookie.get(this.type));
if (amount > 1e14) cookie.set(this.type, 1e14);
if (amount < -1e14) cookie.set(this.type, -1e14);
}
amount(): number {
this[resetMoney]();
return cookie.get(this.type) - 0;
}
amountName(): string {
return money.getAmountName(this.amount());
}
recharge(m: number): number {
m = m - 0;
var n: number,
o: number = this.amount();
switch (society) {
case 1:
case 2:
/* 特殊部分 */
if (o.getValidValue(true) == 1e13 && m.getValidValue(true) == -9e12) {
n = 9e12;
break;
}
if (o.getPrefix(false) >= 13 && Math.abs(m.getValidValue(true)) == 9e12)
m = m > 0 ? 1e13 : -1e13;
/* 特殊部分完 */
var oPref = o.getPrefix(false),
mPref = m.getPrefix(false);
if (oPref > mPref) n = o;
else if (oPref < mPref) n = m;
else n = o + m;
n = n.getValidValue(true);
break;
default:
n = o + m;
break;
}
cookie.set(this.type, n);
this.refreshMoney();
return this.amount();
}
cost(m: number): number | false {
if (m > this.amount()) {
console.warn('余额不足!');
return false;
}
return this.recharge(-m);
}
refreshMoney(query: string | object = '#amount-num'): string | false {
var el: HTMLElement | null;
if (typeof query === 'string')
el = document.querySelector(query);
else if (typeof query === 'object' && query instanceof HTMLElement)
el = query;
else if (typeof query === 'object' && query instanceof jQuery)
el = query[0];
else return false;
if (el === null) return false;
return (el.innerText = this.amountName());
}
static getAmountName(amount: number): string {
return `${amount.getValidValue(false)} ${amount.getPrefix(true)}元`;
}
static amount(type: string, name: boolean = false): number | string {
return window[type]['amount' + (name ? 'Name' : '')]();
}
static recharge(money: number, type: string): number {
return window[type].recharge(money);
}
static cost(money: number, type: string): number {
return window[type].cost(money);
}
static refreshMoney(type: string = 'bill', el = '#amount-num'): string | false {
return window[type].refreshMoney(el);
}
static create(type: string): object | false {
/* if (window[type] !== undefined) {
console.error("The money type which you created is exist or has already in other use, please try other type name!");
return false;
} */
return (window[type] = new money(type));
}
}
function ee(x: number, a: number = 1): number {
if (x === undefined) return Math.E;
return a * Math.pow(10, x);
}
Math.social = function (n: number): number {
switch (society) {
case 2:
return Math.round(n);
case 1:
return Math.trunc(n);
default:
return n;
}
};
Number.prototype.getPrefix = function (name: boolean = false): number | string {
const metricPrefixName: (string | undefined)[] = ['', , , , '万', , , , '亿', , , , '兆', '∞ '];
function divE(n: number, x: number): number {
return Math.social(n / ee(x));
}
var l: number[] = [0, 4, 8, 12, 13],
a: number = l[l.length - 1];
for (let i: number = 1; i < l.length; i++)
if (divE(<number>this, l[i]) == 0) {
a = l[i - 1];
break;
}
return name ? <string>metricPrefixName[a] : a;
};
Number.prototype.getValidValue = function (full: boolean = false): number {
var pref: number = ee(<number>this.getPrefix(false)),
a: number = Math.social(<number>this / pref);
return full ? a * pref : a;
};
/* -webkit-fill-available */
String.prototype.i = function (index: number, character: string = ""): string {
return this.slice(0, index) + String(character) + this.slice(index + 1);
}
String.prototype.hyphenToCamelCase = function (): string {
var result: string = "",
capital: boolean = false;
for (let char of this.toLowerCase()) {
if (`-_+.,:`.includes(char)) capital = true;
else {
result += (capital ? char.toUpperCase() : char);
capital = false;
}
}
return result;
}
String.prototype.replaces = function (a: string | string[], b: string | string[], sep: string = ',', caseInsensitive: boolean = false): string {
var s: string = <string>this;
if (!Array.isArray(a)) a = a.split(sep);
if (b && !Array.isArray(b)) b = b.split(sep);
for (let i = 0; i < a.length; i++)
s = s.replace(new RegExp(a[i], (caseInsensitive ? "gi" : "g")), (b ? b[i] : ''));
return s;
}
document.Import = function (src: string, type: string = "text/javascript"): void {
var script = document.createElement('script');
script.src = src;
script.type = type;
document.body.appendChild(script);
}
})();
var cookie = {
set: function (name: string, value: any, days: number = 36500): void {
var expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = name + '=' + escape(value) + ';expires=' + expires.toUTCString();
},
get: function (name: string): any {
var arr: string[] | null,
reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
if ((arr = document.cookie.match(reg))) return arr[2];
else return null;
},
text: () => document.cookie
}
var urlState = {
data: {},
clear: function (): true {
this.data = {};
history.pushState("", "", location.href.split('?')[0]);
return true;
},
reset: function (): boolean {
var questionMark: number = location.href.indexOf('?');
this.data = {};
if (questionMark === -1) return false;
var state: string[] = location.href.slice(questionMark + 1).split('&');
state.forEach(set => {
var divide: string[] = set.split('=');
this.data[decodeURIComponent(divide[0])] = decodeURIComponent(divide[1]);
});
return true;
},
get: function (name: string): string | null {
if (!this.reset()) return null;
var result: string | undefined = this.data[name];
return (result === undefined ? null : result);
},
set: function (name: string, value?: string | number): boolean {
this.reset();
if (typeof arguments[0] === "object") return this.burn({ ...this.data, ...arguments[0] });
for (let i = 0; i < arguments.length; i += 2) {
const name = arguments[i],
value = arguments[i + 1];
this.data[name] = value;
if (value === undefined || value === null)
delete this.data[name];
}
return this.burn();
},
burn: function (obj?: object): boolean {
if (obj !== undefined)
this.data = obj;
if (JSON.stringify(this.data) === '{}') return this.clear();
var encodeState = {};
for (let key in this.data) {
if (typeof this.data[key] == 'function') continue;
encodeState[encodeURIComponent(key)] = encodeURIComponent(this.data[key]);
}
var encodeURL = JSON.stringify(encodeState).replace(/\:/g, '=').replace(/\,/g, '&').replace(/\"/g, '').slice(1, -1);
history.pushState("", "", "?" + encodeURL);
return true;
},
obj: function (): object | null {
if (!this.reset()) return null;
return this.data;
}
};
urlState.reset()
var rootCSS = {
text: {},
val: {},
value: {},
reset: function (): void {
for (let i = 0; i < document.styleSheets.length; i++) {
try {
for (let j = 0; j < document.styleSheets[i].cssRules.length; j++) {
if (document.styleSheets[i].cssRules[j].selectorText == ":root") {
for (let k = 0; k < document.styleSheets[i].cssRules[j].style.length; k++) {
let name: string = document.styleSheets[i].cssRules[j].style[k],
value: string | number = document.styleSheets[i].cssRules[j].style.getPropertyValue(name).trim(),
CamelCase: string = name.hyphenToCamelCase(),
camelCase: string = CamelCase[0].toLowerCase() + CamelCase.slice(1);
this.text[camelCase] = this.text[CamelCase] = this.text[name] = value;
// value = Number((<string>value).replaces("px,rem,em,vw,vh,vmin,vmax,%,in,cm,mm,pt,pc,ex,ch,ms,s", '', undefined, true));
value = parseFloat(<string>value);
this.val[camelCase] = this.val[CamelCase] = this.val[name] = value;
}
}
}
} catch (e) { continue; }
}
this.value = this.val;
}
}
rootCSS.reset();
////
money.create('bill');
money.refreshMoney();
|
f446def5de6b1af35acbe52886c6e0851d7b2075
|
TypeScript
|
chase-moskal/event-decorators
|
/source/interfaces.ts
| 2.859375
| 3
|
export type EventDetails<T extends CustomEvent>
= T extends CustomEvent<infer D> ? D : never
export type Dispatcher<E extends CustomEvent> = (
options?: CustomEventInit<EventDetails<E>>
) => void
export interface EventListener {
name: string
target: EventTarget
handler: (event: Event) => void
options?: boolean | AddEventListenerOptions
}
export interface EventDecoratorOptions extends CustomEventInit {
name?: string
}
export interface ListenerDecoratorOptions extends AddEventListenerOptions {
name?: string
target?: EventTarget
}
export type EventClass = new(...args: any[]) => Event | CustomEvent
|
60eb800572fa3452a0aefc1ee3e6ebfa8b7f96c4
|
TypeScript
|
fctucker/challenge
|
/src/app/weather/weather.ts
| 2.796875
| 3
|
import {Driver} from "../util/driver";
import {appWidth} from "../util/constants";
import {Subscription} from "rxjs/Subscription";
export abstract class Weather {
public enabled: boolean = false;
public gravity: {} = {dx: 0, dy: 5};
private subscription: Subscription = null;
isTransitioningOut: boolean = false;
constructor(public driver: Driver) {
this.driver.emitter.subscribe((eventType: string) => {
if (eventType == 'tick') {
if (this.enabled) {
var dx: number = ((this.driver.windDirection == 'RIGHT') ? 1 : -1) * this.driver.windSpeed + this.gravity['dx'];
var dy: number = this.gravity['dy'];
this.moveParticles(dx, dy);
if (!this.isTransitioningOut) {
for (var i: number = 0; i < 10; i++) {
this.addParticle(Math.floor((Math.random() * 4 * appWidth) - 1.5 * appWidth), 100);
}
}
}
}
});
}
abstract transitionIn(): Promise;
public transitionOut(): void {
this.isTransitioningOut = true;
}
abstract getName(): string;
abstract getLabel(): string;
abstract addParticle(x: number, y: number): void;
abstract moveParticles(dx: number, dy: number): void;
public run(): void {
this.enabled = true;
}
}
|
cce681b894710a3150d82ca6ef4ef2312a2addfd
|
TypeScript
|
FernandoBasso/programming-how-to
|
/typescript/ts50/ch05-generics/l30d-index-types.ts
| 3.328125
| 3
|
export const NAME = "l30d Generic Constraints - Index Types";
const log: Console["log"] = console.log.bind(console);
type VideoFormatURLs = {
format360p: URL;
format480p: URL;
format720p: URL;
format1080p: URL;
};
type SubtitleURLs = {
english: URL;
german: URL;
french: URL;
};
//
// Observe that both types above, although having different
// keys, the value on those keys are always of the type ‘URL’.
//
declare const videos: VideoFormatURLs;
declare function loadFormat(format: string): void;
//
// Let's make our generic less generic, by constraining it to
// be a subtype of ‘object’.
//
// We use the ‘extends’ keyword. Whatever ‘ObjType’ is, it
// must be a subtype (extend) of ‘object’.
//
function isAvailable<ObjType extends object>(
obj: ObjType,
key: string | number | symbol,
): key is keyof ObjType {
return key in obj;
}
const format = "format240p" as string;
type URLList = {
[key: string]: URL;
};
//
// We don't know the properties themselves, but we know their
// values should be of type ‘URL’.
//
// Let's not extend from ‘object’ anymore, but from ‘URLList’.
//
function loadFile<Formats extends URLList>(
fileFormats: Formats,
format: string,
): void {
if (isAvailable(fileFormats, format)) {
log(fileFormats[format]);
}
}
|
d6d08dfdca86f76f0e9982e5fe4158701692cc7a
|
TypeScript
|
Pringmore/demo-app-two
|
/src/app/app.component.ts
| 2.53125
| 3
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit {
title = 'demo-app-two';
checkOne(param: number) {
switch (param) {
case 12:
return param;
break;
default:
console.log('parameter different than 12');
break;
}
}
ngOnInit() {
console.log('testing the demo-app-two linting!');
const element = 'test';
console.log(element);
// const arrayA = [1, 23];
// for (const el of arrayA) {
// console.log(el);
// }
}
}
|
062d409399c7fb7e1c586d66dbb7a3449319e6b7
|
TypeScript
|
reececomo/transl8r
|
/src/helpers/fetch.ts
| 2.703125
| 3
|
import { Translate, TranslateRequest } from '@google-cloud/translate/build/src/v2';
import { config, Dict } from '../config';
import { preparePlaceholders, resolvePlaceholders } from './placeholders';
const translate = async (text: string, options: TranslateRequest): Promise<string> => {
const client = new Translate({
keyFilename: config.googleTranslateKeyFile,
});
const [translation] = await client.translate(text, options);
return translation;
};
export const fetchTranslation = async (
original: string,
baseLang: string,
newLang: string,
): Promise<string> => {
if (baseLang === newLang) {
return original;
}
const before = preparePlaceholders(original);
const translation = await translate(before, {
from: baseLang,
to: newLang,
});
return resolvePlaceholders(translation);
};
// Translate some subset of keys from the base JSON into the new language.
export const fetchTranslations = async (
baseJson: Dict,
keysToTranslate: string[],
baseLang: string,
newLang: string,
): Promise<Dict> =>
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
new Promise((resolve, reject) => {
Promise.all(
keysToTranslate.map(async key => ({
[key]: await fetchTranslation(baseJson[key] ?? '', baseLang, newLang),
})),
)
.then(data => resolve(Object.assign({}, ...data)))
.catch(error => reject(error));
}) as Promise<Dict>;
|