repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
ACM-VIT/uniauth-backend
|
src/dashboard/dto/create-dashboard.dto.ts
|
<gh_stars>100-1000
export class CreateDashboardDto {}
|
ACM-VIT/uniauth-backend
|
src/dashboard/dashboard.service.ts
|
<reponame>ACM-VIT/uniauth-backend
import { Injectable } from '@nestjs/common';
import { CreateDashboardDto } from './dto/create-dashboard.dto';
import { UpdateDashboardDto } from './dto/update-dashboard.dto';
@Injectable()
export class DashboardService {
create(createDashboardDto: CreateDashboardDto) {
return 'This action adds a new dashboard';
}
findAll() {
return `This action returns all dashboard`;
}
findOne(id: number) {
return `This action returns a #${id} dashboard`;
}
update(id: number, updateDashboardDto: UpdateDashboardDto) {
return `This action updates a #${id} dashboard`;
}
remove(id: number) {
return `This action removes a #${id} dashboard`;
}
}
|
ACM-VIT/uniauth-backend
|
src/account/constants/access_token.constants.ts
|
import * as config from 'config';
export const accessTokenJwtConstants = {
secret: config.get('access_token.secret'),
expiresIn: config.get('access_token.expires'),
issuer: config.get('access_token.issuer'),
};
|
ACM-VIT/uniauth-backend
|
src/auth/dto/login.dto.ts
|
import { IsEmail, IsNotEmpty } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class LoginDto {
/** college email id of student */
@IsNotEmpty()
@IsEmail()
@ApiProperty({
description: 'college email id of student ',
example: '<EMAIL>',
required: true,
})
email: string;
/** password of student */
@IsNotEmpty()
@ApiProperty({
description: 'password',
example: '<PASSWORD>',
required: true,
})
password: string;
}
export class LoginDtoWithToken extends LoginDto {
@IsNotEmpty()
token: string;
}
|
ACM-VIT/uniauth-backend
|
src/user/user.repository.ts
|
<gh_stars>0
import { Injectable, UseFilters } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { MongoExceptionFilter } from 'src/auxiliary/exceptions/mongo.exceptions';
import { CreateUserDto } from './dto/create-user.dto';
import { User, UserDocument } from './user.schema';
/**
* **User Repository**
*
* This is the data persistence layer and is responsible for database related operations.
*
* @category User
*/
@Injectable()
export class UserRepository {
constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}
}
|
ACM-VIT/uniauth-backend
|
src/account/dto/create-account.dto.ts
|
<filename>src/account/dto/create-account.dto.ts
export class CreateAccountDto {}
|
ACM-VIT/uniauth-backend
|
src/dashboard/dto/update-dashboard.dto.ts
|
import { PartialType } from '@nestjs/mapped-types';
import { CreateDashboardDto } from './create-dashboard.dto';
export class UpdateDashboardDto extends PartialType(CreateDashboardDto) {}
|
kenyipp/rounding-values
|
index.d.ts
|
<filename>index.d.ts
"use strict";
declare namespace roundingValues {
interface Options {
/**
Recurse nested objects and objects in arrays.
@default false
*/
readonly deep?: boolean;
/**
Exclude keys from being rounding.
@default []
*/
readonly exclude?: ReadonlyArray<string | RegExp>;
/**
The decimal place for rounding
@default 2
*/
readonly decimal?: number;
}
}
declare function roundingValues<T extends ReadonlyArray<{ [key: string]: any }>>(
input: T,
options?: roundingValues.Options,
): T;
declare function roundingValues<T extends { [key: string]: any }>(
input: T,
options?: roundingValues.Options,
): T;
declare function roundingValues<number>(
input: number,
options?: roundingValues.Options,
): number;
export = roundingValues;
|
shravankulkarni05/iv-insta-profile-viewer
|
src/app/app-routing.module.ts
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { IpvDashboardComponent } from './features/insta-profile-viewer/ipv-dashboard/ipv-dashboard.component';
const routes: Routes = [
{path: '', component: IpvDashboardComponent},
{path: 'ipv', component: IpvDashboardComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
|
shravankulkarni05/iv-insta-profile-viewer
|
src/app/shared/shared-constants.ts
|
<gh_stars>0
export class SharedConstants {
public static readonly PROXY_API = '/iv/';
public static readonly INSTA_PROF_SUFFIX = '/?__a=1'
public static readonly INSTA_WEB_URL = 'https://www.instagram.com/'
}
|
shravankulkarni05/iv-insta-profile-viewer
|
src/app/shared/iv-footer/iv-footer.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { IvFooterComponent } from './iv-footer.component';
describe('IvFooterComponent', () => {
let component: IvFooterComponent;
let fixture: ComponentFixture<IvFooterComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ IvFooterComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(IvFooterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
shravankulkarni05/iv-insta-profile-viewer
|
src/app/shared/directives/image-loader.directive.ts
|
<gh_stars>0
import {
Directive,
Attribute,
Renderer2,
ElementRef,
HostListener } from '@angular/core';
@Directive({
selector: '[imageLoader]'
})
export class ImageLoaderDirective {
constructor(@Attribute('loader') public loader: string, @Attribute('onErrorSrc') public onErrorSrc: string, private renderer: Renderer2, private el: ElementRef) {
this.renderer.setAttribute(this.el.nativeElement, 'src', this.loader);
}
@HostListener('load') onLoad() {
this.renderer.setAttribute(this.el.nativeElement, 'src', this.el.nativeElement.src);
}
@HostListener('error') onError() {
this.renderer.setAttribute(this.el.nativeElement, 'src', this.onErrorSrc);
}
}
|
shravankulkarni05/iv-insta-profile-viewer
|
src/app/features/insta-profile-viewer/ipv-profile/ipv-profile.component.ts
|
<gh_stars>0
import { Component, Input } from '@angular/core';
import { InstaProfileData } from '../ipv-dashboard/ipv-dashboard.component';
@Component({
selector: 'app-ipv-profile',
templateUrl: './ipv-profile.component.html',
styleUrls: ['./ipv-profile.component.css']
})
export class IpvProfileComponent {
@Input() profileData: InstaProfileData;
}
|
shravankulkarni05/iv-insta-profile-viewer
|
src/app/shared/shared.module.ts
|
import { NgModule } from '@angular/core';
import { IvFooterComponent } from './iv-footer/iv-footer.component';
import { IvHeaderComponent } from './iv-header/iv-header.component';
import { ImageLoaderDirective } from './directives/image-loader.directive';
@NgModule({
declarations: [IvHeaderComponent, IvFooterComponent, ImageLoaderDirective],
exports: [IvHeaderComponent, IvFooterComponent, ImageLoaderDirective],
})
export class SharedModule {}
|
shravankulkarni05/iv-insta-profile-viewer
|
src/app/app.module.ts
|
<filename>src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { SharedModule } from './shared/shared.module';
import { IpvDashboardComponent } from './features/insta-profile-viewer/ipv-dashboard/ipv-dashboard.component';
import { IpvProfileComponent } from './features/insta-profile-viewer/ipv-profile/ipv-profile.component';
import {HttpClientModule} from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MatButtonModule} from '@angular/material/button';
import {MatInputModule} from '@angular/material/input';
import { FormsModule } from '@angular/forms';
import { MatCardModule } from '@angular/material/card';
@NgModule({
declarations: [
AppComponent,
IpvDashboardComponent,
IpvProfileComponent
],
imports: [
BrowserModule,
AppRoutingModule,
SharedModule,
HttpClientModule,
BrowserAnimationsModule,
MatButtonModule,
MatInputModule,
FormsModule,
MatCardModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
shravankulkarni05/iv-insta-profile-viewer
|
src/app/features/insta-profile-viewer/ipv-dashboard/ipv-dashboard.component.ts
|
<filename>src/app/features/insta-profile-viewer/ipv-dashboard/ipv-dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { APIService } from 'src/app/shared/api-service';
import { SharedConstants } from 'src/app/shared/shared-constants';
export interface InstaProfileData {
userName: string;
fullName: string;
biography: string;
avatar: string,
profilePicUrl: string
followingCount: number;
followersCount: number;
postsCount: number;
isPrivate: boolean;
isProfessionalAccnt: boolean;
instaUrl: string;
}
@Component({
selector: 'app-ipv-dashboard',
templateUrl: './ipv-dashboard.component.html',
styleUrls: ['./ipv-dashboard.component.css']
})
export class IpvDashboardComponent implements OnInit {
instaResp: any;
profileData: InstaProfileData;
userName: string = 'shravan_kulkarni5';
constructor(private apiService: APIService) { }
ngOnInit(): void {
}
private getProfileData(userName: string) {
if (!userName) {
return;
}
this.apiService.get(SharedConstants.PROXY_API + userName + SharedConstants.INSTA_PROF_SUFFIX)
.subscribe((resp: any) => {
this.instaResp = resp;
const user = resp['graphql']['user'];
this.profileData = {
biography : user.biography,
profilePicUrl : this.getProfilePictureUrl(user.profile_pic_url_hd),
avatar: this.getProfilePictureUrl(user.profile_pic_url),
userName : user.username,
fullName : user.full_name,
followingCount : user.edge_follow.count,
followersCount : user.edge_followed_by.count,
postsCount : user.edge_owner_to_timeline_media.count,
isPrivate : user.is_private,
isProfessionalAccnt : user.is_professional_account,
instaUrl: SharedConstants.INSTA_WEB_URL + user.username
} as InstaProfileData;
});
}
searchProfile(userName: string) {
if (!userName) {
return;
}
this.getProfileData(userName);
}
getProfilePictureUrl(url: string) {
const spiltUrl = url.split("/v");
return '/profile/v' + spiltUrl[1];
// this.apiService.get(profileUrl).subscribe(data => {
// console.log(data)
// });
}
}
|
Noah2610/chat-app
|
src/components/user-avatar.tsx
|
import { Avatar, AvatarProps } from "@material-ui/core";
import { AccountCircle } from "@material-ui/icons";
import { getNameInitials } from "../util";
export type UserAvatarProps = {
name?: string | null;
email?: string | null;
src?: string | null;
} & Omit<AvatarProps, "src">;
export default function UserAvatar({
name,
email,
src,
...props
}: UserAvatarProps) {
return (
<Avatar src={src || undefined} {...props}>
{(!!name && getNameInitials(name)) ||
(!!email && getNameInitials(email, { isEmail: true })) || (
<AccountCircle />
)}
</Avatar>
);
}
|
Noah2610/chat-app
|
src/components/app-bar.tsx
|
import {
createStyles,
makeStyles,
AppBar,
Box,
Toolbar,
} from "@material-ui/core";
import Heading from "./heading";
import Login from "./login";
const useStyles = makeStyles((_theme) =>
createStyles({
root: {
borderTopLeftRadius: 4,
borderTopRightRadius: 4,
},
}),
);
export default function PageAppBar() {
const styles = useStyles();
return (
<AppBar className={styles.root} position="relative">
<Toolbar>
<Box
display="flex"
justifyContent="space-between"
alignItems="center"
width="100%"
>
<Heading>Chat App</Heading>
<Login />
</Box>
</Toolbar>
</AppBar>
);
}
|
Noah2610/chat-app
|
src/components/centered.tsx
|
<gh_stars>0
import { Box, BoxProps } from "@material-ui/core";
export type CenteredProps = BoxProps;
export default function Centered(props: CenteredProps) {
return (
<Box
display="flex"
justifyContent="center"
alignItems="center"
{...props}
/>
);
}
|
Noah2610/chat-app
|
src/firebase/api/messages.ts
|
<gh_stars>0
import { useCollectionData } from "react-firebase-hooks/firestore";
import { DataOptions as UseCollectionDataOptions } from "react-firebase-hooks/firestore/dist/firestore/types";
import { Query } from ".";
import { firestore } from "..";
import {
CollectionReference,
FirebaseError,
Message,
WithIdAndRef,
} from "../types";
export function getMessagesCollection(): CollectionReference<Message> {
return firestore.collection("messages") as CollectionReference<Message>;
}
export type UseMessagesData = {
messages: WithIdAndRef<Message>[];
isLoading: boolean;
error?: FirebaseError;
};
export function useMessages(
collection?: CollectionReference<Message>,
editQueryFn = (query: Query<Message>) => query,
options: UseCollectionDataOptions<Message> = {},
): UseMessagesData {
if (!collection) {
collection = getMessagesCollection();
}
const query = editQueryFn(
collection.orderBy("createdAt", "desc").limit(20),
);
const [messages = [], isLoading, error] = useCollectionData<
Message,
"id",
"ref"
>(query, {
...options,
idField: "id",
refField: "ref",
});
return {
messages,
isLoading,
error,
};
}
|
Noah2610/chat-app
|
src/util/index.ts
|
<filename>src/util/index.ts
import { Timestamp } from "../firebase/types";
export function formatTimestamp(timestamp: Timestamp): string {
if (!timestamp) {
return "--:--:--";
}
const today = new Date();
const dateInst = new Date(timestamp.seconds * 1000);
const date = {
year: dateInst.getFullYear(),
month: dateInst.getMonth(),
day: dateInst.getDate(),
hour: dateInst.getHours(),
minute: dateInst.getMinutes(),
second: dateInst.getSeconds(),
};
const isToday =
today.getFullYear() === date.year &&
today.getMonth() === date.month &&
today.getDate() === date.day;
const pad = (num: number) => num.toString().padStart(2, "0");
return (
(isToday
? ""
: `${pad(date.year)}-${pad(date.month + 1)}-${pad(date.day)} `) +
`${pad(date.hour)}:${pad(date.minute)}:${pad(date.second)}`
);
}
export function getNameInitials(
name: string,
options?: { maxLen?: number; isEmail?: boolean },
): string {
options = options ?? {};
let { maxLen, isEmail } = options;
maxLen = maxLen ?? 2;
isEmail = isEmail ?? false;
if (isEmail) {
const indexOfAtSign = name.indexOf("@");
name = name.slice(0, indexOfAtSign);
}
const initials = name
.trim()
.split(isEmail ? "." : " ")
.map((word) => word[0].toUpperCase())
.filter((letter) => !!letter);
const limitedInitials = initials.splice(0, maxLen);
const lastInitial = initials.pop();
if (lastInitial && limitedInitials.length > 1) {
limitedInitials[limitedInitials.length - 1] = lastInitial;
}
return limitedInitials.join("");
}
|
Noah2610/chat-app
|
src/pages/_app.tsx
|
import { AppProps } from "next/app";
import { ThemeProvider, CssBaseline } from "@material-ui/core";
import theme from "../theme";
export default function App({ pageProps, Component }: AppProps) {
return (
<>
<ThemeProvider theme={theme}>
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</>
);
}
|
Noah2610/chat-app
|
src/firebase/types/index.ts
|
import firebase from "firebase/app";
export type { default as Message } from "./message";
export type Id = string;
export type Ref = any;
export type Uid = string;
export type WithId<T> = T & { id: Id };
export type WithRef<T> = T & { ref: Ref };
export type WithIdAndRef<T> = WithId<WithRef<T>>;
export type Timestamp = firebase.firestore.Timestamp | null;
export type FirebaseError = firebase.FirebaseError;
export type { User } from "@firebase/auth-types";
export type {
CollectionReference,
DocumentData,
FieldValue,
QuerySnapshot,
} from "@firebase/firestore-types";
|
Noah2610/chat-app
|
src/pages/index.tsx
|
<reponame>Noah2610/chat-app
import { Box } from "@material-ui/core";
import App from "../components/app";
export default function Home() {
return (
<>
<Box maxWidth="640px" marginX="auto">
<App />
</Box>
</>
);
}
|
Noah2610/chat-app
|
src/components/chat-messages-list/list-item.tsx
|
import { memo } from "react";
import {
Avatar,
Box,
Paper,
Theme,
Typography,
createStyles,
makeStyles,
} from "@material-ui/core";
import ReactMarkdown from "react-markdown";
import { Message, Uid } from "../../firebase/types";
import { formatTimestamp } from "../../util";
export type ChatMessageListItemProps = {
message: Message;
loggedInUid: Uid;
};
type StylesProps = {
isLoggedInUserMessage: boolean;
};
const AVATAR_HEIGHT = 48;
const ARROW_SIZE = 16;
const useStyles = makeStyles<Theme, StylesProps>((theme) =>
createStyles({
root: {
display: "flex",
justifyContent: "flex-start",
alignItems: "flex-end",
gap: ARROW_SIZE / 2,
},
avatar: {
width: AVATAR_HEIGHT,
height: AVATAR_HEIGHT,
display: "flex",
alignItems: "center",
flexShrink: 0,
},
message: {
position: "relative",
color: theme.palette.text.primary,
backgroundColor: ({ isLoggedInUserMessage }) =>
isLoggedInUserMessage
? theme.palette.primary.dark
: theme.palette.primary.light,
},
content: {
fontSize: theme.typography.body1.fontSize,
"& > p:first-child": {
marginTop: 0,
},
"& > p:last-child": {
marginBottom: 0,
},
},
arrow: {
position: "absolute",
width: ARROW_SIZE,
height: ARROW_SIZE,
bottom: AVATAR_HEIGHT / 2 - ARROW_SIZE / 2,
left: -(ARROW_SIZE / 2),
backgroundColor: ({ isLoggedInUserMessage }) =>
isLoggedInUserMessage
? theme.palette.primary.dark
: theme.palette.primary.light,
boxShadow: "inherit",
transform: "rotate(45deg)",
clipPath: "polygon(0 0, 100% 100%, 0 100%)",
},
}),
);
function ChatMessageListItem({
message,
loggedInUid,
}: ChatMessageListItemProps) {
const isLoggedInUserMessage = loggedInUid === message.uid;
const styles = useStyles({ isLoggedInUserMessage });
return (
<Box className={styles.root}>
<Box className={styles.avatar}>
{message.photoURL ? <Avatar src={message.photoURL} /> : <></>}
</Box>
<Paper className={styles.message} elevation={2}>
<Box className={styles.arrow} />
<Box padding={2} paddingBottom={1}>
<ReactMarkdown className={styles.content}>
{message.content}
</ReactMarkdown>
<Box marginTop={1}>
<Typography variant="caption" color="textSecondary">
{formatTimestamp(message.createdAt)}
</Typography>
</Box>
</Box>
</Paper>
</Box>
);
}
export default memo(
ChatMessageListItem,
(
{ message: messageA, loggedInUid: loggedInUidA },
{ message: messageB, loggedInUid: loggedInUidB },
) =>
messageA.content === messageB.content &&
messageA.createdAt?.seconds === messageB.createdAt?.seconds &&
messageA.photoURL === messageB.photoURL &&
loggedInUidA === loggedInUidB,
);
|
Noah2610/chat-app
|
src/firebase/api/index.ts
|
<gh_stars>0
export type { Query } from "@firebase/firestore-types";
export * from "./messages";
|
Noah2610/chat-app
|
src/components/heading.tsx
|
<filename>src/components/heading.tsx
import { Typography, TypographyProps } from "@material-ui/core";
type HeadingProps = {
children: React.ReactNode;
} & TypographyProps;
export default function Heading({ children, ...props }: HeadingProps) {
return (
<Typography color="textPrimary" variant="h1" {...props}>
{children}
</Typography>
);
}
|
Noah2610/chat-app
|
src/theme.ts
|
<filename>src/theme.ts
import { createMuiTheme } from "@material-ui/core";
export default createMuiTheme({
palette: {
primary: {
main: "#601ea8",
light: "#934edb",
dark: "#2a0078",
contrastText: "#cccccc",
},
secondary: {
main: "#5c9123",
light: "#8dc253",
dark: "#2b6300",
contrastText: "#ffffff",
},
text: {
primary: "#ffffff",
secondary: "#cccccc",
},
background: {
default: "#282c34",
paper: "#353942",
},
},
typography: {
fontFamily: "Roboto",
body1: {
fontSize: "18px",
},
h1: {
fontSize: "64px",
letterSpacing: "6px",
wordSpacing: "12px",
margin: "16px",
textShadow: "3px 3px 6px #000000",
},
h2: {
fontSize: "48px",
},
h3: {
fontSize: "32px",
},
h4: {
fontSize: "24px",
},
h5: {
fontSize: "20px",
},
h6: {
fontSize: "18px",
},
},
});
|
Noah2610/chat-app
|
src/components/chat-messages-list/index.tsx
|
<gh_stars>0
import { createStyles, makeStyles, Box } from "@material-ui/core";
import { useAuthState } from "react-firebase-hooks/auth";
import ListItem from "./list-item";
import { auth } from "../../firebase";
import { Message, WithIdAndRef } from "../../firebase/types";
export type ChatMessagesListProps = {
messages: WithIdAndRef<Message>[];
};
const useStyles = makeStyles((_theme) =>
createStyles({
root: {
display: "flex",
flexDirection: "column-reverse",
justifyContent: "flex-start",
alignItems: "flex-start",
gridGap: 8,
maxHeight: 480,
overflowY: "auto",
},
}),
);
export default function ChatMessagesList({ messages }: ChatMessagesListProps) {
const styles = useStyles();
const [user] = useAuthState(auth);
if (!user) {
return null;
}
return (
<Box className={styles.root}>
{messages.map((message) => (
<ListItem
key={message.id}
message={message}
loggedInUid={user.uid}
/>
))}
</Box>
);
}
|
Noah2610/chat-app
|
src/components/app.tsx
|
import { Box } from "@material-ui/core";
import AppBar from "./app-bar";
import ChatRoom from "./chat-room";
export default function App() {
return (
<>
<Box position="relative">
<AppBar />
<ChatRoom />
</Box>
</>
);
}
|
Noah2610/chat-app
|
src/components/login.tsx
|
import { Box, Button, CircularProgress, IconButton } from "@material-ui/core";
import firebase from "firebase/app";
import { useAuthState } from "react-firebase-hooks/auth";
import UserAvatar from "./user-avatar";
import { auth } from "../firebase";
export default function Login() {
const [user, isLoading] = useAuthState(auth);
const signInWithGoogle = () => {
const provider = new firebase.auth.GoogleAuthProvider();
auth.signInWithPopup(provider);
};
const logout = () => {
auth.signOut();
};
return (
<Box>
{isLoading ? (
<>
<CircularProgress />
</>
) : (
<>
{!user ? (
<Button
variant="contained"
color="secondary"
onClick={signInWithGoogle}
>
Login
</Button>
) : (
<IconButton>
<Box borderRadius={4} boxShadow={4}>
<UserAvatar
variant="rounded"
src={user.photoURL}
name={user.displayName}
email={user.email}
/>
</Box>
</IconButton>
)}
</>
)}
</Box>
);
}
|
Noah2610/chat-app
|
src/components/chat-input.tsx
|
import { useState } from "react";
import {
Box,
Button,
CircularProgress,
FormControl,
Icon,
TextField,
} from "@material-ui/core";
import SendIcon from "@material-ui/icons/Send";
export type ChatInputProps = {
sendMessage: (message: string) => Promise<void>;
};
export default function ChatInput({ sendMessage }: ChatInputProps) {
const [input, setInput] = useState("");
return (
<Box>
<form
action="#"
onSubmit={(e) => {
e.preventDefault();
sendMessage(input);
setInput("");
}}
>
<FormControl fullWidth>
<TextField
size="small"
value={input}
label="Message"
variant="filled"
onChange={(e) => setInput(e.currentTarget.value)}
InputProps={{
endAdornment: (
<Button
type="submit"
size="large"
endIcon={<SendIcon />}
>
Send
</Button>
),
}}
/>
</FormControl>
</form>
</Box>
);
}
|
Noah2610/chat-app
|
src/firebase/types/message.ts
|
<gh_stars>0
import { Timestamp, Uid } from "../types";
type Message = {
content: string;
createdAt: Timestamp;
uid: Uid;
photoURL: string | null;
};
export default Message;
|
Noah2610/chat-app
|
src/components/chat-room.tsx
|
import { Box, CircularProgress, Paper } from "@material-ui/core";
import firebase from "firebase/app";
import { useAuthState } from "react-firebase-hooks/auth";
import ChatMessagesList from "./chat-messages-list";
import ChatInput from "./chat-input";
import Centered from "./centered";
import { auth } from "../firebase";
import { Timestamp } from "../firebase/types";
import { useMessages, getMessagesCollection } from "../firebase/api";
export default function ChatRoom() {
const [user, isLoadingUser] = useAuthState(auth);
const messagesCollection = getMessagesCollection();
const {
messages,
isLoading: isLoadingMessages,
error: messagesError,
} = useMessages(messagesCollection, (query) => query.limit(10));
const isLoading = isLoadingUser || isLoadingMessages;
if (!user) {
return null;
}
const sendMessage = async (message: string) => {
if (!message.match(/^\s*$/)) {
await messagesCollection.add({
content: message,
createdAt: firebase.firestore.FieldValue.serverTimestamp() as Timestamp,
uid: user.uid,
photoURL: user.photoURL,
});
}
};
return isLoading ? (
<Centered>
<CircularProgress />
</Centered>
) : (
<Paper elevation={8}>
<Box
display="flex"
flexDirection="column"
justifyContent="flex-start"
alignItems="stretch"
gridGap="16px"
padding={4}
paddingTop={0}
>
<ChatMessagesList messages={messages} />
<ChatInput sendMessage={sendMessage} />
</Box>
</Paper>
);
}
|
Noah2610/chat-app
|
src/firebase/index.ts
|
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
if (typeof window !== undefined) {
if (firebase.apps.length === 0) {
firebase.initializeApp({
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId:
process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
});
}
}
export const auth = firebase.auth();
export const firestore = firebase.firestore();
|
rwblair/BLiMP
|
neuroscout/frontend/src/Routes.tsx
|
import * as React from 'react';
import { Route, Redirect, Switch } from 'react-router-dom';
import { message } from 'antd';
import './css/App.css';
import AnalysisList from './AnalysisList';
import AnalysisBuilder from './analysis_builder/Builder';
import { AppState } from './coretypes';
import { config } from './config';
import FAQ from './FAQ';
import { NotFound } from './HelperComponents';
import Home from './Home';
import Ingest from './Ingest';
const isBlimp = (config.blimp === 'true');
import { PredictorCollectionList } from './predictor_collection/CollectionList';
export default class Routes extends React.Component<AppState, {}> {
render() {
return (
<Switch>
<Route
exact={true}
path="/"
render={props =>
<Home />
}
/>
<Route
exact={true}
path="/builder"
render={props => {
// This is a temporary solution to prevent non logged-in users from entering the builder.
// Longer term to automatically redirect the user to the target URL after login we
// need to implement something like the auth workflow example here:
// https://reacttraining.com/react-router/web/example/auth-workflow
if (this.props.auth.loggedIn || this.props.auth.openLogin) {
return <AnalysisBuilder
updatedAnalysis={() => this.props.loadAnalyses()}
key={props.location.key}
datasets={this.props.datasets}
doTour={this.props.auth.openTour}
/>;
}
message.warning('Please log in first and try again');
return <Redirect to="/" />;
}}
/>
<Route
path="/builder/:id"
render={props =>
<AnalysisBuilder
id={props.match.params.id}
updatedAnalysis={() => this.props.loadAnalyses()}
userOwns={this.props.analyses.filter((x) => x.id === props.match.params.id).length > 0}
datasets={this.props.datasets}
doTooltip={true}
/>}
/>
<Route
exact={true}
path="/public/:id"
render={props =>
<AnalysisBuilder
id={props.match.params.id}
updatedAnalysis={() => this.props.loadAnalyses()}
userOwns={this.props.analyses.filter((x) => x.id === props.match.params.id).length > 0}
datasets={this.props.datasets}
doTooltip={true}
/>
}
/>
<Route
exact={true}
path="/public"
render={props =>
<AnalysisList
analyses={this.props.publicAnalyses}
cloneAnalysis={this.props.cloneAnalysis}
datasets={this.props.datasets}
publicList={true}
/>}
/>
<Route
exact={true}
path="/myanalyses"
render={props =>
<AnalysisList
analyses={this.props.analyses}
cloneAnalysis={this.props.cloneAnalysis}
onDelete={this.props.onDelete}
datasets={this.props.datasets}
publicList={false}
/>}
/>
{ isBlimp &&
<Route
path="/ingest"
render={props =>
<Ingest getDatasets={this.props.getDatasets} />
}
/>
}
<Route
exact={true}
path="/faq"
render={() => <FAQ/>}
/>
<Route
path="/mycollections"
render={props =>
<PredictorCollectionList
datasets={this.props.datasets}
collections={this.props.auth.predictorCollections}
/>}
/>
<Route component={NotFound} />
</Switch>
);
}
}
|
rwblair/BLiMP
|
neuroscout/frontend/src/coretypes.ts
|
/*
Type definitinos for key models, such as analysis, run, predictor, contrast, transformation, etc.
The data models below are largely UI agonstic. This module is a good starting point to understand the
shape of the data in the frontend app. All resusable type definitions should go into this module.
*/
export type AnalysisStatus = 'DRAFT' | 'PENDING' | 'PASSED' | 'FAILED' | 'SUBMITTING';
// Analysis type in Analysis Builder
export interface Analysis {
analysisId: string | undefined;
name: string;
description: string;
datasetId: string | null; // ID of selected dataset
runIds: string[]; // IDs of selected runs
predictions: string;
predictorIds: string[]; // IDs of selected predictors
hrfPredictorIds: string[];
status: AnalysisStatus;
private?: boolean;
modifiedAt?: string;
config: AnalysisConfig;
transformations: Transformation[];
contrasts: Contrast[];
model?: BidsModel;
autoContrast: boolean;
}
// Normalized dataset object in Analysis Builder
export interface Dataset {
name: string;
id: string;
authors: string[];
url: string;
description: string;
tasks: Task[];
active: boolean;
}
// Dataset object as returned by /api/datasets
export interface ApiDataset {
id: number;
name: string;
description: {
Authors: string[];
Description: string;
URL: string;
};
url: string;
summary: string;
tasks: Task[];
active: boolean;
}
export interface Run {
id: string;
number: string;
session: string | null;
subject: string | null;
task: string;
}
export interface Task {
id: string;
name: string;
description?: string;
numRuns: number;
summary?: string;
}
export interface Predictor {
id: string;
name: string;
source: string | null;
description: string | null;
extracted_feature?: ExtractedFeature;
private: boolean;
dataset_id?: number;
}
export interface ExtractedFeature {
description: string;
extractor_name: string;
}
export interface AnalysisConfig {
smoothing: number;
predictorConfigs: { [id: string]: PredictorConfig };
}
export interface PredictorConfig {
convolution: 'Gamma' | 'Beta' | 'Alpha';
temporalDerivative: boolean;
orthogonalize: boolean;
}
interface BooleanParam {
kind: 'boolean';
name: string;
value: boolean;
}
interface PredictorsParam {
kind: 'predictors';
name: string;
value: string[];
}
export type Parameter = BooleanParam | PredictorsParam;
export type TransformName = 'Scale' | 'Orthogonalize' | 'Threshold'
| 'Or' | 'And' | 'Not' | 'Convolve' | 'Factor' | 'Replace';
export type StepLevel = 'Run' | 'Session' | 'Subject' | 'Dataset';
export type ReplaceNA = 'before' | 'after' | undefined;
export interface Transformation {
Name: TransformName;
ReplaceNa?: ReplaceNA;
Input?: string[]; // predictor IDs
Output?: string[];
Demean?: boolean;
Rescale?: boolean;
Other?: string[];
Weights?: number[];
Threshold?: number;
Binarize?: boolean;
Above?: boolean;
Signed?: boolean;
Replace?: any;
Prefix?: string[];
Constraint?: string;
RefLevel?: string;
}
// Lookup hash of available transformations (as specified in transforms.ts) by their name
export interface XformRules {
[name: string]: Transformation;
}
export type TabName =
| 'overview'
| 'predictors'
| 'transformations'
| 'contrasts'
| 'modeling'
| 'review'
| 'submit';
export type ContrastTypeEnum = 't' | 'F';
export interface Contrast {
Name: string;
ConditionList: string[];
Weights: number[];
ContrastType: ContrastTypeEnum;
}
export interface Store {
activeTab: TabName;
predictorsActive: boolean;
predictorsLoad: boolean;
loadInitialPredictors: boolean;
transformationsActive: boolean;
contrastsActive: boolean;
hrfActive: boolean;
reviewActive: boolean;
submitActive: boolean;
analysis: Analysis;
datasets: Dataset[];
availableRuns: Run[];
selectedTaskId: string | null;
availablePredictors: Predictor[];
// Technically selectedPredictors is redundant because we're also storing Analysis.predictorIds
// but store these separately for performance reasons
selectedPredictors: Predictor[];
selectedHRFPredictors: Predictor[];
unsavedChanges: boolean;
currentLevel: StepLevel;
postReports: boolean;
model: BidsModel;
poll: boolean;
saveFromUpdate: boolean;
activeXform?: Transformation;
activeXformIndex: number;
activeContrast?: Contrast;
activeContrastIndex: number;
xformErrors: string[];
contrastErrors: string[];
fillAnalysis: boolean;
analysis404: boolean;
doTooltip: boolean;
auth?: AuthStoreState;
}
export interface ApiRun {
id: string;
number: string;
session: string | null;
subject: string | null;
}
// Shape of Analysis object as consumed/produced by the backend API
export interface ApiAnalysis {
hash_id?: string;
name: string;
description: string;
predictions: string;
status: AnalysisStatus;
private?: boolean;
dataset_id: string;
runs?: string[];
predictors?: string[];
transformations?: Transformation[];
contrasts?: Contrast[];
config: AnalysisConfig;
modified_at?: string;
model?: BidsModel;
}
export interface BidsModel {
Input?: ImageInput;
Steps?: Step[] | never[];
Name?: string;
Description?: string;
}
export interface ImageInput {
Task?: string;
Run?: number[];
Session?: string[];
Subject?: string[];
}
export interface Step {
Model?: StepModel;
Transformations?: Transformation[];
Contrasts?: Contrast[];
Level: string;
AutoContrasts?: boolean;
}
export interface StepModel {
X: string[];
HRF_X?: string[];
}
export interface ModelContrast {
Name: string;
Predictors: string[];
Weights: number[];
ContrastType: 't' | 'F';
}
export interface PredictorCollection {
id: string;
uploaded_at?: string;
status?: string;
traceback?: string;
collection_name: string;
// predictors?: {id: string, name: string}[];
predictors?: Predictor[];
}
// Shape of User object as consumed/produced by the backend API
export interface ApiUser {
email: string;
name: string;
picture: string;
analyses: ApiAnalysis[];
predictor_collections: PredictorCollection[];
first_login: boolean;
}
// The more condensed version of analysis object as returned by the user route
// and displayed as list of analyses on the homepage
export interface AppAnalysis {
id: string;
name: string;
description: string;
status: AnalysisStatus;
datasetName?: string;
modifiedAt?: string;
}
export interface AuthStoreState {
jwt: string;
loggedIn: boolean;
openLogin: boolean;
openSignup: boolean;
openReset: boolean;
openEnterResetToken: boolean;
openTour: boolean;
loginError: string;
signupError: string;
resetError: string;
email: string | undefined;
name: string | undefined;
password: string | undefined;
token: string | null;
loggingOut: boolean; // flag set on logout to know to redirect after logout
nextURL: string | null; // will probably remove this and find a better solution to login redirects
gAuth: any;
avatar: string;
predictorCollections: PredictorCollection[];
}
export interface AppState {
loadAnalyses: () => void;
analyses: AppAnalysis[]; // List of analyses belonging to the user
publicAnalyses: AppAnalysis[]; // List of public analyses
auth: AuthStoreState;
datasets: Dataset[];
cloneAnalysis: (number) => void;
onDelete: (analysis: AppAnalysis) => void;
getDatasets: () => void;
}
export interface RunFilters {
numbers: string[];
subjects: string[];
sessions: string[];
}
// shape of objects returned by api/analyses/{id}/uploads
export interface ApiUpload {
collection_id: number;
uploaded_at: string;
files: [{level: string, status: string, traceback: (null | string)}];
}
|
rwblair/BLiMP
|
neuroscout/frontend/src/analysis_builder/Contrasts.tsx
|
<reponame>rwblair/BLiMP
/*
This module includes the following components:
- ContrastsTab: parent component for the contrast tab of the analysis builder
- ContrastDisplay: component to display a single contrast
*/
import * as React from 'react';
import { Button, Row, Col, Icon, List } from 'antd';
import {
DragDropContext,
Draggable,
Droppable,
DroppableProvided,
DropResult,
DroppableStateSnapshot, DraggableProvided, DraggableStateSnapshot
} from 'react-beautiful-dnd';
import { Analysis, Predictor, Contrast } from '../coretypes';
import { reorder } from '../utils';
import { DisplayErrorsInline } from '../HelperComponents';
import { ContrastEditor, emptyContrast } from './ContrastEditor';
interface ContrastDisplayProps {
index: number;
contrast: Contrast;
onDelete: (index: number) => void;
onEdit: (index: number) => void;
}
const ContrastDisplay = (props: ContrastDisplayProps) => {
const { contrast, index, onDelete, onEdit } = props;
return (
<div style={{'width': '100%'}}>
<div style={{'float': 'right'}}>
<Button type="primary" onClick={() => onEdit(index)}>
<Icon type="edit" />
</Button>
<Button type="danger" onClick={() => onDelete(index)}>
<Icon type="delete" />
</Button>
</div>
<div>
<b>{`${contrast.Name}`} </b>{`${contrast.ContrastType} test`}<br/>
{/*contrast.ConditionList && contrast.ConditionList.map((predictor, i) => {
return(predictor + ': ' + contrast.Weights[i] + ' ');
})*/}
</div>
</div>
);
};
interface ContrastsTabProps {
predictors: Predictor[];
contrasts: Contrast[];
onSave: (contrasts: Contrast[]) => void;
analysis: Analysis;
updateAnalysis: (value: any) => void;
activeContrastIndex: number;
activeContrast?: Contrast;
contrastErrors: string[];
updateBuilderState: (value: any) => any;
}
interface ContrastsTabState {
mode: 'add' | 'edit' | 'view';
}
export class ContrastsTab extends React.Component<ContrastsTabProps, ContrastsTabState> {
constructor(props: ContrastsTabProps) {
super(props);
this.state = { mode: 'view' };
}
onSave = (contrast: Contrast) => {
let { activeContrastIndex } = this.props;
let newContrasts = this.props.contrasts;
if (activeContrastIndex >= 0) {
newContrasts[activeContrastIndex] = contrast;
} else {
newContrasts.push(contrast);
}
this.props.onSave(newContrasts);
this.props.updateBuilderState('activeContrastIndex')(-1);
this.props.updateBuilderState('activeContrast')(undefined);
this.setState({ mode: 'view'});
};
onDelete = (index: number) => {
// Delete contrast with index
const newContrasts = this.props.contrasts.filter((elemm, i) => i !== index);
if (this.props.activeContrastIndex === index) {
this.setState({mode: 'view'});
this.props.updateBuilderState('activeContrastIndex')(-1);
}
this.props.onSave(newContrasts);
};
onEdit = (index: number) => {
this.props.updateBuilderState('activeContrastIndex')(index);
this.props.updateBuilderState('activeContrast')({...this.props.contrasts[index]});
this.props.updateBuilderState('contrastErrors')([] as string[]);
this.setState({mode: 'add'});
};
onCancel = () => {
this.props.updateBuilderState('activeContrastIndex')(-1);
this.props.updateBuilderState('activeContrast')(undefined);
this.props.updateBuilderState('contrastErrors')([] as string[]);
this.setState({ mode: 'view'});
};
onDragEnd = (result: DropResult): void => {
const { source, destination } = result;
if (!destination) {
return;
}
let newContrasts = reorder(
this.props.contrasts,
source.index,
destination.index
);
if (this.props.activeContrastIndex === source.index) {
this.props.updateBuilderState('activeContrastIndex')(destination.index);
}
this.props.onSave(newContrasts);
};
updateAnalysis = (attrName: string) => (value: any) => {
let newAnalysis = { ...this.props.analysis };
newAnalysis[attrName] = value;
this.props.updateAnalysis(newAnalysis);
};
addAutoContrasts = () => {
let predictors = this.props.predictors;
let newContrasts = [...this.props.contrasts];
predictors.map((x) => {
if (x.source === 'fmriprep') {
return;
}
let newContrast = emptyContrast();
newContrast.Name = `${x.name}`;
newContrast.ConditionList = [ x.name ];
newContrast.Weights = [ 1 ];
newContrasts.push(newContrast);
});
this.props.onSave(newContrasts);
};
removeAutoContrasts = () => {
let predictors = this.props.predictors;
let newContrasts = this.props.contrasts.filter((x) => predictors.map(y => y.name).indexOf(x.Name) === -1);
this.props.onSave(newContrasts);
};
getStyle = (index: number): string => {
if (index === this.props.activeContrastIndex) {
return 'selectedXform';
}
return 'unselectedXform';
}
render() {
const { predictors, activeContrastIndex, activeContrast } = this.props;
const { mode } = this.state;
const AddMode = () => (
<div>
{activeContrastIndex === -1 &&
<h2>
Add a new contrast:
</h2>
}
<ContrastEditor
onSave={this.onSave}
onCancel={this.onCancel}
availablePredictors={predictors}
activeContrast={activeContrast ? activeContrast : emptyContrast()}
updateBuilderState={this.props.updateBuilderState}
contrastErrors={this.props.contrastErrors}
key={activeContrastIndex}
/>
</div>
);
const ViewMode = () => (
<div>
<br />
{mode !== 'add' && <DisplayErrorsInline errors={this.props.contrastErrors} />}
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId="droppable">
{(provided: DroppableProvided, snapshot: DroppableStateSnapshot) => (
<div
ref={provided.innerRef}
{...provided.droppableProps}
>
<List
size="small"
bordered={true}
dataSource={this.props.contrasts}
locale={{ emptyText: 'You haven\'t added any contrasts' }}
renderItem={(contrast, index) => (
<List.Item className={this.getStyle(index)}>
<Draggable key={index} draggableId={'' + index} index={index}>
{(providedDraggable: DraggableProvided, snapshotDraggable: DraggableStateSnapshot) => (
<div
style={{'width': '100%'}}
ref={providedDraggable.innerRef}
{...providedDraggable.dragHandleProps}
>
<div {...providedDraggable.draggableProps}>
<ContrastDisplay
key={index}
index={index}
contrast={contrast}
onDelete={this.onDelete}
onEdit={this.onEdit}
/>
{providedDraggable.placeholder}
</div>
</div>
)}
</Draggable>
</List.Item>
)}
/>
</div>
)}
</Droppable>
</DragDropContext>
<br />
<Button type="default" onClick={() => this.setState({ mode: 'add' })}>
<Icon type="plus" /> Add Contrast
</Button>
<p />
<Button type="default" onClick={this.addAutoContrasts}>
<Icon type="plus" /> Generate Automatic Contrasts
</Button>
</div>
);
return (
<div>
<Row>
<Col md={9}>
{ViewMode()}
</Col>
<Col md={1}/>
<Col md={14}>
{mode === 'add' && AddMode()}
</Col>
</Row>
</div>
);
}
}
|
rwblair/BLiMP
|
neuroscout/frontend/src/utils/index.ts
|
<filename>neuroscout/frontend/src/utils/index.ts
import { message } from 'antd';
import { authActions } from '../auth.actions';
// Display error to user as a UI notification and log it to console
export const displayError = (error: Error) => {
try {
message.error(error.toString(), 5);
} catch (e) {
// to make jsdom tests work
return;
} finally {
// tslint:disable-next-line:no-console
console.error(error);
}
};
// moveItem moves an item in a given array up (toward index zero) or down (toward the last index),
// returning a new array
export type MoveItem<T> = (array: Array<T>, index: number, direction: 'up' | 'down') => Array<T>;
export const moveItem: MoveItem<any> = (array, index, direction) => {
let newArray = [...array];
if (direction === 'up') {
if (index === 0) return newArray;
newArray[index - 1] = array[index];
newArray[index] = array[index - 1];
} else if (direction === 'down') {
if (index >= array.length - 1) return newArray;
newArray[index + 1] = array[index];
newArray[index] = array[index + 1];
} else {
throw new Error('Invalid direction');
}
return newArray;
};
async function pres(res) {
// tslint:disable-next-line:no-console
console.log(await res);
}
export const _fetch = (path: string, options?: object) => {
return fetch(path, options).then(response => {
// Need to figure this response out. openLogin triggers modal to popup,
// but in next cycle. Keep track of request, and after submit on modal
// run jwt fetch again?
if (response.status === 401) {
authActions.update({
openLogin: true,
loggedIn: false,
});
throw new Error('Please Login Again');
}
if (response.status >= 400) {
pres(response);
return { statusCode: response.status };
} else {
return response.json().then(json => {
// Always add statusCode to the data object or array returned by response.json()
// This is problematic if length is ever an attribute of a non array response from api.
// Also problematic if response.json() returns and empty string
let copy: any;
if ('length' in json) {
// array
copy = [...json];
(copy as any).statusCode = response.status;
} else {
// object
copy = { ...json, statusCode: response.status };
}
return copy;
});
}
});
};
// Wrapper around the standard 'fetch' that takes care of:
// - Adding jwt to request header
// - Decoding JSON response and adding the response status code to decoded JSON object
export const jwtFetch = (path: string, options?: any, noCT?: boolean) => {
const jwt = window.localStorage.getItem('jwt');
if (!options) { options = {}; }
if (!options.headers) { options.headers = {}; }
options.headers.Authorization = 'JWT ' + jwt;
if (!options.headers['Content-type'] && !noCT) {
options.headers['Content-type'] = 'application/json';
}
return _fetch(path, options);
};
export const timeout = (ms: number) => {
return new Promise(resolve => setTimeout(resolve, ms));
};
export const alphaSort = (x: string[]) => {
return x.sort((a, b) => a.localeCompare(b));
};
export const reorder = (list: any[], startIndex: number, endIndex: number): any[] => {
const result = [...list];
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
export const isDefined = <T>(argument: T | undefined): argument is T => {
return argument !== undefined;
};
|
rwblair/BLiMP
|
neuroscout/frontend/src/App.tsx
|
<filename>neuroscout/frontend/src/App.tsx<gh_stars>0
/*
Top-level App component containing AppState. The App component is currently responsible for:
- Authentication (signup, login and logout)
- Routing
- Managing user's saved analyses (list display, clone and delete)
*/
import * as React from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import Reflux from 'reflux';
import { Layout, Modal, message } from 'antd';
import ReactGA from 'react-ga';
import './css/App.css';
import { api } from './api';
import { AuthStore } from './auth.store';
import { authActions } from './auth.actions';
import { config } from './config';
import { ApiAnalysis, AppAnalysis, AppState } from './coretypes';
import { LoginModal, ResetPasswordModal, SignupModal } from './Modals';
import Routes from './Routes';
import { jwtFetch, timeout } from './utils';
import { withTracker } from './utils/analytics';
import Navbar from './Navbar';
import Tour from './Tour';
const DOMAINROOT = config.server_url;
const { Content } = Layout;
if (config.ga_key) {
ReactGA.initialize(config.ga_key);
}
type JWTChangeProps = {
loadAnalyses: () => any;
checkAnalysesStatus: (key: number) => any;
jwt: string;
};
// This global var lets the dumb polling loops know when to exit.
let checkCount = 0;
class JWTChange extends React.Component<JWTChangeProps, {}> {
constructor(props) {
super(props);
if (this.props.jwt !== '' && this.props.jwt !== null) {
props.loadAnalyses();
checkCount += 1;
props.checkAnalysesStatus(checkCount);
}
}
componentDidUpdate(prevProps, prevState) {
if (!!this.props.jwt && this.props.jwt !== prevProps.jwt) {
this.props.loadAnalyses();
}
}
render() { return null; }
}
// Top-level App component
class App extends Reflux.Component<any, {}, AppState> {
constructor(props) {
super(props);
this.state = {
loadAnalyses: () => {
api.getAnalyses().then(analyses => {
this.setState({ analyses });
});
},
analyses: [],
publicAnalyses: [],
auth: authActions.getInitialState(),
datasets: [],
onDelete: this.onDelete,
cloneAnalysis: this.cloneAnalysis,
getDatasets: this.getDatasets
};
this.store = AuthStore;
api.getPublicAnalyses().then((publicAnalyses) => {
this.setState({ publicAnalyses });
});
this.getDatasets();
}
getDatasets = () => {
api.getDatasets(false).then((datasets) => {
if (datasets.length !== 0) {
this.setState({ datasets });
}
});
};
/* short polling function checking api for inprocess analyses to see if
* there have been any changes
*/
checkAnalysesStatus = async (key: number) => {
while (true) {
if (key < checkCount) { return; }
if (!(this.state.auth.loggedIn)) { return; }
let changeFlag = false;
let updatedAnalyses = this.state.analyses.map(async (analysis) => {
if (['DRAFT', 'PASSED'].indexOf(analysis.status) > -1) {
return analysis;
}
let id = analysis.id;
return jwtFetch(`${DOMAINROOT}/api/analyses/${id}`, { method: 'get' })
.then((data: ApiAnalysis) => {
if ((data.status !== analysis.status)
&& (['SUBMITTING', 'PENDING'].indexOf(data.status) === -1)) {
changeFlag = true;
message.info(`analysis ${id} updated from ${analysis.status} to ${data.status}`);
analysis.status = data.status;
}
return analysis;
})
.catch(() => { return analysis; });
});
Promise.all(updatedAnalyses).then((values) => {
if (changeFlag) {
this.setState({ analyses: values});
}
});
await timeout(12000);
}
};
// Actually delete existing analysis given its hash ID, called from onDelete()
deleteAnalysis = (id): void => {
api.deleteAnalysis(id).then((response) => {
if (response === true) {
this.setState({ analyses: this.state.analyses.filter(a => a.id !== id) });
}
});
}
// Delete analysis if the necessary conditions are met
onDelete = (analysis: AppAnalysis) => {
const { deleteAnalysis } = this;
if (analysis.status && ['DRAFT', 'FAILED'].includes(analysis.status) === false) {
message.warning('This analysis has already been submitted and cannot be deleted.');
return;
}
Modal.confirm({
title: 'Are you sure you want to delete this analysis?',
content: '',
okText: 'Yes',
cancelText: 'No',
onOk() {
deleteAnalysis(analysis.id);
}
});
}
cloneAnalysis = (id: string): void => {
api.cloneAnalysis(id).then((analysis) => {
if (analysis !== null) {
this.setState({ analyses: this.state.analyses.concat([analysis]) });
}
});
};
AnalyticIndex = withTracker(Routes);
render() {
if (this.state.auth.loggingOut) {
return (
<Router>
<Redirect to="/" />
</Router>
);
}
return (
<Router>
<div>
<JWTChange
loadAnalyses={this.state.loadAnalyses}
checkAnalysesStatus={this.checkAnalysesStatus}
jwt={this.state.auth.jwt}
/>
{this.state.auth.openLogin && <LoginModal {...this.state.auth} />}
{this.state.auth.openReset && <ResetPasswordModal {...this.state.auth} />}
{this.state.auth.openSignup && <SignupModal {...this.state.auth} />}
<Tour
isOpen={this.state.auth.openTour}
closeTour={authActions.closeTour}
/>
<Layout>
<Content style={{ background: '#fff' }}>
<Navbar {...this.state.auth} />
<br />
<Route
render={(routeProps) =>
<this.AnalyticIndex {...{...routeProps, ...this.state}} />
}
/>
</Content>
</Layout>
</div>
</Router>
);
}
componentDidUpdate(prevProps, prevState) {
// Need to do this so logout redirect only happens once, otherwise it'd be an infinite loop
if (this.state.auth.loggingOut) {
authActions.update({ loggingOut: false });
this.setState({analyses: []});
}
}
}
export default App;
|
alexandrepa/caprine
|
source/browser/selectors.ts
|
export default {
conversationList: 'div[role="navigation"] > div > ul',
conversationSelector: '._4u-c._1wfr .__i_, ._4u-c._1wfr #conversationWindow'
};
|
stscoundrel/goodbrother
|
src/client.ts
|
<gh_stars>0
import axios from 'axios';
import { PullRequest, PullRequestSearchResponses } from './models/pull-request';
import { fromPullRequestSearchResponse } from './mappers/pull-requests';
const API_URL = 'https://api.github.com';
const MAX_REQUESTS = 5;
const getPullRequestsByUser = async (username: string) : Promise<PullRequest[]> => {
let hasMoreResults = true;
let page = 1;
const items: PullRequest[] = [];
while (hasMoreResults && page <= MAX_REQUESTS) {
try {
// eslint-disable-next-line no-await-in-loop
const response = await axios.get(`${API_URL}/search/issues?q=user:${username}+is:pr+state:open&per_page=100&page=${page}`);
const responsePRs = response.data as PullRequestSearchResponses;
items.push(
...responsePRs.items.map((pullRequest) => fromPullRequestSearchResponse(pullRequest)),
);
if (items.length >= responsePRs.total_count || responsePRs.items.length === 0) {
hasMoreResults = false;
}
page += 1;
} catch (e) {
throw new Error(`Could not list PRs for user ${username}. Faced error: ${e.message}`);
}
}
return items;
};
export default {
getPullRequestsByUser,
};
|
stscoundrel/goodbrother
|
tests/unit/pull-requests.test.ts
|
<gh_stars>0
import axios from 'axios';
import mockPrSearchResponse from '../fixtures/pr-search-response.json';
import { getPullRequestsByUser, groupPullRequestsByRepository } from '../../src';
jest.mock('axios');
describe('Goodbrother PR tests', () => {
beforeEach(() => {
axios.get.mockRestore();
});
test('By user: processes search response to pull request models', async () => {
// Mock Github api call
axios.get.mockImplementationOnce(() => Promise.resolve({ data: mockPrSearchResponse }));
const results = await getPullRequestsByUser('stscoundrel');
results.forEach((result) => {
expect(Object.keys(result)).toEqual(['id', 'name', 'link', 'isDependabot', 'repository']);
});
expect(results[0].name).toBe('Bump next-pwa from 5.4.0 to 5.4.4');
expect(results[0].link).toBe('https://github.com/stscoundrel/runes/pull/108');
expect(results[0].isDependabot).toBeTruthy();
expect(results.length).toBe(16);
});
test('By user: errors if GH api fails', async () => {
axios.get
.mockImplementationOnce(() => { throw new Error('GH sucks today'); });
expect(async () => {
await getPullRequestsByUser('stscoundrel');
}).rejects.toThrow('Could not list PRs for user stscoundrel. Faced error: GH sucks today');
});
test('Groups found PRs by repository', async () => {
// Mock Github api call
axios.get.mockImplementationOnce(() => Promise.resolve({ data: mockPrSearchResponse }));
const response = await getPullRequestsByUser('stscoundrel');
const result = groupPullRequestsByRepository(response);
const expected = [
{
name: 'stscoundrel/runes',
link: 'https://github.com/stscoundrel/runes',
count: 13,
pullRequests: [
{
id: 1075530244,
name: 'Bump next-pwa from 5.4.0 to 5.4.4',
link: 'https://github.com/stscoundrel/runes/pull/108',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067868936,
name: 'Bump eslint-plugin-react-hooks from 4.2.0 to 4.3.0',
link: 'https://github.com/stscoundrel/runes/pull/105',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067868852,
name: 'Bump eslint-config-next from 12.0.2 to 12.0.4',
link: 'https://github.com/stscoundrel/runes/pull/104',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067868687,
name: 'Bump babel-jest from 27.3.1 to 27.4.2',
link: 'https://github.com/stscoundrel/runes/pull/103',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067868357,
name: 'Bump eslint-plugin-jest from 25.2.2 to 25.3.0',
link: 'https://github.com/stscoundrel/runes/pull/102',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067868269,
name: 'Bump jest from 27.3.1 to 27.4.2',
link: 'https://github.com/stscoundrel/runes/pull/101',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067868016,
name: 'Bump @babel/eslint-parser from 7.16.0 to 7.16.3',
link: 'https://github.com/stscoundrel/runes/pull/100',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067867842,
name: 'Bump cypress from 8.7.0 to 9.1.0',
link: 'https://github.com/stscoundrel/runes/pull/99',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067867532,
name: 'Bump eslint-plugin-import from 2.25.2 to 2.25.3',
link: 'https://github.com/stscoundrel/runes/pull/97',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067867444,
name: 'Bump next-sitemap from 1.6.192 to 1.6.203',
link: 'https://github.com/stscoundrel/runes/pull/96',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067867250,
name: 'Bump sass from 1.43.4 to 1.44.0',
link: 'https://github.com/stscoundrel/runes/pull/95',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067866740,
name: 'Bump eslint-plugin-react from 7.26.1 to 7.27.1',
link: 'https://github.com/stscoundrel/runes/pull/94',
isDependabot: true,
repository: 'stscoundrel/runes',
},
{
id: 1067866608,
name: 'Bump eslint-plugin-jsx-a11y from 6.4.1 to 6.5.1',
link: 'https://github.com/stscoundrel/runes/pull/93',
isDependabot: true,
repository: 'stscoundrel/runes',
},
],
},
{
name: 'stscoundrel/gatsby-source-plugin-zoega',
link: 'https://github.com/stscoundrel/gatsby-source-plugin-zoega',
count: 1,
pullRequests: [
{
id: 1068208284,
name: 'Bump eslint-config-airbnb-base from 14.2.1 to 15.0.0',
link: 'https://github.com/stscoundrel/gatsby-source-plugin-zoega/pull/18',
isDependabot: true,
repository: 'stscoundrel/gatsby-source-plugin-zoega',
},
],
},
{
name: 'stscoundrel/gatsby-source-cleasby-vigfusson',
link: 'https://github.com/stscoundrel/gatsby-source-cleasby-vigfusson',
count: 1,
pullRequests: [
{
id: 1067800663,
name: 'Bump eslint-config-airbnb-base from 14.2.1 to 15.0.0',
link: 'https://github.com/stscoundrel/gatsby-source-cleasby-vigfusson/pull/23',
isDependabot: true,
repository: 'stscoundrel/gatsby-source-cleasby-vigfusson',
},
],
},
{
name: 'stscoundrel/bower',
link: 'https://github.com/stscoundrel/bower',
count: 1,
pullRequests: [
{
id: 874776617,
name: 'CI workflow: add Node 16',
link: 'https://github.com/stscoundrel/bower/pull/1',
isDependabot: false,
repository: 'stscoundrel/bower',
},
],
},
];
expect(result).toEqual(expected);
});
test('Paginates response, if more pages available', async () => {
/**
* Mock search api response, that claims to have 203 results.
* It's same response each time, we just expect to fetch it thrice.
*/
const mockPaginatedResponse = { ...mockPrSearchResponse };
// Fill fixture with 100 copies of same PR.
const fixturePR = mockPrSearchResponse.items[0];
mockPaginatedResponse.items = [];
// Claim to have 203 results.
mockPaginatedResponse.total_count = 203;
for (let i = 0; i < 100; i += 1) {
mockPaginatedResponse.items.push(fixturePR);
}
axios.get.mockImplementation(() => Promise.resolve({ data: mockPaginatedResponse }));
const result = await getPullRequestsByUser('stscoundrel');
// Assert API received three calls with increasing paged value
expect(axios.get).toHaveBeenCalledTimes(3);
expect(axios.get.mock.calls[0][0]).toEqual('https://api.github.com/search/issues?q=user:stscoundrel+is:pr+state:open&per_page=100&page=1');
expect(axios.get.mock.calls[1][0]).toEqual('https://api.github.com/search/issues?q=user:stscoundrel+is:pr+state:open&per_page=100&page=2');
expect(axios.get.mock.calls[2][0]).toEqual('https://api.github.com/search/issues?q=user:stscoundrel+is:pr+state:open&per_page=100&page=3');
// Assert we received all items from responses.
expect(result.length).toEqual(mockPaginatedResponse.items.length * 3);
});
});
|
stscoundrel/goodbrother
|
src/models/pull-request.ts
|
<reponame>stscoundrel/goodbrother
export interface PullRequestUser {
login: string,
}
export interface PullRequest {
id: string,
name: string,
link: string,
isDependabot: boolean,
repository: string,
}
export interface PullRequestSearchResponse {
id: string,
title: string,
user: PullRequestUser,
html_url: string,
repository_url: string,
}
export interface PullRequestSearchResponses {
total_count: number,
items: PullRequestSearchResponse[],
}
|
stscoundrel/goodbrother
|
tests/integration/github.test.ts
|
<reponame>stscoundrel/goodbrother<filename>tests/integration/github.test.ts
import { getPullRequestsByUser, groupPullRequestsByRepository } from '../../src';
describe('Goodbrother integration test suite', () => {
test('Gets PRs by user', async () => {
const result = await getPullRequestsByUser('stscoundrel');
// Should always have debug PR on goodbrother repository.
expect(result.some((pullRequest) => pullRequest.repository === 'stscoundrel/goodbrother'))
.toBeTruthy();
expect(result.some((pullRequest) => pullRequest.name === 'Fixture PR for integration tests'))
.toBeTruthy();
expect(result.length > 0).toBeTruthy();
});
test('Groups PRs by user', async () => {
const response = await getPullRequestsByUser('stscoundrel');
const result = groupPullRequestsByRepository(response);
const goodbrotherPRs = result.filter((repository) => repository.name === 'stscoundrel/goodbrother')[0];
expect(goodbrotherPRs.pullRequests.some((pullRequest) => pullRequest.name === 'Fixture PR for integration tests'))
.toBeTruthy();
expect(goodbrotherPRs.pullRequests.length > 0).toBeTruthy();
});
});
|
stscoundrel/goodbrother
|
src/mappers/pull-requests.ts
|
<reponame>stscoundrel/goodbrother
import { PullRequestSearchResponse, PullRequest } from '../models/pull-request';
export const fromPullRequestSearchResponse = (pullRequestResponse: PullRequestSearchResponse)
: PullRequest => ({
id: pullRequestResponse.id,
name: pullRequestResponse.title,
link: pullRequestResponse.html_url,
isDependabot: pullRequestResponse.user.login.includes('dependabot'),
repository: pullRequestResponse.repository_url.replace('https://api.github.com/repos/', ''),
});
export default {
fromPullRequestSearchResponse,
};
|
stscoundrel/goodbrother
|
src/models/repository.ts
|
<filename>src/models/repository.ts<gh_stars>0
import { PullRequest } from './pull-request';
export interface RepositorySummary {
name: string,
link: string,
count: number,
pullRequests: PullRequest[],
}
|
stscoundrel/goodbrother
|
src/index.ts
|
<filename>src/index.ts<gh_stars>0
import { RepositorySummary } from './models/repository';
import { PullRequest } from './models/pull-request';
import client from './client';
export const groupPullRequestsByRepository = (pullRequests: PullRequest[])
: RepositorySummary[] => {
const summaries: RepositorySummary[] = [];
const repositories = new Set();
pullRequests.forEach((pullRequest) => repositories.add(pullRequest.repository));
repositories.forEach((repository: string) => {
const pulls = pullRequests.filter((pullRequest) => pullRequest.repository === repository);
const summary = {
name: repository,
link: `https://github.com/${repository}`,
count: pulls.length,
pullRequests: pulls,
};
summaries.push(summary);
});
return summaries;
};
export const getPullRequestsByUser = async (username: string): Promise<PullRequest[]> => (
client.getPullRequestsByUser(username)
);
export default {
getPullRequestsByUser,
groupPullRequestsByRepository,
};
|
SudoDotDog/Sudoo-Flag
|
test/mock/declare.ts
|
/**
* @author WMXPY
* @namespace Flag
* @description Declare
* @override Mock
*/
export type MockTwoFlagType = 'hello' | 'world';
|
SudoDotDog/Sudoo-Flag
|
src/declare.ts
|
/**
* @author WMXPY
* @namespace Flag
* @description Declare
*/
export type FlagConfig<F extends string> = {
readonly target: string;
readonly flags: F[];
};
export type FlagStorage<F extends string> = {
readonly targets: string[];
readonly flags: Array<FlagConfig<F>>;
};
|
SudoDotDog/Sudoo-Flag
|
test/unit/util.test.ts
|
<reponame>SudoDotDog/Sudoo-Flag
/**
* @author WMXPY
* @namespace Flag
* @description Util
* @override Unit Test
*/
import { expect } from "chai";
import * as Chance from "chance";
import { FlagConfig, utilAttachFlag, utilRemoveFlag } from "../../src";
import { MockTwoFlagType } from "../mock/declare";
describe('Given (Util) Helper Methods', (): void => {
const chance: Chance.Chance = new Chance('flag-util');
it('should be able to attach flag', (): void => {
const targetName: string = chance.string();
const originalConfig: FlagConfig<MockTwoFlagType> = {
target: targetName,
flags: ['hello'],
};
const newConfig: FlagConfig<MockTwoFlagType> = utilAttachFlag(originalConfig, 'world');
expect(newConfig.flags).to.be.lengthOf(2);
expect(newConfig.flags[0]).to.be.equal('hello');
expect(newConfig.flags[1]).to.be.equal('world');
});
it('should be able to remove flag', (): void => {
const targetName: string = chance.string();
const originalConfig: FlagConfig<MockTwoFlagType> = {
target: targetName,
flags: ['hello', 'world'],
};
const newConfig: FlagConfig<MockTwoFlagType> = utilRemoveFlag(originalConfig, 'world');
expect(newConfig.flags).to.be.lengthOf(1);
expect(newConfig.flags[0]).to.be.equal('hello');
});
});
|
SudoDotDog/Sudoo-Flag
|
src/util.ts
|
<reponame>SudoDotDog/Sudoo-Flag<filename>src/util.ts
/**
* @author WMXPY
* @namespace Flag
* @description Util
*/
import { FlagConfig } from "./declare";
export const utilAttachFlag = <F extends string>(flagConfig: FlagConfig<F>, newFlag: F): FlagConfig<F> => {
const existFlags: F[] = flagConfig.flags;
if (existFlags.includes(newFlag)) {
return flagConfig;
}
return {
...flagConfig,
flags: [...existFlags, newFlag],
};
};
export const utilRemoveFlag = <F extends string>(flagConfig: FlagConfig<F>, removeFlag: F): FlagConfig<F> => {
const existFlags: F[] = flagConfig.flags;
if (!existFlags.includes(removeFlag)) {
return flagConfig;
}
return {
...flagConfig,
flags: existFlags.filter((flag: string) => {
return flag !== removeFlag;
}),
};
};
|
SudoDotDog/Sudoo-Flag
|
src/flag.ts
|
/**
* @author WMXPY
* @namespace Flag
* @description Flag
*/
import { FlagConfig, FlagStorage } from "./declare";
import { utilAttachFlag, utilRemoveFlag } from "./util";
export class FlagManager<F extends string = string> {
public static empty<F extends string = string>(): FlagManager<F> {
return new FlagManager<F>([], []);
}
public static fromTargets<F extends string = string>(targets: F[]): FlagManager<F> {
return new FlagManager<F>(targets, []);
}
public static fromStorage<F extends string = string>(storage: FlagStorage<F>): FlagManager<F> {
return new FlagManager<F>(storage.targets, storage.flags);
}
private readonly _targets: string[];
private readonly _flags: Map<string, FlagConfig<F>>;
private constructor(targets: string[], flags: Array<FlagConfig<F>>) {
this._targets = targets;
this._flags = new Map();
for (const flag of flags) {
this._flags.set(flag.target, flag);
}
}
public get targetLength(): number {
return this._targets.length;
}
public get flagLength(): number {
return this._flags.size;
}
public getFlag(target: string): string[] {
const flagConfig: FlagConfig<F> | undefined = this._flags.get(target);
if (!flagConfig) {
return [];
}
return flagConfig.flags;
}
public attachFlag(target: string, flag: F): this {
const flagConfig: FlagConfig<F> | undefined = this._flags.get(target);
if (!flagConfig) {
return this;
}
const newConfig: FlagConfig<F> = utilAttachFlag(flagConfig, flag);
this._flags.set(target, newConfig);
return this;
}
public removeFlag(target: string, flag: F): this {
const flagConfig: FlagConfig<F> | undefined = this._flags.get(target);
if (!flagConfig) {
return this;
}
const newConfig: FlagConfig<F> = utilRemoveFlag(flagConfig, flag);
this._flags.set(target, newConfig);
return this;
}
public toStorage(): FlagStorage<F> {
return {
targets: this._targets,
flags: Array.from(this._flags.values()),
};
}
}
|
SudoDotDog/Sudoo-Flag
|
src/index.ts
|
/**
* @author WMXPY
* @namespace Flag
* @description index
*/
export * from "./declare";
export * from "./flag";
export * from "./util";
|
PixDay/Pokedex
|
src/app/models/pokemon.model.ts
|
export class Pokemon
{
name: string;
image: string;
id: number;
pokemonId: number;
types: string[];
default_competencies: string[];
}
|
PixDay/Pokedex
|
src/app/services/pokemons/pokemons.service.ts
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Pokemon } from 'src/app/models/pokemon.model';
@Injectable({
providedIn: 'root'
})
export class PokemonsService {
constructor(private http: HttpClient) { }
getPokemon(id: number, listOfPokemons: Pokemon[], loopIndex: number) {
(this.http.get(`https://pokeapi.co/api/v2/pokemon/${id}`).forEach((data: any) => {
listOfPokemons[loopIndex].image = data.sprites.front_default;
data.types.forEach((types: any) => {
listOfPokemons[loopIndex].types.push(types.type.name);
})
}));
}
}
|
PixDay/Pokedex
|
src/app/pages/regions/regions.component.ts
|
import { Component, OnInit } from '@angular/core';
import { PokedexService } from 'src/app/services/pokedex/pokedex.service';
import { PokemonsService } from 'src/app/services/pokemons/pokemons.service';
import { Pokemon } from 'src/app/models/pokemon.model';
@Component({
selector: 'app-regions',
templateUrl: './regions.component.html',
styleUrls: ['./regions.component.css']
})
export class RegionsComponent implements OnInit {
public regions: string[] =
[
'National',
'Kanto',
'Johto',
'Hoenn',
'Sinnoh',
'Unova',
'Kalos',
'Alola',
'Galar'
];
currentRegion: string = "";
currentRegionIndex: number = 0;
listOfPokemons: Pokemon[] = [];
constructor(public pokedexService: PokedexService, public pokemonService: PokemonsService)
{
}
ngOnInit(): void
{
}
setRegion(region: string)
{
this.currentRegion = region;
this.currentRegionIndex = this.regions.indexOf(region) + 1;
this.pokedexService.getPokedex(this.currentRegionIndex, this.listOfPokemons);
}
resetApp()
{
this.currentRegion = '';
this.listOfPokemons = [];
}
}
|
PixDay/Pokedex
|
src/app/services/pokedex/pokedex.service.ts
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Pokemon } from 'src/app/models/pokemon.model';
import { PokemonsService } from '../pokemons/pokemons.service';
@Injectable({
providedIn: 'root'
})
export class PokedexService {
constructor(private http: HttpClient, public pokemonService: PokemonsService) { }
getPokedex(region: number, listOfPokemon: Pokemon[])
{
this.http.get('https://pokeapi.co/api/v2/pokedex/' + region).forEach((data: any) => {
let id = 1;
data.pokemon_entries.forEach((pokemonData: any) => {
let pokemon: Pokemon = {
name: pokemonData.pokemon_species.name,
image: "",
id: id,
pokemonId: (pokemonData.pokemon_species.url.match(/(\d+)(?!.*\d)/)[0]),
types: [],
default_competencies: []
};
id++;
listOfPokemon.push(pokemon);
});
id = 0;
listOfPokemon.forEach(pokemon => {
this.pokemonService.getPokemon(pokemon.pokemonId, listOfPokemon, id);
id++;
})
});
}
}
|
beremm14/Swift_Pi_Test
|
Pi_Node_Server/src/server.ts
|
// Node.js Modul
import * as path from 'path';
// Externes Modul (via npm installieren)
import * as express from 'express';
import * as bodyParser from 'body-parser';
export class Server {
private _port: number;
private _server: express.Express;
constructor (port: number) {
const assetsPath = path.join(__dirname, '..', 'assets');
this._port = port;
this._server = express();
// Alle Dateien im assets-Ordner verwenden
this._server.use('/', express.static(assetsPath));
this._server.use(bodyParser.json());
this._server.use(bodyParser.urlencoded());
}
public start () {
this._server.listen(this._port);
console.log('HTTP Server gestartet auf Port: ' + this._port);
}
public get port () {
return this._port;
}
}
|
beremm14/Swift_Pi_Test
|
Pi_Node_Server/src/main.ts
|
import { Server } from './server';
class Main {
public static main () {
const server = new Server(8080);
server.start();
}
}
Main.main();
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/stomp.ts
|
<reponame>virtualmusicsoft/gamma<filename>server-midi/front-end-ionic2/app/stomp.ts<gh_stars>0
// Generated by CoffeeScript 1.7.1
/*
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2010-2013 [<NAME>](http://jmesnil.net/)
Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
*/
(function() {
var Byte, Client, Frame, Stomp,
__hasProp = {}.hasOwnProperty,
__slice = [].slice;
Byte = {
LF: '\x0A',
NULL: '\x00'
};
Frame = (function() {
var unmarshallSingle;
function Frame(command, headers, body) {
this.command = command;
this.headers = headers != null ? headers : {};
this.body = body != null ? body : '';
}
Frame.sizeOfUTF8 = function(s) {
if (s) {
return encodeURI(s).match(/%..|./g).length;
} else {
return 0;
}
};
Frame.prototype.toString = function() {
var lines, name, skipContentLength, value, _ref;
lines = [this.command];
skipContentLength = this.headers['content-length'] === false ? true : false;
if (skipContentLength) {
delete this.headers['content-length'];
}
_ref = this.headers;
for (name in _ref) {
if (!__hasProp.call(_ref, name)) continue;
value = _ref[name];
lines.push("" + name + ":" + value);
}
if (this.body && !skipContentLength) {
lines.push("content-length:" + (Frame.sizeOfUTF8(this.body)));
}
lines.push(Byte.LF + this.body);
return lines.join(Byte.LF);
};
unmarshallSingle = function(data) {
var body, chr, command, divider, headerLines, headers, i, idx, len, line, start, trim, _i, _j, _len, _ref, _ref1;
divider = data.search(RegExp("" + Byte.LF + Byte.LF));
headerLines = data.substring(0, divider).split(Byte.LF);
command = headerLines.shift();
headers = {};
trim = function(str) {
return str.replace(/^\s+|\s+$/g, '');
};
_ref = headerLines.reverse();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
idx = line.indexOf(':');
headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1));
}
body = '';
start = divider + 2;
if (headers['content-length']) {
len = parseInt(headers['content-length']);
body = ('' + data).substring(start, start + len);
} else {
chr = null;
for (i = _j = start, _ref1 = data.length; start <= _ref1 ? _j < _ref1 : _j > _ref1; i = start <= _ref1 ? ++_j : --_j) {
chr = data.charAt(i);
if (chr === Byte.NULL) {
break;
}
body += chr;
}
}
return new Frame(command, headers, body);
};
Frame.unmarshall = function(datas) {
var data;
return (function() {
var _i, _len, _ref, _results;
_ref = datas.split(RegExp("" + Byte.NULL + Byte.LF + "*"));
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
data = _ref[_i];
if ((data != null ? data.length : void 0) > 0) {
_results.push(unmarshallSingle(data));
}
}
return _results;
})();
};
Frame.marshall = function(command, headers, body) {
var frame;
frame = new Frame(command, headers, body);
return frame.toString() + Byte.NULL;
};
return Frame;
})();
Client = (function() {
var now;
function Client(ws) {
this.ws = ws;
this.ws.binaryType = "arraybuffer";
this.counter = 0;
this.connected = false;
this.heartbeat = {
outgoing: 10000,
incoming: 10000
};
this.maxWebSocketFrameSize = 16 * 1024;
this.subscriptions = {};
}
Client.prototype.debug = function(message) {
var _ref;
return typeof window !== "undefined" && window !== null ? (_ref = window.console) != null ? _ref.log(message) : void 0 : void 0;
};
now = function() {
if (Date.now) {
return Date.now();
} else {
return new Date().valueOf;
}
};
Client.prototype._transmit = function(command, headers, body) {
var out;
out = Frame.marshall(command, headers, body);
if (typeof this.debug === "function") {
this.debug(">>> " + out);
}
while (true) {
if (out.length > this.maxWebSocketFrameSize) {
this.ws.send(out.substring(0, this.maxWebSocketFrameSize));
out = out.substring(this.maxWebSocketFrameSize);
if (typeof this.debug === "function") {
this.debug("remaining = " + out.length);
}
} else {
return this.ws.send(out);
}
}
};
Client.prototype._setupHeartbeat = function(headers) {
var serverIncoming, serverOutgoing, ttl, v, _ref, _ref1;
if ((_ref = headers.version) !== Stomp.VERSIONS.V1_1 && _ref !== Stomp.VERSIONS.V1_2) {
return;
}
_ref1 = (function() {
var _i, _len, _ref1, _results;
_ref1 = headers['heart-beat'].split(",");
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
_results.push(parseInt(v));
}
return _results;
})(), serverOutgoing = _ref1[0], serverIncoming = _ref1[1];
if (!(this.heartbeat.outgoing === 0 || serverIncoming === 0)) {
ttl = Math.max(this.heartbeat.outgoing, serverIncoming);
if (typeof this.debug === "function") {
this.debug("send PING every " + ttl + "ms");
}
this.pinger = Stomp.setInterval(ttl, (function(_this) {
return function() {
_this.ws.send(Byte.LF);
return typeof _this.debug === "function" ? _this.debug(">>> PING") : void 0;
};
})(this));
}
if (!(this.heartbeat.incoming === 0 || serverOutgoing === 0)) {
ttl = Math.max(this.heartbeat.incoming, serverOutgoing);
if (typeof this.debug === "function") {
this.debug("check PONG every " + ttl + "ms");
}
return this.ponger = Stomp.setInterval(ttl, (function(_this) {
return function() {
var delta;
delta = now() - _this.serverActivity;
if (delta > ttl * 2) {
if (typeof _this.debug === "function") {
_this.debug("did not receive server activity for the last " + delta + "ms");
}
return _this.ws.close();
}
};
})(this));
}
};
Client.prototype._parseConnect = function() {
var args, connectCallback, errorCallback, headers;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
headers = {};
switch (args.length) {
case 2:
headers = args[0], connectCallback = args[1];
break;
case 3:
if (args[1] instanceof Function) {
headers = args[0], connectCallback = args[1], errorCallback = args[2];
} else {
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2];
}
break;
case 4:
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3];
break;
default:
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3], headers.host = args[4];
}
return [headers, connectCallback, errorCallback];
};
Client.prototype.connect = function() {
var args, errorCallback, headers, out;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
out = this._parseConnect.apply(this, args);
headers = out[0], this.connectCallback = out[1], errorCallback = out[2];
if (typeof this.debug === "function") {
this.debug("Opening Web Socket...");
}
this.ws.onmessage = (function(_this) {
return function(evt) {
var arr, c, client, data, frame, messageID, onreceive, subscription, _i, _len, _ref, _results;
data = typeof ArrayBuffer !== 'undefined' && evt.data instanceof ArrayBuffer ? (arr = new Uint8Array(evt.data), typeof _this.debug === "function" ? _this.debug("--- got data length: " + arr.length) : void 0, ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = arr.length; _i < _len; _i++) {
c = arr[_i];
_results.push(String.fromCharCode(c));
}
return _results;
})()).join('')) : evt.data;
_this.serverActivity = now();
if (data === Byte.LF) {
if (typeof _this.debug === "function") {
_this.debug("<<< PONG");
}
return;
}
if (typeof _this.debug === "function") {
_this.debug("<<< " + data);
}
_ref = Frame.unmarshall(data);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
frame = _ref[_i];
switch (frame.command) {
case "CONNECTED":
if (typeof _this.debug === "function") {
_this.debug("connected to server " + frame.headers.server);
}
_this.connected = true;
_this._setupHeartbeat(frame.headers);
_results.push(typeof _this.connectCallback === "function" ? _this.connectCallback(frame) : void 0);
break;
case "MESSAGE":
subscription = frame.headers.subscription;
onreceive = _this.subscriptions[subscription] || _this.onreceive;
if (onreceive) {
client = _this;
messageID = frame.headers["message-id"];
frame.ack = function(headers) {
if (headers == null) {
headers = {};
}
return client.ack(messageID, subscription, headers);
};
frame.nack = function(headers) {
if (headers == null) {
headers = {};
}
return client.nack(messageID, subscription, headers);
};
_results.push(onreceive(frame));
} else {
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled received MESSAGE: " + frame) : void 0);
}
break;
case "RECEIPT":
_results.push(typeof _this.onreceipt === "function" ? _this.onreceipt(frame) : void 0);
break;
case "ERROR":
_results.push(typeof errorCallback === "function" ? errorCallback(frame) : void 0);
break;
default:
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled frame: " + frame) : void 0);
}
}
return _results;
};
})(this);
this.ws.onclose = (function(_this) {
return function() {
var msg;
msg = "Whoops! Lost connection to " + _this.ws.url;
if (typeof _this.debug === "function") {
_this.debug(msg);
}
_this._cleanUp();
return typeof errorCallback === "function" ? errorCallback(msg) : void 0;
};
})(this);
return this.ws.onopen = (function(_this) {
return function() {
if (typeof _this.debug === "function") {
_this.debug('Web Socket Opened...');
}
headers["accept-version"] = Stomp.VERSIONS.supportedVersions();
headers["heart-beat"] = [_this.heartbeat.outgoing, _this.heartbeat.incoming].join(',');
return _this._transmit("CONNECT", headers);
};
})(this);
};
Client.prototype.disconnect = function(disconnectCallback, headers) {
if (headers == null) {
headers = {};
}
this._transmit("DISCONNECT", headers);
this.ws.onclose = null;
this.ws.close();
this._cleanUp();
return typeof disconnectCallback === "function" ? disconnectCallback() : void 0;
};
Client.prototype._cleanUp = function() {
this.connected = false;
if (this.pinger) {
Stomp.clearInterval(this.pinger);
}
if (this.ponger) {
return Stomp.clearInterval(this.ponger);
}
};
Client.prototype.send = function(destination, headers, body) {
if (headers == null) {
headers = {};
}
if (body == null) {
body = '';
}
headers.destination = destination;
return this._transmit("SEND", headers, body);
};
Client.prototype.subscribe = function(destination, callback, headers) {
var client;
if (headers == null) {
headers = {};
}
if (!headers.id) {
headers.id = "sub-" + this.counter++;
}
headers.destination = destination;
this.subscriptions[headers.id] = callback;
this._transmit("SUBSCRIBE", headers);
client = this;
return {
id: headers.id,
unsubscribe: function() {
return client.unsubscribe(headers.id);
}
};
};
Client.prototype.unsubscribe = function(id) {
delete this.subscriptions[id];
return this._transmit("UNSUBSCRIBE", {
id: id
});
};
Client.prototype.begin = function(transaction) {
var client, txid;
txid = transaction || "tx-" + this.counter++;
this._transmit("BEGIN", {
transaction: txid
});
client = this;
return {
id: txid,
commit: function() {
return client.commit(txid);
},
abort: function() {
return client.abort(txid);
}
};
};
Client.prototype.commit = function(transaction) {
return this._transmit("COMMIT", {
transaction: transaction
});
};
Client.prototype.abort = function(transaction) {
return this._transmit("ABORT", {
transaction: transaction
});
};
Client.prototype.ack = function(messageID, subscription, headers) {
if (headers == null) {
headers = {};
}
headers["message-id"] = messageID;
headers.subscription = subscription;
return this._transmit("ACK", headers);
};
Client.prototype.nack = function(messageID, subscription, headers) {
if (headers == null) {
headers = {};
}
headers["message-id"] = messageID;
headers.subscription = subscription;
return this._transmit("NACK", headers);
};
return Client;
})();
Stomp = {
VERSIONS: {
V1_0: '1.0',
V1_1: '1.1',
V1_2: '1.2',
supportedVersions: function() {
return '1.1,1.0';
}
},
client: function(url, protocols) {
var klass, ws;
if (protocols == null) {
protocols = ['v10.stomp', 'v11.stomp'];
}
klass = Stomp.WebSocketClass || WebSocket;
ws = new klass(url, protocols);
return new Client(ws);
},
over: function(ws) {
return new Client(ws);
},
Frame: Frame
};
if (typeof exports !== "undefined" && exports !== null) {
exports.Stomp = Stomp;
}
if (typeof window !== "undefined" && window !== null) {
Stomp.setInterval = function(interval, f) {
return window.setInterval(f, interval);
};
Stomp.clearInterval = function(id) {
return window.clearInterval(id);
};
window.Stomp = Stomp;
} else if (!exports) {
self.Stomp = Stomp;
}
}).call(this);
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/pages/choose-chord/choose-chord.ts
|
<gh_stars>0
import {Page, NavController, NavParams, Alert} from 'ionic-angular';
import {GameChordPage} from '../game-chord/game-chord';
@Page({
templateUrl: 'build/pages/choose-chord/choose-chord.html'
})
export class ChooseChordPage {
constructor(private nav: NavController,
private navParams: NavParams) {
}
onPageDidEnter() {
}
goToGame() {
//TODO: passar parâmetros se for o caso
this.nav.push(GameChordPage);
}
}
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/providers/git-hub-service/git-hub-service.ts
|
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class GitHubService {
constructor(private http: Http) {
}
getRepos(username) {
let repos = this.http.get(`https://api.github.com/users/${username}/repos`);
return repos;
}
getDetails(repo) {
let headers = new Headers();
headers.append('Accept','application/vnd.github.VERSION.html');
return this.http.get(`${repo.url}/readme`, { headers: headers });
}
}
/*
Generated class for the GitHubService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
@Injectable()
export class GitHubService {
data: any = null;
constructor(public http: Http) {}
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.get('path/to/data.json')
.map(res => res.json())
.subscribe(data => {
// we've got back the raw data, now generate the core schedule data
// and save the data for later reference
this.data = data;
resolve(this.data);
});
});
}
}
*/
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/pages/choose-game/choose-game.ts
|
<reponame>virtualmusicsoft/gamma
import {Page, NavController, NavParams, Alert} from 'ionic-angular';
import {GamePage} from '../game/game';
import {NoteLevel} from '../../providers/note-service/note-service';
@Page({
templateUrl: 'build/pages/choose-game/choose-game.html'
})
export class ChooseGamePage {
public sol:boolean = true;
public fa:boolean = false;
public solfa:boolean = false;
public
private delayShowAlertScore:boolean = false;
private delayScore:any;
constructor(private nav: NavController,
private navParams: NavParams) {
}
onPageDidEnter() {
if (this.delayShowAlertScore) {
this.showAlertScore();
}
this.delayShowAlertScore = false;
}
goToGame(levelRaw:String) {
var p_level:NoteLevel = NoteLevel.valueOf(levelRaw);
new Promise((resolve, reject) => {
this.nav.push(GamePage, {resolve: resolve, level:p_level});
}).then(score => {
this.delayScore = score;
this.delayShowAlertScore = true;
});
}
showAlertScore() {
let alert = Alert.create({
title: 'Pontuação',
subTitle: 'Sua pontuação: ' +this.delayScore,
buttons: [{text: 'OK' }]
});
this.nav.present(alert);
}
}
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/typings/index.d.ts
|
/// <reference path="modules/debug/index.d.ts" />
/// <reference path="modules/stomp-websocket/stomp-websocket.d.ts" />
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/pages/result/result.ts
|
<filename>server-midi/front-end-ionic2/app/pages/result/result.ts
import {Page, NavController, NavParams, ViewController} from 'ionic-angular';
import {ChooseGamePage} from '../choose-game/choose-game';
import {RecordsService} from '../../providers/records-service/records-service';
/*
Generated class for the ResultPage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
@Page({
templateUrl: 'build/pages/result/result.html',
})
export class ResultPage {
public records;
public isRecord : boolean = false;
constructor(public nav: NavController,
public navParams: NavParams,
public viewCtrl: ViewController,
public recordsService: RecordsService) {
}
onPageLoaded() {
this.viewCtrl.showBackButton(false);
}
onPageWillEnter() {
new Promise((resolve, reject) => {
this.recordsService.tryAddNewRecord(this.navParams.get("score"), "note-fa-n1", {resolve: resolve});
}).then(data => {
this.records = data[0];
this.isRecord = data[1];
});
}
onPageDidEnter() {
//TODO: informar que se trata de um novo record!
}
getScore() {
return this.navParams.get("score");
}
goToChooseGame() {
this.nav.setRoot(ResultPage);
this.nav.push(ChooseGamePage);
}
}
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/providers/midiinput-service/midiinput-service.ts
|
<gh_stars>0
import {Injectable} from '@angular/core';
import * as SockJS from 'sockjs-client';
import BaseEvent = __SockJSClient.BaseEvent;
import SockJSClass = __SockJSClient.SockJSClass;
export interface HandleMidiInputListerner {
handleMidiInput(message:string):void;
}
export interface ConnectionListerner {
onConnection():void;
onClose():void;
}
@Injectable()
export class MidiInputService {
public host:String = "localhost:8080";
public status:String = "Disconnected";
public count:number = -1;
private client:SockJSClass;
private mystomp:StompClient;
private handleMidiInputListerner:HandleMidiInputListerner;
private connectionListerner:ConnectionListerner;
constructor() {
this.count++;
}
reconnect() {
//TODO: descomentar
///setTimeout($scope.initSockets, 10000);
};
setHandleMidiInputListerner(handleMidiInputListerner:HandleMidiInputListerner) {
this.handleMidiInputListerner = handleMidiInputListerner;
}
setConnectionListerner(connectionListerner:ConnectionListerner) {
this.connectionListerner = connectionListerner;
}
connect() {
if (this.client == null) {
this.status = "Connecting...";
this.client = new SockJS('http://' + this.host + '/note');
this.mystomp = Stomp.over(this.client);
this.mystomp.connect({}, (frame) => {
this.count++;
this.status = "Connected";
this.notifyConnectionListerner();
this.mystomp.subscribe("/topic/midiinput", (message:StompFrame) => {
this.notifyHandleMidiInputListerner(message.body);
});
});
this.client.onclose = this.reconnect;
}
}
notifyHandleMidiInputListerner(raw:string) {
if (this.handleMidiInputListerner != null) {
this.handleMidiInputListerner.handleMidiInput(raw);
}
}
notifyConnectionListerner() {
if (this.connectionListerner != null) {
this.connectionListerner.onConnection();
}
}
}
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/app.ts
|
<filename>server-midi/front-end-ionic2/app/app.ts<gh_stars>0
import {App, Platform, Storage, SqlStorage} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';
import {ConnectMidiInputPage} from './pages/connect-midiinput/connect-midiinput';
import {MidiInputService} from './providers/midiinput-service/midiinput-service';
import {RecordsService} from './providers/records-service/records-service';
@App({
template: '<ion-nav [root]="rootPage"></ion-nav>',
config: {}, // http://ionicframework.com/docs/v2/api/config/Config/,
providers: [MidiInputService, RecordsService]
})
export class MyApp {
//rootPage: any = HomePage;
rootPage: any = ConnectMidiInputPage;
constructor(platform: Platform) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
});
}
}
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/providers/note-service/note-service.ts
|
import {Injectable} from '@angular/core';
export class NoteHtml {
constructor(public src:string, public left:string, public top:string) {}
static Default = class {
static left_upwline : string = "80px";
static left_upwoline : string = "86px";
}
static Clave = class {
static Sol = class {
static C = new NoteHtml("img/note_up_w_line.png", NoteHtml.Default.left_upwline, "68px");
static D = new NoteHtml("img/note_up_wo_line.png", NoteHtml.Default.left_upwoline, "60px");
static E = new NoteHtml("img/note_up_wo_line.png", NoteHtml.Default.left_upwoline, "55px");
static F = new NoteHtml("img/note_up_wo_line.png", NoteHtml.Default.left_upwoline, "49px");
static G = new NoteHtml("img/note_up_wo_line.png", NoteHtml.Default.left_upwoline, "43px");
static CSharp = new NoteHtml("img/note_up_w_line_sharp.png", NoteHtml.Default.left_upwline, "68px");
static DSharp = new NoteHtml("img/note_up_wo_line_sharp.png", NoteHtml.Default.left_upwoline, "60px");
static FSharp = new NoteHtml("img/note_up_wo_line_sharp.png", NoteHtml.Default.left_upwoline, "49px");
static GSharp = new NoteHtml("img/note_up_wo_line_sharp.png", NoteHtml.Default.left_upwoline, "43px");
}
static Fa = class {
static C = new NoteHtml("img/note_down_w_line.png", NoteHtml.Default.left_upwline, "160px");
static B = new NoteHtml("img/note_down_wo_line.png", NoteHtml.Default.left_upwoline, "167px");
static A = new NoteHtml("img/note_down_wo_line.png", NoteHtml.Default.left_upwoline, "172px");
static G = new NoteHtml("img/note_down_wo_line.png", NoteHtml.Default.left_upwoline, "178px");
static F = new NoteHtml("img/note_down_wo_line.png", NoteHtml.Default.left_upwoline, "184px");
static BSharp = new NoteHtml("img/note_down_wo_line_sharp.png", NoteHtml.Default.left_upwoline, "167px");
static ASharp = new NoteHtml("img/note_down_wo_line_sharp.png", NoteHtml.Default.left_upwoline, "172px");
static GSharp = new NoteHtml("img/note_down_wo_line_sharp.png", NoteHtml.Default.left_upwoline, "178px");
}
}
}
export class BasicNote {
constructor(public note:string) {
}
static C = new BasicNote("C");
static D = new BasicNote("D");
static E = new BasicNote("E");
static F = new BasicNote("F");
static G = new BasicNote("G");
static A = new BasicNote("A");
static B = new BasicNote("B");
static CSharp = new BasicNote("C#");
static DSharp = new BasicNote("D#");
static FSharp = new BasicNote("F#");
static GSharp = new BasicNote("G#");
static ASharp = new BasicNote("A#");
static BSharp = new BasicNote("B#");
static ALL : BasicNote[] = [BasicNote.C, BasicNote.D, BasicNote.E, BasicNote.F, BasicNote.G, BasicNote.A, BasicNote.B,
BasicNote.CSharp, BasicNote.DSharp, BasicNote.FSharp, BasicNote.GSharp, BasicNote.ASharp];
static valueOf(noteWithOctave:string) {
var strNote : string = BasicNote.getNote(noteWithOctave);
for (var item of BasicNote.ALL) {
if (item.note == strNote) {
return item;
}
}
throw new Error("Invalid noteWithOctave: " + noteWithOctave);
}
static getNote(noteWithOctave:string) {
var index = noteWithOctave.search(/\d/);
return noteWithOctave.substring(0, index);
}
static getOctave(noteWithOctave:string) {
var index = noteWithOctave.search(/\d/);
return +noteWithOctave.substring(index, noteWithOctave.length);
}
}
export class Note {
public baseNote : BasicNote;
public octave : number;
constructor(public noteWithOctave:string, public info:NoteHtml) {
this.baseNote = BasicNote.valueOf(noteWithOctave);
this.octave = BasicNote.getOctave(noteWithOctave);
}
hasNoteHtml() {
return (this.info == null);
}
static valueOf(noteWithOctave:string) {
//TODO: cosiderar a clave de sol e fá ou apenas uma das duas no parâmetro da função
var result:Note = ClaveSol.get(noteWithOctave);
if (result == null) {
result = ClaveFa.get(noteWithOctave);
}
if (result == null) {
result = new Note(noteWithOctave, null);
}
return result;
}
static get(noteWithOctave:string, notes:Note[]) {
var result = null;
for (var item of notes) {
if (item.noteWithOctave == noteWithOctave) {
return item;
}
}
return result;
}
}
export class ClaveSol extends Note {
//TODO: considerar a configuração do Dó central
//TODO: criar as notas com #
//TODO: ainda não há A e B (verificar como isso se relacionará com o level do game)
static C = new Note("C4", NoteHtml.Clave.Sol.C);
static D = new Note("D4", NoteHtml.Clave.Sol.D);
static E = new Note("E4", NoteHtml.Clave.Sol.E);
static F = new Note("F4", NoteHtml.Clave.Sol.F);
static G = new Note("G4", NoteHtml.Clave.Sol.G);
//TODO: faltando "A" e "B" - ver como vai compatibilizar com os níveis
static CSharp = new Note("C4#", NoteHtml.Clave.Sol.CSharp);
static DSharp = new Note("D4#", NoteHtml.Clave.Sol.DSharp);
static FSharp = new Note("F4#", NoteHtml.Clave.Sol.FSharp);
static GSharp = new Note("G4#", NoteHtml.Clave.Sol.GSharp);
//TODO: faltando "A" - ver como vai compatibilizar com os níveis
static ALL_BASIC_NOTES = [ClaveSol.C, ClaveSol.D, ClaveSol.E, ClaveSol.F, ClaveSol.G];
static ALL_BASIC_SEMI_NOTES = [ClaveSol.CSharp, ClaveSol.DSharp, ClaveSol.FSharp, ClaveSol.GSharp];
static ALL : ClaveSol[] = ClaveSol.ALL_BASIC_NOTES.concat(ClaveSol.ALL_BASIC_SEMI_NOTES);
static get(noteWithOctave:string) {
return Note.get(noteWithOctave, ClaveSol.ALL);
}
}
export class ClaveFa extends Note {
//TODO: criar as notas com #
static C = new Note("C4", NoteHtml.Clave.Fa.C);
static B = new Note("B3", NoteHtml.Clave.Fa.B);
static A = new Note("A3", NoteHtml.Clave.Fa.A);
static G = new Note("G3", NoteHtml.Clave.Fa.G);
static F = new Note("F3", NoteHtml.Clave.Fa.F);
static BSharp = new Note("B3#", NoteHtml.Clave.Fa.BSharp);
static ASharp = new Note("A3#", NoteHtml.Clave.Fa.ASharp);
static GSharp = new Note("G3#", NoteHtml.Clave.Fa.GSharp);
static ALL_BASIC_NOTES = [ClaveFa.C, ClaveFa.B, ClaveFa.A, ClaveFa.G, ClaveFa.F];
static ALL_BASIC_SEMI_NOTES = [ClaveFa.BSharp, ClaveFa.ASharp, ClaveFa.GSharp];
static ALL : ClaveFa[] = ClaveFa.ALL_BASIC_NOTES.concat(ClaveFa.ALL_BASIC_SEMI_NOTES);;
static get(noteWithOctave:string) {
return Note.get(noteWithOctave, ClaveFa.ALL);
}
}
export class Chord {
static C:Chord = new Chord("C", [BasicNote.C, BasicNote.E, BasicNote.G]);
static D:Chord = new Chord("D", [BasicNote.D, BasicNote.F, BasicNote.A]);
constructor( private name:String, private notes:BasicNote[]) {
}
getNotes():BasicNote[] {
return this.notes;
}
getName() {
return this.name;
}
//TODO: colocar os outros acordes
static ALL:any[] = [Chord.C, Chord.D];
}
export class NoteLevel {
static RightHandLevel:NoteLevel = new NoteLevel("level1", true, false, false);
static LeftHandLevel:NoteLevel = new NoteLevel("level2", false, true, false);
static RightAndLeftHandLevel:NoteLevel = new NoteLevel("level3",true, true, false);
static RightAndLeftHandPlusSeminotesLevel:NoteLevel = new NoteLevel("level4", true, true, true);
static ALL:NoteLevel[] = [NoteLevel.RightHandLevel,
NoteLevel.LeftHandLevel,
NoteLevel.RightAndLeftHandLevel,
NoteLevel.RightAndLeftHandPlusSeminotesLevel];
constructor(public id, public sol:boolean, public fa:boolean, public semiNote:boolean) {
}
static valueOf(levelRaw:String) {
for (var item of NoteLevel.ALL) {
if (item.id == levelRaw) {
return item;
}
}
throw new Error("Invalid levelRaw: " + levelRaw);
}
}
@Injectable()
export class NoteService {
//static ALL_SOL_FA:Note[] = ClaveSol.ALL.concat(ClaveFa.ALL);
constructor() {}
getNoteFromRawMidi(rawMidiInput:string):any[] {
var midiinput = JSON.parse(rawMidiInput);
var on = midiinput.on;
var rawNote = midiinput.note;
return [Note.valueOf(rawNote), on];
}
}
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/pages/connect-midiinput/connect-midiinput.ts
|
import {Page, NavController} from 'ionic-angular';
import {ChooseGamePage} from '../choose-game/choose-game';
import {ChooseChordPage} from '../choose-chord/choose-chord';
import {MidiInputService} from '../../providers/midiinput-service/midiinput-service';
import {ConnectionListerner} from '../../providers/midiinput-service/midiinput-service';
import {Router} from '@angular/router';
@Page({
templateUrl: 'build/pages/connect-midiinput/connect-midiinput.html'
})
export class ConnectMidiInputPage implements ConnectionListerner {
constructor(private nav: NavController,
public midiInput: MidiInputService,
private router:Router) {
midiInput.setConnectionListerner(this);
midiInput.host = window.location.host;
}
startConnection() {
this.midiInput.connect();
}
onConnection() {
//this.goToChooseChordGame();
this. goToChooseGame();
}
onClose() {}
goToChooseChordGame() {
this.nav.push(ChooseChordPage);
}
goToChooseGame() {
this.nav.push(ChooseGamePage);
}
}
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/providers/records-service/records-service.ts
|
<gh_stars>0
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
import {App, Platform, Storage, SqlStorage} from 'ionic-angular';
/*
Generated class for the RecordsService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class RecordsService {
public storage: Storage = null;
public score;
constructor(public platform: Platform) {
this.platform.ready()
.then(() => {
this.storage = new Storage(SqlStorage);
/*this.dummyData();
this.load();*/
});
}
/*dummyData() {
var record = [{'score': 51}];
this.storage.setJson('note-fa', record);
}
load() {
this.storage
.get('note-fa')
.then((data) => {
if (data != null)
var local = JSON.parse(data);
this.score = local[0].score;
});
}*/
tryAddNewRecord(score, game_label, params?: any) {
this.storage
.get(game_label)
.then((data) => {
var newScore = {'score': score};
var myData: any[];
var isRecord = true;
if (data == null) {
myData = [newScore];
} else {
myData = JSON.parse(data);
myData.push(newScore);
var sortedArray: any[] = myData.sort((n1,n2) => n2.score - n1.score);
if (sortedArray.length > 5) {
if (sortedArray[sortedArray.length-1] == newScore) {
isRecord = false;
}
sortedArray = sortedArray.slice(0, sortedArray.length-1);
myData = sortedArray;
}
}
this.storage.setJson(game_label, myData);
//TODO: dizer se se trata de novo record
params.resolve([myData, isRecord, score]);
});
}
}
|
virtualmusicsoft/gamma
|
server-midi/front-end-ionic2/app/pages/game/game.ts
|
/// <reference path="../../../node_modules/retyped-sockjs-client-tsd-ambient/sockjs-client.d.ts" />
/// <reference path="../../../typings/modules/stomp-websocket/stomp-websocket.d.ts" />
import {Page, NavController, NavParams, Alert} from 'ionic-angular';
import {NoteService, Note, NoteHtml, ClaveFa, ClaveSol, NoteLevel} from '../../providers/note-service/note-service';
import {MidiInputService, HandleMidiInputListerner} from '../../providers/midiinput-service/midiinput-service';
import {ResultPage} from '../result/result';
import {Observable} from 'rxjs/Rx'
import * as SockJS from 'sockjs-client';
import BaseEvent = __SockJSClient.BaseEvent;
import SockJSClass = __SockJSClient.SockJSClass;
@Page({
templateUrl: 'build/pages/game/game.html',
providers: [NoteService],
selector: 'game'
})
export class GamePage implements HandleMidiInputListerner {
public inputNotes:Note[] = [];
public gameNotes:Note[] = [];
public score:number = 0;
public isGameRunning:boolean = true;
public timeRemaining:number = 0;
public timeTotal:number = 0;
public incremento:number = 0;
public updateProgressBySecond:number = 5;
public intervalValue:number = 1000 / this.updateProgressBySecond;
public secondsToResponse:number = 5; //TODO: personalizar via localstorange
private timer;
private lastNote:Note;
private level:NoteLevel;
private maxChallenges:number = 3;
private counterChallenges:number = 0;
private randomNotes:Note[] = [];
constructor(private nav: NavController,
private noteService: NoteService,
private navParams: NavParams,
public midiInput: MidiInputService) {
//TODO: BUG? no construtor vai iniciar só uma vez? Parece que não.
this.level = navParams.get('level');
this.dummyNotas();
//TODO: cuidado deve ficar em um
if (this.level.sol) {
this.randomNotes = this.randomNotes.concat(ClaveSol.ALL_BASIC_NOTES);
if (this.level.semiNote) {
this.randomNotes = this.randomNotes.concat(ClaveSol.ALL_BASIC_SEMI_NOTES);
}
}
if (this.level.fa) {
this.randomNotes = this.randomNotes.concat(ClaveFa.ALL_BASIC_NOTES);
if (this.level.semiNote) {
this.randomNotes = this.randomNotes.concat(ClaveFa.ALL_BASIC_SEMI_NOTES);
}
}
if (this.randomNotes.length <= 1 ) {
throw new Error("Error: this.randomNotes.length <= 0!");
}
midiInput.setHandleMidiInputListerner(this);
}
onConnection() {}
/**
* Útil para renderizar notas
*/
dummyNotas() {
/*this.gameNotes.push(ClaveSol.CSharp);
this.gameNotes.push(ClaveSol.DSharp);
this.gameNotes.push(ClaveSol.FSharp);
this.gameNotes.push(ClaveSol.GSharp);*/
}
getNextNote() {
var temp:Note;
do {
temp = this.getPreviewNextNote();
} while(temp == this.lastNote);
this.lastNote = temp;
return temp;
}
getPreviewNextNote() {
var index = Math.floor(Math.random() * this.randomNotes.length);
return this.randomNotes[index];
}
handleMidiInput(rawMidiInput:string):void {
//TODO: verificar se o game está em execução!
var midiinput = this.noteService.getNoteFromRawMidi(rawMidiInput);
var note = midiinput[0];
var keyOn = midiinput[1];
if (keyOn) {
if (note.info != null) {
this.computeNewScore(note);
}
}
}
match():boolean {
//TODO: distinguir "Do" da Clave sol com a clave de "Fá"
if (this.gameNotes.length != this.inputNotes.length) {
return false;
}
for(let gameNote of this.gameNotes) {
if (this.inputNotes.indexOf(gameNote) == -1) {
return false;
}
}
return true;
}
computeNewScore(note?:Note) {
if (this.isGameRunning) {
this.isGameRunning = false;
if (note != null) {
this.inputNotes.push(note);
}
if (this.gameNotes.length != 0) {
let match = this.match();
//TODO: valor do score deveria ser de acordo com o tempo gasto para respondere o tempo q teve para responder
if (match) {
this.score += 10;
} else {
this.score -= 10;
}
}
if (this.counterChallenges >= this.maxChallenges) {
this.stop();
return;
}
this.gameNotes = [];
this.gameNotes.push(this.getNextNote());
this.inputNotes = [];
this.counterChallenges++;
this.reset();
}
}
start() {
this.initTimer();
}
reset() {
if (this.timer != null) {
this.timer.unsubscribe();
}
this.initTimer();
}
stop() {
this.isGameRunning = false;
if (this.timer != null) {
this.timer.unsubscribe();
}
this.cleanTimer();
this.goToResult();
}
goToResult() {
this.nav.push(ResultPage, {score:this.score});
}
cleanTimer() {
this.timeTotal = this.intervalValue * this.updateProgressBySecond * this.secondsToResponse;
this.timeRemaining = this.timeTotal;
this.incremento = 0;
}
initTimer() {
this.cleanTimer();
//TODO: this.incremento parece que não está servindo para NADA!
this.timer = Observable
.interval(this.intervalValue)
.takeWhile(() => true)
.map((x) => this.incremento+this.intervalValue)
.subscribe((x) => {
this.incremento += this.intervalValue;
this.timeRemaining -= this.intervalValue;
if (this.timeRemaining <= 0) {
this.incremento = 0;
this.timeRemaining = this.timeTotal;
this.computeNewScore();
}
});
this.isGameRunning = true;
}
}
|
mainnika/npm-jayson
|
index.d.ts
|
import { EventEmitter } from 'events';
export interface ClientOptions {
reviver?: Function;
replacer?: Function;
version?: number;
generator?: Function;
encoding?: string;
}
export interface ServerOptions {
reviver?: Function;
replacer?: Function;
router?: Function;
collect?: boolean;
params?: any;
version?: number;
encoding?: string;
}
export interface MethodOptions<T, R> {
handler?: MethodHandler<T, R>;
collect?: boolean;
params?: any;
}
export interface JsonRpcMessage {
id: string | number | null;
version: number;
}
export interface JsonRpcMessageRequest<T = any> extends JsonRpcMessage {
params?: T;
method?: string;
}
export interface JsonRpcMessageResponse<T = any> extends JsonRpcMessage {
result?: T;
error?: JsonRpcError;
}
export interface JsonRpcError<T = any> {
code: number;
message: string;
data?: T;
}
export type ResponseCallback<T> = (err?: {}, response?: JsonRpcMessageResponse<T>) => void;
export type ResponseCallbackBatch = (err: {} | undefined, responses: JsonRpcMessageResponse[]) => void;
export type ResponseCallbackSplitted<T> = (err?: {}, responseErr?: JsonRpcError, responseResult?: T) => void;
export type ResponseCallbackSplittedBatch = (err: {} | undefined, errorResponces: JsonRpcMessageResponse[], successResponces: JsonRpcMessageResponse[]) => void;
export class Client extends EventEmitter {
constructor(server?: Server, options?: ClientOptions);
constructor(options?: ClientOptions);
request<T, R>(method: string, params?: T, callback?: ResponseCallback<R>): JsonRpcMessageRequest<T>;
request<T, R>(method: string, params?: T, callback?: ResponseCallbackSplitted<R>): JsonRpcMessageRequest<T>;
request<T, R>(method: string, params?: T, id?: string | number | null, callback?: ResponseCallback<R>): JsonRpcMessageRequest<T>;
request<T, R>(method: string, params?: T, id?: string | number | null, callback?: ResponseCallbackSplitted<R>): JsonRpcMessageRequest<T>;
request<T, R>(method: JsonRpcMessageRequest<T>, callback?: ResponseCallback<R>): JsonRpcMessageRequest<T>;
request<T, R>(method: JsonRpcMessageRequest<T>, callback?: ResponseCallbackSplitted<R>): JsonRpcMessageRequest<T>;
request<T, R>(method: JsonRpcMessageRequest<T>, id?: string | number | null, callback?: ResponseCallback<R>): JsonRpcMessageRequest<T>;
request<T, R>(method: JsonRpcMessageRequest<T>, id?: string | number | null, callback?: ResponseCallbackSplitted<R>): JsonRpcMessageRequest<T>;
request(method: JsonRpcMessageRequest[], callback?: ResponseCallbackBatch): JsonRpcMessageRequest;
request(method: JsonRpcMessageRequest[], callback?: ResponseCallbackSplittedBatch): JsonRpcMessageRequest;
}
export type MethodCallback<R> = (err: {} | undefined, response: R) => void;
export type MethodHandler<T = any, R = any> = (request: T, callback: MethodCallback<R>) => void;
export class Server extends EventEmitter {
constructor(methods?: Methods, options?: ServerOptions);
method<T, R>(name: string, definition: MethodHandler<T, R>): void;
method<T, R>(name: string, definition: Method<T, R>): void;
method(name: string, definition: Client): void;
methods(methods?: Methods): void;
hasMethod(name: string): boolean;
removeMethod(name: string): void;
getMethod(name: string): Method;
error<T>(code?: number, message?: string, data?: T): JsonRpcError<T>;
call<T, R>(request: JsonRpcMessageRequest<T>, callback?: (err?: JsonRpcError, response?: JsonRpcMessageResponse<R>) => void): void;
call(requests: JsonRpcMessageRequest[], callback?: (err: null, responses: JsonRpcMessageResponse[]) => void): void;
call<R>(request: string, callback?: (err?: JsonRpcError, response?: JsonRpcMessageResponse<R>) => void): void;
}
export class Method<T = any, R = any> {
constructor(handler: MethodHandler<T, R>, options?: MethodOptions<T, R>);
constructor(options?: MethodOptions<T, R>);
getHandler(): MethodHandler<T, R>;
execute(server: Server, params?: T, callback?: MethodCallback<R>): void;
}
interface Methods {
[name: string]: MethodHandler;
}
export namespace Utils {
export namespace JSON {
interface StringifyOptions {
replacer?: Function;
}
interface StringifyCallback {
(err: any, str: string): void;
}
interface ParseOptions {
reviver?: Function;
}
interface ParseCallback {
(err: any, obj: Object): void;
}
export function stringify(obj: any, options: StringifyOptions, callback: StringifyCallback): void;
export function parse(str: string, options: ParseOptions, callback: ParseCallback): void;
}
}
|
mainnika/npm-jayson
|
test.ts
|
<filename>test.ts<gh_stars>0
/// <reference path="./bundle.d.ts" />
import * as jayson from 'jayson';
class ExtendFromJaysonClient extends jayson.Client {
public static get Create(): ExtendFromJaysonClient {
return new ExtendFromJaysonClient();
}
public static test(): void {
const client: ExtendFromJaysonClient = ExtendFromJaysonClient.Create;
client.request('foo', { foo: 'bar' }, 0, (err?: {}, response?: jayson.JsonRpcMessageResponse<string>) => {
response.id;
response.version;
response.result;
response.error.code;
response.error.data;
response.error.message;
});
client.request('foo', { bar: 'foo' }, (err?: {}, error?: jayson.JsonRpcError, result?: string) => {
result;
error.code;
error.data;
error.message;
});
client.request(
[
client.request('foo', { foo: 'bar' }),
client.request('foo'),
client.request('foo', { foo: 'bar' }, '0'),
client.request('foo', { bar: 'foo' }, 0),
client.request('foo', { bar: 'foo' }, null),
client.request('foo', { bar: 'foo' }, null)
],
(err?: {}, responses?: jayson.JsonRpcMessageResponse[]) => {
responses[5].id;
responses[4].version;
responses[3].result;
responses[2].error.code;
responses[1].error.data;
responses[0].error.message;
}
);
}
}
class ExtendFromJaysonServer extends jayson.Server {
public static get Create(): ExtendFromJaysonServer {
return new ExtendFromJaysonServer();
}
constructor() {
const options: jayson.ServerOptions = {
collect: true
};
super({}, options);
this.method('foo', this.foo);
this.method('bar', new ExtendFromJaysonMethod());
this.method('relay', ExtendFromJaysonClient.Create);
this.call(
{
id: 0,
method: 'foo',
params: {
foo: 'bar'
},
version: 2
},
(err?: jayson.JsonRpcError, response?: jayson.JsonRpcMessageResponse<string>): void => {
err.code;
err.data;
err.message;
response.id;
response.id;
response.version;
response.result;
response.error.code;
response.error.data;
response.error.message;
}
);
this.call(
[
{
id: 0,
method: 'foo',
params: {
foo: 'bar'
},
version: 2
},
{
id: 0,
method: 'foo',
params: {
foo: 'bar'
},
version: 2
}
],
(err: {}, responses: jayson.JsonRpcMessageResponse[]): void => {
responses[5].id;
responses[4].version;
responses[3].result;
responses[2].error.code;
responses[1].error.data;
responses[0].error.message;
}
);
}
private foo(args: { foo: string }, callback: (err?: {}, result?: { bar: string }) => void): void {
callback(undefined, { bar: args.foo });
}
}
class ExtendFromJaysonMethod extends jayson.Method<string, string> {
public getHandler() {
return (request: string, callback: (err?: {}, response?: string) => void) => {
callback(undefined, request);
};
}
}
|
michivo/mss22-sample-frontend
|
src/app/articles/articles.service.spec.ts
|
import { HttpClient } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { NGXLogger } from 'ngx-logger';
import { LoggerTestingModule } from 'ngx-logger/testing';
import { of } from 'rxjs';
import { asyncData } from '../helpers/async-observable-helpers';
import { Article } from './article';
import { ArticleService } from './articles.service';
describe('ArticleServiceService', () => {
let service: ArticleService;
let httpClientSpy: jasmine.SpyObj<HttpClient>;
beforeEach(() => {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
TestBed.configureTestingModule({
imports: [
LoggerTestingModule
]
});
service = new ArticleService(httpClientSpy, TestBed.inject(NGXLogger));
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should get articles from the service url', (done: DoneFn) => {
const expectedArticles: Article[] = [
{
description: 'Humpty Dumpty sat on a wall',
identifier: '4294967296',
identifierType: 'custom',
name: 'Egg'
}
];
httpClientSpy.get.and.returnValue(of(expectedArticles));
service.getArticles().subscribe({
next: articles => {
expect(expectedArticles).toEqual(articles.data!);
done();
},
error: done.fail
})
});
});
|
michivo/mss22-sample-frontend
|
src/app/app.module.ts
|
<filename>src/app/app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ArticleListComponent } from './articles/article-list/article-list.component';
import { ArticleCreationComponent } from './articles/article-creation/article-creation.component';
import { ArticleDetailsComponent } from './articles/article-details/article-details.component';
import { FormsModule } from '@angular/forms';
import { LoggerModule, NgxLoggerLevel } from 'ngx-logger';
@NgModule({
declarations: [
AppComponent,
ArticleListComponent,
ArticleCreationComponent,
ArticleDetailsComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
LoggerModule.forRoot({
level: NgxLoggerLevel.DEBUG
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
michivo/mss22-sample-frontend
|
src/app/articles/article-details/article-details.component.ts
|
<filename>src/app/articles/article-details/article-details.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { Article } from '../article';
@Component({
selector: 'tr[app-article-details]',
templateUrl: './article-details.component.html',
styleUrls: ['./article-details.component.scss']
})
export class ArticleDetailsComponent {
@Input() article?:Article;
}
|
michivo/mss22-sample-frontend
|
src/app/utils/http-error-response.ts
|
<gh_stars>1-10
import { HttpErrorResponse } from '@angular/common/http';
export function getErrorMessage(response: HttpErrorResponse): string {
if (response === undefined) {
return '';
} else if (response.error === undefined) {
return response.message;
} else if (response.error instanceof Object) {
if (response.error.errors !== undefined) {
return Object.keys(response.error.errors).map((key) => {
return `${key}: ${response.error.errors[key]}`;
}).join('. ');
}
}
return response.message;
}
|
michivo/mss22-sample-frontend
|
src/app/utils/non-empty.response.ts
|
export class NonEmptyResponse<T> {
constructor(
public success: boolean,
public errorMessage: string,
public data?: T,
) {
}
}
|
michivo/mss22-sample-frontend
|
src/app/articles/article.ts
|
<filename>src/app/articles/article.ts
export interface Article {
identifier: string,
identifierType: string,
name: string,
description: string,
}
|
michivo/mss22-sample-frontend
|
src/app/articles/articles.service.ts
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Article } from './article';
import { NonEmptyResponse } from './../utils/non-empty.response';
import { getErrorMessage } from './../utils/http-error-response';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { NGXLogger } from 'ngx-logger';
@Injectable({
providedIn: 'root'
})
export class ArticleService {
private url: string;
constructor(private http: HttpClient, private logger: NGXLogger) {
this.url = 'https://mss-sample-service.oa.r.appspot.com/api/v1/articles';
}
getArticles(): Observable<NonEmptyResponse<Article[]>> {
return this.http.get<Article[]>(this.url).pipe(
map(response => {
return new NonEmptyResponse<Article[]>(true, '', response);
}),
catchError((errorResp: HttpErrorResponse) => {
const errorMessage = getErrorMessage(errorResp);
return of(new NonEmptyResponse<Article[]>(false, errorMessage, undefined));
}));
}
addArticle(article: Article): Observable<NonEmptyResponse<Article>> {
this.logger.debug('Adding new article');
this.logger.debug(article);
return this.http.post<Article>(this.url, article).pipe(
map(response => {
return new NonEmptyResponse<Article>(true, '', response);
}),
catchError((errorResp: HttpErrorResponse) => {
const errorMessage = getErrorMessage(errorResp);
return of(new NonEmptyResponse<Article>(false, errorMessage, undefined));
}),
);
}
}
|
michivo/mss22-sample-frontend
|
src/app/articles/article-list/article-list.component.ts
|
<filename>src/app/articles/article-list/article-list.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subject, takeUntil } from 'rxjs';
import { Article } from '../article';
import { ArticleService } from '../articles.service';
@Component({
selector: 'app-article-list',
templateUrl: './article-list.component.html',
styleUrls: ['./article-list.component.scss']
})
export class ArticleListComponent implements OnInit, OnDestroy {
articles: Article[];
adding: boolean;
destroy$: Subject<boolean> = new Subject<boolean>();
constructor(private articleService: ArticleService) {
this.articles = [];
this.adding = false;
}
ngOnInit(): void {
this.loadArticles();
}
ngOnDestroy(): void {
this.destroy$.next(true);
this.destroy$.unsubscribe();
}
loadArticles() {
this.articleService.getArticles()
.pipe(takeUntil(this.destroy$))
.subscribe(resp => {
this.articles = resp.data!;
});
}
addArticle() {
this.adding = true;
}
saveArticle(article: Article) {
this.adding = false;
this.articleService.addArticle(article)
.pipe(takeUntil(this.destroy$))
.subscribe(resp => {
this.articles.push(resp.data!);
})
}
cancelAdding() {
this.adding = false;
}
}
|
michivo/mss22-sample-frontend
|
src/app/articles/article-creation/article-creation.component.ts
|
<gh_stars>1-10
import { Component, EventEmitter, Output } from '@angular/core';
import { Article } from '../article';
@Component({
selector: 'app-article-creation',
templateUrl: './article-creation.component.html',
styleUrls: ['./article-creation.component.scss']
})
export class ArticleCreationComponent {
@Output() addRequest = new EventEmitter<Article>();
@Output() cancelRequest = new EventEmitter();
article: Article;
constructor() {
this.article = {
description: '',
name: '',
identifier: '',
identifierType: 'custom'
};
}
saveArticle() {
this.addRequest.emit(this.article);
}
cancel() {
this.cancelRequest.emit();
}
}
|
yjcyun/adopt_korean_dogs_api
|
src/dogs/dogs.model.ts
|
<reponame>yjcyun/adopt_korean_dogs_api
export interface Dog {
id: string;
name: string;
description: string;
location: Location;
status: AdoptionStatus;
}
export enum Location {
KOREA = 'KOREA',
TORONTO = 'TORONTO',
VANCOUVER = 'VANCOUVER',
NEW_YORK = 'NEW_YORK',
LOS_ANGELES = 'LOS_ANGELES',
CHICAGO = 'CHICAGO',
}
export enum AdoptionStatus {
AVAILABLE = 'AVAILABLE',
IN_PROGRESS = 'IN_PROGRESS',
ADOPTED = 'ADAPTED',
}
|
yjcyun/adopt_korean_dogs_api
|
src/dogs/dto/get-dogs-filter.dto.ts
|
import { IsEnum, IsOptional, IsString } from 'class-validator';
import { AdoptionStatus } from '../dogs.model';
export class GetDogsFilterDto {
@IsOptional()
@IsEnum(AdoptionStatus)
status?: AdoptionStatus;
@IsOptional()
@IsString()
search?: string;
}
|
yjcyun/adopt_korean_dogs_api
|
src/dogs/dogs.service.ts
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { v4 as uuid } from 'uuid';
import { CreateDogDto } from './dto/create-dogs.dto';
import { AdoptionStatus, Dog, Location } from './dogs.model';
import { GetDogsFilterDto } from './dto/get-dogs-filter.dto';
@Injectable()
export class DogsService {
private dogs: Dog[] = [];
getAllDogs(): Dog[] {
return this.dogs;
}
getDogsWithFilter(filterDto: GetDogsFilterDto): Dog[] {
const { status, search } = filterDto;
let dogs = this.getAllDogs();
if (status) {
dogs = dogs.filter((dog) => dog.status === status);
}
if (search) {
dogs = dogs.filter((dog) => {
if (dog.name.includes(search) || dog.description.includes(search)) {
return true;
}
});
}
return dogs;
}
getDogById(id: string): Dog {
const found = this.dogs.find((task) => task.id === id);
if (!found) {
throw new NotFoundException(`Task with ID ${id} not found`);
}
return found;
}
createDog(createDogDto: CreateDogDto): Dog {
const { name, description } = createDogDto;
const dog: Dog = {
id: uuid(),
name,
description,
location: Location.KOREA,
status: AdoptionStatus.AVAILABLE,
};
this.dogs.push(dog);
return dog;
}
updateAdoptionStatus(id: string, status: AdoptionStatus) {
const dog = this.getDogById(id);
dog.status = status;
return dog;
}
deleteDog(id: string): void {
const found = this.getDogById(id);
this.dogs = this.dogs.filter((dog) => dog.id !== found.id);
}
}
|
yjcyun/adopt_korean_dogs_api
|
src/dogs/dto/update-dogs-status.dto.ts
|
<gh_stars>0
import { IsEnum } from 'class-validator';
import { AdoptionStatus } from '../dogs.model';
export class UpdateDogsStatusDto {
@IsEnum(AdoptionStatus)
status: AdoptionStatus;
}
|
yjcyun/adopt_korean_dogs_api
|
src/dogs/dogs.controller.ts
|
import { UpdateDogsStatusDto } from './dto/update-dogs-status.dto';
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
} from '@nestjs/common';
import { DogsService } from './dogs.service';
import { Dog } from './dogs.model';
import { CreateDogDto } from './dto/create-dogs.dto';
import { GetDogsFilterDto } from './dto/get-dogs-filter.dto';
@Controller('dogs')
export class DogsController {
constructor(private dogsService: DogsService) {}
@Get()
getDogs(@Query() filterDto: GetDogsFilterDto): Dog[] {
if (Object.keys(filterDto).length) {
return this.dogsService.getDogsWithFilter(filterDto);
} else {
return this.dogsService.getAllDogs();
}
}
@Get('/:dogId')
getDogById(@Param('dogId') id: string): Dog {
return this.dogsService.getDogById(id);
}
@Post()
createTask(@Body() createDogDto: CreateDogDto) {
return this.dogsService.createDog(createDogDto);
}
@Patch('/:dogId/status')
updateAdoptionStatus(
@Param('dogId') id: string,
@Body() updateAdoptionStatusDto: UpdateDogsStatusDto,
): Dog {
const { status } = updateAdoptionStatusDto;
return this.dogsService.updateAdoptionStatus(id, status);
}
@Delete('/:dogId')
deleteDog(@Param('dogId') id: string): void {
return this.dogsService.deleteDog(id);
}
}
|
JoshuaKGoldberg/typestat-example
|
src/index.ts
|
<reponame>JoshuaKGoldberg/typestat-example
export const withString1 = (arg) => arg;
export const withString2 = (arg) => arg;
export const withString3 = (arg) => arg;
export const usesWithString = () => {
return [withString1(""), withString2(""), withString3("")];
};
|
ludorival/smart-issue-tracker-sdk
|
test/generator.ts
|
<gh_stars>1-10
import { values } from 'lodash'
import {
Comparator,
EventHandler,
Issue,
TrackIssueOptions,
trackIssues,
} from '../src/index'
export interface Error {
timestamp: number
message: string
ignored?: boolean
customAttribute?: number
}
export interface TestIssue extends Issue<Error> {
title: string
body: string
comments: string[]
newOccurrences: Error[]
}
let issuesCollections: { [id: string]: Required<TestIssue> } = {}
export const initOptions = async ({
initialIssues = [],
compareOccurrence = (source, target) =>
source.message.localeCompare(target.message),
compareIssue,
eventHandler,
}: {
initialIssues?: Error[]
compareOccurrence?: Comparator<Error>
compareIssue?: Comparator<TestIssue>
eventHandler?: EventHandler<TestIssue, Error>
} = {}): Promise<TrackIssueOptions<TestIssue, Error>> => {
issuesCollections = {}
const options: TrackIssueOptions<TestIssue, Error> = {
hooks: {
getIdentifier: (a) => a.timestamp,
initializeNewIssue: (occ) => ({
newOccurrences: [],
occurrences: [occ],
title: occ.message,
body: '',
comments: [],
}),
compareIssue,
compareOccurrence,
shouldBundleIssueInto: (issueToBundle) =>
!issueToBundle.occurrences[0]?.ignored,
},
issueClient: {
createIssue: jest.fn().mockImplementation((issue: TestIssue) => {
const id = issue.occurrences[0].timestamp.toString()
issuesCollections[id] = {
...issue,
id,
url: `https://issue-tracker/project/${id}`,
title: issue.occurrences[0].message,
body: `Found ${issue.occurrences.length} occurences of "${issue.occurrences[0].message}"`,
comments: [],
}
return Promise.resolve(issuesCollections[id])
}),
fetchIssues: jest.fn().mockImplementation(() => {
return Promise.resolve(values(issuesCollections))
}),
updateIssue: jest
.fn()
.mockImplementation((issue: Required<TestIssue>) => {
issuesCollections[issue.id] = {
...issuesCollections[issue.id],
comments: [
...(issuesCollections[issue.id]?.comments as string[]),
`Found new ${issue.newOccurrences.length} occurences of ${issue.title}`,
],
}
return Promise.resolve(issuesCollections[issue.id])
}),
},
eventHandler: {
...eventHandler,
onBundledIssue: (target, newOccurrences) =>
(target.newOccurrences = (target.newOccurrences || []).concat(
newOccurrences
)),
onNotBundledIssue: (source, target) => {
if (!target && !source.id) {
source.newOccurrences = source.occurrences
}
},
},
}
initialIssues.length && (await trackIssues(initialIssues, options))
jest.clearAllMocks()
return options
}
let lastTimestamp = 0
export const anError = (message: string, timestamp?: number): Error => {
if (!timestamp) {
lastTimestamp += 1
timestamp = lastTimestamp
}
return {
message,
timestamp,
}
}
beforeEach(() => {
lastTimestamp = 0
})
|
ludorival/smart-issue-tracker-sdk
|
usage.ts
|
import { trackIssues, IssueClient, Comparator, Issue } from './src'
// --- your occurence type
interface Occurrence {
timestamp: number
message: string
}
// --- your issue type
interface MyIssueType extends Issue<Occurrence> {
title: string
body: string
comments: string[]
newOccurrences: Occurrence[]
}
// --- your issue client
class MyIssueClient implements IssueClient<MyIssueType, Occurrence> {
store: Required<MyIssueType>[] = []
async createIssue(issue: MyIssueType) {
// here you can create the issue related to an untracked error
const savedIssue = {
...issue,
id: this.store.length.toString(),
url: 'http://issue-client/newIdIssue',
body: `Found ${issue.newOccurrences.length} occurences of "${issue.title}"`,
}
this.store.push(savedIssue)
return this.store[this.store.length - 1]
}
async updateIssue(error: MyIssueType) {
// here you can update the issue for example add a new comment for new occurences
const comments = [
...error.comments,
`Found new ${error.newOccurrences.length} occurences of ${error.title}`,
]
return { ...error, comments } as Required<MyIssueType>
}
async fetchIssues() {
return this.store
}
}
// Your custom comparator
const compareOccurrence: Comparator<Occurrence> = (a, b) =>
a.message.localeCompare(b.message)
// use it
const errors: Occurrence[] = [
{ message: 'Error when create the checkout', timestamp: 1 },
{ message: 'Error When Create The Checkout', timestamp: 2 },
{ message: 'Null Pointer Exception on payment page', timestamp: 3 },
{ message: 'cannot call login on undefined', timestamp: 4 },
{ message: 'Null Pointer Exception on payment page', timestamp: 5 },
]
trackIssues(errors, {
issueClient: new MyIssueClient(),
hooks: {
getIdentifier: (occurrence) => occurrence.timestamp, //to avoid adding the same occurrence
compareOccurrence,
},
}).then((trackedErrors) => console.log(trackedErrors))
// should return
// - "Error when create the checkout" (occurrences : 2)
// - "Null Pointer Exception on payment page" (occurrences : 2)
// - "cannot call login on undefined" (occurences : 1)
|
ludorival/smart-issue-tracker-sdk
|
test/index.test.ts
|
<reponame>ludorival/smart-issue-tracker-sdk<gh_stars>1-10
import { difference } from 'lodash'
import { Comparator, trackIssues } from '../src/index'
import { anError, Error, TestIssue, initOptions } from './generator'
describe('Track New Errors', () => {
test('should track a new error', async () => {
// given
const errors: Error[] = [anError('A new error')]
const options = await initOptions()
// when
const trackedErrors = await trackIssues(errors, options)
// then
expect(options.issueClient.createIssue).toHaveBeenCalled()
expect(trackedErrors).toMatchSnapshot()
})
test('should zip sames new errors together', async () => {
// given
const errors: Error[] = [
anError('A new error'),
anError('Another error'),
anError('A new error'),
anError('A new error'),
anError('Another error'),
anError('Still an error'),
]
const options = await initOptions()
// when
const trackedErrors = await trackIssues(errors, options)
// then
expect(trackedErrors).toHaveLength(3)
expect(trackedErrors[0].occurrences).toHaveLength(3)
expect(trackedErrors[1].occurrences).toHaveLength(2)
expect(trackedErrors[2].occurrences).toHaveLength(1)
expect(options.issueClient.createIssue).toHaveBeenCalled()
expect(trackedErrors).toMatchSnapshot()
})
test('should ignore an occurrence from an attribute', async () => {
// given
const errors: Error[] = [
anError('Error 1'),
{ ...anError('Error 2'), ignored: true },
anError('Error 3'),
]
const onIgnoredOccurrence = jest.fn()
const options = await initOptions({ eventHandler: { onIgnoredOccurrence } })
// when
const trackedErrors = await trackIssues(errors, options)
// then
expect(trackedErrors).toHaveLength(2)
expect(trackedErrors[0].occurrences).toHaveLength(1)
expect(trackedErrors[1].occurrences).toHaveLength(1)
expect(options.issueClient.createIssue).toHaveBeenCalled()
expect(onIgnoredOccurrence).toHaveBeenCalledTimes(1)
})
})
describe('Track Existing Errors', () => {
test('should track an existing error', async () => {
// given
const options = await initOptions({
initialIssues: [anError('A new error')],
})
const errors: Error[] = [anError('A new error')]
// when
const trackedErrors = await trackIssues(errors, options)
// then
expect(trackedErrors).toHaveLength(1)
expect(trackedErrors[0].occurrences).toHaveLength(2)
expect(options.issueClient.createIssue).toHaveBeenCalledTimes(0)
expect(options.issueClient.updateIssue).toHaveBeenCalled()
expect(trackedErrors).toMatchSnapshot()
})
test('should track multiples existing errors', async () => {
// given
const options = await initOptions({
initialIssues: [
anError('Error 1'),
anError('Error 2'),
anError('Error 1'),
anError('Error 2'),
anError('Error 3'),
],
})
const errors: Error[] = [
anError('Error 1'),
anError('Error 2'),
anError('Error 1'),
anError('Error 4'),
anError('Error 4'),
]
// when
const trackedErrors = await trackIssues(errors, options)
// then
expect(trackedErrors).toHaveLength(3)
expect(trackedErrors[0].occurrences).toHaveLength(4)
expect(trackedErrors[1].occurrences).toHaveLength(3)
expect(trackedErrors[2].occurrences).toHaveLength(2)
expect(options.issueClient.createIssue).toHaveBeenCalledTimes(1)
expect(options.issueClient.updateIssue).toHaveBeenCalledTimes(2)
expect(trackedErrors).toMatchSnapshot()
})
test('should not track errors with same timestamp', async () => {
// given
const options = await initOptions({
initialIssues: [
anError('Error 1', 2),
anError('Error 2', 3),
anError('Error 2', 4),
],
})
const errors: Error[] = [
anError('Error 1', 1),
anError('Error 1', 2),
anError('Error 1', 3),
anError('Error 2', 3),
anError('Error 2', 4),
]
// when
const trackedErrors = await trackIssues(errors, options)
// then
expect(trackedErrors).toHaveLength(1)
expect(trackedErrors[0].occurrences).toHaveLength(3)
expect(options.issueClient.createIssue).toHaveBeenCalledTimes(0)
expect(options.issueClient.updateIssue).toHaveBeenCalledTimes(1)
})
test('should ignore matched errors for already tracked errors', async () => {
// given
const options = await initOptions({
initialIssues: [anError('Error 1', 1), anError('Error 2', 2)],
})
const errors: Error[] = [anError('Error 3', 1)]
const onMatchedTrackedIssues = jest.fn()
// when
const trackedErrors = await trackIssues(errors, {
...options,
hooks: {
compareIssue: () => 0,
},
eventHandler: {
onMatchedTrackedIssues,
},
})
// then
expect(trackedErrors).toHaveLength(1)
expect(onMatchedTrackedIssues).toHaveBeenCalled()
expect(options.issueClient.createIssue).toHaveBeenCalledTimes(0)
expect(options.issueClient.updateIssue).toHaveBeenCalledTimes(1)
})
})
describe('Custom comparator', () => {
test('should use a custom comparator based on differences threshold', async () => {
// given
const comparator: Comparator<Error> = (a, b) => {
const threshold =
(a.message.length -
difference(a.message.split(''), b.message.split('')).length) /
a.message.length
return threshold >= 0.8 ? 0 : a.message.localeCompare(b.message)
}
const options = await initOptions({
initialIssues: [],
compareOccurrence: comparator,
})
// when
const trackedErrors = await trackIssues(
[anError('Error 1 : Arg0'), anError('Error 1 : Arg1')],
options
)
// then
expect(trackedErrors).toHaveLength(1)
expect(trackedErrors[0].occurrences).toHaveLength(2)
expect(trackedErrors).toMatchSnapshot()
})
test('should use a custom comparator based on an error attribute', async () => {
// given
const comparator: Comparator<Error> = (a, b) =>
(a.customAttribute as number) - (b.customAttribute as number)
const options = await initOptions({
initialIssues: [],
compareOccurrence: comparator,
})
const errors: Error[] = [
{ ...anError('Error 1'), customAttribute: 1 },
{ ...anError('Error 1'), customAttribute: 2 },
{ ...anError('Error 1'), customAttribute: 1 },
]
// when
const trackedErrors = await trackIssues(errors, options)
// then
expect(trackedErrors).toHaveLength(2)
expect(trackedErrors[0].occurrences).toHaveLength(2)
expect(trackedErrors[1].occurrences).toHaveLength(1)
expect(trackedErrors).toMatchSnapshot()
})
test('should use a custom bundled comparator comparator ', async () => {
// given
const comparator: Comparator<Error> = (a, b) => {
const wordsA = a.message.split(' ')
const wordsB = b.message.split(' ')
const diff = difference(wordsA, wordsB)
const threshold = (wordsA.length - diff.length) / wordsA.length
return threshold >= 0.8 ? 0 : a.message.localeCompare(b.message)
}
const comparatorBundledErrors: Comparator<TestIssue> = (a, b) =>
b.occurrences.some((occ) => comparator(a.occurrences[0], occ) === 0)
? 0
: comparator(a.occurrences[0], b.occurrences[0])
const options = await initOptions({
initialIssues: [],
compareOccurrence: undefined,
compareIssue: comparatorBundledErrors,
})
// when
const trackedErrors = await trackIssues(
[
anError('Long Error with multiple Arguments : (Arg1, Arg2, Arg3)'),
anError('Long Error with multiple Arguments : (Arg5, Arg4, Arg3)'),
anError('Long Error with multiple Arguments : (Arg0, Arg7, Arg8)'),
anError('Long Error with multiple Arguments : (Arg1, Arg2, Arg4)'),
],
options
)
// then
expect(trackedErrors).toHaveLength(3)
expect(trackedErrors[1].occurrences).toHaveLength(2)
expect(trackedErrors).toMatchSnapshot()
})
})
|
ludorival/smart-issue-tracker-sdk
|
src/trackIssues.ts
|
<filename>src/trackIssues.ts
import {
EventHandler,
Hook,
Issue,
TrackIssueOptions,
TrackedIssue,
Comparator,
} from '.'
export async function trackIssues<T extends Issue<R>, R>(
occurrences: R[],
{
issueClient,
hooks: {
initializeNewIssue = (occurrence: R) =>
({ occurrences: [occurrence] } as T),
...rest
},
eventHandler = {},
}: TrackIssueOptions<T, R>
): Promise<TrackedIssue<T>[]> {
if (!occurrences.length) return []
const newIssues: T[] = occurrences.map((occurrence) =>
initializeNewIssue(occurrence)
)
const savedIssues: T[] = await issueClient.fetchIssues()
const bundledIssues = bundleIssues(savedIssues, newIssues, rest, eventHandler)
const trackedIssues = await Promise.all(
bundledIssues.map((issue) => {
return issue.id
? issueClient.updateIssue(issue as TrackedIssue<T>)
: issueClient.createIssue(issue)
})
)
return trackedIssues
}
function bundleIssues<T extends Issue<R>, R>(
savedIssues: T[],
newIssues: T[],
{
shouldBundleIssueInto = () => true,
compareOccurrence,
compareIssue = defaultComparator(compareOccurrence),
getIdentifier,
}: Hook<T, R>,
{
// eslint-disable-next-line @typescript-eslint/no-empty-function
onIgnoredOccurrence = () => {},
// eslint-disable-next-line @typescript-eslint/no-empty-function
onBundledIssue = () => {},
// eslint-disable-next-line @typescript-eslint/no-empty-function
onMatchedTrackedIssues = () => {},
// eslint-disable-next-line @typescript-eslint/no-empty-function
onNotBundledIssue = () => {},
}: EventHandler<T, R>
): T[] {
const mapBundled: { [key: string]: boolean } = {}
return savedIssues
.concat(newIssues)
.sort(compareIssue)
.reduce<T[]>((accumulated, current) => {
const last = accumulated[accumulated.length - 1]
const similar = last && compareIssue(last, current) === 0
const shouldBundle =
!last || shouldBundleIssueInto(current, last, similar)
const newOccurrences =
similar && last && shouldBundle
? getIdentifier
? keepNewOccurrences<T, R>(last, current, getIdentifier)
: current.occurrences
: []
if (similar && last?.id && current.id) {
onMatchedTrackedIssues(last, current)
} else if ((similar && !newOccurrences.length) || !shouldBundle) {
onIgnoredOccurrence(current, last)
return accumulated
} else if (similar && newOccurrences.length) {
last.occurrences = last.occurrences.concat(newOccurrences)
if (last.id) mapBundled[last.id] = true
onBundledIssue(last, newOccurrences, current)
return accumulated
} else if (last) {
onNotBundledIssue(current, last)
}
return [...accumulated, current]
}, [])
.filter((issue) => !issue.id || mapBundled[issue.id])
}
function defaultComparator<T extends Issue<R>, R>(
compare?: Comparator<R>
): Comparator<T> {
if (!compare)
throw new Error('Compare Occurrence or Compare Issue must be implemented')
return (source, target) => {
const firstOccurrence = target.occurrences[0]
return source.occurrences.some((o) => compare(o, firstOccurrence) === 0)
? 0
: compare(source.occurrences[0], firstOccurrence)
}
}
type ExtendedOccurrence<R> = { target: boolean; occurrence: R }
const keepNewOccurrences = <T extends Issue<R>, R>(
fromIssue: T,
toIssue: T,
getIdentifier: (o: R) => number | string
): R[] => {
const extendedTargetOccurences = toIssue.occurrences.map((occurrence) => ({
target: true,
occurrence,
}))
const extendedFromOccurences = fromIssue.occurrences.map((occurrence) => ({
target: false,
occurrence,
}))
const compareStringOrNumber = (
a: number | string,
b: number | string
): number => {
if (typeof a === 'number' && typeof b === 'number') return a - b
else return a.toString().localeCompare(b.toString())
}
const compare: Comparator<ExtendedOccurrence<R>> = (a, b) =>
compareStringOrNumber(
getIdentifier(a.occurrence),
getIdentifier(b.occurrence)
)
const newOnes = extendedFromOccurences
.concat(extendedTargetOccurences)
.sort(compare)
.reduce<ExtendedOccurrence<R>[]>((acc, value, i, array) => {
if (array[i + 1] && compare(value, array[i + 1]) === 0) {
return acc
}
if (array[i - 1] && compare(value, array[i - 1]) === 0) {
return acc
}
if (!value.target) {
return acc
}
return acc.concat(value)
}, [])
.map((e) => e.occurrence)
return newOnes
}
|
ludorival/smart-issue-tracker-sdk
|
src/index.ts
|
<gh_stars>1-10
'use strict'
export * from './trackIssues'
export interface Issue<T> {
id?: string
url?: string
occurrences: T[]
}
export type TrackedIssue<T> = T & { id: string }
export interface IssueClient<T extends Issue<R>, R> {
createIssue(issue: T): Promise<TrackedIssue<T>>
updateIssue(issue: TrackedIssue<T>): Promise<TrackedIssue<T>>
fetchIssues(): Promise<TrackedIssue<T>[]>
}
export type Comparator<T> = (source: T, target: T) => number
export interface Hook<T extends Issue<R>, R> {
initializeNewIssue?: (occurrence: R) => T
compareIssue?: Comparator<T>
shouldBundleIssueInto?: (
issueToBundle: T,
into: T,
areSimilar: boolean
) => boolean
compareOccurrence?: Comparator<R>
getIdentifier?: (occurrence: R) => number | string
}
export interface EventHandler<T extends Issue<R>, R> {
onIgnoredOccurrence?: (source: T, target: T) => void
onBundledIssue?: (target: T, newOccurences: R[], current: T) => void
onMatchedTrackedIssues?: (source: T, target: T) => void
onNotBundledIssue?: (source: T, target?: T) => void
}
export type TrackIssueOptions<T extends Issue<R>, R> = {
issueClient: IssueClient<T, R>
hooks: Hook<T, R>
eventHandler?: EventHandler<T, R>
}
|
secoya/hablar.js
|
src/analysis/type_inference.ts
|
import { ASTRoot as ConstraintAST, Node as ConstraintNode } from '../trees/constraint';
import {
Node as ExprNode,
TypedBinaryOpNode,
TypedFunctionInvocationNode,
TypedNode as TypedExprNode,
TypedNumberNode,
TypedStringLiteralNode,
TypedVariableNode,
VariableNode as ExprVariableNode,
} from '../trees/expression';
import { ASTRoot, TypedASTRoot, TypedNode as TypedTextNode, VariableNode as TextVariableNode } from '../trees/text';
import { default as TypeMap, InferredType, UsageLocation } from '../type_map';
function addConstraintTypeUsageForNode(
typeMap: TypeMap,
node: ConstraintNode,
ast: ConstraintAST,
text: ASTRoot,
): void {
const location = {
constraints: ast,
text: text,
};
const addTypeInfo = (variable: string, type: 'unknown' | 'gender' | 'enum' | 'number') => {
typeMap.addTypeUsage(variable, type, {
location,
node,
nodeType: 'constraint',
type,
});
};
if (node.op === '!') {
const variable = node.operand.name;
// We get no type information from this kind of thing. Just log the
// unknown type.
const type: 'unknown' = 'unknown';
addTypeInfo(variable, type);
} else {
const variable = node.lhs.name;
const type = node.rhs.type;
addTypeInfo(variable, type);
}
}
export function inferConstraintTypes(typeMap: TypeMap, ast: ConstraintAST, textAST: ASTRoot) {
for (const constraint of ast.nodes) {
addConstraintTypeUsageForNode(typeMap, constraint, ast, textAST);
}
}
function addExprTypeInfo(
typeMap: TypeMap,
variable: ExprVariableNode,
type: InferredType,
location: UsageLocation,
): InferredType {
if (type === 'error' || type === 'gender' || type === 'enum') {
throw new Error('Invalid expression type usage type: ' + type);
}
return typeMap.addTypeUsage(variable.name, type, {
location,
node: variable,
nodeType: 'expression',
// We have excluded the other values from type in the guard above. I think this is a typescript bug
type: type as 'unknown' | 'number-or-string' | 'number' | 'string',
});
}
function inferExprType(
typeMap: TypeMap,
node: ExprNode,
location: UsageLocation,
resultType?: InferredType,
): InferredType {
const exprType = node.exprNodeType;
switch (node.exprNodeType) {
case 'unary_minus':
inferExprType(typeMap, node.op, location, 'number');
return 'number';
case 'variable': {
if (resultType != null) {
const resultExprType = addExprTypeInfo(typeMap, node, resultType, location);
if (resultExprType === 'gender' || resultExprType === 'enum') {
return 'string';
}
return resultExprType;
}
const nodeExprType = addExprTypeInfo(typeMap, node, 'unknown', location);
if (nodeExprType === 'gender' || nodeExprType === 'enum') {
return 'string';
}
return nodeExprType;
}
case 'number':
return 'number';
case 'string_literal':
return 'string';
case 'function_invocation':
const parameterTypes = typeMap.functionParameterTypes(node.name);
const types = parameterTypes.kind === 'known' ? parameterTypes.types : [];
let idx = 0;
for (const param of node.parameters) {
const typeToInfer = idx < types.length ? types[idx] : undefined;
inferExprType(typeMap, param, location, typeToInfer);
idx++;
}
typeMap.addFunction(node.name);
return 'unknown';
case 'binary_op': {
const binopType = node.binaryOp;
switch (node.binaryOp) {
case 'plus': {
if (resultType !== 'number' || resultType == null) {
resultType = 'number-or-string';
}
const lhs = inferExprType(typeMap, node.lhs, location, resultType);
const rhs = inferExprType(typeMap, node.rhs, location, resultType);
if (lhs !== rhs) {
return 'number-or-string';
}
if (lhs === 'number') {
return 'number';
} else if (lhs === 'string') {
return 'string';
}
return lhs;
}
case 'minus':
case 'divide':
case 'multiply':
inferExprType(typeMap, node.lhs, location, 'number');
inferExprType(typeMap, node.rhs, location, 'number');
return 'number';
default:
throw new Error('Unknown binary operator: ' + binopType);
}
}
default:
throw new Error('Unknown expression type: ' + exprType);
}
}
export function inferExpressionTypes(typeMap: TypeMap, node: ExprNode, location: UsageLocation) {
inferExprType(typeMap, node, location);
}
export function inferTextTypes(typeMap: TypeMap, textAST: ASTRoot, constraintAST?: ConstraintAST) {
const location = {
constraints: constraintAST,
text: textAST,
};
const addVariableTypeInfo = (node: TextVariableNode) => {
typeMap.addTypeUsage(node.value, 'number-or-string', {
location,
node,
nodeType: 'text',
type: 'number-or-string',
});
};
for (const node of textAST.nodes) {
switch (node.textNodeType) {
case 'variable':
addVariableTypeInfo(node);
break;
case 'expr':
inferExpressionTypes(typeMap, node.value, location);
break;
default: // Not needed - nothing to infer in literal types
}
}
}
function makeTypedExpressionNode(node: ExprNode, typeMap: TypeMap): TypedExprNode {
const exprNodeType = node.exprNodeType;
if (node.exprNodeType === 'string_literal') {
return {
exprNodeType: 'string_literal',
exprType: 'string',
isConstant: true,
pos: node.pos,
typed: true,
value: node.value,
} as TypedStringLiteralNode;
} else if (node.exprNodeType === 'number') {
return {
exprNodeType: 'number',
exprType: 'number',
isConstant: true,
pos: node.pos,
typed: true,
value: node.value,
} as TypedNumberNode;
} else if (node.exprNodeType === 'variable') {
if (!typeMap.hasInfoForType(node.name)) {
throw new Error(
`Type for variable ${node.name} not found in type map.` +
'Are you sure you ran the type inference phase first?',
);
}
let type = typeMap.getVariableType(node.name);
if (type === 'gender' || type === 'enum') {
// Expressions don't deal with these type of variables.
// This might need changing if the functions
// get support for declaring types as well.
type = 'string';
}
return {
exprNodeType: 'variable',
exprType: type,
isConstant: false,
name: node.name,
pos: node.pos,
typed: true,
} as TypedVariableNode;
} else if (node.exprNodeType === 'unary_minus') {
const typedOp = makeTypedExpressionNode(node.op, typeMap);
const exprType = typedOp.exprType;
return {
exprNodeType: 'unary_minus',
exprType: exprType,
isConstant: typedOp.isConstant,
op: typedOp,
pos: node.pos,
typed: true,
};
} else if (node.exprNodeType === 'binary_op') {
const typedLhs = makeTypedExpressionNode(node.lhs, typeMap);
const lhsType = typedLhs.exprType;
const typedRhs = makeTypedExpressionNode(node.rhs, typeMap);
const rhsType = typedRhs.exprType;
const makeBinaryResult = (
op: 'plus' | 'minus' | 'divide' | 'multiply',
type: InferredType,
): TypedBinaryOpNode => {
return {
binaryOp: op,
exprNodeType: 'binary_op',
exprType: type,
isConstant: typedLhs.isConstant && typedRhs.isConstant,
lhs: typedLhs,
pos: node.pos,
rhs: typedRhs,
typed: true,
};
};
const binopType = node.binaryOp;
switch (node.binaryOp) {
case 'plus': {
const bothNumbers = lhsType === 'number' && rhsType === 'number';
let type: InferredType = 'number-or-string';
if (bothNumbers) {
type = 'number';
} else if (lhsType === 'string' && rhsType === 'string') {
type = 'string';
}
// Attempt to find the most specific type of both sides
// Basicly if either side is a string, the result
// is also a string. Otherwise it is number-or-string
return makeBinaryResult('plus', type);
}
case 'minus':
case 'divide':
case 'multiply': {
return makeBinaryResult(node.binaryOp, 'number');
}
default:
throw new Error('Unknown binary operator: ' + binopType);
}
} else if (node.exprNodeType === 'function_invocation') {
// For simplicity's sake. We state that functions
// may only return strings. This should be *ok* as
// any potential calculations can be done inside the function.
// And in any case in general they should be used
// to return some kind of escaped markup.
const parameters: TypedExprNode[] = node.parameters.map((n) => makeTypedExpressionNode(n, typeMap));
return {
exprNodeType: 'function_invocation',
exprType: 'string',
isConstant: false,
name: node.name,
parameters: parameters,
pos: node.pos,
typed: true,
} as TypedFunctionInvocationNode;
} else {
throw new Error('Unknown expression type: ' + exprNodeType);
}
}
export function makeTypedExpressionTree(typeMap: TypeMap, node: ExprNode): TypedExprNode {
if (!typeMap.isFrozen()) {
throw new Error('Type map passed must be frozen. Use TypeMap.freeze()');
}
if (typeMap.hasTypeErrors()) {
typeMap.throwTypeErrors();
}
return makeTypedExpressionNode(node, typeMap);
}
export function makeTypedExpressionList(typeMap: TypeMap, ast: ASTRoot): TypedASTRoot {
if (!typeMap.isFrozen()) {
throw new Error('Type map passed must be frozen. Use TypeMap.freeze()');
}
if (typeMap.hasTypeErrors()) {
typeMap.throwTypeErrors();
}
const result: TypedTextNode[] = [];
for (const node of ast.nodes) {
const textType = node.textNodeType;
if (node.textNodeType === 'literal') {
result.push({
pos: node.pos,
textNodeType: 'literal',
textType: 'string',
typed: true,
value: node.value,
});
} else if (node.textNodeType === 'variable') {
const type = typeMap.getVariableType(node.value);
result.push({
pos: node.pos,
textNodeType: 'variable',
textType: type,
typed: true,
value: node.value,
});
} else if (node.textNodeType === 'expr') {
// I don't know why typescript doesn't get that this is an expression.
// but this workaround does the trick.
const val = (node.value as any) as ExprNode;
const exprRes = makeTypedExpressionTree(typeMap, val);
result.push({
pos: node.pos,
textNodeType: 'expr',
textType: exprRes.exprType,
typed: true,
value: exprRes,
});
} else {
throw new Error('Unknown text node type: ' + textType);
}
}
return {
input: ast.input,
nodes: result,
};
}
|
secoya/hablar.js
|
test/analysis/expression_type_inference.ts
|
import * as infer from '../../src/analysis/type_inference';
import { Node as ConstraintNode } from '../../src/trees/constraint';
import {
BinaryOpNode,
FunctionInvocationNode,
Node,
NumberNode,
StringLiteralNode,
TypedBinaryOpNode,
TypedFunctionInvocationNode,
TypedNode,
TypedNumberNode,
TypedStringLiteralNode,
TypedUnaryMinusNode,
TypedVariableNode,
UnaryMinusNode,
VariableNode,
} from '../../src/trees/expression';
import { Node as TextNode } from '../../src/trees/text';
import TypeMap from '../../src/type_map';
import { InferredType, TypeInfo } from '../../src/type_map';
const makeEmptyPos = () => ({
firstColumn: 0,
firstLine: 1,
lastColumn: 0,
lastLine: 1,
});
const location = {
constraints: {
input: '',
nodes: [] as ConstraintNode[],
},
text: {
input: '',
nodes: [] as TextNode[],
},
};
function getTypeInfo(typeMap: TypeMap, variable: string): TypeInfo {
expect(typeMap.hasInfoForType(variable)).toBe(true);
return typeMap.getVariableTypeInfo(variable);
}
function makeVariableNode(name: string): VariableNode {
return {
exprNodeType: 'variable',
name: name,
pos: makeEmptyPos(),
};
}
function makeTypedVariableNode(name: string, type: InferredType): TypedVariableNode {
return {
exprNodeType: 'variable',
exprType: type,
isConstant: false,
name: name,
pos: makeEmptyPos(),
typed: true,
};
}
function makeNumberNode(val: number): NumberNode {
return {
exprNodeType: 'number',
pos: makeEmptyPos(),
value: val,
};
}
function makeTypedNumberNode(val: number): TypedNumberNode {
return {
exprNodeType: 'number',
exprType: 'number',
isConstant: true,
pos: makeEmptyPos(),
typed: true,
value: val,
};
}
function makeUnaryMinusNode(op: Node): UnaryMinusNode {
return {
exprNodeType: 'unary_minus',
op: op,
pos: makeEmptyPos(),
};
}
function makeTypedUnaryMinusNode(op: TypedNode, type: InferredType): TypedUnaryMinusNode {
return {
exprNodeType: 'unary_minus',
exprType: type,
isConstant: op.isConstant,
op: op,
pos: makeEmptyPos(),
typed: true,
};
}
function makeStringLiteralNode(val: string): StringLiteralNode {
return {
exprNodeType: 'string_literal',
pos: makeEmptyPos(),
value: val,
};
}
function makeTypedStringLiteralNode(val: string): TypedStringLiteralNode {
return {
exprNodeType: 'string_literal',
exprType: 'string',
isConstant: true,
pos: makeEmptyPos(),
typed: true,
value: val,
};
}
function makeBinaryPlusNode(lhs: Node, rhs: Node): BinaryOpNode {
return {
binaryOp: 'plus',
exprNodeType: 'binary_op',
lhs: lhs,
pos: makeEmptyPos(),
rhs: rhs,
};
}
function makeTypedBinaryPlusNode(lhs: TypedNode, rhs: TypedNode, type: InferredType): TypedBinaryOpNode {
return {
binaryOp: 'plus',
exprNodeType: 'binary_op',
exprType: type,
isConstant: lhs.isConstant && rhs.isConstant,
lhs: lhs,
pos: makeEmptyPos(),
rhs: rhs,
typed: true,
};
}
function makeBinaryNumberNode(lhs: Node, rhs: Node): BinaryOpNode {
return {
binaryOp: 'minus',
exprNodeType: 'binary_op',
lhs: lhs,
pos: makeEmptyPos(),
rhs: rhs,
};
}
function makeTypedBinaryNumberNode(lhs: TypedNode, rhs: TypedNode, type: InferredType): TypedBinaryOpNode {
return {
binaryOp: 'minus',
exprNodeType: 'binary_op',
exprType: type,
isConstant: lhs.isConstant && rhs.isConstant,
lhs: lhs,
pos: makeEmptyPos(),
rhs: rhs,
typed: true,
};
}
function makeFunctionInvocationNode(name: string, parameters: Node[]): FunctionInvocationNode {
return {
exprNodeType: 'function_invocation',
name: name,
parameters,
pos: makeEmptyPos(),
};
}
function makeTypedFunctionInvocationNode(
name: string,
parameters: TypedNode[],
type: 'error' | 'string',
): TypedFunctionInvocationNode {
return {
exprNodeType: 'function_invocation',
exprType: type,
isConstant: false,
name: name,
parameters,
pos: makeEmptyPos(),
typed: true,
};
}
describe('Type inference', () => {
describe('Binary operators', () => {
describe('Plus', () => {
it('Should infer var+10 as number-or-string', () => {
const varName = 'var';
const node = makeBinaryPlusNode(makeVariableNode(varName), makeNumberNode(10));
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('number-or-string').toEqual(info.type);
const typedNode = makeTypedBinaryPlusNode(
makeTypedVariableNode(varName, 'number-or-string'),
makeTypedNumberNode(10),
'number-or-string',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
it('Should infer var+"hello" as number-or-string', () => {
const varName = 'var';
const node = makeBinaryPlusNode(makeVariableNode(varName), makeStringLiteralNode('hello'));
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('number-or-string').toEqual(info.type);
const typedNode = makeTypedBinaryPlusNode(
makeTypedVariableNode(varName, 'number-or-string'),
makeTypedStringLiteralNode('hello'),
'number-or-string',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
it('Should infer both vars in var+var2 as number-or-string', () => {
const varName = 'var';
const secondVarName = 'var2';
const node = makeBinaryPlusNode(makeVariableNode(varName), makeVariableNode(secondVarName));
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('number-or-string').toEqual(info.type);
const secondInfo = getTypeInfo(typeMap, secondVarName);
expect('number-or-string').toEqual(secondInfo.type);
const typedNode = makeTypedBinaryPlusNode(
makeTypedVariableNode(varName, 'number-or-string'),
makeTypedVariableNode(secondVarName, 'number-or-string'),
'number-or-string',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
it('Should infer var+5 where var is number as number', () => {
const varName = 'var';
const node = makeBinaryPlusNode(makeVariableNode(varName), makeNumberNode(5));
const typeMap = new TypeMap();
typeMap.addTypeUsage(varName, 'number', {
nodeType: 'custom',
});
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('number').toEqual(info.type);
const typedNode = makeTypedBinaryPlusNode(
makeTypedVariableNode(varName, 'number'),
makeTypedNumberNode(5),
'number',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
});
describe('Number operators', () => {
it('Should infer var-5 as number', () => {
const varName = 'var';
const node = makeBinaryNumberNode(makeVariableNode(varName), makeNumberNode(5));
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('number').toEqual(info.type);
const typedNode = makeTypedBinaryNumberNode(
makeTypedVariableNode(varName, 'number'),
makeTypedNumberNode(5),
'number',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
it('Should infers both vars in var-var2 as number', () => {
const varName = 'var';
const secondVarName = 'var2';
const node = makeBinaryNumberNode(makeVariableNode(varName), makeVariableNode(secondVarName));
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('number').toEqual(info.type);
const secondInfo = getTypeInfo(typeMap, secondVarName);
expect('number').toEqual(secondInfo.type);
const typedNode = makeTypedBinaryNumberNode(
makeTypedVariableNode(varName, 'number'),
makeTypedVariableNode(secondVarName, 'number'),
'number',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
});
});
describe('Unary minus', () => {
it('Should infer -var as number', () => {
const varName = 'var';
const node = makeUnaryMinusNode(makeVariableNode(varName));
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('number').toEqual(info.type);
const typedNode = makeTypedUnaryMinusNode(makeTypedVariableNode(varName, 'number'), 'number');
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
it('Should infer -(var+5) as number', () => {
const varName = 'var';
const node = makeUnaryMinusNode(makeBinaryPlusNode(makeVariableNode(varName), makeNumberNode(5)));
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('number').toEqual(info.type);
const typedNode = makeTypedUnaryMinusNode(
makeTypedBinaryPlusNode(makeTypedVariableNode(varName, 'number'), makeTypedNumberNode(5), 'number'),
'number',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
it('Should infer both vars in -(var+var2) as number', () => {
const varName = 'var';
const secondVarName = 'var2';
const node = makeUnaryMinusNode(
makeBinaryPlusNode(makeVariableNode(varName), makeVariableNode(secondVarName)),
);
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('number').toEqual(info.type);
const secondInfo = getTypeInfo(typeMap, secondVarName);
expect('number').toEqual(secondInfo.type);
const typedNode = makeTypedUnaryMinusNode(
makeTypedBinaryPlusNode(
makeTypedVariableNode(varName, 'number'),
makeTypedVariableNode(secondVarName, 'number'),
'number',
),
'number',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
describe('Fail cases', () => {
it('Should fail to unify number with string', () => {
const varName = 'var';
const node = makeUnaryMinusNode(makeVariableNode(varName));
const typeMap = new TypeMap();
typeMap.addTypeUsage(varName, 'string', {
nodeType: 'custom',
});
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect(typeMap.hasTypeErrors()).toBe(true);
expect('error').toEqual(info.type);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
it('Should fail to unify number with enum', () => {
const varName = 'var';
const node = makeUnaryMinusNode(makeVariableNode(varName));
const typeMap = new TypeMap();
typeMap.addTypeUsage(varName, 'enum', {
nodeType: 'custom',
});
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect(typeMap.hasTypeErrors()).toBe(true);
expect('error').toEqual(info.type);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
it('Should fail to unify number with gender', () => {
const varName = 'var';
const node = makeUnaryMinusNode(makeVariableNode(varName));
const typeMap = new TypeMap();
typeMap.addTypeUsage(varName, 'gender', {
nodeType: 'custom',
});
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect(typeMap.hasTypeErrors()).toBe(true);
expect('error').toEqual(info.type);
expect(0).toEqual(Array.from(typeMap.functionNames()).length);
});
});
});
describe('Functions', () => {
it('Will infer unknown for variable used as a parameter', () => {
const varName = 'var';
const node = makeFunctionInvocationNode('fn', [makeVariableNode(varName)]);
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('unknown').toEqual(info.type);
const typedNode = makeTypedFunctionInvocationNode(
'fn',
[makeTypedVariableNode(varName, 'unknown')],
'string',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(['fn']).toEqual(Array.from(typeMap.functionNames()));
});
it('Will infer unknown for multiple variables used as parameters', () => {
const varName = 'var';
const secondVarName = 'var2';
const node = makeFunctionInvocationNode('fn', [makeVariableNode(varName), makeVariableNode(secondVarName)]);
const typeMap = new TypeMap();
infer.inferExpressionTypes(typeMap, node, location);
typeMap.freeze();
const info = getTypeInfo(typeMap, varName);
expect('unknown').toEqual(info.type);
const secondInfo = getTypeInfo(typeMap, secondVarName);
expect('unknown').toEqual(secondInfo.type);
const typedNode = makeTypedFunctionInvocationNode(
'fn',
[makeTypedVariableNode(varName, 'unknown'), makeTypedVariableNode(secondVarName, 'unknown')],
'string',
);
const typeInfo = infer.makeTypedExpressionTree(typeMap, node);
expect(typedNode).toEqual(typeInfo);
expect(['fn']).toEqual(Array.from(typeMap.functionNames()));
});
});
});
|
secoya/hablar.js
|
test/analysis/constraints_type_inference.ts
|
<filename>test/analysis/constraints_type_inference.ts
import * as infer from '../../src/analysis/type_inference';
import TypeMap from '../../src/type_map';
import { ConstraintTypeUsage, TypeInfo, TypeUsage } from '../../src/type_map';
import {
EnumNode,
EqualityNode,
GenderNode,
IdentifierNode,
IneqNode,
Node,
NumberNode,
} from '../../src/trees/constraint';
const makeEmptyPos = () => ({
firstColumn: 0,
firstLine: 1,
lastColumn: 0,
lastLine: 1,
});
function getTypeInfo(typeMap: TypeMap, variable: string): TypeInfo {
expect(typeMap.hasInfoForType(variable)).toBe(true);
return typeMap.getVariableTypeInfo(variable);
}
function makeNumberNode(variable: string, op: '=' | '!=' | '>' | '<' | '<=' | '>=' = '='): Node {
const numberNode: NumberNode = {
pos: makeEmptyPos(),
type: 'number',
value: 5,
};
const varNode: IdentifierNode = {
name: variable,
pos: makeEmptyPos(),
type: 'identifier',
};
if (op === '=' || op === '!=') {
const res: EqualityNode = {
lhs: varNode,
op: op as '=' | '!=',
pos: makeEmptyPos(),
rhs: numberNode,
};
return res;
} else {
const res: IneqNode = {
lhs: varNode,
op: op as '>' | '<' | '<=' | '>=',
pos: makeEmptyPos(),
rhs: numberNode,
};
return res;
}
}
function makeEnumNode(variable: string, op: '=' | '!=' = '='): Node {
const enumNode: EnumNode = {
pos: makeEmptyPos(),
type: 'enum',
value: 'some-enum',
};
const varNode: IdentifierNode = {
name: variable,
pos: makeEmptyPos(),
type: 'identifier',
};
const res: EqualityNode = {
lhs: varNode,
op: op,
pos: makeEmptyPos(),
rhs: enumNode,
};
return res;
}
function makeGenderNode(variable: string, op: '=' | '!=' = '='): Node {
const genderNode: GenderNode = {
pos: makeEmptyPos(),
type: 'gender',
value: 'F',
};
const varNode: IdentifierNode = {
name: variable,
pos: makeEmptyPos(),
type: 'identifier',
};
const res: EqualityNode = {
lhs: varNode,
op: op,
pos: makeEmptyPos(),
rhs: genderNode,
};
return res;
}
function makeIgnoreNode(variable: string): Node {
const varNode: IdentifierNode = {
name: variable,
pos: makeEmptyPos(),
type: 'identifier',
};
return {
op: '!',
operand: varNode,
pos: makeEmptyPos(),
};
}
function assertConstraintUsage(usage: TypeUsage): ConstraintTypeUsage {
expect('constraint').toEqual(usage.nodeType);
if (usage.nodeType !== 'constraint') {
throw new Error('Make flow happy');
}
return usage;
}
describe('Type inference', () => {
describe('Constraints', () => {
describe('Ignore', () => {
it('Should infer ignore constraints as unknown', () => {
const constraints = [makeIgnoreNode('i')];
const typeMap = new TypeMap();
const textAST = {
input: 'test',
nodes: [],
};
const constraintAST = {
input: '!i',
nodes: constraints,
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'i');
expect({
type: 'unknown',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'unknown',
},
],
}).toEqual(typeInfo);
const usage = assertConstraintUsage(typeInfo.usages[0]);
expect(constraints[0]).toEqual(usage.node);
expect(constraintAST).toEqual(usage.location.constraints);
expect(textAST).toEqual(usage.location.text);
});
});
describe('Numbers', () => {
it('Should infer number equals as number', () => {
const constraints = [makeNumberNode('n', '=')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'n=5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'number',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
it('Should infer number not-equals as number', () => {
const constraints = [makeNumberNode('n', '!=')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'n!=5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'number',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
it('Should infer number less-than as number', () => {
const constraints = [makeNumberNode('n', '<')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'n<5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'number',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
it('Should infer number less-than-equals as number', () => {
const constraints = [makeNumberNode('n', '<=')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'n<=5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'number',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
it('Should infer number greater-than as number', () => {
const constraints = [makeNumberNode('n', '>')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'n>5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'number',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
it('Should infer number greater-than-equals as number', () => {
const constraints = [makeNumberNode('n', '>=')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'n>=5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'number',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
});
describe('Genders', () => {
it('Should infer gender equals as gender type', () => {
const constraints = [makeGenderNode('g', '=')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'g=5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'g');
expect({
type: 'gender',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'gender',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
it('Should infer gender not-equals as gender type', () => {
const constraints = [makeGenderNode('g', '!=')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'g!=5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'g');
expect({
type: 'gender',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'gender',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
});
describe('Enums', () => {
it('Should infer enum equals as enum type', () => {
const constraints = [makeEnumNode('e', '=')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'e=5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'e');
expect({
type: 'enum',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'enum',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
it('Should infer enum not-equals as enum type', () => {
const constraints = [makeEnumNode('e', '!=')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'e!=5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'e');
expect({
type: 'enum',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'enum',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
});
});
describe('Multiple distinct variable', () => {
it('Should infer types for both variables', () => {
const constraints = [makeEnumNode('e'), makeNumberNode('i')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'e="enum", i=5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(2).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'e');
expect({
type: 'enum',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'enum',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
const numberTypeInfo = getTypeInfo(typeMap, 'i');
expect({
type: 'number',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[1],
nodeType: 'constraint',
type: 'number',
},
],
}).toEqual(numberTypeInfo);
assertConstraintUsage(numberTypeInfo.usages[0]);
});
});
describe('Same variable multiple constraints', () => {
describe('Initial number', () => {
it('Is number when used as number two times', () => {
const constraints = [makeNumberNode('n'), makeNumberNode('n', '>')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'n=5, n>5',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'number',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[1],
nodeType: 'constraint',
type: 'number',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
assertConstraintUsage(typeInfo.usages[1]);
});
it('Is number when used as ignore', () => {
const constraints = [makeNumberNode('n'), makeIgnoreNode('n')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'n=5,!n',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'number',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[1],
nodeType: 'constraint',
type: 'unknown',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
assertConstraintUsage(typeInfo.usages[1]);
});
});
describe('Fail cases', () => {
it('Cannot reconcile with enum', () => {
const constraints = [makeNumberNode('n'), makeEnumNode('n')];
const typeMap = new TypeMap();
const constraintAST = {
input: 'n=5,n="enum"',
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'error',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[1],
nodeType: 'constraint',
type: 'enum',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
assertConstraintUsage(typeInfo.usages[1]);
});
it('Cannot reconcile with gender', () => {
const constraints = [makeNumberNode('n'), makeGenderNode('n')];
const typeMap = new TypeMap();
const constraintAST = {
input: "n=5,n='F'",
nodes: constraints,
};
const textAST = {
input: 'test',
nodes: [],
};
infer.inferConstraintTypes(typeMap, constraintAST, textAST);
expect(1).toEqual(typeMap.size);
const typeInfo = getTypeInfo(typeMap, 'n');
expect({
type: 'error',
usages: [
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[0],
nodeType: 'constraint',
type: 'number',
},
{
location: {
constraints: constraintAST,
text: textAST,
},
node: constraints[1],
nodeType: 'constraint',
type: 'gender',
},
],
}).toEqual(typeInfo);
assertConstraintUsage(typeInfo.usages[0]);
assertConstraintUsage(typeInfo.usages[1]);
});
});
});
});
});
|
secoya/hablar.js
|
src/analysis/constraints.ts
|
import { ASTRoot } from '../trees/constraint';
import { TypedASTRoot as TextTypedASTRoot } from '../trees/text';
import DeadCodeError from '../errors/dead_code_error';
function isDefiniteReturn(ast: ASTRoot) {
for (const node of ast.nodes) {
if (node.op !== '!') {
return false;
}
}
return true;
}
/**
* For now, this just reports cases where some constraint nodes are dead.
* Due to a previous constraint always being true.
*
* In the future, I would love for this to do more analysis and determine
* cases like these as dead:
*
* n = 5: $n is 5
* n != 5: $n is not 5
* n = 3: This is dead
*
* But this is much more complicated with more values than one. However,
* it is more than possible.
*/
export function analyzeConstraints(
translations: Array<{
constraints: ASTRoot;
translation: TextTypedASTRoot;
}>,
): void {
let definiteReturn = false;
for (const translation of translations) {
if (isDefiniteReturn(translation.constraints)) {
definiteReturn = true;
continue;
}
if (definiteReturn) {
throw new DeadCodeError('Dead code', translations, translation);
}
}
}
|
secoya/hablar.js
|
src/parsers/constraint.ts
|
import { Node } from '../trees/constraint';
import getParser from './get_parser';
const constraintParser = getParser('constraint');
export type ConstraintParserResult = {
input: string;
nodes: Node[];
};
export default function parse(input: string): ConstraintParserResult {
return {
input: input,
nodes: constraintParser.parse(input),
};
}
|
secoya/hablar.js
|
src/errors/dead_code_error.ts
|
import { ASTRoot as ConstraintAST } from '../trees/constraint';
import { TypedASTRoot as TextAST } from '../trees/text';
export default class DeadCodeError extends Error {
public message: string;
public constructor(
message: string,
translations: Array<{
constraints: ConstraintAST;
translation: TextAST;
}>,
deadTranslation: {
constraints: ConstraintAST;
translation: TextAST;
},
) {
super(message);
Object.setPrototypeOf(this, DeadCodeError.prototype);
}
}
DeadCodeError.prototype.name = 'DeadCodeError';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.