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 |
|---|---|---|---|---|---|---|
900ae21c78ee9f5f9ac002627e80a357027dd195 | TypeScript | DataSignInc/did-siop-lib | /src/core/Signers.ts | 2.984375 | 3 | import { createHash, createSign, constants as cryptoConstants } from 'crypto';
import { leftpad } from './Utils';
import { Key, RSAKey, ECKey, OKP } from './JWKUtils';
import { ALGORITHMS, KEY_FORMATS } from './globals';
import { eddsa as EdDSA, ec as EC} from 'elliptic';
export const ERRORS = Object.freeze({
NO_PRIVATE_KEY: 'Not a private key',
INVALID_ALGORITHM: 'Invalid algorithm',
});
/**
* @classdesc This abstract class defines the interface for classes used to cryptographically sign messages
*/
export abstract class Signer{
/**
* @param {string} message - Message which needs to be signed
* @param {Key} key - A Key object used to sign the message
* @param {ALGORITHMS} [algorithm] - The algorithm used for the signing process.
* This param is defined as optional here because some Signers only support a specific algorithm
* @returns {Buffer} - A Buffer object which contains the generated signature in binary form
* @remarks This is the method which will essentially be used for signing process.
* Any extending subclass must provide a concrete definition for this method.
*/
abstract sign(message: string, key: Key | string, algorithm?: ALGORITHMS): Buffer;
}
/**
* @classdesc This class provides RSA message signing
* @extends {Signer}
*/
export class RSASigner extends Signer{
/**
* @param {string} message - Message which needs to be signed
* @param {RSAKey} key - An RSAKey object used to sign the message
* @param {ALGORITHMS} algorithm - The algorithm used for the signing process. Must be one of RSA + SHA variant
* @returns {Buffer} - A Buffer object which contains the generated signature in binary form
* @remarks This method first checks if the key provided has private part. Then it proceed to sign the message using
* selected algorithm (RSA + given SHA variant)
*/
sign(message: string, key: RSAKey, algorithm: ALGORITHMS): Buffer {
if(key.isPrivate()){
let signer;
let signerParams: any = {
key: key.exportKey(KEY_FORMATS.PKCS8_PEM),
};
switch(algorithm){
case ALGORITHMS.RS256: signer = createSign('RSA-SHA256'); break;
case ALGORITHMS.RS384: signer = createSign('RSA-SHA384'); break;
case ALGORITHMS.RS512: signer = createSign('RSA-SHA512'); break;
case ALGORITHMS.PS256: {
signer = createSign('RSA-SHA256');
signerParams.padding = cryptoConstants.RSA_PKCS1_PSS_PADDING;
signerParams.saltLength = cryptoConstants.RSA_PSS_SALTLEN_DIGEST
break;
}
case ALGORITHMS.PS384: {
signer = createSign('RSA-SHA384');
signerParams.padding = cryptoConstants.RSA_PKCS1_PSS_PADDING;
signerParams.saltLength = cryptoConstants.RSA_PSS_SALTLEN_DIGEST
break;
}
case ALGORITHMS.PS512:{
signer = createSign('RSA-SHA512');
signerParams.padding = cryptoConstants.RSA_PKCS1_PSS_PADDING;
signerParams.saltLength = cryptoConstants.RSA_PSS_SALTLEN_DIGEST
break;
}
default: throw new Error(ERRORS.INVALID_ALGORITHM)
}
return signer.update(message).sign(signerParams);
}
else{
throw new Error(ERRORS.NO_PRIVATE_KEY);
}
}
}
/**
* @classdesc This class provides Elliptic Curve message signing
* @extends {Signer}
*/
export class ECSigner extends Signer{
/**
* @param {string} message - Message which needs to be signed
* @param {ECKey} key - An ECKey object used to sign the message
* @param {ALGORITHMS} algorithm - The algorithm used for the signing process. Must be one of Curve variant + SHA variant
* @returns {Buffer} - A Buffer object which contains the generated signature in binary form
* @remarks This method first checks if the key provided has private part. Then it proceed to sign the message using
* selected algorithm (given Curve + given SHA variant)
*/
sign(message: string, key: ECKey, algorithm: ALGORITHMS): Buffer {
if(key.isPrivate()){
let sha;
let ec;
switch(algorithm){
case ALGORITHMS.ES256: {
sha = createHash('sha256');
ec = new EC('p256');
break;
}
case ALGORITHMS.ES384: {
sha = createHash('sha384');
ec = new EC('p384');
break;
}
case ALGORITHMS.ES512: {
sha = createHash('sha512');
ec = new EC('p512');
break;
}
case ALGORITHMS.ES256K: {
sha = createHash('sha256');
ec = new EC('secp256k1');
break;
}
case ALGORITHMS.EdDSA: {
sha = createHash('sha256');
ec = new EC('ed25519');
break;
}
default: throw new Error(ERRORS.INVALID_ALGORITHM);
}
let hash = sha.update(message).digest('hex');
let ecKey = ec.keyFromPrivate(key.exportKey(KEY_FORMATS.HEX));
let ec256k_signature = ecKey.sign(hash);
let signature = Buffer.alloc(64);
Buffer.from(leftpad(ec256k_signature.r.toString('hex')), 'hex').copy(signature, 0);
Buffer.from(leftpad(ec256k_signature.s.toString('hex')), 'hex').copy(signature, 32);
return signature;
}
else{
throw new Error(ERRORS.NO_PRIVATE_KEY);
}
}
}
/**
* @classdesc This class provides Edwards Curve message signing
* @extends {Signer}
*/
export class OKPSigner extends Signer{
/**
* @param {string} message - Message which needs to be signed
* @param {OKP} key - An OKP object used to sign the message
* @param {ALGORITHMS} algorithm - The algorithm used for the signing process. (ed25519 curve)
* @returns {Buffer} - A Buffer object which contains the generated signature in binary form
* @remarks This method first checks if the key provided has private part. Then it proceed to sign the message using
* selected algorithm (ed25519)
*/
sign(message: string, key: OKP, algorithm: ALGORITHMS): Buffer {
if(key.isPrivate()){
let ed;
switch(algorithm){
case ALGORITHMS.EdDSA: {
ed = new EdDSA('ed25519');
break;
}
default: throw new Error(ERRORS.INVALID_ALGORITHM);
}
let edKey = ed.keyFromSecret(key.exportKey(KEY_FORMATS.HEX));
let edDsa_signature = edKey.sign(Buffer.from(message));
return Buffer.from(edDsa_signature.toHex(), 'hex');
}
else{
throw new Error(ERRORS.NO_PRIVATE_KEY);
}
}
}
/**
* @classdesc This class provides message signing using ES256K-R algorithm
* @extends {Signer}
*/
export class ES256KRecoverableSigner extends Signer{
/**
* @param {string} message - Message which needs to be signed
* @param {ECKey | string} key - The key either as an ECKey or a hex string
* @returns {Buffer} - A Buffer object which contains the generated signature in binary form
* @remarks This method first checks whether the key is a string. If it is not then it will be converted to string
* using ECKey.exportKey(). This class supports only one algorithm which is curve secp256k1 recoverable method.
*/
sign(message: string, key: ECKey | string): Buffer {
let keyHexString;
if(typeof key === 'string'){
keyHexString = key;
}
else{
keyHexString = key.exportKey(KEY_FORMATS.HEX);
}
let sha = createHash('sha256');
let ec = new EC('secp256k1');
let hash = sha.update(message).digest('hex');
let signingKey = ec.keyFromPrivate(keyHexString);
let ec256k_signature = signingKey.sign(hash);
let jose = Buffer.alloc(65);
Buffer.from(leftpad(ec256k_signature.r.toString('hex')), 'hex').copy(jose, 0);
Buffer.from(leftpad(ec256k_signature.s.toString('hex')), 'hex').copy(jose, 32);
if (ec256k_signature.recoveryParam !== undefined && ec256k_signature.recoveryParam !== null) jose[64] = ec256k_signature.recoveryParam;
return jose;
}
} |
c47ecc52629de4c6854ea594be7c0963ca7dba6e | TypeScript | whirly/teamview.nodejs | /server/cli/db/sync.ts | 2.53125 | 3 | import { CommandModule } from 'yargs';
import {IFixture, IFixtureSide, IPerformance, PlayerPosition} from '../../../shared/models';
import logger from '../../logger';
import * as models from '../../models';
import { connectDatabase, disconnectFromDatabase } from '../../mongoose';
import axios from 'axios';
import {crunchPlayersData} from "./optimize";
interface IArgs {
force?: boolean;
login?: string;
password?: string;
}
const command: CommandModule = {
command: 'db:sync',
describe: 'Sync team/player with master database',
builder: {},
handler
};
export default command;
async function processPlayer(baseUrl: string, token: string) {
const config: any = {
method: 'get',
url: baseUrl + 'mercato/1',
headers: {
'Authorization': token
}
};
const response = await axios.request(config);
const players = JSON.parse(response.data).players;
let numberOfPlayers: number = 0;
// On commence par s'occuper des joueurs
for (const player of players) {
// On retire le player_ devant l'id. On se demande pourquoi il est là.
player.id = player.id.slice(7);
const existingPlayer = await models.Player.findOne({ idMpg: player.id });
if (existingPlayer) {
let team = await models.Team.findOne({ idMpg: player.teamid });
// On a trouvé la team en question, on va donc rajouter notre joueur
if (team) {
// Est ce que notre joueur n'est pas déjà dans cette équipe ?
if (team.players.findIndex((item: any) => item.equals(player.teamid)) == -1) {
// On l'ajoute
team.players.push(existingPlayer);
await team.save();
}
} else {
// La team n'existe pas encore, on la créé
team = await models.Team.create({
idMpg: player.teamid,
name: player.club
});
// On ajoute notre joueur
team.players.push(existingPlayer);
await team.save();
}
// On vérifie si le gus a pas changé d'équipe en fait.
if (team._id != existingPlayer.team) {
// Il a changé d'équipe, on va le virer de son ancienne équipe
const teamPrevious = await models.Team.findById(existingPlayer.team);
// Si cette équipe existe encore.
if (teamPrevious) {
teamPrevious.players.splice(
teamPrevious.players.findIndex((item: any) => item.equals(existingPlayer._id)), 1);
// On sauvegarde l'équipe modifié
await teamPrevious.save();
}
}
// On met à jour le joueur avec les infos qui sont susceptibles d'avoir changé (valeur, role, équipe)
// Et on sauvegarde le tout.
existingPlayer.value = player.quotation;
existingPlayer.role = player.position;
existingPlayer.team = team._id;
await existingPlayer.save();
numberOfPlayers++;
} else {
const playerNew = await models.Player.create({
firstName: player.firstname,
lastName: player.lastname,
idMpg: player.id,
role: player.position,
value: player.quotation
});
let team = await models.Team.findOne({ idMpg: player.teamid });
if (!team) {
team = await models.Team.create({
idMpg: player.teamid,
name: player.club
});
}
playerNew.team = team._id;
await playerNew.save();
team.players.push(playerNew);
await team.save();
numberOfPlayers++;
}
}
logger.info(numberOfPlayers + ' joueurs traités.');
}
function findTactic(matchSide: any): string {
return matchSide.players[Object.keys(matchSide.players)[0]].info.formation_used;
}
function getRoleForPosition(position: string): PlayerPosition {
if (position == 'Goalkeeper') return PlayerPosition.Goal;
if (position == 'Defender') return PlayerPosition.Defender;
if (position == 'Midfielder') return PlayerPosition.Midfield;
if (position == 'Striker') return PlayerPosition.Striker;
// Si je n'ai pas réussi à lire la position du mec, on va dire qu'il est goal.
return PlayerPosition.Goal;
}
// Dans le cas où la perf existe déjà on s'arrange quand même pour la mettre à jour
async function updatePerformances(year: number, day: number, data: any) {
// tslint:disable-next-line:forin
for (const playerID in data.players) {
const playerInfos = data.players[playerID];
const player = await models.Player.findOne({ idMpg: playerID });
const performancePrevious = await models.Performance.findOne({ player, day, year });
// On va la mettre à jour, parce que bon il y aura toujours ces histoires de mecs
// qui ont finalement hérité d'un but quelques jours plus tard
performancePrevious.position = playerInfos.info.position;
performancePrevious.place = playerInfos.info.formation_place;
performancePrevious.rate = playerInfos.info.note_final_2015;
performancePrevious.goalFor = playerInfos.info.goals;
performancePrevious.goalAgainst = playerInfos.info.own_goals;
performancePrevious.cardRed = playerInfos.info.red_card > 0;
performancePrevious.cardYellow = playerInfos.info.yellow_card > 0;
performancePrevious.sub = playerInfos.info.sub == 1;
performancePrevious.minutes = playerInfos.info.mins_played;
performancePrevious.penaltyFor = playerInfos.stat.att_pen_goal
? playerInfos.stat.att_pen_goal
: 0;
// On sauvegarde le bordel.
delete performancePrevious._id;
await models.Performance.findOneAndUpdate({ player, day, year }, performancePrevious);
}
}
async function processPlayers(year: number, day: number, data: any): Promise<IPerformance[]> {
const performances = [];
// tslint:disable-next-line:forin
for (const playerID in data.players) {
const playerInfos = data.players[playerID];
let player = await models.Player.findOne({ idMpg: playerID });
// Le joueur peut ne pas exister, parce que ce monsieur a quitté le championnat.
// Merci à Valentin Eysseric d'avoir été le premier :)
if (!player) {
// On créer une enveloppe player
player = await models.Player.create({
idMpg: playerID,
firstName: '', // le paquet d'infos ne comporte que le nom de famille pour l'affichage tactique
lastName: playerInfos.info.lastname,
role: getRoleForPosition(playerInfos.info.position),
value: 0,
team: null
});
}
// Est ce qu'on a déjà cette perf ?
const performancePrevious = await models.Performance.findOne({ player, day, year });
// Non on va la créer
if (!performancePrevious) {
const team = await models.Team.findOne({ idMpg: data.id });
// Pour l'instant on stocke juste les perfs
// Mais on pourrait réfléchir à récupérer les stats pour voir ce qu'on pourrait faire.
const playerPerformance = await models.Performance.create({
player,
team,
year,
day,
position: playerInfos.info.position,
place: playerInfos.info.formation_place,
rate: playerInfos.info.note_final_2015,
goalFor: playerInfos.info.goals,
goalAgainst: playerInfos.info.own_goals,
cardYellow: playerInfos.info.yellow_card > 0,
cardRed: playerInfos.info.red_card > 0,
sub: playerInfos.info.sub == 1,
minutes: playerInfos.info.mins_played,
penaltyFor: playerInfos.stat.att_pen_goal
});
performances.push(playerPerformance);
// On stocke aussi la performance dans les infos du joueurs.
player.performances.push(playerPerformance);
await player.save();
}
}
return performances;
}
async function processMatches(baseUrl: string, token: string) {
for (let i = 1; i < 39; i++) {
const queryDay = await axios.get(baseUrl + 'championship/1/calendar/' + i.toString() );
const day = JSON.parse(queryDay.data);
const year = 2020;
logger.info('Traitement jour ' + i);
for (const match of day.matches) {
// Si le champ score est vide, c'est que le match n'a pas encore été joué, on ne le traite donc pas
// ... pour l'instant du moins, ça serait intéressant de voir ce qu'on pourrait faire avec les cotes
if (match.home.score != '' && match.home.score != undefined && match.home.scoretmp == undefined) {
const score = `${match.home.score.toString()}:${match.away.score.toString()}`;
const line = `${match.home.club}-${match.away.club} ${score}`;
logger.info(line);
// Process each match
const matchInfos = await axios.get(baseUrl + 'championship/match/' + match.id);
const matchDetailed = JSON.parse(matchInfos.data);
// Là sur le coup, je n'ai pas compris pourquoi les ids sont préfixés de "match_" ... bon ben on le vire
matchDetailed.id = matchDetailed.id.slice(6);
// find teams
const teamAway = await models.Team
.findOne({ idMpg: matchDetailed.Away.id })
.populate('players fixtures').exec();
const teamHome = await models.Team
.findOne({ idMpg: matchDetailed.Home.id })
.populate('players fixtures').exec();
// find fixtures
let fixture = await models.Fixture.findOne({ idMpg: matchDetailed.id })
.populate('home.performances').populate('away.performances').exec();
let document: IFixture = {
year,
day: i,
idMpg: matchDetailed.id.toString(),
home: {
team: teamHome,
formation: findTactic(matchDetailed.Home)
},
away: {
team: teamAway,
formation: findTactic(matchDetailed.Away)
}
};
// Fixture does not exists yet
if (!fixture) {
fixture = await models.Fixture.create( document );
// Populate players and their performance
fixture.home.performances = await processPlayers(year, i, matchDetailed.Home);
fixture.away.performances = await processPlayers(year, i, matchDetailed.Away);
// On calcule le median, la moyenne, la variance
await addVariance(fixture.home);
await addVariance(fixture.away);
await fixture.save();
teamAway.fixtures.push(fixture);
teamHome.fixtures.push(fixture);
await teamAway.save();
await teamHome.save();
} else {
await updatePerformances(year, i, matchDetailed.Home);
await updatePerformances(year, i, matchDetailed.Away);
// On rajoute les variances, median, etc...
// Vu que ça peut évoluer en fonction de la réattribution des buts
await addVariance(fixture.home);
await addVariance(fixture.away);
fixture.depopulate('performances');
await fixture.save();
}
}
}
}
// Basically we are done.
}
/*
Basiquement, on va précalculer les performances globales d'une équipe sur un match.
Parce qu'on est un peu au bon endroit pour faire ça. Globalement on veut la moyenne des joueurs sur ce
match, le median de note, et la variance de la performance. Derrière du coup on pourra faire de jolies graphes
et surtout voir si un mec surperforme par rapport à son équipe.
La grande interrogation reste quand même de savoir si on ne calcule qu'avec les titulaires ou pas. Parce que
le pauvre gars que tu fais toujours rentrer à la 89mn il risque d'avoir toujours son 5 syndical. En même temps
c'est bien ça qu'on veut.
*/
async function addVariance(fixtureSide: IFixtureSide) {
const ratings = Array<number>();
let sum = 0;
// On récupère les notes pour les gens où ça existe. On inclus tous ceux qui ont joué
for (const performance of fixtureSide.performances) {
if (performance.rate > 0) {
ratings.push(performance.rate);
sum += performance.rate;
}
}
// On trie par ordre croissant de note
ratings.sort((a,b) => a - b);
const amount = ratings.length;
fixtureSide.average = sum / amount;
fixtureSide.median = ratings[ Math.floor( amount / 2 )];
fixtureSide.variance = ratings.reduce((accumulator, value) =>
Math.pow(value - fixtureSide.average, 2), 0) / amount;
}
async function handler(args: IArgs): Promise<void> {
const baseUrl: string = 'https://api.monpetitgazon.com/';
await connectDatabase(process.env.MONGO_URL);
let response = await axios.post(baseUrl+"user/signIn", {
email: args.login,
password: args.password,
language: 'fr-FR'
});
if (response.status == 200 && response.data.token) {
// Grab da token
let token = response.data.token;
// On s'occupe d'abord des joueurs
logger.info('Traitement des joueurs...');
await processPlayer(baseUrl, token);
// On s'attaque après aux performances
// 38 journées, on s'en occupe.
logger.info('Traitement des matchs...');
await processMatches(baseUrl, token);
// On précalcule les statistiques des joueurs
// Cela va permettre de fortement descendre la charge du client
// avec moins de flexibilité, que l'on utilise pas
await crunchPlayersData();
}
await disconnectFromDatabase();
}
|
8d0b4420d676ecfef2061b6d49b7016f2b85ebc8 | TypeScript | MartinREMY42/multi-game-project | /src/app/games/pylos/PylosTutorial.ts | 2.84375 | 3 | import { PylosCoord } from 'src/app/games/pylos/PylosCoord';
import { PylosMove } from 'src/app/games/pylos/PylosMove';
import { PylosState } from 'src/app/games/pylos/PylosState';
import { Player } from 'src/app/jscaip/Player';
import { MGPValidation } from 'src/app/utils/MGPValidation';
import { TutorialStep } from '../../components/wrapper-components/tutorial-game-wrapper/TutorialStep';
const _: Player = Player.NONE;
const O: Player = Player.ZERO;
const X: Player = Player.ONE;
export class PylosTutorial {
public tutorial: TutorialStep[] = [
TutorialStep.informational(
$localize`Goal of the game`,
$localize`At Pylos, the goal is to be the last to play.
To do this, you have to save up your pieces.
As soon as a player puts its last piece, that player loses the game immediately.
Here is what the initial board looks like, it is a board of 4 x 4 squares.
This board will become a pyramid, little by little.
It will be filled by the pieces of your stock. Each player has 15 pieces.`,
PylosState.getInitialState(),
),
TutorialStep.anyMove(
$localize`Dropping a piece`,
$localize`When it is your turn, you can always drop one of your piece on an empty square.
The gray squares are where you can drop your pieces.<br/><br/>
Click on one of the squares to drop a piece there.`,
PylosState.getInitialState(),
PylosMove.fromDrop(new PylosCoord(1, 1, 0), []),
$localize`There you go, as simple as that.`,
),
TutorialStep.fromMove(
$localize`Climbing`,
$localize`When 4 pieces form a square, it is possible to put a fifth piece on top.
However, when that happens, you can save a piece by climbing instead of dropping a piece.
To climb:
<ol>
<li>Click on one of your free pieces, which should be lower than the landing square.</li>
<li>Click on an empty landing square, higher than your selected piece.</li>
</ol><br/>
Go ahead, climb!`,
new PylosState([
[
[O, X, _, _],
[X, O, _, _],
[_, _, _, _],
[_, _, _, O],
], [
[_, _, _],
[_, _, _],
[_, _, _],
], [
[_, _],
[_, _],
], [
[_],
],
], 0),
[PylosMove.fromClimb(new PylosCoord(3, 3, 0), new PylosCoord(0, 0, 1), [])],
$localize`Congratulations!<br/>
Some important notes:
<ol>
<li>You cannot move a piece that is directly below another one.</li>
<li>Of course, you cannot move the opponent's pieces.</li>
<li>You can only climb when the landing square is higher than the starting square.</li>
</ol>`,
$localize`Failed!`,
),
TutorialStep.fromMove(
$localize`Square (1/2)`,
$localize`When the piece you just moved or dropped is the fourth one of a square of your color,
you can choose anywhere on the board one or two of your pieces.
These pieces will be removed from the board, allowing you to save up one or two pieces.
A chosen piece must not be directly below another piece.
A chosen piece can be the piece you just placed.
You're playing Dark.<br/><br/>
Form a square, then click twice on one of the four pieces to remove only that one.`,
new PylosState([
[
[O, O, _, _],
[_, O, _, _],
[_, _, _, _],
[_, _, _, _],
], [
[_, _, _],
[_, _, _],
[_, _, _],
], [
[_, _],
[_, _],
], [
[_],
],
], 0),
[
PylosMove.fromDrop(new PylosCoord(0, 1, 0), [new PylosCoord(0, 0, 0)]),
PylosMove.fromDrop(new PylosCoord(0, 1, 0), [new PylosCoord(0, 1, 0)]),
PylosMove.fromDrop(new PylosCoord(0, 1, 0), [new PylosCoord(1, 0, 0)]),
PylosMove.fromDrop(new PylosCoord(0, 1, 0), [new PylosCoord(1, 1, 0)]),
],
$localize`Congratulations, you have saved up one piece.`,
$localize`Failed!`,
),
TutorialStep.fromPredicate(
$localize`Square (2/2)`,
$localize`You're playing Dark.<br/><br/>
Do like in the previous step, but this time click on two different pieces.`,
new PylosState([
[
[O, O, _, _],
[_, O, _, _],
[_, _, _, _],
[_, _, _, _],
], [
[_, _, _],
[_, _, _],
[_, _, _],
], [
[_, _],
[_, _],
], [
[_],
],
], 0),
PylosMove.fromDrop(new PylosCoord(0, 1, 0), [new PylosCoord(0, 0, 0), new PylosCoord(1, 0, 0)]),
(move: PylosMove, _state: PylosState) => {
if (move.secondCapture.isPresent()) {
return MGPValidation.SUCCESS;
}
if (move.firstCapture.isPresent()) {
return MGPValidation.failure($localize`Failed, you only captured one piece.`);
}
return MGPValidation.failure($localize`Failed, you did not capture any piece.`);
},
$localize`Congratulations, you have saved up two pieces.`,
),
];
}
|
035cd3c32bda486d0ce29882aaefb9f148ec529a | TypeScript | nimi/ngx-elasticsearch | /packages/core/src/query/ImmutableQuery.ts | 2.6875 | 3 | import { BoolMust } from './query_dsl';
import { guid } from '../utils';
import { SelectedFilter } from './SelectedFilter';
import { omitBy, omit, values, pick, merge, isUndefined } from 'lodash';
import { update } from '../utils/immutability-helper';
export type SourceFilterType = string | Array<string> | boolean;
/**
* @name ImmutableQuery
* @description
*
* This class is responsible for building, storing and accessing
* query objects. It manages the query object as the class name implies
* by making updates via immutable transactions
*
*/
export class ImmutableQuery {
/**
* Default state of the index of none is provided
*/
static defaultIndex: any = {
queryString: '',
filtersMap: {},
selectedFilters: [],
queries: [],
filters: [],
_source: null,
size: 10
};
/**
* @name query
* @description Publicly accessible query object
*/
public query: any;
/**
* @name index
* @description Internal state of the index
*/
private index: any;
constructor(index: any = ImmutableQuery.defaultIndex) {
this.index = index;
this.buildQuery();
}
/**
* @name buildQuery
* @description Create a query from the index state
*/
buildQuery() {
const q: any = {};
if(this.index.queries.length > 0) {
q.query = BoolMust(this.index.queries)
}
if (this.index.filters.length > 0) {
q.post_filter = BoolMust(this.index.filters);
}
q.aggs = this.index.aggs;
q.size = this.index.size;
q.from = this.index.from;
q.sort = this.index.sort;
q.highlight = this.index.highlight;
q.suggest = this.index.suggest;
if (this.index._source) {
q._source = this.index._source;
}
this.query = omitBy(q, isUndefined);
}
/**
* @name hasFilters
* @description Check if index has any filters
*/
hasFilters() {
return this.index.filters.length > 0;
}
/**
* @name buildFiltersOrQuery
* @description Check if index has filters or queries
*/
hasFiltersOrQuery() {
return (this.index.queries.length +
this.index.filters.length) > 0 || !!this.index.sort;
}
/**
* @name addQuery
* @description Add a new query to the index
* @param query
*/
addQuery(query: any) {
if (!query) {
return this;
}
return this.update({
queries:{ $push: [query] }
});
}
/**
* @name setQueryString
* @description Set the query string on the index
* @param queryString
*/
setQueryString(queryString: string | any | undefined) {
return this.update({ $merge: { queryString } });
}
/**
* @name getQueryString
* @description Get query string from the index state
*/
getQueryString() {
return this.index.queryString;
}
/**
* @name addSelectedFilter
* @description Add a single filter to index filters
* @param selectedFilter
*/
addSelectedFilter(selectedFilter: SelectedFilter){
return this.addSelectedFilters([ selectedFilter ]);
}
/**
* @name addSelectedFilters
* @description Add a set of filters to index selected filters
* @param selectedFilters
*/
addSelectedFilters(selectedFilters: Array<SelectedFilter>) {
return this.update({
selectedFilters: { $push: selectedFilters }
});
}
/**
* @name setSelectedFilters
* @description Get the current set of selected filters
*/
getSelectedFilters() {
return this.index.selectedFilters;
}
/**
* @name addAnonymousFilter
* @description Add an unnamed filter
* @param filter
*/
addAnonymousFilter(filter: any) {
return this.addFilter(guid(), filter);
}
/**
* @name addFilter
* @description Add filters to index filter set
* @param key
* @param filter
*/
addFilter(key: string, filter: any) {
return this.update({
filters: { $push: [filter] },
filtersMap:{ $merge:{ [key]: filter } }
});
}
/**
* @name setAggs
* @description Set the aggs on the index
* @param aggs
*/
setAggs(aggs: any) {
return this.deepUpdate('aggs', aggs);
}
/**
* @name getFilters
* @description Get a list of filters
* @param keys
*/
getFilters(keys: any[] = []) {
return this.getFiltersWithoutKeys(keys);
}
/**
* @name _getFilters
* @description Internal method for getting filters
* @param keys
* @param method
*/
private _getFilters(keys: any, method: Function) {
keys = [].concat(keys);
const filters = values(method(this.index.filtersMap || {}, keys));
return BoolMust(filters);
}
/**
* @name getFiltersWithKeys
* @description Get filters with a certain set of keys
* @param keys
*/
getFiltersWithKeys(keys: any[]) {
return this._getFilters(keys, pick);
}
/**
* @name getFiltersWithoutKeys
* @description Get filters without a specified set included
* @param keys
*/
getFiltersWithoutKeys(keys: any) {
return this._getFilters(keys, omit);
}
/**
* @name setSize
* @description Set the index size
* @param size
*/
setSize(size: number) {
return this.update({ $merge: { size } });
}
/**
* @name setSort
* @description Set the index state for sort order
* @param sort
*/
setSort(sort: any) {
return this.update({ $merge: {sort:sort}});
}
/**
* @name setSource
* @description Set source property for the index
* @param _source
*/
setSource(_source: SourceFilterType) {
return this.update({ $merge: { _source } });
}
/**
* @name setQueryString
* @description Set the highlight prop on the index
* @param highlight
*/
setHighlight(highlight: any) {
return this.deepUpdate('highlight', highlight);
}
/**
* @name getSize
* @description Get the query size
*/
getSize() {
return this.query.size;
}
/**
* @name setFrom
* @description Set the from prop on the index
* @param from
*/
setFrom(from: number) {
return this.update({ $merge: { from } });
}
/**
* @name getFrom
* @description Get the from prop of the query
*/
getFrom() {
return this.query.from;
}
/**
* @name getPage
* @description Get the page based on size and from state
*/
getPage() {
return 1 + Math.floor((this.getFrom() || 0) / (this.getSize() || 10));
}
/**
* @name deepUpdate
* @description Update index state prop deeply
* @param key
* @param ob
*/
deepUpdate(key: string, ob: any){
return this.update({
$merge: {
[key]: merge({}, this.index[key] || {}, ob)
}
});
}
/**
* @name setSuggestions
* @description Set the suggestions state on the index
* @param suggestions
*/
setSuggestions(suggestions: any) {
return this.update({
$merge: {suggest: suggestions }
});
}
/**
* @name update
* @description Apply a new query to the index state
* @param updateDef immutable operation to be applied
*/
private update(updateDef: any) {
return new ImmutableQuery(
update(this.index, updateDef)
);
}
/**
* @name getJSON
* @description Get the JSON query
*/
getJSON() {
return this.query;
}
/**
* @name printJSON
* @description Print the JSON query
*/
printJSON(){
console.log(JSON.stringify(this.getJSON(), null, 2));
}
}
|
b3887b20da4cf2ccf1d88322237861d25f92193b | TypeScript | arist0tl3/typescript-express-starter | /src/index.ts | 2.578125 | 3 | import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import compression from 'compression';
const app = express();
// Use process.env as default
const PORT = process.env.PORT || 3333;
// Whitelist all routes with cors
app.use(cors());
// Use express json
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Make sure no responses are getting cached
app.use((req, res, next) => {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
});
// Enable gzip compression
app.use(compression());
// Define our routes
app.get('/', (req, res) => {
res.status(200).json({ hello: 'world' });
});
// Start server
app.listen(PORT, () => {
// eslint-disable-next-line no-console
console.log(`Server is listening on port ${PORT}`);
});
|
51fe005311e97b4736227673478761c4f98207c2 | TypeScript | xrl8tien/tool_management_ui | /src/app/model/Kpi.ts | 2.53125 | 3 | export class Kpi {
id: number;
code_employee: string;
target: number;
create_time: Date;
constructor(id: number,
code_employee: string,
target: number,
create_time: Date) {
this.id = id;
this.code_employee = code_employee;
this.target = target;
this.create_time = create_time;
}
} |
b348ec9f846634badada2176736d64c0bc52cf4f | TypeScript | alxmcr/spacestagram-react | /src/reducers/likesReducer.ts | 3.21875 | 3 | import { Reducer } from "react";
// Reducers
export interface LikesState {
nasaIds: string[];
}
export interface LikesAction {
type: "LIKE" | "UNLIKE",
payload: string
}
export const likesReducer: Reducer<LikesState, LikesAction> = (state: LikesState, action: LikesAction) => {
let currentState = state;
const nasaId = action?.payload;
const currentNasaIds = state?.nasaIds;
switch (action.type) {
case "LIKE":
const nasaIds = currentNasaIds.includes(nasaId)
? currentNasaIds
: [...currentNasaIds, nasaId]
const likesStateUpdated = { ...state, nasaIds }
localStorage.setItem("LIKES", JSON.stringify(likesStateUpdated))
return likesStateUpdated;
case "UNLIKE":
const filterCondition = (likeNasaId: string) => likeNasaId !== nasaId
const nasaIdsFiltered = currentNasaIds.filter(filterCondition);
const unlikesStateUpdated = { ...state, nasaIds: nasaIdsFiltered };
localStorage.setItem("LIKES", JSON.stringify(unlikesStateUpdated))
return unlikesStateUpdated;
default:
return currentState;
}
} |
fa1a9665a0c6325482d6f65cbc9bb331572cb1a2 | TypeScript | mitre/heimdall2 | /apps/backend/src/authn/github.strategy.ts | 2.53125 | 3 | import {Injectable, UnauthorizedException} from '@nestjs/common';
import {PassportStrategy} from '@nestjs/passport';
import axios from 'axios';
import {Strategy} from 'passport-github';
import {ConfigService} from '../config/config.service';
import {User} from '../users/user.model';
import {AuthnService} from './authn.service';
interface GithubProfile {
name: string | null;
login: string;
}
interface GithubEmail {
email: string;
verified: boolean;
}
@Injectable()
export class GithubStrategy extends PassportStrategy(Strategy, 'github') {
constructor(
private readonly authnService: AuthnService,
private readonly configService: ConfigService
) {
super({
clientID: configService.get('GITHUB_CLIENTID') || 'disabled',
clientSecret: configService.get('GITHUB_CLIENTSECRET') || 'disabled',
authorizationURL: `
${
configService.get('GITHUB_ENTERPRISE_INSTANCE_BASE_URL') ||
configService.defaultGithubBaseURL
}login/oauth/authorize`,
tokenURL: `${
configService.get('GITHUB_ENTERPRISE_INSTANCE_BASE_URL') ||
configService.defaultGithubBaseURL
}login/oauth/access_token`,
userProfileURL: `${
configService.get('GITHUB_ENTERPRISE_INSTANCE_API_URL') ||
configService.defaultGithubAPIURL
}user`,
scope: 'user:email',
passReqToCallback: true
});
}
async validate(
req: Record<string, unknown>,
accessToken: string
): Promise<User> {
// Get user's linked emails from Github
const githubEmails = await axios
.get<GithubEmail[]>(
`${
this.configService.get('GITHUB_ENTERPRISE_INSTANCE_API_URL') ||
this.configService.defaultGithubAPIURL
}user/emails`,
{
headers: {Authorization: `token ${accessToken}`}
}
)
.then(({data}) => {
return data;
});
// Get user's info
const userInfoResponse = await axios
.get<GithubProfile>(
`${
this.configService.get('GITHUB_ENTERPRISE_INSTANCE_API_URL') ||
this.configService.defaultGithubAPIURL
}user`,
{
headers: {Authorization: `token ${accessToken}`}
}
)
.then(({data}) => {
return data;
});
let firstName = userInfoResponse.login;
let lastName = '';
if (typeof userInfoResponse.name === 'string') {
firstName = this.authnService.splitName(userInfoResponse.name).firstName;
lastName = this.authnService.splitName(userInfoResponse.name).lastName;
}
// Get first email
const primaryEmail = githubEmails[0];
// Only validate if the user has verified their email with Github
if (primaryEmail.verified) {
// Check if the user already exists, if not they will be created
return this.authnService.validateOrCreateUser(
primaryEmail.email,
firstName,
lastName,
'github'
);
} else {
throw new UnauthorizedException(
'Please verify your email with Github before logging into Heimdall.'
);
}
}
}
|
a78385195f935db3dcf7ee01182736926d44e80e | TypeScript | harogen-net/viewer | /src/utils/LayerViewFactory.ts | 2.53125 | 3 | import { Layer, LayerType } from "../model/Layer";
import { LayerView } from "../view/LayerView";
import { ImageView } from "../view/layer/ImageView";
import { TextView } from "../view/layer/TextView";
import { ImageLayer } from "../model/layer/ImageLayer";
import { TextLayer } from "../model/layer/TextLayer";
import $ from "jquery";
export class LayerViewFactory {
public static ViewFromLayer(layer:Layer):LayerView {
switch(layer.type){
case LayerType.IMAGE:
return new ImageView(layer as ImageLayer, $('<div class="layerWrapper" />'));
case LayerType.TEXT:
return new TextView(layer as TextLayer, $('<div class="layerWrapper" />'));
default:
return new LayerView(layer, $('<div class="layerWrapper" />'));
// return null;
}
}
} |
8894bd283491ab375242ecaa6128b460bc45f16a | TypeScript | siyul-park/conev-sync | /package/conev-sync-core/src/source/sources.ts | 2.84375 | 3 | import merge, { Options } from 'deepmerge';
import Source from './source';
class Sources implements Source {
private readonly sources: Source[];
private readonly options?: Options;
constructor(sources: Source[], options?: Options) {
this.sources = sources;
this.options = options;
}
add(source: Source, priority = -1): Sources {
if (priority === -1) this.sources.push(source);
else this.sources.splice(priority, 0, source);
return this;
}
export(): Map<string, Record<string, unknown>> {
const configs = this.sources.map((source) => source.export());
const mergedConfig = new Map<string, Record<string, unknown>[]>();
configs.forEach((config) => {
config.forEach((value, key) => {
if (!mergedConfig.get(key)) mergedConfig.set(key, []);
mergedConfig.get(key)?.push(value);
});
});
const config = new Map<string, Record<string, unknown>>();
mergedConfig.forEach((value, key) => {
config.set(
key,
merge.all(value, this.options) as Record<string, unknown>
);
});
return config;
}
}
export default Sources;
|
c913413a2ce02d109dedb79b4ba9b012bc9f49a5 | TypeScript | DeskproApps/github | /src/utils/getUniqUsersLogin.ts | 2.640625 | 3 | import uniq from "lodash/uniq";
import isArray from "lodash/isArray";
import { User } from "../services/github/types";
const getUniqUsersLogin = (
user?: User|null,
assignee?: User|null,
assignees?: User[],
): Array<User["login"]> => {
let users = [];
if (user?.login) {
users.push(user.login);
}
if (assignee?.login) {
users.push(assignee.login);
}
if (isArray(assignees)) {
users = users.concat(assignees.map(({ login }) => login));
}
users = uniq(users);
return users
};
export { getUniqUsersLogin };
|
28f010c270e6bd9c6a82a803529d26a2fef15d68 | TypeScript | ananas-dev/slippi-quick-tournaments-1 | /src/responders.ts | 2.796875 | 3 | interface Response {
type: string;
message?: string;
}
export function success(message?: string): Response {
return {
type: "success",
message: message
};
}
export function error(message: string): Response {
return {
type: "error",
message: message,
};
}
|
bddbcf157ba873337c075875609cbc07080cfce2 | TypeScript | quasarframework/quasar | /ui/types/utils/is.d.ts | 4.125 | 4 | interface is {
/**
* Recursively checks if one Object is equal to another.
* Also supports Map, Set, ArrayBuffer, Regexp, Date, and many more.
*
* @example
* const objA = { foo: 1, bar: { baz: 2 } }
* const objB = { foo: 1, bar: { baz: 2 } }
* objA === objB // false
* is.deepEqual(objA, objB) // true
*/
// Can't do it both ways, see: https://github.com/microsoft/TypeScript/issues/26916#issuecomment-555691585
deepEqual<T>(obj1: T, obj2: unknown): obj2 is T;
/**
* Checks if a value is an object.
* Note: Map, Set, ArrayBuffer, Regexp, Date, etc. are also objects,
* but null and Arrays are not.
*
* @example
* is.object({}) // true
* is.object([]) // false
* is.object(null) // false
* is.object(1) // false
* is.object(new Map()) // true
* is.object(new Set()) // true
*/
object<T>(val: T): val is Record<any, any>;
/**
* Checks if a value is a Date object.
*
* @see `date.isValid()` If you want to check if a value is a valid date string or number
*
* @example
* is.date(new Date()) // true
* is.date(Date.now()) // false
* is.date(new Date('2022-09-24T11:00:00.000Z')) // true
* is.date('2022-09-24') // false
*/
date(val: unknown): val is Date;
/**
* Checks if a value is a RegExp.
*
* @example <caption>Literal notation</caption>
* is.regexp(/foo/); // true
* @example <caption>Constructor</caption>
* is.regexp(new RegExp('bar', 'g')); // true
*/
regexp(val: unknown): val is RegExp;
/**
* Checks if a value is a finite number.
* Note: BigInts, NaN, and Infinity values are not considered as numbers.
*
* @example
* is.number(1); // true
* is.number('1'); // false
* is.number(1n); // false
* is.number(NaN); // false
* is.number(Infinity); // false
*/
number(val: unknown): val is number;
}
export declare const is: is;
|
92ba84b74951d6372e8de3631183e9752fbf5172 | TypeScript | anyweez/scraper | /structs/source.ts | 2.9375 | 3 | /**
* Represents a single news source.
*/
export class Source {
id: string;
name: string;
constructor(raw) {
this.id = raw.id;
this.name = raw.name;
}
} |
fa42575f26fd9bb099f749cd55eef0691bacfce6 | TypeScript | Bluefinger/rythe | /src/operators/dropWith.ts | 3.109375 | 3 | import { emitSKIP } from "../signal";
import { Stream, OperatorFn } from "../types/stream";
import { map } from "./map";
/**
* Pushes non-repeating values using a predicate function. Skips any repeated values.
*/
export const dropWith = <T>(
predicate: (prev: T | undefined, next: T) => boolean
): OperatorFn<T, T> => (source: Stream<T>): Stream<T> => {
let prev: T | undefined;
return map<T>(
(value): T => (predicate(prev, value) ? emitSKIP() : (prev = value))
)(source);
};
|
783292df6cda4e1f42deb85c6830310a94ed62bf | TypeScript | matheusqs/e-commerce-books | /src/app/pages/cart/cart.component.ts | 2.625 | 3 | import { Component, OnInit } from '@angular/core';
import { Book } from 'src/app/core/models/book';
import { CartService } from 'src/app/core/services/cart.service';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.scss'],
})
export class CartComponent implements OnInit {
public total = '';
constructor(public cartService: CartService) {}
ngOnInit(): void {
this.total = this.formatCurrency(this.calculateTotalCart());
}
public formatCurrency(value: number): string {
return new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL',
}).format(value);
}
public handleRemoveBookClick(id: string): void {
this.cartService.removeBook(id);
this.total = this.formatCurrency(this.calculateTotalCart());
}
public handleAddBookClick(book: Book): void {
this.cartService.addBook(book);
this.total = this.formatCurrency(this.calculateTotalCart());
}
private calculateTotalCart(): number {
return this.cartService.books.reduce<number>(
(acc, current) => current.price * current.quantity + acc,
0
);
}
}
|
2d001561f2a72a11e716ac94321bc4e53568c745 | TypeScript | cross-development/practice | /simple-code/ts-code/src/tasks-02/task-02-03.ts | 3.6875 | 4 | const findLongestWord = function (string: string): string {
const words: string[] = string.split(' ');
let LongestWord: string = words[0];
for (const word of words) {
if (word.length > LongestWord.length) {
LongestWord = word;
}
}
return LongestWord;
};
/*
* Вызовы функции для проверки работоспособности твоей реализации.
*/
console.log(findLongestWord('The quick brown fox jumped over the lazy dog')); // 'jumped'
console.log(findLongestWord('Google do a roll')); // 'Google'
console.log(findLongestWord('May the force be with you')); // 'force'
|
528436c46a10e038f4d6ef5352c9e5c608cb9be4 | TypeScript | wesherwo/dynamic-forms | /src/app/controls/checkbox.ts | 2.6875 | 3 | import { ControlBase } from './control-base';
export class Checkbox extends ControlBase<string> {
controlType = 'checkbox';
type: string;
constructor(options: {} = {}) {
super(options);
}
update(newValue){
this.value = newValue.checked;
}
isValid(){
return super.isValid();
}
}
|
25c613404543a23e472a1717f6d198854e3577b5 | TypeScript | Flipize/GithubAngular | /src/models/Movie.ts | 3.125 | 3 | export class Movie {
constructor(private Title?: string, private year?: number, private director?: string) {
}
get Name(): string {
return this.Title;
}
set Name(value: string) {
this.Title = value;
}
get Year(): number {
return this.year;
}
set Year(value: number) {
this.year = value;
}
get Director(): string {
return this.director;
}
set Director(value: string) {
this.director = value;
}
}
|
c652beea349eb148caa69a8b0cd8d5571b516087 | TypeScript | mjvandermeulen/outlets-react | /src/redux/outlets/types.ts | 2.84375 | 3 | interface SwitchDataValues {
mode: boolean
}
export interface SwitchData {
[group: string]: SwitchDataValues
}
export interface TimerDataValues {
time: number
isTimerRunning: boolean
}
export interface TimerData {
[group: string]: TimerDataValues
}
export type SyncRequestData = string[] // array of groups
export interface OutletDataValues extends SwitchDataValues, TimerDataValues {}
// OR
// type OutletDataValues = SwitchDataValues & TimerDataValues // *** LEARN
// https://stackoverflow.com/questions/44983560/how-to-exclude-a-key-from-an-interface-in-typescript
// LEARN ***
// type OmitGroup<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
// type SocketData = OmitGroup<GroupSocketData, 'group'>
export interface GroupsData {
[group: string]: OutletDataValues
}
export type OutletData = {
groups: GroupsData
}
// actions
// TODO: switch to mirroredKeys... ****
export const PASS = 'PASS'
export const SET_SWITCH_DATA = 'SET_SWITCH_DATA'
export const SET_TIMER_DATA = 'SET_TIMER_DATA'
export const SET_SYNC_DATA = 'SET_SYNC_DATA'
export const TIMER_ADJUST = 'TIMER_ADJUST'
export const TIMER_STARTPAUSE = 'TIMER_STARTPAUSE'
export const TIMER_CANCEL = 'TIMER_CANCEL'
// Move to sockets somewhere... TODO ****
export const OUTLET_SWITCH_CHANNEL = 'OUTLET_SWITCH_CHANNEL'
export const OUTLET_TIMER_CHANNEL = 'OUTLET_TIMER_CHANNEL'
export const OUTLET_SYNC_CHANNEL = 'OUTLET_SYNC_CHANNEL'
interface SetSwitchDataAction {
type: typeof SET_SWITCH_DATA
payload: {
data: SwitchData
}
}
interface SetTimerDataAction {
type: typeof SET_TIMER_DATA
payload: {
data: TimerData
}
}
/**
* Dispatched by middle ware when processing either:
* sendSyncRequestAction
* receiveSyncDataAction
* PASS is used after sendSyncRequestAction (no further action is needed)
*/
interface SetSyncDataAction {
type: typeof SET_SYNC_DATA | typeof PASS
payload: {
data: GroupsData
}
}
export type OutletActionTypes =
| SetSwitchDataAction
| SetTimerDataAction
| SetSyncDataAction
|
678e3207d9aa3287aaab866d9356c35c4e1976c1 | TypeScript | fearthecowboy/scratchpad | /compute/2019-12-01/models/GalleryApplicationProperties.ts | 2.859375 | 3 | import { OperatingSystemTypes } from '../enums/OperatingSystemTypes';
/**
* @description Describes the properties of a gallery Application Definition.
*/
export interface GalleryApplicationProperties {
/**
* @description The description of this gallery Application Definition resource. This property is updatable.
*/
description: string;
/**
* @description The Eula agreement for the gallery Application Definition.
*/
eula: string;
/**
* @description The privacy statement uri.
*/
privacyStatementUri: string;
/**
* @description The release note uri.
*/
releaseNoteUri: string;
/**
* @description The end of life date of the gallery Application Definition. This property can be used for decommissioning purposes. This property is updatable.
*/
endOfLifeDate: dateTime;
/**
* @description This property allows you to specify the supported type of the OS that application is built for. <br><br> Possible values are: <br><br> **Windows** <br><br> **Linux**
*/
supportedOSType?: OperatingSystemTypes;
}
|
9ed85629e3d3afdd32fcb4343a1090a5481f07ab | TypeScript | ivan-skv/weatherapp | /src/utils/events.ts | 3.1875 | 3 | export default class EventEmitter {
private listeners: { [x: string]: Array<(...args: any[]) => void>; }
constructor() {
this.listeners = {};
}
addListener(event: string, callback: (...args: any) => void): void {
const listeners = Array.isArray(this.listeners[event]) ? this.listeners[event] : [];
this.listeners[event] = listeners;
if (listeners.indexOf(callback) === -1) {
listeners.push(callback)
}
}
off(event?: string, callback?: (...args: any[]) => void): void {
if (!event) {
const events = Object.keys(this.listeners);
for (const e of events) {
this.listeners[e].length = 0;
delete this.listeners[e]
}
return;
}
if (!callback) {
if (!Array.isArray(this.listeners[event])) {
return;
}
this.listeners[event].length = 0;
delete this.listeners[event]
return;
}
if (!Array.isArray(this.listeners[event])) {
return;
}
const index = this.listeners[event].indexOf(callback);
if (index !== -1) {
this.listeners[event].splice(index, 1)
}
}
emit(event: string, ...args: any[]): void {
const listeners = this.listeners[event]
if (!Array.isArray(listeners)) {
return;
}
for (const callback of listeners) {
callback(...args)
}
}
}
|
31c73c3f7ff3cc4e9d41408c884b8e3747ec2c9f | TypeScript | dlucazeau/ngx-lro-datepicker | /src/app/_datepicker/_models/visual-day.spec.ts | 2.84375 | 3 | import { VisualDay } from './visual-day';
describe('VisualDay', () =>
{
it('ctor / calendar / should not be a weekend', async () =>
{
// Arrange
const d: Date = new Date(2020, 0, 18);
// Act
const vd = new VisualDay(d, new Date(1970, 0, 1), new Date(1970, 0, 1), new Date(1970, 0, 1), null, null);
// Assert
expect(vd.day).toEqual(18);
expect(vd.isWeekend).toBe(true);
});
it('ctor / calendar / should be a weekend', async () =>
{
// Arrange
const d: Date = new Date(2020, 0, 19);
// Act
const vd = new VisualDay(d, new Date(1970, 0, 1), new Date(1970, 0, 1), new Date(1970, 0, 1), null, null);
// Assert
expect(vd.day).toEqual(19);
expect(vd.isWeekend).toBe(true);
});
it('ctor / calendar / should be uncheckable', async () =>
{
// Arrange
const d: Date = new Date(2019, 11, 31);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2020, 0, 31);
// Act
const vd = new VisualDay(d, new Date(1970, 0, 1), minDate, maxDate, null, null);
// Assert
expect(vd.isCheckable).toBe(false);
});
it('ctor / calendar / should be uncheckable', async () =>
{
// Arrange
const d: Date = new Date(2020, 1, 18);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2020, 0, 31);
// Act
const vd = new VisualDay(d, new Date(1970, 0, 1), minDate, maxDate, null, null);
// Assert
expect(vd.isCheckable).toBe(false);
});
it('ctor / calendar / should be checkable', async () =>
{
// Arrange
const d: Date = new Date(2020, 0, 18);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2020, 0, 31);
// Act
const vd = new VisualDay(d, new Date(1970, 0, 1), minDate, maxDate, null, null);
// Assert
expect(vd.isCheckable).toBe(true);
});
it('ctor / calendar / should be checkable', async () =>
{
// Arrange
const d: Date = new Date(2020, 0, 1);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2020, 0, 31);
// Act
const vd = new VisualDay(d, new Date(1970, 0, 1), minDate, maxDate, null, null);
// Assert
expect(vd.isCheckable).toBe(true);
});
it('ctor / calendar / should be checkable', async () =>
{
// Arrange
const d: Date = new Date(2020, 0, 31);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2020, 0, 31);
// Act
const vd = new VisualDay(d, new Date(1970, 0, 1), minDate, maxDate, null, null);
// Assert
expect(vd.isCheckable).toBe(true);
});
it('ctor / calendar / isInRange should be true', async () =>
{
// Arrange
const d: Date = new Date(2020, 0, 18);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2020, 0, 31);
const sinceDate = new Date(2020, 0, 13);
const untilDate = new Date(2020, 0, 19);
// Act
const vd = new VisualDay(d, new Date(1970, 0, 1), minDate, maxDate, sinceDate, untilDate);
// Assert
expect(vd.isInRange).toBe(true);
});
it('ctor / calendar / isInRange should be false', async () =>
{
// Arrange
const d: Date = new Date(2020, 0, 31);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2020, 0, 31);
const sinceDate = new Date(2020, 0, 13);
const untilDate = new Date(2020, 0, 19);
// Act
const vd = new VisualDay(d, new Date(1970, 0, 1), minDate, maxDate, sinceDate, untilDate);
// Assert
expect(vd.isInRange).toBe(false);
});
it('ctor / calendar / isInputDate should be true', async () =>
{
// Arrange
const d: Date = new Date(2020, 0, 18);
const inputDate = new Date(2020, 0, 18);
// Act
const vd = new VisualDay(d, inputDate, new Date(1970, 0, 1), new Date(1970, 0, 1), new Date(1970, 0, 1), new Date(1970, 0, 1));
// Assert
expect(vd.isInputDate).toBe(true);
});
it('ctor / calendar / isInputDate should be false', async () =>
{
// Arrange
const d: Date = new Date(2020, 0, 17);
const inputDate = new Date(2020, 0, 18);
// Act
const vd = new VisualDay(d, inputDate, new Date(1970, 0, 1), new Date(1970, 0, 1), new Date(1970, 0, 1), new Date(1970, 0, 1));
// Assert
expect(vd.isInputDate).toBe(false);
});
});
|
659fab8ef34b7cd2a45e2e0db7bb1d823872ddcf | TypeScript | FrontEnd-ro/frontend.ro | /server/event/event.router.ts | 2.734375 | 3 | import express, { Request, Response } from 'express';
import EventModel from './event.model';
import { ServerError } from '../utils/ServerError';
import EmailService, { EMAIL_TEMPLATE } from '../Email.service';
const eventRouter = express.Router();
eventRouter.get('/:label/seats', async function getAvailableSeats(
req: Request<{ label: string; }>,
res: Response<{ label: string; total: number; free: number; }>
) {
const { label } = req.params;
try {
const eventInfo = await EventModel.getByLabel(label);
if (!eventInfo) {
new ServerError(404, 'generic.404', { label }).send(res);
return
}
res.json({
label,
total: eventInfo.total,
free: eventInfo.total - eventInfo.attendees.length
});
} catch (err) {
console.error("[getAvailableSeats]", err);
new ServerError(500, 'generic.500').send(res);
}
});
eventRouter.post('/:label/register', async function registerToEvent(
req: Request<{ label: string; }, {}, { name: string; email: string; tel: string; }>,
res: Response
) {
const { label } = req.params;
const { name, email, tel } = req.body;
try {
const eventInfo = await EventModel.getByLabel(label);
if (!eventInfo) {
new ServerError(404, 'generic.404', { label }).send(res);
return
}
if (eventInfo.attendees.find(attendee => attendee.email === email || attendee.tel === tel)) {
new ServerError(400, 'events.already_registered').send(res);
return
}
const freeSeatsCount = eventInfo.total - eventInfo.attendees.length;
if (freeSeatsCount >= 1) {
await EventModel.addAttendee(label, { name, email, tel });
// No "await" here since the email is not
// critical for the continuation of the flow.
EmailService.sendTemplateWithAlias(
email,
EMAIL_TEMPLATE.GIT_INCEPATORI_REGISTERED,
{
name,
sender_name: "Păvă",
product_name: "Git & GitHub pentru începători",
}
);
res.status(201).send();
} else {
new ServerError(400, 'events.fully_booked').send(res);
return
}
} catch (err) {
console.error("[registerToEvent]", err);
new ServerError(500, err.message || 'Oops! Se pare că nu am putut să te înregistrăm. Încearcă din nou.').send(res);
}
});
eventRouter.post('/:label/waitlist', async function addToWaitlist(
req: Request<{ label: string; }, {}, { name: string; email: string; tel: string; }>,
res: Response
) {
const { label } = req.params;
const { name, email, tel } = req.body;
try {
const eventInfo = await EventModel.getByLabel(label);
if (!eventInfo) {
new ServerError(404, 'generic.404', { label }).send(res);
return
}
if (eventInfo.attendees.find(attendee => attendee.email === email || attendee.tel === tel)) {
new ServerError(400, 'events.already_registered').send(res);
return
}
if (eventInfo.waitlist.find(attendee => attendee.email === email || attendee.tel === tel)) {
new ServerError(400, 'events.already_on_waitlist').send(res);
return
}
await EventModel.addToWaitlist(label, { name, email, tel });
// No "await" here since the email is not
// critical for the continuation of the flow.
EmailService.sendTemplateWithAlias(
email,
EMAIL_TEMPLATE.GIT_INCEPATORI_WAITLIST,
{
name,
sender_name: "Păvă",
product_name: "Git & GitHub pentru începători",
}
);
res.status(200).send()
} catch (err) {
console.error("[addToWaitlist]", err);
new ServerError(500, err.message || 'Oops! Se pare că nu am putut să te adaugăm pe lista de așteptare. Încearcă din nou.').send(res);
}
});
export default eventRouter;
|
9c092a98c8e10fc12f2dc55a6a7b4255e121524a | TypeScript | Andor123/exercise | /ts/24.ts | 3.671875 | 4 | var func = (x)=> {
if (typeof x == "number") {
console.log(x + " is numeric");
}
else if (typeof x == "string") {
console.log(x + " is a string");
}
};
func(12);
func("Tom"); |
f513500a18d51210d0ee66047a7c763c3484e2d1 | TypeScript | Kasama/petshop-backend | /src/models/Event.ts | 2.609375 | 3 | import ApplicationModel from './ApplicationModel';
import Pet from './Pet';
import Service from './Service';
class Event extends ApplicationModel {
public name: string;
public date: string;
public slot: number;
public pet_id: string;
public service_id: string;
constructor(base?: any) {
super(Event, base);
this.refersTo(Pet, 'pet_id');
this.refersTo(Service, 'service_id');
}
fields(): string[] {
return [
'name',
'date',
'slot',
'pet_id',
'service_id',
];
}
}
export default Event;
|
05e8a39494994489c10052716f5cd72c1d629122 | TypeScript | szab100/sfdb | /admin/ui/src/app/error/error.component.ts | 2.546875 | 3 | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpStatus } from '../services/constants';
@Component({
selector: 'app-error',
templateUrl: './error.component.html',
styleUrls: ['./error.component.scss']
})
export class ErrorComponent implements OnInit {
title: string;
errorMessage: string;
constructor(private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
this.route.params.subscribe(params => {
if (params['errorCode']) {
this.updateErrorMessage(Number(params['errorCode']));
}
});
}
private updateErrorMessage(errorCode: number): void {
switch (errorCode) {
case HttpStatus.UNAUTHORIZED:
this.title = 'Login required';
this.errorMessage = `You are currently logged out or your authentication token has expired.
Please login using the button on the top-right!`;
break;
case HttpStatus.FORBIDDEN:
this.title = 'Unauthorized access';
this.errorMessage = 'You are not authorized to access the selected resource.';
break;
case HttpStatus.REQUEST_TIMEOUT:
this.title = 'Request timed out';
this.errorMessage = 'Your previous request has timed out. Please try again.';
break;
case HttpStatus.API_DOWN:
this.title = 'SFDB API is unreachable';
this.errorMessage = 'We couldn\'t reach SFDB backend API. Please make sure it is running and try again.';
break;
default:
this.title = 'Something went wrong.';
this.errorMessage = 'A generic error has happened';
}
}
}
|
de99aaa9cf4052e1ebff3a8e9efab143845b63f4 | TypeScript | hmuralt/typestately | /src/core/ReducerHelpers.ts | 2.96875 | 3 | import { Reducer, Action } from "redux";
import RouteAction, { isRouteAction } from "./RouteAction";
import RoutingOption from "./RoutingOption";
import DefaultStateReducer from "./DefaultStateReducer";
export interface DefaultStateReducerWithOptionalRoutingOptions<TState, TActionType>
extends DefaultStateReducer<TState, Action<TActionType>> {
routingOptions?: Map<TActionType, RoutingOption>;
}
export interface ExtensibleReducer<TState, TActionType>
extends DefaultStateReducerWithOptionalRoutingOptions<TState, TActionType> {
routingOptions: Map<TActionType, RoutingOption>;
handling<TAction extends Action<TActionType>>(
type: TActionType,
reducerFunction: DefaultStateReducer<Readonly<TState>, TAction>,
routingOption?: RoutingOption
): ExtensibleReducer<TState, TActionType>;
}
export function createExtensibleReducer<TState, TActionType>(): ExtensibleReducer<TState, TActionType> {
const reducerFunctions = new Map<TActionType, Reducer<Readonly<TState>, Action<TActionType>>>();
const routingOptions = new Map<TActionType, RoutingOption>();
function handling<TAction extends Action<TActionType>>(
type: TActionType,
reducerFunction: DefaultStateReducer<Readonly<TState>, TAction>,
routingOption?: RoutingOption
) {
reducerFunctions.set(type, reducerFunction);
if (routingOption !== undefined) {
routingOptions.set(type, routingOption);
}
return reducer;
}
function reducer(state: TState, action: Action<TActionType>) {
if (!reducerFunctions.has(action.type)) {
return state;
}
const reducerFunction = reducerFunctions.get(action.type)!;
return reducerFunction(state, action);
}
reducer.handling = handling;
reducer.routingOptions = routingOptions;
return reducer;
}
export function withDefaultStateToReduxReducer<TState, TActionType>(
defaultState: TState,
reducer: DefaultStateReducer<Readonly<TState>, Action<TActionType>>
): Reducer<TState, Action<TActionType>> {
return (state: TState | undefined = defaultState, action: Action<TActionType>) => {
return reducer(state, action);
};
}
export function withRouteReducer<TState, TActionType>(
identifier: string,
reducer: Reducer<TState, Action<TActionType>>,
routingOptions: Map<TActionType, RoutingOption>
) {
return (state: TState, action: Action<TActionType> | RouteAction<TActionType>) => {
if (!isRouteAction(action)) {
return routingOptions.has(action.type) && routingOptions.get(action.type)!.isRoutedOnly
? state
: reducer(state, action);
}
const actionToHandle = action.action;
const routingOption = routingOptions.get(actionToHandle.type) || {
isForThisInstance: true
};
if (
(!routingOption.isForThisInstance && !routingOption.isForOtherInstances) ||
(routingOption.isForThisInstance && !routingOption.isForOtherInstances && action.identifier !== identifier) ||
(routingOption.isForOtherInstances && !routingOption.isForThisInstance && action.identifier === identifier)
) {
return state;
}
return reducer(state, actionToHandle);
};
}
|
325ccba1a0190a3c830bd9d48e75a5cd04ff1b9a | TypeScript | bitsevn/workspaces | /src/app/features/tree/tree.component.ts | 2.640625 | 3 | import { Component, Input, OnInit } from '@angular/core';
export class Item {
id: number | string;
name: string;
}
export enum NodeType {
BRANCH = 'branch',
LEAF = 'leaf'
}
export interface TreeNode<T> {
id: number | string;
name: string;
nodeType: NodeType;
visible?: boolean;
expanded?: boolean;
value?: T;
children?: TreeNode<T>[];
}
@Component({
selector: 'app-tree',
templateUrl: './tree.component.html',
styleUrls: ['./tree.component.scss']
})
export class TreeComponent implements OnInit {
@Input() rootNodeClass = 'tree-root';
@Input() nestedRootNodeClass = 'tree-nested';
@Input() nodes: TreeNode<Item>[] = [];
@Input() rootNode: TreeNode<Item>;
branchNodeType = NodeType.BRANCH;
leafNodeType = NodeType.LEAF;
constructor() {}
ngOnInit() {
/* const toggler = document.getElementsByClassName('folder-caret');
let i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener('click', function() {
this.parentElement.querySelector('app-tree > .tree-nested').classList.toggle('tree-active');
this.classList.toggle('folder-caret-down');
});
toggler[i].addEventListener('mousedown', function() {
this.parentElement
.querySelector('app-tree > .tree-branch')
.classList.toggle('tree-highlight');
});
toggler[i].addEventListener('mouseup', function() {
this.parentElement
.querySelector('app-tree > .tree-branch')
.classList.toggle('tree-highlight');
});
} */
}
toggle(event) {
const caret = event.target;
caret.classList.toggle('folder-caret-down');
const nestedTree = caret.parentElement.querySelector('app-tree .tree-nested');
if (nestedTree) nestedTree.classList.toggle('tree-active');
}
toggleHighlight(event) {
const caret = event.target;
const branch = caret.parentElement.querySelector('app-tree .tree-branch');
branch.classList.toggle('tree-highlight');
}
}
|
295828db4abc50612dfd9a79f2d488283e199836 | TypeScript | YePpHa/maia-yt | /src/app/settings-storage/SettingsStorageFactory.ts | 2.515625 | 3 | import { SettingsStorage } from "./SettingsStorage";
import { Storage } from "../libs/storage/Storage";
import { Container, injectable } from "inversify";
export const storageCache: {[key: string]: SettingsStorage} = {};
@injectable()
export class SettingsStorageFactory {
private _storage: Storage;
private _container: Container;
constructor(storage: Storage, container: Container) {
this._storage = storage;
this._container = container;
}
createStorage(namespace: string): SettingsStorage {
if (!storageCache.hasOwnProperty(namespace)) {
storageCache[namespace] = new SettingsStorage(namespace, this._storage);
this._container.bind<SettingsStorage>(SettingsStorage).toConstantValue(storageCache[namespace]);
}
return storageCache[namespace];
}
} |
62e70f5c9f4104be3000818379775bc82795de7a | TypeScript | jlambert97/msAuthorization | /src/graphql/resources/user/schema.ts | 2.59375 | 3 | const userTypes = `
type User {
id: ID!
name: String!
email: String!
createdAt: String!
updatedAt: String!
}
input UserCreate {
name: String!
email: String!
password: String!
}
input UserUpdatePassword {
password: String!
}
`
const userQueries = `
users(first: Int, offset: Int): [ User! ]!
user(id: ID!): User
`
const userMutations = `
createUser(input: UserCreate!): User
updatePassword(id: ID!, input: UserUpdatePassword!): Boolean
`
export {
userTypes,
userQueries,
userMutations,
} |
167f25590b5cdd8bf4c3e086b7333a6248b5183b | TypeScript | mpicciollicmq/framework-investigations | /typescript-marionette/src/TodosView.ts | 2.609375 | 3 | namespace TodoMVC {
"use strict";
interface CheckboxEventTarget extends EventTarget {
checked: boolean;
}
interface CheckboxEvent extends Event {
currentTarget: CheckboxEventTarget;
}
interface TodosViewOptions {
collection: TodoCollection;
}
/** Controls the rendering of the list of items, including the filtering of activs vs completed items for display. */
export class TodosView extends Marionette.CompositeView<Todo, TodoView> {
constructor(options: TodosViewOptions) {
super({
childViewContainer: ".js-todo-list"
});
this.collection = options.collection;
this.events = <any>{
"click @ui.toggle": this.onToggleAllClick
};
this.delegateEvents();
}
childView = TodoView;
collection: TodoCollection;
collectionEvents = {
"change:completed": this.render,
"all": this.setCheckAllState
};
template = "#todosViewTemplate";
ui = {
toggle: ".js-toggle-all"
};
private get toggleElement(): JQuery {
return <any>this.ui.toggle as JQuery;
}
filter(child: Todo) {
const filteredOn = FilterChannel.filterState.filter;
return child.matchesFilter(filteredOn);
}
initialize() {
this.listenTo(FilterChannel.filterState, "change:filter", this.render);
}
private onToggleAllClick(e: CheckboxEvent) {
const isChecked = e.currentTarget.checked;
this.collection.each((todo: Todo) => {
todo.save({ completed: isChecked });
});
}
private setCheckAllState() {
// TODO: This code here is pretty weird. Clean it up.
this.toggleElement.prop("checked", this.collection.allCompleted());
this.$el.parent().toggle(this.collection.length > 0);
}
}
} |
117226f83c2b31c3f8db2d8f2941753d96791598 | TypeScript | jalescardoso/ionic2-cordova-plugin-googlemaps-v2 | /ionic-native/src/plugins/text-to-speech.ts | 3.21875 | 3 | import { Plugin, Cordova } from './plugin';
export interface TTSOptions {
/** text to speak */
text: string;
/** a string like 'en-US', 'zh-CN', etc */
locale?: string;
/** speed rate, 0 ~ 1 */
rate?: number;
}
/**
* @name TextToSpeech
* @description
* Text to Speech plugin
*
* @usage
* ```
* import {TextToSpeech} from 'ionic-native';
*
* TextToSpeech.speak('Hello World')
* .then(() => console.log('Success'))
* .catch((reason: any) => console.log(reason));
*
* ```
* @interfaces
* TTSOptions
*/
@Plugin({
pluginName: 'TextToSpeech',
plugin: 'cordova-plugin-tts',
pluginRef: 'TTS',
repo: 'https://github.com/vilic/cordova-plugin-tts'
})
export class TextToSpeech {
/**
* This function speaks
* @param options {string | TTSOptions} Text to speak or TTSOptions
* @return {Promise<any>} Returns a promise that resolves when the speaking finishes
*/
@Cordova({
successIndex: 1,
errorIndex: 2
})
static speak(options: string | TTSOptions): Promise<any> {
return;
}
static stop(): Promise<any> {
return;
}
}
|
7319552789856ac8a9637326643553cdc5e1b8b9 | TypeScript | first-line-outsourcing/media-shop | /src/app/shared/models/order.model.ts | 2.6875 | 3 | import { Address } from './address.model';
import { Product } from './product.model';
export class Order {
public id: string;
public products: Product[];
public total: number;
public tax: number;
public currency: string;
public grandTotal: number;
public payment: string;
public promocode: string;
public addressOrder: Address;
public createdAt: Date;
public createdBy: string;
public firstName?: string;
public lastName?: string;
constructor(obj) {
for (const key in obj) {
switch (key) {
case 'addressOrder':
this.addressOrder = obj[key];
break;
case 'createdAt':
this.createdAt = new Date(obj[key]);
break;
case 'products':
this.products = obj[key].map((item) => new Product(item));
break;
default:
this[key] = obj[key];
}
}
}
}
|
b873366c465577d628058d02c39405efd6fbc887 | TypeScript | DEV6hub/TypeScript-Course-Files | /Demos/Unit04/Demo05/arrow_functions.ts | 3.703125 | 4 | class Person {
constructor(public name: string) { }
sayHello(friends: string[]): void {
// this will work
friends.forEach((friend: string) => {
console.log(`${this.name} says hello to ${friend}`);
});
// this will not
friends.forEach(function(friend: string) {
console.log(`${this.name} says hello to ${friend}`);
});
}
};
const jane = new Person('Jane');
const friends: string[] = ['Bob', 'Sally'];
jane.sayHello(friends);
|
76dc125efce065deb4f4a0083cf012e2bb9ec787 | TypeScript | ldqUndefined/ts-algorithms | /src/chapter1/questions/1-4/Ex_1_4_15.ts | 4.125 | 4 | //线性级别的,数组两端向中间走
const twoSumFaster = (arr: number[]): number => {
//最小大于0或者最大小于0都可以直接得出结果为0
if (arr.length === 0 || arr[0] > 0 || arr[arr.length - 1] < 0) {
return 0;
}
let count = 0,
lo = 0,
hi = arr.length - 1;
//整数对,只有1个0应该不算吧,这里就不是<=了
while (lo < hi) {
if (arr[lo] + arr[hi] < 0) {
lo++;
} else if (arr[lo] + arr[hi] > 0) {
hi--;
} else {
count++;
lo++;
hi--;
}
}
return count;
};
//一样的思想,内层循环头尾向中间走
const threeSumFaster = (arr: number[]): number => {
if (arr.length < 3 || arr[0] > 0 || arr[arr.length] < 0) {
return 0;
}
let count = 0;
for (let i = 0, len = arr.length; i < len - 2; i++) {
let lo = i + 1,
hi = arr.length - 1;
while (lo < hi) {
if (arr[i] + arr[lo] + arr[hi] < 0) {
lo++;
} else if (arr[i] + arr[lo] + arr[hi] > 0) {
hi--;
} else {
count++;
lo++;
hi--;
}
}
}
return count;
};
|
cd6241b3bacbf7d0b3295a33dac1ce829881603b | TypeScript | rocketryjs/device-launchpad-mk2 | /src/features/clock.ts | 2.921875 | 3 | import type {Device} from "@rocketry/core";
import bindDeep from "bind-deep";
const clear: Clock<DependentDevice>["clear"] = function () {
// Stop the interval
if (this.clock.interval) {
clearInterval(this.clock.interval);
delete this.clock.interval;
}
return this;
};
const change: Clock<DependentDevice>["change"] = function (
// Beats per minute
bpm: number,
// Will stop after 48 messages (2 beats) by default
maxReps = 48
) {
// Save
this.clock.current = bpm;
// Clear if called before last one was stopped
this.clock.clear();
// Stop sending MIDI clock messages when closing the device
// `device.reset()` should be run before `device.close()` as this only prevents extra messages
if (!this.clock.hasCloseListener) {
this.clock.hasCloseListener = true;
this.on("close", () => this.clock.clear());
}
let reps = 0;
this.clock.interval = setInterval(
// Call MIDI clock
() => {
// Will stop after reached maxReps if not 0 or otherwise falsy
if (reps < maxReps || !maxReps) {
this.send([248]);
reps++;
} else {
this.clock.clear();
}
},
// Timing formula: 1000 / messages per second
// Messages per second: messages per minute / 60
// Messages per minute: 24 pulses per beat
1000 / (bpm * 24 / 60)
);
return this;
};
const set: Clock<DependentDevice>["set"] = change;
const reset: Clock<DependentDevice>["reset"] = function () {
// Reset to 120bpm if the bpm is set to something other than 120
if (typeof this.clock.current !== "undefined" && this.clock.current !== 120) {
return this.clock.change(120);
}
return this;
};
export const clock: Clock<DependentDevice> = {
clear,
change,
set,
reset,
current: undefined,
hasCloseListener: false,
};
declare abstract class DependentDevice extends Device<DependentDevice> {
clock: Clock<void, DependentDevice>;
}
export interface Clock<T extends DependentDevice | void, R extends DependentDevice | void = T> {
current?: number;
hasCloseListener: boolean;
interval?: NodeJS.Timeout;
clear (this: T): R;
change (this: T, bpm: number, maxReps?: number): R;
set (this: T, bpm: number, maxReps?: number): R;
reset (this: T): R;
}
export const makeClock = function <T extends DependentDevice> (device: T): Clock<void, T> {
return bindDeep(clock as Omit<Clock<T>, "interval">, device);
};
|
28aa3d4c214196391c058c6932c4a74c84249c21 | TypeScript | movelikeabishop/twitter-app | /src/api/twitter/index.ts | 2.671875 | 3 | import Twitter from 'twitter';
import FilterTweets from './filter/tweetFilter';
import { ITweet } from './schema';
import { NotFoundError } from '../../core/ApiError';
import PaginationController from './paginationController';
export interface ITweetsResponse{
tweets: ITweet[], // an array of tweets in our schema
search_metadata: any // metadata as provided in twitter response
};
export interface ITweetResponse{
tweet: ITweet
};
export default class TwitterClient {
private client: Twitter
constructor(twitterOptions: Twitter.AccessTokenOptions | Twitter.BearerTokenOptions){
this.client = new Twitter(twitterOptions);
}
async searchTweets(params: Twitter.RequestParams) : Promise<ITweetsResponse>{
// Search tweets with the given params
let response = await this.client.get('search/tweets',
PaginationController.setPaginationParams(params));
// Filter tweets to fit our schema
let tweets: ITweet[] = await FilterTweets(response.statuses);
return {tweets, search_metadata: response.search_metadata};
}
async getMinimalTweets(ids: string): Promise<ITweetsResponse> {
let response = await this.client.get('statuses/lookup', {id: ids, include_entities: false});
// Filter tweets to fit our schema
let tweets: ITweet[] = await FilterTweets(<any[]>response);
if(tweets.length < 1){
// no tweet found
throw new NotFoundError('No tweet found with given ids');
}
else return {tweets, search_metadata: response.search_metadata};
}
async getExtendedTweets(ids: string): Promise<ITweetsResponse> {
let response = await this.client.get(`statuses/lookup`, {id: ids, tweet_mode:'extended'});
// Filter tweets to fit our schema
let tweets: ITweet[] = await FilterTweets(<any[]>response);
if(tweets.length < 1){
// no tweet found
throw new NotFoundError('No tweet found with given ids');
}
return {tweets, search_metadata: response.search_metadata};
}
async getTweetWithReplies(id: string): Promise<ITweetResponse> {
let extendedTweets = await this.getExtendedTweets(id);
// select the first tweet and load replies
let tweet = extendedTweets.tweets[0];
let repliesResp = await this.loadRepliesForTweet(tweet);
// assign replies to tweet
tweet.replies = repliesResp.tweets;
return {
tweet
};
}
public async loadRepliesForTweet(tweet: ITweet) : Promise<ITweetsResponse> {
let {user, id_str} = tweet;
// save tweet's post datestamp
let tweet_at = new Date(tweet.created_at);
// load all replies to this user
let allRepliesToTweet:ITweet[] = [];
let replies:ITweetsResponse;
let max_id = null;
do {
// load all replies to user
replies = await this.searchTweets({
q: `to:${user.screen_name}`,
max_id,
include_entities: false,
count: 100
});
// select only replies done to THIS tweet
replies.tweets.forEach(tweet => {
if(tweet.in_reply_to.status_id_str === id_str){
allRepliesToTweet.push(tweet);
}
})
// Get max_id from next_results
if(replies.search_metadata.next_results){
let next = <string>replies.search_metadata.next_results;
// Use PaginationController to get max_id
max_id = PaginationController.getParameterFromQueryString(next, 'max_id');
}
else{
// BREAK loop if no more results exist
break;
}
// get last reply tweet's post datestamp
let last_reply_at = new Date(replies.tweets[replies.tweets.length - 1].created_at);
// BREAK loop if last reply is earlier than tweet itself
if(last_reply_at.valueOf() < tweet_at.valueOf()){
break;
}
} while (true);
return {tweets: allRepliesToTweet, search_metadata: replies.search_metadata};
}
};
|
9c8fddbbfc7cc14c71395475b1c4a8c4f62b6e85 | TypeScript | npmcdn-to-unpkg-bot/TS_config | /ts-namespace/src/myapp/controllers/MainCtrl.ts | 2.625 | 3 | namespace MyApp.Controllers {
export class MainCtrl {
static $inject = ["NameSvc"];
constructor(private svc: Services.NameSvc) {
this.name = 'World...';
svc.getName().then( n => this.name = n );
}
public name: string
public show($event) {
window.alert($event);
}
}
} |
73ae44923afe6040d0eca45ab6cdd1983f7a1d77 | TypeScript | NoworksM/home-server-api | /src/entity/Role.ts | 2.546875 | 3 | import {Column, Entity, Index, ManyToMany, PrimaryGeneratedColumn} from "typeorm";
import {Length} from "class-validator";
import {User} from "./User";
@Entity()
export class Role {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
@Index({unique: true})
@Length(3, 64)
name: string;
@ManyToMany(() => User, user => user.roles)
users: User[];
} |
613b7be5fde249b21c6f376d8860637058af0dfa | TypeScript | rootulp/exercism | /typescript/resistor-color-duo/resistor-color-duo.ts | 3.375 | 3 | export class ResistorColor {
private colors: string[];
constructor (colors: string[]) {
if (colors.length < 2) {
throw Error('At least two colors need to be present');
}
// Ignore additional colors
this.colors = colors.splice(0, 2);
}
public value(): number {
let result = ""
for (let color of this.colors) {
result += colorCode(color);
}
return Number.parseInt(result)
}
}
export const colorCode = (color: string) => {
return COLORS.indexOf(color)
}
export const COLORS = [
'black',
'brown',
'red',
'orange',
'yellow',
'green',
'blue',
'violet',
'grey',
'white',
]
|
1533b74249e2deeaf250a97ce85b5f369147f47e | TypeScript | rodolfoHOk/hiok.despensa | /src/services/produtos.ts | 2.515625 | 3 | import Produto from "../interface/produto";
import apiClient from "./apiClient";
const url = '/produtos'
export function getAllProdutos(){
return apiClient.get(url);
}
export function getProdutos({nome, categoria}:{nome: string, categoria: string}){
return apiClient.get(url, {
params: {
nome: nome,
categoria: categoria
}
});
}
export function postProduto(produto: Produto) {
return apiClient.post(url, produto);
}
export function getProdutoPorId(_id: string) {
return apiClient.get(`${url}/${_id}`);
}
export function putProduto(_id: string, produto: Produto) {
return apiClient.put(`${url}/${_id}`, produto);
}
export function deleteProduto(_id: string) {
return apiClient.delete(`${url}/${_id}`);
}
export function patchProduto(_id: string, quantidade: number) {
return apiClient.patch(`${url}/${_id}`, {quantidade: quantidade});
}
|
707f0af07e30e4803ff343793e9c222cb7fadae1 | TypeScript | corbinu/eslint-typescript-smoketest | /projects/glimmer/packages/glimmer-benchmarks/lib/benchmarks/baseline.ts | 2.703125 | 3 | import { TemplateBenchmarkScenario, BenchmarkScenario } from '../bench';
class SingleTextNodeScenario extends TemplateBenchmarkScenario {
public name = "single text node";
public description = "A simple static text template";
template() {
return `hi`;
}
renderContext(): Object {
return {};
}
test(render: () => HTMLElement) {
let result = render().outerHTML;
if (result !== '<div>hi</div>') {
throw new Error(`Invalid render: ${result}`);
}
}
}
export default <typeof BenchmarkScenario[]>[
SingleTextNodeScenario
];
|
09769cddf2aba4f576f00b09511ad90131b808da | TypeScript | O4epegb/Practice | /algorithms/in-typescript/src/utils/index.ts | 2.984375 | 3 | export function mutatedSwap(
firstIndex: number,
secondIndex: number,
array: Array<number>
) {
const temp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
}
|
a3b484dcf2b27a0d8e67df2472348f32fabc5a98 | TypeScript | EllaB12/loop-machine | /src/app/components/loop-list/loop-list.component.ts | 2.703125 | 3 | import { Component, Input, OnInit } from '@angular/core';
import { Loop } from '../../models/loop.model';
@Component({
selector: 'loop-list',
templateUrl: './loop-list.component.html',
styleUrls: ['./loop-list.component.less']
})
export class LoopListComponent implements OnInit {
@Input() loops!: Loop[];
playLoops: Loop[] = [];
constructor() { }
ngOnInit(): void {
}
addLoop(loop: Loop) {
const loopIndex = this.loops.findIndex(item => item.name === loop.name);
if(this.playLoops.length > 0) {
if( this.playLoops[this.playLoops.length - 1].startTime > 0) {
// In case the previous loop is also in a pending state
this.loops[loopIndex].startTime = this.playLoops[0].endTime;
} else {
this.loops[loopIndex].startTime = this.playLoops[this.playLoops.length - 1].endTime;
}
}
this.playLoops.push(loop);
}
removeLoop(loop: Loop) {
const loopIndex = this.playLoops.findIndex(item => item.name === loop.name);
this.playLoops.splice(loopIndex, 1);
}
}
|
0bb9452fd5a38617497a13e651ed94905146ee43 | TypeScript | MarkSFrancis/course-review | /utils/hooks/firebase/firestore/query/state.ts | 2.59375 | 3 | import { db as fireDb } from "../../../../firebase/firestore";
import { Query } from "./queryTypeHelpers";
export type FirebaseQueryBuilder<TQuery extends Query> = (
db: typeof fireDb
) => TQuery;
export interface QueryFailedState {
state: "error";
error: unknown;
}
export interface QuerySuccessState<T> {
state: "success";
value: T;
}
export interface QueryNotFoundState {
state: "notFound";
}
export interface QueryLoadingState {
state: "loading";
}
export type QueryState<T> =
| QuerySuccessState<T>
| QueryLoadingState
| QueryFailedState
| QueryNotFoundState;
|
c9af5effddd3918c18daa03ad1c36538892945e3 | TypeScript | thundermiracle/geocoder-free | /packages/geocoder-free-utils/__test__/lib/getLocaleString.test.ts | 2.84375 | 3 | import getLocaleString from 'lib/getLocaleString';
test('input is wrong', () => {
const result1 = getLocaleString(null);
const result2 = getLocaleString('');
expect(result1).toEqual('');
expect(result2).toEqual('');
});
test('input is not date string', () => {
const result = getLocaleString('abc');
expect(result).toEqual('');
});
test('input is correct', () => {
const result = getLocaleString('2019-08-29');
const expected = new Date('2019-08-29').toLocaleString();
expect(result).toEqual(expected);
});
|
27c3ea49535a899b0a1665805bde24caf98740ba | TypeScript | ViGouRCanberra/Tamafit | /app/src/components/saveManager.ts | 2.671875 | 3 | import { readFileSync, writeFileSync, unlinkSync } from "fs";
//CONSTS
var SAVE_PATH = "tama.sav";
export function SaveManager() {
}
SaveManager.prototype.getData = function() {
//unlinkSync(SAVE_PATH);
return getFileData();
}
SaveManager.prototype.saveStepData = function(newData) {
var data = getFileData();
data.payments = newData.payments;
data.date = newData.date;
writeFileSync(SAVE_PATH, data, "json");
}
SaveManager.prototype.saveStatsData = function(newData) {
var data = getFileData();
data.hunger = newData.hunger;
data.statsDate = newData.statsDate;
writeFileSync(SAVE_PATH, data, "json");
}
SaveManager.prototype.saveHungerData = function(newData) {
var data = getFileData();
data.hunger = newData.hunger;
writeFileSync(SAVE_PATH, data, "json");
}
var getFileData = function() {
try {
return readFileSync(SAVE_PATH, "json");
} catch (error) {
createSaveFile();
return readFileSync(SAVE_PATH, "json");
}
}
var createSaveFile = function() {
writeFileSync(
SAVE_PATH,
{
'hunger': 0,
'hours': 0,
'statsDate': new Date().toISOString(),
'payments': 0,
'date': 0
},
"json"
);
} |
08e892f7dcd954c58d8f92b95559823cb2ed6bf3 | TypeScript | genstackio/libs-js | /packages/themes2tailwindcss/src/index.ts | 2.625 | 3 | import fs from 'fs';
import ejs from 'ejs';
import { colord } from 'colord';
import path from 'path';
export type value_format = 'auto' | 'raw' | 'rgba' | 'rgb' | 'hexa' | 'rgblist';
export type extended_variable_value = [value_format, string];
export type variable_value = string | number | undefined | extended_variable_value;
export type variable = {
value: variable_value;
comment?: string;
};
export type variables = {
[key: string]: variable;
};
export type config = {
variables?: variables;
};
export async function themes2tailwindcss(sourceDir: string, targetDir: string, options: any = {}): Promise<string[]> {
return Promise.all(
(await listThemeFiles(sourceDir, options)).map(
async (filePath: string): Promise<string> => convertThemeFileToTailwindcss(filePath, targetDir, options),
),
);
}
// noinspection JSUnusedLocalSymbols
export async function listThemeFiles(sourceDir: string, options: any = {}): Promise<string[]> {
return fs
.readdirSync(sourceDir)
.map((f) => (f.toString ? f.toString() : f))
.filter((f) => /\.js$/.test(f) && !/index\.js$/.test(f))
.map((f) => `${sourceDir}/${f}`);
}
// noinspection JSUnusedLocalSymbols
export async function saveCssFileContent(filePath: string, content: string, options: any = {}): Promise<void> {
fs.writeFileSync(filePath, content);
}
// noinspection JSUnusedLocalSymbols
export function convertThemeFileNameToName(filePath: string, options: any = {}): string {
return (filePath.match(/([^/]+)\.js$/) || [])[1]
.split(/[-_]+/)
.map((x) => x.toLowerCase())
.join('-');
}
export function buildVariableName(k: string) {
return k.split(/_/g).join('-');
}
export function buildCssSelectors(config: any) {
const main = config.name === 'default' ? ':root' : `.theme-${config.name}`;
return {
cssSelector: main,
cssDarkSelector:
config.name === 'default' ? `:root.dark , :root .dark` : `.dark${main}, .dark ${main}, ${main} .dark`,
};
}
function convertToRaw(v) {
return { value: String(v) };
}
function convertToRgbList(v) {
const { r, g, b } = colord(v).toRgb();
const vh = colord(v).toHex().toUpperCase();
return { value: `${r}, ${g}, ${b}`, comment: vh };
}
function convertToRgba(v) {
const { r, g, b, a } = colord(v).toRgb();
const vh = colord(v).toHex().toUpperCase();
return { value: `rgba(${r}, ${g}, ${b}, ${a})`, comment: vh };
}
function convertToHexa(v) {
const vh = colord(v).toHex().toUpperCase();
return { value: vh };
}
function convertToRgb(v) {
const { r, g, b } = colord(v).toRgb();
const vh = colord(v).toHex().toUpperCase();
return { value: `rgb(${r}, ${g}, ${b})`, comment: vh };
}
export function convertVariable(k, v, acc) {
let kk = buildVariableName(k);
if (!kk) return;
const varType = 'dark_' === k.slice(0, 5) ? 'cssDarkVariables' : 'cssVariables';
kk = 'dark_' === k.slice(0, 5) ? kk.slice(5) : kk;
v = Array.isArray(v) ? v : ['auto', v];
let vv: any = undefined;
switch (v[0]) {
case 'raw':
vv = convertToRaw(v[1]);
break;
case 'rgba':
vv = convertToRgba(v[1]);
break;
case 'rgblist':
vv = convertToRgbList(v[1]);
break;
case 'rgb':
vv = convertToRgb(v[1]);
break;
case 'hexa':
vv = convertToHexa(v[1]);
break;
default:
case 'auto':
if ('string' === typeof v[1] && /^#[0-9a-f]{3,6}$/i.test(v[1])) {
vv = convertToRgbList(v[1]);
} else {
vv = convertToRaw(v[1]);
}
break;
}
acc[varType][kk] = vv;
}
export async function convert(config: config): Promise<string> {
const vars: [string, variable][] = Object.entries(config.variables || {});
const typedVars: {
cssVariables: { [key: string]: { value: string | number | undefined; comment?: string } };
cssDarkVariables: { [key: string]: { value: string | number | undefined; comment?: string } };
} = vars.reduce(
(acc, [k, v]) => {
convertVariable(k, v, acc);
return acc;
},
{ cssVariables: {}, cssDarkVariables: {} },
);
const cssVariables = Object.entries(typedVars.cssVariables)
.sort(
(
a: [string, { value: string | number | undefined; comment?: string }],
b: [string, { value: string | number | undefined; comment?: string }],
) => {
return a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0;
},
)
.reduce((acc, [k, v]) => {
acc[k] = v;
return acc;
}, {});
const cssDarkVariables = Object.entries(typedVars.cssDarkVariables)
.sort(
(
a: [string, { value: string | number | undefined; comment?: string }],
b: [string, { value: string | number | undefined; comment?: string }],
) => {
return a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0;
},
)
.reduce((acc, [k, v]) => {
acc[k] = v;
return acc;
}, {});
const params = {
...buildCssSelectors(config),
cssVariables,
cssDarkVariables,
isDefault: config['name'] === 'default',
config,
};
return ejs.render(fs.readFileSync(`${__dirname}/../templates/theme.css.ejs`, 'utf-8'), params);
}
export async function convertThemeFileToTailwindcss(
filePath: string,
targetDir: string,
options: any = {},
): Promise<string> {
const config: any = { variables: require(path.resolve(filePath)) || {}, options } || {};
config.name = config.name || convertThemeFileNameToName(filePath, config);
const targetFilePath = `${targetDir}/${config.name}.css`;
await saveCssFileContent(targetFilePath, await convert(config));
return targetFilePath;
}
export default themes2tailwindcss;
|
b62a9893470cabb8188757b10f1166343d6f2fd1 | TypeScript | future4code/Bruno-Silva | /logic-exercises/exercise3/src/maxValueTheft.ts | 3.375 | 3 | export const maxValueTheft = (
valuesOfHouseArray: number[],
houseIndex: number = 0,
finalValueOfTheft: number = 0,
possibleValueOfTheft: number = 0
): number => {
if (valuesOfHouseArray.length < 1) {
return finalValueOfTheft;
};
if (houseIndex <= valuesOfHouseArray.length - 1) {
for (let i=houseIndex; i<valuesOfHouseArray.length; i = i + 2) {
possibleValueOfTheft += valuesOfHouseArray[i];
};
return maxValueTheft(
valuesOfHouseArray,
houseIndex + 1,
finalValueOfTheft < possibleValueOfTheft? possibleValueOfTheft : finalValueOfTheft,
0
);
} else {
return finalValueOfTheft;
};
}; |
7b2a28f555cb08be587615be77598d89cf4212f5 | TypeScript | Splidejs/splide | /src/js/components/Controller/Controller.ts | 2.71875 | 3 | import { EVENT_END_INDEX_CHANGED, EVENT_REFRESH, EVENT_RESIZED, EVENT_UPDATED } from '../../constants/events';
import { MOVING, SCROLLING } from '../../constants/states';
import { LOOP, SLIDE } from '../../constants/types';
import { EventInterface } from '../../constructors';
import { Splide } from '../../core/Splide/Splide';
import { AnyFunction, BaseComponent, Components, Options } from '../../types';
import { apply, approximatelyEqual, between, clamp, floor, isString, isUndefined, min } from '../../utils';
/**
* The interface for the Controller component.
*
* @since 3.0.0
*/
export interface ControllerComponent extends BaseComponent {
go( control: number | string, allowSameIndex?: boolean, callback?: AnyFunction ): void;
scroll( destination: number, duration?: number, snap?: boolean, callback?: AnyFunction ): void;
getNext( destination?: boolean ): number;
getPrev( destination?: boolean ): number;
getEnd(): number;
setIndex( index: number ): void;
getIndex( prev?: boolean ): number;
toIndex( page: number ): number;
toPage( index: number ): number;
toDest( position: number ): number;
hasFocus(): boolean;
isBusy(): boolean;
/** @internal */
getAdjacent( prev: boolean, destination?: boolean ): number;
}
/**
* The component for controlling the slider.
*
* @since 3.0.0
*
* @param Splide - A Splide instance.
* @param Components - A collection of components.
* @param options - Options.
*
* @return A Controller component object.
*/
export function Controller( Splide: Splide, Components: Components, options: Options ): ControllerComponent {
const { on, emit } = EventInterface( Splide );
const { Move } = Components;
const { getPosition, getLimit, toPosition } = Move;
const { isEnough, getLength } = Components.Slides;
const { omitEnd } = options;
const isLoop = Splide.is( LOOP );
const isSlide = Splide.is( SLIDE );
const getNext = apply( getAdjacent, false );
const getPrev = apply( getAdjacent, true );
/**
* The current index.
*/
let currIndex = options.start || 0;
/**
* The latest end index.
*/
let endIndex: number;
/**
* The previous index.
*/
let prevIndex = currIndex;
/**
* The latest number of slides.
*/
let slideCount: number;
/**
* The latest `perMove` value.
*/
let perMove: number;
/**
* The latest `perMove` value.
*/
let perPage: number;
/**
* Called when the component is mounted.
*/
function mount(): void {
init();
on( [ EVENT_UPDATED, EVENT_REFRESH, EVENT_END_INDEX_CHANGED ], init );
on( EVENT_RESIZED, onResized );
}
/**
* Initializes some parameters.
* Needs to check the number of slides since the current index may be out of the range after refresh.
* The process order must be Elements -> Controller -> Move.
*/
function init(): void {
slideCount = getLength( true );
perMove = options.perMove;
perPage = options.perPage;
endIndex = getEnd();
const index = clamp( currIndex, 0, omitEnd ? endIndex : slideCount - 1 );
if ( index !== currIndex ) {
currIndex = index;
Move.reposition();
}
}
/**
* Called when the viewport width is changed.
* The end index can change if `autoWidth` or `fixedWidth` is enabled.
*/
function onResized(): void {
if ( endIndex !== getEnd() ) {
emit( EVENT_END_INDEX_CHANGED );
}
}
/**
* Moves the slider by the control pattern.
*
* @see `Splide#go()`
*
* @param control - A control pattern.
* @param allowSameIndex - Optional. Determines whether to allow going to the current index or not.
* @param callback - Optional. A callback function invoked after transition ends.
*/
function go( control: number | string, allowSameIndex?: boolean, callback?: AnyFunction ): void {
if ( ! isBusy() ) {
const dest = parse( control );
const index = loop( dest );
if ( index > -1 && ( allowSameIndex || index !== currIndex ) ) {
setIndex( index );
Move.move( dest, index, prevIndex, callback );
}
}
}
/**
* Scrolls the slider to the specified destination with updating indices.
*
* @param destination - The position to scroll the slider to.
* @param duration - Optional. Specifies the scroll duration.
* @param snap - Optional. Whether to snap the slider to the closest slide or not.
* @param callback - Optional. A callback function invoked after scroll ends.
*/
function scroll( destination: number, duration?: number, snap?: boolean, callback?: AnyFunction ): void {
Components.Scroll.scroll( destination, duration, snap, () => {
const index = loop( Move.toIndex( getPosition() ) );
setIndex( omitEnd ? min( index, endIndex ) : index );
callback && callback();
} );
}
/**
* Parses the control and returns a slide index.
*
* @param control - A control pattern to parse.
*
* @return A `dest` index.
*/
function parse( control: number | string ): number {
let index = currIndex;
if ( isString( control ) ) {
const [ , indicator, number ] = control.match( /([+\-<>])(\d+)?/ ) || [];
if ( indicator === '+' || indicator === '-' ) {
index = computeDestIndex( currIndex + +`${ indicator }${ +number || 1 }`, currIndex );
} else if ( indicator === '>' ) {
index = number ? toIndex( +number ) : getNext( true );
} else if ( indicator === '<' ) {
index = getPrev( true );
}
} else {
index = isLoop ? control : clamp( control, 0, endIndex );
}
return index;
}
/**
* Returns an adjacent destination index.
*
* @internal
*
* @param prev - Determines whether to return a previous or next index.
* @param destination - Optional. Determines whether to get a destination index or a slide one.
*
* @return An adjacent index if available, or otherwise `-1`.
*/
function getAdjacent( prev: boolean, destination?: boolean ): number {
const number = perMove || ( hasFocus() ? 1 : perPage );
const dest = computeDestIndex( currIndex + number * ( prev ? -1 : 1 ), currIndex, ! ( perMove || hasFocus() ) );
if ( dest === -1 && isSlide ) {
if ( ! approximatelyEqual( getPosition(), getLimit( ! prev ), 1 ) ) {
return prev ? 0 : endIndex;
}
}
return destination ? dest : loop( dest );
}
/**
* Converts the desired destination index to the valid one.
* - If the `move` option is `true`, finds the dest index whose position is different with the current one.
* - This may return clone indices if the editor is the loop mode,
* or `-1` if there is no slide to go.
* - There are still slides where the carousel can go if borders are between `from` and `dest`.
* - If `focus` is available, needs to calculate the dest index even if there are enough number of slides.
*
* @param dest - The desired destination index.
* @param from - A base index.
* @param snapPage - Optional. Whether to snap a page or not.
*
* @return A converted destination index, including clones.
*/
function computeDestIndex( dest: number, from: number, snapPage?: boolean ): number {
if ( isEnough() || hasFocus() ) {
const index = computeMovableDestIndex( dest );
if ( index !== dest ) {
from = dest;
dest = index;
snapPage = false;
}
if ( dest < 0 || dest > endIndex ) {
if ( ! perMove && ( between( 0, dest, from, true ) || between( endIndex, from, dest, true ) ) ) {
dest = toIndex( toPage( dest ) );
} else {
if ( isLoop ) {
dest = snapPage
? dest < 0 ? - ( slideCount % perPage || perPage ) : slideCount
: dest;
} else if ( options.rewind ) {
dest = dest < 0 ? endIndex : 0;
} else {
dest = -1;
}
}
} else {
if ( snapPage && dest !== from ) {
dest = toIndex( toPage( from ) + ( dest < from ? -1 : 1 ) );
}
}
} else {
dest = -1;
}
return dest;
}
/**
* Finds the dest index whose position is different with the current one for `trimSpace: 'move'`.
* This can be negative or greater than `length - 1`.
*
* @param dest - A dest index.
*
* @return A dest index.
*/
function computeMovableDestIndex( dest: number ): number {
if ( isSlide && options.trimSpace === 'move' && dest !== currIndex ) {
const position = getPosition();
while ( position === toPosition( dest, true ) && between( dest, 0, Splide.length - 1, ! options.rewind ) ) {
dest < currIndex ? --dest : ++dest;
}
}
return dest;
}
/**
* Loops the provided index only in the loop mode.
*
* @param index - An index to loop.
*
* @return A looped index.
*/
function loop( index: number ): number {
return isLoop ? ( index + slideCount ) % slideCount || 0 : index;
}
/**
* Returns the end index where the slider can go.
* For example, if the slider has 10 slides and the `perPage` option is 3,
* the slider can go to the slide 8 (the index is 7).
* If the `omitEnd` option is available, computes the index from the slide position.
*
* @return An end index.
*/
function getEnd(): number {
let end = slideCount - ( hasFocus() || ( isLoop && perMove ) ? 1 : perPage );
while ( omitEnd && end-- > 0 ) {
if ( toPosition( slideCount - 1, true ) !== toPosition( end, true ) ) {
end++;
break;
}
}
return clamp( end, 0, slideCount - 1 );
}
/**
* Converts the page index to the slide index.
*
* @param page - A page index to convert.
*
* @return A slide index.
*/
function toIndex( page: number ): number {
return clamp( hasFocus() ? page : perPage * page, 0, endIndex );
}
/**
* Converts the slide index to the page index.
*
* @param index - An index to convert.
*
* @return A page index.
*/
function toPage( index: number ): number {
return hasFocus()
? min( index, endIndex )
: floor( ( index >= endIndex ? slideCount - 1 : index ) / perPage );
}
/**
* Converts the destination position to the dest index.
*
* @param destination - A position to convert.
*
* @return A dest index.
*/
function toDest( destination: number ): number {
const closest = Move.toIndex( destination );
return isSlide ? clamp( closest, 0, endIndex ) : closest;
}
/**
* Sets a new index and retains old one.
*
* @param index - A new index to set.
*/
function setIndex( index: number ): void {
if ( index !== currIndex ) {
prevIndex = currIndex;
currIndex = index;
}
}
/**
* Returns the current/previous index.
*
* @param prev - Optional. Whether to return previous index or not.
*/
function getIndex( prev?: boolean ): number {
return prev ? prevIndex : currIndex;
}
/**
* Verifies if the focus option is available or not.
*
* @return `true` if the slider has the focus option.
*/
function hasFocus(): boolean {
return ! isUndefined( options.focus ) || options.isNavigation;
}
/**
* Checks if the slider is moving/scrolling or not.
*
* @return `true` if the slider can move, or otherwise `false`.
*/
function isBusy(): boolean {
return Splide.state.is( [ MOVING, SCROLLING ] ) && !! options.waitForTransition;
}
return {
mount,
go,
scroll,
getNext,
getPrev,
getAdjacent,
getEnd,
setIndex,
getIndex,
toIndex,
toPage,
toDest,
hasFocus,
isBusy,
};
}
|
cbc687fee498096269d590f6f7fdcd32a294bd59 | TypeScript | linkiez/JCMserver | /public/ts/view/mensagemView.ts | 2.828125 | 3 | export class MensagemView {
private divMensagem: HTMLDivElement;
constructor() {
this.divMensagem = document.querySelector("#divMensagem");
}
mensagemLimpar(): void {
if (this.divMensagem.classList.contains("alert-success")) {
this.divMensagem.classList.remove("alert-success");
}
if (this.divMensagem.classList.contains("alert-danger")) {
this.divMensagem.classList.remove("alert-danger");
}
this.divMensagem.innerHTML = ``;
}
mensagemSucesso(mensagem: string): void {
this.mensagemLimpar();
this.divMensagem.classList.add("alert-success");
this.divMensagem.textContent = mensagem;
}
mensagemErro(mensagem: string): void {
this.mensagemLimpar();
this.divMensagem.classList.add("alert-danger");
this.divMensagem.textContent = mensagem;
}
}
|
a80e48406bbab078a8878df4bc5e4e3f8f28a881 | TypeScript | goeaway/user-tagger | /src/common/services/site-user-service.ts | 2.640625 | 3 | import { ISiteUserService, IStorageService } from "../abstract-types";
import { SiteUser, Site, UserTag, RGBExtensions } from "../types";
import * as uuid from "uuid";
export default class SiteUserService implements ISiteUserService {
private LOCAL_STORAGE_SITE_USER_KEY = "user-tagger.saved-site-user.";
private _storageService: IStorageService;
constructor(storageService: IStorageService) {
this._storageService = storageService;
}
getUser = (username: string) : SiteUser => {
const existing = this._storageService.get<SiteUser>(this.LOCAL_STORAGE_SITE_USER_KEY + username);
// return the existing if it exists, otherwise return an empty user. Don't bother putting that empty one in the store
// at the moment we don't need it there and it will be added if the app user decides to add a tag to it
return existing || { username: username, tags: [] };
};
getAllUsers = () : Array<SiteUser> => {
return this._storageService.getMatchingKey<SiteUser>(this.LOCAL_STORAGE_SITE_USER_KEY + "*");
}
getTagsNotFoundOnUser = (excludingUser?: SiteUser, search?: string) : Array<UserTag> => {
let allTags: Array<UserTag> = [];
// todo fix this so we can get all tags saved so far
this.getAllUsers().forEach(u => allTags = allTags.concat(u.tags));
if(excludingUser) {
allTags = allTags.filter(t => !excludingUser.tags.some(ex => ex.id === t.id));
}
if(search) {
allTags = allTags.filter(t => t.name.indexOf(search) > -1)
}
return allTags;
}
setUser = (user: SiteUser) => {
if(!user) {
throw "user was null";
}
this._storageService.set(this.LOCAL_STORAGE_SITE_USER_KEY + user.username, user);
}
} |
8fdc3044c52256d6b6805ece659fe75468877668 | TypeScript | ziyofun/cb-sea | /src/course.ts | 2.921875 | 3 | import base from './base'
import { genQuery } from './util'
interface ICourse {
id?: string
name?: string
type?: string
state?: string
semesterId?: number
stageId?: number
subjectId?: number
subjectName?: string
stageName?: string
semesterName?: string
}
interface ISemester {
id?: number
name?: string
}
interface IStage {
id?: number
name?: string
childs?: ISemester[]
}
interface ISubject {
id?: number
name?: string
childs?: IStage[]
}
export class Course extends base {
/**
*
* @param id : 课程id
*
*/
public async get(id: string): Promise<ICourse> {
return (await this.getHttp(`/courses/${id}`)) as ICourse
}
/**
*
* @param subjectId : 学科id
* @param stageId : 学段id
* @param semesterId : 学期id
* @param param type : 课程类型
* return: 课程列表
*/
public async getList({
subjectId,
stageId,
semesterId,
type,
}: {
subjectId?: string
stageId?: string
semesterId?: string
type: 'system' | 'special'
}): Promise<any> {
return (await this.getHttp(`/courses?${genQuery({ subjectId, stageId, semesterId, type })}`)) as ICourse[]
}
/**
*
* @param id : 课程id
* return: 课程结构(包括课程下的章,大节,小节,知识点)
*
*/
public getTree(id: string): Promise<any> {
return this.getHttp(`/courses/tree/${id}`)
}
/**
* return: 学科学段学期树形结构
*/
public async getTreeStruct() {
return (await this.getHttp('/courses/treeStruct')) as ISubject[]
}
}
|
6467441bd6cf772d08d4b1ca6613c0a02dcef536 | TypeScript | harut0111/redux-crud | /src/component/ReduxCRUD/reduxCRUDSlice.ts | 2.84375 | 3 | import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "../../app/store";
export interface postsType {
id: string;
title: string;
message: string;
}
export interface reduxCRUDType {
posts: Array<postsType>;
}
const initialState: reduxCRUDType = {
posts: [],
};
export const reduxCRUD = createSlice({
name: "reduxCRUD",
initialState: initialState,
reducers: {
post: (state, action: PayloadAction<postsType>) => {
state.posts.push(action.payload);
},
remove: (state, action: PayloadAction<string>) => {
state.posts = state.posts.filter((post) => post.id !== action.payload);
},
update: (state, action: PayloadAction<postsType>) => {
state.posts = state.posts.map((post) =>
post.id === action.payload.id ? action.payload : post
);
},
},
});
export const { post, remove, update } = reduxCRUD.actions;
export const selectPosts = (state: RootState): Array<postsType> =>
state.reduxCRUD.posts;
export default reduxCRUD.reducer;
|
1ef6a27031646aae922fa161fb5e70bd078abed5 | TypeScript | sarker24/eesmiley-fromtend | /frontend-client/src/pages/registration/GuestRegistrationHistory/utils/phraseLocalize.ts | 2.546875 | 3 | import { InjectedIntl } from 'react-intl';
function phraseLocalize(intl: InjectedIntl, key: string): string {
const lastDot: number = key.lastIndexOf('.');
if (lastDot < 0) {
return intl.messages[key];
}
const lastKey: string = key.substring(lastDot + 1);
const pluralKeys: string[] = ['zero', 'one', 'other'];
if (!pluralKeys.includes(lastKey)) {
return intl.messages[key];
}
const baseKey: string = key.substring(0, lastDot);
return intl.messages[baseKey][lastKey] as string;
}
export default phraseLocalize;
|
2433ea0eb2b81b140075a8f0253b1532c5dd207c | TypeScript | Autapomorph/forecast | /src/utils/weather/time/__tests__/index.test.ts | 2.859375 | 3 | import { DateTime } from 'luxon';
import formatTime from '..';
describe('Format time', () => {
it('should return instance of DateTime', () => {
expect(formatTime(0, 'Europe/Moscow')).toBeInstanceOf(DateTime);
});
it('should convert to UTC+3 zone', () => {
const res = formatTime(0, 'UTC+3');
expect(res.toString()).toEqual('1970-01-01T03:00:00.000+03:00');
});
it('should convert to UTC zone', () => {
const res = formatTime(0);
expect(res.toString()).toEqual('1970-01-01T00:00:00.000Z');
});
it('should handle nonexistent IANA time zone', () => {
const res = formatTime(0, 'nonexistent IANA time zone');
expect(res.toString()).toBe('Invalid DateTime');
});
});
|
b31ef3e5333760eb033f0126d6a2a8242e36625c | TypeScript | bigshoesdev/WorkLine-App | /src/app/main/auth/register/register.ts | 2.515625 | 3 | import { Component } from '@angular/core';
import { UserService } from 'src/app/services/user.service';
import { UtilService } from 'src/app/services/util.service';
import { Router } from '@angular/router';
@Component({
selector: 'auth-register',
templateUrl: 'register.html',
styleUrls: ['register.scss'],
})
export class RegisterPage {
user = {
name: '',
code: '',
mobile: '',
type: 1, // 1: Employer 0: Employee
};
constructor(private _router: Router, private userService: UserService, private utilService: UtilService) { }
async register() {
if (this.user.name === '' || this.user.code === '' || this.user.mobile === '') {
this.utilService.showErrorToast('Please fill in blanks.');
return;
}
await this.utilService.showLoading();
this.userService.registerUser({
name: this.user.name,
code: this.user.code,
mobile: this.user.mobile,
type: this.user.type
}).then(o => {
this.utilService.closeLoading();
if (o.success) {
this.utilService.showSuccessToast('Successfully Registered');
this._router.navigate(['auth/login']);
} else {
this.utilService.showErrorToast(o.message);
}
}, (error) => {
this.utilService.closeLoading();
this.utilService.showErrorToast(error.message);
});
}
}
|
548f30050f421330a17e74b1b77f38186a501765 | TypeScript | huangdoudou6174/cocosGame | /TypeScript/Script/Recommend/RecommendConfig.ts | 2.65625 | 3 |
const { ccclass, property } = cc._decorator;
/**使用Youzi互推时,管理后台提供的平台渠道 默认微信 */
const PLAT_TYPE_CHANNELID = {
Test: 1001, //测试也用微信,此处为避免cc.Enum报错,使用1001,,get访问时会自动变为1002
WeChat: 1002, //微信
Oppo: 8001, //oppo小游戏
TouTiao: 11001 //头条小游戏
};
/**互推配置脚本,挂载在互推根节点上 */
@ccclass
export default class RecommendConfig extends cc.Component {
public static recommendPlatformType = cc.Enum({
PC: 0,
WX: -1,
TT: -1,
QQ: -1,
OPPO: -1,
VIVO: -1,
XiaoMi: -1,
LeYou: -1,
DYB_QQ: -1,
Blue_Android: -1,
Blue_IOS: -1,
Youzi: -1,
});
@property({
type: RecommendConfig.recommendPlatformType,
tooltip: "互推类型",
})
public type: number = RecommendConfig.recommendPlatformType.PC;
@property({
tooltip: "使用Youzi互推时,渠道提供的appid 如果是微信渠道 填写微信后台提供的appid。"
})
public Youzi_Appid: string = "";
@property({
tooltip: "使用Youzi互推时,中心化资源版本 中心化提供的资源版本号 向中心化对接组咨询 默认'1.00.00'。"
})
public Youzi_ResVersion: string = "1.00.00";
public static YouziChannelType = cc.Enum(PLAT_TYPE_CHANNELID);
@property({
type: RecommendConfig.YouziChannelType,
tooltip: "使用Youzi互推时,管理后台提供的平台渠道 默认微信",
visible: true,
})
protected _Youzi_ChannelId: number = RecommendConfig.YouziChannelType.WeChat;
public get Youzi_ChannelId() {
if (this._Youzi_ChannelId == PLAT_TYPE_CHANNELID.Test) {
return PLAT_TYPE_CHANNELID.WeChat;
} else {
return this._Youzi_ChannelId;
}
}
}
|
e3092780938d6c00905ec6a88570bb26072c851b | TypeScript | couturecraigj/slds-react-components | /components/DateInput/__tests__/useCalendar.spec.ts | 2.53125 | 3 | import { renderHook } from "@testing-library/react-hooks";
import useCalendar from "../hooks/useCalendar";
import { getFormat } from "../parseDate";
describe("useCalendar", () => {
let languageGetter;
beforeEach(() => {
languageGetter = jest.spyOn(window.navigator, "language", "get");
});
it("should work", () => {
languageGetter.mockReturnValue("de-DE");
getFormat();
const {
result: { current: calendar }
} = renderHook(() => useCalendar(new Date()));
expect(calendar).toBeDefined();
});
it("should render correct month and year `de-DE`", () => {
languageGetter.mockReturnValue("de-DE");
getFormat();
const {
result: {
current: [calendar]
}
} = renderHook(() => useCalendar(new Date(2020, 4, 5)));
expect(calendar.selected.year).toEqual(2020);
expect(calendar.selected.month).toEqual(4);
expect(calendar.selected.day).toEqual(5);
expect(calendar.selected.value).toEqual("05.05.2020");
});
it("should render correct month and year `de-DE`", () => {
languageGetter.mockReturnValue("de-DE");
getFormat();
const {
result: {
current: [calendar]
}
} = renderHook(() => useCalendar(new Date(2020, 4, 5)));
expect(calendar.month.visible.index).toEqual(4);
expect(calendar.month.visible.label).toEqual("May");
expect(calendar.selected.month).toEqual(4);
});
it("should render correct month and year `en-US`", () => {
languageGetter.mockReturnValue("en-US");
getFormat();
const {
result: {
current: [calendar]
}
} = renderHook(() => useCalendar(new Date(2020, 4, 5)));
expect(calendar.selected.year).toEqual(2020);
expect(calendar.selected.month).toEqual(4);
expect(calendar.selected.day).toEqual(5);
expect(calendar.selected.value).toEqual("5/5/2020");
});
it("should render correct month and year `en-US`", () => {
languageGetter.mockReturnValue("en-US");
getFormat();
const {
result: {
current: [calendar]
}
} = renderHook(() => useCalendar(new Date(2020, 4, 5)));
expect(calendar.month.visible.index).toEqual(4);
expect(calendar.month.visible.label).toEqual("May");
expect(calendar.selected.month).toEqual(4);
});
it("should render the correct amount of weeks at 2020-05-31", () => {
const {
result: {
current: [calendar]
}
} = renderHook(() => useCalendar(new Date(2020, 4, 31)));
expect(calendar.month.visible.length).toEqual(31);
expect(calendar.weeks.length).toEqual(6);
});
});
|
054802325a57e68ccf4864a7fd81a7cf56a27bb2 | TypeScript | irrigador/form_recursive | /server/src/controllers/ClassesController.ts | 2.578125 | 3 | import { Request, Response } from 'express';
import db from '../database/connection';
export default class ClassesController{
async index(request: Request, response: Response) {
const filters = request.query;
const subject = filters.subject as string;
if (!filters.subject) {
return response.status(400).json ({
error: 'Falta adicionar algo'
});
}
const classes = await db ('classes')
.where('classes.subject', '=', subject)
.join('users', 'classes.user_id', '=', 'users.id')
.select(['classes.*', 'users.*']);
return response.json(classes);
}
async create (request: Request, response: Response) {
const {
name,
avatar,
whatsapp,
bio,
subject,
cost,
week_day,
from,
to
} = request.body;
const trx = await db.transaction();
try {
const instertUsersIds = await trx ('users').insert({
name,
avatar,
whatsapp,
bio,
});
const user_id = instertUsersIds [0];
const insertedClassesIds = await trx ('classes').insert ({
subject,
cost,
user_id,
});
await trx ('class_schedule').insert ({
week_day,
from,
to
});
await trx.commit();
return response.status(201).send();
} catch (err) {
await trx.rollback();
return response.status(400).json ({
error: 'Erro na criação de alguma classe'
})
}
}
} |
3cf74c23280f9baaeab78de6107fd6595a7a2b6b | TypeScript | hetashpatel7/COMP397-Lesson01-Part2 | /Lesson1/scripts/game.ts | 2.546875 | 3 | class person {
constructor()
{ }
public saysHello()
{
console.log("Hello world")}
}
function init() {
var myPerson = new person();
myPerson.saysHello();
} |
4fd4370ae742d93ea0cdcd2e76ca8c2d4673e441 | TypeScript | nonameche/myblog | /src/hooks/useAntdTable.ts | 2.625 | 3 | import { useState, useCallback } from 'react'
import axios from '@/utils/axios'
import useMount from './useMount'
/**
* useAntdTable hooks 用于处理 loading 逻辑以及换页 检索等
*
* @param {Object} obj
* @param {Function} obj.fetchList 获取列表的函数
* @param {Object} obj.queryParams 默认要检索的参数
*/
export default function useAntdTable({ requestUrl = '', queryParams = null, columns = [], isAdmin = true }) {
const [loading, setLoading] = useState(false)
const [dataList, setDataList] = useState([])
const [tablePagination, setTablePagination] = useState({ current: 1, pageSize: 10, total: 0 })
useMount(fetchListWithLoading)
function fetchDataList(params) {
const requestParams = {
page: tablePagination.current,
pageSize: tablePagination.pageSize,
...queryParams,
...params
}
axios
.get(requestUrl, { params: requestParams })
.then(response => {
const { page, pageSize } = requestParams
const { count, rows } = response.data
if (count > 0 && count > pageSize) {
const totalPage = Math.ceil(count / pageSize)
if (totalPage < page) return fetchDataList({ page: totalPage }) // 例如 删除了列表里只有一项且删除,则需要跳转回前一页 也即最后一页
}
tablePagination.current = page
tablePagination.total = count
setTablePagination({ ...tablePagination }) // 设置分页
setDataList(rows)
setLoading(false)
console.log('%c useAntdTabled', 'background: yellow', requestParams, rows)
})
.catch(error => {
console.log('fetchDataList error: ', requestParams, error)
setLoading(false)
})
}
async function fetchListWithLoading(params) {
setLoading(true)
fetchDataList(params)
}
async function updateList(func) {
try {
setLoading(true)
await func()
fetchDataList(null)
} catch (error) {
console.log('updateList error: ', error)
setLoading(false)
}
}
/**
* 分页、排序、筛选变化时触发
* 注意 当前只封装分页
*/
function handleTableChange(pagination, filters, sorter) {
if (JSON.stringify(filters) === '{}' && JSON.stringify(sorter) === '{}') {
fetchListWithLoading({ page: pagination.current })
}
}
/**
* 检索功能
*/
function onSearch(params) {
fetchListWithLoading({ page: 1, ...params })
}
return {
tableProps: {
className: isAdmin ? 'admin-table' : '',
rowKey: 'id',
loading,
columns,
dataSource: dataList,
pagination: {
current: tablePagination.current,
pageSize: tablePagination.pageSize,
total: tablePagination.total,
showTotal: total => `共 ${total} 条`
},
onChange: handleTableChange
},
dataList,
updateList: useCallback(updateList, [tablePagination, queryParams]), // 进行 action 操作 比如删除修改数据后获取数据 @example updateList(() => { return axios.put('xxxx') })
onSearch: useCallback(onSearch, [tablePagination, queryParams]),
setLoading: useCallback(setLoading, [])
}
}
|
d5143938a0e02036d9cbc7c9432805156c303ebb | TypeScript | lixin2628/h5-egret-libs | /templates/UISlideView/UISlideBackGround.ts | 2.609375 | 3 | /**
* Created by Lixin on 15/11/24.
*
* 横向滑动栏 背景
*
*/
class UISlideBackGround extends egret.Sprite {
public config:any;
public constructor(config:any) {
super();
this.config = config;
this.width = this.config.SlideViewWidch;
this.height = this.config.SlideViewHeight;
if (typeof this.config.SlideViewBgStyle.background == "string") {
var bit:egret.Bitmap = new egret.Bitmap(RES.getRes(this.config.SlideViewBgStyle.background));
this.addChild(bit);
} else {
var shp:egret.Shape = new egret.Shape();
shp.graphics.beginFill(this.config.SlideViewBgStyle.background, this.config.SlideViewBgStyle.alpha);
if (this.config.SlideViewBgStyle.strokeSize > 0) {
shp.graphics.lineStyle(this.config.SlideViewBgStyle.strokeSize, this.config.SlideViewBgStyle.color, 1);
}
shp.graphics.drawRect(0, 0, this.width, this.height);
shp.graphics.endFill();
this.addChild(shp);
console.log('add child');
}
}
} |
93b37f9d0b20a3c38fd72edd5802ffbcce00303c | TypeScript | nguyenvanuoc/angular | /iOffice-theme/projects/main/src/app/shared-components/validator.ts | 2.859375 | 3 | import { AbstractControl, ValidationErrors } from '@angular/forms';
export class MyValidator {
static DemoValidator(control: AbstractControl): ValidationErrors | null {
return demoValid(control);
}
}
export function demoValid(control: AbstractControl): ValidationErrors | null {
if (control.value != null && control.value.startsWith(' ')) {
return {
trimError: { value: 'control has leading whitespace' },
};
}
if (control.value != null && control.value.endsWith(' ')) {
return {
trimError: { value: 'control has trailing whitespace' },
};
}
return null;
}
|
78753d3bb0234d83a3c23d20dee76d4ce14ff5a2 | TypeScript | Hydro-Dog/react-todo | /src/redux/reducers/pagination-reducer.ts | 2.734375 | 3 | import { CHANGE_PAGE } from "../actions/pagination-actions"
const initialState = {
currentPage: '1'
}
export const paginationReducer = (state = initialState, action: any) => {
switch (action.type) {
case CHANGE_PAGE: {
return {
...state,
currentPage: action.payload
}
}
default: {
return state
}
}
} |
2acf40ff6a33233709add6a067012823b6aa4d62 | TypeScript | torkpe/reebee-project | /src/services/showService.ts | 2.578125 | 3 | import { ShowDetails, ShowsResponse } from '../interface/interface';
import Axios from "../utils/axios";
export class ShowService extends Axios {
private url = 'https://api.tvmaze.com/';
async searchShows (searchKey: string): Promise<ShowDetails[]>{
const response = await this.axios.get(`${this.url}search/shows?q=${searchKey}`);
return response.data.map((data: ShowsResponse) => ({
name: data.show.name,
image: data.show.image,
genres: data.show.genres,
summary: data.show.summary,
id: data.show.id
}))
}
async getShow (id: string): Promise<ShowDetails>{
const response = await this.axios.get(`${this.url}shows/${id}`);
return response.data;
}
}
export default new ShowService();
|
6bc872a7725707999ec6d1618008a296cf2e6344 | TypeScript | SergioEGGit/Project_Translator_From_Java_To_Javascript_And_Python_SEG | /Source Code/Backend/Traductores/Javascript/src/AnalizadorLexicoSintactico/Clase.ts | 2.859375 | 3 | // Imports
// Clase Abstracta
import { Instruccion } from "./Instruccion";
// Metodo Identacion
import { AgregarIdentacion } from './Variables_Metodos';
// Clase Principal
export class Clase extends Instruccion {
// Constructor
constructor(Linea: number, Columna: number, private Identificador: String, private BloqueClase: Instruccion) {
// Super
super(Linea, Columna)
}
// Metodo Traducir
public Traducir() {
// Declaraciones
let Identificador = this.Identificador;
let BloqueClase = this.BloqueClase.Traducir();
// Traduccion
let Traduccion = AgregarIdentacion() + "class " + Identificador + " { \n\n" +
AgregarIdentacion() + " constructor() { \n\n" +
AgregarIdentacion() + " } \n\n" +
BloqueClase + "\n" +
AgregarIdentacion() + "} \n\n";
return Traduccion;
}
} |
cb5508cb07d919ec48f46dc69009e52ad7d5b62e | TypeScript | Marcosaurios/martian-robots | /src/server/routes/exploration.ts | 2.84375 | 3 | import express from 'express';
import Mars from '../../mars';
/**
* Process a map and its robots in Mars
* @param {express.Request} req Request object
* @param {express.Response} res object, which will be returned with the exploration result
*/
/** */
function explore(
req: express.Request,
res: express.Response,
): express.Response {
if (!req.files || !req.files.file.name.endsWith('.txt')) {
return res
.send({ error: 'You have to submit a file in order to process it.' })
.status(422);
}
const str = req.files.file.data.toString();
const planet = new Mars(str);
planet.startExploration();
const out = planet.getOutput();
return res.contentType('text/plain').send(out);
}
export default explore;
|
36f0e72ff4fa4c4d6dc375ba0b06d3ab61adf02a | TypeScript | bastienhousiaux/pokerCoach | /ts/poker/Card.ts | 3.515625 | 4 | namespace poker{
export class Card{
static CARD_STRING_VALUES=["2","3","4","5","6","7","8","9","T","J","Q","K","A"];
static CARD_STRING_COLORS=["♥","♦","♣","♠"];
constructor(public value:number=0,public color:number=0){
}
getStringRepresentation():string{
return this.getCardStringValue()+this.getCardColorValue();
}
getNumberRepresentation():number{
return this.color*Card.CARD_STRING_VALUES.length+this.value;
}
fromNumberRepresentation(representation:number){
this.value=representation%13;
this.color=Math.floor(representation/13);
}
getCardStringValue():string{
return Card.CARD_STRING_VALUES[this.value];
}
getCardColorValue():string{
return Card.CARD_STRING_COLORS[this.color];
}
}
}
|
906fd800e3d9f549f8c623ea23e266c38977f121 | TypeScript | alex-davies/circuitnect | /test/engine/Hex.test.ts | 2.6875 | 3 | ///<reference path="../../lib/qunit/qunit.d.ts"/>
import Hex = require('../../engine/Hex');
export function run(){
QUnit.module('Hex');
//QUnit.test( "Neighbours", function( assert ) {
// assert.deepEqual(Hex.Neighbours({pos_b:2, pos_a:3}),[
// {pos_b:2,pos_a:2},
// {pos_b:3,pos_a:2},
// {pos_b:3,pos_a:3},
// {pos_b:2,pos_a:4},
// {pos_b:1,pos_a:4},
// {pos_b:1,pos_a:3}
// ]);
//
//});
QUnit.test( "Ring - when radius 0 should be start point", function( assert ) {
var ring = Hex.Ring({a:2, b:3}, 0);
assert.deepEqual(ring,[{a:2, b:3}]);
});
QUnit.test( "Ring - should be ring of points", function( assert ) {
var ring = Hex.Ring({a:2, b:3}, 2, Hex.Direction.pos_a);
assert.deepEqual(ring,[
{a:4, b:3},
{a:4, b:2},
{a:4, b:1},
{a:3, b:1},
{a:2, b:1},
{a:1,b:2},
{a:0,b:3},
{a:0,b:4},
{a:0,b:5},
{a:1,b:5},
{a:2,b:5},
{a:3,b:4},
]);
});
QUnit.test( "Spiral - should be increasing ring of points", function( assert ) {
var spiral = Hex.Spiral({a:2, b:3}, 2, Hex.Direction.pos_a);
assert.deepEqual(spiral,[
{a:2, b:3},
{a:3,b:3},
{a:3,b:2},
{a:2,b:2},
{a:1,b:3},
{a:1,b:4},
{a:2,b:4},
{a:4, b:3},
{a:4, b:2},
{a:4, b:1},
{a:3, b:1},
{a:2, b:1},
{a:1,b:2},
{a:0,b:3},
{a:0,b:4},
{a:0,b:5},
{a:1,b:5},
{a:2,b:5},
{a:3,b:4},
]);
});
QUnit.test( "ToCartesianPoint - FlatTop move only in Y direction", function( assert ) {
var cart = Hex.ToCartesianPoint({a:0, b:1}, 10, Hex.CartesianOrientation.FlatTop);
assert.equal(cart.x, 0);
assert.equal(cart.y, Hex.CartesianDimensions(10,Hex.CartesianOrientation.FlatTop).height);
});
QUnit.test( "ToCartesianPoint - FlatTop move only in X direction", function( assert ) {
var cart = Hex.ToCartesianPoint({a:2, b:-1}, 10, Hex.CartesianOrientation.FlatTop);
assert.equal(cart.x, Hex.CartesianDimensions(10,Hex.CartesianOrientation.FlatTop).width + 10);
assert.equal(cart.y, 0);
});
QUnit.test( "ToHexPoint - FlatTop move only in X direction", function( assert ) {
var hex = Hex.ToHexPoint({x:0, y:10}, 10, Hex.CartesianOrientation.FlatTop);
assert.equal(hex.b, 1);
assert.equal(hex.a, 0);
});
QUnit.test( "CartesianDimensions - FlatTop single tile dimensions", function( assert ) {
var dimensions = Hex.CartesianDimensions(10, Hex.CartesianOrientation.FlatTop);
assert.equal(dimensions.width, 20);
decEqual(assert, dimensions.height, 17.3, 0.1,'');
});
function decEqual(assert, actual, expected, tolerance, message) {
assert.ok(Math.abs(actual - expected) <= tolerance, message);
}
}
|
ac977e23dafaaaf47878cdb3281dcc35dbe20fa6 | TypeScript | swc-project/swc | /crates/swc_bundler/tests/.cache/deno/cf12ac454c69f7afb74184149dc89ad59a2120c7.ts | 2.515625 | 3 | // Loaded from https://deno.land/x/deno_image@v0.0.3/lib/decoders/fast-png/types.ts
import { IOBuffer } from './iobuffer/IOBuffer.ts';
declare enum StrategyValues {
Z_FILTERED = 1,
Z_HUFFMAN_ONLY = 2,
Z_RLE = 3,
Z_FIXED = 4,
Z_DEFAULT_STRATEGY = 0,
}
export interface DeflateFunctionOptions {
level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
windowBits?: number;
memLevel?: number;
strategy?: StrategyValues;
dictionary?: any;
raw?: boolean;
to?: "string";
}
export type PNGDataArray = Uint8Array | Uint16Array;
export type DecoderInputType = IOBuffer | ArrayBufferLike | ArrayBufferView;
export type BitDepth = 1 | 2 | 4 | 8 | 16;
export interface IPNGResolution {
/**
* Pixels per unit, X axis
*/
x: number;
/**
* Pixels per unit, Y axis
*/
y: number;
/**
* Unit specifier
*/
unit: ResolutionUnitSpecifier;
}
export enum ResolutionUnitSpecifier {
/**
* Unit is unknown
*/
UNKNOWN = 0,
/**
* Unit is the metre
*/
METRE = 1,
}
export interface IImageData {
width: number;
height: number;
data: PNGDataArray;
depth?: BitDepth;
channels?: number;
}
export interface IDecodedPNG {
width: number;
height: number;
data: PNGDataArray;
depth: BitDepth;
channels: number;
text: { [key: string]: string };
resolution?: IPNGResolution;
palette?: IndexedColors;
}
export interface IPNGDecoderOptions {
checkCrc?: boolean;
}
export interface IPNGEncoderOptions {
zlib?: DeflateFunctionOptions;
}
export type IndexedColors = number[][];
export interface IInflator {
result: Uint8Array | Array<any> | string;
err: number;
msg: string;
push: Function;
onData: Function;
onEnd: Function;
}
|
62d896dcf7161b4564cc207a7725b8addfafa909 | TypeScript | imba-js/stdio | /src/streams/mock-stream.ts | 2.921875 | 3 | import {Stream} from './stream';
export class MockStream implements Stream
{
private _content: Array<string> = [];
private _columns: number;
private _rows: number;
constructor(columns: number = 80, rows: number = 20)
{
this._columns = columns;
this._rows = rows;
}
public write(message: string): void
{
this._content.push(message);
}
public isTTY(): boolean
{
return true;
}
public getContent(): Array<string>
{
return this._content;
}
public getColumns(): number
{
return this._columns;
}
public getRows(): number
{
return this._rows;
}
}
|
4b8d0d43f4bb754d1a7a14b4b75fe454acc17dbd | TypeScript | UCSD-PL/rs-benchmarks | /d3/src-ts/geom/voronoi.ts | 2.59375 | 3 | /// <reference path="../../d3.d.ts" />
/// <reference path="../core/functor.ts" />
/// <reference path="voronoi/.ts" />
/// <reference path="geom.ts" />
/// <reference path="point.ts" />
d3.geom.voronoi = function(points) {
var x = d3_geom_pointX,
y = d3_geom_pointY,
fx = x,
fy = y,
clipExtent = d3_geom_voronoiClipExtent;
// @deprecated; use voronoi(data) instead.
if (points) return voronoi(points);
function voronoi(data) {
var polygons = new Array(data.length),
x0 = clipExtent[0][0],
y0 = clipExtent[0][1],
x1 = clipExtent[1][0],
y1 = clipExtent[1][1];
d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
var edges = cell.edges,
site = cell.site,
polygon = polygons[i] = edges.length ? edges.map(function(e) { var s = e.start(); return [s.x, s.y]; })
: site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [[x0, y1], [x1, y1], [x1, y0], [x0, y0]]
: [];
polygon.point = data[i];
});
return polygons;
}
function sites(data) {
return data.map(function(d, i) {
return {
x: Math.round(fx(d, i) / ε) * ε,
y: Math.round(fy(d, i) / ε) * ε,
i: i
};
});
}
voronoi.links = function(data) {
return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
return edge.l && edge.r;
}).map(function(edge) {
return {
source: data[edge.l.i],
target: data[edge.r.i]
};
});
};
voronoi.triangles = function(data) {
var triangles = [];
d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
var site = cell.site,
edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder),
j = -1,
m = edges.length,
e0,
s0,
e1 = edges[m - 1].edge,
s1 = e1.l === site ? e1.r : e1.l;
while (++j < m) {
e0 = e1;
s0 = s1;
e1 = edges[j].edge;
s1 = e1.l === site ? e1.r : e1.l;
if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
triangles.push([data[i], data[s0.i], data[s1.i]]);
}
}
});
return triangles;
};
voronoi.x = function(_) {
return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
};
voronoi.y = function(_) {
return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
};
voronoi.clipExtent = function(_) {
if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
return voronoi;
};
// @deprecated; use clipExtent instead.
voronoi.size = function(_) {
if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
return voronoi.clipExtent(_ && [[0, 0], _]);
};
return voronoi;
};
var d3_geom_voronoiClipExtent = [[-1e6, -1e6], [1e6, 1e6]];
function d3_geom_voronoiTriangleArea(a, b, c) {
return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
}
|
6acb833801b0b8dd71a66f2e2443847081e56f60 | TypeScript | DrH97/dcs-engineering-test | /test/unit.test.ts | 2.734375 | 3 | import { createConnection, getConnection, getRepository } from "typeorm";
import Lot from "../src/entity/Lot";
import {
calculateLotsQuantitySum,
getFirstLot,
sellLots,
sortLotsByExpiry
} from "../src/common/utils";
import supertest from "supertest";
import App from "../src/app";
const server = new App(3002);
const app = server.app;
beforeAll(async () => {
await createConnection({
type: "sqlite",
database: ":memory:",
dropSchema: true,
entities: [Lot],
synchronize: true,
logging: false
}).then(async () => {
await setUpDb();
});
});
afterAll(() => {
const conn = getConnection();
return conn.close();
});
const setUpDb = async () => {
const timestamp = new Date().valueOf();
const lots = [
{
name: "foo",
quantity: 5,
expiry: new Date(timestamp)
},
{
name: "foo",
quantity: 5,
expiry: new Date(timestamp + 20000)
},
{
name: "foo",
quantity: 5,
expiry: new Date(timestamp + 15000)
}
];
await getConnection()
.createQueryBuilder()
.insert()
.into(Lot)
.values(lots)
.execute();
};
describe("DB Tests", () => {
const lot = new Lot();
it("Add Lot", async () => {
lot.name = "foo";
lot.quantity = 5;
lot.expiry = new Date();
await lot.save();
const response = await Lot.findOne({ id: lot.id });
expect(response).toStrictEqual(lot);
});
it("Update Lot", async () => {
lot.name = "bar";
lot.quantity = 50;
await getConnection()
.createQueryBuilder()
.update(Lot)
.set({ ...lot })
.where("id = :id", { id: lot.id })
.execute();
const response = await Lot.findOne({ id: lot.id });
expect(response).toStrictEqual(lot);
});
it("Delete Lot", async () => {
await getConnection()
.createQueryBuilder()
.delete()
.from(Lot)
.where({ id: lot.id })
.execute();
const response = await Lot.findOne({ id: lot.id });
expect(response).toBeUndefined();
});
});
describe("Controller Tests", () => {
it("get quantity of only valid lots", async () => {
const lots: Lot[] = await Lot.findNonExpired("foo");
const x = [...lots];
const response = calculateLotsQuantitySum(lots);
sortLotsByExpiry(x);
const lot = getFirstLot(x);
expect(response).toStrictEqual({
quantity: 10,
validTill: lot?.expiry.valueOf()
});
});
it("Ensure sell quantity is checked", async () => {
const response = await supertest(app)
.post("/api/v1/foo/sell")
.send({ quantity: 100 })
.set("Accept", "application/json")
.expect("Content-Type", /json/);
expect(response.status).toBe(422);
expect(response.body.errors.body[0].keyword).toBe("max");
});
it("check selling across lots", async () => {
let lots: Lot[] = await getRepository(Lot)
.createQueryBuilder("lot")
.where("name = :name", { name: "foo" })
.andWhere("strftime('%s', expiry) > strftime('%s','now')")
.andWhere("quantity > 0")
.getMany();
sortLotsByExpiry(lots);
await sellLots(lots, 6);
lots = await getRepository(Lot)
.createQueryBuilder("lot")
.where("name = :name", { name: "foo" })
.andWhere("strftime('%s', expiry) > strftime('%s','now')")
.andWhere("quantity > 0")
.getMany();
const x = [...lots];
const response = calculateLotsQuantitySum(lots);
sortLotsByExpiry(x);
const lot = getFirstLot(x);
expect(response).toStrictEqual({
quantity: 4,
validTill: lot?.expiry.valueOf()
});
});
});
|
124fb469085e1c8982b9ac1596be514bf55a0e92 | TypeScript | aldukhn/Tayssir | /libs/api-interfaces/src/lib/Region.ts | 2.515625 | 3 | export interface Region {
id: string;
code: string;
name: string;
nameAr: string;
}
export interface Province {
id: string;
code: string;
name: string;
nameAr: string;
region: Region;
}
export interface Circle {
id: string;
code: string;
name: string;
nameAr: string;
province: Province;
}
export interface Commune {
id: string;
code: string;
name: string;
name_ar: string;
province_id: string;
circle_id: string;
region_id: string
is_municipal: boolean,
is_arrondissment: boolean,
is_centre: boolean
}
export interface Caidat {
id: string;
name: string;
nameAr: string;
communeList: Array<Commune>;
description: string;
descriptionAr: string;
}
|
141e0d69003a1b89270e9850910d1e3ee2e72469 | TypeScript | DuoM2/damage-calc | /calc/src/data/interface.ts | 2.65625 | 3 | export interface As<T> {__brand: T}
export type ID = string & As<'ID'>;
export type GenerationNum = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
export type GenderName = 'M' | 'F' | 'N';
export type StatName = 'hp' | 'atk' | 'def' | 'spa' | 'spd' | 'spe';
export type Stat = StatName | 'spc';
export type StatsTable<T = number> = {[stat in StatName]: T} & {spc?: T};
export type AbilityName = string & As<'AbilityName'>;
export type ItemName = string & As<'ItemName'>;
export type MoveName = string & As<'MoveName'>;
export type SpeciesName = string & As<'SpeciesName'>;
export type StatusName = 'slp' | 'psn' | 'brn' | 'frz' | 'par' | 'tox';
export type GameType = 'Singles' | 'Doubles';
export type Terrain = 'Electric' | 'Grassy' | 'Psychic' | 'Misty';
export type Weather =
| 'Sand' | 'Sun' | 'Rain' | 'Hail' | 'Harsh Sunshine' | 'Heavy Rain' | 'Strong Winds';
export type NatureName =
'Adamant' | 'Bashful' | 'Bold' | 'Brave' | 'Calm' |
'Careful' | 'Docile' | 'Gentle' | 'Hardy' | 'Hasty' |
'Impish' | 'Jolly' | 'Lax' | 'Lonely' | 'Mild' |
'Modest' | 'Naive' | 'Naughty' | 'Quiet' | 'Quirky' |
'Rash' | 'Relaxed' | 'Sassy' | 'Serious' | 'Timid';
export type TypeName =
'Normal' | 'Fighting' | 'Flying' | 'Poison' | 'Ground' | 'Rock' | 'Bug' | 'Ghost' | 'Steel' |
'Fire' | 'Water' | 'Grass' | 'Electric' | 'Psychic' | 'Ice' | 'Dragon' | 'Dark' | 'Fairy' | '???';
export type MoveCategory = 'Physical' | 'Special' | 'Status';
export type MoveRecoil = boolean | number | 'crash' | 'Struggle';
export interface Generations {
get(gen: GenerationNum): Generation;
}
export interface Generation {
readonly num: GenerationNum;
readonly abilities: Abilities;
readonly items: Items;
readonly moves: Moves;
readonly species: Species;
readonly types: Types;
readonly natures: Natures;
}
export type DataKind = 'Ability' | 'Item' | 'Move' | 'Species' | 'Type' | 'Nature';
export interface Data<NameT> {
readonly id: ID;
readonly name: NameT;
readonly kind: DataKind;
}
export interface Abilities {
get(id: ID): Ability | undefined;
[Symbol.iterator](): IterableIterator<Ability>;
}
export interface Ability extends Data<AbilityName> {
readonly kind: 'Ability';
}
export interface Items {
get(id: ID): Item | undefined;
[Symbol.iterator](): IterableIterator<Item>;
}
export interface Item extends Data<ItemName> {
readonly kind: 'Item';
readonly megaEvolves?: SpeciesName;
readonly isBerry?: boolean;
readonly naturalGift?: Readonly<{basePower: number; type: TypeName}>;
}
export interface Moves {
get(id: ID): Move | undefined;
[Symbol.iterator](): IterableIterator<Move>;
}
export interface Move extends Data<MoveName> {
readonly kind: 'Move';
readonly bp: number;
readonly type: TypeName;
readonly category?: MoveCategory;
readonly hasSecondaryEffect?: boolean;
readonly isSpread?: boolean | 'allAdjacent';
readonly makesContact?: boolean;
readonly hasRecoil?: MoveRecoil;
readonly alwaysCrit?: boolean;
readonly givesHealth?: boolean;
readonly percentHealed?: number;
readonly ignoresBurn?: boolean;
readonly isPunch?: boolean;
readonly isBite?: boolean;
readonly isBullet?: boolean;
readonly isSound?: boolean;
readonly isPulse?: boolean;
readonly hasPriority?: boolean;
readonly dropsStats?: number;
readonly ignoresDefenseBoosts?: boolean;
readonly dealsPhysicalDamage?: boolean;
readonly bypassesProtect?: boolean;
readonly isZ?: boolean;
readonly isMax?: boolean;
readonly usesHighestAttackStat?: boolean;
readonly zp?: number;
readonly maxPower?: number;
readonly isMultiHit?: boolean;
readonly isTwoHit?: boolean;
}
export interface Species {
get(id: ID): Specie | undefined;
[Symbol.iterator](): IterableIterator<Specie>;
}
// TODO: rename these fields to be readable
export interface Specie extends Data<SpeciesName> {
readonly kind: 'Species';
readonly t1: TypeName; // type1
readonly t2?: TypeName; // type2
readonly bs: Readonly<{
hp: number;
at: number;
df: number;
sa: number;
sd: number;
sp: number;
sl?: number;
}>; // baseStats
readonly w: number; // weight
readonly canEvolve?: boolean;
readonly gender?: GenderName;
readonly formes?: SpeciesName[];
readonly isAlternateForme?: boolean;
readonly ab?: AbilityName; // ability
}
export interface Types {
get(id: ID): Type | undefined;
[Symbol.iterator](): IterableIterator<Type>;
}
export type TypeEffectiveness = 0 | 0.5 | 1 | 2;
export interface Type extends Data<TypeName> {
readonly kind: 'Type';
readonly category?: MoveCategory;
readonly effectiveness: Readonly<{[type in TypeName]?: TypeEffectiveness}>;
}
export interface Natures {
get(id: ID): Nature | undefined;
[Symbol.iterator](): IterableIterator<Nature>;
}
export interface Nature extends Data<NatureName> {
readonly kind: 'Nature';
readonly plus: StatName;
readonly minus: StatName;
}
|
699c9442a0f9acd04067a4f32d7ed8795d56bba3 | TypeScript | kpokhare/cloud-governance-client | /typescript/src/models/CommonStatus.ts | 2.609375 | 3 | /* tslint:disable */
/* eslint-disable */
/*
* Cloud Governance Api
*
* Contact: support@avepoint.com
*/
/**
*
* @export
* @enum {string}
*/
export enum CommonStatus {
Inactive = 0,
Active = 1
}
export function CommonStatusFromJSON(json: any): CommonStatus {
return CommonStatusFromJSONTyped(json, false);
}
export function CommonStatusFromJSONTyped(json: any, ignoreDiscriminator: boolean): CommonStatus {
return json as CommonStatus;
}
export function CommonStatusToJSON(value?: CommonStatus | null): any {
return value as any;
}
|
da678db30a6e6542fc1e5836b367f2dfa1b87157 | TypeScript | mako34/typescript_tuto | /4_interfaces.ts | 4.15625 | 4 | interface Iperson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
//implementation"?
var customer:Iperson = {
firstName:"mako",
lastName:"tkt",
sayHi:():string => {return "hola q hace"}
}
console.log("customer obj");
console.log(customer.firstName);
console.log(customer.lastName);
console.log(customer.sayHi())
// simple Inheritance
interface Person {
age:number
}
interface Musician extends Person {
instrument:string
}
var drummer = <Musician>{}; //creador?
drummer.age = 27;
drummer.instrument = "congas";
console.log(`age: ${drummer.age}; with instrument: ${drummer.instrument}`);
// multiple inheritance
interface Iparent1 {
v1:number
}
interface Iparent2 {
v2:number
}
interface Child extends Iparent1, Iparent2 {}
var Iobj:Child = { v1:12, v2:23}
console.log(`value 1: ${this.v1} and value2: ${this.v2}`) // why undefined?
|
0cf2816d6e34f1ddc52de0b82e0911fb3a444541 | TypeScript | baleocho/angular-http-head | /src/app/pages/home/home.component.ts | 2.5625 | 3 | import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../services/http.service'
declare var $: any;
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
urlIdEliminar: number;
showAlert: boolean = false;
mensajeAlTerminar: string = "";
mensajeAceptar: string = "";
urlInput: string;
currentId = 4;
urls: any = [
{
id: 1,
url: "http://google.com",
mensaje: "ok",
codigo: "200"
},
{
id: 2,
url: "http://amazon.com.mx",
mensaje: "ok",
codigo: "200"
},
{
id: 3,
url: "http://localhost:3000",
mensaje: "ok",
codigo: "200"
},
]
constructor(private http: HttpService) { }
ngOnInit() {
this.onActualizar();
}
onAgregar(url: string) {
let newUrl = {
id: this.currentId,
url: url,
mensaje: "",
codigo: ""
};
this.urls.push(newUrl);
this.currentId += 1;
this.showAlert = true;
this.mensajeAlTerminar = "Url Agregada";
setTimeout(() => { this.showAlert = false }, 1000);
}
onEliminar(id: number) {
$("#verificar").modal('show');
for (var i = 0; i < this.urls.length; i++) {
if (this.urls[i].id === id) {
this.mensajeAceptar = "Esta seguro de eliminar el URL: " + this.urls[i].id + " " + this.urls[i].url;
this.urlIdEliminar = this.urls[i].id;
}
}
}
onConfirmarEliminar(id: number) {
for (var i = 0; i < this.urls.length; i++) {
if (this.urls[i].id === id) {
this.urls.splice(i, 1);
this.showAlert = true;
this.mensajeAlTerminar = "Url Eliminada";
setTimeout(() => { this.showAlert = false }, 1000);
}
}
}
verificarDisponibilidad(id) {
// Parametros a enviar
let body = {
url: this.urls[id].url
};
setTimeout(() => { // Espera 100 ms para que se cargue correctamente la informacion
this.http.post('/api/verificarDisponibilidad', body).subscribe(res => {
this.urls[id].mensaje = res.statusMessage;
this.urls[id].codigo = res.statusCode;
console.table(res);
}, error => {
console.log(error);
});
}, 100);
}
onActualizar(){
for (var i = 0; i < this.urls.length; i++) {
this.verificarDisponibilidad(i);
}
this.showAlert = true;
this.mensajeAlTerminar = "Urls Actualizadas";
setTimeout(() => { this.showAlert = false }, 1000);
}
}
|
5026af251d310bd7ea79ae3d74db0d705cc365be | TypeScript | garmin954/-vue3-netease-music | /src/utils/rem.ts | 3.015625 | 3 | /**
* 根据视窗计算rem
*/
import { throttle } from 'lodash';
export const remBase = 14;
let htmlFontSize: number;
const calc = (): void => {
const maxFontSize = 18;
const minFontSize = 14;
const html = document.getElementsByTagName('html')[0];
const width = html.clientWidth;
let size = remBase * (width / 1440);
size = Math.min(maxFontSize, size);
size = Math.max(minFontSize, size);
html.style.fontSize = size + 'px';
htmlFontSize = size;
};
((): void => {
calc();
window.addEventListener('resize', throttle(calc, 500));
})();
// 根据基准字号计算
// 用于静态样式
export function toRem(px: number): string {
return `${px / remBase}rem`;
}
// 根据当前的html根字体大小计算
// 用于某些js的动态计算
export function toCurrentRem(px: number) : string {
return `${px / htmlFontSize}rem`;
}
|
ee30e128db8ecc994c27493fc0a94d5d17b39d93 | TypeScript | quatico-solutions/web-component-analyzer | /src/util/get-type-hint-from-type.ts | 3.796875 | 4 | import { SimpleType, toTypeString } from "ts-simple-type";
import { Type, TypeChecker } from "typescript";
/**
* Returns a "type hint" from a type
* The type hint is an easy to read representation of the type and is not made for being parsed.
* @param type
* @param checker
*/
export function getTypeHintFromType(type: string | Type | SimpleType | undefined, checker: TypeChecker): string | undefined {
if (type == null) return undefined;
if (typeof type === "string") return type;
const typeHint = toTypeString(type, checker);
// Replace "anys" and "{}" with more human friendly representations
if (typeHint === "any") return undefined;
if (typeHint === "any[]") return "array";
if (typeHint === "{}") return "object";
return typeHint;
}
|
8aabd1efacaf912326f0e699505d358b371681a5 | TypeScript | a313008430/webGLLearn | /app/core/Utils.ts | 3.3125 | 3 | export default class Utils {
/**
* 创建并编译一个着色器
*
* @param {!WebGLRenderingContext} gl WebGL上下文。
* @param {string} shaderSource GLSL 格式的着色器代码
* @param {number} shaderType 着色器类型, VERTEX_SHADER 或
* FRAGMENT_SHADER。
* @return {!WebGLShader} 着色器。
*/
static compileShader(gl: WebGLRenderingContext, shaderSource: string, shaderType: number) {
// 创建着色器程序
var shader: WebGLShader = gl.createShader(shaderType)!;
// 设置着色器的源码
gl.shaderSource(shader, shaderSource);
// 编译着色器
gl.compileShader(shader);
// 检测编译是否成功
var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!success) {
// 编译过程出错,获取错误信息。
throw "could not compile shader:" + gl.getShaderInfoLog(shader);
}
return shader;
}
/**
* 从 2 个着色器中创建一个程序
*
* @param {!WebGLRenderingContext) gl WebGL上下文。
* @param {!WebGLShader} vertexShader 一个顶点着色器。
* @param {!WebGLShader} fragmentShader 一个片断着色器。
* @return {!WebGLProgram} 程序
*/
static createProgram(gl: WebGLRenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader): WebGLProgram {
// 创建一个程序
var program: WebGLProgram = gl.createProgram()!;
// 附上着色器
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
// 链接到程序
gl.linkProgram(program);
// 检查链接是否成功
var success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!success) {
// 链接过程出现问题
throw ("program filed to link:" + gl.getProgramInfoLog(program));
}
return program;
};
/**
* Resize a canvas to match the size its displayed.
* @param {HTMLCanvasElement} canvas The canvas to resize.
* @param {number} [multiplier] amount to multiply by.
* Pass in window.devicePixelRatio for native pixels.
* @return {boolean} true if the canvas was resized.
* @memberOf module:webgl-utils
*/
static resizeCanvasToDisplaySize(canvas: HTMLCanvasElement, multiplier?: number) {
multiplier = multiplier || 1;
const width = canvas.clientWidth * multiplier | 0;
const height = canvas.clientHeight * multiplier | 0;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
return false;
}
} |
8267374785e8075009711c2cfc1753d0fba15042 | TypeScript | Gaetano1979/introducion-node-ts | /lib/index.ts | 2.75 | 3 | export function hola() {
console.log('Hola a todos desde nuevo module');
}
export function holaDos(nome:string) {
console.log('Hola a te che sei nuovo'+nome);
}
export const holaTs = () => {
console.log('Hola desde paquete npm ts');
}
|
9959b7d5622187271fd58677faaefe65533554ff | TypeScript | junpotatoes/store-6 | /client/src/lib/customStyledComponents/utils/cssStringify.ts | 2.59375 | 3 | import { compile, serialize, stringify } from 'stylis';
/**
* stylis를 사용하여 css를 serialize 합니다.
* compile을 사용하여 SCSS 문법을 해석하고,
* 이를 직렬화하여 반환합니다.
*/
const cssSerializer = (tag: string, content: string) =>
serialize(compile(`.${tag}{${content}}`), stringify);
export default cssSerializer;
|
47712701b574bdb788f3732d2229bccbb76f9024 | TypeScript | dbecaj/boofio-api | /src/modules/services/dtos/service.dto.ts | 2.546875 | 3 | import { Types } from 'mongoose';
import { DLocation } from '../../../shared/dtos/common.dto';
import { IOpeningHours, IService, IBusinessHours } from '../entities/service.entity';
import { SERVICE_TYPE } from '../services.enum';
import { IImage } from '../../common/image/image.entity';
export class DOpeningHours {
monday: IBusinessHours;
tuesday: IBusinessHours;
wednesday: IBusinessHours;
thursday: IBusinessHours;
friday: IBusinessHours;
saturday: IBusinessHours;
sunday: IBusinessHours;
constructor(openingHours: IOpeningHours) {
this.monday = openingHours.monday || { opening: null, closing: null };
this.tuesday = openingHours.tuesday || { opening: null, closing: null };
this.wednesday = openingHours.wednesday || { opening: null, closing: null };
this.thursday = openingHours.thursday || { opening: null, closing: null };
this.friday = openingHours.friday || { opening: null, closing: null };
this.saturday = openingHours.saturday || { opening: null, closing: null };
this.sunday = openingHours.sunday || { opening: null, closing: null };
}
}
export class DPublicService {
_id: Types.ObjectId;
ownerId: Types.ObjectId;
type: SERVICE_TYPE;
name: string;
location: DLocation;
phone: string;
email: string;
openingHours: IOpeningHours;
description: string;
range: number;
createDate: Date;
image?: IImage;
street: string;
post: string;
constructor(service: IService) {
this._id = service._id;
this.ownerId = service.ownerId;
this.type = service.type;
this.name = service.name;
this.location = new DLocation(service.location);
this.phone = service.phone;
this.email = service.email;
this.openingHours = service.openingHours;
this.description = service.description;
this.range = service.range;
this.createDate = service.createDate;
this.image = service.image;
this.street = service.street;
this.post = service.post;
}
}
export class DPrivateService extends DPublicService {
purchases: Types.ObjectId[];
constructor(service: IService) {
super(service);
this.purchases = service.purchases;
}
}
export class DNearService extends DPublicService {
distance: number;
constructor(service: IService) {
super(service);
this.distance = (service as any).distance;
}
}
|
a4ed42b9cfed0be46163b55ca42880b24c936320 | TypeScript | gitter-badger/destiny | /src/index/generateTrees/shared/findSharedParent.ts | 3.09375 | 3 | import path from "path";
/** Find the common parent directory between all paths. */
export const findSharedParent = (paths: string[]) => {
if (paths.length === 1) return path.dirname(paths[0]);
const parentPaths: string[] = [];
const parts: string[][] = paths.map(x => x.split("/"));
const firstParts = parts[0];
firstParts.forEach((part, idx) => {
const allPartsMatch = parts.every(p => p[idx] === part);
if (allPartsMatch) {
parentPaths.push(part);
}
});
return parentPaths.join("/");
};
|
9dc71bf977894b4286a4ffb478c6ac99d6735789 | TypeScript | sethfowler/chromium-trace-analyzer | /src/writer.ts | 3.265625 | 3 | import stripAnsiStream from 'strip-ansi-stream';
import process from 'process';
import util from 'util';
export class IndentingWriter {
private _stream: NodeJS.WriteStream;
private _indent: number = 0;
private _specialChar: string | undefined = undefined;
private _specialCol: number = 0;
constructor(private _tabWidth: number = 2) {
// Make sure we're writing to a terminal. If not, strip out ANSI codes so
// that redirecting our output to a file doesn't leave you with a bunch of
// escape sequence gobbledygook.
if (process.stdout.isTTY) {
this._stream = process.stdout;
} else {
this._stream = stripAnsiStream();
this._stream.pipe(process.stdout);
}
}
indent(by: number = 1): void {
this._indent += by * this._tabWidth;
}
unindent(by: number = 1): void {
this._indent -= by * this._tabWidth;
this._indent = Math.max(this._indent, 0);
}
addSpecial(char: string, offset: number = 0): void {
this._specialChar = char;
this._specialCol = this._indent + offset;
}
removeSpecial(): void {
this._specialChar = undefined;
}
withIndent<R>(action: () => R): R {
try {
this.indent();
return action();
} finally {
this.unindent();
}
}
log(message: any = ''): void {
let prefix = ' '.repeat(this._indent);
if (this._specialChar !== undefined) {
prefix = prefix.substring(0, this._specialCol) +
this._specialChar +
prefix.substring(this._specialCol + this._specialChar.length);
prefix = prefix.substring(0, this._indent + 1);
}
this._stream.write(util.format(`${prefix}${message}`) + '\n');
}
}
|
9f37197da7859458680de7b70cf0a08c53f843e0 | TypeScript | color-coding/ibas-typescript | /openui5/extensions/components/Select.d.ts | 2.640625 | 3 | /**
* @license
* Copyright Color-Coding Studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
declare namespace sap {
namespace extension {
namespace m {
/**
* 选择框
*/
class Select extends sap.m.Select {
/**
* 构造
* @param {string} sId 唯一标记,不要赋值
* @param {any} mSettings 绑定值属性:bindingValue
*/
constructor(sId?: string, mSettings?: any);
/**
* 设置属性值
* @param sPropertyName 属性名称
* @param oValue 值
* @param bSuppressInvalidate 立即
*/
protected setProperty(sPropertyName: string, oValue: any, bSuppressInvalidate?: boolean): this;
/**
* 绑定属性
* @param sName 属性名称
* @param oBindingInfo 绑定信息
*/
bindProperty(sName: string, oBindingInfo: any): this;
/**
* 获取绑定值
*/
getBindingValue(): string;
/**
* 设置绑定值
* @param value 值
*/
setBindingValue(value: string): this;
/**
* 是否没有值
* @param value 值
*/
isEmptyValue(value: any): boolean;
/**
* 获取默认项目
*/
protected getDefaultSelectedItem(): sap.ui.core.Item;
/**
* 加载可选值
*/
loadItems(): this;
}
/** 选择框项目 */
class SelectItem extends sap.ui.core.ListItem {
/** 是否为默认值 */
getDefault(): boolean;
/** 设置为默认值 */
setDefault(value: boolean): SelectItem;
}
/**
* 枚举数据-选择框
*/
class EnumSelect extends Select {
/**
* 获取枚举类型
*/
getEnumType(): any;
/**
* 设置枚举类型
* @param value 枚举类型
*/
setEnumType(value: any): this;
}
/**
* 业务仓库数据-选择框
*/
class RepositorySelect extends Select {
/**
* 获取业务仓库实例
*/
getRepository(): ibas.BORepositoryApplication;
/**
* 设置业务仓库
* @param value 业务仓库实例;业务仓库名称
*/
setRepository(value: ibas.BORepositoryApplication | string): this;
/**
* 获取数据信息
*/
getDataInfo(): repository.IDataInfo;
/**
* 设置数据信息
* @param value 数据信息
*/
setDataInfo(value: repository.IDataInfo | any): this;
/**
* 获取查询条件
*/
getCriteria(): ibas.ICriteria;
/**
* 设置数据信息
* @param value 数据信息
*/
setCriteria(value: ibas.ICriteria | ibas.ICondition[]): this;
/**
* 获取空白数据
*/
getBlankData(): { key: string, text: string };
/**
* 设置空白数据(未设置使用默认,无效值则为不使用)
* @param value 空白数据;undefined表示不使用
*/
setBlankData(value: { key: string, text: string }): this;
}
/**
* 对象属性可选值-选择框
*/
class PropertySelect extends Select {
/**
* 获取数据信息
*/
getDataInfo(): { code: string, name?: string } | string | Function;
/**
* 设置数据信息
* @param value 值
*/
setDataInfo(value: { code: string, name?: string } | string | Function): this;
/**
* 获取属性名称
*/
getPropertyName(): string;
/**
* 设置属性名称
* @param value 属性名称
*/
setPropertyName(value: string): this;
}
/**
* 对象服务系列-选择框
*/
class SeriesSelect extends Select {
/**
* 获取对象编码
*/
getObjectCode(): string;
/**
* 设置对象编码
* @param value 对象编码
*/
setObjectCode(value: string): this;
}
/**
* 重复字符计数-选择框
*/
class RepeatCharSelect extends Select {
/**
* 获取最大数
*/
getMaxCount(): number;
/**
* 设置最大数
* @param value 最大数
*/
setMaxCount(value: number): this;
/**
* 获取重复内容
*/
getRepeatText(): string;
/**
* 设置重复内容
* @param value 重复内容
*/
setRepeatText(value: string): this;
}
/**
* 业务对象属性-选择框
*/
class BusinessObjectPropertiesSelect extends Select {
/**
* 获取数据信息
*/
getDataInfo(): { code: string, name?: string } | string | Function;
/**
* 设置数据信息
* @param value 值
*/
setDataInfo(value: { code: string, name?: string } | string | Function): this;
}
/**
* 货币-选择框
*/
class CurrencySelect extends Select { }
}
}
}
|
3387073777dfe4e064ec70296162b4cbc1c18eaf | TypeScript | forkkit/fly.rs | /v8env/src/fly/data.ts | 3.125 | 3 | /**
* Persistent, global key/value data store. Open collections, write data with `put`. Then retrieve data with `get`.
*
* Keys and values are stored in range chunks. Chunks migrate to the region they're most frequently accessed from.
* @module fly/data
*/
import * as fbs from "../msg_generated";
import * as flatbuffers from "../flatbuffers";
import { sendAsync } from "../bridge";
/**
* A collection of keys and values.
*/
export class Collection {
name: string
/**
* Opens a collection
* @param name name of the collection to open
*/
constructor(name: string) {
this.name = name
}
/**
* Stores data in the collection associated key
* @param key key for data
* @param obj value to store
*/
async put(key: string, obj: any): Promise<boolean> {
if (typeof obj === "number" || obj === undefined || obj === null) {
throw new TypeError("value must be a string, object, or array");
}
const fbb = flatbuffers.createBuilder();
const fbbColl = fbb.createString(this.name);
const fbbKey = fbb.createString(key);
const fbbObj = fbb.createString(JSON.stringify(obj));
fbs.DataPut.startDataPut(fbb);
fbs.DataPut.addCollection(fbb, fbbColl);
fbs.DataPut.addKey(fbb, fbbKey);
fbs.DataPut.addJson(fbb, fbbObj);
await sendAsync(fbb, fbs.Any.DataPut, fbs.DataPut.endDataPut(fbb));
return true;
}
/**
* Retrieves data from the collection store
* @param key key to retrieve
*/
get(key: string): Promise<any> {
const fbb = flatbuffers.createBuilder();
const fbbColl = fbb.createString(this.name);
const fbbKey = fbb.createString(key);
fbs.DataGet.startDataGet(fbb);
fbs.DataGet.addCollection(fbb, fbbColl);
fbs.DataGet.addKey(fbb, fbbKey);
return sendAsync(fbb, fbs.Any.DataGet, fbs.DataGet.endDataGet(fbb)).then(baseRes => {
if (baseRes.msgType() == fbs.Any.NONE)
return null
const msg = new fbs.DataGetReady();
baseRes.msg(msg);
return JSON.parse(msg.json())
})
}
/**
* Deletes data from the collection store.
* @param key key to delete
*/
del(key: string): Promise<boolean> {
const fbb = flatbuffers.createBuilder();
const fbbColl = fbb.createString(this.name);
const fbbKey = fbb.createString(key);
fbs.DataDel.startDataDel(fbb);
fbs.DataDel.addCollection(fbb, fbbColl);
fbs.DataDel.addKey(fbb, fbbKey);
return sendAsync(fbb, fbs.Any.DataDel, fbs.DataDel.endDataDel(fbb)).then(_baseRes => {
return true
})
}
increment(key: string, field: string, amount?: number): Promise<boolean> {
const fbb = flatbuffers.createBuilder();
const fbbColl = fbb.createString(this.name);
const fbbKey = fbb.createString(key);
const fbbField = fbb.createString(field);
fbs.DataIncr.startDataIncr(fbb);
fbs.DataIncr.addCollection(fbb, fbbColl);
fbs.DataIncr.addKey(fbb, fbbKey);
fbs.DataIncr.addField(fbb, fbbField);
fbs.DataIncr.addAmount(fbb, amount || 1);
return sendAsync(fbb, fbs.Any.DataIncr, fbs.DataIncr.endDataIncr(fbb)).then(_baseRes => {
return true
})
}
}
export function collection(name: string) {
return new Collection(name)
}
export function dropCollection(name: string): Promise<boolean> {
const fbb = flatbuffers.createBuilder();
const fbbColl = fbb.createString(name);
fbs.DataDropCollection.startDataDropCollection(fbb);
fbs.DataDropCollection.addCollection(fbb, fbbColl);
return sendAsync(fbb, fbs.Any.DataDropCollection, fbs.DataDropCollection.endDataDropCollection(fbb)).then(_baseRes => {
return true
})
}
function assertValueType(val: any) {
// if (val === )
}
|
2d369a879a7be55c13ee170c934a5fd602da241a | TypeScript | deepkolos/hap-types | /system.bluetooth.d.ts | 2.765625 | 3 | /// <reference path="./types.d.ts"/>
/**
* 蓝牙 bluetooth
* @后台运行限制 禁止使用。后台运行详细用法参见后台运行 脚本。
* @see https://doc.quickapp.cn/features/system/bluetooth.html
*/
declare module '@system.bluetooth' {
interface Bluetooth {
/**
* 初始化蓝牙模块
* @example
* ```js
* bluetooth.openAdapter({
* success: function() {
* console.log('success')
* },
* fail: function(data, code) {
* console.log(`handling fail, code = ${code}`)
* },
* complete: function() {
* console.log('complete')
* }
* })
* ```
*/
openAdapter(OBJECT: OpenAdapterOBJECT): any;
/**
* 关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源。建议在使用蓝牙流程后,与 bluetooth.openAdapter 成对调用。
* @example
* ```js
* bluetooth.closeAdapter({
* success: function() {
* console.log('success')
* },
* fail: function(data, code) {
* console.log(`handling fail, code = ${code}`)
* },
* complete: function() {
* console.log('complete')
* }
* })
* ```
*/
closeAdapter(OBJECT: CloseAdapterOBJECT): any;
/**
* 获取本机蓝牙适配器状态。
* @example
* ```js
* bluetooth.onadapterstatechange = function(data) {
* console.log('adapterState changed, now is', data.available)
* }
* ```
*/
getAdapterState(OBJECT: GetAdapterStateOBJECT): any;
/**
* 开始搜寻附近的蓝牙外围设备。此操作比较耗费系统资源,请在搜索并连接到设备后调用 bluetooth.stopDevicesDiscovery 方法停止搜索。
* @example
* ```js
* bluetooth.startDevicesDiscovery({
* services: ['FEE7'],
* success: function() {
* console.log('success')
* }
* })
* ```
*/
startDevicesDiscovery(OBJECT: StartDevicesDiscoveryOBJECT): any;
/**
* 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
* @example
* ```js
* bluetooth.stopDevicesDiscovery({
* success: function() {
* console.log('success')
* },
* fail: function(data, code) {
* console.log(`handling fail, code = ${code}`)
* },
* complete: function() {
* console.log('complete')
* }
* })
* ```
*/
stopDevicesDiscovery(OBJECT: StopDevicesDiscoveryOBJECT): any;
/**
* 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
* @example
* ```js
* function ab2hex(buffer) {
* var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
* return ('00' + bit.toString(16)).slice(-2)
* })
* return hexArr.join('')
* }
* bluetooth.ondevicefound = function(data) {
* console.log('new device list has founded')
* data.devices.forEach(device => {
* console.log(`handling find new devive:${JSON.stringify(device)}`)
* console.log(`handling advertisData = ${ab2hex(device.advertisData)}`)
*
* for (let key in device.serviceData) {
* console.log(
* `handling serviceData: uuid = ${key}, serviceData = ${ab2hex(
* device.serviceData[key]
* )}`
* )
* }
* })
* }
* ```
*/
getDevices(OBJECT: GetDevicesOBJECT): any;
/**
* 根据 uuid 获取处于已连接状态的设备。
* @example
* ```js
* bluetooth.getConnectedDevices({
* success: function(data) {
* console.log(data)
* if (data.devices[0]) {
* console.log(data.devices[0].name)
* }
* },
* fail: function(data, code) {
* console.log(`handling fail, code = ${code}`)
* },
* complete: function() {
* console.log('complete')
* }
* })
* ```
*/
getConnectedDevices(OBJECT: GetConnectedDevicesOBJECT): any;
/**
* 连接低功耗蓝牙设备。若快应用有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。
* @example
* ```js
* bluetooth.createBLEConnection({
* deviceId: deviceId,
* success: function() {
* console.log('success')
* },
* fail: function(data, code) {
* console.log(`handling fail, code = ${code}`)
* },
* complete: function() {
* console.log('complete')
* }
* })
* ```
*/
createBLEConnection(OBJECT: CreateBLEConnectionOBJECT): any;
/**
* 断开与低功耗蓝牙设备的连接。
* @example
* ```js
* bluetooth.closeBLEConnection({
* deviceId: deviceId,
* success: function() {
* console.log('success')
* },
* fail: function(data, code) {
* console.log(`handling fail, code = ${code}`)
* },
* complete: function() {
* console.log('complete')
* }
* })
* ```
*/
closeBLEConnection(OBJECT: CloseBLEConnectionOBJECT): any;
/**
* 获取蓝牙设备所有服务(service)。
* @example
* ```js
* bluetooth.getBLEDeviceServices({
* deviceId: deviceId,
* success: function(data) {
* data.services.forEach(service => {
* console.log(
* `handling device services: uuid = ${service.uuid}, isPrimary = ${
* service.isPrimary
* }`
* )
* })
* },
* fail: function(data, code) {
* console.log(`handling fail, code = ${code}`)
* },
* complete: function() {
* console.log('complete')
* }
* })
* ```
*/
getBLEDeviceServices(OBJECT: GetBLEDeviceServicesOBJECT): any;
/**
* 获取蓝牙设备某个服务中所有特征值(characteristic)。
* @example
* ```js
* bluetooth.getBLEDeviceCharacteristics({
* deviceId: deviceId,
* serviceId: serviceId,
* success: function(data) {
* data.characteristics.forEach(characteristic => {
* console.log(
* `handling device characteristic : uuid = ${
* characteristic.uuid
* }, can read = ${characteristic.properties.read}`
* )
* })
* },
* fail: function(data, code) {
* console.log(`handling fail, code = ${code}`)
* },
* complete: function() {
* console.log('complete')
* }
* })
* ```
*/
getBLEDeviceCharacteristics(OBJECT: GetBLEDeviceCharacteristicsOBJECT): any;
/**
* 读取低功耗蓝牙设备的特征值的二进制数据值。注意:必须设备的特征值支持 read 才可以成功调用。
* @example
* ```js
* bluetooth.readBLECharacteristicValue({
* // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
* deviceId: deviceId,
* // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
* serviceId: serviceId,
* // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
* characteristicId: characteristicId,
* success: function() {
* // 执行操作成功,读取的值会在onblecharacteristicvaluechange 接口中上报
* console.log('success')
* }
* })
* ```
*/
readBLECharacteristicValue(OBJECT: ReadBLECharacteristicValueOBJECT): any;
/**
* 向低功耗蓝牙设备特征值中写入二进制数据。注意:必须设备的特征值支持 write 才可以成功调用。
* @example
* ```js
* bluetooth.writeBLECharacteristicValue({
* // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound接口中获取
* deviceId: deviceId,
* // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
* serviceId: serviceId,
* // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
* characteristicId: characteristicId,
* // 这里的value是ArrayBuffer类型
* value: buffer,
* success: function() {
* console.log('success')
* },
* fail: function(data, code) {
* console.log(`handling fail, code = ${code}`)
* },
* complete: function() {
* console.log('complete')
* }
* })
* ```
*/
writeBLECharacteristicValue(OBJECT: WriteBLECharacteristicValueOBJECT): any;
/**
* 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。注意:必须设备的特征值支持 notify 或者 indicate 才可以成功调用。另外,必须先启用 notifyBLECharacteristicValueChange 才能监听到设备 characteristicValueChange 事件
* @example
* ```js
* bluetooth.onbleconnectionstatechange = function(data) {
* console.log(
* `handling device state change: deviceId = ${data.deviceId}, connected = ${
* data.connected
* }`
* )
* }
* ```
*/
notifyBLECharacteristicValueChange(
OBJECT: NotifyBLECharacteristicValueChangeOBJECT
): any;
/**
* 监听蓝牙适配器状态变化事件
*/
onadapterstatechange?: (data: OnadapterstatechangeData) => void;
/**
* 监听寻找到新设备的事件
*/
ondevicefound?: (data: OndevicefoundData) => void;
/**
* 监听低功耗蓝牙设备的特征值变化。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
*/
onblecharacteristicvaluechange?: (
data: OnblecharacteristicvaluechangeData
) => void;
}
/**
*
* @param deviceId 蓝牙设备 id[可选]
* @param serviceId 蓝牙特征值对应服务的 uuid[可选]
* @param characteristicId 蓝牙特征值的 uuid[可选]
* @param value 特征值最新的值[可选]
*/
interface OnblecharacteristicvaluechangeData {
deviceId?: String;
serviceId?: String;
characteristicId?: String;
value?: Arraybuffer;
}
/**
*
* @param devices 新搜索到的设备列表,devices 返回值见 getDevices[可选]
*/
interface OndevicefoundData {
devices?: Object[];
}
/**
*
* @param available 蓝牙适配器是否可用[可选]
* @param discovering 蓝牙适配器是否处于搜索状态[可选]
*/
interface OnadapterstatechangeData {
available?: Boolean;
discovering?: Boolean;
}
/**
*
* @param deviceId 蓝牙设备 id
* @param serviceId 蓝牙特征值对应服务的 uuid
* @param characteristicId 蓝牙特征值的 uuid
* @param state 是否启用 notify
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface NotifyBLECharacteristicValueChangeOBJECT {
deviceId: String;
serviceId: String;
characteristicId: String;
state: Boolean;
success?: Function;
fail?: Function;
complete?: Function;
}
/**
*
* @param deviceId 蓝牙设备 id
* @param serviceId 蓝牙特征值对应服务的 uuid
* @param characteristicId 蓝牙特征值的 uuid
* @param value 蓝牙设备特征值对应的二进制值
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface WriteBLECharacteristicValueOBJECT {
deviceId: String;
serviceId: String;
characteristicId: String;
value: Arraybuffer;
success?: Function;
fail?: Function;
complete?: Function;
}
/**
*
* @param deviceId 蓝牙设备 id
* @param serviceId 蓝牙特征值对应服务的 uuid
* @param characteristicId 蓝牙特征值的 uuid
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface ReadBLECharacteristicValueOBJECT {
deviceId: String;
serviceId: String;
characteristicId: String;
success?: Function;
fail?: Function;
complete?: Function;
}
/**
*
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
* @param deviceId 蓝牙设备 id
* @param serviceId 蓝牙服务 uuid,需要使用 getBLEDeviceServices 获取
*/
interface GetBLEDeviceCharacteristicsOBJECT {
success?: GetBLEDeviceCharacteristicsOBJECTSuccessCB;
fail?: Function;
complete?: Function;
deviceId: String;
serviceId: String;
}
/**
* 成功回调。
*/
type GetBLEDeviceCharacteristicsOBJECTSuccessCB = (
successArg: GetBLEDeviceCharacteristicsSuccessSuccessArg
) => any;
/**
* 成功回调。
* @param characteristics 设备服务列表[可选]
*/
interface GetBLEDeviceCharacteristicsSuccessSuccessArg {
characteristics?: Object[];
}
/**
*
* @param deviceId 蓝牙设备 id
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface GetBLEDeviceServicesOBJECT {
deviceId: String;
success?: GetBLEDeviceServicesOBJECTSuccessCB;
fail?: Function;
complete?: Function;
}
/**
* 成功回调。
*/
type GetBLEDeviceServicesOBJECTSuccessCB = (
successArg: GetBLEDeviceServicesSuccessSuccessArg
) => any;
/**
* 成功回调。
* @param services 设备服务列表[可选]
*/
interface GetBLEDeviceServicesSuccessSuccessArg {
services?: Object[];
}
/**
*
* @param deviceId 用于区分设备的 id
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface CloseBLEConnectionOBJECT {
deviceId: String;
success?: Function;
fail?: Function;
complete?: Function;
}
/**
*
* @param deviceId 用于区分设备的 id
* @param timeout 超时时间,单位 ms,不填表示不会超时[可选]
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface CreateBLEConnectionOBJECT {
deviceId: String;
timeout?: Number;
success?: Function;
fail?: Function;
complete?: Function;
}
/**
*
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
* @param services 蓝牙设备主 service 的 uuid 列表
*/
interface GetConnectedDevicesOBJECT {
success?: GetConnectedDevicesOBJECTSuccessCB;
fail?: Function;
complete?: Function;
services: String[];
}
/**
* 成功回调。
*/
type GetConnectedDevicesOBJECTSuccessCB = (
successArg: GetConnectedDevicesSuccessSuccessArg
) => any;
/**
* 成功回调。
* @param devices uuid 对应的的已连接设备列表[可选]
*/
interface GetConnectedDevicesSuccessSuccessArg {
devices?: Object[];
}
/**
*
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface GetDevicesOBJECT {
success?: GetDevicesOBJECTSuccessCB;
fail?: Function;
complete?: Function;
}
/**
* 成功回调。
*/
type GetDevicesOBJECTSuccessCB = (
successArg: GetDevicesSuccessSuccessArg
) => any;
/**
* 成功回调。
* @param devices 蓝牙模块生效期间已发现的蓝牙设备[可选]
*/
interface GetDevicesSuccessSuccessArg {
devices?: Object[];
}
/**
*
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface StopDevicesDiscoveryOBJECT {
success?: Function;
fail?: Function;
complete?: Function;
}
/**
*
* @param services 要搜索的主 service 的 uuid 列表。某些蓝牙设备会广播自己的主 service 的 uuid。如果设置此参数,则只搜索广播包有对应 uuid 的主服务的蓝牙设备。建议主要通过该参数过滤掉周边不需要处理的其他蓝牙设备。[可选]
* @param allowDuplicatesKey 默认值为 false。是否允许重复上报同一设备。如果允许重复上报,则 bluetooth.ondevicefound 方法会多次上报同一设备,但是 RSSI 值会有不同。[可选]
* @param interval 单位毫秒,默认值为 0。上报设备的间隔。0 表示找到新设备立即上报,其他数值根据传入的间隔上报。[可选]
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface StartDevicesDiscoveryOBJECT {
services?: String[];
allowDuplicatesKey?: Boolean;
interval?: Number;
success?: Function;
fail?: Function;
complete?: Function;
}
/**
*
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调[可选]
*/
interface GetAdapterStateOBJECT {
success?: GetAdapterStateOBJECTSuccessCB;
fail?: Function;
complete?: Function;
}
/**
* 成功回调。
*/
type GetAdapterStateOBJECTSuccessCB = (
successArg: GetAdapterStateSuccessSuccessArg
) => any;
/**
* 成功回调。
* @param available 蓝牙适配器是否可用[可选]
* @param discovering 是否正在搜索设备[可选]
*/
interface GetAdapterStateSuccessSuccessArg {
available?: Boolean;
discovering?: Boolean;
}
/**
*
* @param operateAdapter 是否关闭系统蓝牙开关。设置为 true,调用时会关闭系统蓝牙开关。默认值 false。[可选]
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface CloseAdapterOBJECT {
operateAdapter?: Boolean;
success?: Function;
fail?: Function;
complete?: Function;
}
/**
*
* @param operateAdapter 是否打开系统蓝牙开关。设置为 true,在系统蓝牙开关关闭的情况下会弹框提示是否打开。默认值 false。[可选]
* @param success 成功回调。[可选]
* @param fail 失败回调。[可选]
* @param complete 执行结束后的回调。[可选]
*/
interface OpenAdapterOBJECT {
operateAdapter?: Boolean;
success?: Function;
fail?: Function;
complete?: Function;
}
/**
* 蓝牙 bluetooth
* @后台运行限制 禁止使用。后台运行详细用法参见后台运行 脚本。
* @see https://doc.quickapp.cn/features/system/bluetooth.html
*/
const bluetooth: Bluetooth;
export default bluetooth;
}
|
bd55da37c271f059b932bbc5a068166a4a92b365 | TypeScript | 2006NodeDev/Insta-Bytes | /project1-backend/src/routers/reimbursement-router.ts | 2.515625 | 3 | import express, { Request, Response, NextFunction } from "express"
import { reimbursementStatusRouter } from "./reimbursement-status-router"
import { reimbursementUsersRouter } from "./reimbursement-user-router"
import { NewReimbursementInputError } from "../errors/NewReimbursementInputError"
import { Reimbursement } from "../models/Reimbursement"
import { saveNewReimbursement, patchReimbursement, getAllReimbursements } from "../daos/SQL/reimbursements-dao"
import { ReimbursementIdInputError } from "../errors/ReimbursementIdInputError"
import { authorizationMiddleware } from "../middleware/authorization-middleware"
import { authenticationMiddleware } from "../middleware/authentication-middleware"
export let reimbursementRouter = express.Router()
reimbursementRouter.use(authenticationMiddleware);
reimbursementRouter.use('/status', reimbursementStatusRouter)
reimbursementRouter.use('/author/userId', reimbursementUsersRouter)
reimbursementRouter.get('/', authorizationMiddleware(['admin','finance-manager']), async (req:Request, res:Response, next:NextFunction) => {
try{
let allReimbursements = await getAllReimbursements()
res.json(allReimbursements)
}
catch(e){
next(e)
}
})
reimbursementRouter.post('/', authorizationMiddleware(['admin','finance-manager','user']), async (req:Request, res:Response, next:NextFunction) => {
let {author,
amount,
dateSubmitted,
dateResolved,
description,
resolver,
status,
type} = req.body;
if(!author || !amount || !dateSubmitted || !dateResolved || !description || !resolver || !status || !type){
next(new NewReimbursementInputError)
}
else{
console.log("in the else")
let newReimbursement: Reimbursement = {
reimbursementId: 0,
author,
amount,
dateSubmitted,
dateResolved,
description,
resolver,
status,
type}
try{
let savedReimbursement = await saveNewReimbursement(newReimbursement)
res.status(201).send("Created")
res.json(savedReimbursement)
} catch (e){
next(e)
}
}
})
reimbursementRouter.patch('/', authorizationMiddleware(['admin','finance-manager']), async (req:Request, res:Response, next:NextFunction) => {
let id = req.body.reimbursementId;
if(isNaN(+id)){
next(new ReimbursementIdInputError);
}
else{
let reimbursement: Reimbursement = {
reimbursementId: req.body.reimbursementId,
author: req.body.author,
amount: req.body.amount,
dateSubmitted: req.body.dateSubmitted,
dateResolved: req.body.dateResolved,
description: req.body.description,
resolver: req.body.resolver,
status: req.body.status,
type: req.body.type
}
console.log("in the router, just set the reimbursement")
console.log(reimbursement)
try{
let updatedReimbursement = await patchReimbursement(reimbursement)
res.json(updatedReimbursement)
} catch (e){
next(e)
}
}
})
|
fcb6b7b3302b282051dcb7af07ae593adb30b6b2 | TypeScript | vadkuze/weather-app | /src/app/common/components/weather/weather.component.ts | 2.546875 | 3 | import { Component, OnInit, Input, Output, EventEmitter, OnChanges } from '@angular/core';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.scss']
})
export class WeatherComponent implements OnInit, OnChanges {
@Input() data;
@Input() action = 'new';
@Output() onAdd: EventEmitter<number> = new EventEmitter();
@Output() onDelete: EventEmitter<number> = new EventEmitter();
iconCls: string;
constructor() { }
ngOnInit() {
}
ngOnChanges() {
switch(this.action){
case 'favorite' :{
this.iconCls = this.data ? 'icofont-ui-rate-remove' : '';
}break;
default: {
this.iconCls = this.data && this.data.favorite ? 'icofont-ui-rating' : 'icofont-ui-rate-add';
}
}
}
formatTemp(type: string, temp: number){
if(!type) return;
return type.toLowerCase() === 'c' ?
Math.round(temp - 273.15) :
Math.round((temp - 273.15) * 9/5 + 32);
}
formatSpeed(speed){
return Math.round(speed * 3.6);
}
addCity(id){
if(!id) return;
if(this.iconCls == 'icofont-ui-rate-add'){
this.onAdd.emit(id);
this.iconCls = 'icofont-ui-rating';
}else if(this.iconCls == 'icofont-ui-rate-remove'){
this.onDelete.emit(id);
this.iconCls = 'icofont-ui-rate-blank';
}
}
}
|
82e80f7eb7ae349df44e8dd689329bf4c8a6158b | TypeScript | AgentOneCoLtd/gen_mysql_entities_cli | /src/create_ejs_data/index.ts | 2.71875 | 3 | import { isNil } from '@ag1/nil';
import { returnSwitch } from '@ag1/return_switch';
import * as camelcase from 'camelcase';
import { of, Observable } from 'rxjs';
import { IGetAllColumnsResult } from '../get_all_columns';
import { getTsType } from '../get_ts_type';
import { isOptional } from '../is_optional';
export function getMaxLength(dataType: string, characterMaximumLength: number | null): number | null {
if (dataType === 'time') {
return 8;
}
return characterMaximumLength;
}
export interface INormalizeRawColumnResult {
columnName: string;
tsType: string;
maxLength: number | null;
columnType: string;
isOptional: boolean;
isNullable: boolean;
}
export function normalizeRawColumn(r: IGetAllColumnsResult): INormalizeRawColumnResult {
// in MySQL 5.6 it return as column_type
// in MySQL 8.0 it return as COLUMN_TYPE
const columnType = returnSwitch<string | undefined>(isNil(r.column_type))([
[false, r.column_type],
[true, r.COLUMN_TYPE],
]);
if (isNil(columnType)) {
throw new Error(`neither column_type nor COLUMN_TYPE have value: ${r}`);
}
return {
columnName: r.COLUMN_NAME,
tsType: getTsType(r.DATA_TYPE, columnType, r.IS_NULLABLE),
maxLength: getMaxLength(r.DATA_TYPE, r.CHARACTER_MAXIMUM_LENGTH),
columnType,
isOptional: isOptional({
isNullable: r.IS_NULLABLE,
columnDefault: r.COLUMN_DEFAULT,
isIdentity: r.IsIdentity,
}),
isNullable: r.IS_NULLABLE === 'YES',
};
}
export interface ICreateEjsDataResult {
tableName: string;
PascalTableName: string;
columns: INormalizeRawColumnResult[];
}
export function createEjsData(rawColumns: IGetAllColumnsResult[]): Observable<ICreateEjsDataResult> {
const tableName = rawColumns[0].TABLE_NAME;
const columns = rawColumns.map(normalizeRawColumn);
return of({
tableName,
PascalTableName: camelcase(tableName, { pascalCase: true }),
columns,
});
}
|
07191fc00f55efa6dcc8cb73c9262f25fd960d5c | TypeScript | yubaoquan/minigrep | /leetcode/ts/easy/search.ts | 3.796875 | 4 | /**
* 在排序数组中查找数字 I
* https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
* https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/solution/mian-shi-ti-53-i-zai-pai-xu-shu-zu-zhong-cha-zha-5/
*/
function search(nums: number[], target: number): number {
let i = 0;
let j = nums.length - 1;
while (i <= j) {
const m = Math.floor((i + j) / 2);
if (nums[m] <= target) i = m + 1;
else j = m - 1;
}
const right = i;
if (j >= 0 && nums[j] !== target) return 0;
i = 0;
while (i <= j) {
const m = Math.floor((i + j) / 2);
if (nums[m] < target) i = m + 1;
else j = m - 1;
}
const left = j;
return right - left - 1;
}
console.info(search([1, 4], 4));
console.info(search([2, 2], 2));
console.info(search([1], 1));
console.info(search([5, 7, 7, 8, 8, 10], 8));
console.info(search([5, 7, 7, 8, 8, 10], 6));
|
b8c652276dbccf554a2f3205979e6466a42fb1df | TypeScript | thirschbuechler/git-assistant | /src/handlers/git/branch_changed/BranchWarn.handler.ts | 2.765625 | 3 | 'use strict'
import Git from '../../../models/Git'
import InformationMessage from '../../../UI/InformationMessage'
import InputBox from '../../../UI/InputBox'
import MessageOption from '../../../UI/MessageOption'
import QuickPick from '../../../UI/QuickPick'
import QuickPickOption from '../../../UI/QuickPickOption'
import GitRepository from '../../../application/GitRepository'
import ChangeHandler from '../../ChangeHandler'
import Event from '../../../models/Event'
import EventHandler from '../../EventHandler'
import Config, { ConfigOptions } from '../../../application/Config'
/**
* this Handler is responsible to check if the user works on a wrong Branch
*/
export default class BranchWarn extends ChangeHandler {
static registerEventHandler(): void {
if (Config.isEnabled('branchWarn')) {
EventHandler.registerHandler(Event.GIT_BRANCH_CHANGED, this)
}
}
static async handle(repositoryPath: string): Promise<void> {
const gitModel = await GitRepository.getGitModel(repositoryPath)
const currentBranch = gitModel.getBranch()
if (gitModel.isHeadDetached()) {
return
}
if (Config.getValue('branchWarn-illegalBranches').indexOf(currentBranch) < 0) {
return
}
let message = `You are currently on branch "${currentBranch}"`
if (!gitModel.isRootGit()) {
message += ` in Submodule "${repositoryPath}"`
}
message += `. You should not commit on this branch. Would you like to switch branch?`
const action = await InformationMessage.showInformationMessage(
message,
MessageOption.optionYES,
MessageOption.optionNO,
)
if (action !== MessageOption.YES) {
return
}
// let the user choose a branch to checkout
const localBranches = gitModel.getLocalBranches()
const createNewBranchCommand = '[git-assistant][create-new-branch]'
let branch = ''
if (localBranches.length > 1) {
const options: QuickPickOption[] = []
localBranches.forEach((branch) => {
const branchName = branch.getName()
if (branchName !== currentBranch) {
options.push(new QuickPickOption(branchName, branchName))
}
})
options.push(new QuickPickOption('+ create a new branch', createNewBranchCommand))
branch = await QuickPick.showQuickPick('choose the branch to checkout', ...options)
}
if (!branch.length || branch === createNewBranchCommand) {
branch = await InputBox.showInputBox('enter name of the new branch')
await GitRepository.createNewBranch(repositoryPath, branch)
}
BranchWarn.checkoutWithoutStash(gitModel, branch)
}
// tries to checkout a branch
// iff checkout fails => try to stash before checkout
private static checkoutWithoutStash = async (gitModel: Git, branch: string): Promise<void> => {
GitRepository.checkoutBranchForRepository(gitModel.getRelativePath(), branch).catch(() =>
BranchWarn.checkoutWithStash(gitModel, branch),
)
}
// stashes changes => then checkout
// asks user in the end if it should pop the latest changes from stash
private static checkoutWithStash = async (gitModel: Git, branch: string): Promise<void> => {
const stashed = await BranchWarn.stashBeforeCheckout(gitModel.getPath(), branch)
if (!stashed) {
return
}
await GitRepository.checkoutBranchForRepository(gitModel.getRelativePath(), branch)
BranchWarn.stashPopAfterCheckout(gitModel.getPath())
}
private static stashBeforeCheckout = async (repositoryPath: string, branch: string): Promise<boolean> => {
const stashChanges = Config.getValue('branchWarn-stashChanges')
if (stashChanges === ConfigOptions.disabled) {
return false
}
if (stashChanges === ConfigOptions.auto) {
GitRepository.stashSaveChanges(repositoryPath)
.then(() => true)
.catch(() => false)
}
const action = await InformationMessage.showInformationMessage(
`would you like to stash the current changes before checking out branch '${branch}'? The current changes will be lost`,
MessageOption.optionYES,
MessageOption.optionNO,
)
if (action === MessageOption.NO) {
return false
}
await GitRepository.stashSaveChanges(repositoryPath)
return true
}
private static stashPopAfterCheckout = async (repositoryPath: string): Promise<void> => {
const action = await InformationMessage.showInformationMessage(
`would you like to unstash the changes?`,
MessageOption.optionYES,
MessageOption.optionNO,
)
if (action !== MessageOption.YES) {
return
}
await GitRepository.stashPopChanges(repositoryPath)
}
}
|
5098aed0bee4f1bb88a8a5e0f67af09f9845f241 | TypeScript | CS506-MS3/ms3-web | /src/app/_actions/crud.reducer.ts | 2.8125 | 3 | import * as CrudActions from './crud.actions';
export const reducer = (state, action, prefix, initialState) => {
switch (action.type) {
case prefix + CrudActions.SET:
return (<CrudActions.Set>action).payload;
case prefix + CrudActions.CLEAR:
return initialState;
case prefix + CrudActions.UPDATE:
return Object.assign({}, state, (<CrudActions.Update>action).payload);
case prefix + CrudActions.ADD_ITEM:
return {
...state,
list: [...state.list, (<CrudActions.AddItem>action).payload]
};
case prefix + CrudActions.REMOVE_ITEM:
return {
...state,
list: state.list.filter((item) => item.id !== (<CrudActions.RemoveItem>action).payload.id)
};
case prefix + CrudActions.UPDATE_ITEM:
return {
...state,
list: state.list.map(
(item) => item.id === (<CrudActions.UpdateItem>action).payload.id ?
Object.assign({}, item, (<CrudActions.UpdateItem>action).payload) : item
)
};
default:
return state;
}
};
|
43dd96a694f7e736568af272b41e35f94d064954 | TypeScript | cenxky/flexivue | /webpack-helpers/src/index.ts | 2.71875 | 3 | import { Definition } from "../../lib/src/definition"
export interface ECMAScriptModule {
__esModule: boolean
default?: object
}
export function definitionsFromContext(context: __WebpackModuleApi.RequireContext): Definition[] {
return context
.keys()
.map((key) => definitionForModuleWithContextAndKey(context, key))
.filter(value => value) as Definition[]
}
function definitionForModuleWithContextAndKey(context: __WebpackModuleApi.RequireContext, key: string): Definition | undefined {
let identifier = identifierForContextKey(key)
if (identifier) {
return definitionForModuleAndIdentifier(context(key), identifier)
}
}
function definitionForModuleAndIdentifier(module: ECMAScriptModule, identifier: string): Definition | undefined {
let instanceConstructor = module.default as any
if (typeof instanceConstructor == "function") {
return { identifier, instanceConstructor }
}
}
export function identifierForContextKey(key: string): string | undefined {
let logicalName = (key.match(/^(?:\.\/)?(.+)(?:\..+?)$/) || [])[1]
if (logicalName) {
return logicalName.replace(/\//g, "--")
}
}
|
2adfbe699baf567e398602d63655395f6f3ccc24 | TypeScript | jahow/simuworld-proto1 | /ts/meshbuilder.ts | 3.21875 | 3 | /// <reference path="../bower_components/babylonjs/dist/babylon.2.2.d.ts"/>
// This is a utility class that produces a mesh by building it
// step by step with simple operations: add quad, etc.
class MeshBuilder {
// singleton pattern
private static _inst: MeshBuilder;
private static _getInstance(): MeshBuilder {
if(!MeshBuilder._inst) { MeshBuilder._inst = new MeshBuilder(); }
return MeshBuilder._inst;
}
// current mesh data
private _positions: number[];
private _colors: number[];
private _normals: number[];
private _indices: number[];
private _vertex_position: number; // positions in the arrays
private _triangle_position: number;
// temporary vars
private _v1 = new BABYLON.Vector3(0, 0, 0);
private _v2 = new BABYLON.Vector3(0, 0, 0);
private _v3 = new BABYLON.Vector3(0, 0, 0);
private _i1 = 0;
private _i2 = 0;
private _i3 = 0;
// vertex and index counts are used to allocate an array large enough if possible
// if unknown, leave blank
public static startMesh(vertex_count?, triangle_count?) {
var builder = MeshBuilder._getInstance();
if(!vertex_count) { vertex_count = 0; }
if(!triangle_count) { triangle_count = 0; }
// init
builder._positions = new Array<number>(vertex_count * 3);
builder._normals = new Array<number>(vertex_count * 3);
builder._colors = new Array<number>(vertex_count * 4);
builder._indices = new Array<number>(triangle_count * 3);
builder._vertex_position = 0;
builder._triangle_position = 0;
}
// finalize mesh and return it
public static endMesh(name: string, scene: BABYLON.Scene, parent?: BABYLON.Node): BABYLON.Mesh {
var builder = MeshBuilder._getInstance();
var mesh = new BABYLON.Mesh(name, scene, parent);
mesh.setIndices(builder._indices);
mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, builder._positions);
mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, builder._colors);
mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, builder._normals);
return mesh;
}
// MESH BUILDING
public static addVertex(pos: BABYLON.Vector3, norm: BABYLON.Vector3,
col?: BABYLON.Color4 | BABYLON.Color3) {
if(!col) { col = new BABYLON.Color4(1, 1, 1, 1); }
var builder = MeshBuilder._getInstance();
builder._addToArray(builder._positions,
[pos.x, pos.y, pos.z], builder._vertex_position*3);
builder._addToArray(builder._normals,
[norm.x, norm.y, norm.z], builder._vertex_position*3);
builder._addToArray(builder._colors,
[col.r, col.g, col.b, (col['a'] ? col['a'] : 1)], builder._vertex_position*4);
builder._vertex_position += 1;
}
// normals are perpendicular to the triangle
// anti-clockwise: v1, v2, v3
public static addTriangle(v1: BABYLON.Vector3, v2: BABYLON.Vector3,
v3: BABYLON.Vector3, color?: BABYLON.Color4 | BABYLON.Color3) {
var builder = MeshBuilder._getInstance();
builder._i1 = builder._vertex_position;
builder._v1.copyFrom(v3).subtractInPlace(v1);
builder._v2.copyFrom(v2).subtractInPlace(v1);
BABYLON.Vector3.CrossToRef(builder._v1, builder._v2, builder._v3);
builder._v3.normalize();
MeshBuilder.addVertex(v1, builder._v3, color);
MeshBuilder.addVertex(v2, builder._v3, color);
MeshBuilder.addVertex(v3, builder._v3, color);
builder._addToArray(builder._indices,
[builder._i1, builder._i1+1, builder._i1+2], builder._triangle_position*3);
builder._triangle_position += 1;
}
// normals a perpendicular to the vectors v1v2 and v1v4
// anti-clockwise: v1, v2, v3, v4
// normal is optional
public static addQuad(v1: BABYLON.Vector3, v2: BABYLON.Vector3,
v3: BABYLON.Vector3, v4: BABYLON.Vector3,
color?: BABYLON.Color4 | BABYLON.Color3,
normal?: BABYLON.Vector3) {
var builder = MeshBuilder._getInstance();
builder._i1 = builder._vertex_position;
if(!normal) {
builder._v1.copyFrom(v4).subtractInPlace(v1);
builder._v2.copyFrom(v2).subtractInPlace(v1);
BABYLON.Vector3.CrossToRef(builder._v1, builder._v2, builder._v3);
builder._v3.normalize();
normal = builder._v3;
}
MeshBuilder.addVertex(v1, normal, color);
MeshBuilder.addVertex(v2, normal, color);
MeshBuilder.addVertex(v3, normal, color);
MeshBuilder.addVertex(v4, normal, color);
builder._addToArray(builder._indices,
[ builder._i1, builder._i1+1, builder._i1+2,
builder._i1, builder._i1+2, builder._i1+3 ],
builder._triangle_position*3);
builder._triangle_position += 2;
}
// helper
private _addToArray(array: number[], values: number | number[], index) {
if(typeof values === "number") {
if(array.length <= index) { array.push(values); }
else { array[index] = values; }
return;
}
if(values instanceof Array) {
for(var i=0; i<values.length; i++) {
this._addToArray(array, values[i], index+i);
}
return;
}
}
} |
993b461160fc95f6b9d078df09f46ee020e488a5 | TypeScript | Jac21/GistsCollection | /Angular/Angular/UsingReduxToManageStateInAngular/pluralsight-angular-redux/src/app/blocks/spinner/spinner.service.ts | 2.546875 | 3 | import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
export interface ISpinnerState {
show: boolean
}
@Injectable()
export class SpinnerService {
private _spinnerSubject = new Subject();
spinnerState = <Observable<ISpinnerState>>this._spinnerSubject.asObservable();
show() {
this._spinnerSubject.next(<ISpinnerState>{ show: true });
}
hide() {
this._spinnerSubject.next(<ISpinnerState>{ show: false });
}
} |