repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
nythonore/mlabs-blog
|
src/domain/blog/interfaces.ts
|
export interface BlogInterface {
id: number;
userId: number;
title: string;
body: string;
}
export interface StateInterface {
data: BlogInterface[];
loading: boolean;
error: string | null;
}
|
nythonore/mlabs-blog
|
src/domain/blog/reducer.ts
|
import { StateInterface } from './interfaces';
import { enumType, actionType } from './types';
const initialState = {
data: [],
loading: false,
error: null,
};
const reducer = (
state: StateInterface = initialState,
action: actionType
): StateInterface => {
switch (action.type) {
case enumType.REQUEST_LIST_BLOG_LOADING:
return { ...state, loading: true };
case enumType.REQUEST_LIST_BLOG_SUCCESS:
return { ...state, loading: false, data: action.payload, error: null };
case enumType.REQUEST_LIST_BLOG_ERROR:
return { loading: false, data: [], error: action.payload };
default:
return state;
}
};
export default reducer;
|
nythonore/mlabs-blog
|
src/domain/reducers.ts
|
<reponame>nythonore/mlabs-blog
import { combineReducers } from 'redux';
import blogReducer from './blog/reducer';
const reducers = combineReducers({
blog: blogReducer,
});
export type rootState = ReturnType<typeof reducers>;
export default reducers;
|
nythonore/mlabs-blog
|
src/resources/components/Search.tsx
|
<gh_stars>0
import { useDispatch } from 'react-redux';
import { Form } from 'react-bootstrap';
import { listBlog } from '../../domain/blog/actions';
const Search = () => {
const dispatch = useDispatch();
return (
<div className='quick-search'>
<Form.Group>
<Form.Control
type='text'
name='search'
placeholder='Quick Search...'
autoComplete='off'
onChange={({ target: { value } }) => dispatch(listBlog(value))}
/>
</Form.Group>
</div>
);
};
export default Search;
|
nythonore/mlabs-blog
|
src/domain/blog/actions.ts
|
<reponame>nythonore/mlabs-blog
import axios from 'axios';
import { Dispatch } from 'redux';
import { enumType, actionType } from './types';
const BASE_URL = 'https://jsonplaceholder.typicode.com/posts';
export const listBlog = (q: string | undefined = undefined) => {
return async (dispatch: Dispatch<actionType>) => {
dispatch({
type: enumType.REQUEST_LIST_BLOG_LOADING,
});
try {
const { data } = await axios.get(BASE_URL, {
params: { q },
});
dispatch({
type: enumType.REQUEST_LIST_BLOG_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: enumType.REQUEST_LIST_BLOG_ERROR,
payload: 'message',
});
}
};
};
|
nythonore/mlabs-blog
|
src/Routes.tsx
|
import { Navigate, useRoutes } from 'react-router-dom';
import BlogListView from './resources/views/BlogListView';
const Routes = () => {
return useRoutes([
{ path: '/', element: <BlogListView /> },
{ path: '*', element: <Navigate to='/' /> },
]);
};
export default Routes;
|
nythonore/mlabs-blog
|
src/domain/blog/types.ts
|
import { BlogInterface } from './interfaces';
export enum enumType {
REQUEST_LIST_BLOG_LOADING = 'REQUEST_LIST_BLOG_LOADING',
REQUEST_LIST_BLOG_SUCCESS = 'REQUEST_LIST_BLOG_SUCCESS',
REQUEST_LIST_BLOG_ERROR = 'REQUEST_LIST_BLOG_ERROR',
}
interface actionLoading {
type: enumType.REQUEST_LIST_BLOG_LOADING;
}
interface actionSuccess {
type: enumType.REQUEST_LIST_BLOG_SUCCESS;
payload: BlogInterface[];
}
interface actionError {
type: enumType.REQUEST_LIST_BLOG_ERROR;
payload: string;
}
export type actionType = actionLoading | actionSuccess | actionError;
|
nythonore/mlabs-blog
|
src/resources/components/Blog.tsx
|
import React from 'react';
import { Row, Col, Image } from 'react-bootstrap';
import { trimText } from '../../core/helpers/utils';
import { BlogInterface } from '../../domain/blog/interfaces';
type Props = {
data: BlogInterface;
};
const Blog = ({ data }: Props) => {
return (
<div className='blog-card cursor shadow'>
<Row>
<Col lg={5} className='image-card'>
<div
style={{
background: `url(https://picsum.photos/300?random=${data.id}) no-repeat`,
backgroundSize: 'cover',
backgroundPosition: 'center',
width: '100%',
height: '100%',
}}
className='image'
></div>
</Col>
<Col lg={7} className='content-card'>
<div className='border px-4 py-4 bg-white'>
<h2 className='font-sz-21 font-wg-600'>{data.title}</h2>
<p className='font-sz-14 font-wg-400 text-muted mt-3'>
{trimText(data.body, 100)}
</p>
<div className='user-card d-flex align-items-center mt-4'>
<Image
alt='<NAME>'
src='https://sikharkumarbhuyan.github.io/assets/img/profile.png'
className='img-fluid'
/>
<div className='px-3 font-sz-14 font-wg-300'>
<p><NAME></p>
<p className='text-muted'>Feb 3, 2022 . 4 min read</p>
</div>
</div>
</div>
</Col>
</Row>
</div>
);
};
export default Blog;
|
nythonore/mlabs-blog
|
src/core/helpers/utils.ts
|
export const trimText = (text: string = '', length: number = 8) => {
if (text.length > length) return `${text.slice(0, length)}...`;
return text;
};
|
nythonore/mlabs-blog
|
src/core/hooks/useTypedSelector.ts
|
import { useSelector, TypedUseSelectorHook } from 'react-redux';
import { rootState } from '../../domain/reducers';
const useTypedSelector: TypedUseSelectorHook<rootState> = useSelector;
export default useTypedSelector;
|
IAmVisco/despair-bot
|
src/helpers/consts.ts
|
import * as pkg from '../../package.json';
import * as triggers from '../../triggers.json';
import { StatsCommand } from '../types';
export const BOT_VERSION = pkg.version;
export const BOT_DESCRIPTION = pkg.description;
export const GITHUB_LINK = pkg.repository;
export const KEYWORDS: StatsCommand[] = triggers.map((trigger) => ({
...trigger,
regex: new RegExp(trigger.regex, 'gi'),
}));
export const contextMessageBody = `**When we say "please give context" we mean:**
・Where, in detail, did you encounter the word, phrase, or sentence?
・Was it a video, anime, manga, or website? If so, which one?
・What was the situation?
・Who said it? To whom?
・Do you have a link to the video or website where you encountered it? How about a screenshot? Audio clip?
***Please answer all of the above before proceeding.***`;
export const dictionaryMessageBody = `
Most "what does this word mean" questions can be answered with a dictionary! There are links to a couple below.
If you checked a dictionary and still have questions, please be specific.
What did you not understand? Do you need an example of how to use the word?
In the meantime, try these dictionaries:
・https://jisho.org/
・https://takoboto.jp/
`;
|
IAmVisco/despair-bot
|
src/services/EmbedFactoryService.ts
|
import { MessageEmbed, ClientUser } from 'discord.js';
import * as moment from 'moment-timezone';
import { BOT_VERSION } from '../helpers/consts';
class EmbedFactoryService {
getEmbedBase(user: ClientUser | null, title: string): MessageEmbed {
const embed = new MessageEmbed()
.setTitle(title)
.setAuthor(`${user?.username} v${BOT_VERSION}`, user?.avatarURL({ dynamic: true }) || '')
.setTimestamp()
.setColor(EmbedFactoryService.getRandomColor())
.setFooter(this.getUptime());
return embed;
}
// TODO: move to proper place
formatDuration(duration: moment.Duration): string {
const days = duration.days() ? `${duration.days()} ${duration.days() > 1 ? 'days,' : 'day,'}` : '';
const hours = duration.hours() ? `${duration.hours()} ${duration.hours() > 1 ? 'hours,' : 'hour,'}` : '';
const mins = duration.minutes() ? `${duration.minutes()} ${duration.minutes() > 1 ? 'minutes,' : 'minute,'}` : '';
const secs = duration.seconds() > 1 ? `${duration.seconds()} seconds` : `${duration.seconds()} second`;
return `${`${days} ${hours} ${mins} ${secs}`.trim()}`;
}
private getUptime(): string {
const uptime = moment.duration(process.uptime(), 'seconds');
const formattedDuration = this.formatDuration(uptime);
return `Uptime: ${formattedDuration}`;
}
private static getRandomColor(): string {
// eslint-disable-next-line no-bitwise
return `#${(Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0')}`;
}
}
export const embedFactory = new EmbedFactoryService();
|
IAmVisco/despair-bot
|
src/helpers/redis.ts
|
<filename>src/helpers/redis.ts
import * as Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_PORT);
redis.config('SET', 'notify-keyspace-events', 'KEA');
export { redis };
|
IAmVisco/despair-bot
|
src/commands/meta.ts
|
import * as moment from 'moment-timezone';
import * as path from 'path';
import { BOT_DESCRIPTION, GITHUB_LINK } from '../helpers/consts';
import { embedFactory } from '../services/EmbedFactoryService';
import { redisCollectorService } from '../services/RedisCollectorService';
import { Command } from '../types';
const group = path.parse(__filename).name;
const help: Command = {
name: 'help',
group,
aliases: ['commands', 'h'],
description: 'Prints out this message.',
execute(message) {
const { user } = message.client;
const orderedCommands: { [key: string]: Array<Command> } = {};
const commands: { [key: string]: Array<Command> } = { uncategorized: [] };
message.client.commands!.forEach((c) => {
if (c.group) {
c.group in commands
? commands[c.group].push(c)
: commands[c.group] = [c];
} else {
commands.uncategorized.push(c);
}
});
Object.keys(commands).sort().forEach((key) => {
const capitalizedKey = key.charAt(0).toUpperCase() + key.slice(1);
orderedCommands[capitalizedKey] = commands[key]
.filter((c) => !c.hidden)
.sort((a, b) => (a.name > b.name ? 1 : -1));
});
const embed = embedFactory.getEmbedBase(user, `${user?.username} commands list`)
.setThumbnail(user?.avatarURL({ dynamic: true }) || '')
.setDescription(BOT_DESCRIPTION);
const prefix = process.env.BOT_PREFIX;
Object.keys(orderedCommands).forEach((k) => {
if (orderedCommands[k].length) {
embed.addField('Group', `**${k}**`);
orderedCommands[k].forEach((c) => {
const commandName = c.aliases
? `${prefix}${c.name} [${c.aliases.join(', ')}]`
: `${prefix}${c.name}`;
embed.addField(commandName, c.description, true);
});
}
});
return message.channel.send(embed);
},
};
const ping: Command = {
name: 'ping',
group,
description: 'Ping!',
async execute(message) {
const msg = await message.channel.send(embedFactory.getEmbedBase(message.client.user, 'Pong!').setColor('GREEN'));
const pingTime = moment(msg.createdTimestamp).diff(moment(message.createdTimestamp));
const replyEmbed = embedFactory.getEmbedBase(message.client.user, 'Pong!')
.setDescription(
`:hourglass: Message ping: ${pingTime}ms\n`
+ `:heartbeat: Websocket ping: ${message.client.ws.ping}ms`,
)
.setColor('GREEN')
.setTimestamp();
return msg.edit(replyEmbed);
},
};
const invite: Command = {
name: 'invite',
group,
description: 'Retrieves bot invite.',
async execute(message) {
// Returns old API link since lib is not updated it yet
return message.channel.send(`<${await message.client.generateInvite()}>`);
},
};
const info: Command = {
name: 'info',
aliases: ['about'],
group,
description: 'Prints bot info.',
async execute(message) {
const { user } = message.client;
const infoEmbed = embedFactory.getEmbedBase(user, 'Source code')
.setURL(GITHUB_LINK)
.setThumbnail(user?.avatarURL({ dynamic: true }) || '')
.setDescription(
`${BOT_DESCRIPTION}\n`
+ 'Check out real time counter [here](https://ayamedespair.com).\n'
+ `[Invite this bot to your server](${await message.client.generateInvite()}).`,
)
.addField('Users known', `${message.client.users.cache.size}`, true)
.addField('Guilds known', `${message.client.guilds.cache.size}`, true)
.addField('Commands executed', `${await redisCollectorService.getKeyValue('commands')}`, true);
return message.channel.send(infoEmbed);
},
};
export default [help, ping, invite, info];
|
IAmVisco/despair-bot
|
src/commands/stats.ts
|
import * as moment from 'moment-timezone';
import * as path from 'path';
import type { MessageEmbed } from 'discord.js';
import { contextMessageBody, dictionaryMessageBody, KEYWORDS } from '../helpers/consts';
import { redis } from '../helpers/redis';
import { embedFactory } from '../services/EmbedFactoryService';
import { redisCollectorService } from '../services/RedisCollectorService';
import { Command, CustomMessage } from '../types';
const group = path.parse(__filename).name;
const keywordCommands = KEYWORDS.map(({ name, description, aliases }): Command => ({
name,
group,
description,
aliases,
async execute(message) {
const statValue = await redisCollectorService.getKeyValue(name);
return message.channel.send(statValue);
},
}));
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const poyoArmy: Command = {
name: 'poyoarmy',
group,
description: 'Shows taken Poyoyo numbers.',
async execute(message) {
if (!message.guild) {
return message.channel.send('Cannot execute command in DMs!');
}
const usernames = message.guild.members.cache.map((member) => {
if (member.nickname?.startsWith('Poyoyo')) {
return member.nickname.split(' ')[0].replace('Poyoyo', '');
}
if (member.user.username.startsWith('Poyoyo')) {
return member.user.username.split(' ')[0].replace('Poyoyo', '');
}
return '';
}).map((x) => parseInt(x, 10)).filter((x) => x).sort((a, b) => a - b);
const duplicates = usernames?.reduce<number[]>((acc, el, i, arr) => {
if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el);
return acc;
}, []);
if (usernames.length) {
const embed = embedFactory.getEmbedBase(message.client.user, 'Poyoyo army list')
.setDescription('Full list of taken Poyoyo numbers.')
.addField('Army size', usernames.length, true)
.addField('Heretics', message.guild.memberCount - usernames.length, true)
.addField('How to join', 'Pick any number that is not listed below and change your nickname **on the server** according to the following format `Poyoyo<number> | <Your Nickname>`');
while (usernames.length) {
const namesChunk = [];
while (namesChunk.join(',').length <= 1000 && usernames.length) {
namesChunk.push(usernames.shift());
}
embed.addField('Numbers taken', namesChunk.join(','));
}
return message.channel.send(duplicates.length
? embed.addField('Duplicates', duplicates.join(', '))
: embed);
}
return message.channel.send('None!');
},
};
const ctx: Command = {
name: 'ctx',
group,
description: 'Resets context counter and shows time since last reset',
aliases: ['context'],
async execute(message, args) {
let newBestSet = false;
const lastReset = moment(await redis.get('context-reset'));
const bestResult = Number(await redis.get('context-best'));
const fromNow = moment.duration(moment().diff(lastReset));
const embed = embedFactory
.getEmbedBase(message.client.user, 'Context timer')
.addField('Time since last time context was mentioned', embedFactory.formatDuration(fromNow));
if (args && args.pop() === 'reset') {
embed.setFooter('Counter reset!');
await redis.set('context-reset', moment().toISOString());
if (fromNow.asMilliseconds() > bestResult) {
newBestSet = true;
embed.setDescription('New best!').addField('Best result', embedFactory.formatDuration(fromNow));
await redis.set('context-best', fromNow.asMilliseconds());
}
} else {
embed.setDescription('Pass \'reset\' as an argument to reset the counter.');
}
!newBestSet && embed.addField('Best result', embedFactory.formatDuration(moment.duration(bestResult)));
return message.channel.send(embed);
},
};
const context: Command = {
name: 'context',
group,
description: 'Pulls out "Provide more context!" message',
async execute(message) {
const contextRequiredTimes = await redis.incr('context-help');
const embed = embedFactory
.getEmbedBase(message.client.user, 'Please, provide more context!')
.setFooter(`Context was required ${contextRequiredTimes} ${contextRequiredTimes === 1 ? 'time' : 'times'}`)
.setDescription(contextMessageBody);
return message.channel.send(embed);
},
};
const dictionary: Command = {
name: 'dictionary',
group,
description: 'Pulls out "Have you tried checking a dictionary?" message',
aliases: ['dict', 'jisho'],
async execute(message) {
const dictionaryNotUsedTimes = await redis.incr('dict-help');
const embed = embedFactory
.getEmbedBase(message.client.user, 'Have you tried checking a dictionary first?')
.setFooter(`A dictionary was not used ${dictionaryNotUsedTimes} ${dictionaryNotUsedTimes === 1 ? 'time' : 'times'}`)
.setDescription(dictionaryMessageBody);
return message.channel.send(embed);
},
};
const cancel: Command = {
name: 'cancel',
group,
description: 'Cancels someone',
aliases: ['cancels'],
async execute(message, args) {
const showList = async (msg: CustomMessage): Promise<MessageEmbed> => {
const embed = embedFactory.getEmbedBase(msg.client.user, 'Cancel list')
.setDescription(`Invoke the command like \`${process.env.BOT_PREFIX}cancel @<user>\` to cancel them!`);
const usersRange = await redis.zrevrange('cancels', 0, 15, 'WITHSCORES');
const chunks = 2;
const userChunks = Array(Math.ceil(usersRange.length / chunks))
.fill(null)
.map((_, i) => usersRange.slice(i * chunks, i * chunks + chunks));
embed.addField(
'Sorted list',
userChunks
.filter(([, cancelAmount]) => +cancelAmount > 1)
.map(([userId, cancelAmount]) => `<@${userId}> - ${cancelAmount}`).join('\n'),
);
return embed;
};
const cancelUser = async (msg: CustomMessage): Promise<MessageEmbed> => {
const embed = embedFactory.getEmbedBase(msg.client.user, 'User cancelled!');
const timesCancelled = await redis.zincrby('cancels', 1, message.mentions.users.first()!.id);
const firstTime = timesCancelled === '1';
embed.addField(
firstTime ? 'Congrats!' : 'Here we go again',
firstTime
? "It's your first time getting cancelled!"
: `You've already been cancelled ${timesCancelled} times.`,
);
return embed;
};
const embed = (!args?.length || !message.mentions.users.size)
? await showList(message)
: await cancelUser(message);
return message.channel.send(embed);
},
};
export default keywordCommands.concat([ctx, context, dictionary, cancel]);
|
IAmVisco/despair-bot
|
src/services/RedisCollectorService.ts
|
import { logger } from '../helpers/logger';
import { redis } from '../helpers/redis';
import { KEYWORDS } from '../helpers/consts';
class RedisCollectorService {
async getKeyValue(key: string): Promise<number> {
return parseInt(await redis.get(key) || '0', 10);
}
countKeywords(content: string): void {
try {
// eslint-disable-next-line no-restricted-syntax
for (const { name, regex } of KEYWORDS) {
const matchAmount = (content.match(regex) || []).length;
matchAmount && redis.incrby(name, matchAmount);
}
} catch (e) {
logger.error('Cannot increment Redis counter', e);
}
}
incrementCommandCount(): Promise<number> {
return redis.incr('commands');
}
}
export const redisCollectorService = new RedisCollectorService();
|
nurdiansyah/version-bump-prompt
|
src/normalize-options.ts
|
import * as globby from "globby";
import { hasMagic } from "globby";
import { isReleaseType, ReleaseType } from "./release-type";
import { VersionBumpOptions } from "./types/version-bump-options";
interface Interface {
input?: NodeJS.ReadableStream | NodeJS.ReadStream | false;
output?: NodeJS.WritableStream | NodeJS.WriteStream | false;
[key: string]: unknown;
}
/**
* A specific version release.
*/
export interface VersionRelease {
type: "version";
version: string;
}
/**
* Prompt the user for the release number.
*/
export interface PromptRelease {
type: "prompt";
preid: string;
}
/**
* A bump release, relative to the current version number.
*/
export interface BumpRelease {
type: ReleaseType;
preid: string;
}
/**
* One of the possible Release types.
*/
export type Release = VersionRelease | PromptRelease | BumpRelease;
/**
* Normalized and sanitized options
*/
export interface NormalizedOptions {
release: Release;
commit?: {
message: string;
noVerify: boolean;
all: boolean;
};
tag?: {
name: string;
};
push: boolean;
files: string[];
cwd: string;
interface: Interface;
ignoreScripts: boolean;
}
/**
* Converts raw VersionBumpOptions to a normalized and sanitized Options object.
*/
export async function normalizeOptions(raw: VersionBumpOptions): Promise<NormalizedOptions> {
// Set the simple properties first
let preid = typeof raw.preid === "string" ? raw.preid : "beta";
let push = Boolean(raw.push);
let all = Boolean(raw.all);
let noVerify = Boolean(raw.noVerify);
let cwd = raw.cwd || process.cwd();
let ignoreScripts = Boolean(raw.ignoreScripts);
let release: Release;
if (!raw.release || raw.release === "prompt") {
release = { type: "prompt", preid };
}
else if (isReleaseType(raw.release)) {
release = { type: raw.release, preid };
}
else {
release = { type: "version", version: raw.release };
}
let tag;
if (typeof raw.tag === "string") {
tag = { name: raw.tag };
}
else if (raw.tag) {
tag = { name: "v" };
}
// NOTE: This must come AFTER `tag` and `push`, because it relies on them
let commit;
if (typeof raw.commit === "string") {
commit = { all, noVerify, message: raw.commit };
}
else if (raw.commit || tag || push) {
commit = { all, noVerify, message: "release v" };
}
let files;
if (Array.isArray(raw.files) && raw.files.length > 0) {
files = await strictGlobMatches(raw.files, { cwd });
}
else {
// Try to find these files by default.
// If they don't exist, then they will NOT be included in the `files` array.
files = await globby(["package.json", "package-lock.json"], { cwd });
}
let ui: Interface;
if (raw.interface === false) {
ui = { input: false, outut: false };
}
else if (raw.interface === true || !raw.interface) {
ui = { input: process.stdin, output: process.stdout };
}
else {
let { input, output, ...other } = raw.interface;
if (input === true || (input !== false && !input)) {
input = process.stdin;
}
if (output === true || (output !== false && !output)) {
output = process.stdout;
}
ui = { input, output, ...other };
}
if (release.type === "prompt" && !(ui.input && ui.output)) {
throw new Error("Cannot prompt for the version number because input or output has been disabled.");
}
return { release, commit, tag, push, files, cwd, interface: ui, ignoreScripts };
}
/**
* Returns all files that match the given glob patterns.
* An error is thrown if any pattern matches zero files.
*/
async function strictGlobMatches(files: string[], options: object): Promise<string[]> {
// Match all glob patterns simultaneously
let matches = await Promise.all(files.map((file) => strictGlobMatch(file, options)));
// Get all the unique files
let matchedFiles = new Set<string>();
for (let match of matches) {
for (let file of match) {
matchedFiles.add(file);
}
}
return [...matchedFiles];
}
/**
* Returns all files that match the given glob pattern.
* An error is thrown if the pattern matches zero files.
*/
async function strictGlobMatch(file: string, options: object): Promise<string[]> {
let matches = await globby(file, options);
if (matches.length === 0) {
if (hasMagic(file)) {
throw new Error(`Could not find any files matching "${file}".`);
}
else {
throw new Error(`Could not find file: ${file}.`);
}
}
// Return files in a predictable order
return matches.sort();
}
|
nurdiansyah/version-bump-prompt
|
src/get-old-version.ts
|
import * as semver from "semver";
import { readJsonFile } from "./fs";
import { isManifest } from "./manifest";
import { Operation } from "./operation";
/**
* Finds the current version number from files such as package.json.
* An error is thrown if no version number can be found.
*/
export async function getOldVersion(operation: Operation): Promise<Operation> {
let { cwd, files } = operation.options;
// Check all JSON files in the files list
let filesToCheck = files.filter((file) => file.endsWith(".json"));
// Always check package.json
if (!filesToCheck.includes("package.json")) {
filesToCheck.push("package.json");
}
// Check each file, in order, and return the first valid version number we find
for (let file of filesToCheck) {
let version = await readVersion(file, cwd);
if (version) {
// We found the current version number!
return operation.update({
oldVersionSource: file,
oldVersion: version,
});
}
}
// If we get here, then no version number was found
throw new Error(
`Unable to determine the current version number. Checked ${filesToCheck.join(", ")}.`
);
}
/**
* Tries to read the version number from the specified JSON file.
*
* @returns - The version number, or undefined if the file doesn't have a version number
*/
async function readVersion(file: string, cwd: string): Promise<string | undefined> {
try {
let { data: manifest } = await readJsonFile(file, cwd);
if (isManifest(manifest)) {
if (semver.valid(manifest.version)) {
return manifest.version;
}
}
}
catch (error) {
// Ignore errors (no such file, not valid JSON, etc.)
// Just try the next file instead.
return undefined;
}
}
|
nurdiansyah/version-bump-prompt
|
src/release-type.ts
|
<gh_stars>100-1000
import { ReleaseType } from "semver";
export { ReleaseType };
/**
* The different types of pre-releases.
*/
export const prereleaseTypes: ReleaseType[] = ["premajor", "preminor", "prepatch", "prerelease"];
/**
* All possible release types.
*/
export const releaseTypes: ReleaseType[] = prereleaseTypes.concat(["major", "minor", "patch"]);
/**
* Determines whether the specified value is a pre-release.
*/
export function isPrerelease(value: any): boolean {
return prereleaseTypes.includes(value);
}
/**
* Determines whether the specified value is a valid ReleaseType string.
*/
export function isReleaseType(value: any): value is ReleaseType {
return releaseTypes.includes(value);
}
|
nurdiansyah/version-bump-prompt
|
src/types/version-bump-progress.ts
|
<reponame>nurdiansyah/version-bump-prompt
import { VersionBumpResults } from "./version-bump-results";
/**
* Progress events that indicate the progress of the `versionBump()` function.
*/
export const enum ProgressEvent {
FileUpdated = "file updated",
FileSkipped = "file skipped",
GitCommit = "git commit",
GitTag = "git tag",
GitPush = "git push",
NpmScript = "npm script",
}
/**
* The NPM version scripts
*
* @see https://docs.npmjs.com/cli/version.html
*/
export const enum NpmScript {
PreVersion = "preversion",
Version = "version",
PostVersion = "postversion",
}
/**
* Information about the progress of the `versionBump()` function.
*/
export interface VersionBumpProgress extends VersionBumpResults {
event: ProgressEvent;
script?: NpmScript;
}
|
nurdiansyah/version-bump-prompt
|
src/cli/parse-args.ts
|
import * as commandLineArgs from "command-line-args";
import * as semver from "semver";
import { isReleaseType } from "../release-type";
import { VersionBumpOptions } from "../types/version-bump-options";
import { ExitCode } from "./exit-code";
import { usageText } from "./help";
/**
* The parsed command-line arguments
*/
export interface ParsedArgs {
help?: boolean;
version?: boolean;
quiet?: boolean;
options: VersionBumpOptions;
}
/**
* Parses the command-line arguments
*/
export function parseArgs(argv: string[]): ParsedArgs {
try {
let args = commandLineArgs(
[
{ name: "preid", type: String },
{ name: "commit", alias: "c", type: String },
{ name: "tag", alias: "t", type: String },
{ name: "push", alias: "p", type: Boolean },
{ name: "all", alias: "a", type: Boolean },
{ name: "no-verify", type: Boolean },
{ name: "quiet", alias: "q", type: Boolean },
{ name: "version", alias: "v", type: Boolean },
{ name: "help", alias: "h", type: Boolean },
{ name: "ignore-scripts", type: Boolean },
{ name: "git-files", type: String, multiple: true },
{ name: "files", type: String, multiple: true, defaultOption: true },
],
{ argv }
);
let parsedArgs: ParsedArgs = {
help: args.help as boolean,
version: args.version as boolean,
quiet: args.quiet as boolean,
options: {
preid: args.preid as string,
commit: args.commit as string | boolean,
tag: args.tag as string | boolean,
push: args.push as boolean,
all: args.all as boolean,
noVerify: args["no-verify"] as boolean,
files: args.files as string[],
gitFiles: args["git-files"] as string[],
ignoreScripts: args["ignore-scripts"] as boolean,
}
};
// If --preid is used without an argument, then throw an error, since it's probably a mistake.
// If they want to use the default value ("beta"), then they should not pass the argument at all
if (args.preid === null) {
throw new Error("The --preid option requires a value, such as \"alpha\", \"beta\", etc.");
}
// If --commit is used without an argument, then treat it as a boolean flag
if (args.commit === null) {
parsedArgs.options.commit = true;
}
// If --tag is used without an argument, then treat it as a boolean flag
if (args.tag === null) {
parsedArgs.options.tag = true;
}
// If a version number or release type was specified, then it will mistakenly be added to the "files" array
if (parsedArgs.options.files && parsedArgs.options.files.length > 0) {
let firstArg = parsedArgs.options.files[0];
if (firstArg === "prompt" || isReleaseType(firstArg) || semver.valid(firstArg)) {
parsedArgs.options.release = firstArg;
parsedArgs.options.files.shift();
}
}
return parsedArgs;
}
catch (error) {
// There was an error parsing the command-line args
return errorHandler(error as Error);
}
}
function errorHandler(error: Error): never {
console.error(error.message);
console.error(usageText);
return process.exit(ExitCode.InvalidArgument);
}
|
nurdiansyah/version-bump-prompt
|
dist/index.d.ts
|
<filename>dist/index.d.ts
import versionBump from "@jsdevtools/version-bump-prompt";
export * from "@jsdevtools/version-bump-prompt";
export default versionBump;
|
nurdiansyah/version-bump-prompt
|
src/index.ts
|
import { versionBump } from "./version-bump";
// Exprot the external type definitions as named exports
export { ReleaseType } from "./release-type";
export * from "./types/version-bump-options";
export * from "./types/version-bump-results";
export * from "./types/version-bump-progress";
// Export `versionBump` as a named export and the default export
export { versionBump };
export default versionBump;
// CommonJS default export hack
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = Object.assign(module.exports.default, module.exports);
}
|
nurdiansyah/version-bump-prompt
|
src/get-new-version.ts
|
<gh_stars>100-1000
import * as inquirer from "inquirer";
import * as semver from "semver";
import { ReleaseType, SemVer } from "semver";
import { BumpRelease, PromptRelease } from "./normalize-options";
import { Operation } from "./operation";
import { isPrerelease, releaseTypes } from "./release-type";
/**
* Determines the new version number, possibly by prompting the user for it.
*/
export async function getNewVersion(operation: Operation): Promise<Operation> {
let { release } = operation.options;
let { oldVersion } = operation.state;
switch (release.type) {
case "prompt":
return promptForNewVersion(operation);
case "version":
let newSemVer = new SemVer(release.version, true);
return operation.update({
newVersion: newSemVer.version,
});
default:
return operation.update({
release: release.type,
newVersion: getNextVersion(oldVersion, release),
});
}
}
/**
* Returns the next version number of the specified type.
*/
function getNextVersion(oldVersion: string, bump: BumpRelease): string {
let oldSemVer = new SemVer(oldVersion);
let newSemVer = oldSemVer.inc(bump.type, bump.preid);
if (
isPrerelease(bump.type) &&
newSemVer.prerelease.length === 2 &&
newSemVer.prerelease[0] === bump.preid &&
String(newSemVer.prerelease[1]) === "0"
) {
// This is a special case when going from a non-prerelease version to a prerelease version.
// SemVer sets the prerelease version to zero (e.g. "1.23.456" => "1.23.456-beta.0").
// But the user probably expected it to be "1.23.456-beta.1" instead.
// @ts-expect-error - TypeScript thinks this array is read-only
newSemVer.prerelease[1] = "1";
newSemVer.format();
}
return newSemVer.version;
}
/**
* Returns the next version number for all release types.
*/
function getNextVersions(oldVersion: string, preid: string): Record<ReleaseType, string> {
let next: Record<string, string> = {};
for (let type of releaseTypes) {
next[type] = getNextVersion(oldVersion, { type, preid });
}
return next;
}
/**
* Prompts the user for the new version number.
*
* @returns - A tuple containing the new version number and the release type (if any)
*/
async function promptForNewVersion(operation: Operation): Promise<Operation> {
let { oldVersion, oldVersionSource } = operation.state;
let release = operation.options.release as PromptRelease;
let prompts = inquirer.createPromptModule(operation.options.interface as inquirer.StreamOptions);
let next = getNextVersions(oldVersion, release.preid);
let answers: {
release: ReleaseType | "none" | "custom";
newVersion?: string;
};
answers = await prompts([
{
type: "list",
name: "release",
message: `\nThe current version in ${oldVersionSource} is ${oldVersion}\nHow would you like to bump it?`,
default: "patch",
pageSize: 10,
choices: [
{ value: "major", name: `major (${next.major})` },
{ value: "minor", name: `minor (${next.minor})` },
{ value: "patch", name: `patch (${next.patch})` },
{ value: "premajor", name: `pre-release major (${next.premajor})` },
{ value: "preminor", name: `pre-release minor (${next.preminor})` },
{ value: "prepatch", name: `pre-release patch (${next.prepatch})` },
{ value: "prerelease", name: `pre-release (${next.prerelease})` },
new inquirer.Separator(),
{ value: "none", name: `leave as-is (${oldVersion})` },
{ value: "custom", name: "custom..." },
]
},
{
type: "input",
name: "newVersion",
message: "Enter the new version number:",
default: oldVersion,
when: (previousAnswer) => previousAnswer.release === "custom",
filter: semver.clean,
validate: (newVersion: string) => {
return semver.valid(newVersion) ? true : "That's not a valid version number";
},
}
]);
switch (answers.release) {
case "none":
return operation.update({ newVersion: oldVersion });
case "custom":
return operation.update({ newVersion: answers.newVersion! });
default:
return operation.update({
release: answers.release,
newVersion: next[answers.release],
});
}
}
|
nurdiansyah/version-bump-prompt
|
src/run-npm-script.ts
|
<reponame>nurdiansyah/version-bump-prompt<gh_stars>100-1000
import * as ezSpawn from "@jsdevtools/ez-spawn";
import { readJsonFile } from "./fs";
import { isManifest, Manifest } from "./manifest";
import { Operation } from "./operation";
import { NpmScript, ProgressEvent } from "./types/version-bump-progress";
/**
* Runs the specified NPM script in the package.json file.
*/
export async function runNpmScript(script: NpmScript, operation: Operation): Promise<Operation> {
let { cwd, ignoreScripts } = operation.options;
if (!ignoreScripts) {
let { data: manifest } = await readJsonFile("package.json", cwd);
if (isManifest(manifest) && hasScript(manifest, script)) {
await ezSpawn.async("npm", ["run", script, "--silent"], { stdio: "inherit" });
operation.update({ event: ProgressEvent.NpmScript, script });
}
}
return operation;
}
/**
* Determines whether the specified NPM script exists in the given manifest.
*/
function hasScript(manifest: Manifest, script: NpmScript): boolean {
let scripts = manifest.scripts as Record<NpmScript, string> | undefined;
if (scripts && typeof scripts === "object") {
return Boolean(scripts[script]);
}
return false;
}
|
nurdiansyah/version-bump-prompt
|
src/version-bump.ts
|
import { getNewVersion } from "./get-new-version";
import { getOldVersion } from "./get-old-version";
import { gitCommit, gitPush, gitTag } from "./git";
import { Operation } from "./operation";
import { runNpmScript } from "./run-npm-script";
import { VersionBumpOptions } from "./types/version-bump-options";
import { NpmScript } from "./types/version-bump-progress";
import { VersionBumpResults } from "./types/version-bump-results";
import { updateFiles } from "./update-files";
/**
* Prompts the user for a version number and updates package.json and package-lock.json.
*
* @returns - The new version number
*/
export async function versionBump(): Promise<VersionBumpResults>;
/**
* Bumps the version number in package.json, package-lock.json.
*
* @param release
* The release version or type. Can be one of the following:
*
* - The new version number (e.g. "1.23.456")
* - A release type (e.g. "major", "minor", "patch", "prerelease", etc.)
* - "prompt" to prompt the user for the version number
*/
export async function versionBump(release: string): Promise<VersionBumpResults>;
/**
* Bumps the version number in one or more files, prompting the user if necessary.
* Optionally also commits, tags, and pushes to git.
*/
export async function versionBump(options: VersionBumpOptions): Promise<VersionBumpResults>;
/**
* Bumps the version number in one or more files, prompting the user if necessary.
* Optionally also commits, tags, and pushes to git.
*/
export async function versionBump(arg: VersionBumpOptions | string = {}): Promise<VersionBumpResults> {
if (typeof arg === "string") {
arg = { release: arg };
}
let operation = await Operation.start(arg);
// Get the old and new version numbers
await getOldVersion(operation);
await getNewVersion(operation);
// Run npm preversion script, if any
await runNpmScript(NpmScript.PreVersion, operation);
// Update the version number in all files
await updateFiles(operation);
// Run npm version script, if any
await runNpmScript(NpmScript.Version, operation);
// Git commit and tag, if enabled
await gitCommit(operation);
await gitTag(operation);
// Run npm postversion script, if any
await runNpmScript(NpmScript.PostVersion, operation);
// Push the git commit and tag, if enabled
await gitPush(operation);
return operation.results;
}
|
nurdiansyah/version-bump-prompt
|
src/types/version-bump-results.ts
|
import { ReleaseType } from "../release-type";
/**
* Information about the work that was performed by the `versionBump()` function.
*/
export interface VersionBumpResults {
/**
* The release type that was used, or `undefined` if an explicit version number was used.
*/
release?: ReleaseType;
/**
* The previous version number in package.json.
*/
oldVersion: string;
/**
* The new version number.
*/
newVersion: string;
/**
* The commit message that was used for the git commit, or `false` if no git commit was created.
*
* NOTE: This will never be an empty string. It will always contain at least the new version number.
*/
commit: string | false;
/**
* The tag name that was used for the git tag, or `false` if no git tag was created.
*
* NOTE: This will never be an empty string. It will always contain at least the new version number.
*/
tag: string | false;
/**
* The files that were actually modified.
*/
updatedFiles: string[];
/**
* The files that were not updated because they did not contain the old version number.
*/
skippedFiles: string[];
}
|
nurdiansyah/version-bump-prompt
|
src/git.ts
|
import * as ezSpawn from "@jsdevtools/ez-spawn";
import { Operation } from "./operation";
import { ProgressEvent } from "./types/version-bump-progress";
/**
* Commits the modififed files to Git, if the `commit` option is enabled.
*/
export async function gitCommit(operation: Operation): Promise<Operation> {
if (!operation.options.commit) {
return operation;
}
let { all, noVerify, message } = operation.options.commit;
let { updatedFiles, newVersion, gitFiles } = operation.state;
let args = [];
if (all) {
// Commit ALL files, not just the ones that were bumped
args.push("--all");
}
if (noVerify) {
// Bypass git commit hooks
args.push("--no-verify");
}
// Create the commit message
let commitMessage = formatVersionString(message, newVersion);
args.push("--message", commitMessage);
// Append the file names last, as variadic arguments
if (!all) {
args = args.concat(updatedFiles);
if (gitFiles) {
args = args.concat(gitFiles);
}
}
await ezSpawn.async("git", ["commit", ...args]);
return operation.update({ event: ProgressEvent.GitCommit, commitMessage });
}
/**
* Tags the Git commit, if the `tag` option is enabled.
*/
export async function gitTag(operation: Operation): Promise<Operation> {
if (!operation.options.tag) {
return operation;
}
let { commit, tag } = operation.options;
let { newVersion } = operation.state;
let args = [
// Create an annotated tag, which is recommended for releases.
// See https://git-scm.com/docs/git-tag
"--annotate",
// Use the same commit message for the tag
"--message", formatVersionString(commit!.message, newVersion),
];
// Create the Tag name
let tagName = formatVersionString(tag.name, newVersion);
args.push(tagName);
await ezSpawn.async("git", ["tag", ...args]);
return operation.update({ event: ProgressEvent.GitTag, tagName });
}
/**
* Pushes the Git commit and tag, if the `push` option is enabled.
*/
export async function gitPush(operation: Operation): Promise<Operation> {
if (!operation.options.push) {
return operation;
}
// Push the commit
await ezSpawn.async("git", "push");
if (operation.options.tag) {
// Push the tag
await ezSpawn.async("git", ["push", "--tags"]);
}
return operation.update({ event: ProgressEvent.GitPush });
}
/**
* Accepts a version string template (e.g. "release v" or "This is the %s release").
* If the template contains any "%s" placeholders, then they are replaced with the version number;
* otherwise, the version number is appended to the string.
*/
function formatVersionString(template: string, newVersion: string): string {
if (template.includes("%s")) {
return template.replace(/%s/g, newVersion);
}
else {
return template + newVersion;
}
}
|
nurdiansyah/version-bump-prompt
|
src/cli/help.ts
|
<reponame>nurdiansyah/version-bump-prompt
import { manifest } from "../manifest";
/**
* Text explaining how to use the CLI
*/
export const usageText = `
Usage: bump [release] [options] [files...]
release:
The release version or type. Can be one of the following:
- A semver version number (ex: 1.23.456)
- prompt: Prompt for the version number (this is the default)
- major: Increase major version
- minor: Increase minor version
- patch: Increase patch version
- premajor: Increase major version, pre-release
- preminor: Increase preminor version, pre-release
- prepatch: Increase prepatch version, pre-release
- prerelease: Increase prerelease version
options:
--preid <name> The identifier for prerelease versions.
Defaults to "beta".
-c, --commit [message] Commit changed files to Git.
Defaults to "release vX.X.X".
-t, --tag [tag] Tag the commit in Git.
The Default tag is "vX.X.X"
-p, --push Push the Git commit.
-a, --all Commit/tag/push ALL pending files,
not just the ones that were bumped.
(same as "git commit -a")
--no-verify Bypass Git commit hooks
(same as "git commit --no-verify")
-v, --version Show the version number
-q, --quiet Suppress unnecessary output
--git-files add git files for include commit
-h, --help Show usage information
--ignore-scripts Bypass version scripts
files...
One or more files and/or globs to bump (ex: README.md *.txt docs/**/*).
Defaults to package.json and package-lock.json.
Examples:
bump patch
Bumps the patch version number in package.json and package-lock.json.
Nothing is committed to git.
bump major --commit
Bumps the major version number in package.json and package-lock.json.
Commits package.json and package-lock.json to git, but does not tag the commit.
bump -tpa README.md
Prompts for the new version number and updates package.json, package-lock.json, and README.md.
Commits ALL modified files to git, tags the commit, and pushes the commit.
bump 4.27.9934 --tag "Version " bower.json docs/**/*.md
Sets the version number to 4.27.9934 in package.json, package-lock.json, bower.json,
and all markdown files in the "docs" directory. Commits the updated files to git,
and tags the commit as "Version 4.27.9934".
`;
/**
* Text describing the program and how to use it
*/
export const helpText = `
${manifest.name} - ${manifest.description}
${usageText}`;
|
nurdiansyah/version-bump-prompt
|
src/manifest.ts
|
<reponame>nurdiansyah/version-bump-prompt<gh_stars>100-1000
// NOTE: We can't `import` the package.json file because it's outside of the "src" directory.
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
const manifest = require("../package.json") as Manifest;
export { manifest };
/**
* The npm package manifest (package.json)
*/
export interface Manifest {
name: string;
version: string;
description: string;
[key: string]: unknown;
}
/**
* Determines whether the specified value is a package manifest.
*/
export function isManifest(obj: any): obj is Manifest {
return obj &&
typeof obj === "object" &&
isOptionalString(obj.name) &&
isOptionalString(obj.version) &&
isOptionalString(obj.description);
}
/**
* Determines whether the specified value is a string, null, or undefined.
*/
function isOptionalString(value: any): value is string | undefined {
let type = typeof value;
return value === null ||
type === "undefined" ||
type === "string";
}
|
balovbohdan/fwd-ann
|
src/lib/calculators/output-errors/calc-errors-with-teacher.ts
|
import {Matrix} from 'matrix-calculus';
import { OutputErrors } from './types';
import { Signals, SignalsErrors } from '../../signals';
type Data = {
output:Signals;
idealOutput:Signals;
};
const calcErrorsMatrix = ({ output, idealOutput }:Data):Matrix => {
const outputMatrix:Matrix = output.getMatrix();
return idealOutput
.getMatrix()
.mutate((unit, row, col) => unit - outputMatrix.get(row || 0, col || 0));
};
const calcErrorsWithTeacher = async ({ output, idealOutput }:Data):Promise<OutputErrors> => {
output.hasTheSameSizeStrict(idealOutput);
const errorsMatrix = calcErrorsMatrix({ output, idealOutput });
const errors = new SignalsErrors(errorsMatrix);
return { errors };
};
export default calcErrorsWithTeacher;
|
balovbohdan/fwd-ann
|
dist/lib/ann/create.d.ts
|
import { ANN } from './ANN';
import * as T from './types';
import { T as TLayers } from '../layers';
import { T as TLayersPairsWeights } from '../weights/layers-pairs-weights';
import { Params as RndWeightParams } from '../weights/layers-pair-weights/rnd/create-rnd-weight';
declare type Data = {
id?: string | null;
layersData: TLayers.LayersRawData;
rndWeightParams?: RndWeightParams;
layersWeightsData?: TLayersPairsWeights.DirtyData;
};
declare const create: (data: Data, params?: T.Params | undefined) => ANN;
export default create;
|
balovbohdan/fwd-ann
|
src/lib/teacher/types.ts
|
import { ANN } from '../ann';
import { Signals } from '../signals';
export type Result = {
ann:ANN;
log:Log;
};
export type Log = Array<{epoch:number, cycle:number, RootMSE:number}>;
export type PreparedParams = {
epoches:number;
};
export type Params = {
epoches?:number;
};
export type Data = {
ann:ANN;
sets:Sets;
};
export type CycleData = {
set:Set;
epoch:number;
cycle:number;
};
export type Sets = Array<Set>;
export type Set = {
task:Signals;
idealOutput:Signals;
};
|
balovbohdan/fwd-ann
|
dist/lib/calculators/ann-output/calc-ann-output.d.ts
|
import { ANN } from '../../ann';
import { Signals } from '../../signals';
export declare type Res = {
output: Signals;
layersInputs: Array<Signals>;
layersOutputs: Array<Signals>;
};
declare type Data = {
ann: ANN;
signals: Signals;
};
declare const calcAnnOutput: ({ ann, signals }: Data) => Promise<Res>;
export default calcAnnOutput;
|
balovbohdan/fwd-ann
|
src/lib/calculators/ann-output/weights-to-signals.ts
|
<filename>src/lib/calculators/ann-output/weights-to-signals.ts
import { Matrix } from 'matrix-calculus';
import { Signals } from '../../signals';
import { Weights } from '../../weights/layers-pair-weights';
type Data = {
weights:Weights;
signals:Signals;
};
const weightsToSignals = (data:Data):Signals => {
const signals:Matrix = data.signals.getMatrix();
const transposedWeights:Matrix = data.weights.getMatrix().transpose();
return new Signals(transposedWeights.multiply(signals));
};
export default weightsToSignals;
|
balovbohdan/fwd-ann
|
src/lib/ann/create.ts
|
<reponame>balovbohdan/fwd-ann
import { ANN } from './ANN';
import * as T from './types';
import createLayers, { T as TLayers } from '../layers';
import createLayersPairsWeights from '../weights/layers-pairs-weights';
import { T as TLayersPairsWeights } from '../weights/layers-pairs-weights';
import { Params as RndWeightParams } from '../weights/layers-pair-weights/rnd/create-rnd-weight';
import createRndLayersWeightsFromLayersRawData from '../weights/layers-pairs-weights/rnd/create-rnd-layers-weights-from-layers-raw-data';
type Data = {
id?:string|null;
layersData:TLayers.LayersRawData;
rndWeightParams?:RndWeightParams;
layersWeightsData?:TLayersPairsWeights.DirtyData;
};
const create = (data:Data, params?:T.Params):ANN => {
const { id, layersData, rndWeightParams, layersWeightsData } = data;
const layers = createLayers(layersData);
const layersWeights = layersWeightsData
? createLayersPairsWeights(layersWeightsData)
: createRndLayersWeightsFromLayersRawData({ layersData, rndWeightParams });
return new ANN({ id, layers, layersWeights }, params);
};
export default create;
|
balovbohdan/fwd-ann
|
src/lib/weights/layers-pairs-weights/create.ts
|
import { Matrix } from 'matrix-calculus';
import { DirtyData } from './types';
import { LayersWeights } from './LayersWeights';
import { Weights } from '../layers-pair-weights';
const create = (data:DirtyData):LayersWeights => {
const weights = createWeights(data);
return new LayersWeights(weights);
};
const createWeights = (data:DirtyData):Array<Weights> =>
data.map(item => new Weights(new Matrix(item)));
export default create;
|
balovbohdan/fwd-ann
|
src/lib/layers/Layers.ts
|
import * as T from './types';
import { Units } from '../units';
export class Layers {
constructor(layers:T.LayersData) {
this.layers = layers;
}
getOutputLayer():Units|never {
const num = this.getQty();
const lastIndex = num - 1;
const layer = this.layers[lastIndex];
if (!layer.isOutput())
throw new LayersError('Failed to look for ANN output layer.');
return layer;
}
getQty():number {
return this.layers.length;
}
getAll():T.LayersData {
return this.layers;
}
getPairs():Array<T.LayersPair> {
const layersQty = this.getQty();
if (layersQty < 2) return [];
const pairs:Array<{left:Units, right:Units, index:number}> = [];
for (let i = 1; i < layersQty; i++) {
const layersPairIndex:number = i - 1;
pairs.push({
right: this.layers[i],
index: layersPairIndex,
left: this.layers[layersPairIndex],
});
}
return pairs;
}
forEach(f:(layer:Units, i?:number, arr?:T.LayersData)=>void):void {
this.layers.forEach(f);
}
forEachPair(f:(layersPair:T.LayersPair)=>void):void {
return this.getPairs().forEach(f);
}
map(f:(layer:Units, i?:number, arr?:T.LayersData)=>any):Array<any> {
return this.layers.map(f);
}
mapPairs(f:(layersPair:T.LayersPair)=>any):Array<any> {
return this.getPairs().map(f);
}
private readonly layers:T.LayersData;
}
class LayersError extends Error {
constructor(message:string) {
super(message);
Object.setPrototypeOf(this, LayersError.prototype);
}
}
|
balovbohdan/fwd-ann
|
dist/lib/weights/layers-pairs-weights/rnd/create-rnd-layers-weights-from-layers-raw-data.d.ts
|
import { T as TLayers } from '../../../layers';
import { LayersWeights } from '../LayersWeights';
import { Params as RndWeightsParams } from '../../layers-pair-weights/rnd/create-rnd-weight';
declare type Params = {
layersData: TLayers.LayersRawData;
rndWeightParams?: RndWeightsParams;
};
declare const createRndLayersWeightsFromLayersRawData: (params: Params) => LayersWeights;
export default createRndLayersWeightsFromLayersRawData;
|
balovbohdan/fwd-ann
|
dist/lib/ann/index.d.ts
|
<filename>dist/lib/ann/index.d.ts
import * as T from './types';
export { T };
export { ANN } from './ANN';
export { default } from './create';
|
balovbohdan/fwd-ann
|
dist/lib/teacher/Teacher.d.ts
|
import * as T from './types';
export declare class Teacher {
static teach(data: T.Data, params?: T.Params): Promise<T.Result>;
private constructor();
private teach;
private doTeach;
private startCycle;
private static prepareParams;
private log;
private readonly ann;
private readonly teachingDatasets;
private readonly params;
}
|
balovbohdan/fwd-ann
|
src/lib/signals/index.ts
|
export { Signals } from './Signals';
export { Mutator } from './mutators';
export { SignalsErrors } from './SignalsErrors';
|
balovbohdan/fwd-ann
|
dist/lib/calculators/back-error-propagation/calc-updated-weights.d.ts
|
<gh_stars>0
import { ANN } from '../../ann';
import { LayersPair } from '../../layers/types';
import { Signals, SignalsErrors } from '../../signals';
import { Weights } from '../../weights/layers-pair-weights';
declare type Data = {
ann: ANN;
errors: SignalsErrors;
layersPair: LayersPair;
layersOutputs: Array<Signals>;
};
declare const calcUpdatedWeights: (data: Data) => Promise<Weights>;
export default calcUpdatedWeights;
|
balovbohdan/fwd-ann
|
dist/lib/weights/layers-pair-weights/rnd/create-rnd-weights.d.ts
|
import { Weights } from '../Weights';
import { Params as RndWeightParams } from './create-rnd-weight';
export declare type Params = {
leftUnitsQty: number;
rightUnitsQty: number;
rndWeightParams?: RndWeightParams;
};
declare const createRndWeights: (params: Params) => Weights | null;
export default createRndWeights;
|
balovbohdan/fwd-ann
|
dist/lib/calculators/output-errors/calc-errors-with-teacher.d.ts
|
<gh_stars>0
import { OutputErrors } from './types';
import { Signals } from '../../signals';
declare type Data = {
output: Signals;
idealOutput: Signals;
};
declare const calcErrorsWithTeacher: ({ output, idealOutput }: Data) => Promise<OutputErrors>;
export default calcErrorsWithTeacher;
|
balovbohdan/fwd-ann
|
src/lib/weights/layers-pair-weights/rnd/create-rnd-weight.ts
|
<gh_stars>0
import { assignDeep } from '../../../../utils/object-utils';
import { floating } from '../../../../utils/math-utils/random-number';
export type Params = {
min?:number;
max?:number;
leftUnitsQty?:number;
rightUnitsQty?:number;
exclude?:Array<number>;
};
type ParamsPrepared = {
min:number;
max:number;
exclude?:Array<number>;
};
const defParams:Params = {
min: -1,
max: 1,
exclude: [0],
leftUnitsQty: 0,
rightUnitsQty: 0,
};
const prepareParams = (params:Params = {}):ParamsPrepared => {
params = assignDeep(defParams, params);
if (params.leftUnitsQty) {
const limit:number = 1 / Math.sqrt(params.leftUnitsQty);
params.max = limit;
params.min = -limit;
}
const preparedParams:{min:number, max:number, exclude?:Array<number>} = {
min: params.min || 0,
max: params.max || 0,
};
if (params.exclude)
preparedParams.exclude = params.exclude;
return preparedParams;
};
const createRndWeight = (params:Params) => {
const paramsPrepared = prepareParams(params);
return floating(paramsPrepared);
};
export default createRndWeight;
|
balovbohdan/fwd-ann
|
src/lib/signals/mutators.ts
|
<reponame>balovbohdan/fwd-ann
import { Signals } from './Signals';
import { funcs } from 'math-funcs-calculus';
export type Mutator = (signals:Signals, Func?:Func)=>Signals;
type Func = {
calc:Function;
};
const { Logistic, RationalSigmoid } = funcs;
export const mutator:Mutator = (signals:Signals, Func:Func = RationalSigmoid):Signals => {
const signalsData = signals
.getMatrix()
.mutate(Func.calc.bind(Func));
return new Signals(signalsData);
};
export const logistic = (signals:Signals):Signals =>
mutator(signals, Logistic);
export const rationalSigmoid = (signals:Signals):Signals =>
mutator(signals, RationalSigmoid);
|
balovbohdan/fwd-ann
|
src/lib/calculators/back-error-propagation/calc-layers-output-errors.ts
|
import { ANN } from '../../ann';
import { SignalsErrors } from '../../signals';
import calcLayerOutputErrors from './calc-layer-output-errors';
export type Res = Array<SignalsErrors>|null;
type Data = {
ann:ANN;
outputErrors:SignalsErrors|null;
};
const calcLayersOutputErrors = async ({ ann, outputErrors }:Data):Promise<Res> => {
if (!outputErrors)
return null;
const layers = ann.getLayers().getAll();
const layersQty = layers.length;
const layersErrors:Array<SignalsErrors> = (new Array(layersQty)).fill(null);
for (let i = layersQty - 1; i >= 0; i--) {
const layer = layers[i];
const nextItemIndex = i + 1;
const isOutputLayer = layer.isOutput();
const layerErrors = calcLayerOutputErrors({
ann,
aimLayer: layer,
layersPairIndex: isOutputLayer ? null : i,
nextLayerOutputErrors: isOutputLayer
? outputErrors
: layersErrors[nextItemIndex],
});
if (layerErrors)
layersErrors[i] = layerErrors;
}
return layersErrors;
};
export default calcLayersOutputErrors;
|
balovbohdan/fwd-ann
|
dist/lib/units/Units.d.ts
|
<reponame>balovbohdan/fwd-ann
import * as T from './types';
import { Unit } from './Unit';
import { Signals } from '../signals';
import { LayerType } from '../layers';
import { ActivationFunction } from '../activation-funcs';
export declare class Units {
constructor(data: T.UnitsRaw);
getNames(): Array<string>;
getActivationFunction(): ActivationFunction | null;
map(f: (unit: Unit, i?: number, units?: T.UnitsData) => any): Array<any>;
forEach(f: (unit: Unit, i?: number, units?: T.UnitsData) => void): void;
get(i: number): Unit;
getQty(): number;
getType(): LayerType;
activateSignals(signals: Signals): Signals;
isInput(): boolean;
isOutput(): boolean;
isHidden(): boolean;
calcOutput(input: Signals): Signals;
private activateSignal;
private readonly name;
private readonly type;
private readonly units;
}
|
balovbohdan/fwd-ann
|
src/lib/signals/normalize.ts
|
<filename>src/lib/signals/normalize.ts
import { Signals } from './Signals';
import { rationalSigmoid, Mutator } from './mutators';
const normalize = (signals:Signals, mutator:Mutator|null = rationalSigmoid):Signals =>
(mutator || rationalSigmoid)(signals);
export default normalize;
|
balovbohdan/fwd-ann
|
dist/lib/layers/types.d.ts
|
<reponame>balovbohdan/fwd-ann
import { Units } from '../units';
import { Data as LayerData } from '../units/create';
export declare type LayersPair = {
left: Units;
right: Units;
index: number;
};
export declare type LayersData = Array<Units>;
export declare type LayersRawData = Readonly<ReadonlyArray<LayerData>>;
|
balovbohdan/fwd-ann
|
src/lib/units/Units.ts
|
<reponame>balovbohdan/fwd-ann<filename>src/lib/units/Units.ts
import * as T from './types';
import { Unit } from './Unit';
import { Signals } from '../signals';
import { LayerType } from '../layers';
import { ActivationFunction } from '../activation-funcs';
import { decimal } from '../../utils/math-utils/random-number';
export class Units {
constructor(data:T.UnitsRaw) {
this.units = data.units;
this.type = data.type;
this.name = data.name || 'Units-' + decimal();
}
getNames():Array<string> {
return this.map(unit => unit.getName());
}
/**
* DO NOTICE!
* This method returns activation function class of the first unit!
* It you need more detailed information you have to inspect every unit.
*/
getActivationFunction():ActivationFunction|null {
try {
return this.units[0].getActivationFunction() || null;
} catch (e) {
console.warn('Failed to get activation function of ANN unit.', e);
return null;
}
}
map(f:(unit:Unit, i?:number, units?:T.UnitsData)=>any):Array<any> {
return this.units.map(f);
}
forEach(f:(unit:Unit, i?:number, units?:T.UnitsData)=>void) {
this.units.forEach(f);
}
get(i:number):Unit {
return this.units[i] || null;
}
getQty():number {
return this.units.length;
}
getType():LayerType {
return this.type;
}
activateSignals(signals:Signals):Signals {
const activatedSignalsData = signals
.getMatrix()
.mutate(this.activateSignal);
return new Signals(
activatedSignalsData,
signals.getNames()
);
}
isInput():boolean {
return this.getType() === LayerType.INPUT;
}
isOutput():boolean {
return this.getType() === LayerType.OUTPUT;
}
isHidden():boolean {
return this.getType() === LayerType.HIDDEN;
}
calcOutput(input:Signals):Signals {
if (this.getQty() !== input.getQty())
throw new UnitsError('Units number and input signals number mismatch.');
const outputSignals:Array<number> = this.map((unit, i) =>
unit.getActivationFunction()
.calc(input.get(i || 0))
);
return Signals.create(outputSignals);
}
private activateSignal = (signal:number, row:number):number => {
try {
return this.get(row)
.getActivationFunction()
.calc(signal);
} catch (e) {
console.warn('Failed to mutate ANN signal.', e);
return 0;
}
};
private readonly name:string;
private readonly type:LayerType;
private readonly units:T.UnitsData;
}
class UnitsError extends Error {
constructor(message:string) {
super(message);
Object.setPrototypeOf(this, UnitsError.prototype);
}
}
|
balovbohdan/fwd-ann
|
dist/lib/calculators/back-error-propagation/calc-layer-output-errors.d.ts
|
import { ANN } from '../../ann';
import { Units } from '../../units';
import { SignalsErrors } from '../../signals';
declare type Data = {
ann: ANN;
aimLayer: Units;
layersPairIndex: number | null;
nextLayerOutputErrors: SignalsErrors;
};
declare const calcLayerOutputErrors: (data: Data) => SignalsErrors | null;
export default calcLayerOutputErrors;
|
balovbohdan/fwd-ann
|
src/utils/id-generator.ts
|
const generate = (length:number = 10):string => {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let txt = '';
for (let i = 0; i < length; i++) {
txt += possible.charAt(
Math.floor(
Math.random() * possible.length
)
);
}
return txt;
};
export default generate;
|
balovbohdan/fwd-ann
|
dist/lib/signals/mutators.d.ts
|
<filename>dist/lib/signals/mutators.d.ts
import { Signals } from './Signals';
export declare type Mutator = (signals: Signals, Func?: Func) => Signals;
declare type Func = {
calc: Function;
};
export declare const mutator: Mutator;
export declare const logistic: (signals: Signals) => Signals;
export declare const rationalSigmoid: (signals: Signals) => Signals;
export {};
|
balovbohdan/fwd-ann
|
src/lib/layers/index.ts
|
import * as T from './types';
export { T };
export { Layers } from './Layers';
export { default } from './create';
export { LayerName } from './LayerName';
export { LayerType } from './LayerType';
|
balovbohdan/fwd-ann
|
src/lib/signals/Signals.ts
|
import { matrixFactories, Matrix } from 'matrix-calculus';
import normalize from './normalize';
import { Mutator } from './mutators';
import { clone } from '../../utils/object-utils';
const { SingleColMatrixFactory } = matrixFactories;
export class Signals {
static create(signals:Array<number>, names:Array<string> = []) {
const signalsMatrix = SingleColMatrixFactory.create(signals);
return new Signals(signalsMatrix, names);
}
constructor(signals:Matrix, names:Array<string> = []) {
this.signals = signals;
this.names = names || [];
}
getNames():Array<string> {
return clone(this.names);
}
setNames(names:Array<string>) {
if (names.length !== this.getQty())
throw new SignalsError('Names and units quantity mismatch.');
this.names = names;
}
get(i:number):number {
return this.getMatrix().get(i, 0);
}
getMatrix():Matrix {
return this.signals.getClone();
}
getQty():number {
return this.getMatrix().getUnitsQty();
}
normalize(mutator?:Mutator|null):Signals {
return normalize(this, mutator);
}
/**
* Adds offset to the signals.
* It is needed to prevent zero signals.
* Zero signals 'kills' ability of the ANN to learn.
*/
offset(offset:number = .1):Signals {
const signals = this.getMatrix().sum(offset);
return new Signals(signals);
}
hasTheSameSizeStrict(signals:Signals):Signals|never {
if (this.hasTheSameSize(signals))
return this;
throw new SignalsError('ANN signals have different sizes.');
}
hasTheSameSize(signals:Signals):boolean {
const matrix = signals.getMatrix();
return this.getMatrix().hasTheSameDimensions(matrix);
}
sortByNames():Signals|never {
const namedSignals:{[key:string]:number} = this.getNamedSignalsData();
const namesSorted:Array<string> = this.getNames().sort();
const sortedSignalsData:Array<number> = namesSorted
.map(name => +namedSignals[name] || 0);
const sortedSignalsMatrix:Matrix = SingleColMatrixFactory.create(sortedSignalsData);
return new Signals(sortedSignalsMatrix, namesSorted);
}
private getNamedSignalsData():{[key:string]:number}|never {
if (!this.names || this.names.length <= 0)
throw new SignalsError('Got invalid signals names.');
const names:Array<string> = this.getNames();
const namedSignals:{[key:string]:number} = {};
const signals:Array<number> = this.getMatrix().getPlainData();
names.forEach((name, i) => namedSignals[name] = signals[i]);
return namedSignals;
}
private names:Array<string>;
private readonly signals:Matrix;
}
class SignalsError extends Error {
constructor(message:string) {
super(message);
Object.setPrototypeOf(this, Signals.prototype);
}
}
|
balovbohdan/fwd-ann
|
src/lib/layers/create.ts
|
<gh_stars>0
import * as T from './types';
import { Layers } from './Layers';
import createUnits from '../units/create';
const create = (data:T.LayersRawData):Layers => {
const layersRawData = makeData(data);
return new Layers(layersRawData);
};
const makeData = (data:T.LayersRawData):T.LayersData => {
const layersData:T.LayersData = [];
data.forEach(layerData => layersData.push(createUnits(layerData)));
return layersData;
};
export default create;
|
balovbohdan/fwd-ann
|
dist/lib/layers/create.d.ts
|
<filename>dist/lib/layers/create.d.ts
import { Layers } from './Layers';
declare const create: (data: readonly import("../units/create").Data[]) => Layers;
export default create;
|
balovbohdan/fwd-ann
|
dist/config.d.ts
|
<filename>dist/config.d.ts
declare const config: Readonly<{
ann: {
defParams: {
learningSpeed: number;
inputSignals: {
offset: number;
needOffset: boolean;
needNormalize: boolean;
normalizer: (signals: import(".").Signals) => import(".").Signals;
};
};
};
teacher: {
defParams: {
epoches: number;
};
};
}>;
export default config;
|
balovbohdan/fwd-ann
|
dist/lib/calculators/back-error-propagation/calc-updated-layers-weights.d.ts
|
<reponame>balovbohdan/fwd-ann
import { ANN } from '../../ann';
import { Signals, SignalsErrors } from '../../signals';
import { LayersWeights } from '../../weights/layers-pairs-weights';
declare type Data = {
ann: ANN;
input: Signals;
errors: SignalsErrors | null;
};
declare const calcUpdatedLayersWeights: ({ ann, input, errors }: Data) => Promise<LayersWeights>;
export default calcUpdatedLayersWeights;
|
balovbohdan/fwd-ann
|
src/utils/math-utils/arithmetic-average.ts
|
type Calculator = (numbers:Array<number>)=>number;
export const simple = (values:Array<number>):number => {
const len = values.length;
if (len <= 0)
throw new ArithmeticAverageError('Failed to calc "Simple Arithmetic Average" value. Got empty numbers array.');
try {
return values.reduce((sum, n) => (sum + +n), 0) / len;
} catch (e) {
throw new ArithmeticAverageError(e.message);
}
};
export const crossed = (left:Array<number>, right:Array<number>, calc?:Calculator):Array<number> => {
if (left.length !== right.length)
throw new ArithmeticAverageError('Numbers qty mismatch.');
const doCalc:Calculator = calc || simple;
try {
return left.map((n, i) => doCalc([+n, +right[i]]));
} catch (e) {
throw new ArithmeticAverageError(e.message);
}
};
class ArithmeticAverageError extends Error {
constructor(message:string) {
super(message);
this.message = message;
this.stack = (new Error()).stack;
}
readonly message:string;
readonly stack:string|undefined;
}
|
balovbohdan/fwd-ann
|
src/lib/weights/layers-pairs-weights/LayersWeights.ts
|
import * as T from './types';
import { Weights } from '../layers-pair-weights';
export class LayersWeights {
constructor(layersWeights:T.Data) {
this.weights = layersWeights;
}
get(layersPairIndex:number|null):Weights|null {
return layersPairIndex === null
? null
: this.weights[layersPairIndex] || null;
}
getAllDirty():T.DirtyData {
return this.weights.map(weights => weights.getMatrix().getData());
}
getAll():Array<Weights> {
return this.weights;
}
private readonly weights:T.Data;
}
|
balovbohdan/fwd-ann
|
dist/lib/calculators/back-error-propagation/calc-theta.d.ts
|
<gh_stars>0
import { Matrix } from 'matrix-calculus';
import { Signals } from '../../signals';
import { LayersPair } from '../../layers/types';
declare type Data = {
output: Signals;
layersPair: LayersPair;
};
declare const calcTheta: ({ output, layersPair }: Data) => Matrix;
export default calcTheta;
|
balovbohdan/fwd-ann
|
dist/utils/object-utils.d.ts
|
<filename>dist/utils/object-utils.d.ts
export declare const clone: <T extends object>(obj: T) => T;
export declare const assignDeep: <T extends object>(target: object, source: object, concatArrays?: boolean) => T;
export declare const freezeDeep: <T extends Object>(obj: {
[key: string]: any;
} & T) => Readonly<T>;
|
balovbohdan/fwd-ann
|
src/lib/calculators/back-error-propagation/calc-updated-layers-weights.ts
|
<filename>src/lib/calculators/back-error-propagation/calc-updated-layers-weights.ts
import { ANN, T as TANN } from '../../ann';
import { Signals, SignalsErrors } from '../../signals';
import calcUpdatedWeights from './calc-updated-weights';
import { LayersWeights, T as TLayersWeights } from '../../weights/layers-pairs-weights';
import calcLayersOutputErrors, { Res as LayersErrors } from './calc-layers-output-errors';
type Data = {
ann:ANN;
input:Signals;
errors:SignalsErrors|null;
};
type Res = LayersWeights;
type LayersOutputs = Array<Signals>;
const getLayersPairErrors = (layersErrors:LayersErrors, layersPairIndex:number):SignalsErrors|never => {
const errors = layersErrors
? layersErrors[layersPairIndex + 1]
: null;
if (errors)
return errors;
throw new UpdatedLayersWeightsError('Got invalid ANN layers pair output errors.');
};
const getLayersPairOutputs = (layersOutputs:LayersOutputs, layersPairIndex:number):Array<Signals>|never => {
if (!layersOutputs)
throw new UpdatedLayersWeightsError('Got invalid ANN layers outputs.');
const left = layersOutputs[layersPairIndex];
const right = layersOutputs[layersPairIndex + 1];
if (!left)
throw new UpdatedLayersWeightsError('Got invalid ANN layers pair left output.');
if (!right)
throw new UpdatedLayersWeightsError('Got invalid ANN layers pair right output.');
return [left, right];
};
const calcLayersPairs = async (layersErrors:LayersErrors, layersOutputs:LayersOutputs, ann:ANN)
:Promise<TLayersWeights.Data> => {
let promise:any = Promise.resolve();
const updatedLayersWeightsData:TLayersWeights.Data = [];
ann.getLayers().forEachPair(layersPair => {
return promise = promise
.then(async () => {
const updatedWeights = await calcUpdatedWeights({
ann,
layersPair,
errors: getLayersPairErrors(layersErrors, layersPair.index),
layersOutputs: getLayersPairOutputs(layersOutputs, layersPair.index || 0),
});
updatedLayersWeightsData.push(updatedWeights);
});
});
await promise;
return updatedLayersWeightsData;
};
const calcUpdatedLayersWeights = async ({ ann, input, errors }:Data):Promise<Res> => {
if (!input)
throw new UpdatedLayersWeightsError('Got invalid ANN input.');
if (!errors)
return ann.getLayersWeights();
const complexOutput:TANN.ComplexOutput = await ann.calcComplexOutput(input);
const layersErrors:LayersErrors = await calcLayersOutputErrors({
ann,
outputErrors: errors,
});
const layersWeightsData = await calcLayersPairs(layersErrors, complexOutput.layersOutputs, ann);
return new LayersWeights(layersWeightsData);
};
class UpdatedLayersWeightsError extends Error {
constructor(message:string) {
super(message);
Object.setPrototypeOf(this, UpdatedLayersWeightsError.prototype);
}
}
export default calcUpdatedLayersWeights;
|
balovbohdan/fwd-ann
|
src/utils/math-utils/number-capacity.ts
|
<filename>src/utils/math-utils/number-capacity.ts
export const getCapacity = (n:number):number =>
sign(n) * Math.abs(Math.floor(n)).toString().length;
export const getCapacityBase = (capacity:number):number =>
capacity === 1
? 1
: Math.pow(10, capacity);
export const getNumberByCapacity = (capacity:number):number =>
Math.pow(10, capacity);
export const getBaseCapacityNumber = (n:number):number =>
getNumberByCapacity(getCapacity(n));
export const sign = (n:number):number =>
n === 0 || isNaN(n)
? n
: n > 0 ? 1 : -1;
|
balovbohdan/fwd-ann
|
dist/lib/calculators/back-error-propagation/calc-layers-output-errors.d.ts
|
import { ANN } from '../../ann';
import { SignalsErrors } from '../../signals';
export declare type Res = Array<SignalsErrors> | null;
declare type Data = {
ann: ANN;
outputErrors: SignalsErrors | null;
};
declare const calcLayersOutputErrors: ({ ann, outputErrors }: Data) => Promise<Res>;
export default calcLayersOutputErrors;
|
balovbohdan/fwd-ann
|
src/examples/numbers.ts
|
import createANN from '../lib/ann';
import { Signals } from '../lib/signals';
import { Teacher } from '../lib/teacher';
import { LayerType } from '../lib/layers';
import { activationFuncs } from '../lib/activation-funcs';
const { ReLU } = activationFuncs;
const config = {
ann: {
params: {
learningSpeed: .1,
},
data: {
id: 'ExampleANN',
layersData: [
{
type: LayerType.INPUT,
unitsData: [{
qty: 6,
ActivationFunction: ReLU,
}],
},
{
type: LayerType.HIDDEN,
unitsData: [{
qty: 7,
ActivationFunction: ReLU,
}],
},
{
type: LayerType.OUTPUT,
unitsData: [{
qty: 1,
ActivationFunction: ReLU,
}],
},
],
},
},
teacher: {
params: {
epoches: 200,
},
testSet: [
[0, 0, 0, 0, 0, 0, 0],
[.1, 1, 1, 0, 0, 0, 0],
[.2, 0, 0, 1, 1, 0, 0],
[.3, 0, 0, 0, 0, 1, 1],
],
data: {
sets: [
{
task: Signals.create([0, 0, 0, 0, 0, 0]),
idealOutput: Signals.create([0]),
},
{
task: Signals.create([1, 1, 0, 0, 0, 0]),
idealOutput: Signals.create([.1]),
},
{
task: Signals.create([0, 0, 1, 1, 0, 0]),
idealOutput: Signals.create([.2]),
},
{
task: Signals.create([0, 0, 0, 0, 1, 1]),
idealOutput: Signals.create([.3]),
},
],
},
},
};
const ann = createANN(config.ann.data, config.ann.params);
Teacher.teach({ ann, ...config.teacher.data }, config.teacher.params)
.then(({ ann }) => {
for (let units of config.teacher.testSet) {
const expectedOutput = units[0];
const input = Signals.create(units.slice(1));
ann.calcOutput(input)
.then(signals => {
const output = Math.round(signals.getMatrix().get(0, 0) * 100) / 100;
console.log(`${units} -> output: ${output}; expected: ${expectedOutput}`);
});
}
});
|
balovbohdan/fwd-ann
|
src/config.ts
|
<reponame>balovbohdan/fwd-ann
import { freezeDeep } from './utils/object-utils';
import { rationalSigmoid } from './lib/signals/mutators';
const config = freezeDeep({
ann: {
defParams: {
learningSpeed: 1,
inputSignals: {
offset: .1,
needOffset: true,
needNormalize: true,
normalizer: rationalSigmoid,
},
},
},
teacher: {
defParams: {
epoches: 10000,
},
},
});
export default config;
|
balovbohdan/fwd-ann
|
src/lib/units/types.ts
|
import { Unit } from './Unit';
import { LayerType } from '../layers';
export type UnitsData = Array<Unit>;
export type UnitsRaw = {
name?:string;
type:LayerType;
units:UnitsData;
};
|
balovbohdan/fwd-ann
|
dist/lib/calculators/ann-output/calc-layers-pair.d.ts
|
import { ANN } from '../../ann';
import { Signals } from '../../signals';
import { LayersPair } from '../../layers/types';
declare type Data = {
ann: ANN;
signals: Signals;
layersPair: LayersPair;
};
declare type Res = {
dirtyOutput: Signals;
layersInputs: Array<Signals>;
layersOutputs: Array<Signals>;
};
declare const calcLayersPair: ({ ann, signals, layersPair }: Data) => Res;
export default calcLayersPair;
|
balovbohdan/fwd-ann
|
dist/utils/math-utils/numbers-collection-alias.d.ts
|
<filename>dist/utils/math-utils/numbers-collection-alias.d.ts
export declare const encode: (numbers: number[]) => number;
export declare const decode: (cipher: number) => number[];
|
balovbohdan/fwd-ann
|
src/lib/weights/layers-pairs-weights/rnd/create-rnd-layers-weights.ts
|
import { LayersWeights } from '../LayersWeights';
import { Weights } from '../../layers-pair-weights';
import createRndWeights, { Params as RndWeightsParams } from '../../layers-pair-weights/rnd/create-rnd-weights';
export type Params = Array<RndWeightsParams>;
const createRndLayersWeightsData = (params:Params):Array<Weights> => {
const weightsCollection:Array<Weights> = [];
for (let paramsPart of params) {
const weights:Weights|null = createRndWeights(paramsPart);
if (weights === null) continue;
weightsCollection.push(weights);
}
return weightsCollection;
};
const createRndLayersWeights = (params:Params) => {
const data = createRndLayersWeightsData(params);
return new LayersWeights(data);
};
export default createRndLayersWeights;
|
balovbohdan/fwd-ann
|
src/utils/math-utils/random-number.ts
|
import { assignDeep } from '../object-utils';
import * as capacityUtils from './number-capacity';
type ValidParams = {
exclude?:Array<number>;
};
type FloatingParams = {
min?:number;
max?:number;
exclude?:Array<number>;
};
type DecimalParameterizedParams = {
min?:number;
max?:number;
exclude?:Array<number>;
};
type GetMaxSafeIntegerParams = {
min:number;
max:number;
};
export const decimal = ():number =>
Math.abs(Math.random() * Date.now() >> 0);
export const sign = () =>
Math.random() < .5 ? -1 : 1;
// https://learn.javascript.ru/task/random-int-min-max
export const decimalWithParams = (params:DecimalParameterizedParams = {}):number => {
const {min, max, exclude} = assignDeep({ min: 0, max: 1 }, params);
const n = Math.floor(min + Math.random() * (max + 1 - min));
return valid(n, { exclude })
? n
: floating(params);
};
export const floating = (params?:FloatingParams):number => {
const {min, max, exclude} = assignDeep({ min: .001, max: 1 }, params || {});
const base = getMaxSafeInteger({ min, max });
let n = decimalWithParams({ min: min * base, max: max * base }) / base;
return valid(n, { exclude })
? n
: floating(params);
};
const valid = (n:number, params?:ValidParams):boolean =>
params
? !(params.exclude && params.exclude.includes(n))
: true;
const getMaxSafeInteger = (params:GetMaxSafeIntegerParams):number =>
Math.min(
Number.MAX_SAFE_INTEGER - capacityUtils.getBaseCapacityNumber(params.min),
Number.MAX_SAFE_INTEGER - capacityUtils.getBaseCapacityNumber(params.max)
);
|
balovbohdan/fwd-ann
|
src/lib/teacher/Teacher.ts
|
<reponame>balovbohdan/fwd-ann<gh_stars>0
import { errors } from 'math-funcs-calculus';
import { ANN } from '../ann';
import * as T from './types';
import config from '../../config';
import { assignDeep } from '../../utils/object-utils';
import calcErrorsWithTeacher from '../calculators/output-errors/calc-errors-with-teacher';
import calcUpdatedLayersWeights from '../calculators/back-error-propagation/calc-updated-layers-weights';
export class Teacher {
static teach(data:T.Data, params?:T.Params):Promise<T.Result> {
const teacher = new Teacher(data, params);
return teacher.teach();
}
private constructor(data:T.Data, params?:T.Params) {
this.ann = data.ann;
this.teachingDatasets = data.sets;
this.params = Teacher.prepareParams(params);
}
private async teach():Promise<T.Result> {
await this.doTeach();
return {
ann: this.ann,
log: this.log,
};
}
private doTeach() {
const { epoches } = this.params;
const cycles:number = this.teachingDatasets.length;
let promise:Promise<Teacher> = Promise.resolve(this);
for (let epoch = 0; epoch < epoches; epoch++) {
for (let cycle = 0; cycle < cycles; cycle++) {
promise = promise.then(
() => this.startCycle({
set: this.teachingDatasets[cycle],
epoch,
cycle,
})
);
}
}
return promise;
}
private async startCycle(data:T.CycleData):Promise<Teacher> {
const input = data.set.task;
const output = await this.ann.calcOutput(input);
const outputErrorsData = await calcErrorsWithTeacher({
output,
idealOutput: data.set.idealOutput,
});
const updatedLayersWeights = await calcUpdatedLayersWeights({
input,
ann: this.ann,
errors: outputErrorsData.errors,
});
if (!updatedLayersWeights)
throw new TeacherError('Got invalid updated ANN layers weights.');
this.log.push({
epoch: data.epoch,
cycle: data.cycle,
RootMSE: errors.RootMSE.calc(
data.set.idealOutput.getMatrix().getPlainData(),
output.getMatrix().getPlainData()
),
});
this.ann.setLayersWeights(updatedLayersWeights);
return this;
}
private static prepareParams(params:T.Params = {}):T.PreparedParams|never {
const mergedParams:T.PreparedParams = assignDeep(config.teacher.defParams, params);
if (mergedParams.epoches <= 0)
throw new TeacherError('Got invalid epoches qty.');
return mergedParams;
}
private log:T.Log = [];
private readonly ann:ANN;
private readonly teachingDatasets:T.Sets;
private readonly params:T.PreparedParams;
}
class TeacherError extends Error {
constructor(message:string) {
super(message);
Object.setPrototypeOf(this, TeacherError.prototype);
}
}
|
balovbohdan/fwd-ann
|
dist/lib/weights/layers-pair-weights/Weights.d.ts
|
<reponame>balovbohdan/fwd-ann<filename>dist/lib/weights/layers-pair-weights/Weights.d.ts
import { Matrix } from 'matrix-calculus';
export declare class Weights {
constructor(weights: Matrix);
getMatrix(): Matrix;
private readonly weights;
}
|
balovbohdan/fwd-ann
|
src/utils/math-utils/aaw.ts
|
// 'Arithmetic Average Weighted' calculator.
import { clone } from '../object-utils';
type Data = {
values:Array<number>;
weights:Array<number>;
};
const calc = (weights:Array<number>, values:Array<number>) => {
const { weights: w, values: v } = prepareData(weights, values);
if (w.length === 0)
throw new AAWError('Got invalid weights.', v, w);
if (v.length === 0)
throw new AAWError('Got invalid values.', v, w);
const divider = w.reduce((sum, w) => sum + w, 0);
const dividend = v.reduce((sum, v, i) => sum + v * w[i], 0);
const aaw = dividend / divider;
if (!Number.isFinite(aaw))
throw new AAWError('Failed to calc "Arithmetic Average Weighted".', v, w);
return aaw;
};
const prepareData = (weights:Array<number>, values:Array<number>):Data => {
const valuesClone = clone(values);
const weightsClone = clone(weights);
return {
values: valuesClone,
weights: valuesClone.map((value, i) => Number.isFinite(weightsClone[i]) ? weightsClone[i] : 1),
};
};
class AAWError extends Error {
constructor(message:string, weights:Array<number>, values:Array<number>) {
super(message);
this.message = message;
this.weights = weights;
this.values = values;
this.stack = (new Error()).stack;
}
readonly message:string;
readonly values:Array<number>;
readonly weights:Array<number>;
readonly stack:string|undefined;
}
export default calc;
|
balovbohdan/fwd-ann
|
dist/lib/ann/ANN.d.ts
|
<filename>dist/lib/ann/ANN.d.ts
import * as T from './types';
import { Layers } from '../layers';
import { Signals } from '../signals';
import { LayersWeights } from '../weights/layers-pairs-weights';
export declare class ANN {
constructor(data: T.Data, params?: T.Params);
getId(): string | null;
setId(id: string): void;
getLayers(): Layers;
getLayersWeights(): LayersWeights;
setLayersWeights(layersWeights: LayersWeights): ANN;
getLearningSpeed(): number;
calcOutput(input: Signals): Promise<Signals>;
calcComplexOutput(input: Signals): Promise<T.ComplexOutput>;
private prepareInputSignals;
private static prepareData;
private id;
private layersWeights;
private readonly name;
private readonly layers;
private readonly params;
}
|
balovbohdan/fwd-ann
|
src/lib/calculators/back-error-propagation/calc-updated-weights.ts
|
import { Matrix } from 'matrix-calculus';
import { ANN } from '../../ann';
import { LayersPair } from '../../layers/types';
import calcDeltaWeights from './calc-delta-weights';
import { Signals, SignalsErrors } from '../../signals';
import { Weights } from '../../weights/layers-pair-weights';
type Data = {
ann:ANN;
errors:SignalsErrors;
layersPair:LayersPair;
layersOutputs:Array<Signals>;
};
const calcUpdatedWeightsData = ({ ann, errors, layersPair, layersOutputs }:Data):Matrix => {
const layersPairWeights = ann.getLayersWeights().get(layersPair.index);
if (!layersPairWeights)
throw new UpdatedWeightsError('Got invalid ANN layers pair weights.');
const deltaWeights:Matrix|null = calcDeltaWeights({
ann,
errors,
layersPair,
layersOutputs,
});
const oldWeights:Matrix = layersPairWeights.getMatrix();
return deltaWeights
? oldWeights.sum(deltaWeights)
: oldWeights;
};
const calcUpdatedWeights = async (data:Data):Promise<Weights> => {
const weightsData = calcUpdatedWeightsData(data);
return new Weights(weightsData);
};
class UpdatedWeightsError extends Error {
constructor(message:string) {
super(message);
Object.setPrototypeOf(this, UpdatedWeightsError.prototype);
}
}
export default calcUpdatedWeights;
|
balovbohdan/fwd-ann
|
dist/lib/weights/layers-pairs-weights/utils.d.ts
|
<gh_stars>0
import { LayersWeights } from './LayersWeights';
export declare const isIdentical: (left: LayersWeights, right: LayersWeights) => Promise<boolean>;
export declare const hasTheSameSizeStrict: (left: LayersWeights, right: LayersWeights) => boolean;
export declare const hasTheSameSize: (left: LayersWeights, right: LayersWeights) => boolean;
|
balovbohdan/fwd-ann
|
src/lib/calculators/back-error-propagation/calc-theta.ts
|
// https://docs.google.com/document/d/1DSlzdK0LM1GqxDPES9GFLvuniNYoJNe5kEUfMS4FWsM
import { Matrix } from 'matrix-calculus';
import { Signals } from '../../signals';
import { LayersPair } from '../../layers/types';
type Data = {
output:Signals;
layersPair:LayersPair;
};
const calcTheta = ({ output, layersPair }:Data):Matrix => {
const ActivationFunc = layersPair.right.getActivationFunction();
if (!ActivationFunc)
throw new ThetaError('Got invalid activation function.');
const matrix = output.getMatrix();
return ActivationFunc.calcComplexDerivative(matrix);
};
class ThetaError extends Error {
constructor(message:string) {
super(message);
Object.setPrototypeOf(this, ThetaError.prototype);
}
}
export default calcTheta;
|
balovbohdan/fwd-ann
|
dist/lib/weights/layers-pair-weights/rnd/create-rnd-weight.d.ts
|
<filename>dist/lib/weights/layers-pair-weights/rnd/create-rnd-weight.d.ts
export declare type Params = {
min?: number;
max?: number;
leftUnitsQty?: number;
rightUnitsQty?: number;
exclude?: Array<number>;
};
declare const createRndWeight: (params: Params) => number;
export default createRndWeight;
|
balovbohdan/fwd-ann
|
src/lib/activation-funcs/index.ts
|
import { ActivationFunction } from './types';
import * as activationFuncs from './activation-funcs';
export default activationFuncs;
export { activationFuncs, ActivationFunction };
|
balovbohdan/fwd-ann
|
src/lib/calculators/output-errors/types.ts
|
<reponame>balovbohdan/fwd-ann
import {SignalsErrors} from '../../signals';
export type OutputErrors = {
errors:SignalsErrors|null;
};
|
balovbohdan/fwd-ann
|
dist/utils/id-generator.d.ts
|
<reponame>balovbohdan/fwd-ann
declare const generate: (length?: number) => string;
export default generate;
|
balovbohdan/fwd-ann
|
src/lib/layers/types.ts
|
<reponame>balovbohdan/fwd-ann
import { Units } from '../units';
import { Data as LayerData } from '../units/create';
export type LayersPair = {
left:Units;
right:Units;
index:number;
};
export type LayersData = Array<Units>;
export type LayersRawData = Readonly<ReadonlyArray<LayerData>>;
|
balovbohdan/fwd-ann
|
dist/lib/calculators/back-error-propagation/calc-delta-weights.d.ts
|
<reponame>balovbohdan/fwd-ann<filename>dist/lib/calculators/back-error-propagation/calc-delta-weights.d.ts
import { Matrix } from 'matrix-calculus';
import { ANN } from '../../ann';
import { LayersPair } from '../../layers/types';
import { Signals, SignalsErrors } from '../../signals';
declare type Data = {
ann: ANN;
layersPair: LayersPair;
errors: SignalsErrors | null;
layersOutputs: Array<Signals>;
};
declare const calcDeltaWeights: (data: Data) => Matrix | null;
export default calcDeltaWeights;
|
balovbohdan/fwd-ann
|
dist/utils/math-utils/aaw.d.ts
|
<gh_stars>0
declare const calc: (weights: number[], values: number[]) => number;
export default calc;
|
balovbohdan/fwd-ann
|
src/lib/calculators/ann-output/calc-layers-pair.ts
|
import { ANN } from '../../ann';
import { Signals } from '../../signals';
import { LayersPair } from '../../layers/types';
import weightsToSignals from './weights-to-signals';
type Data = {
ann:ANN;
signals:Signals;
layersPair:LayersPair;
};
type Res = {
dirtyOutput:Signals;
layersInputs:Array<Signals>;
layersOutputs:Array<Signals>;
};
const calcLayersPair = ({ ann, signals, layersPair }:Data):Res => {
const weights = ann.getLayersWeights().get(layersPair.index);
const activatedInput:Signals = layersPair.left.activateSignals(<Signals>signals);
if (!weights)
throw new LayersPairCalculatorError('Got invalid ANN layers weights.');
const layersPairDirtyOutput = weightsToSignals({
weights,
signals: activatedInput,
});
const activatedOutput:Signals = layersPair.right.activateSignals(layersPairDirtyOutput);
return {
dirtyOutput: layersPairDirtyOutput,
layersInputs: [signals, layersPairDirtyOutput],
layersOutputs: [activatedInput, activatedOutput],
};
};
class LayersPairCalculatorError extends Error {
constructor(message:string) {
super(message);
Object.setPrototypeOf(this, LayersPairCalculatorError.prototype);
}
}
export default calcLayersPair;
|
balovbohdan/fwd-ann
|
dist/lib/teacher/index.d.ts
|
<reponame>balovbohdan/fwd-ann
import * as T from './types';
export { T };
export { Teacher } from './Teacher';
|
balovbohdan/fwd-ann
|
src/lib/weights/layers-pairs-weights/index.ts
|
<gh_stars>0
import * as T from './types';
export { T };
export { default } from './create';
export { LayersWeights } from './LayersWeights';
|
balovbohdan/fwd-ann
|
dist/lib/calculators/back-error-propagation/calc-delta.d.ts
|
import { Matrix } from 'matrix-calculus';
import { T } from '../../layers';
import { Signals, SignalsErrors } from '../../signals';
declare type Data = {
output: Signals;
errors: SignalsErrors;
layersPair: T.LayersPair;
};
declare const calcDelta: ({ output, errors, layersPair }: Data) => Matrix;
export default calcDelta;
|
balovbohdan/fwd-ann
|
src/lib/weights/layers-pairs-weights/rnd/create-params.ts
|
import { Params as Res } from './create-rnd-layers-weights';
import createWeightsParams from '../../layers-pair-weights/rnd/create-weights-params';
import { Params as RandomWeightParam } from '../../layers-pair-weights/rnd/create-rnd-weight';
import { LayersRawData } from '../../../layers/types';
export type Data = {
layersData:LayersRawData;
randomWeightParams?:Array<RandomWeightParam>;
};
const createParams = (data:Data):Res => {
const response:Res = [];
const { layersData } = data;
const layersQty = layersData.length;
const randomWeightParams = data.randomWeightParams || [];
for (let i = 1; i < layersQty; i++) {
const layersSequenceIndex = i - 1;
response.push(
createWeightsParams({
rightLayerData: layersData[i],
leftLayerData: layersData[layersSequenceIndex],
randomWeightParams: randomWeightParams[layersSequenceIndex] || null,
})
);
}
return response;
};
export default createParams;
|
balovbohdan/fwd-ann
|
src/index.ts
|
export { Signals } from './lib/signals';
export { Teacher } from './lib/teacher';
export { LayerType } from './lib/layers';
export { default, ANN } from './lib/ann';
export { activationFuncs } from './lib/activation-funcs';
|
balovbohdan/fwd-ann
|
src/lib/ann/types.ts
|
<gh_stars>0
import { Layers } from '../layers';
import { Mutator } from '../signals';
import { LayersWeights } from '../weights/layers-pairs-weights';
import { Res as AnnOutputCalculatorRes } from '../calculators/ann-output/calc-ann-output';
export type ComplexOutput = AnnOutputCalculatorRes;
export type Params = {
learningSpeed?:number;
inputSignals?:{
offset?:number;
needOffset?:boolean;
needNormalize?:boolean;
normalizer?:Mutator|null;
};
};
export type ParamsPrepared = Params & {
learningSpeed:number;
inputSignals: {
offset:number;
needOffset:boolean;
needNormalize:boolean;
normalizer:Mutator|null;
};
};
export type Data = {
name?:string;
layers:Layers;
id?:string|null;
layersWeights:LayersWeights;
};
export type DataPrepared = Data & {
name:string;
id:string|null;
};
|
balovbohdan/fwd-ann
|
src/lib/layers/LayerType.ts
|
<gh_stars>0
export enum LayerType {
INPUT = 'input',
HIDDEN = 'hidden',
OUTPUT = 'output',
}
|
balovbohdan/fwd-ann
|
src/lib/weights/layers-pair-weights/rnd/create-rnd-weights.ts
|
<reponame>balovbohdan/fwd-ann
import { Matrix, Data as MatrixData } from 'matrix-calculus';
import { Weights } from '../Weights';
import createRndWeight, { Params as RndWeightParams } from './create-rnd-weight';
export type Params = {
leftUnitsQty:number;
rightUnitsQty:number;
rndWeightParams?:RndWeightParams;
};
const createRndWeights = (params:Params):Weights|null => {
try {
const weights = createWeightsMatrix(params);
return new Weights(weights);
} catch (e) {
console.warn(e);
return null;
}
};
const createWeightsMatrix = ({ leftUnitsQty, rightUnitsQty, rndWeightParams = {} }:Params):Matrix => {
const rowsQty = leftUnitsQty;
const colsQty = rightUnitsQty;
const matrixData:MatrixData = [];
if (rowsQty <= 0 || colsQty <= 0)
return new Matrix([]);
for (let row = 0; row < rowsQty; row++) {
matrixData[row] = [];
for (let col = 0; col < colsQty; col++)
matrixData[row][col] = createRndWeight(rndWeightParams);
}
return new Matrix(matrixData);
};
export default createRndWeights;
|
balovbohdan/fwd-ann
|
dist/lib/signals/Signals.d.ts
|
import { Matrix } from 'matrix-calculus';
import { Mutator } from './mutators';
export declare class Signals {
static create(signals: Array<number>, names?: Array<string>): Signals;
constructor(signals: Matrix, names?: Array<string>);
getNames(): Array<string>;
setNames(names: Array<string>): void;
get(i: number): number;
getMatrix(): Matrix;
getQty(): number;
normalize(mutator?: Mutator | null): Signals;
offset(offset?: number): Signals;
hasTheSameSizeStrict(signals: Signals): Signals | never;
hasTheSameSize(signals: Signals): boolean;
sortByNames(): Signals | never;
private getNamedSignalsData;
private names;
private readonly signals;
}
|
balovbohdan/fwd-ann
|
src/lib/activation-funcs/types.ts
|
import { Matrix } from 'matrix-calculus';
export type ActivationFunction = {
func:Func;
calc:(n:number)=>number;
calcComplexDerivative:(matrix:Matrix)=>Matrix;
};
type Func = {
calc: (n:number)=>number;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.