branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/main | <repo_name>FuramyD/linkedin-redesign<file_sep>/client/src/app/pipes/pipes.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { NamePipe } from './name-pipe/name-pipe.pipe'
import { PrefixPlusPipe } from './prefix-plus-pipe/prefix-plus.pipe'
import { MaskedPhonePipe } from './masked-phone/masked-phone.pipe'
import { MaskedEmailPipe } from './masked-email/masked-email.pipe'
import { AvatarPipe } from './avatar.pipe'
@NgModule({
declarations: [
NamePipe,
PrefixPlusPipe,
MaskedPhonePipe,
MaskedEmailPipe,
AvatarPipe,
],
exports: [
PrefixPlusPipe,
NamePipe,
MaskedPhonePipe,
MaskedEmailPipe,
AvatarPipe,
],
imports: [CommonModule],
})
export class PipesModule {}
<file_sep>/client/src/app/interfaces/chat/chats.ts
import { IMessage } from './message'
export interface IChats {
chats: {
chatId: number
users: { userId: number }[]
messages: IMessage[]
}[]
}
<file_sep>/client/src/app/plugins/hystModal.ts
export class HystModal {
constructor(props: any) {
const defaultConfig = {
backscroll: true,
linkAttributeName: 'data-hystmodal',
closeOnOverlay: true,
closeOnEsc: true,
closeOnButton: true,
waitTransitions: false,
catchFocus: true,
fixedSelectors: '*[data-hystfixed]',
beforeOpen: () => {},
afterClose: () => {},
}
this.config = Object.assign(defaultConfig, props)
if (this.config.linkAttributeName) {
this.init()
}
this._closeAfterTransition = this._closeAfterTransition.bind(this)
}
config: any
isOpened: boolean | undefined
openedWindow: boolean | undefined
starter: boolean | undefined
_nextWindows: boolean | undefined
_scrollPosition: number | undefined
_reopenTrigger: boolean | undefined
_overlayChecker: boolean | undefined
_isMoved: boolean | undefined
_focusElements: any
_modalBlock: boolean | undefined
shadow: any
init() {
this.isOpened = false
this.openedWindow = false
this.starter = false
this._nextWindows = false
this._scrollPosition = 0
this._reopenTrigger = false
this._overlayChecker = false
this._isMoved = false
this._focusElements = [
'a[href]',
'area[href]',
'input:not([disabled]):not([type="hidden"]):not([aria-hidden])',
'select:not([disabled]):not([aria-hidden])',
'textarea:not([disabled]):not([aria-hidden])',
'button:not([disabled]):not([aria-hidden])',
'iframe',
'object',
'embed',
'[contenteditable]',
'[tabindex]:not([tabindex^="-"])',
]
this._modalBlock = false
const existingShadow = document.querySelector('.hystmodal__shadow')
if (existingShadow) {
this.shadow = existingShadow
} else {
this.shadow = document.createElement('div')
this.shadow.classList.add('hystmodal__shadow')
document.body.appendChild(this.shadow)
}
this.eventsFeeler()
}
eventsFeeler(): void {
document.addEventListener(
'click',
(e): void => {
const clickedlink = e.target.closest(
'[' + this.config.linkAttributeName + ']',
)
if (!this._isMoved && clickedlink) {
e.preventDefault()
this.starter = clickedlink
let targetSelector = this.starter.getAttribute(
this.config.linkAttributeName,
)
this._nextWindows = document.querySelector(targetSelector)
this.open()
return
}
if (
this.config.closeOnButton &&
e.target.closest('[data-hystclose]')
) {
this.close()
return
}
},
)
if (this.config.closeOnOverlay) {
document.addEventListener(
'mousedown',
(e) => {
if (
!this._isMoved &&
e.target instanceof Element &&
!e.target.classList.contains('hystmodal__wrap')
)
return
this._overlayChecker = true
}.bind(this),
)
document.addEventListener(
'mouseup',
function (e) {
if (
!this._isMoved &&
e.target instanceof Element &&
this._overlayChecker &&
e.target.classList.contains('hystmodal__wrap')
) {
e.preventDefault()
!this._overlayChecker
this.close()
return
}
this._overlayChecker = false
}.bind(this),
)
}
window.addEventListener(
'keydown',
function (e) {
if (
!this._isMoved &&
this.config.closeOnEsc &&
e.which == 27 &&
this.isOpened
) {
e.preventDefault()
this.close()
return
}
if (
!this._isMoved &&
this.config.catchFocus &&
e.which == 9 &&
this.isOpened
) {
this.focusCatcher(e)
return
}
}.bind(this),
)
}
open(selector) {
if (selector) {
if (typeof selector === 'string') {
this._nextWindows = document.querySelector(selector)
} else {
this._nextWindows = selector
}
}
if (!this._nextWindows) {
console.log('Warning: hystModal selector is not found')
return
}
if (this.isOpened) {
this._reopenTrigger = true
this.close()
return
}
this.openedWindow = this._nextWindows
this._modalBlock = this.openedWindow.querySelector('.hystmodal__window')
this.config.beforeOpen(this)
this._bodyScrollControl()
this.shadow.classList.add('hystmodal__shadow--show')
this.openedWindow.classList.add('hystmodal--active')
this.openedWindow.setAttribute('aria-hidden', 'false')
if (this.config.catchFocus) this.focusControl()
this.isOpened = true
}
close() {
if (!this.isOpened) {
return
}
if (this.config.waitTransitions) {
this.openedWindow.classList.add('hystmodal--moved')
this._isMoved = true
this.openedWindow.addEventListener(
'transitionend',
this._closeAfterTransition,
)
this.openedWindow.classList.remove('hystmodal--active')
} else {
this.openedWindow.classList.remove('hystmodal--active')
this._closeAfterTransition()
}
}
_closeAfterTransition() {
this.openedWindow.classList.remove('hystmodal--moved')
this.openedWindow.removeEventListener(
'transitionend',
this._closeAfterTransition,
)
this._isMoved = false
this.shadow.classList.remove('hystmodal__shadow--show')
this.openedWindow.setAttribute('aria-hidden', 'true')
if (this.config.catchFocus) this.focusControl()
this._bodyScrollControl()
this.isOpened = false
this.openedWindow.scrollTop = 0
this.config.afterClose(this)
if (this._reopenTrigger) {
this._reopenTrigger = false
this.open()
}
}
focusControl() {
const nodes = this.openedWindow.querySelectorAll(this._focusElements)
if (this.isOpened && this.starter) {
this.starter.focus()
} else {
if (nodes.length) nodes[0].focus()
}
}
focusCatcher(e) {
const nodes = this.openedWindow.querySelectorAll(this._focusElements)
const nodesArray = Array.prototype.slice.call(nodes)
if (!this.openedWindow.contains(document.activeElement)) {
nodesArray[0].focus()
e.preventDefault()
} else {
const focusedItemIndex = nodesArray.indexOf(document.activeElement)
console.log(focusedItemIndex)
if (e.shiftKey && focusedItemIndex === 0) {
nodesArray[nodesArray.length - 1].focus()
e.preventDefault()
}
if (!e.shiftKey && focusedItemIndex === nodesArray.length - 1) {
nodesArray[0].focus()
e.preventDefault()
}
}
}
_bodyScrollControl() {
if (!this.config.backscroll) return
// collect fixed selectors to array
let fixedSelectors = Array.prototype.slice.call(
document.querySelectorAll(this.config.fixedSelectors),
)
let html = document.documentElement
if (this.isOpened === true) {
html.classList.remove('hystmodal__opened')
html.style.marginRight = ''
fixedSelectors.map(el => {
el.style.marginRight = ''
})
window.scrollTo(0, this._scrollPosition)
html.style.top = ''
return
}
this._scrollPosition = window.pageYOffset
let marginSize = window.innerWidth - html.clientWidth
html.style.top = -this._scrollPosition + 'px'
if (marginSize) {
html.style.marginRight = marginSize + 'px'
fixedSelectors.map(el => {
el.style.marginRight =
parseInt(getComputedStyle(el).marginRight) +
marginSize +
'px'
})
}
html.classList.add('hystmodal__opened')
}
}
<file_sep>/server/src/users/users.controller.ts
import { Body, Controller, Delete, Get, HttpStatus, Param, Post, Query, Res, UploadedFile, UseInterceptors } from '@nestjs/common'
import { Express, Request } from 'express'
import { UsersService } from './users.service'
import { CreateUserDto } from '../dto/create-user.dto'
import { AuthDto } from '../dto/auth.dto'
import { Response } from 'express'
import { SendConnectionDto } from '../dto/send-connection.dto'
import { IPersonalInfo } from '../interfaces/edit-profile/personalInfo'
import { FileInterceptor } from '@nestjs/platform-express'
import { diskStorage } from 'multer'
import { extname } from 'path'
import { IContact } from '../interfaces/contact'
import { IProject } from '../interfaces/project'
import { IExp } from '../interfaces/exp'
import { IUniversity } from '../interfaces/university'
import { ILocality } from '../interfaces/locality'
const storage = diskStorage({
destination: (req, file, callback) => {
callback(null, 'src/uploads')
},
filename(req: Request, file: Express.Multer.File, callback: (error: Error | null, filename: string) => void): void {
callback(null, file.fieldname + '_' + Date.now() + extname(file.originalname))
},
})
@Controller('users')
export class UsersController {
constructor(private usersService: UsersService) {}
@Post('create')
async createUser(@Body() body: CreateUserDto, @Res() res: Response): Promise<void> {
const user = await this.usersService.createUser(body)
if (user) {
res.status(HttpStatus.CREATED).send({ user })
return
}
res.status(HttpStatus.CONFLICT).send({
error: 'A user with the same email or phone number already exists',
})
}
@Post('auth')
async authUser(@Body() body: AuthDto, @Res() res: Response): Promise<void> {
const user = await this.usersService.authUser(body)
if (user) {
res.status(HttpStatus.OK).send({ user })
} else res.status(HttpStatus.CONFLICT).send({ error: 'User is not found' })
}
@Get('find/:id')
async findUserById(@Param() param, @Res() res: Response, @Query() query: { fullName?: string }): Promise<void> {
if (param.id === 'all') {
const users = await this.usersService.findAllUsers(query)
res.status(HttpStatus.OK).send({ users })
return
}
if (param.id.match(/,/)) {
const users = await this.usersService.findUsersById(param.id)
if (users) res.status(HttpStatus.OK).send({ users })
else res.status(HttpStatus.CONFLICT).send({ error: 'Users not found' })
return
}
const user = await this.usersService.findUserById(+param.id)
if (user) res.status(HttpStatus.OK).send({ user })
else res.status(HttpStatus.CONFLICT).send({ error: 'User is not found' })
}
@Post('remove/:id')
async removeUser(@Param() param, @Body() data: { password: string }, @Res() res: Response): Promise<void> {
const isRemoved = await this.usersService.removeUser(+param.id, data.password)
if (isRemoved) res.status(HttpStatus.OK).send({ message: `Your account has been deleted` })
else if (isRemoved === null) res.status(HttpStatus.CONFLICT).send({ error: 'User is not found' })
else if (isRemoved === false) res.status(HttpStatus.CONFLICT).send({ error: 'Wrong password' })
}
@Post('connections/send/:id') // :id - userId
async sendConnection(@Param() param, @Body() data: SendConnectionDto, @Res() res: Response): Promise<void> {
const { sent } = await this.usersService.sendConnection(data.senderId, +param.id, data.message)
if (sent) res.status(HttpStatus.OK).send({ sent })
else res.status(HttpStatus.CONFLICT).send({ sent })
}
@Post('connections/accept/:id') // :id - senderId
async acceptConnection(@Param() param, @Body() data: { userId: number; date: number }, @Res() res: Response): Promise<void> {
const result = await this.usersService.acceptConnection(+param.id, data.userId, data.date)
if (result && result.user) res.status(HttpStatus.OK).send({ user: result.user, chatId: result.chatId })
else res.status(HttpStatus.OK).send({ error: `User with id: ${param.id} is not found` })
}
@Post('connections/decline/:id') // :id - senderId
async declineConnection(@Param() param, @Body() data: { userId: number }, @Res() res: Response): Promise<void> {
const user = this.usersService.declineConnection(+param.id, data.userId)
if (user) res.status(HttpStatus.OK).send(user)
else res.status(HttpStatus.OK).send({ error: `User with id: ${param.id} is not found` })
}
@Post('connections/remove/:id') // :id - senderId
async removeConnection(@Param() param, @Body() data: { userId: number }, @Res() res: Response): Promise<void> {
const user = this.usersService.removeConnection(+param.id, data.userId)
if (user) res.status(HttpStatus.OK).send(user)
else res.status(HttpStatus.OK).send({ error: `User with id: ${param.id} is not found` })
}
@Get('connections/clear/:id')
clearConnections(@Param() param, @Res() res: Response): void {
this.usersService.clearConnections(+param.id).then(r => console.log(r))
res.send({ msg: 'success' })
}
@Post('find/:id/edit/profile-info')
async editPersonalInfo(@Param() param, @Body() info: IPersonalInfo, @Res() res: Response): Promise<void> {
const response = await this.usersService.editPersonalInfo(+param.id, info)
if (response === 'changed') res.status(HttpStatus.OK).send({ status: 'changed', newInfo: info })
if (response === 'not found') res.status(HttpStatus.NOT_FOUND).send({ status: 'not found' })
}
@Post(':id/avatar/upload')
@UseInterceptors(
FileInterceptor('avatar', {
storage,
}),
)
async avatarUpload(@UploadedFile() file: Express.Multer.File, @Param() param: { id: string }, @Res() res: Response): Promise<void> {
console.log('upload')
const result = await this.usersService.uploadAvatar(file, +param.id)
if (result)
res.status(HttpStatus.OK).send({
message: 'Avatar uploaded successfully',
url: `http://localhost:3000/uploads/${file.filename}`,
})
if (!result) res.status(HttpStatus.CONFLICT).send({ message: 'Avatar not loaded' })
}
@Delete(':id/avatar/delete')
async deleteAvatar(@Param() param: { id: string }, @Res() res: Response): Promise<void> {
const result = this.usersService.deleteAvatar(+param.id)
if (result) res.status(HttpStatus.OK).send({ message: 'Avatar has been deleted' })
if (!result) res.status(HttpStatus.OK).send({ message: 'Avatar has not been deleted' })
}
@Get('validate/:id/:fieldName/:value')
async validateUserBySomething(@Param() param: { id: string; fieldName: string; value: string }, @Res() res: Response) {
const { id, fieldName, value } = param
const user = await this.usersService.validateUserBySomething(+id, fieldName, value)
if (user) res.status(HttpStatus.OK).send(user)
else res.status(HttpStatus.NOT_FOUND).send({ message: 'User is not found' })
}
@Post(':id/change/email')
async changeEmail(@Param() param: { id: string }, @Body() data: { email: string }, @Res() res: Response): Promise<void> {
const isChanged = await this.usersService.changeEmail(+param.id, data.email)
if (isChanged) res.status(HttpStatus.OK).send({ message: 'email has been changed' })
if (!isChanged) res.status(HttpStatus.NOT_FOUND).send({ message: 'email has not been changed' })
}
@Post(':id/change/phone')
async changePhone(@Param() param: { id: string }, @Body() data: { phone: string }, @Res() res: Response): Promise<void> {
const isChanged = await this.usersService.changePhone(+param.id, data.phone)
if (isChanged) res.status(HttpStatus.OK).send({ message: 'phone has been changed' })
if (!isChanged) res.status(HttpStatus.NOT_FOUND).send({ message: 'phone has not been changed' })
}
@Post(':id/change/password')
async changePassword(
@Param() param: { id: string },
@Body() data: { newPassword: string; oldPassword: string },
@Res() res: Response,
): Promise<void> {
const isChanged = await this.usersService.changePassword(+param.id, data.newPassword, data.oldPassword)
if (isChanged) res.status(HttpStatus.OK).send({ message: 'password has been changed' })
if (isChanged === null) {
res.status(HttpStatus.NOT_FOUND).send({ message: 'incorrect old password' })
return
}
if (!isChanged) res.status(HttpStatus.CONFLICT).send({ message: 'password has not been changed' })
}
@Post(':id/change/role')
async changeRole(@Param() param: { id: string }, @Body() data: { role: string }, @Res() res: Response): Promise<void> {
const changed = await this.usersService.changeRole(+param.id, data.role)
if (changed) res.status(HttpStatus.OK).send({ message: 'Role has been changed' })
else res.status(HttpStatus.CONFLICT).send({ message: 'Role has not been changed, please try again' })
}
@Post(':id/change/company')
async changeCompany(@Param() param: { id: string }, @Body() data: { company: any }, @Res() res: Response): Promise<void> {
// const changed = await this.usersService.changeCompany(+param.id, data.company)
}
@Post(':id/change/about')
async changeAbout(@Param() param: { id: string }, @Body() data: { about: string }, @Res() res: Response): Promise<void> {
const changed = await this.usersService.changeAbout(+param.id, data.about)
if (changed) res.status(HttpStatus.OK).send({ message: 'About has been changed' })
else res.status(HttpStatus.CONFLICT).send({ message: 'About has not been changed, please try again' })
}
@Post(':id/change/profession')
async changeProfession(@Param() param: { id: string }, @Body() data: { profession: string }, @Res() res: Response): Promise<void> {
const changed = await this.usersService.changeProfession(+param.id, data.profession)
if (changed) res.status(HttpStatus.OK).send({ message: 'Profession has been changed' })
else res.status(HttpStatus.CONFLICT).send({ message: 'Profession has not been changed, please try again' })
}
@Post(':id/change/locality')
async changeLocality(@Param() param: { id: string }, @Body() data: { locality: ILocality }, @Res() res: Response): Promise<void> {
const changed = await this.usersService.changeLocality(+param.id, data.locality)
if (changed) res.status(HttpStatus.OK).send({ message: 'Locality has been changed' })
else res.status(HttpStatus.CONFLICT).send({ message: 'Locality has not been changed, please try again' })
}
@Post(':id/change/contact-info')
async changeContactInfo(
@Param() param: { id: string },
@Body() data: { contactInfo: IContact[] },
@Res() res: Response,
): Promise<void> {
const changed = await this.usersService.changeContactInfo(+param.id, data.contactInfo)
if (changed) res.status(HttpStatus.OK).send({ message: 'Contact information has been changed' })
else res.status(HttpStatus.CONFLICT).send({ message: 'Contact information has not been changed, please try again' })
}
@Post(':id/change/projects')
async changeProjects(@Param() param: { id: string }, @Body() data: { projects: IProject[] }, @Res() res: Response): Promise<void> {
const changed = await this.usersService.changeProjects(+param.id, data.projects)
if (changed) res.status(HttpStatus.OK).send({ message: 'Projects have been changed' })
else res.status(HttpStatus.CONFLICT).send({ message: 'Projects have not been changed, please try again' })
}
@Post(':id/change/experience')
async changeExperience(@Param() param: { id: string }, @Body() data: { experience: IExp[] }, @Res() res: Response): Promise<void> {
const changed = await this.usersService.changeExperience(+param.id, data.experience)
if (changed) res.status(HttpStatus.OK).send({ message: 'Experience has been changed' })
else res.status(HttpStatus.CONFLICT).send({ message: 'Experience has not been changed, please try again' })
}
@Post(':id/change/education')
async changeEducation(@Param() param: { id: string }, @Body() data: { education: IUniversity[] }, @Res() res: Response): Promise<void> {
const changed = await this.usersService.changeEducation(+param.id, data.education)
if (changed) res.status(HttpStatus.OK).send({ message: 'Education has been changed' })
else res.status(HttpStatus.CONFLICT).send({ message: 'Education has not been changed, please try again' })
}
@Post(':id/ddd')
async a(@Param() param) {
console.log('aaaa')
await this.usersService.a(+param.id)
}
}
<file_sep>/client/src/app/app-routing.module.ts
import { NgModule } from '@angular/core'
import { RouterModule, Routes } from '@angular/router'
import { BaseLayoutComponent } from './layouts/base/base.component'
import { FeedComponent } from './views/feed/feed.component'
import { NetworkComponent } from './views/network/network.component'
import { JobsComponent } from './views/jobs/jobs.component'
import { ChatComponent } from './views/chat/chat.component'
import { NoticesComponent } from './views/notices/notices.component'
import { ProfileComponent } from './views/profile/profile.component'
import { AuthLayoutComponent } from './layouts/auth/auth.component'
import { AuthorizationComponent } from './views/auth/authorization/authorization.component'
import { RegistrationComponent } from './views/auth/registration/registration.component'
import { AuthGuard } from './guards/auth.guard'
import { EditProfileComponent } from './views/profile/edit-profile/edit-profile.component'
import { AccountDeletedComponent } from './components/account-deleted/account-deleted.component'
const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: '/feed' },
{
component: BaseLayoutComponent,
path: '',
children: [
{
path: 'feed',
component: FeedComponent,
canActivate: [AuthGuard],
},
{
path: 'network',
component: NetworkComponent,
canActivate: [AuthGuard],
},
{
path: 'jobs',
component: JobsComponent,
canActivate: [AuthGuard],
},
{
path: 'chats',
component: ChatComponent,
canActivate: [AuthGuard],
},
{
path: 'notices',
component: NoticesComponent,
canActivate: [AuthGuard],
},
{
path: 'profile',
component: ProfileComponent,
canActivate: [AuthGuard],
},
{
path: 'profile/edit',
component: EditProfileComponent,
canActivate: [AuthGuard],
},
{
path: 'profile/:id',
component: ProfileComponent,
canActivate: [AuthGuard],
},
],
},
{
path: '',
component: AuthLayoutComponent,
children: [
{ path: 'signup', component: RegistrationComponent },
{ path: 'signin', component: AuthorizationComponent },
],
},
{
path: 'account-deleted',
component: AccountDeletedComponent,
},
]
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: [AuthGuard],
})
export class AppRoutingModule {}
<file_sep>/client/src/app/pipes/name-pipe/name-pipe.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'
@Pipe({
name: 'namePipe',
})
export class NamePipe implements PipeTransform {
transform(value: string, ...args: unknown[]): string {
const [firstName, lastName] = value.split(' ')
return `${firstName[0]}. ${lastName}`
}
}
<file_sep>/client/src/app/svg-icon/svg-icon.component.ts
import {
ChangeDetectionStrategy,
Component,
Input,
Inject,
} from '@angular/core'
import { ICONS_PATH } from './icons-path'
@Component({
selector: 'svg[icon]',
template: '<svg:use [attr.href]="href"></svg:use>',
styles: [':host { fill: transparent; stroke: transparent; }'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SvgIconComponent {
@Input()
icon = ''
constructor(@Inject(ICONS_PATH) private readonly path: string) {}
get href(): string {
return `${this.path}/${this.icon}.svg#${this.icon}Icon`
}
}
<file_sep>/client/src/app/store/my-profile/my-profile.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store'
import { myProfileNode, MyProfileState } from './my-profile.reducer'
export const myProfileFeatureSelector = createFeatureSelector<MyProfileState>(
myProfileNode,
)
export const myProfileSelector = createSelector(
myProfileFeatureSelector,
state => state,
)
export const myProfileIdSelector = createSelector(
myProfileFeatureSelector,
state => state.id,
)
export const myProfileNameSelector = createSelector(
myProfileFeatureSelector,
state => ({
firstName: state.firstName,
lastName: state.lastName,
}),
)
export const myProfilePhoneSelector = createSelector(
myProfileFeatureSelector,
state => state.phone,
)
export const myProfileEmailSelector = createSelector(
myProfileFeatureSelector,
state => state.email,
)
export const myProfilePostsSelector = createSelector(
myProfileFeatureSelector,
state => state.info.posts,
)
export const myProfileCurrentViewsSelector = createSelector(
myProfileFeatureSelector,
state => state.info.views.current,
)
export const myProfilePrevViewsSelector = createSelector(
myProfileFeatureSelector,
state => state.info.views.prev,
)
export const myProfileAvatarSelector = createSelector(
myProfileFeatureSelector,
state => {
return state.info.avatar?.url ?? '../../../assets/img/avatar-man.png'
},
)
export const myProfileProfessionSelector = createSelector(
myProfileFeatureSelector,
state => state.info.profession,
)
export const myProfileRoleSelector = createSelector(
myProfileFeatureSelector,
state => state.info.role,
)
export const myProfileDescriptionSelector = createSelector(
myProfileFeatureSelector,
state => state.info.description,
)
export const myProfileAboutSelector = createSelector(
myProfileFeatureSelector,
state => state.info.about,
)
export const myProfileDOBSelector = createSelector(
myProfileFeatureSelector,
state => state.info.dateOfBirth,
)
export const myProfileLocalitySelector = createSelector(
myProfileFeatureSelector,
state => state.info.locality,
)
export const myProfileGenderSelector = createSelector(
myProfileFeatureSelector,
state => state.info.gender,
)
export const myProfileDateOfLastPasswordUpdateSelector = createSelector(
myProfileFeatureSelector,
state => state.info.dateOfLastPasswordUpdate,
)
export const myProfileSentConnectionsSelector = createSelector(
myProfileFeatureSelector,
state => state.info.sentConnections,
)
export const myProfileReceivedConnectionsSelector = createSelector(
myProfileFeatureSelector,
state => state.info.receivedConnections,
)
export const myProfileConnectionsSelector = createSelector(
myProfileFeatureSelector,
state => state.info.connections,
)
export const myProfileContactInfoSelector = createSelector(
myProfileFeatureSelector,
state => state.info.contactInfo,
)
export const myProfileProjectsSelector = createSelector(
myProfileFeatureSelector,
state => state.info.projects,
)
export const myProfileExperienceSelector = createSelector(
myProfileFeatureSelector,
state => state.info.experience,
)
export const myProfileEducationSelector = createSelector(
myProfileFeatureSelector,
state => state.info.education,
)
<file_sep>/client/src/app/interfaces/post/creator.ts
import { IBuffer } from '../buffer'
export interface ICreator {
id: number
fullName: string
avatar: string | null
profession: string
}
<file_sep>/client/src/app/components/network/invitations/invitations.component.ts
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { select, Store } from '@ngrx/store'
import { MyProfileState } from '../../../store/my-profile/my-profile.reducer'
import { ProfileState } from '../../../store/profile/profile.reducer'
import { ProfileService } from '../../../services/profile.service'
import { Observable, of, Subscription } from 'rxjs'
import {
myProfileConnectionsSelector,
myProfileReceivedConnectionsSelector,
myProfileSentConnectionsSelector,
} from '../../../store/my-profile/my-profile.selectors'
import { IUser } from '../../../interfaces/user'
import { filter, map, switchMap } from 'rxjs/operators'
import {
MyProfileAcceptConnectionAction,
MyProfileCancelConnectionAction,
MyProfileDeclineConnectionAction,
} from '../../../store/my-profile/my-profile.actions'
import { ChatService } from '../../../services/chat.service'
@Component({
selector: 'app-invitations',
templateUrl: './invitations.component.html',
styleUrls: ['./invitations.component.less'],
})
export class InvitationsComponent implements OnInit, OnDestroy {
constructor(
private store$: Store<MyProfileState | ProfileState>,
private profileService: ProfileService,
private chatService: ChatService,
) {}
private subs: Subscription[] = []
private set sub(s: Subscription) {
this.subs.push(s)
}
@Input() myProfileId: number = -1
@Input() myConnections$: Observable<
{ user: IUser; date: number }[]
> = new Observable()
currentTab: string = 'received'
receivedConnections$: Observable<
{ userId: number; message: string }[]
> = this.store$.pipe(select(myProfileReceivedConnectionsSelector))
sentConnections$: Observable<
{ user: IUser; message: string }[]
> = this.store$.pipe(
select(myProfileSentConnectionsSelector),
map(connections => {
const identifiers: number[] = []
connections.forEach(el => identifiers.push(el.userId))
return { identifiers, connections }
}),
switchMap(({ identifiers, connections }) => {
if (identifiers.length > 1)
return this.profileService
.getProfileInfo<{ users: IUser[] }>(identifiers.join(','))
.pipe(
map(res => res.users),
map(users => {
return users.map(user => ({
user,
message: (connections.find(
connection => connection.userId === user.id,
) as { userId: number; message: string })
.message,
}))
}),
)
if (identifiers.length === 1)
return this.profileService
.getProfileInfo<{ user: IUser }>(identifiers[0])
.pipe(
map(res => res.user),
map(user => {
return [
{
user,
message: (connections.find(
connection =>
connection.userId === user.id,
) as {
userId: number
message: string
}).message,
},
]
}),
)
else return of([])
}),
)
newConnections: { user: IUser; message: string }[] = []
sentConnections: { user: IUser; message: string }[] = []
recentConnections: { user: IUser; date: number }[] = []
acceptConnection(senderId: number): void {
this.store$.dispatch(
new MyProfileAcceptConnectionAction({
senderId,
userId: this.myProfileId,
date: Date.now(),
}),
)
}
declineConnection(senderId: number): void {
this.store$.dispatch(
new MyProfileDeclineConnectionAction({
senderId,
userId: this.myProfileId,
}),
)
}
cancelConnection(userId: number): void {
this.store$.dispatch(
new MyProfileCancelConnectionAction({
senderId: this.myProfileId,
userId,
}),
)
}
action(data: { type: string; id: number }): void {
if (data.type === 'accept') {
this.acceptConnection(data.id)
}
if (data.type === 'decline') {
this.declineConnection(data.id)
}
if (data.type === 'cancel') {
this.cancelConnection(data.id)
}
}
activateTab(e: MouseEvent): void {
const element = e.target as HTMLElement
const parent = element.parentNode as HTMLElement
const children = Array.from(parent.children)
children.forEach(el => el.classList.remove('active'))
element.classList.add('active')
this.currentTab = (element.textContent as string).toLowerCase()
}
ngOnInit(): void {
this.sub = this.receivedConnections$.subscribe(connections => {
if (!connections.length) {
this.newConnections = []
return
}
const usersId = connections.map(connection => connection.userId)
if (usersId.length > 1) {
this.sub = this.profileService
.getProfileInfo<{ users: IUser[] }>(usersId.join(','))
.subscribe(res => {
const users = res.users
this.newConnections = connections.map(connection => {
return {
user: users.find(
user => user.id === connection.userId,
) as IUser,
message: connection.message,
}
})
})
} else if (usersId.length === 1) {
this.sub = this.profileService
.getProfileInfo<{ user: IUser }>(usersId.join(','))
.subscribe(res => {
const user = res.user
this.newConnections = connections.map(connection => {
return {
user,
message: connection.message,
}
})
})
}
})
this.sub = this.myConnections$
.pipe(
map(connections => {
console.log('map connections', connections)
return connections.reverse()
}),
filter((val, index) => index < 4),
)
.subscribe(connections => {
this.recentConnections = connections
console.log('recent connections', connections)
})
this.sub = this.sentConnections$.subscribe(sent => {
this.sentConnections = sent
})
}
ngOnDestroy(): void {
this.subs.forEach(sub => sub.unsubscribe())
}
}
<file_sep>/server/src/app.module.ts
import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { UsersController } from './users/users.controller'
import { UsersService } from './users/users.service'
import { PostsController } from './posts/posts.controller'
import { PostsService } from './posts/posts.service'
import { ChatGateway } from './chats/chat.gateway'
import { MongooseModule } from '@nestjs/mongoose'
import { PostSchema } from './posts/post.schema'
import { UserSchema } from './users/user.shema'
import { ChatSchema } from './chats/chat.shema'
import { ChatsService } from './chats/chats.service'
import { ChatsController } from './chats/chats.controller'
@Module({
imports: [
MongooseModule.forRoot('mongodb+srv://Furamy:<EMAIL>/myFirstDatabase?retryWrites=true&w=majority'),
MongooseModule.forFeature([
{ name: 'posts', schema: PostSchema },
{ name: 'users', schema: UserSchema },
{ name: 'chats', schema: ChatSchema },
]),
],
controllers: [AppController, UsersController, PostsController, ChatsController],
providers: [AppService, PostsService, UsersService, ChatGateway, ChatsService],
})
export class AppModule {}
<file_sep>/client/src/app/interfaces/post/attached.ts
import { IAttach } from './attach'
export interface IAttached {
files?: IAttach[]
images?: IAttach[]
videos?: IAttach[]
}
<file_sep>/client/src/app/views/auth/authorization/authorization.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core'
import { AuthService } from '../../../services/auth.service'
import { FormControl, FormGroup, Validators } from '@angular/forms'
import { AuthForm } from '../../../../../../server/src/interfaces/auth/auth'
import { ActivatedRoute, Router } from '@angular/router'
import { SignInAction } from '../../../store/auth/auth.actions'
import { AuthState } from '../../../store/auth/auth.reducer'
import { Store } from '@ngrx/store'
import { MyProfileState } from '../../../store/my-profile/my-profile.reducer'
import { MyProfileGetInfoSuccessAction } from '../../../store/my-profile/my-profile.actions'
import { IUser } from '../../../interfaces/user'
import {Subject} from "rxjs";
import {takeUntil} from "rxjs/operators";
@Component({
selector: 'app-authorization',
templateUrl: './authorization.component.html',
styleUrls: ['./authorization.component.less', '../auth.styles.less'],
})
export class AuthorizationComponent implements OnInit, OnDestroy {
constructor(
private authService: AuthService,
private router: Router,
private activatedRoute: ActivatedRoute,
private store$: Store<AuthState | MyProfileState>,
) {}
unsub$ = new Subject()
message: string = ''
backendError = ''
authForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required]),
})
onSubmit(): void {
const form: AuthForm = this.authForm.value
if (this.authForm.valid) {
this.authService.signInRequest(form).subscribe(
res => {
console.log('SERVER AUTH RESPONSE', res)
this.store$.dispatch(new SignInAction())
this.store$.dispatch(
new MyProfileGetInfoSuccessAction({
profile: res.user,
}),
)
localStorage.setItem('currentUser', JSON.stringify(res))
this.router.navigate(['/feed'])
},
err => (this.backendError = err.error.error),
)
}
}
ngOnInit(): void {
// this.authService.testReq()
this.activatedRoute.queryParams.pipe(takeUntil(this.unsub$)).subscribe(params => {
if (params.message) {
this.message = params.message
}
})
console.log(this.message)
}
ngOnDestroy(): void {
this.unsub$.next()
this.unsub$.complete()
}
}
<file_sep>/client/src/app/pipes/prefix-plus-pipe/prefix-plus.pipe.spec.ts
import { PrefixPlusPipe } from './prefix-plus.pipe'
describe('PrefixPlusPipe', () => {
it('create an instance', () => {
const pipe = new PrefixPlusPipe()
expect(pipe).toBeTruthy()
})
})
<file_sep>/client/src/app/views/feed/feed.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { SvgIconModule } from '../../svg-icon/svg-icon.module'
import { FeedComponent } from './feed.component'
import { FeedMainComponent } from './feed-main/feed-main.component'
import { FeedSideComponent } from './feed-side/feed-side.component'
import { PostComponent } from '../../components/post/post.component'
import { FormsModule } from '@angular/forms'
@NgModule({
declarations: [
FeedComponent,
FeedMainComponent,
FeedSideComponent,
PostComponent,
],
imports: [CommonModule, SvgIconModule, FormsModule],
})
export class FeedModule {}
<file_sep>/server/src/posts/posts.service.ts
import { Injectable } from '@nestjs/common'
import { IComment } from '../interfaces/post/comment'
import { IPost } from '../interfaces/post/post'
import { PostDto } from '../dto/post.dto'
import { CommentDto } from '../dto/comment.dto'
import { EditableDto } from '../dto/editable.dto'
@Injectable()
export class PostsService {
posts: IPost[] = []
currentPostId: number = 0
currentCommentId: number = 0
createPost(post: PostDto) {
const POST = {
id: this.currentPostId++,
creator: post.creator,
content: post.content,
dateOfCreation: post.dateOfCreation,
attached: post.attached,
comments: [],
likes: [],
}
this.posts.unshift(POST)
return POST
}
editPost(editablePost: EditableDto): IPost | null {
const post = this.posts.find(post => post.id === editablePost.id)
if (post) {
post.content = editablePost.newContent
post.dateOfLastModify = Date.now()
return post
}
return null
}
findPost(id: number): IPost | undefined {
return this.posts.find(post => post.id === id)
}
findAllPosts(): IPost[] {
return this.posts
}
removePost(id: number): boolean {
this.posts = this.posts.filter(post => post.id !== id)
return true
}
likePost(postId: number, userId: number): boolean {
const post = this.posts.find(post => post.id === postId)
if (post) {
const isLike = post.likes.some(like => like.userId === userId)
if (!isLike) {
post.likes.push({ userId })
return true
}
}
return false
}
dontLikePost(postId: number, userId: number): boolean {
const post = this.posts.find(post => post.id === postId)
if (post) {
post.likes = post.likes.filter(like => like.userId !== userId)
return true
}
return false
}
addComment(postId: number, comment: CommentDto): IComment[] | null {
const post = this.posts.find(post => post.id === postId)
if (post) {
post.comments.push({
id: this.currentCommentId++,
likes: [],
...comment,
})
return post.comments
}
return null
}
editComment(postId: number, editableComment: EditableDto): CommentDto[] | null {
const post = this.posts.find(post => post.id === postId)
if (post) {
const comment = post.comments.find(comment => comment.id === editableComment.id)
if (comment) {
comment.content = editableComment.newContent
comment.dateOfLastModify = Date.now()
return post.comments
}
}
return null
}
removeComment(postId: number, commentId: number): boolean {
const post = this.posts.find(post => post.id === postId)
if (post) {
post.comments = post.comments.filter(comment => comment.id !== commentId)
return true
}
return false
}
likeComment(postId: number, commentId: number, userId: number): boolean {
const post = this.posts.find(post => post.id === postId)
if (post) {
const comment = post.comments.find(comment => comment.id === commentId)
if (comment) {
const isLike = comment.likes.some(like => like.userId === userId)
if (!isLike) {
comment.likes.push({ userId })
return true
}
}
}
return false
}
dontLikeComment(postId: number, commentId: number, userId: number): boolean {
const post = this.posts.find(post => post.id === postId)
if (post) {
const comment = post.comments.find(comment => comment.id === commentId)
if (comment) {
comment.likes = comment.likes.filter(like => like.userId !== userId)
return true
}
}
return false
}
}
<file_sep>/client/src/app/views/feed/feed-side/feed-side.component.ts
import { Component, OnInit } from '@angular/core'
import { select, Store } from '@ngrx/store'
import { MyProfileState } from '../../../store/my-profile/my-profile.reducer'
import { Observable } from 'rxjs'
import { myProfileSelector } from '../../../store/my-profile/my-profile.selectors'
import { map } from 'rxjs/operators'
import { IBuffer } from '../../../interfaces/buffer'
@Component({
selector: 'app-feed-side',
templateUrl: './feed-side.component.html',
styleUrls: ['./feed-side.component.less', '../feed.component.less'],
})
export class FeedSideComponent implements OnInit {
constructor(private store$: Store<MyProfileState>) {}
profile$: Observable<MyProfileState> = this.store$.pipe(
select(myProfileSelector),
)
fullName$: Observable<string> = this.profile$.pipe(
map(profile => `${profile.firstName} ${profile.lastName}`),
)
description$: Observable<string> = this.profile$.pipe(
map(profile => profile.info.description),
)
avatar$: Observable<string> = this.profile$.pipe(
map(profile => profile.info.avatar?.url ?? 'assets/img/avatar-man.png'),
)
ngOnInit(): void {}
}
<file_sep>/client/src/app/dto/comment.dto.ts
import { ICreator } from '../interfaces/post/creator'
export interface CommentDto {
creator: ICreator
content: string
dateOfLastModify?: number
dateOfCreation: number
}
<file_sep>/client/src/app/services/posts.service.ts
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs'
import { IPost } from '../interfaces/post/post'
import { environment } from '../../environments/environment'
import { PostDto } from '../dto/post.dto'
import { CommentDto } from '../dto/comment.dto'
import { IComment } from '../interfaces/post/comment'
@Injectable({
providedIn: 'root',
})
export class PostsService {
constructor(private http: HttpClient) {}
createPost(post: PostDto): Observable<IPost> {
// console.log('service request [POST]:', post)
return this.http.post<IPost>(
`${environment.server_url}/posts/create`,
post,
)
}
editPost(content: string, postId: number): void {}
removePost(postId: number): void {}
likePost(postId: number, userId: number): Observable<{ like: boolean }> {
return this.http.post<{ like: boolean }>(
`${environment.server_url}/posts/like/${postId}`,
{ id: userId },
)
}
dontLikePost(
postId: number,
userId: number,
): Observable<{ like: boolean }> {
return this.http.post<{ like: boolean }>(
`${environment.server_url}/posts/dont-like/${postId}`,
{ id: userId },
)
}
createComment(comment: CommentDto, postId: number): Observable<IComment[]> {
return this.http.post<IComment[]>(
`${environment.server_url}/posts/${postId}/comments/add`,
comment,
)
}
editComment(postId: number, commentId: number, content: string): void {}
removeComment(postId: number, commentId: number): void {}
likeComment(
postId: number,
commentId: number,
userId: number,
): Observable<{ like: boolean }> {
return this.http.post<{ like: boolean }>(
`${environment.server_url}/${postId}/comments/like/${commentId}`,
{ id: userId },
)
}
dontLikeComment(
postId: number,
commentId: number,
userId: number,
): Observable<{ like: boolean }> {
return this.http.post<{ like: boolean }>(
`${environment.server_url}/${postId}/comments/dont-like/${commentId}`,
{ id: userId },
)
}
getPosts(id: string | number): Observable<{ posts: IPost[] }> {
return this.http.get<{ posts: IPost[] }>(
`${environment.server_url}/posts/${id}`,
)
}
}
<file_sep>/client/src/app/interfaces/auth/authError.ts
export interface IAuthError {
target: string
message: string
}
<file_sep>/client/src/app/components/components.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { RouterModule } from '@angular/router'
import { UsersListMdlComponent } from './network/users-list/users-list-mdl/users-list-mdl.component'
import { UsersListNwkComponent } from './network/users-list/users-list-nwk/users-list-nwk.component'
import { SelectComponent } from './select/select.component'
import { SvgIconModule } from '../svg-icon/svg-icon.module'
import { AccountDeletedComponent } from './account-deleted/account-deleted.component'
@NgModule({
declarations: [
UsersListNwkComponent,
UsersListMdlComponent,
SelectComponent,
AccountDeletedComponent,
],
imports: [CommonModule, RouterModule, SvgIconModule],
exports: [UsersListMdlComponent, UsersListNwkComponent, SelectComponent],
})
export class ComponentsModule {}
<file_sep>/client/src/app/interfaces/user.ts
import { IFile } from './file'
import { IContact } from './contact'
import { IProject } from './project'
import { IExp } from './exp'
import { IUniversity } from './university'
export interface IUser {
id: number
firstName: string
lastName: string
email: string
phone: string
password: string
info: {
isOnline: boolean
role: string
description: string
about: string
views: {
current: number
prev: number
}
connections: { userId: number; date: number; chatId: number }[]
sentConnections: { userId: number; message: string; chatId: number }[]
receivedConnections: {
userId: number
message: string
chatId: number
}[]
posts: {
postId: number
}[]
avatar: IFile | null
profileHeaderBg: IFile | null
dateOfBirth: number
gender: string
profession: string
locality: {
country: string
city: string
}
contactInfo: IContact[]
projects: IProject[]
experience: IExp[]
education: IUniversity[]
dateOfLastPasswordUpdate: number
}
}
<file_sep>/server/src/interfaces/chat/message.ts
import { IAttach } from '../post/attach'
export interface IMessage {
id?: number
senderId: number
content: string
time: number
status: string
attached?: IAttach[]
}
<file_sep>/client/src/app/views/profile/edit-profile/edit-components/edit-login-and-security/edit-login-and-security.component.ts
import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core'
import { FormControl, FormGroup, Validators } from '@angular/forms'
// @ts-ignore
import { HystModal } from '../../../../../plugins/hystModal_.js'
import { ProfileService } from '../../../../../services/profile.service'
import { Router } from '@angular/router'
import {takeUntil} from 'rxjs/operators'
import {Subject} from 'rxjs'
@Component({
selector: 'app-edit-login-and-security',
templateUrl: './edit-login-and-security.component.html',
styleUrls: ['./edit-login-and-security.component.less'],
})
export class EditLoginAndSecurityComponent implements OnInit, OnDestroy {
constructor(
private profileService: ProfileService,
private router: Router,
) {}
unsub$ = new Subject()
@Input() profileId: number = -1
@Input() email: string = ''
@Input() phone: string = ''
@Input() dateOfLastPasswordUpdate: number | null = null
@Input() phoneConfirmed: boolean = false
@Input() emailConfirmed: boolean = false
@Output() action = new EventEmitter<{ type: string; data: any }>()
isChangePhone: boolean = false
isChangeEmail: boolean = false
isChangePassword: boolean = false
changePhoneError: string = ''
changeEmailError: string = ''
changePasswordError: string = ''
changePasswordForm = new FormGroup({
currentPassword: new FormControl('', [
Validators.required,
Validators.minLength(6),
]),
newPassword: new FormControl('', [
Validators.required,
Validators.minLength(6),
]),
newPasswordRepeat: new FormControl('', [
Validators.required,
Validators.minLength(6),
]),
})
changePhoneMode(): void {
this.isChangePhone = true
this.isChangeEmail = false
this.isChangePassword = false
}
changeEmailMode(): void {
this.isChangePhone = false
this.isChangeEmail = true
this.isChangePassword = false
}
changePasswordMode(): void {
this.isChangePhone = false
this.isChangeEmail = false
this.isChangePassword = true
}
closeChangeBlock(): void {
this.isChangePhone = false
this.isChangeEmail = false
this.isChangePassword = false
}
deleteAccount(password: string): void {
this.profileService.deleteAccount(this.profileId, password).subscribe(
res => {
localStorage.removeItem('currentUser')
this.router.navigate(['/account-deleted'])
},
err => {},
)
}
changeEmail(email: string): void {
const match = email.match(/.+@.+\..+/i)
console.log(match)
if (!match) {
this.changeEmailError = 'Invalid email'
return
}
if (this.email === email) {
this.changeEmailError = 'Email addresses match'
return
}
this.profileService.changeEmail(this.profileId, email).pipe(takeUntil(this.unsub$)).subscribe(
res => {
console.log(res.message)
},
err => {
console.error(err.message)
},
)
}
changePhone(phone: string): void {
const match = phone.match(/^[- +()0-9]{5,}/)
if (!match) {
this.changePhoneError = 'Invalid phone'
return
}
if (this.phone === phone) {
this.changePhoneError = 'Phones match'
return
}
this.profileService.changePhone(this.profileId, phone).subscribe(
res => {
console.log(res.message)
},
err => {
console.error(err.message)
},
)
}
changePassword(): void {
const form = this.changePasswordForm.value
if (form.newPassword !== form.newPasswordRepeat) {
this.changePasswordError = 'Password mismatch'
return
}
if (form.newPassword === form.currentPassword) {
this.changePasswordError = 'Old and new passwords are the same'
return
}
if (form.newPassword.length < 6) {
this.changePasswordError = 'New password is too short'
return
}
this.profileService
.changePassword(
this.profileId,
form.newPassword,
form.currentPassword,
)
.subscribe(
res => {
console.log(res.message)
},
err => {
console.error(err.message)
},
)
}
ngOnInit(): void {
const deleteAccountModal = new HystModal({
linkAttributeName: 'data-hystmodal',
})
}
ngOnDestroy(): void {
this.unsub$.next()
this.unsub$.complete()
}
}
<file_sep>/server/src/interfaces/post/comment.ts
import { ICreator } from './creator'
export interface IComment {
id: number
creator: ICreator
content: string
dateOfLastModify?: number
dateOfCreation: number
likes: {
userId: number
}[]
}
<file_sep>/client/src/app/views/profile/profile-side/profile-side.component.ts
import { Component, Input, OnInit } from '@angular/core'
import { ProfileState } from '../../../store/profile/profile.reducer'
import { initialProfileState } from '../profile.component'
@Component({
selector: 'app-profile-side',
templateUrl: './profile-side.component.html',
styleUrls: ['./profile-side.component.less', '../profile.component.less'],
})
export class ProfileSideComponent implements OnInit {
constructor() {}
// @Input() isMyProfile: boolean = false
ngOnInit(): void {}
}
<file_sep>/client/src/app/store/my-profile/find-users/find-users.effects.ts
import { Injectable } from '@angular/core'
import { Actions, Effect, ofType } from '@ngrx/effects'
import { EMPTY, Observable } from 'rxjs'
import {
FIND_USERS_BY_FULL_NAME_ACTION_TYPE,
FindUsersActions,
FindUsersByFullNameAction,
} from './find-users.actions'
import { catchError, map, switchMap } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
import { environment } from '../../../../environments/environment'
@Injectable()
export class FindUsersEffects {
constructor(private actions$: Actions, private http: HttpClient) {}
@Effect()
findUsersByFullName$(): Observable<FindUsersActions> {
return this.actions$.pipe(
ofType(FIND_USERS_BY_FULL_NAME_ACTION_TYPE),
switchMap((action: FindUsersByFullNameAction) => {
return this.http
.get(
`${environment.server_url}/users/find/all?fullName=${action.payload.fullName}`,
)
.pipe(
map(users => {
return
}),
catchError(error => {
console.warn(error)
return EMPTY
}),
)
}),
)
}
}
<file_sep>/client/src/app/views/feed/feed-main/feed-main.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core'
import { FileService } from 'src/app/services/file.service'
import { select, Store } from '@ngrx/store'
import { PostState } from '../../../store/posts/post.reducer'
import {
PostCreateAction,
PostGetAction,
SortingPostsAction,
} from '../../../store/posts/post.actions'
import {Observable, Subject} from 'rxjs'
import {map, takeUntil} from 'rxjs/operators'
import { postsSelector } from '../../../store/posts/post.selectors'
import { IPost } from '../../../interfaces/post/post'
import { ICreator } from '../../../interfaces/post/creator'
import { IAttached } from '../../../interfaces/post/attached'
import { MyProfileState } from '../../../store/my-profile/my-profile.reducer'
import {
myProfileIdSelector,
myProfileSelector,
} from '../../../store/my-profile/my-profile.selectors'
@Component({
selector: 'app-feed-main',
templateUrl: './feed-main.component.html',
styleUrls: ['./feed-main.component.less', '../feed.component.less'],
})
export class FeedMainComponent implements OnInit, OnDestroy {
constructor(
private fileService: FileService,
private store$: Store<PostState | MyProfileState>,
) {}
unsub$ = new Subject()
posts$: Observable<IPost[]> = this.store$.pipe(select(postsSelector))
isPosts$: Observable<boolean> = this.posts$.pipe(map(posts => !!posts[0]))
creator$: Observable<ICreator> = this.store$.pipe(
select(myProfileSelector),
map(profile => {
console.log('PROFILE => ', profile)
return {
id: profile.id,
fullName: `${profile.firstName} ${profile.lastName}`,
profession: profile.info.profession,
avatar:
profile.info.avatar?.url ??
'../../../../assets/img/avatar-man.png',
}
}),
)
feedPostSortingType: string | null = 'newest first'
attached: IAttached = {}
creator: ICreator = {
id: 0,
fullName: '',
profession: '',
avatar: '',
}
textareaContent: string = ''
createPost(): void {
console.log(this.textareaContent)
this.store$.dispatch(
new PostCreateAction({
creator: this.creator,
content: this.textareaContent,
dateOfCreation: Date.now(),
attached: this.attached,
}),
)
this.textareaContent = ''
}
textareaResize(e: Event): void {
const elem = e.target as HTMLElement
const offset = elem.offsetHeight - elem.clientHeight
elem.style.height = 'auto'
elem.style.height = elem.scrollHeight + offset + 'px'
}
changeSortingType(e: MouseEvent, sortList: HTMLElement): void {
const elem = e.target as HTMLElement
this.feedPostSortingType = elem.textContent
console.log(elem.textContent)
this.store$.dispatch(
new SortingPostsAction({ sortType: elem.textContent as string }),
)
sortList.classList.remove('active')
}
fileUpload(fileInput: HTMLInputElement, type: string): void {
this.fileService.fileUpload(fileInput, type, this.attached)
}
ngOnInit(): void {
this.creator$.pipe(takeUntil(this.unsub$)).subscribe(creator => (this.creator = creator))
this.posts$.pipe(takeUntil(this.unsub$)).subscribe(posts => console.log('posts =>', posts))
this.store$.dispatch(new PostGetAction({ id: 'all' }))
}
ngOnDestroy(): void {
this.unsub$.next()
this.unsub$.complete()
}
}
<file_sep>/server/src/interfaces/contact.ts
export interface IContact {
contactWay: string
data: string
}
<file_sep>/client/src/app/views/feed/feed-side/feed-side.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { FeedSideComponent } from './feed-side.component'
describe('FeedSideComponent', () => {
let component: FeedSideComponent
let fixture: ComponentFixture<FeedSideComponent>
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FeedSideComponent],
}).compileComponents()
})
beforeEach(() => {
fixture = TestBed.createComponent(FeedSideComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
<file_sep>/client/src/app/store/my-profile/find-users/find-users.reducer.ts
import { IUser } from '../../../interfaces/user'
import {
FIND_USERS_BY_FULL_NAME_SUCCESS_ACTION_TYPE,
FindUsersActions,
} from './find-users.actions'
export const findUsersNode = 'find users'
export interface FindUsersState {
users: IUser[]
}
const initialState = {
users: [],
}
export const findUsersReducer = (
state: FindUsersState,
action: FindUsersActions,
) => {
switch (action.type) {
case FIND_USERS_BY_FULL_NAME_SUCCESS_ACTION_TYPE:
return {
...state,
users: action.payload.users,
}
default:
return state
}
}
<file_sep>/client/src/app/interfaces/chat/messages.ts
import { IMessage } from './message'
export interface IMessages {
day: string
dayMessages: IMessage[]
}
<file_sep>/client/src/app/views/auth/auth.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { AuthorizationComponent } from './authorization/authorization.component'
import { RegistrationComponent } from './registration/registration.component'
import { HttpClientModule } from '@angular/common/http'
import { ReactiveFormsModule } from '@angular/forms'
import { SvgIconModule } from '../../svg-icon/svg-icon.module'
import { RouterModule } from '@angular/router'
@NgModule({
declarations: [AuthorizationComponent, RegistrationComponent],
imports: [
CommonModule,
HttpClientModule,
ReactiveFormsModule,
SvgIconModule,
RouterModule,
],
})
export class AuthModule {}
<file_sep>/client/src/app/store/my-profile/my-profile.reducer.ts
import {
ACCEPT_CONNECTION_SUCCESS_ACTION_TYPE,
CANCEL_CONNECTION_SUCCESS_ACTION_TYPE,
CHANGE_ABOUT_SUCCESS_ACTION_TYPE,
CHANGE_AVATAR_SUCCESS_ACTION_TYPE,
CHANGE_CONTACT_INFO_SUCCESS_ACTION_TYPE,
CHANGE_EDUCATION_SUCCESS_ACTION_TYPE,
CHANGE_EXPERIENCE_SUCCESS_ACTION_TYPE,
CHANGE_LOCALITY_SUCCESS_ACTION_TYPE,
CHANGE_PROFESSION_SUCCESS_ACTION_TYPE,
CHANGE_PROJECTS_SUCCESS_ACTION_TYPE,
CHANGE_ROLE_SUCCESS_ACTION_TYPE,
DECLINE_CONNECTION_SUCCESS_ACTION_TYPE,
DELETE_AVATAR_SUCCESS_ACTION_TYPE,
GET_MY_PROFILE_INFO_SUCCESS_ACTION_TYPE,
MyProfileActions,
REMOVE_CONNECTION_SUCCESS_ACTION_TYPE,
} from './my-profile.actions'
import { IFile } from '../../interfaces/file'
import { IContact } from '../../interfaces/contact'
import { IProject } from '../../interfaces/project'
import { IExp } from '../../interfaces/exp'
import { IUniversity } from '../../interfaces/university'
export const myProfileNode = 'my profile'
export interface MyProfileState {
id: number
firstName: string
lastName: string
email: string
phone: string
password: string
info: {
isOnline: boolean
role: string
description: string
about: string
views: {
current: number
prev: number
}
connections: { userId: number; date: number }[]
sentConnections: { userId: number; message: string }[]
receivedConnections: { userId: number; message: string }[]
posts: {
postId: number
}[]
avatar: IFile | null
profileHeaderBg: IFile | null
dateOfBirth: number
gender: string
profession: string
locality: {
country: string
city: string
}
contactInfo: IContact[]
projects: IProject[]
experience: IExp[]
education: IUniversity[]
dateOfLastPasswordUpdate: number
}
}
const initialState: MyProfileState = {
id: -1,
firstName: '',
lastName: '',
email: '',
phone: '',
password: '',
info: {
isOnline: false,
role: '',
description: '',
about: '',
views: {
current: 0,
prev: 0,
},
connections: [],
sentConnections: [],
receivedConnections: [],
posts: [],
avatar: null,
profileHeaderBg: null,
dateOfBirth: 0,
gender: '',
profession: '',
locality: {
country: '',
city: '',
},
contactInfo: [],
projects: [],
experience: [],
education: [],
dateOfLastPasswordUpdate: 0,
},
}
export const myProfileReducer = (
state: MyProfileState = initialState,
action: MyProfileActions,
) => {
switch (action.type) {
case GET_MY_PROFILE_INFO_SUCCESS_ACTION_TYPE:
return action.payload.profile
case ACCEPT_CONNECTION_SUCCESS_ACTION_TYPE:
console.log(action.payload)
return {
...state,
info: {
...state.info,
connections: [
...state.info.connections,
{
userId: action.payload.senderId,
date: action.payload.date,
},
],
receivedConnections: [],
},
}
case DECLINE_CONNECTION_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
receivedConnections: state.info.receivedConnections.filter(
user => user.userId !== action.payload.senderId,
),
},
}
case CANCEL_CONNECTION_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
sentConnections: state.info.sentConnections.filter(
user => user.userId !== action.payload.userId,
),
},
}
case REMOVE_CONNECTION_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
connections: state.info.connections.filter(
user => user.userId !== action.payload.userId,
),
},
}
case CHANGE_AVATAR_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
avatar: {
...state.info.avatar,
url: action.payload.url,
},
},
}
case DELETE_AVATAR_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
avatar: null,
},
}
case CHANGE_ROLE_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
role: action.payload.role,
},
}
case CHANGE_ABOUT_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
about: action.payload.about,
},
}
case CHANGE_PROFESSION_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
profession: action.payload.profession,
},
}
case CHANGE_LOCALITY_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
locality: action.payload.locality,
},
}
case CHANGE_CONTACT_INFO_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
contactInfo: action.payload.contactInfo,
},
}
case CHANGE_PROJECTS_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
projects: action.payload.projects,
},
}
case CHANGE_EXPERIENCE_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
experience: action.payload.experience,
},
}
case CHANGE_EDUCATION_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
education: action.payload.education,
},
}
default:
return state
}
}
<file_sep>/server/src/users/users.service.ts
import { Injectable } from '@nestjs/common'
import { CreateUserDto } from '../dto/create-user.dto'
import { AuthDto } from '../dto/auth.dto'
import { IUser } from '../interfaces/user'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { UserDocument } from './user.shema'
import { ChatDocument } from '../chats/chat.shema'
import { IPersonalInfo } from '../interfaces/edit-profile/personalInfo'
import { Express } from 'express'
import { IUniversity } from '../interfaces/university'
import { IExp } from '../interfaces/exp'
import { IProject } from '../interfaces/project'
import { IContact } from '../interfaces/contact'
import { ILocality } from '../interfaces/locality'
const URL = 'http://localhost:3000'
@Injectable()
export class UsersService {
nextId: number = 0
constructor(
@InjectModel('users') private userModel: Model<UserDocument>,
@InjectModel('chats') private chatModel: Model<ChatDocument>,
) {
this.userModel
.find()
.exec()
.then(res => (this.nextId = res.length))
}
async createUser(user: CreateUserDto | IUser): Promise<CreateUserDto | null> {
if ((await this.userModel.findOne({ email: user.email }).exec()) || (await this.userModel.findOne({ phone: user.phone }).exec()))
return null
const USER = new this.userModel({
id: this.nextId++,
...user,
info: {
views: {
current: 0,
prev: 0,
},
posts: [],
connections: [],
sentConnections: [],
receivedConnections: [],
avatar: null,
profileHeaderBg: null,
dateOfBirth: 0,
profession: '',
locality: {
country: '',
city: '',
},
chats: [],
},
})
return USER.save()
}
async authUser(authData: AuthDto): Promise<UserDocument | null> {
console.log(555)
const user = await this.userModel.findOne({ email: authData.email, password: <PASSWORD> })
if (user) {
user.info.isOnline = true
return user
}
return null
}
async findUserById(id: number): Promise<UserDocument | null> {
console.log('ID =>>', id)
const user = await this.userModel.findOne({ id: id })
if (user) return user
return null
}
async findUsersById(id: string): Promise<UserDocument[] | null> {
let match = id.match(/(\d+,)+\d+$/)
if (match) {
const identifiers = match[0].split(',')
const users = await this.userModel.find()
return users.filter(user => identifiers.includes(`${user.id}`))
}
return null
}
async validateUserBySomething(id: number, fieldName: string, value: string): Promise<UserDocument | null> {
const user = await this.userModel.findOne({ id, [fieldName]: value })
if (user) {
console.log(user)
return user
}
return null
}
async removeUser(id: number, password: string): Promise<boolean | null> {
const user = await this.userModel.findOne({ id })
if (user.password === password) {
const deleted = await this.userModel.deleteOne({ id })
const users = await this.userModel.find().exec()
const identifiers = []
users.forEach(user => {
identifiers.push(user.id)
})
for (let i = 0; i < identifiers.length; i++) {
let user = await this.userModel.findOne({ id: identifiers[i] })
user.info.connections = user.info.connections.filter(user => user.userId !== id)
await user.save()
}
if (deleted) return true
return null
}
return false
}
async sendConnection(senderId: number, userId: number, message: string): Promise<{ sent: boolean }> {
const user = await this.userModel.findOne({ id: userId })
const sender = await this.userModel.findOne({ id: senderId })
if (user && sender) {
if (user.info.sentConnections.find(user => user.userId === sender.id)) {
return
}
user.info.receivedConnections.push({
userId: senderId,
message: message,
})
sender.info.sentConnections.push({
userId: userId,
message: message,
})
// await this.userModel.updateOne({id: userId}, {
// $push: {
// 'info.receivedConnections': {
// userId: senderId,
// message: message
// }
// }
// })
// await this.userModel.updateOne({id: senderId}, {
// $push: {
// 'info.sentConnections': {
// userId: userId,
// message: message
// }
// }
// })
await user.save()
await sender.save()
return { sent: true }
}
return { sent: false }
}
async acceptConnection(senderId: number, userId: number, date: number): Promise<{ user: UserDocument; chatId: number } | null> {
const user = await this.userModel.findOne({ id: userId })
const sender = await this.userModel.findOne({ id: senderId })
let chats = await this.chatModel.find()
const chat = chats.find(chat => {
return chat.users.find(u => u.userId === userId) && chat.users.find(u => u.userId === senderId)
})
if (chat) {
await this.chatModel.deleteOne({ chatId: chat.chatId })
}
const chatId = chat?.chatId ?? (await this.chatModel.find().exec()).length
const newChat = new this.chatModel({
chatId,
users: [{ userId: senderId }, { userId: userId }],
messages: [],
attached: [],
})
await newChat.save()
if (user && sender) {
if (!user.info.connections.find(user => user.userId === senderId))
if (user.info.receivedConnections.find(user => user.userId === senderId)) {
// проверка на то что sender'a нет в connections
// если sender есть во входящих connections
user.info.receivedConnections = user.info.receivedConnections.filter(user => user.userId !== senderId)
user.info.connections.push({ userId: senderId, date: date, chatId })
sender.info.sentConnections = user.info.sentConnections.filter(user => user.userId !== userId)
sender.info.connections.push({ userId: userId, date: date, chatId })
// await this.userModel.updateOne(
// { id: userId },
// {
// $pullAll: { 'info.receivedConnections': [{ userId: senderId }] },
// $push: { 'info.connections': { userId: senderId, date: date } }
// }
// )
//
// await this.userModel.updateOne(
// {id: senderId},
// {
// $pullAll: { 'info.receivedConnections': [{ userId: userId }] },
// $push: { 'info.connections': { userId: userId, date: date } }
// }
// )
await user.save()
await sender.save()
return { user, chatId } // возвращаем нового user'a
}
}
return null // иначе возвращаем null
}
async declineConnection(senderId: number, userId: number): Promise<UserDocument | null> {
const user = await this.userModel.findOne({ id: userId })
const sender = await this.userModel.findOne({ id: senderId })
if (user && sender) {
if (user.info.receivedConnections.find(user => user.userId === senderId)) {
// если sender есть во входящих connections
user.info.receivedConnections = user.info.receivedConnections.filter(user => user.userId !== senderId) // тогда удаляем его от туда
sender.info.sentConnections = user.info.sentConnections.filter(user => user.userId !== userId) // тоже самое делаем и с sender'ом
await user.save()
await sender.save()
return user
}
}
return null
}
async removeConnection(senderId: number, userId: number): Promise<UserDocument | null> {
const user = await this.userModel.findOne({ id: userId })
const sender = await this.userModel.findOne({ id: senderId })
let chats = await this.chatModel.find()
const chat = chats.find(chat => {
return chat.users.find(u => u.userId === userId) && chat.users.find(u => u.userId === senderId)
})
if (chat) {
await this.chatModel.deleteOne({ chatId: chat.chatId })
}
if (user && sender) {
if (
sender.info.connections.find(user => user.userId === userId) &&
user.info.connections.find(user => user.userId === senderId)
) {
sender.info.connections = sender.info.connections.filter(user => user.userId !== userId)
user.info.connections = user.info.connections.filter(user => user.userId !== senderId)
await user.save()
await sender.save()
}
return user
}
return null
}
async findAllUsers(query?: { fullName?: string }): Promise<any> {
let users = await this.userModel.find().exec()
if (query?.fullName) {
const [firstName, lastName] = query.fullName.split(' ').map(el => {
if (el) return el.toLowerCase()
return ''
})
users = users.filter(user => {
if (firstName && lastName)
return (
user.firstName.toLowerCase().startsWith(firstName) && // === firstName
user.lastName.toLowerCase().startsWith(lastName)
)
if (firstName) return user.firstName.toLowerCase().startsWith(firstName)
return false
})
}
return users
}
async clearConnections(id: number): Promise<any> {
const user = await this.userModel.findOne({ id })
user.info.connections = []
await user.save()
}
async editPersonalInfo(id: number, info: IPersonalInfo): Promise<string> {
const user = await this.userModel.findOne({ id })
if (!user) return 'not found'
user.firstName = info.firstName
user.lastName = info.lastName
user.info.dateOfBirth = info.dateOfBirth
user.info.gender = info.gender
await user.save()
return 'changed'
}
async uploadAvatar(file: Express.Multer.File, userId: number): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
console.log(file)
user.info.avatar = {
fileName: file.originalname,
encoding: file.encoding,
mimetype: file.mimetype,
url: `${URL}/uploads/${file.filename}`,
size: file.size,
}
await user.save()
return true
}
async deleteAvatar(userId: number): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.info.avatar = null
await user.save()
return true
}
async changeEmail(userId: number, email: string): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.email = email
await user.save()
return true
}
async changePhone(userId: number, phone: string): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.phone = phone
await user.save()
return true
}
async changePassword(userId: number, newPassword: string, oldPassword: string): Promise<boolean | null> {
const user = await this.userModel.findOne({ id: userId, password: oldPassword })
if (!user) return null
if (newPassword === oldPassword) return false
user.password = <PASSWORD>
await user.save()
return true
}
async changeRole(userId: number, role: string): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.info.role = role
await user.save()
return true
}
// async changeCompany(userId: number, company: string): Promise<boolean> {}
async changeAbout(userId: number, about: string): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.info.about = about
await user.save()
return true
}
async changeProfession(userId: number, profession: string): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.info.profession = profession
await user.save()
return true
}
async changeLocality(userId: number, locality: ILocality): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.info.locality = locality
await user.save()
return true
}
async changeContactInfo(userId: number, contactInfo: IContact[]): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.info.contactInfo = contactInfo
await user.save()
return true
}
async changeProjects(userId: number, projects: IProject[]): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.info.projects = projects
await user.save()
return true
}
async changeExperience(userId: number, experience: IExp[]): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.info.experience = experience
await user.save()
return true
}
async changeEducation(userId: number, education: IUniversity[]): Promise<boolean> {
const user = await this.userModel.findOne({ id: userId })
if (!user) return false
user.info.education = education
await user.save()
return true
}
async a(userId: number) {
const user = await this.userModel.findOne({ id: userId })
user.info.projects = []
user.info.contactInfo = []
await user.save()
}
}
<file_sep>/client/src/app/store/my-profile/my-profile.effects.ts
import { Injectable } from '@angular/core'
import { Actions, Effect, ofType } from '@ngrx/effects'
import { ProfileService } from '../../services/profile.service'
import {
ACCEPT_CONNECTION_ACTION_TYPE,
CANCEL_CONNECTION_ACTION_TYPE,
DECLINE_CONNECTION_ACTION_TYPE,
GET_MY_PROFILE_INFO_ACTION_TYPE,
REMOVE_CONNECTION_ACTION_TYPE,
JOIN_TO_CHAT,
MyProfileAcceptConnectionAction,
MyProfileAcceptConnectionSuccessAction,
MyProfileActions,
MyProfileCancelConnectionAction,
MyProfileCancelConnectionSuccessAction,
MyProfileDeclineConnectionAction,
MyProfileDeclineConnectionSuccessAction,
MyProfileGetInfoAction,
MyProfileGetInfoSuccessAction,
MyProfileRemoveConnectionAction,
MyProfileRemoveConnectionSuccessAction,
MyProfileChangeRoleAction,
CHANGE_ROLE_ACTION_TYPE,
CHANGE_ABOUT_ACTION_TYPE,
MyProfileChangeAboutAction,
CHANGE_PROFESSION_ACTION_TYPE,
MyProfileChangeProfessionAction,
MyProfileChangeRoleSuccessAction,
MyProfileChangeAboutSuccessAction,
MyProfileChangeProfessionSuccessAction,
MyProfileChangeLocalityAction,
MyProfileChangeLocalitySuccessAction,
CHANGE_LOCALITY_ACTION_TYPE,
MyProfileChangeContactInfoAction,
CHANGE_CONTACT_INFO_ACTION_TYPE,
MyProfileChangeContactInfoSuccessAction,
CHANGE_PROJECTS_ACTION_TYPE,
MyProfileChangeProjectsAction,
MyProfileChangeProjectsSuccessAction,
CHANGE_EXPERIENCE_ACTION_TYPE,
MyProfileChangeExperienceAction,
MyProfileChangeEducationSuccessAction,
CHANGE_EDUCATION_ACTION_TYPE,
MyProfileChangeEducationAction,
MyProfileChangeExperienceSuccessAction,
} from './my-profile.actions'
import { catchError, map, mergeMap, switchMap } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
import { environment } from '../../../environments/environment'
import { IUser } from '../../interfaces/user'
import { EMPTY, Observable } from 'rxjs'
import { ChatService } from '../../services/chat.service'
@Injectable()
export class MyProfileEffects {
constructor(
private actions$: Actions,
private profileService: ProfileService,
private chatService: ChatService,
private http: HttpClient,
) {}
@Effect()
getProfileInfo$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(GET_MY_PROFILE_INFO_ACTION_TYPE),
switchMap((action: MyProfileGetInfoAction) => {
if (Number.isInteger(action.payload.id)) {
return this.profileService
.getProfileInfo<{ user: IUser }>(action.payload.id)
.pipe(
map(res => {
console.log(res.user)
return new MyProfileGetInfoSuccessAction({
profile: res.user,
})
}),
catchError(() => EMPTY),
)
}
return EMPTY
}),
)
}
@Effect()
acceptConnection$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(ACCEPT_CONNECTION_ACTION_TYPE),
mergeMap((action: MyProfileAcceptConnectionAction) => {
const payload = action.payload
return this.profileService
.acceptConnection(
payload.senderId,
payload.userId,
payload.date,
)
.pipe(
map(res => {
this.chatService.joinToChat(res.chatId)
return new MyProfileAcceptConnectionSuccessAction({
senderId: payload.senderId,
date: payload.date,
})
}),
catchError(err => {
console.log(
'MyProfileAcceptConnectionAction error: ',
err,
)
return EMPTY
}),
)
}),
)
}
@Effect()
declineConnection$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(DECLINE_CONNECTION_ACTION_TYPE),
mergeMap((action: MyProfileDeclineConnectionAction) => {
const payload = action.payload
return this.profileService
.declineConnection(payload.senderId, payload.userId)
.pipe(
map(
() =>
new MyProfileDeclineConnectionSuccessAction({
senderId: payload.senderId,
}),
),
catchError(err => {
console.log(
'MyProfileDeclineConnectionAction error:',
err,
)
return EMPTY
}),
)
}),
)
}
@Effect()
cancelConnection$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(CANCEL_CONNECTION_ACTION_TYPE),
mergeMap((action: MyProfileCancelConnectionAction) => {
const payload = action.payload
return this.profileService
.cancelConnection(payload.senderId, payload.userId)
.pipe(
map(
() =>
new MyProfileCancelConnectionSuccessAction({
userId: payload.userId,
}),
),
catchError(err => EMPTY),
)
}),
)
}
@Effect()
removeConnection$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(REMOVE_CONNECTION_ACTION_TYPE),
mergeMap((action: MyProfileRemoveConnectionAction) => {
const payload = action.payload
return this.profileService
.removeConnection(payload.senderId, payload.userId)
.pipe(
map(
() =>
new MyProfileRemoveConnectionSuccessAction({
userId: payload.userId,
}),
),
catchError(err => {
console.log(
'ProfileRemoveConnectionAction error:',
err,
)
return EMPTY
}),
)
}),
)
}
@Effect()
changeRole$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(CHANGE_ROLE_ACTION_TYPE),
mergeMap((action: MyProfileChangeRoleAction) => {
const { role, id } = action.payload
return this.profileService.changeRole(role, id).pipe(
map(changed => {
console.log(changed)
return new MyProfileChangeRoleSuccessAction({ role })
}),
catchError(err => {
console.log(err)
return EMPTY
}),
)
}),
)
}
// changeCompany$(): Observable<MyProfileActions> {}
@Effect()
changeAbout$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(CHANGE_ABOUT_ACTION_TYPE),
mergeMap((action: MyProfileChangeAboutAction) => {
const { about, id } = action.payload
return this.profileService.changeAbout(about, id).pipe(
map(changed => {
console.log(changed)
return new MyProfileChangeAboutSuccessAction({ about })
}),
catchError(err => {
console.log(err)
return EMPTY
}),
)
}),
)
}
@Effect()
changeProfession$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(CHANGE_PROFESSION_ACTION_TYPE),
mergeMap((action: MyProfileChangeProfessionAction) => {
const { profession, id } = action.payload
return this.profileService
.changeProfession(profession, id)
.pipe(
map(changed => {
console.log(changed)
return new MyProfileChangeProfessionSuccessAction({
profession,
})
}),
catchError(err => {
console.log(err)
return EMPTY
}),
)
}),
)
}
@Effect()
changeLocality$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(CHANGE_LOCALITY_ACTION_TYPE),
mergeMap((action: MyProfileChangeLocalityAction) => {
const { locality, id } = action.payload
return this.profileService.changeLocality(locality, id).pipe(
map(changed => {
console.log(changed)
return new MyProfileChangeLocalitySuccessAction({
locality,
})
}),
catchError(err => {
console.log(err)
return EMPTY
}),
)
}),
)
}
@Effect()
changeContactInfo$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(CHANGE_CONTACT_INFO_ACTION_TYPE),
mergeMap((action: MyProfileChangeContactInfoAction) => {
const { contactInfo, id } = action.payload
return this.profileService
.changeContactInfo(contactInfo, id)
.pipe(
map(changed => {
console.log(changed)
return new MyProfileChangeContactInfoSuccessAction({
contactInfo,
})
}),
catchError(err => {
console.log(err)
return EMPTY
}),
)
}),
)
}
@Effect()
changeProjects$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(CHANGE_PROJECTS_ACTION_TYPE),
mergeMap((action: MyProfileChangeProjectsAction) => {
const { projects, id } = action.payload
return this.profileService.changeProjects(projects, id).pipe(
map(changed => {
console.log(changed)
return new MyProfileChangeProjectsSuccessAction({
projects,
})
}),
catchError(err => {
console.log(err)
return EMPTY
}),
)
}),
)
}
@Effect()
changeExperience$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(CHANGE_EXPERIENCE_ACTION_TYPE),
mergeMap((action: MyProfileChangeExperienceAction) => {
const { experience, id } = action.payload
return this.profileService
.changeExperience(experience, id)
.pipe(
map(changed => {
console.log(changed)
return new MyProfileChangeExperienceSuccessAction({
experience,
})
}),
catchError(err => {
console.log(err)
return EMPTY
}),
)
}),
)
}
@Effect()
changeEducation$(): Observable<MyProfileActions> {
return this.actions$.pipe(
ofType(CHANGE_EDUCATION_ACTION_TYPE),
mergeMap((action: MyProfileChangeEducationAction) => {
const { education, id } = action.payload
return this.profileService.changeEducation(education, id).pipe(
map(changed => {
console.log(changed)
return new MyProfileChangeEducationSuccessAction({
education,
})
}),
catchError(err => {
console.log(err)
return EMPTY
}),
)
}),
)
}
@Effect()
findOtherUsers$(): Observable<MyProfileActions> {
return this.actions$.pipe(ofType())
}
}
<file_sep>/client/src/app/views/profile/edit-profile/edit-profile.component.ts
import { Component, OnInit } from '@angular/core'
@Component({
selector: 'app-edit-profile',
templateUrl: './edit-profile.component.html',
styleUrls: ['./edit-profile.component.less'],
})
export class EditProfileComponent implements OnInit {
constructor() {}
currentTab: string = 'Personal data' // 'Additional information'
changeTab(tab: string): void {
this.currentTab = tab.trim()
}
ngOnInit(): void {}
}
<file_sep>/client/src/app/store/my-profile/edit-profile/edit-profile.reducer.ts
import {
EditProfileActions,
SET_ERROR_AD_ALERT_ACTION_TYPE,
SET_ERROR_LS_ALERT_ACTION_TYPE,
SET_SUCCESS_AD_ALERT_ACTION_TYPE,
SET_SUCCESS_LS_ALERT_ACTION_TYPE,
} from './edit-profile.actions'
interface ADAlerts {
role: string
// company: string,
about: string
profession: string
locality: string
contactInfo: string
projects: string
experience: string
education: string
}
interface LSAlerts {
email: string
password: string
phone: string
}
interface EditProfile {
AD: {
successAlerts: ADAlerts
errorAlerts: ADAlerts
}
LS: {
successAlerts: LSAlerts
errorAlerts: LSAlerts
}
}
const initialState: EditProfile = {
AD: {
successAlerts: {
role: '',
// company: '',
about: '',
profession: '',
locality: '',
contactInfo: '',
projects: '',
experience: '',
education: '',
},
errorAlerts: {
role: '',
// company: ',
about: '',
profession: '',
locality: '',
contactInfo: '',
projects: '',
experience: '',
education: '',
},
},
LS: {
successAlerts: {
email: '',
password: '',
phone: '',
},
errorAlerts: {
email: '',
password: '',
phone: '',
},
},
}
export const EditProfileReducer: /*EditProfile | void*/ any = (
state: EditProfile = initialState,
action: EditProfileActions,
) => {
switch (action.type) {
case SET_SUCCESS_AD_ALERT_ACTION_TYPE:
return
case SET_SUCCESS_LS_ALERT_ACTION_TYPE:
return
case SET_ERROR_AD_ALERT_ACTION_TYPE:
return
case SET_ERROR_LS_ALERT_ACTION_TYPE:
return
}
}
<file_sep>/client/src/app/store/auth/auth.actions.ts
import { Action } from '@ngrx/store'
/* ACTION TYPES */
export const SIGN_IN_ACTION_TYPE: string = '[AUTH] sign in'
export const SIGN_IN_SUCCESS_ACTION_TYPE: string = '[AUTH] sign in success'
export const SIGN_IN_FAILED_ACTION_TYPE: string = '[AUTH] sign in failed'
export const LOG_OUT_ACTION_TYPE: string = '[AUTH] log out'
export const LOG_OUT_SUCCESS_ACTION_TYPE: string = '[AUTH] log out success'
export const LOG_OUT_FAILED_ACTION_TYPE: string = '[AUTH] log out failed'
/* ACTIONS */
export class SignInAction implements Action {
readonly type = SIGN_IN_ACTION_TYPE
}
export class LogOutAction implements Action {
readonly type = LOG_OUT_ACTION_TYPE
}
export type AuthActions = SignInAction | LogOutAction
<file_sep>/server/src/chats/chats.service.ts
import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { ChatDocument } from './chat.shema'
@Injectable()
export class ChatsService {
constructor(@InjectModel('chats') private chatModel: Model<ChatDocument>) {}
async getChats() {
return this.chatModel.find().exec()
}
async getChat(id: number) {
return this.chatModel.find({ chatId: id }).exec()
}
async deleteOne(id: number) {
await this.chatModel.deleteOne({ chatId: id }).exec()
}
async deleteAll() {
await this.chatModel.deleteMany().exec()
}
}
<file_sep>/server/src/chats/chat.shema.ts
import { Prop, raw, Schema, SchemaFactory } from '@nestjs/mongoose'
import { Document } from 'mongoose'
import { IAttach } from '../interfaces/post/attach'
export type ChatDocument = Chat & Document
@Schema()
export class Chat {
@Prop()
chatId: number
@Prop({ type: [{ userId: Number }] })
users: { userId: number }[]
@Prop(
raw([
{
day: String,
dayMessages: [
{
id: Number,
senderId: Number,
content: String,
time: Number,
status: String,
attached: [
{
name: String,
type: String,
size: Number,
result: String,
},
],
},
],
},
]),
)
messages: Record<string, any>
@Prop(
raw([
{
name: String,
type: String,
size: Number,
result: String,
},
]),
)
attached: Record<string, any>
}
// @ts-ignore
export const ChatSchema = SchemaFactory.createForClass(Chat)
// @ts-ignore
<file_sep>/client/src/app/store/profile/profile.effects.ts
import { Injectable } from '@angular/core'
import { Actions, Effect, ofType } from '@ngrx/effects'
import { ProfileService } from '../../services/profile.service'
import {
ACCEPT_CONNECTION_ACTION_TYPE,
DECLINE_CONNECTION_ACTION_TYPE,
GET_PROFILE_INFO_ACTION_TYPE,
ProfileAcceptConnectionAction,
ProfileAcceptConnectionSuccessAction,
ProfileActions,
ProfileDeclineConnectionAction,
ProfileDeclineConnectionSuccessAction,
ProfileGetInfoAction,
ProfileGetInfoSuccessAction,
ProfileRemoveConnectionAction,
ProfileRemoveConnectionSuccessAction,
ProfileSendConnectionAction,
ProfileSendConnectionSuccessAction,
REMOVE_CONNECTION_ACTION_TYPE,
SEND_CONNECTION_ACTION_TYPE,
} from './profile.actions'
import { catchError, map, switchMap } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
import { environment } from '../../../environments/environment'
import { IUser } from '../../interfaces/user'
import { EMPTY, Observable, of } from 'rxjs'
import { Router } from '@angular/router'
@Injectable()
export class ProfileEffects {
constructor(
private actions$: Actions,
private profileService: ProfileService,
private http: HttpClient,
private router: Router,
) {}
@Effect()
getProfileInfo$(): Observable<ProfileActions> {
return this.actions$.pipe(
ofType(GET_PROFILE_INFO_ACTION_TYPE),
switchMap((action: ProfileGetInfoAction) => {
if (Number.isInteger(action.payload.id)) {
return this.profileService
.getProfileInfo<{ user: IUser }>(action.payload.id)
.pipe(
map(res => {
return new ProfileGetInfoSuccessAction({
profile: res.user,
})
}),
catchError(() => {
this.router.navigate(['/profile/not-found'])
return EMPTY
}),
)
}
return EMPTY
}),
)
}
@Effect()
sendConnection$(): Observable<ProfileActions> {
return this.actions$.pipe(
ofType(SEND_CONNECTION_ACTION_TYPE),
switchMap((action: ProfileSendConnectionAction) => {
const payload = action.payload
return this.profileService
.sendConnection(
payload.senderId,
payload.userId,
payload.message,
)
.pipe(
map(() => {
return new ProfileSendConnectionSuccessAction({
senderId: payload.senderId,
})
}),
catchError(err => {
console.log('send connection effect error: ', err)
return EMPTY
}),
)
}),
)
}
@Effect()
acceptConnection$(): Observable<ProfileActions> {
return this.actions$.pipe(
ofType(ACCEPT_CONNECTION_ACTION_TYPE),
switchMap((action: ProfileAcceptConnectionAction) => {
const payload = action.payload
return this.profileService
.acceptConnection(
payload.senderId,
payload.userId,
payload.date,
)
.pipe(
map(
() =>
new ProfileAcceptConnectionSuccessAction({
userId: payload.userId,
date: payload.date,
}),
),
catchError(err => {
console.log(
'ProfileAcceptConnectionAction error: ',
err,
)
return EMPTY
}),
)
}),
)
}
@Effect()
declineConnection$(): Observable<ProfileActions> {
return this.actions$.pipe(
ofType(DECLINE_CONNECTION_ACTION_TYPE),
switchMap((action: ProfileDeclineConnectionAction) => {
const payload = action.payload
return this.profileService
.declineConnection(payload.senderId, payload.userId)
.pipe(
map(
() =>
new ProfileDeclineConnectionSuccessAction({
senderId: payload.senderId,
}),
),
catchError(err => {
console.log(
'ProfileDeclineConnectionAction error:',
err,
)
return EMPTY
}),
)
}),
)
}
@Effect()
removeConnection$(): Observable<ProfileActions> {
return this.actions$.pipe(
ofType(REMOVE_CONNECTION_ACTION_TYPE),
switchMap((action: ProfileRemoveConnectionAction) => {
const payload = action.payload
return this.profileService
.removeConnection(payload.senderId, payload.userId)
.pipe(
map(
() =>
new ProfileRemoveConnectionSuccessAction({
senderId: payload.senderId,
}),
),
catchError(err => {
console.log(
'ProfileRemoveConnectionAction error:',
err,
)
return EMPTY
}),
)
}),
)
}
}
<file_sep>/server/src/posts/posts.controller.ts
import { Body, Controller, Delete, Get, HttpStatus, Param, Post, Res } from '@nestjs/common'
import { PostDto } from '../dto/post.dto'
import { CommentDto } from '../dto/comment.dto'
import { EditableDto } from '../dto/editable.dto'
import { PostsService } from './posts.service'
import { Response } from 'express'
import { UsersService } from '../users/users.service'
type ID = string | number
@Controller('posts')
export class PostsController {
constructor(private postsService: PostsService, private usersService: UsersService) {}
@Post('create')
async createPost(@Body() post: PostDto, @Res() res: Response): Promise<void> {
console.log('POST:', post)
const POST = await this.postsService.createPost(post)
res.status(HttpStatus.CREATED).send(POST)
}
@Post('edit')
async editPost(@Body() editablePost: EditableDto, @Res() res: Response): Promise<void> {
const editedPost = await this.postsService.editPost(editablePost)
res.status(HttpStatus.OK).send(editedPost)
}
@Get(':id')
async findPost(@Param() param: { id: number | string }, @Res() res: Response): Promise<void> {
if (param.id === 'all') {
const posts = await this.postsService.findAllPosts()
res.status(HttpStatus.OK).send({ posts })
} else {
const post = await this.postsService.findPost(+param.id)
if (post) res.status(HttpStatus.OK).send(post)
else
res.status(HttpStatus.CONFLICT).send({
error: `Post with id ${param.id} not found`,
})
}
}
@Delete('remove/:id')
async removePost(@Param() param: { id: ID }, @Res() res: Response): Promise<void> {
const removed = await this.postsService.removePost(+param.id)
if (removed) res.status(HttpStatus.OK).send({ removed })
else res.status(HttpStatus.OK).send({ removed: false })
}
@Post('like/:id')
async likePost(@Param() param: { id: ID }, @Body() user: { id: number }, @Res() res: Response): Promise<void> {
const like = await this.postsService.likePost(+param.id, user.id)
if (like) res.status(HttpStatus.OK).send({ like: true })
else
res.status(HttpStatus.CONFLICT).send({
error: 'the post has already been liked',
})
}
@Post('dont-like/:id')
async dontLikePost(@Param() param: { id: ID }, @Body() user: { id: number }, @Res() res: Response): Promise<void> {
const dontLike = await this.postsService.dontLikePost(+param.id, user.id)
if (dontLike) res.status(HttpStatus.OK).send({ like: false })
else
res.status(HttpStatus.CONFLICT).send({
error: `post with id ${param.id} not found`,
})
}
@Post(':id/comments/add')
async addComment(@Param() param: { id: ID }, @Body() comment: CommentDto, @Res() res: Response): Promise<void> {
const comments = await this.postsService.addComment(+param.id, comment)
if (comments) res.status(HttpStatus.CREATED).send({ comments })
else
res.status(HttpStatus.CONFLICT).send({
error: `Post with id ${param.id} not found`,
})
}
@Post(':id/comments/edit')
async editComment(@Param() param: { id: ID }, @Body() editableComment: EditableDto, @Res() res: Response): Promise<void> {
const comments = await this.postsService.editComment(+param.id, editableComment)
if (comments) res.status(HttpStatus.OK).send({ comments })
else
res.status(HttpStatus.CONFLICT).send({
error: `Post with id ${param.id} not found`,
})
}
@Delete(':postId/comments/remove/:commentId')
async removeComment(@Param() param: { postId: ID; commentId: ID }, @Res() res: Response): Promise<void> {
const removed = await this.postsService.removeComment(+param.postId, +param.commentId)
if (removed) res.status(HttpStatus.OK).send({ removed })
else res.status(HttpStatus.OK).send({ removed: false })
}
@Post(':postId/comments/like/:commentId')
async likeComment(@Param() param: { postId: ID; commentId: ID }, @Body() user: { id: number }, @Res() res: Response): Promise<void> {
const like = await this.postsService.likeComment(+param.postId, +param.commentId, user.id)
if (like) res.status(HttpStatus.OK).send({ like: true })
else
res.status(HttpStatus.CONFLICT).send({
error: `Post with id ${param.postId} or comment with id ${param.commentId} not found`,
})
}
@Post(':postId/comments/dont-like/:commentId')
async dontLikeComment(
@Param() param: { postId: ID; commentId: ID },
@Body() user: { id: number },
@Res() res: Response,
): Promise<void> {
const dontLike = await this.postsService.dontLikeComment(+param.postId, +param.commentId, user.id)
if (dontLike) res.status(HttpStatus.OK).send({ like: false })
else
res.status(HttpStatus.CONFLICT).send({
error: `Post with id ${param.postId} or comment with id ${param.commentId} not found`,
})
}
}
<file_sep>/client/src/app/views/profile/edit-profile/edit-components/edit-additional-info/edit-additional-info.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { EditAdditionalInfoComponent } from './edit-additional-info.component'
describe('EditAdditionalInfoComponent', () => {
let component: EditAdditionalInfoComponent
let fixture: ComponentFixture<EditAdditionalInfoComponent>
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [EditAdditionalInfoComponent],
}).compileComponents()
})
beforeEach(() => {
fixture = TestBed.createComponent(EditAdditionalInfoComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
<file_sep>/client/src/app/store/my-profile/find-users/find-users.actions.ts
import { Action } from '@ngrx/store'
import { IUser } from '../../../interfaces/user'
export const FIND_USERS_BY_FULL_NAME_ACTION_TYPE =
'[FIND USERS] find users by full name'
export const FIND_USERS_BY_FULL_NAME_SUCCESS_ACTION_TYPE =
'[FIND USERS] users by full name is found'
export class FindUsersByFullNameAction implements Action {
readonly type = FIND_USERS_BY_FULL_NAME_ACTION_TYPE
constructor(
public payload: {
fullName: string
},
) {}
}
export class FindUsersByFullNameSuccessAction implements Action {
readonly type = FIND_USERS_BY_FULL_NAME_SUCCESS_ACTION_TYPE
constructor(
public payload: {
users: IUser[]
},
) {}
}
export type FindUsersActions =
| FindUsersByFullNameAction
| FindUsersByFullNameSuccessAction
<file_sep>/server/src/posts/post.schema.ts
import { Prop, raw, Schema, SchemaFactory } from '@nestjs/mongoose'
export type PostDocument = Post & Document
const Attach = { type: { name: String, type: String, size: Number, result: String }, required: false }
const Comment = {
id: Number,
creator: {
id: Number,
fullName: String,
profession: String,
avatar: String,
},
content: String,
dateOfLastModify: { type: Number, required: false },
dateOfCreation: Number,
likes: [{ userId: Number }],
}
@Schema()
export class Post {
@Prop()
id: number
@Prop(
raw({
id: Number,
fullName: String,
profession: String,
avatar: String,
}),
)
creator: Record<string, any>
@Prop()
content: string
@Prop({ required: false })
dateOfLastModify: number
@Prop()
dateOfCreation: number
@Prop()
likes: {
userId: number
}[]
@Prop(
raw({
files: [Attach],
images: [Attach],
videos: [Attach],
}),
)
attached: Record<string, any>
@Prop(raw(Comment))
comments: [Record<string, any>]
}
export const PostSchema = SchemaFactory.createForClass(Post)
<file_sep>/client/src/app/layouts/base/base.component.ts
import { Component, OnInit } from '@angular/core'
import { AuthState } from '../../store/auth/auth.reducer'
import { select, Store } from '@ngrx/store'
import { Observable } from 'rxjs'
import { authStatusSelector } from '../../store/auth/auth.selectors'
import { Router } from '@angular/router'
import { PostGetAction } from '../../store/posts/post.actions'
@Component({
selector: 'app-base-layout',
templateUrl: './base.component.html',
styleUrls: ['./base.component.less'],
})
export class BaseLayoutComponent implements OnInit {
authStatus$: Observable<boolean> = this.store$.pipe(
select(authStatusSelector),
)
constructor(private store$: Store<AuthState>, private router: Router) {}
ngOnInit(): void {
this.authStatus$.subscribe(res => {
if (!res) {
this.router.navigate(['/signin'])
}
})
}
}
<file_sep>/client/src/app/pipes/avatar.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'
import { IBuffer } from '../interfaces/buffer'
@Pipe({
name: 'avatar',
})
export class AvatarPipe implements PipeTransform {
transform(value: IBuffer | string | null, ...args: unknown[]): any {
if (typeof value === 'string') return value
if (value === null) return 'assets/img/avatar-man.png'
const arrayBufferView = new Uint8Array(value.data)
// const blob = new Blob([ arrayBufferView ], { type: 'image/jpeg' })
// console.log(blob)
// const urlCreator = window.URL || window.webkitURL
//
// return urlCreator.createObjectURL(blob)
}
}
<file_sep>/client/src/app/app.component.ts
import { Component, OnInit } from '@angular/core'
import { Store } from '@ngrx/store'
import { AuthState } from './store/auth/auth.reducer'
import { SignInAction } from './store/auth/auth.actions'
import { MyProfileState } from './store/my-profile/my-profile.reducer'
import { MyProfileGetInfoAction } from './store/my-profile/my-profile.actions'
import { WebSocketService } from './services/web-socket.service'
import { ChatService } from './services/chat.service'
import { of } from 'rxjs'
import { mergeMap, switchMap } from 'rxjs/operators'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less'],
})
export class AppComponent implements OnInit {
title = 'client'
constructor(
private store$: Store<AuthState | MyProfileState>,
private webSocketService: WebSocketService,
private chatService: ChatService,
) {}
ngOnInit(): void {
if (localStorage.getItem('currentUser')) {
this.store$.dispatch(new SignInAction())
this.store$.dispatch(
new MyProfileGetInfoAction({
id: JSON.parse(
localStorage.getItem('currentUser') as string,
).user.id,
}),
)
}
this.webSocketService
.listen('some event')
.subscribe(data => console.log(data))
this.chatService.connect()
}
}
<file_sep>/client/src/app/views/profile/edit-profile/edit-components/edit-additional-info/edit-additional-info.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
import { IProject } from '../../../../../interfaces/project'
import { IContact } from '../../../../../interfaces/contact'
import { IFile } from '../../../../../interfaces/file'
import { IExp } from '../../../../../interfaces/exp'
import { IUniversity } from '../../../../../interfaces/university'
import { FormControl, FormGroup, Validators } from '@angular/forms'
@Component({
selector: 'app-edit-additional-info',
templateUrl: './edit-additional-info.component.html',
styleUrls: ['./edit-additional-info.component.less'],
})
export class EditAdditionalInfoComponent implements OnInit {
@Input() role: string = ''
@Input() about: string = ''
@Input() profession: string = ''
@Input() locality: { country: string; city: string } = {
country: '',
city: '',
}
@Input() contactInfo: IContact[] = []
@Input() projects: IProject[] = []
@Input() experience: IExp[] = []
@Input() education: IUniversity[] = []
@Output() onChange = new EventEmitter<{ type: string; data: any }>()
/*
* Заполнение форм данными полученными из @Input() locality не работает, наверное
* форма создается раньше, чем данные приходят из родительского компонента.
* Поэтому заполнение формы текущими значениями идет в хуке ngOnInit.
*/
localityForm = new FormGroup({
country: new FormControl(this.locality.country, [Validators.required]),
city: new FormControl(this.locality.city, [Validators.required]),
})
roleError: string = ''
aboutError: string = ''
professionError: string = ''
localityError: string = ''
contactInfoError: string = ''
projectsError: string = ''
jobError: string = ''
educationError: string = ''
roleSuccessAlert: string = ''
aboutSuccessAlert: string = ''
professionSuccessAlert: string = ''
localitySuccessAlert: string = ''
contactInfoSuccessAlert: string = ''
projectsSuccessAlert: string = ''
jobSuccessAlert: string = ''
educationSuccessAlert: string = ''
constructor() {}
addContactWay(): void {
this.contactInfo.push({
contactWay: '',
data: '',
})
}
removeContactWay(contact: IContact): void {
this.contactInfo = this.contactInfo.filter(c => c !== contact)
}
addProject(): void {
console.log(this.projects)
this.projects.push({
name: '',
role: '',
date: '',
about: '',
poster: null,
})
}
removeProject(project: IProject): void {
this.projects = this.projects.filter(p => p !== project)
}
addJob(): void {
this.experience.push({
companyName: '',
profession: '',
start: '',
end: '',
logo: null,
})
}
removeJob(job: IExp): void {
this.experience = this.experience.filter(j => j !== job)
}
addUniversity(): void {
this.education.push({
name: '',
facultyAndDegree: '',
comment: '',
start: '',
end: '',
logo: null,
})
}
removeUniversity(university: IUniversity): void {
this.education = this.education.filter(u => u !== university)
}
uploadPosterHandler(e: Event, project: IProject): void {
const target = e.target as HTMLInputElement
const file = target.files?.item(0) as File
this.uploadPoster(file, project)
}
uploadJobLogoHandler(e: Event, job: IExp): void {
const target = e.target as HTMLInputElement
const file = target.files?.item(0) as File
this.uploadJobLogo(file, job)
}
uploadUniversityLogoHandler(e: Event, university: IUniversity): void {
const target = e.target as HTMLInputElement
const file = target.files?.item(0) as File
this.uploadUniversityLogo(file, university)
}
uploadPoster(file: File, project: IProject): void {
this.uploadFile(file, (e: ProgressEvent) => {
console.log(e)
const fr = e.target as FileReader
if (project.poster) project.poster.url = fr.result as string
else {
project.poster = {
encoding: '',
fileName: '',
mimetype: '',
size: 0,
url: fr.result as string,
file,
}
}
})
}
uploadJobLogo(file: File, job: IExp): void {
this.uploadFile(file, (e: ProgressEvent) => {
const fr = e.target as FileReader
if (job.logo) job.logo.url = fr.result as string
else {
job.logo = {
encoding: '',
fileName: '',
mimetype: '',
size: 0,
url: fr.result as string,
file,
}
}
})
}
uploadUniversityLogo(file: File, university: IUniversity): void {
this.uploadFile(file, (e: ProgressEvent) => {
const fr = e.target as FileReader
if (university.logo) university.logo.url = fr.result as string
else {
university.logo = {
encoding: '',
fileName: '',
mimetype: '',
size: 0,
url: fr.result as string,
file,
}
}
})
}
uploadFile(file: File, cb: (ev: ProgressEvent) => void): void {
const fr = new FileReader()
fr.onload = cb
fr.readAsDataURL(file)
}
changeRole(): void {
this.onChange.emit({ type: 'role', data: this.role })
}
changeAbout(): void {
this.onChange.emit({ type: 'about', data: this.about })
}
changeProfession(): void {
this.onChange.emit({ type: 'profession', data: this.profession })
}
changeLocality(): void {
this.onChange.emit({ type: 'locality', data: this.localityForm.value })
}
changeContactInfo(): void {
if (!this.contactInfo[0]) {
this.contactInfoError = 'Enter anything'
return
}
for (const contactWay of this.contactInfo) {
if (this.isEmpty(contactWay)) {
this.contactInfoError = 'All fields must be filled'
return
}
}
this.onChange.emit({ type: 'contact-info', data: this.contactInfo })
}
changeProjects(): void {
if (!this.projects[0]) {
this.projectsError = 'Enter anything'
return
}
for (const project of this.projects) {
if (this.isEmpty(project)) {
this.projectsError = 'All fields must be filled'
return
}
}
this.onChange.emit({ type: 'projects', data: this.projects })
this.projectsError = ''
}
changeExperience(): void {
if (!this.experience[0]) {
this.jobError = 'Enter anything'
return
}
for (const job of this.experience) {
console.log(job)
if (this.isEmpty(job)) {
this.jobError = 'All fields must be filled'
return
}
if (!this.dateValidation(job.start, job.end)) {
this.jobError =
'The date of dismissal cannot be earlier than the date of employment'
return
}
}
this.onChange.emit({ type: 'experience', data: this.experience })
this.jobError = ''
}
changeEducation(): void {
if (!this.education[0]) {
this.educationError = 'Enter anything'
return
}
for (const university of this.education) {
if (this.isEmpty(university)) {
this.educationError = 'All fields must be filled'
return
}
if (!this.dateValidation(university.start, university.end)) {
this.educationError =
'The graduation date of the university cannot be earlier than the admission date'
return
}
}
this.onChange.emit({ type: 'education', data: this.education })
this.educationError = ''
}
isEmpty(entity: any): boolean {
entity = Object.entries(entity)
for (const [_, val] of entity) {
if (val === '') return true
}
return false
}
dateValidation(start: string, end: string): boolean {
const [startYear, startMonth, startDay] = start.split('-')
const [endYear, endMonth, endDay] = end.split('-')
if (
endYear < startYear ||
(endYear === startYear && endMonth < startMonth) ||
(endYear === startYear &&
endMonth === startMonth &&
endDay < startDay)
)
return false
return true
}
ngOnInit(): void {
const { country, city } = this.localityForm.controls
country.setValue(this.locality.country)
city.setValue(this.locality.city)
}
}
<file_sep>/client/src/app/components/post/post.component.ts
import { Component, Input, OnInit } from '@angular/core'
import { FeedMainComponent } from '../../views/feed/feed-main/feed-main.component'
import { select, Store } from '@ngrx/store'
import { PostState } from '../../store/posts/post.reducer'
import { MyProfileState } from '../../store/my-profile/my-profile.reducer'
import {
CommentCreateAction,
PostCommentsCloseAction,
PostCommentsOpenAction,
PostDontLikeAction,
PostLikeAction,
} from '../../store/posts/post.actions'
import { myProfileSelector } from '../../store/my-profile/my-profile.selectors'
import { map } from 'rxjs/operators'
import { PostsService } from '../../services/posts.service'
import { ILike } from '../../interfaces/post/like'
import { IPost } from '../../interfaces/post/post'
import { ICreator } from '../../interfaces/post/creator'
import { Observable, of } from 'rxjs'
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.less'],
})
export class PostComponent implements OnInit {
constructor(
private feedMainComponent: FeedMainComponent,
private store$: Store<PostState | MyProfileState>,
private postsService: PostsService,
) {}
@Input() postInfo: IPost = {
attached: {},
content: '',
creator: {
id: 0,
fullName: '',
profession: '',
avatar: '',
},
dateOfCreation: 0,
id: 0,
likes: [],
comments: [],
commentsOpen: false,
}
content: string = ''
profile: ICreator = {
id: 0,
fullName: '',
profession: '',
avatar: null,
}
likes: ILike[] = this.postInfo.likes
liked: boolean = false
createComment(textarea: HTMLTextAreaElement): void {
this.store$.dispatch(
new CommentCreateAction({
postId: this.postInfo.id,
commentInfo: {
creator: this.profile,
content: textarea.value.replace(/\n/g, '<br>'),
dateOfCreation: Date.now(),
},
}),
)
}
likePost(like: HTMLElement): void {
if (!this.liked) {
like.classList.add('waiting')
this.store$.dispatch(
new PostLikeAction({
postId: this.postInfo.id,
userId: this.profile.id,
}),
)
// like.classList.remove('waiting')
} else {
like.classList.add('waiting')
this.store$.dispatch(
new PostDontLikeAction({
postId: this.postInfo.id,
userId: this.profile.id,
}),
)
}
}
openCloseComments(): void {
if (!this.postInfo.commentsOpen)
this.store$.dispatch(
new PostCommentsOpenAction({ postId: this.postInfo.id }),
)
if (this.postInfo.commentsOpen)
this.store$.dispatch(
new PostCommentsCloseAction({ postId: this.postInfo.id }),
)
}
likeComment(): void {}
textareaResize(e: Event): void {
this.feedMainComponent.textareaResize(e)
}
ngOnInit(): void {
console.log(this.postInfo)
this.content = this.postInfo.content.replace(/\n/g, '<br>')
this.likes = this.postInfo.likes
this.store$
.pipe(
select(myProfileSelector),
map(profile => {
return {
id: profile.id,
fullName: `${profile.firstName} ${profile.lastName}`,
profession: profile.info.profession,
avatar:
profile.info.avatar?.url ??
'../../../../assets/img/avatar-man.png',
}
}),
)
.subscribe(creator => {
this.profile = creator
this.liked = this.likes.some(
like => like.userId === this.profile.id,
)
})
console.log('likes', this.likes)
console.log('liked', this.liked)
}
}
<file_sep>/client/src/app/views/notices/notices.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { NoticesComponent } from './notices.component'
@NgModule({
declarations: [NoticesComponent],
imports: [CommonModule],
})
export class NoticesModule {}
<file_sep>/client/src/app/components/header/header.component.ts
import { Component, OnInit } from '@angular/core'
import { ProfileService } from '../../services/profile.service'
import { IRoute } from '../../../../../server/src/interfaces/route'
import { Observable, of } from 'rxjs'
import { MyProfileState } from '../../store/my-profile/my-profile.reducer'
import { select, Store } from '@ngrx/store'
import { map } from 'rxjs/operators'
import {
myProfileAvatarSelector,
myProfileCurrentViewsSelector,
myProfileNameSelector,
myProfilePrevViewsSelector,
} from '../../store/my-profile/my-profile.selectors'
import { IBuffer } from '../../interfaces/buffer'
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.less'],
})
export class HeaderComponent implements OnInit {
constructor(
private profileService: ProfileService,
private store$: Store<MyProfileState>,
) {}
prevViews$: Observable<number> = this.store$.pipe(
select(myProfilePrevViewsSelector),
)
currentViews$: Observable<number> = this.store$.pipe(
select(myProfileCurrentViewsSelector),
)
fullName$: Observable<string> = this.store$.pipe(
select(myProfileNameSelector),
map(name => `${name.firstName[0]}. ${name.lastName}`),
)
avatar$: Observable<string> = this.store$.pipe(
select(myProfileAvatarSelector),
map(avatar => {
return avatar
}),
)
routes: IRoute[] = [
{ path: '/feed', icon: 'feed', name: 'feed' },
{ path: '/network', icon: 'network', name: 'network' },
{ path: '/jobs', icon: 'jobs', name: 'jobs' },
{ path: '/chats', icon: 'chats', name: 'chats' },
{ path: '/notices', icon: 'notices', name: 'notices' },
]
location: Location = location
viewsProgress(): number {
let prev: number
let current: number
this.currentViews$.subscribe(res => {
current = res
})
this.prevViews$.subscribe(res => {
prev = res
})
// @ts-ignore
return current - prev
}
trendingIcon(): string {
if (this.viewsProgress() > 0) return 'trendingUp'
if (this.viewsProgress() < 0) return 'trendingDown'
return 'trendingFlat'
}
ngOnInit(): void {}
}
<file_sep>/client/src/app/services/web-socket.service.ts
import { Injectable } from '@angular/core'
import * as io from 'socket.io-client'
import { Observable } from 'rxjs'
import { environment } from '../../environments/environment'
@Injectable({
providedIn: 'root',
})
export class WebSocketService {
private socket: SocketIOClient.Socket
constructor() {
this.socket = io(environment.server_url, {
transports: ['websocket', 'polling'],
})
}
listen<T>(eventName: string): Observable<T> {
return new Observable(subscriber => {
this.socket.on(eventName, (data: T) => {
subscriber.next(data)
})
})
}
emit<T>(eventName: string, data: T): void {
this.socket.emit(eventName, data)
}
}
<file_sep>/server/src/interfaces/post/attach.ts
export interface IAttach {
name: string
type: string
size: number
result: string | number[] | null
}
<file_sep>/server/src/chats/chat.gateway.ts
import { OnGatewayConnection, OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketServer, WsResponse } from '@nestjs/websockets'
import { Server, Socket } from 'socket.io'
import { IMessage } from '../interfaces/chat/message'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { ChatDocument } from './chat.shema'
@WebSocketGateway()
export class ChatGateway {
constructor(@InjectModel('chats') private chatModel: Model<ChatDocument>) {}
@WebSocketServer() wss: Server
@SubscribeMessage('sendConnection')
sendConnection(socket: Socket, data: any): void {
console.log('[Send Connection]', '\ndata:', data)
socket.join(data.chatId)
}
@SubscribeMessage('joinPrivateChat')
joinPrivateChat(socket: Socket, data: any): void {
socket.join(data.chatId)
socket.to(data.chatId).emit('joinSuccess', { message: 'Success' })
console.log('success join')
console.log(socket.adapter.rooms)
}
@SubscribeMessage('sendMessage')
async receiveMessage(socket: Socket, data: { message: IMessage; chatId: number | string }): Promise<void> {
console.log(data)
const chat = await this.chatModel.findOne({ chatId: +data.chatId })
const date = new Date().toLocaleDateString()
const dayMessages = chat.messages.find(m => m.day === date)
data.message.status = 'sent'
if (!dayMessages) {
chat.messages.push({
day: date,
dayMessages: [data.message],
})
}
if (dayMessages) {
dayMessages.dayMessages.push(data.message)
}
await chat.save()
socket.to(data.chatId.toString()).emit('receiveMessage', { messages: chat.messages, chatId: data.chatId })
socket.emit('receiveMessage', { messages: chat.messages, chatId: data.chatId })
}
@SubscribeMessage('readMessages')
async messagesRead(socket: Socket, data: { chatId: number | string; profileId: number | string }): Promise<void> {
const chat = await this.chatModel.findOne({ chatId: +data.chatId })
if (!chat) return
chat.messages.forEach(m => {
m.dayMessages.forEach(message => {
if (message.status !== 'read' && message.senderId !== data.profileId) message.status = 'read'
})
})
chat.save()
socket.to(data.chatId.toString()).emit('messagesRead', { chat })
socket.emit('messagesRead', { chat })
}
}
<file_sep>/client/src/app/views/profile/profile-main/profile-main.component.ts
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { ProfileState } from '../../../store/profile/profile.reducer'
import { initialProfileState } from '../profile.component'
import { Observable, Subject } from 'rxjs'
import { select, Store } from '@ngrx/store'
import {
profileAvatarSelector,
profileConnectionsSelector, profileContactInfoSelector,
profileDescriptionSelector,
profileHeaderBgSelector,
profileLocalitySelector,
profileNameSelector,
profileProfessionSelector,
profileSelector,
profileSentConnectionsSelector,
} from '../../../store/profile/profile.selectors'
import { IUser } from '../../../interfaces/user'
import { map, startWith, switchMap, takeUntil } from 'rxjs/operators'
import { MyProfileState } from '../../../store/my-profile/my-profile.reducer'
import {
myProfileReceivedConnectionsSelector,
myProfileSelector,
} from '../../../store/my-profile/my-profile.selectors'
// @ts-ignore
import { HystModal } from '../../../plugins/hystModal_.js'
import {
ProfileAcceptConnectionAction,
ProfileDeclineConnectionAction,
ProfileRemoveConnectionAction,
ProfileSendConnectionAction,
} from '../../../store/profile/profile.actions'
import { ProfileService } from '../../../services/profile.service'
import {IContact} from "../../../interfaces/contact";
@Component({
selector: 'app-profile-main',
templateUrl: './profile-main.component.html',
styleUrls: ['./profile-main.component.less', '../profile.component.less'],
})
export class ProfileMainComponent implements OnInit, OnDestroy {
constructor(
private store$: Store<ProfileState | MyProfileState>,
private profileService: ProfileService,
) {}
unsub$ = new Subject()
@Input() isMyProfile: boolean = false
currentTab = 'profile'
headerBg$: Observable<string> = this.store$.pipe(
select(profileHeaderBgSelector),
)
avatar$: Observable<string> = this.store$.pipe(
select(profileAvatarSelector),
)
fullName$: Observable<string> = this.store$.pipe(
select(profileNameSelector),
)
description$: Observable<string> = this.store$.pipe(
select(profileDescriptionSelector),
)
profession$: Observable<string> = this.store$.pipe(
select(profileProfessionSelector),
)
connections$: Observable<
{ user: IUser; date: number }[]
> = this.store$.pipe(
select(profileConnectionsSelector),
switchMap(connections => {
return this.profileService.getConnectionsById$(connections)
}),
startWith([]),
)
connectionsLength$: Observable<number> = this.connections$.pipe(
map(connections => connections.length),
)
locality$: Observable<string | null> = this.store$.pipe(
select(profileLocalitySelector),
)
contactInfo$: Observable<IContact[]> = this.store$.pipe(
select(profileContactInfoSelector)
)
sentConnection: boolean = false
incomingConnection: boolean = false
isConnection: boolean = false
myProfile = { id: 0 }
profile = { id: 0 }
sendConnection(message: string): void {
this.store$.dispatch(
new ProfileSendConnectionAction({
senderId: this.myProfile.id,
userId: this.profile.id,
message,
}),
)
}
acceptConnection(): void {
this.store$.dispatch(
new ProfileAcceptConnectionAction({
senderId: this.profile.id,
userId: this.myProfile.id,
date: Date.now(),
}),
)
}
declineConnection(): void {
this.store$.dispatch(
new ProfileDeclineConnectionAction({
senderId: this.myProfile.id,
userId: this.profile.id,
}),
)
}
removeConnection(
userId: number = this.profile.id,
senderId: number = this.myProfile.id,
): void {
this.store$.dispatch(
new ProfileRemoveConnectionAction({
senderId,
userId,
}),
)
}
activateTab(e: MouseEvent): void {
const element = e.target as HTMLElement
const parent = element.parentNode as HTMLElement
const children = Array.from(parent.children)
children.forEach(el => el.classList.remove('active'))
element.classList.add('active')
this.currentTab = (element.textContent as string).toLowerCase()
}
ngOnInit(): void {
const sendConnectionModal = new HystModal({
linkAttributeName: 'data-hystmodal',
})
const connectionsListModal = new HystModal({
linkAttributeName: 'data-hystmodal',
})
const contactInfoModal = new HystModal({
linkAttributeName: 'data-hystmodal',
})
const profile$ = this.store$.pipe(
select(profileSelector),
takeUntil(this.unsub$),
)
this.store$
.pipe(select(myProfileSelector), takeUntil(this.unsub$))
.subscribe(res => (this.myProfile = res))
profile$.subscribe(res => {
this.profile = res
})
this.store$
.pipe(
select(profileSentConnectionsSelector),
map(incoming =>
incoming.some(user => user.userId === this.myProfile.id),
),
takeUntil(this.unsub$),
)
.subscribe(resp => (this.incomingConnection = resp))
profile$
.pipe(
map(user => user.info.receivedConnections),
map(received =>
received.some(user => user.userId === this.myProfile.id),
),
takeUntil(this.unsub$),
)
.subscribe(res => (this.sentConnection = res))
profile$
.pipe(
map(user => user.info.connections),
map(connections =>
connections.some(user => user.userId === this.myProfile.id),
),
takeUntil(this.unsub$),
)
.subscribe(res => (this.isConnection = res))
this.contactInfo$.subscribe(res => {
console.log(res)
})
}
ngOnDestroy(): void {
this.unsub$.next()
this.unsub$.complete()
}
}
<file_sep>/client/src/app/svg-icon/icons-path.ts
import { InjectionToken } from '@angular/core'
export const ICONS_PATH = new InjectionToken<string>('Pass to the icons folder')
<file_sep>/server/src/interfaces/edit-profile/personalInfo.ts
export interface IPersonalInfo {
firstName: string
lastName: string
gender: string
dateOfBirth: string | number
}
<file_sep>/client/src/app/store/profile/profile.actions.ts
/* ACTION TYPES */
import { Action } from '@ngrx/store'
import { ProfileState } from './profile.reducer'
import { IUser } from '../../interfaces/user'
export const GET_PROFILE_INFO_ACTION_TYPE = '[PROFILE] get info'
export const GET_PROFILE_INFO_SUCCESS_ACTION_TYPE = '[PROFILE] success get info'
export const SEND_CONNECTION_ACTION_TYPE = '[PROFILE] send connection'
export const ACCEPT_CONNECTION_ACTION_TYPE = '[PROFILE] accept connection'
export const DECLINE_CONNECTION_ACTION_TYPE = '[PROFILE] decline connection'
export const REMOVE_CONNECTION_ACTION_TYPE = '[PROFILE] remove connection'
export const SEND_CONNECTION_SUCCESS_ACTION_TYPE =
'[PROFILE] success send connection'
export const ACCEPT_CONNECTION_SUCCESS_ACTION_TYPE =
'[PROFILE] success accept connection'
export const DECLINE_CONNECTION_SUCCESS_ACTION_TYPE =
'[PROFILE] success decline connection'
export const REMOVE_CONNECTION_SUCCESS_ACTION_TYPE =
'[PROFILE] success remove connection'
/* ACTIONS */
/* GET INFO */
export class ProfileGetInfoAction implements Action {
readonly type = GET_PROFILE_INFO_ACTION_TYPE
constructor(
public payload: {
id: number
},
) {}
}
export class ProfileGetInfoSuccessAction implements Action {
readonly type = GET_PROFILE_INFO_SUCCESS_ACTION_TYPE
constructor(public payload: { profile: IUser }) {}
}
/* CONNECTIONS */
export class ProfileSendConnectionAction implements Action {
readonly type = SEND_CONNECTION_ACTION_TYPE
constructor(
public payload: {
senderId: number
userId: number
message: string
},
) {}
}
export class ProfileAcceptConnectionAction implements Action {
readonly type = ACCEPT_CONNECTION_ACTION_TYPE
constructor(
public payload: {
senderId: number
userId: number
date: number
},
) {}
}
export class ProfileDeclineConnectionAction implements Action {
readonly type = DECLINE_CONNECTION_ACTION_TYPE
constructor(
public payload: {
senderId: number
userId: number
},
) {}
}
export class ProfileRemoveConnectionAction implements Action {
readonly type = REMOVE_CONNECTION_ACTION_TYPE
constructor(
public payload: {
senderId: number
userId: number
},
) {}
}
export class ProfileSendConnectionSuccessAction implements Action {
readonly type = SEND_CONNECTION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
senderId: number
},
) {}
}
export class ProfileAcceptConnectionSuccessAction implements Action {
readonly type = ACCEPT_CONNECTION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
userId: number
date: number
},
) {}
}
export class ProfileDeclineConnectionSuccessAction implements Action {
readonly type = DECLINE_CONNECTION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
senderId: number
},
) {}
}
export class ProfileRemoveConnectionSuccessAction implements Action {
readonly type = REMOVE_CONNECTION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
senderId: number
},
) {}
}
export type ProfileActions =
| ProfileGetInfoAction
| ProfileGetInfoSuccessAction
| ProfileSendConnectionAction
| ProfileSendConnectionSuccessAction
| ProfileAcceptConnectionAction
| ProfileAcceptConnectionSuccessAction
| ProfileDeclineConnectionAction
| ProfileDeclineConnectionSuccessAction
| ProfileRemoveConnectionAction
| ProfileRemoveConnectionSuccessAction
<file_sep>/client/src/app/interfaces/contact.ts
export interface IContact {
contactWay: string | null
data: string | null
}
<file_sep>/client/src/app/views/profile/edit-profile/edit-profile-side/edit-profile-side.component.ts
import { Component, EventEmitter, OnInit, Output } from '@angular/core'
@Component({
selector: 'app-edit-profile-side',
templateUrl: './edit-profile-side.component.html',
styleUrls: ['./edit-profile-side.component.less'],
})
export class EditProfileSideComponent implements OnInit {
@Output() onChangeTab = new EventEmitter<string>()
constructor() {}
activateTab(e: MouseEvent, menu: HTMLElement): void {
const tabs = Array.from(menu.children) as HTMLElement[]
const target = e.target as HTMLElement
if (target.classList.contains('menu')) return
tabs.forEach(el => el.classList.remove('active'))
if (!target.classList.contains('tab')) {
const tab = target.closest('.tab') as HTMLElement
tab.classList.add('active')
this.onChangeTab.emit(tab.textContent ?? '')
} else {
target.classList.add('active')
this.onChangeTab.emit(target.textContent ?? '')
}
}
ngOnInit(): void {}
}
<file_sep>/client/src/app/store/chat/chat.reducer.ts
import { IChat } from '../../interfaces/chat/chat'
import { IUser } from '../../interfaces/user'
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity'
import {
CHANGE_CURRENT_CHAT,
ChatActions,
LOAD_CHATS_SUCCESS,
READ_MESSAGES,
RECEIVE_MESSAGE,
} from './chat.actions'
import { IMessages } from '../../interfaces/chat/messages'
export const chatNode = 'chat'
export interface Chat1 {
chats: IChat[]
currentChat: IChat | null
currentBuddy: IUser | null
}
export interface Chat {
chat: IChat
buddy: IUser
}
export interface ChatState extends EntityState<Chat> {
currentChat: number | null
messages: IMessages[]
}
export const adapter: EntityAdapter<Chat> = createEntityAdapter<Chat>({
selectId: instance => instance.chat.chatId,
})
export const initialState: ChatState = adapter.getInitialState({
currentChat: null,
messages: [],
})
export const chatReducer = (state = initialState, action: ChatActions) => {
switch (action.type) {
case LOAD_CHATS_SUCCESS:
if (state.currentChat !== -1) {
const curChat = action.payload.chats.find(
c => c.chat.chatId === state.currentChat,
)
if (curChat) {
return {
...adapter.setAll(action.payload.chats, state),
messages: curChat.chat.messages,
}
}
}
return adapter.setAll(action.payload.chats, state)
case CHANGE_CURRENT_CHAT:
return {
...state,
currentChat: action.payload.id,
messages: state.entities[action.payload.id]?.chat.messages,
}
case RECEIVE_MESSAGE:
if (action.payload.chatId === state.currentChat) {
return {
...state,
messages: action.payload.messages,
}
}
return state
case READ_MESSAGES:
return {
...state,
messages: action.payload.messages,
}
default:
return state
}
}
const {
selectIds,
selectEntities,
selectAll,
selectTotal,
} = adapter.getSelectors()
export const selectChatIds = selectIds
export const selectChatEntities = selectEntities
export const selectAllChats = selectAll
export const selectChatTotal = selectTotal
<file_sep>/client/src/app/directives/directives.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { VarDirective } from './var.directive'
@NgModule({
declarations: [VarDirective],
imports: [CommonModule],
exports: [VarDirective],
})
export class DirectivesModule {}
<file_sep>/client/src/app/services/chat.service.ts
import { Injectable } from '@angular/core'
import { select, Store } from '@ngrx/store'
import { ChatState } from '../store/chat/chat.reducer'
import {
ReadMessageAction,
ReceiveMessageAction,
} from '../store/chat/chat.actions'
import { IMessage } from '../interfaces/chat/message'
import { WebSocketService } from './web-socket.service'
import { IUser } from '../interfaces/user'
import { Observable, of, Subject } from 'rxjs'
import { HttpClient } from '@angular/common/http'
import { IChat } from '../interfaces/chat/chat'
import { environment } from '../../environments/environment'
import { filter, map, switchMap, takeUntil } from 'rxjs/operators'
import { MyProfileState } from '../store/my-profile/my-profile.reducer'
import { myProfileIdSelector } from '../store/my-profile/my-profile.selectors'
import { IMessages } from '../interfaces/chat/messages'
@Injectable({
providedIn: 'root',
})
export class ChatService {
constructor(
private socketService: WebSocketService,
private store$: Store<MyProfileState | ChatState>,
private http: HttpClient,
) {}
unsub$ = new Subject()
profileId$: Observable<number> = this.store$.pipe(
select(myProfileIdSelector),
)
joinToChat(chatId: number): void {
this.socketService.emit('joinPrivateChat', { chatId })
}
sendMessage(message: string, senderId: number, chatId: number): void {
this.socketService.emit<{ message: IMessage; chatId: number }>(
'sendMessage',
{
message: {
senderId,
status: 'wait',
time: Date.now(),
content: message,
},
chatId,
},
)
}
connect(): void {
this.unsub$.next()
this.unsub$.complete()
this.unsub$ = new Subject()
this.http
.get<{ chats: IChat[] }>(`${environment.server_url}/chats/find/all`)
.pipe(
map(res => res.chats),
switchMap(chats => {
return this.profileId$.pipe(
map(id => {
return chats.filter(chat => {
return chat.users.find(u => u.userId === id)
})
}),
map(res => {
console.log(res)
return res
}),
)
}),
)
.subscribe(myChats => {
myChats.forEach(chat => {
this.joinToChat(chat.chatId)
})
})
this.socketService
.listen<{ messages: IMessages[]; chatId: number }>('receiveMessage')
.pipe(takeUntil(this.unsub$))
.subscribe(data => {
console.log(
'[WebSocket Message]',
data.messages[data.messages.length - 1].dayMessages[
data.messages[data.messages.length - 1].dayMessages
.length - 1
].content,
)
this.store$.dispatch(
new ReceiveMessageAction({
chatId: data.chatId,
messages: data.messages,
}),
)
})
this.socketService
.listen<{ messages: IMessages[]; chatId: number }>('readMessages')
.pipe(takeUntil(this.unsub$))
.subscribe(data => {
this.store$.dispatch(
new ReadMessageAction({
chatId: data.chatId,
messages: data.messages,
}),
)
})
this.socketService
.listen<{ message: string }>('joinSuccess')
.pipe(takeUntil(this.unsub$))
.subscribe(data => console.log('[WebSocket Join]', data.message))
}
readMessages(profileId: number, chatId: number): void {
this.socketService.emit('readMessages', { chatId, profileId })
}
getChats(): void {}
getBuddyProfiles(chats: IChat[], profileId: number): Observable<IUser[]> {
const myChats = chats.filter(chat => {
return chat.users.some(user => user.userId === profileId)
})
console.log('chats', chats)
const identifiers: number[] = []
myChats.forEach(chat => {
const buddy = chat.users.find(user => user.userId !== profileId)
if (!buddy) return
identifiers.push(buddy.userId)
})
const param = identifiers.join(',')
console.log('PARAM:', param)
if (!param) return of([])
if (identifiers.length > 1) {
return this.http
.get<{ users: IUser[] }>(
`${environment.server_url}/users/find/${param}`,
)
.pipe(map(res => res.users))
} else {
return this.http
.get<{ user: IUser }>(
`${environment.server_url}/users/find/${param}`,
)
.pipe(map(res => [res.user]))
}
}
}
<file_sep>/server/src/interfaces/post/like.ts
export interface ILike {
userId: number
}
<file_sep>/client/src/app/services/auth.service.ts
import { Injectable } from '@angular/core'
import { environment } from '../../environments/environment'
import { Observable } from 'rxjs'
import { HttpClient } from '@angular/common/http'
import { RegistrationForm } from '../../../../server/src/interfaces/auth/registration'
import { AuthForm } from '../../../../server/src/interfaces/auth/auth'
import { IsdCountryCode } from '../../../../server/src/interfaces/auth/isdCountryCode'
import { MyProfileState } from '../store/my-profile/my-profile.reducer'
import { map } from 'rxjs/operators'
import { IUser } from '../interfaces/user'
@Injectable({
providedIn: 'root',
})
export class AuthService {
isAuth: boolean
constructor(private http: HttpClient) {
this.isAuth = false
}
signUpRequest(formValue: RegistrationForm): Observable<RegistrationForm> {
formValue.passwordRepeat = <PASSWORD>
return this.http.post<RegistrationForm>(
`${environment.server_url}/users/create`,
formValue,
{
headers: {
'Content-Type': 'application/json',
},
},
)
}
signInRequest(formValue: AuthForm): Observable<{ user: IUser }> {
return this.http
.post<{ user: IUser }>(
`${environment.server_url}/users/auth`,
formValue,
)
.pipe(
map(res => {
console.log(res)
return res
}),
)
}
getIsdCountryCode(): Observable<IsdCountryCode[]> {
return this.http.get<IsdCountryCode[]>(
'https://gist.githubusercontent.com/iamswapnilsonar/0e1868229e98cc27a6d2e3487b44f7fa/raw/10f8979f0b1daa0e0b490137d51fb96736767a09/isd_country_code.json',
)
}
testReq(): void {
this.http
.get(`${environment.server_url}/users/test`)
.subscribe(res => console.log(res))
}
}
<file_sep>/client/src/app/services/profile.service.ts
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { environment } from '../../environments/environment'
import { Observable, of } from 'rxjs'
import { AuthState } from '../store/auth/auth.reducer'
import { IUser } from '../interfaces/user'
import { map } from 'rxjs/operators'
import { IPersonalInfo } from '../interfaces/edit-profile/personalInfo'
import { IContact } from '../interfaces/contact'
import { IProject } from '../interfaces/project'
import { IExp } from '../interfaces/exp'
import { IUniversity } from '../interfaces/university'
@Injectable({
providedIn: 'root',
})
export class ProfileService {
constructor(private http: HttpClient) {}
findUsersByFullName(fullName: string): Observable<IUser[]> {
return this.http
.get<{ users: IUser[] }>(
`${environment.server_url}/users/find/all?fullName=${fullName}`,
)
.pipe(map(res => res.users))
}
getProfileInfo<T>(id: number | string): Observable<T> {
return this.http.get<T>(`${environment.server_url}/users/find/${id}`)
}
getConnectionsById$(
connections: { userId: number; date: number }[],
): Observable<{ user: IUser; date: number }[]> {
const identifiers = connections.map(connection => connection.userId)
if (identifiers.length > 1) {
return this.getProfileInfo<{ users: IUser[] }>(
identifiers.join(','),
).pipe(
map(res => {
return connections.map(connection => {
return {
user: res.users.find(
us => us.id === connection.userId,
) as IUser,
date: connection.date,
}
})
}),
)
} else if (identifiers.length === 1) {
return this.getProfileInfo<{ user: IUser }>(
identifiers.join(','),
).pipe(
map(res => {
return connections.map(connection => {
return {
user: res.user,
date: connection.date,
}
})
}),
)
} else {
// console.log('connections is empty')
return of([])
}
}
sendConnection(
senderId: number,
userId: number,
message: string,
): Observable<{ sent: boolean }> {
return this.http.post<{ sent: boolean }>(
`${environment.server_url}/users/connections/send/${userId}`,
{
senderId,
message,
},
)
}
acceptConnection(
senderId: number,
userId: number,
date: number,
): Observable<{ user: IUser; chatId: number }> {
return this.http.post<{ user: IUser; chatId: number }>(
`${environment.server_url}/users/connections/accept/${senderId}`,
{ userId, date },
)
}
declineConnection(senderId: number, userId: number): Observable<IUser> {
return this.http.post<IUser>(
`${environment.server_url}/users/connections/decline/${senderId}`,
{ userId },
)
}
cancelConnection(senderId: number, userId: number): Observable<IUser> {
return this.http.post<IUser>(
`${environment.server_url}/users/connections/decline/${senderId}`,
{ userId },
)
}
removeConnection(senderId: number, userId: number): Observable<IUser> {
return this.http.post<IUser>(
`${environment.server_url}/users/connections/remove/${senderId}`,
{ userId },
)
}
editPersonalInfo(info: IPersonalInfo, id: number): Observable<any> {
return this.http.post(
`${environment.server_url}/users/find/${id}/edit/profile-info`,
info,
)
}
changeAvatar(
fileToUpload: File,
id: number,
): Observable<{ message: string; url: string }> {
const formData: FormData = new FormData()
formData.append('avatar', fileToUpload, fileToUpload.name)
return this.http.post<{ message: string; url: string }>(
`${environment.server_url}/users/${id}/avatar/upload`,
formData,
)
}
deleteAvatar(id: number): Observable<{ message: string }> {
return this.http.delete<{ message: string }>(
`${environment.server_url}/users/${id}/avatar/delete`,
)
}
changeEmail(id: number, email: string): Observable<{ message: string }> {
return this.http.post<{ message: string }>(
`${environment.server_url}/users/${id}/change/email`,
{ email },
)
}
changePhone(id: number, phone: string): Observable<{ message: string }> {
return this.http.post<{ message: string }>(
`${environment.server_url}/users/${id}/change/phone`,
{ phone },
)
}
changePassword(
id: number,
newPassword: string,
oldPassword: string,
): Observable<{ message: string }> {
return this.http.post<{ message: string }>(
`${environment.server_url}/users/${id}/change/password`,
{ oldPassword, newPassword },
)
}
deleteAccount(userId: number, password: string): Observable<any> {
return this.http.post(
`${environment.server_url}/users/remove/${userId}`,
{ password },
)
}
changeRole(role: string, id: number): Observable<any> {
return this.http.post(
`${environment.server_url}/users/${id}/change/role`,
{ role },
)
}
changeCompany(company: any, id: number): Observable<any> {
return this.http.post(
`${environment.server_url}/users/${id}/change/company`,
{ company },
)
}
changeAbout(about: string, id: number): Observable<any> {
return this.http.post(
`${environment.server_url}/users/${id}/change/about`,
{ about },
)
}
changeProfession(profession: string, id: number): Observable<any> {
return this.http.post(
`${environment.server_url}/users/${id}/change/profession`,
{ profession },
)
}
changeLocality(
locality: { country: string; city: string },
id: number,
): Observable<any> {
return this.http.post(
`${environment.server_url}/users/${id}/change/locality`,
{ locality },
)
}
changeContactInfo(contactInfo: IContact[], id: number): Observable<any> {
return this.http.post(
`${environment.server_url}/users/${id}/change/contact-info`,
{ contactInfo },
)
}
changeProjects(projects: IProject[], id: number): Observable<any> {
return this.http.post(
`${environment.server_url}/users/${id}/change/projects`,
{ projects },
)
}
changeExperience(experience: IExp[], id: number): Observable<any> {
return this.http.post(
`${environment.server_url}/users/${id}/change/experience`,
{ experience },
)
}
changeEducation(education: IUniversity[], id: number): Observable<any> {
return this.http.post(
`${environment.server_url}/users/${id}/change/education`,
{ education },
)
}
}
<file_sep>/client/src/app/views/views.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { RouterModule } from '@angular/router'
import { ChatModule } from './chat/chat.module'
import { FeedModule } from './feed/feed.module'
import { JobsModule } from './jobs/jobs.module'
import { NetworkModule } from './network/network.module'
import { NoticesModule } from './notices/notices.module'
import { ProfileModule } from './profile/profile.module'
import { PipesModule } from '../pipes/pipes.module'
import { SvgIconModule } from '../svg-icon/svg-icon.module'
import { ICONS_PATH } from '../svg-icon/icons-path'
import { AuthModule } from './auth/auth.module'
import { PostsService } from '../services/posts.service'
@NgModule({
declarations: [],
imports: [
CommonModule,
ChatModule,
FeedModule,
JobsModule,
NetworkModule,
NoticesModule,
ProfileModule,
AuthModule,
PipesModule,
SvgIconModule,
RouterModule,
],
providers: [
{
provide: ICONS_PATH,
useValue: 'assets/img/svg',
},
PostsService,
],
exports: [],
})
export class ViewsModule {}
<file_sep>/client/src/app/interfaces/auth/registration.ts
export interface RegistrationForm {
firstName: string
lastName: string
phone: string
email: string
password: string
passwordRepeat: string | undefined
}
<file_sep>/client/src/app/services/file.service.ts
import { Injectable } from '@angular/core'
import { IAttach } from '../interfaces/post/attach'
import { IAttached } from '../interfaces/post/attached'
@Injectable({
providedIn: 'root',
})
export class FileService {
constructor() {}
fileUpload(
fileInput: HTMLInputElement,
type: string,
attached: IAttached,
): void {
fileInput.onchange = (e: Event) => {
const { files } = e.target as HTMLInputElement
;[].forEach.call(files, (file: File) => {
const fileReader = new FileReader()
console.log(file)
fileReader.onload = (ev: ProgressEvent) => {
const fr = ev.target as FileReader
console.log(fr)
const attach: IAttach = {
name: file.name,
type: file.type,
size: file.size,
result: fr.result,
}
if (file.type.match('image')) {
if (!attached.images) attached.images = []
attached.images.push(attach)
} else if (file.type.match('video')) {
if (!attached.videos) attached.videos = []
attached.videos.push(attach)
} else {
if (!attached.files) attached.files = []
attached.files.push(attach)
}
}
fileReader.readAsDataURL(file)
})
}
fileInput.click()
}
}
<file_sep>/client/src/app/store/posts/post.effects.ts
import { Injectable } from '@angular/core'
import { Actions, Effect, ofType } from '@ngrx/effects'
import {
COMMENT_CREATE_ACTION_TYPE,
CommentCreateAction,
CommentCreateFailedAction,
CommentCreateSuccessAction,
POST_CREATE_ACTION_TYPE,
POST_CREATE_FAILED_ACTION_TYPE,
POST_DONT_LIKE_ACTION_TYPE,
POST_GET_ACTION_TYPE,
POST_LIKE_ACTION_TYPE,
PostActions,
PostCreateAction,
PostCreateFailedAction,
PostCreateSuccessAction,
PostDontLikeAction,
PostDontLikeFailedAction,
PostDontLikeSuccessAction,
PostGetAction,
PostGetFailedAction,
PostGetSuccessAction,
PostLikeAction,
PostLikeFailedAction,
PostLikeSuccessAction,
} from './post.actions'
import { catchError, map, mergeMap, switchMap } from 'rxjs/operators'
import { PostsService } from '../../services/posts.service'
import { Observable, of } from 'rxjs'
import { PostDto } from '../../dto/post.dto'
import { CommentDto } from '../../dto/comment.dto'
@Injectable()
export class PostEffects {
constructor(
private actions$: Actions,
private postsService: PostsService,
) {}
@Effect()
createPost$(): Observable<PostActions> {
return this.actions$.pipe(
ofType(POST_CREATE_ACTION_TYPE),
switchMap((action: PostCreateAction) => {
return this.postsService
.createPost(action.payload as PostDto)
.pipe(
map(post => {
console.log('PAYLOAD:', action.payload)
return new PostCreateSuccessAction({ post })
}),
catchError(err =>
of(new PostCreateFailedAction({ err })),
),
)
}),
)
}
editPost$(): Observable<PostActions> | any {}
removePost$(): Observable<PostActions> | any {}
@Effect()
likePost$(): Observable<PostActions> {
return this.actions$.pipe(
ofType(POST_LIKE_ACTION_TYPE),
switchMap((action: PostLikeAction) => {
const payload = action.payload
return this.postsService
.likePost(payload.postId, payload.userId)
.pipe(
map(like => {
return new PostLikeSuccessAction({
postId: payload.postId,
userId: payload.userId,
})
}),
catchError(err =>
of(new PostLikeFailedAction({ err })),
),
)
}),
)
}
@Effect()
dontLikePost$(): Observable<PostActions> {
return this.actions$.pipe(
ofType(POST_DONT_LIKE_ACTION_TYPE),
switchMap((action: PostDontLikeAction) => {
const payload = action.payload
return this.postsService
.dontLikePost(payload.postId, payload.userId)
.pipe(
map(like => {
return new PostDontLikeSuccessAction({
postId: payload.postId,
userId: payload.userId,
})
}),
catchError(err =>
of(new PostDontLikeFailedAction({ err })),
),
)
}),
)
}
@Effect()
addComment$(): Observable<PostActions> {
return this.actions$.pipe(
ofType(COMMENT_CREATE_ACTION_TYPE),
switchMap((action: CommentCreateAction) => {
const payload = action.payload as {
postId: number
commentInfo: CommentDto
}
return this.postsService
.createComment(payload.commentInfo, payload.postId)
.pipe(
map(comments => {
return new CommentCreateSuccessAction({
...comments,
postId: payload.postId,
})
}),
catchError(err =>
of(new CommentCreateFailedAction({ err })),
),
)
}),
)
}
@Effect()
getPosts$(): Observable<PostActions> {
return this.actions$.pipe(
ofType(POST_GET_ACTION_TYPE),
switchMap((action: PostGetAction) => {
return this.postsService.getPosts(action.payload.id).pipe(
map(posts => {
return posts.posts
}),
map(posts => new PostGetSuccessAction({ posts })),
catchError(err => of(new PostGetFailedAction({ err }))),
)
}),
)
}
}
<file_sep>/client/src/app/views/profile/profile.component.ts
import { Component, OnInit } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { select, Store } from '@ngrx/store'
import { ProfileState } from '../../store/profile/profile.reducer'
import { ProfileGetInfoAction } from '../../store/profile/profile.actions'
import { profileSelector } from '../../store/profile/profile.selectors'
import {
myProfileIdSelector,
myProfileSelector,
} from '../../store/my-profile/my-profile.selectors'
import { MyProfileState } from '../../store/my-profile/my-profile.reducer'
import { Observable } from 'rxjs'
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.less'],
})
export class ProfileComponent implements OnInit {
constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
private store$: Store<ProfileState | MyProfileState>,
) {}
myProfileId$: Observable<number> = this.store$.pipe(
select(myProfileIdSelector),
)
isMyProfile: boolean = false
ngOnInit(): void {
this.activatedRoute.params.subscribe(params => {
if (params.id) {
this.myProfileId$.subscribe(id => {
console.log('id:', id, '\nparams id:', params.id)
this.isMyProfile = id === +params.id
})
console.log('params id:', +params.id)
this.store$.dispatch(
new ProfileGetInfoAction({ id: +params.id }),
)
} else {
this.myProfileId$.subscribe(id => {
this.router.navigate([`/profile/${id}`])
})
}
})
}
}
export const initialProfileState = {
email: '',
firstName: '',
id: 0,
info: {
avatar: null,
connections: [],
dateOfBirth: 0,
description: '',
isOnline: false,
posts: [],
profession: '',
profileHeaderBg: null,
receivedConnections: [],
sentConnections: [],
views: { current: 0, prev: 0 },
},
lastName: '',
password: '',
phone: '',
}
<file_sep>/server/src/interfaces/project.ts
import { IFile } from './file'
export interface IProject {
name: string | null
role: string | null
date: string | null
about: string | null
poster: (IFile & { file: File }) | null
}
<file_sep>/client/src/app/store/posts/post.reducer.ts
import {
COMMENT_CREATE_FAILED_ACTION_TYPE,
COMMENT_CREATE_SUCCESS_ACTION_TYPE,
POST_COMMENTS_CLOSE_ACTION_TYPE,
POST_COMMENTS_OPEN_ACTION_TYPE,
POST_CREATE_FAILED_ACTION_TYPE,
POST_CREATE_SUCCESS_ACTION_TYPE,
POST_DONT_LIKE_FAILED_ACTION_TYPE,
POST_DONT_LIKE_SUCCESS_ACTION_TYPE,
POST_EDIT_FAILED_ACTION_TYPE,
POST_EDIT_SUCCESS_ACTION_TYPE,
POST_GET_FAILED_ACTION_TYPE,
POST_GET_SUCCESS_ACTION_TYPE,
POST_LIKE_FAILED_ACTION_TYPE,
POST_LIKE_SUCCESS_ACTION_TYPE,
PostActions,
SORTING_POSTS_ACTION_TYPE,
} from './post.actions'
import { IPost } from '../../interfaces/post/post'
import { IComment } from '../../interfaces/post/comment'
export const postNode = 'post'
export interface PostState {
posts: IPost[]
error: string
}
const initialState: PostState = {
posts: [],
error: '',
}
export const postReducer = (
state: PostState = initialState,
action: PostActions,
) => {
switch (action.type) {
case POST_CREATE_SUCCESS_ACTION_TYPE:
return {
...state,
posts: [action.payload.post, ...state.posts],
}
case POST_CREATE_FAILED_ACTION_TYPE:
return {
...state,
error: action.payload.err,
}
case POST_EDIT_SUCCESS_ACTION_TYPE:
return {
...state,
}
case POST_EDIT_FAILED_ACTION_TYPE:
return {
...state,
error: action.payload.err,
}
case POST_LIKE_SUCCESS_ACTION_TYPE:
return {
...state,
posts: state.posts.map(post => {
if (action.payload.postId === post.id) {
return {
...post,
likes: [
...post.likes,
{ userId: action.payload.userId },
],
}
}
return post
}),
}
case POST_LIKE_FAILED_ACTION_TYPE:
return {
...state,
error: action.payload.err,
}
case POST_DONT_LIKE_SUCCESS_ACTION_TYPE:
return {
...state,
posts: state.posts.map(post => {
if (action.payload.postId === post.id) {
return {
...post,
likes: post.likes.filter(
user => user.userId !== action.payload.userId,
),
}
}
return post
}),
}
case POST_DONT_LIKE_FAILED_ACTION_TYPE:
return {
...state,
// error: action.payload.err
}
case POST_GET_SUCCESS_ACTION_TYPE:
return {
...state,
posts: action.payload.posts,
}
case POST_GET_FAILED_ACTION_TYPE:
return {
...state,
error: action.payload.err,
}
case POST_COMMENTS_OPEN_ACTION_TYPE:
return {
...state,
posts: state.posts.map(post => {
if (post.id === action.payload.postId) {
return {
...post,
commentsOpen: true,
}
}
return post
}),
}
case POST_COMMENTS_CLOSE_ACTION_TYPE:
return {
...state,
posts: state.posts.map(post => {
if (post.id === action.payload.postId) {
return {
...post,
commentsOpen: false,
}
}
return post
}),
}
case SORTING_POSTS_ACTION_TYPE: {
if (action.payload.sortType === 'trending')
return {
...state,
posts: state.posts
.slice()
.sort(
(post1, post2) =>
post2?.likes.length - post1?.likes.length,
),
}
if (action.payload.sortType === 'newest first')
return {
...state,
posts: state.posts
.slice()
.sort(
(post1, post2) =>
post2.dateOfCreation - post1.dateOfCreation,
),
}
if (action.payload.sortType === 'lastest first')
return {
...state,
posts: state.posts
.slice()
.sort(
(post1, post2) =>
post1.dateOfCreation - post2.dateOfCreation,
),
}
return state
}
case COMMENT_CREATE_SUCCESS_ACTION_TYPE:
const payload = action.payload as {
postId: number
comments: IComment[]
}
return {
...state,
posts: state.posts.map(post => {
if (post.id === payload.postId)
return {
...post,
comments: payload.comments,
}
return post
}),
}
case COMMENT_CREATE_FAILED_ACTION_TYPE:
default:
return state
}
}
<file_sep>/client/src/app/views/profile/profile.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { RouterModule } from '@angular/router'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ComponentsModule } from '../../components/components.module'
import { SvgIconModule } from '../../svg-icon/svg-icon.module'
import { ProfileComponent } from './profile.component'
import { ProfileMainComponent } from './profile-main/profile-main.component'
import { ProfileSideComponent } from './profile-side/profile-side.component'
import { EditProfileSideComponent } from './edit-profile/edit-profile-side/edit-profile-side.component'
import { EditProfileMainComponent } from './edit-profile/edit-profile-main/edit-profile-main.component'
import { EditProfileComponent } from './edit-profile/edit-profile.component'
import { EditPersonalDataComponent } from './edit-profile/edit-components/edit-personal-data/edit-personal-data.component'
import { EditLoginAndSecurityComponent } from './edit-profile/edit-components/edit-login-and-security/edit-login-and-security.component'
import { EditAdditionalInfoComponent } from './edit-profile/edit-components/edit-additional-info/edit-additional-info.component'
import { PipesModule } from '../../pipes/pipes.module'
import { VarDirective } from '../../directives/var.directive'
import { DirectivesModule } from '../../directives/directives.module'
@NgModule({
declarations: [
ProfileComponent,
ProfileMainComponent,
ProfileSideComponent,
EditProfileComponent,
EditProfileSideComponent,
EditProfileMainComponent,
EditPersonalDataComponent,
EditLoginAndSecurityComponent,
EditAdditionalInfoComponent,
],
imports: [
CommonModule,
ComponentsModule,
RouterModule,
ReactiveFormsModule,
SvgIconModule,
FormsModule,
PipesModule,
DirectivesModule,
],
})
export class ProfileModule {}
<file_sep>/client/src/app/views/chat/chat-side/chat-side.component.ts
import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core'
import { IChat } from '../../../interfaces/chat/chat'
import { IUser } from '../../../interfaces/user'
import {Observable, Subject} from 'rxjs'
import { switchMap } from 'rxjs/operators'
import { ChatService } from '../../../services/chat.service'
import { select, Store } from '@ngrx/store'
import { MyProfileState } from '../../../store/my-profile/my-profile.reducer'
import { Chat, ChatState } from '../../../store/chat/chat.reducer'
import {
allChatsSelector,
currentChatSelector,
} from '../../../store/chat/chat.selectors'
@Component({
selector: 'app-chat-side',
templateUrl: './chat-side.component.html',
styleUrls: ['./chat-side.component.less'],
})
export class ChatSideComponent implements OnInit {
constructor(
private chatService: ChatService,
private store$: Store<MyProfileState | ChatState>,
) {}
@Input() profileId: number = -1
@Output() action = new EventEmitter<{ type: string; data: any }>()
allChats$: Observable<Chat[]> = this.store$.pipe(select(allChatsSelector))
currentChat$: Observable<Chat | null | undefined> = this.store$.pipe(
select(currentChatSelector),
)
unread = []
activateChat(chatId: number | string): void {
this.action.emit({ type: 'changeActiveChat', data: chatId })
}
ngOnInit(): void {}
}
<file_sep>/client/src/app/views/chat/chat.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { ChatComponent } from './chat.component'
import { ChatMainComponent } from './chat-main/chat-main.component'
import { ChatSideComponent } from './chat-side/chat-side.component'
import { FormsModule } from '@angular/forms'
import { SvgIconModule } from '../../svg-icon/svg-icon.module'
import { ChatService } from '../../services/chat.service'
import { AppRoutingModule } from '../../app-routing.module'
@NgModule({
declarations: [ChatComponent, ChatMainComponent, ChatSideComponent],
imports: [CommonModule, FormsModule, SvgIconModule, AppRoutingModule],
providers: [ChatService],
})
export class ChatModule {}
<file_sep>/client/src/app/interfaces/file.ts
export interface IFile {
fileName: string
encoding: string
mimetype: string
url: string
size: number
}
<file_sep>/client/src/app/views/network/network.module.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { NetworkComponent } from './network.component'
import { NetworkSideComponent } from './network-side/network-side.component'
import { NetworkMainComponent } from './network-main/network-main.component'
import { SvgIconModule } from '../../svg-icon/svg-icon.module'
import { RouterModule } from '@angular/router'
import { ConnectionsListComponent } from '../../components/network/connections-list/connections-list.component'
import { InvitationsComponent } from '../../components/network/invitations/invitations.component'
import { ComponentsModule } from '../../components/components.module'
@NgModule({
declarations: [
NetworkComponent,
NetworkSideComponent,
NetworkMainComponent,
ConnectionsListComponent,
InvitationsComponent,
],
imports: [CommonModule, SvgIconModule, RouterModule, ComponentsModule],
exports: [],
})
export class NetworkModule {}
<file_sep>/client/src/app/app.module.ts
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { AppRoutingModule } from './app-routing.module'
import { SvgIconModule } from './svg-icon/svg-icon.module'
import { ViewsModule } from './views/views.module'
import { PipesModule } from './pipes/pipes.module'
import { ReactiveFormsModule } from '@angular/forms'
import { AppComponent } from './app.component'
import { HeaderComponent } from './components/header/header.component'
import { FooterComponent } from './components/footer/footer.component'
import { AuthLayoutComponent } from './layouts/auth/auth.component'
import { BaseLayoutComponent } from './layouts/base/base.component'
import { StoreModule } from '@ngrx/store'
import { StoreDevtoolsModule } from '@ngrx/store-devtools'
import { environment } from '../environments/environment'
import { EffectsModule } from '@ngrx/effects'
import { StoreRouterConnectingModule } from '@ngrx/router-store'
import { SocketIoConfig, SocketIoModule } from 'ngx-socket-io'
import { metaReducers, reducers } from './store'
import { PostEffects } from './store/posts/post.effects'
import { MyProfileEffects } from './store/my-profile/my-profile.effects'
import { ProfileEffects } from './store/profile/profile.effects'
import { DirectivesModule } from './directives/directives.module'
import { ChatEffects } from './store/chat/chat.effects'
const config: SocketIoConfig = { url: environment.server_url, options: {} }
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
AuthLayoutComponent,
BaseLayoutComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
SvgIconModule,
ViewsModule,
PipesModule,
DirectivesModule,
ReactiveFormsModule,
StoreModule.forRoot(reducers, {
metaReducers,
runtimeChecks: {
strictActionImmutability: true,
strictStateImmutability: true,
},
}),
StoreDevtoolsModule.instrument({
maxAge: 25,
logOnly: environment.production,
}),
EffectsModule.forRoot([
PostEffects,
MyProfileEffects,
ProfileEffects,
ChatEffects,
]),
StoreRouterConnectingModule.forRoot(),
SocketIoModule.forRoot(config),
],
providers: [],
bootstrap: [AppComponent],
exports: [],
})
export class AppModule {}
<file_sep>/server/src/dto/post.dto.ts
import { IAttached } from '../interfaces/post/attached'
import { ICreator } from '../interfaces/post/creator'
export interface PostDto {
creator: ICreator
content: string
dateOfCreation: number
attached: IAttached
}
<file_sep>/client/src/app/interfaces/buffer.ts
export interface IBuffer {
type: string
data: Uint8Array
}
<file_sep>/client/src/app/store/posts/post.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store'
import { postNode, PostState } from './post.reducer'
export const postFeatureSelector = createFeatureSelector<PostState>(postNode)
export const postsSelector = createSelector(
postFeatureSelector,
(state: PostState) => {
return state?.posts || []
},
)
export const postsErrorSelector = createSelector(
postFeatureSelector,
state => state.error,
)
<file_sep>/client/src/app/views/profile/edit-profile/edit-profile-main/edit-profile-main.component.ts
import { Component, Input, OnInit } from '@angular/core'
import { select, Store } from '@ngrx/store'
import { Observable } from 'rxjs'
import { map, take, takeUntil } from 'rxjs/operators'
import {
myProfileAboutSelector,
myProfileAvatarSelector,
myProfileContactInfoSelector,
myProfileDateOfLastPasswordUpdateSelector,
myProfileDOBSelector,
myProfileEducationSelector,
myProfileEmailSelector,
myProfileExperienceSelector,
myProfileGenderSelector,
myProfileIdSelector,
myProfileLocalitySelector,
myProfileNameSelector,
myProfilePhoneSelector,
myProfileProfessionSelector,
myProfileProjectsSelector,
myProfileRoleSelector,
} from '../../../../store/my-profile/my-profile.selectors'
import { MyProfileState } from '../../../../store/my-profile/my-profile.reducer'
import { ProfileService } from '../../../../services/profile.service'
import { IPersonalInfo } from '../../../../interfaces/edit-profile/personalInfo'
import {
MyProfileChangeAboutAction,
MyProfileChangeAvatarSuccessAction,
MyProfileChangeContactInfoAction,
MyProfileChangeEducationAction,
MyProfileChangeExperienceAction,
MyProfileChangeLocalityAction,
MyProfileChangeProfessionAction,
MyProfileChangeProjectsAction,
MyProfileChangeRoleAction,
MyProfileDeleteAvatarSuccessAction,
} from '../../../../store/my-profile/my-profile.actions'
import { IContact } from '../../../../interfaces/contact'
import { IProject } from '../../../../interfaces/project'
import { IUniversity } from '../../../../interfaces/university'
import { IExp } from '../../../../interfaces/exp'
@Component({
selector: 'app-edit-profile-main',
templateUrl: './edit-profile-main.component.html',
styleUrls: ['./edit-profile-main.component.less'],
})
export class EditProfileMainComponent implements OnInit {
constructor(
private store$: Store<MyProfileState>,
private profileService: ProfileService,
) {}
@Input() currentTab: string = ''
profileId: number = -1
firstName$: Observable<string> = this.store$.pipe(
select(myProfileNameSelector),
map(fullName => {
console.log(fullName)
return fullName.firstName
}),
)
lastName$: Observable<string> = this.store$.pipe(
select(myProfileNameSelector),
map(fullName => fullName.lastName),
)
dateOfBirth$: Observable<number> = this.store$.pipe(
select(myProfileDOBSelector),
)
gender$: Observable<string> = this.store$.pipe(
select(myProfileGenderSelector),
)
avatar$: Observable<string> = this.store$.pipe(
select(myProfileAvatarSelector),
)
email$: Observable<string> = this.store$.pipe(
select(myProfileEmailSelector),
)
phone$: Observable<string> = this.store$.pipe(
select(myProfilePhoneSelector),
)
dateOfLastPasswordUpdate$: Observable<number> = this.store$.pipe(
select(myProfileDateOfLastPasswordUpdateSelector),
)
profileId$: Observable<number> = this.store$.pipe(
select(myProfileIdSelector),
take(2),
)
role$: Observable<string> = this.store$.pipe(select(myProfileRoleSelector))
about$: Observable<string> = this.store$.pipe(
select(myProfileAboutSelector),
)
profession$: Observable<string> = this.store$.pipe(
select(myProfileProfessionSelector),
)
contactInfo$: Observable<IContact[]> = this.store$.pipe(
select(myProfileContactInfoSelector),
map(contacts => {
if (!contacts[0]) return [{ contactWay: '', data: '' }]
return contacts
}),
)
// @ts-ignore
locality$: Observable<{ country: string; city: string }>
projects$: Observable<IProject[]> = this.store$.pipe(
select(myProfileProjectsSelector),
map(projects => {
if (!projects[0])
return [
{ name: '', role: '', date: '', about: '', poster: null },
]
return projects
}),
)
experience$: Observable<IExp[]> = this.store$.pipe(
select(myProfileExperienceSelector),
map(experience => {
if (!experience[0])
return [
{
companyName: '',
profession: '',
start: '',
end: '',
logo: null,
},
]
return experience
}),
)
education$: Observable<IUniversity[]> = this.store$.pipe(
select(myProfileEducationSelector),
map(education => {
if (!education[0])
return [
{
name: '',
facultyAndDegree: '',
comment: '',
start: '',
end: '',
logo: null,
},
]
return education
}),
)
editPersonalInfoStatus: { status: string; message: string } | null = null
editPersonalInfo(info: IPersonalInfo): void {
const [year, month, day] = (info.dateOfBirth as string).split('-')
console.log(day)
this.profileService
.editPersonalInfo(
{
...info,
dateOfBirth: Number(
new Date(
Number(year),
Number(month) - 1,
Number(day) + 1,
),
),
},
this.profileId,
)
.subscribe(res => {
if (res.status === 'changed') {
this.editPersonalInfoStatus = {
status: 'success',
message: 'Personal information has been changed',
}
}
if (res.status === 'not found')
this.editPersonalInfoStatus = {
status: 'fail',
message: 'User is not found, try reloading this page',
}
})
}
changeAvatarHandler(data: { type: string; file: File }): void {
if (data.type === 'change') this.changeAvatar(data.file)
if (data.type === 'delete') this.deleteAvatar()
}
changeAvatar(file: File): void {
this.profileService.changeAvatar(file, this.profileId).subscribe(
res => {
console.log(res)
// console.log(res.message)
this.store$.dispatch(
new MyProfileChangeAvatarSuccessAction({ url: res.url }),
)
},
err => {
console.error(err.message)
},
)
}
deleteAvatar(): void {
this.profileService.deleteAvatar(this.profileId).subscribe(
res => {
console.log(res.message)
this.store$.dispatch(new MyProfileDeleteAvatarSuccessAction())
},
err => {
console.error(err.message)
},
)
}
changeRole(role: string): void {
this.store$.dispatch(
new MyProfileChangeRoleAction({ role, id: this.profileId }),
)
}
// changeCompany(company: any): void
changeAbout(about: string): void {
this.store$.dispatch(
new MyProfileChangeAboutAction({ about, id: this.profileId }),
)
}
changeProfession(profession: string): void {
this.store$.dispatch(
new MyProfileChangeProfessionAction({
profession,
id: this.profileId,
}),
)
}
changeLocality(locality: { country: string; city: string }): void {
this.store$.dispatch(
new MyProfileChangeLocalityAction({ locality, id: this.profileId }),
)
}
changeContactInfo(contactInfo: IContact[]): void {
this.store$.dispatch(
new MyProfileChangeContactInfoAction({
contactInfo,
id: this.profileId,
}),
)
}
changeProjects(projects: IProject[]): void {
this.store$.dispatch(
new MyProfileChangeProjectsAction({ projects, id: this.profileId }),
)
}
changeExperience(experience: IExp[]): void {
this.store$.dispatch(
new MyProfileChangeExperienceAction({
experience,
id: this.profileId,
}),
)
}
changeEducation(education: IUniversity[]): void {
this.store$.dispatch(
new MyProfileChangeEducationAction({
education,
id: this.profileId,
}),
)
}
changeAdditionalInfoHandler(ev: { type: string; data: any }): void {
switch (ev.type) {
case 'role':
this.changeRole(ev.data)
return
case 'about':
this.changeAbout(ev.data)
return
case 'profession':
this.changeProfession(ev.data)
return
case 'locality':
this.changeLocality(ev.data)
return
case 'contact-info':
this.changeContactInfo(ev.data)
return
case 'projects':
this.changeProjects(ev.data)
return
case 'experience':
this.changeExperience(ev.data)
return
case 'education':
this.changeEducation(ev.data)
return
}
}
ngOnInit(): void {
this.profileId$.subscribe(id => (this.profileId = id))
this.locality$ = this.store$.pipe(
select(myProfileLocalitySelector),
map(locality => {
console.log('Locality:', locality)
return locality
}),
)
}
}
<file_sep>/client/src/app/pipes/avatar.pipe.spec.ts
import { AvatarPipe } from './avatar.pipe'
describe('AvatarPipe', () => {
it('create an instance', () => {
const pipe = new AvatarPipe()
expect(pipe).toBeTruthy()
})
})
<file_sep>/server/src/app.controller.ts
import { Controller, Get, Param, Res } from '@nestjs/common'
import { AppService } from './app.service'
import { Response } from 'express'
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('uploads/:fileName')
getFile(@Param() param: { fileName: string }, @Res() res: Response): void {
res.sendFile(param.fileName, { root: 'src/uploads' })
}
}
<file_sep>/client/src/app/views/network/network.component.ts
import { Component, OnInit } from '@angular/core'
@Component({
selector: 'app-network',
templateUrl: './network.component.html',
styleUrls: ['./network.component.less'],
})
export class NetworkComponent implements OnInit {
constructor() {}
activeTab: string = 'invitations'
activateTab(tab: string): void {
console.log(tab)
this.activeTab = tab
}
ngOnInit(): void {}
}
<file_sep>/client/src/app/store/my-profile/find-users/find-users.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store'
import { findUsersNode, FindUsersState } from './find-users.reducer'
export const findUsersFeatureSelector = createFeatureSelector<FindUsersState>(
findUsersNode,
)
export const otherUsersSelector = createSelector(
findUsersFeatureSelector,
state => state.users,
)
<file_sep>/client/src/app/store/index.ts
import { Action, ActionReducerMap, MetaReducer } from '@ngrx/store'
import { environment } from '../../environments/environment'
import { authNode, authReducer, AuthState } from './auth/auth.reducer'
import { postNode, postReducer, PostState } from './posts/post.reducer'
import {
myProfileNode,
myProfileReducer,
MyProfileState,
} from './my-profile/my-profile.reducer'
import {
profileNode,
profileReducer,
ProfileState,
} from './profile/profile.reducer'
import {
findUsersNode,
findUsersReducer,
FindUsersState,
} from './my-profile/find-users/find-users.reducer'
import { chatNode, chatReducer, ChatState } from './chat/chat.reducer'
export interface State {
[authNode]: AuthState
[chatNode]: ChatState
[myProfileNode]: MyProfileState
[postNode]: PostState
[profileNode]: ProfileState
[findUsersNode]: FindUsersState
}
export const reducers: ActionReducerMap<State> = {
[authNode]: authReducer,
// @ts-ignore
[chatNode]: chatReducer,
// @ts-ignore
[postNode]: postReducer,
// @ts-ignore
[myProfileNode]: myProfileReducer,
// @ts-ignore
[profileNode]: profileReducer,
// @ts-ignore
[findUsersNode]: findUsersReducer,
}
export const metaReducers: MetaReducer<State>[] = !environment.production
? []
: []
<file_sep>/client/src/app/store/auth/auth.reducer.ts
import {
AuthActions,
LOG_OUT_ACTION_TYPE,
SIGN_IN_ACTION_TYPE,
} from './auth.actions'
export const authNode = 'auth'
export interface AuthState {
authStatus: boolean
}
const initialState: AuthState = {
authStatus: false,
}
export const authReducer = (state = initialState, action: AuthActions) => {
switch (action.type) {
case SIGN_IN_ACTION_TYPE:
return {
...state,
authStatus: true,
}
case LOG_OUT_ACTION_TYPE:
return {
...state,
authStatus: false,
}
default:
return state
}
}
<file_sep>/client/src/app/components/network/users-list/users-list-mdl/users-list-mdl.component.ts
import {
Component,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output,
} from '@angular/core'
import { Subscription } from 'rxjs'
import { IUser } from '../../../../interfaces/user'
@Component({
selector: 'app-users-list-mdl',
templateUrl: './users-list-mdl.component.html',
styleUrls: ['../users-list.component.less'],
})
export class UsersListMdlComponent implements OnInit, OnDestroy {
constructor() {}
private subs: Subscription[] = []
private set sub(s: Subscription) {
this.subs.push(s)
}
@Input() connections: { user: IUser; date: number }[] = []
@Input() isMyProfile: boolean = false
@Output() action: EventEmitter<{
action: string
userId: number
}> = new EventEmitter<{ action: string; userId: number }>()
removeConnection(userId: number): void {
this.action.emit({ action: 'remove', userId })
}
ngOnInit(): void {}
ngOnDestroy(): void {
this.subs.forEach(sub => sub.unsubscribe())
}
}
<file_sep>/client/src/app/plugins/getAverageColor.ts
function draw(
img: HTMLImageElement,
): {
ctx: CanvasRenderingContext2D
width: number
height: number
} {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
canvas.width = img.width
canvas.height = img.height
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(img, 0, 0, img.width, img.height)
return {
ctx,
width: canvas.width,
height: canvas.height,
}
}
function getColors(canvData: {
ctx: CanvasRenderingContext2D
width: number
height: number
}) {
const { ctx, width, height } = canvData
const colors = {}
let col, pixels, r, g, b, a
r = g = b = a = 0
pixels = ctx.getImageData(0, 0, width, height)
for (let i = 0, data = pixels.data; i < data.length; i += 4) {
r = data[i]
g = data[i + 1]
b = data[i + 2]
a = data[i + 3] // alpha
// skip pixels >50% transparent
if (a < 255 / 2) continue
col = rgbToHex(r, g, b)
if (!colors[col]) colors[col] = 0
colors[col]++
}
return colors
}
function rgbToHex(r: number, g: number, b: number): string {
if (r > 255 || g > 255 || b > 255)
throw new Error('Invalid color component')
return ((r << 16) | (g << 8) | b).toString(16)
}
<file_sep>/client/src/app/store/my-profile/edit-profile/edit-profile.actions.ts
import { Action } from '@ngrx/store'
export const SET_SUCCESS_AD_ALERT_ACTION_TYPE =
'[Edit Profile] Set success AD alert type'
export const SET_SUCCESS_LS_ALERT_ACTION_TYPE =
'[Edit Profile] Set success LS alert type'
export const SET_ERROR_AD_ALERT_ACTION_TYPE =
'[Edit Profile] Set error AD alert type'
export const SET_ERROR_LS_ALERT_ACTION_TYPE =
'[Edit Profile] Set error LS alert type'
export class SetSuccessADAlert implements Action {
readonly type = SET_SUCCESS_AD_ALERT_ACTION_TYPE
constructor(
public payload: {
type: string
content: string
},
) {}
}
export class SetSuccessLSAlert implements Action {
readonly type = SET_SUCCESS_LS_ALERT_ACTION_TYPE
constructor(
public payload: {
type: string
content: string
},
) {}
}
export class SetErrorADAlert implements Action {
readonly type = SET_ERROR_AD_ALERT_ACTION_TYPE
constructor(
public payload: {
type: string
content: string
},
) {}
}
export class SetErrorLSAlert implements Action {
readonly type = SET_ERROR_LS_ALERT_ACTION_TYPE
constructor(
public payload: {
type: string
content: string
},
) {}
}
export type EditProfileActions =
| SetSuccessADAlert
| SetSuccessLSAlert
| SetErrorADAlert
| SetErrorLSAlert
<file_sep>/client/src/app/pipes/masked-email/masked-email.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'
@Pipe({
name: 'maskedEmail',
})
export class MaskedEmailPipe implements PipeTransform {
transform(value: string, ...args: unknown[]): string {
const [startEmail, endEmail] = value.split('@')
const maskedStart = `${startEmail[0] + startEmail[1]}•••`
return maskedStart + '@' + endEmail
}
}
<file_sep>/README.md
"# linkedin-redesign"
<file_sep>/client/src/app/components/network/users-list/users-list-nwk/users-list-nwk.component.ts
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output,
ViewChild,
} from '@angular/core'
import { EMPTY, fromEvent, Subscription } from 'rxjs'
import { debounceTime, map, switchMap } from 'rxjs/operators'
import { IUser } from '../../../../interfaces/user'
import { environment } from '../../../../../environments/environment'
// @ts-ignore
import { HystModal } from '../../../../plugins/hystModal_'
import { ProfileService } from '../../../../services/profile.service'
@Component({
selector: 'app-users-list-nwk',
templateUrl: './users-list-nwk.component.html',
styleUrls: ['../users-list.component.less'],
})
export class UsersListNwkComponent implements OnInit, OnDestroy, AfterViewInit {
constructor(private profileService: ProfileService) {}
private subs: Subscription[] = []
private set sub(s: Subscription) {
this.subs.push(s)
}
// @ts-ignore
private searchSub: Subscription
currentUserId: number = -1
@Input() connections: { user: IUser; date: number }[] = []
@Input() isMyProfile: boolean = false
@Input() myProfileId: number = -1
@Output() action = new EventEmitter<{
action: string
userId: number
message?: string
}>()
@ViewChild('searchConnections') search: ElementRef | null = null
otherUsers: IUser[] = []
isMyConnection(
connections: { user: IUser; date: number }[],
userId: number,
): boolean {
return !!connections.find(con => con.user.id === userId)
}
isMySentConnection(user: IUser): boolean {
return !!user.info.receivedConnections.find(
u => u.userId === this.myProfileId,
)
}
isMyIncomingConnection(user: IUser): boolean {
return !!user.info.sentConnections.find(
u => u.userId === this.myProfileId,
)
}
sendConnection(userId: number, message: string): void {
this.action.emit({ action: 'send', userId, message })
this.updateUsers()
}
acceptConnection(userId: number): void {
this.action.emit({ action: 'accept', userId })
this.updateUsers()
}
cancelConnection(userId: number): void {
this.action.emit({ action: 'cancel', userId })
this.updateUsers()
}
declineConnection(userId: number): void {
this.action.emit({ action: 'decline', userId })
this.updateUsers()
}
removeConnection(userId: number): void {
this.action.emit({ action: 'remove', userId })
this.updateUsers()
}
updateUsers(): void {
this.searchSub?.unsubscribe()
setTimeout(() => {
this.searchSub = this.profileService
.findUsersByFullName(this.search?.nativeElement.value)
.subscribe(res => {
this.otherUsers = res.filter(
user =>
user.id !== this.myProfileId &&
!user.info.connections.find(
connection =>
connection.userId === this.myProfileId,
), // &&
// !user.info.sentConnections.find(connection => connection.userId === this.myProfileId) &&
// !user.info.receivedConnections.find(connection => connection.userId === this.myProfileId)
)
console.log(this.otherUsers)
})
}, 300)
}
ngAfterViewInit(): void {
if (!this.search) console.log('Не нашел поиск')
this.sub = fromEvent<InputEvent>(this.search?.nativeElement, 'input')
.pipe(
debounceTime(500),
map((ev: InputEvent) => (ev.target as HTMLInputElement).value),
switchMap(value => {
if (value === '') return []
return this.profileService.findUsersByFullName(value)
}),
)
.subscribe((res: IUser[]) => {
this.otherUsers = res.filter(
user =>
user.id !== this.myProfileId &&
!user.info.connections.find(
connection =>
connection.userId === this.myProfileId,
), // &&
// !user.info.sentConnections.find(connection => connection.userId === this.myProfileId) &&
// !user.info.receivedConnections.find(connection => connection.userId === this.myProfileId)
)
console.log(this.otherUsers)
})
}
ngOnInit(): void {
const sendConnectionModal = new HystModal({
linkAttributeName: 'data-hystmodal',
})
}
ngOnDestroy(): void {
this.subs.forEach(sub => sub.unsubscribe())
}
}
<file_sep>/server/src/chats/chats.controller.ts
import { Controller, Get, HttpStatus, Param, Query, Res } from '@nestjs/common'
import { Response } from 'express'
import { ChatsService } from './chats.service'
@Controller('chats')
export class ChatsController {
constructor(private chatsService: ChatsService) {}
@Get('find/all')
async getChats(@Res() res: Response): Promise<void> {
const chats = await this.chatsService.getChats()
if (!chats) return
if (chats[0]) res.status(HttpStatus.OK).send({ chats })
if (!chats[0]) res.status(HttpStatus.NOT_FOUND).send({ error: `No chat was found` })
}
@Get('find/:id')
async getChat(@Param() param: { id: string }, @Res() res: Response): Promise<void> {
const chat = await this.chatsService.getChat(+param.id)
if (chat) res.status(HttpStatus.OK).send({ chat })
if (!chat) res.status(HttpStatus.NOT_FOUND).send({ error: `chat with id: ${param.id} not found` })
}
@Get('delete/all')
async deleteAll() {
await this.chatsService.deleteAll()
}
@Get('delete/:id')
async deleteOne(@Param() param: { id: string }) {
await this.chatsService.deleteOne(+param.id)
}
}
<file_sep>/client/src/app/views/profile/edit-profile/edit-components/edit-personal-data/edit-personal-data.component.ts
import {
Component,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
SimpleChanges,
} from '@angular/core'
import { FormControl, FormGroup, Validators } from '@angular/forms'
import { ProfileService } from '../../../../../services/profile.service'
import { IBuffer } from '../../../../../interfaces/buffer'
@Component({
selector: 'app-edit-personal-data',
templateUrl: './edit-personal-data.component.html',
styleUrls: ['./edit-personal-data.component.less'],
})
export class EditPersonalDataComponent implements OnInit, OnChanges {
constructor() {}
@Input() firstName: string = ''
@Input() lastName: string = ''
@Input() DOB: number = 0
@Input() gender: string = ''
@Input() avatar: string | IBuffer = ''
@Input() editStatus: { status: string; message: string } | null = null
@Output() saveChanges = new EventEmitter()
@Output() changeAvatar = new EventEmitter()
editProfileDataForm = new FormGroup({
firstName: new FormControl(this.firstName, [
Validators.required,
Validators.minLength(2),
]),
lastName: new FormControl(this.lastName, [Validators.required]),
dateOfBirth: new FormControl(
new Date(this.DOB).toJSON().split('T')[0],
[Validators.required],
),
})
selectedGender: string = ''
genderIsRequiredError: boolean = false
changeAvatarMenu: HTMLElement | null = null
toggleChangeAvatarMenu(menu: HTMLElement): void {
menu.classList.toggle('transparent')
menu.classList.toggle('hidden')
this.changeAvatarMenu = menu
}
hideChangeAvatarMenu(menu: HTMLElement): void {
menu.classList.add('transparent')
menu.classList.add('hidden')
}
selectOnChange(option: string): void {
this.selectedGender = option
}
changeAvatarHandler(e: Event): void {
const target = e.target as HTMLInputElement
const files = target.files as FileList
this.changeAvatar.emit({ type: 'change', file: files.item(0) })
target.value = ''
if (this.changeAvatarMenu)
this.toggleChangeAvatarMenu(this.changeAvatarMenu)
}
deleteAvatarHandler(): void {
this.changeAvatar.emit({ type: 'delete' })
if (this.changeAvatarMenu)
this.toggleChangeAvatarMenu(this.changeAvatarMenu)
}
onSubmit(): void {
if (this.selectedGender === 'Indicate your gender') {
this.genderIsRequiredError = true
return
}
this.genderIsRequiredError = false
if (this.editProfileDataForm.valid) {
this.saveChanges.emit({
...this.editProfileDataForm.value,
gender: this.selectedGender.trim(),
})
}
}
ngOnInit(): void {}
ngOnChanges(changes: SimpleChanges): void {
if (
changes.hasOwnProperty('firstName') &&
changes.hasOwnProperty('lastName') &&
changes.hasOwnProperty('DOB')
) {
this.editProfileDataForm.setValue({
firstName: changes.firstName.currentValue,
lastName: changes.lastName.currentValue,
dateOfBirth: new Date(changes.DOB.currentValue)
.toJSON()
.split('T')[0],
})
}
}
}
<file_sep>/client/src/app/store/chat/chat.effects.ts
import { Injectable } from '@angular/core'
import { Actions, Effect, ofType } from '@ngrx/effects'
import { EMPTY, Observable } from 'rxjs'
import {
ChatActions,
LOAD_CHATS,
LoadChatsAction,
LoadChatsSuccessAction,
} from './chat.actions'
import { catchError, map, switchMap } from 'rxjs/operators'
import { environment } from '../../../environments/environment'
import { HttpClient } from '@angular/common/http'
import { IChat } from '../../interfaces/chat/chat'
import { IUser } from '../../interfaces/user'
import { ProfileService } from '../../services/profile.service'
import { Chat } from './chat.reducer'
@Injectable()
export class ChatEffects {
constructor(
private actions$: Actions,
private http: HttpClient,
private profileService: ProfileService,
) {}
@Effect()
loadChats$(): Observable<ChatActions> {
console.log('loading chats...')
return this.actions$.pipe(
ofType(LOAD_CHATS),
switchMap((action: LoadChatsAction) => {
const { profileId } = action.payload
return this.http
.get<{ chats: IChat[] }>(
`${environment.server_url}/chats/find/all`,
)
.pipe(
switchMap(resp => {
return this.http
.get<{ user: IUser }>(
`${environment.server_url}/users/find/${profileId}`,
)
.pipe(
switchMap(res => {
const connections =
res.user.info.connections
return this.profileService.getConnectionsById$(
connections,
)
}),
map((res: { user: IUser }[]) => {
const chats: Chat[] = resp.chats
.filter(chat =>
chat.users.some(
u => u.userId === profileId,
),
)
.map(chat => {
const buddyId =
chat.users.find(
u =>
u.userId !==
profileId,
)?.userId ?? -1
const buddy = res.find(
u => u.user.id === buddyId,
)?.user as IUser
return {
chat,
buddy,
}
})
console.log('chats:', chats)
return chats
}),
)
}),
map(
(chats: Chat[]) =>
new LoadChatsSuccessAction({ chats }),
),
catchError((res: { error: string }) => {
console.log(res.error)
return EMPTY
}),
)
}),
)
}
// @Effect()
// getCurrentBuddy$(): Observable<ChatActions> {
// return this.actions$.pipe(
// ofType(GET_CURRENT_BUDDY),
// switchMap((action: GetCurrentBuddyAction) => {
// return this.http.get<{ user: IUser }>(`${environment.server_url}/users/find/${action.payload.buddyId}`)
// .pipe(
// map(res => new GetCurrentBuddySuccessAction({ buddy: res.user })),
// catchError(err => {
// console.warn(err)
// return EMPTY
// })
// )
// })
// )
// }
//
// @Effect()
// getCurrentChatId$(): Observable<ChatActions> {
// return this.actions$.pipe(
// ofType(GET_CURRENT_CHAT),
// switchMap((action: GetCurrentChatAction) => {
// const { profileId, buddyId } = action.payload
// return this.http.get<{ chats: IChat[] }>(`${environment.server_url}/chats/find/all`)
// .pipe(
// map(res => {
// return res.chats.filter(chat => {
// return chat.users.find(user => user.userId === profileId)
// && chat.users.find(user => user.userId === buddyId)
// })[0]
// }),
// map(chat => {
// if (chat) return new GetCurrentChatSuccessAction({ chat })
// return new GetCurrentChatFailedAction({ error: 'something went wrong' })
// }),
// catchError(err => {
// console.warn(err)
// return EMPTY
// })
// )
// })
// )
// }
}
<file_sep>/client/src/app/components/select/select.component.ts
import {
Component,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
SimpleChanges,
} from '@angular/core'
import { IsdCountryCode } from '../../../../../server/src/interfaces/auth/isdCountryCode'
@Component({
selector: 'app-select',
templateUrl: './select.component.html',
styleUrls: ['./select.component.less'],
})
export class SelectComponent implements OnInit, OnChanges {
constructor() {}
@Input() options: string[] = []
@Input() selectedByDefault: string = ''
@Input() error: boolean = false
@Output() onChange = new EventEmitter<string>()
selected: string = ''
toggleOptions(el: HTMLElement): void {
el.classList.toggle('show')
}
closeOptions(el: HTMLElement): void {
el.classList.remove('show')
}
changeSelected(option: string, select: HTMLElement): void {
this.closeOptions(select)
if (this.selected === option) return
this.selected = option
this.onChange.emit(option)
}
ngOnInit(): void {
this.onChange.emit(this.selectedByDefault)
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.hasOwnProperty('selectedByDefault'))
this.onChange.emit(changes.selectedByDefault.currentValue)
}
}
<file_sep>/client/src/app/views/network/network-side/network-side.component.ts
import { Component, EventEmitter, OnInit, Output } from '@angular/core'
@Component({
selector: 'app-network-side',
templateUrl: './network-side.component.html',
styleUrls: ['./network-side.component.less'],
})
export class NetworkSideComponent implements OnInit {
constructor() {}
@Output() activateItem: EventEmitter<string> = new EventEmitter<string>()
activeMenuItem: string = ''
activateListItem(e: MouseEvent, list: HTMLElement): void {
if (e.target === list) return
const element = (e.target as HTMLElement).closest('.menu__item')
if (element) {
const listItems = Array.from(list.children)
listItems.forEach(el => el.classList.remove('active'))
element.classList.add('active')
this.activeMenuItem =
element.querySelector('.title')?.textContent ?? ''
this.activateItem.emit(this.activeMenuItem.toLowerCase().trim())
}
}
ngOnInit(): void {}
}
<file_sep>/client/src/app/store/profile/profile.reducer.ts
import {
ACCEPT_CONNECTION_SUCCESS_ACTION_TYPE,
DECLINE_CONNECTION_SUCCESS_ACTION_TYPE,
GET_PROFILE_INFO_SUCCESS_ACTION_TYPE,
ProfileActions,
REMOVE_CONNECTION_SUCCESS_ACTION_TYPE,
SEND_CONNECTION_SUCCESS_ACTION_TYPE,
} from './profile.actions'
import { IFile } from '../../interfaces/file'
import {IContact} from "../../interfaces/contact";
import {IProject} from "../../interfaces/project";
import {IExp} from "../../interfaces/exp";
import {IUniversity} from "../../interfaces/university";
export const profileNode = 'profile'
export interface ProfileState {
id: number
firstName: string
lastName: string
email: string
phone: string
password: string
info: {
isOnline: boolean
description: string
views: {
current: number
prev: number
}
connections: { userId: number; date: number }[]
sentConnections: { userId: number; message: string }[]
receivedConnections: { userId: number /* message: string */ }[]
posts: {
postId: number
}[]
avatar: IFile | null
profileHeaderBg: IFile | null
dateOfBirth: number
profession: string
locality: {
country: string
city: string
}
contactInfo: IContact[]
projects: IProject[]
experience: IExp[]
education: IUniversity[]
}
}
const initialState: ProfileState = {
id: -1,
firstName: '',
lastName: '',
email: '',
phone: '',
password: '',
info: {
isOnline: false,
description: '',
views: {
current: 0,
prev: 0,
},
connections: [],
sentConnections: [],
receivedConnections: [],
posts: [],
avatar: null,
profileHeaderBg: null,
dateOfBirth: 0,
profession: '',
locality: {
country: '',
city: '',
},
contactInfo: [],
projects: [],
experience: [],
education: [],
},
}
export const profileReducer = (
state: ProfileState = initialState,
action: ProfileActions,
) => {
switch (action.type) {
case GET_PROFILE_INFO_SUCCESS_ACTION_TYPE:
return action.payload.profile
case SEND_CONNECTION_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
receivedConnections: [
...state.info.receivedConnections,
{ userId: action.payload.senderId },
],
},
}
case ACCEPT_CONNECTION_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
connections: [
...state.info.connections,
{
userId: action.payload.userId,
date: action.payload.date,
},
],
sentConnections: state.info.sentConnections.filter(
user => user.userId !== action.payload.userId,
),
},
}
case DECLINE_CONNECTION_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
receivedConnections: state.info.receivedConnections.filter(
user => user.userId !== action.payload.senderId,
),
},
}
case REMOVE_CONNECTION_SUCCESS_ACTION_TYPE:
return {
...state,
info: {
...state.info,
connections: state.info.connections.filter(
user => user.userId !== action.payload.senderId,
),
},
}
default:
return state
}
}
<file_sep>/client/src/app/views/chat/chat.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'
import {Observable, Subject} from 'rxjs'
import { select, Store } from '@ngrx/store'
import { myProfileIdSelector } from '../../store/my-profile/my-profile.selectors'
import { ChatService } from '../../services/chat.service'
import { MyProfileState } from '../../store/my-profile/my-profile.reducer'
import { Chat, ChatState } from '../../store/chat/chat.reducer'
import {
LoadChatsAction,
ChangeCurrentChatAction,
} from '../../store/chat/chat.actions'
import { EntityState } from '@ngrx/entity'
import {takeUntil} from "rxjs/operators";
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.less'],
})
export class ChatComponent implements OnInit, OnDestroy {
constructor(
private chatService: ChatService,
private store$: Store<MyProfileState | ChatState | EntityState<Chat>>,
) {}
unsub$ = new Subject()
profileId: number = -1
activeChat: number = -1
profileId$: Observable<number> = this.store$.pipe(
select(myProfileIdSelector),
)
readInterval: number = -1
sideActionsHandler(action: { type: string; data: any }): void {
switch (action.type) {
case 'changeActiveChat':
if (this.activeChat === action.data) return
this.activeChat = action.data
this.store$.dispatch(
new ChangeCurrentChatAction({ id: action.data }),
)
this.store$.dispatch(
new LoadChatsAction({ profileId: this.profileId }),
)
// clearInterval(this.readInterval)
this.chatService.readMessages(this.profileId, action.data)
// this.readInterval = setInterval(this.chatService.readMessages, 1000, this.profileId, this.activeChat)
this.chatService.connect()
break
default:
break
}
}
ngOnInit(): void {
this.profileId$.pipe(takeUntil(this.unsub$)).subscribe(id => {
this.profileId = id
})
setTimeout(() => {
this.store$.dispatch(
new LoadChatsAction({ profileId: this.profileId }),
)
}, 100)
}
ngOnDestroy(): void {
this.unsub$.next()
this.unsub$.complete()
}
}
<file_sep>/client/src/app/store/posts/post.actions.ts
import { Action } from '@ngrx/store'
import { PostDto } from '../../dto/post.dto'
import { IPost } from '../../interfaces/post/post'
import { CommentDto } from '../../dto/comment.dto'
/* TYPES */
/* POSTS TYPES */
export const POST_CREATE_ACTION_TYPE = '[POST] Create'
export const POST_CREATE_SUCCESS_ACTION_TYPE = '[POST] Create success'
export const POST_CREATE_FAILED_ACTION_TYPE = '[POST] Create failed'
export const POST_EDIT_ACTION_TYPE = '[POST] Edit'
export const POST_EDIT_SUCCESS_ACTION_TYPE = '[POST] Edit success'
export const POST_EDIT_FAILED_ACTION_TYPE = '[POST] Edit failed'
export const POST_GET_ACTION_TYPE = '[POST] Get'
export const POST_GET_SUCCESS_ACTION_TYPE = '[POST] Get success'
export const POST_GET_FAILED_ACTION_TYPE = '[POST] Get failed'
export const POST_REMOVE_ACTION_TYPE = '[POST] Remove'
export const POST_REMOVE_SUCCESS_ACTION_TYPE = '[POST] Remove success'
export const POST_REMOVE_FAILED_ACTION_TYPE = '[POST] Remove failed'
export const POST_LIKE_ACTION_TYPE = '[POST] Like'
export const POST_LIKE_SUCCESS_ACTION_TYPE = '[POST] Like success'
export const POST_LIKE_FAILED_ACTION_TYPE = '[POST] Like failed'
export const POST_DONT_LIKE_ACTION_TYPE = '[POST] Dont like'
export const POST_DONT_LIKE_SUCCESS_ACTION_TYPE = '[POST] Dont like success'
export const POST_DONT_LIKE_FAILED_ACTION_TYPE = '[POST] Dont like failed'
export const SORTING_POSTS_ACTION_TYPE = '[POST] sorting posts'
/* COMMENTS TYPES */
export const COMMENT_CREATE_ACTION_TYPE = '[COMMENT] Create'
export const COMMENT_CREATE_SUCCESS_ACTION_TYPE = '[COMMENT] Create success'
export const COMMENT_CREATE_FAILED_ACTION_TYPE = '[COMMENT] Create failed'
export const COMMENT_EDIT_ACTION_TYPE = '[COMMENT] Edit'
export const COMMENT_EDIT_SUCCESS_ACTION_TYPE = '[COMMENT] Edit success'
export const COMMENT_EDIT_FAILED_ACTION_TYPE = '[COMMENT] Edit failed'
export const COMMENT_GET_ACTION_TYPE = '[COMMENT] Get'
export const COMMENT_GET_SUCCESS_ACTION_TYPE = '[COMMENT] Get success'
export const COMMENT_GET_FAILED_ACTION_TYPE = '[COMMENT] Get failed'
export const COMMENT_REMOVE_ACTION_TYPE = '[COMMENT] Remove'
export const COMMENT_REMOVE_SUCCESS_ACTION_TYPE = '[COMMENT] Remove success'
export const COMMENT_REMOVE_FAILED_ACTION_TYPE = '[COMMENT] Remove failed'
export const COMMENT_LIKE_ACTION_TYPE = '[COMMENT] Like'
export const COMMENT_LIKE_SUCCESS_ACTION_TYPE = '[COMMENT] Like success'
export const COMMENT_LIKE_FAILED_ACTION_TYPE = '[COMMENT] Like failed'
export const COMMENT_DONT_LIKE_ACTION_TYPE = '[COMMENT] Dont like'
export const COMMENT_DONT_LIKE_SUCCESS_ACTION_TYPE =
'[COMMENT] Dont like success'
export const COMMENT_DONT_LIKE_FAILED_ACTION_TYPE = '[COMMENT] Dont like failed'
export const POST_COMMENTS_OPEN_ACTION_TYPE = '[POST] Comments open'
export const POST_COMMENTS_CLOSE_ACTION_TYPE = '[POST] Comments close'
/* POSTS */
export class PostCreateAction implements Action {
readonly type = POST_CREATE_ACTION_TYPE
constructor(public payload: PostDto) {}
}
export class PostCreateSuccessAction implements Action {
readonly type = POST_CREATE_SUCCESS_ACTION_TYPE
constructor(
public payload: {
post: IPost
},
) {}
}
export class PostCreateFailedAction implements Action {
readonly type = POST_CREATE_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class PostEditAction implements Action {
readonly type = POST_EDIT_ACTION_TYPE
}
export class PostEditSuccessAction implements Action {
readonly type = POST_EDIT_SUCCESS_ACTION_TYPE
constructor(public payload: {}) {}
}
export class PostEditFailedAction implements Action {
readonly type = POST_EDIT_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class PostGetAction implements Action {
readonly type = POST_GET_ACTION_TYPE
constructor(
public payload: {
id: string | number
},
) {}
}
export class PostGetSuccessAction implements Action {
readonly type = POST_GET_SUCCESS_ACTION_TYPE
constructor(
public payload: {
posts: IPost[]
},
) {}
}
export class PostGetFailedAction implements Action {
readonly type = POST_GET_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class PostRemoveAction implements Action {
readonly type = POST_REMOVE_ACTION_TYPE
}
export class PostRemoveSuccessAction implements Action {
readonly type = POST_REMOVE_SUCCESS_ACTION_TYPE
constructor(public payload: {}) {}
}
export class PostRemoveFailedAction implements Action {
readonly type = POST_REMOVE_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class PostLikeAction implements Action {
readonly type = POST_LIKE_ACTION_TYPE
constructor(
public payload: {
postId: number
userId: number
},
) {}
}
export class PostLikeSuccessAction implements Action {
readonly type = POST_LIKE_SUCCESS_ACTION_TYPE
constructor(
public payload: {
postId: number
userId: number
},
) {}
}
export class PostLikeFailedAction implements Action {
readonly type = POST_LIKE_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class PostDontLikeAction implements Action {
readonly type = POST_DONT_LIKE_ACTION_TYPE
constructor(
public payload: {
postId: number
userId: number
},
) {}
}
export class PostDontLikeSuccessAction implements Action {
readonly type = POST_DONT_LIKE_SUCCESS_ACTION_TYPE
constructor(
public payload: {
postId: number
userId: number
},
) {}
}
export class PostDontLikeFailedAction implements Action {
readonly type = POST_DONT_LIKE_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class PostCommentsOpenAction implements Action {
readonly type = POST_COMMENTS_OPEN_ACTION_TYPE
constructor(
public payload: {
postId: number
},
) {}
}
export class PostCommentsCloseAction implements Action {
readonly type = POST_COMMENTS_CLOSE_ACTION_TYPE
constructor(
public payload: {
postId: number
},
) {}
}
export class SortingPostsAction implements Action {
readonly type = SORTING_POSTS_ACTION_TYPE
constructor(public payload: { sortType: string }) {}
}
/* COMMENTS */
export class CommentCreateAction implements Action {
readonly type = COMMENT_CREATE_ACTION_TYPE
constructor(
public payload: {
postId: number
commentInfo: CommentDto
},
) {}
}
export class CommentCreateSuccessAction implements Action {
readonly type = COMMENT_CREATE_SUCCESS_ACTION_TYPE
constructor(public payload: {}) {}
}
export class CommentCreateFailedAction implements Action {
readonly type = COMMENT_CREATE_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class CommentEditAction implements Action {
readonly type = COMMENT_EDIT_ACTION_TYPE
}
export class CommentEditSuccessAction implements Action {
readonly type = COMMENT_EDIT_SUCCESS_ACTION_TYPE
constructor(public payload: {}) {}
}
export class CommentEditFailedAction implements Action {
readonly type = COMMENT_EDIT_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class CommentGetAction implements Action {
readonly type = COMMENT_GET_ACTION_TYPE
constructor(payload: { id: string | number }) {}
}
export class CommentGetSuccessAction implements Action {
readonly type = COMMENT_GET_SUCCESS_ACTION_TYPE
constructor(public payload: {}) {}
}
export class CommentGetFailedAction implements Action {
readonly type = COMMENT_GET_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class CommentRemoveAction implements Action {
readonly type = COMMENT_REMOVE_ACTION_TYPE
}
export class CommentRemoveSuccessAction implements Action {
readonly type = COMMENT_REMOVE_SUCCESS_ACTION_TYPE
constructor(public payload: {}) {}
}
export class CommentRemoveFailedAction implements Action {
readonly type = COMMENT_REMOVE_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class CommentLikeAction implements Action {
readonly type = COMMENT_LIKE_ACTION_TYPE
}
export class CommentLikeSuccessAction implements Action {
readonly type = COMMENT_LIKE_SUCCESS_ACTION_TYPE
constructor(public payload: {}) {}
}
export class CommentLikeFailedAction implements Action {
readonly type = COMMENT_LIKE_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export class CommentDontLikeAction implements Action {
readonly type = COMMENT_DONT_LIKE_ACTION_TYPE
}
export class CommentDontLikeSuccessAction implements Action {
readonly type = COMMENT_DONT_LIKE_SUCCESS_ACTION_TYPE
constructor(public payload: {}) {}
}
export class CommentDontLikeFailedAction implements Action {
readonly type = COMMENT_DONT_LIKE_FAILED_ACTION_TYPE
constructor(
public payload: {
err: any
},
) {}
}
export type PostActions =
| PostCreateSuccessAction
| PostCreateFailedAction
| PostEditSuccessAction
| PostEditFailedAction
| PostGetSuccessAction
| PostGetFailedAction
| PostRemoveSuccessAction
| PostRemoveFailedAction
| PostLikeSuccessAction
| PostLikeFailedAction
| PostDontLikeSuccessAction
| PostDontLikeFailedAction
| PostCommentsOpenAction
| PostCommentsCloseAction
| SortingPostsAction
| CommentCreateSuccessAction
| CommentCreateFailedAction
| CommentEditSuccessAction
| CommentEditFailedAction
| CommentGetSuccessAction
| CommentGetFailedAction
| CommentRemoveSuccessAction
| CommentRemoveFailedAction
| CommentLikeSuccessAction
| CommentLikeFailedAction
| CommentDontLikeSuccessAction
| CommentDontLikeFailedAction
<file_sep>/client/src/app/views/auth/registration/registration.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core'
import { FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms'
import { environment } from 'src/environments/environment'
import { AuthService } from 'src/app/services/auth.service'
import {debounceTime, takeUntil} from 'rxjs/operators'
import { IsdCountryCode } from '../../../../../../server/src/interfaces/auth/isdCountryCode'
import { RegistrationForm } from '../../../../../../server/src/interfaces/auth/registration'
import { IAuthError } from '../../../../../../server/src/interfaces/auth/authError'
import { Router } from '@angular/router'
import { Subject } from 'rxjs'
@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrls: ['./registration.component.less', '../auth.styles.less'],
})
export class RegistrationComponent implements OnInit, OnDestroy {
constructor(private authService: AuthService, private router: Router) {}
unsub$ = new Subject()
IsdCountryCodes: IsdCountryCode[] | undefined
repeatPasswordError = false
backendError = ''
registrationForm = new FormGroup({
firstName: new FormControl('', [
Validators.minLength(2),
Validators.required,
]),
lastName: new FormControl('', [
Validators.minLength(2),
Validators.required,
]),
email: new FormControl('', [Validators.email, Validators.required]),
phone: new FormControl('', [
Validators.required,
Validators.pattern('[- +()0-9]{5,}'),
]),
password: new FormControl('', [
Validators.minLength(6),
Validators.required,
]),
passwordRepeat: new FormControl('', [
Validators.minLength(6),
Validators.required,
]),
})
onSubmit(): void {
const form: RegistrationForm = this.registrationForm.value
if (form.password === form.passwordRepeat) {
this.repeatPasswordError = false
if (this.registrationForm.valid) {
this.authService
.signUpRequest(this.registrationForm.value)
.subscribe(
res => {
console.log(res)
this.router.navigate(['/signin'], {
queryParams: {
message:
'You have successfully registered and you can log in',
},
})
},
err => (this.backendError = err.error.error),
)
}
} else {
this.repeatPasswordError = true
}
}
ngOnInit(): void {
this.authService
.getIsdCountryCode()
.pipe(takeUntil(this.unsub$))
.subscribe(val => (this.IsdCountryCodes = val))
this.registrationForm.valueChanges
.pipe(debounceTime(600))
.subscribe(form => {
if (form.password === form.passwordRepeat)
this.repeatPasswordError = false
else this.repeatPasswordError = true
})
}
ngOnDestroy(): void {
this.unsub$.next()
this.unsub$.complete()
}
}
<file_sep>/client/src/app/store/auth/auth.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store'
import { authNode, AuthState } from './auth.reducer'
export const authFeatureSelector = createFeatureSelector<AuthState>(authNode)
export const authStatusSelector = createSelector(
authFeatureSelector,
(state: AuthState) => state.authStatus,
)
<file_sep>/client/src/app/store/chat/chat.actions.ts
import { Action } from '@ngrx/store'
import { IMessage } from '../../interfaces/chat/message'
import { IChat } from '../../interfaces/chat/chat'
import { IUser } from '../../interfaces/user'
import { Chat } from './chat.reducer'
import { IMessages } from '../../interfaces/chat/messages'
import { Update } from '@ngrx/entity'
export const RECEIVE_MESSAGE = '[CHAT] receive msg'
export const RECEIVE_MESSAGE_SUCCESS = '[CHAT] receive msg success'
export const READ_MESSAGES = '[CHAT] read messages'
export const LOAD_CHATS = '[CHAT] load chats'
export const LOAD_CHATS_SUCCESS = '[CHAT] load chats success'
export const CHANGE_CURRENT_CHAT = '[CHAT] change current chat'
export const GET_CURRENT_BUDDY = '[CHAT] get current buddy'
export const GET_CURRENT_BUDDY_SUCCESS = '[CHAT] get current buddy success'
export const GET_CURRENT_CHAT = '[CHAT] get current chat'
export const GET_CURRENT_CHAT_SUCCESS = '[CHAT] get current chat success'
export const GET_CURRENT_CHAT_FAILED = '[CHAT] get current chat failed'
export class ReceiveMessageAction implements Action {
readonly type = RECEIVE_MESSAGE
constructor(
public payload: {
chatId: number
messages: IMessages[]
},
) {}
}
export class LoadChatsAction implements Action {
readonly type = LOAD_CHATS
constructor(public payload: { profileId: number }) {}
}
export class LoadChatsSuccessAction implements Action {
readonly type = LOAD_CHATS_SUCCESS
constructor(
public payload: {
chats: Chat[]
},
) {}
}
export class ChangeCurrentChatAction implements Action {
readonly type = CHANGE_CURRENT_CHAT
constructor(public payload: { id: number | string }) {}
}
export class GetCurrentChatFailedAction implements Action {
readonly type = GET_CURRENT_CHAT_FAILED
constructor(public payload: { error: string }) {}
}
export class ReadMessageAction {
readonly type = READ_MESSAGES
constructor(
public payload: {
chatId: number
messages: IMessages[]
},
) {}
}
export type ChatActions =
| ReceiveMessageAction
| LoadChatsAction
| LoadChatsSuccessAction
| GetCurrentChatFailedAction
| ChangeCurrentChatAction
| ReadMessageAction
<file_sep>/client/src/app/components/network/connections-list/connections-list.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
import { IUser } from '../../../interfaces/user'
@Component({
selector: 'app-connections-list',
templateUrl: './connections-list.component.html',
styleUrls: ['./connections-list.component.less'],
})
export class ConnectionsListComponent implements OnInit {
@Input() connections: { user: IUser; message: string }[] = []
@Input() type: string = ''
@Output() action = new EventEmitter<{ type: string; id: number }>()
acceptConnection(id: number): void {
this.action.emit({ type: 'accept', id })
}
declineConnection(id: number): void {
this.action.emit({ type: 'decline', id })
}
cancelConnection(id: number): void {
this.action.emit({ type: 'cancel', id })
}
constructor() {}
ngOnInit(): void {}
}
<file_sep>/client/src/app/views/network/network-main/network-main.component.ts
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { select, Store } from '@ngrx/store'
import { MyProfileState } from '../../../store/my-profile/my-profile.reducer'
import { Observable, of, Subscription } from 'rxjs'
import {
myProfileConnectionsSelector,
myProfileIdSelector,
myProfileReceivedConnectionsSelector,
myProfileSentConnectionsSelector,
} from '../../../store/my-profile/my-profile.selectors'
import { ProfileService } from '../../../services/profile.service'
import { IUser } from '../../../interfaces/user'
import { ProfileState } from '../../../store/profile/profile.reducer'
import {
MyProfileGetInfoAction,
MyProfileRemoveConnectionAction,
} from '../../../store/my-profile/my-profile.actions'
import { filter, map, switchMap } from 'rxjs/operators'
import {
ProfileAcceptConnectionAction,
ProfileDeclineConnectionAction,
ProfileSendConnectionAction,
} from '../../../store/profile/profile.actions'
@Component({
selector: 'app-network-main',
templateUrl: './network-main.component.html',
styleUrls: ['./network-main.component.less'],
})
export class NetworkMainComponent implements OnInit, OnDestroy {
constructor(
private store$: Store<MyProfileState | ProfileState>,
private profileService: ProfileService,
) {}
private subs: Subscription[] = []
private set sub(s: Subscription) {
this.subs.push(s)
}
myConnections: { user: IUser; date: number }[] = []
myProfileId: number = -1
@Input() activeTab: string = ''
myConnections$: Observable<
{ user: IUser; date: number }[]
> = this.store$.pipe(
select(myProfileConnectionsSelector),
switchMap(connections => {
return this.profileService.getConnectionsById$(connections)
}),
)
sendConnection(userId: number, message: string): void {
console.log('[SEND] user id:', userId, 'message:', message)
this.store$.dispatch(
new ProfileSendConnectionAction({
senderId: this.myProfileId,
userId,
message,
}),
)
}
acceptConnection(userId: number): void {
console.log('[ACCEPT] user id:', userId)
this.store$.dispatch(
new ProfileAcceptConnectionAction({
senderId: userId,
userId: this.myProfileId,
date: Date.now(),
}),
)
}
declineConnection(userId: number): void {
console.log('[DECLINE] user id:', userId)
this.store$.dispatch(
new ProfileDeclineConnectionAction({
senderId: userId,
userId: this.myProfileId,
}),
)
}
cancelConnection(userId: number): void {
console.log('[CANCEL] user id:', userId)
this.store$.dispatch(
new ProfileDeclineConnectionAction({
senderId: this.myProfileId,
userId,
}),
)
}
removeConnection(userId: number): void {
console.log('[REMOVE] user id:', userId)
this.store$.dispatch(
new MyProfileRemoveConnectionAction({
senderId: this.myProfileId,
userId,
}),
)
}
connectionsActionHandler(data: {
action: string
userId: number
message?: string
}): void {
const { action, ...d } = data
const { userId, message = '' } = d
switch (action) {
case 'send':
this.sendConnection(userId, message)
return
case 'accept':
this.acceptConnection(userId)
return
case 'decline':
this.declineConnection(userId)
return
case 'cancel':
this.cancelConnection(userId)
return
case 'remove':
this.removeConnection(userId)
return
}
}
ngOnInit(): void {
this.sub = this.store$
.pipe(select(myProfileIdSelector))
.subscribe(id => {
if (id >= 0) this.myProfileId = id
else
this.myProfileId = JSON.parse(
localStorage.getItem('currentUser') as string,
).user.id
}) // get this.myProfileId
this.store$.dispatch(
new MyProfileGetInfoAction({ id: this.myProfileId }),
) // get info
this.sub = this.myConnections$.subscribe(
connections => (this.myConnections = connections),
)
}
ngOnDestroy(): void {
this.subs.forEach(sub => sub.unsubscribe())
}
}
<file_sep>/server/src/users/user.shema.ts
import { Prop, raw, Schema, SchemaFactory } from '@nestjs/mongoose'
import { Document } from 'mongoose'
import { strict } from 'assert'
import { IContact } from '../interfaces/contact'
import { IProject } from '../interfaces/project'
import { IExp } from '../interfaces/exp'
import { IUniversity } from '../interfaces/university'
export type UserDocument = User & Document
@Schema()
export class User {
@Prop()
id: number
@Prop()
firstName: string
@Prop()
lastName: string
@Prop()
email: string
@Prop()
phone: string
@Prop()
password: string
@Prop(
raw({
isOnline: Boolean,
role: String,
description: String,
about: String,
views: {
current: Number,
prev: Number,
},
connections: [{ userId: Number, date: Number, chatId: Number }],
sentConnections: [{ userId: Number, message: String, chatId: Number }],
receivedConnections: [{ userId: Number, message: String, chatId: Number }],
posts: [{ postId: Number }],
avatar: { fileName: String, encoding: String, mimetype: String, url: String, size: Number },
profileHeaderBg: String,
dateOfBirth: Number,
profession: String,
gender: String,
locality: {
country: String,
city: String,
},
contactInfo: [{ contactWay: String, data: String }],
projects: [
{
name: String,
role: String,
date: String,
about: String,
poster: { fileName: String, encoding: String, mimetype: String, url: String, size: Number },
},
],
experience: [
{
companyName: String,
profession: String,
start: String,
end: String,
logo: { fileName: String, encoding: String, mimetype: String, url: String, size: Number },
},
],
education: [
{
name: String,
facultyAndDegree: String,
comment: String,
start: String,
end: String,
logo: { fileName: String, encoding: String, mimetype: String, url: String, size: Number },
},
],
dateOfLastPasswordUpdate: Number,
}),
)
info: Record<string, any>
}
export const UserSchema = SchemaFactory.createForClass(User)
<file_sep>/client/src/app/store/profile/profile.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store'
import { profileNode, ProfileState } from './profile.reducer'
export const profileFeatureSelector = createFeatureSelector<ProfileState>(
profileNode,
)
export const profileSelector = createSelector(
profileFeatureSelector,
state => state,
)
export const profileIdSelector = createSelector(
profileFeatureSelector,
state => state.id,
)
export const profileNameSelector = createSelector(
profileFeatureSelector,
state => `${state.firstName} ${state.lastName}`,
)
export const profilePhoneSelector = createSelector(
profileFeatureSelector,
state => state.phone,
)
export const profileEmailSelector = createSelector(
profileFeatureSelector,
state => state.email,
)
export const profilePostsSelector = createSelector(
profileFeatureSelector,
state => state.info.posts,
)
export const profileConnectionsSelector = createSelector(
profileFeatureSelector,
state => state.info.connections,
)
export const profileCurrentViewsSelector = createSelector(
profileFeatureSelector,
state => state.info.views.current,
)
export const profilePrevViewsSelector = createSelector(
profileFeatureSelector,
state => state.info.views.prev,
)
export const profileAvatarSelector = createSelector(
profileFeatureSelector,
state => state.info.avatar?.url ?? '../../../assets/img/avatar-man.png',
)
export const profileHeaderBgSelector = createSelector(
profileFeatureSelector,
state =>
state.info.profileHeaderBg?.url ??
'../../../assets/img/profile-header.png',
)
export const profileDescriptionSelector = createSelector(
profileFeatureSelector,
state => state.info.description,
)
export const profileProfessionSelector = createSelector(
profileFeatureSelector,
state => state.info.profession,
)
export const profileDOBSelector = createSelector(
profileFeatureSelector,
state => state.info.dateOfBirth,
)
export const profileLocalitySelector = createSelector(
profileFeatureSelector,
state => {
const { city, country } = state.info.locality
if (city && country) return `${city}, ${country}`
if (city) return `${city}`
if (country) return `${country}`
return null
},
)
export const profileContactInfoSelector = createSelector(
profileFeatureSelector,
state => state.info.contactInfo
)
export const profileSentConnectionsSelector = createSelector(
profileFeatureSelector,
state => state.info.sentConnections,
)
<file_sep>/server/src/interfaces/chat/chat.ts
import { IAttach } from '../post/attach'
import { IMessages } from './messages'
export interface IChat {
chatId: number
users: { userId: number }[]
attached: IAttach[]
messages: IMessages[]
}
<file_sep>/client/src/app/store/my-profile/my-profile.actions.ts
/* ACTION TYPES */
import { Action } from '@ngrx/store'
import { MyProfileState } from './my-profile.reducer'
import { IUser } from '../../interfaces/user'
import { IContact } from '../../interfaces/contact'
import { IProject } from '../../interfaces/project'
import { IUniversity } from '../../interfaces/university'
import { IExp } from '../../interfaces/exp'
export const GET_MY_PROFILE_INFO_ACTION_TYPE = '[MY PROFILE] get info'
export const GET_MY_PROFILE_INFO_SUCCESS_ACTION_TYPE =
'[MY PROFILE] get info success'
export const ACCEPT_CONNECTION_ACTION_TYPE = '[MY PROFILE] accept connection'
export const ACCEPT_CONNECTION_SUCCESS_ACTION_TYPE =
'[MY PROFILE] success accept connection'
export const DECLINE_CONNECTION_ACTION_TYPE = '[MY PROFILE] decline connection'
export const DECLINE_CONNECTION_SUCCESS_ACTION_TYPE =
'[MY PROFILE] success decline connection'
export const CANCEL_CONNECTION_ACTION_TYPE = '[MY PROFILE] cancel connection'
export const CANCEL_CONNECTION_SUCCESS_ACTION_TYPE =
'[MY PROFILE] success cancel connection'
export const REMOVE_CONNECTION_ACTION_TYPE = '[MY PROFILE] remove connection'
export const REMOVE_CONNECTION_SUCCESS_ACTION_TYPE =
'[MY PROFILE] remove connection success'
export const CHANGE_AVATAR_ACTION_TYPE = '[MY PROFILE] change avatar'
export const CHANGE_AVATAR_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change avatar success'
export const DELETE_AVATAR_SUCCESS_ACTION_TYPE =
'[MY PROFILE] delete avatar success'
// change additional information action types
export const CHANGE_ROLE_ACTION_TYPE = '[MY PROFILE] change role'
export const CHANGE_ROLE_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change role success'
export const CHANGE_COMPANY_ACTION_TYPE = '[MY PROFILE] change company'
export const CHANGE_COMPANY_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change company success'
export const CHANGE_ABOUT_ACTION_TYPE = '[MY PROFILE] change about'
export const CHANGE_ABOUT_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change about success'
export const CHANGE_PROFESSION_ACTION_TYPE = '[MY PROFILE] change profession'
export const CHANGE_PROFESSION_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change profession success'
export const CHANGE_LOCALITY_ACTION_TYPE = '[MY PROFILE] change locality'
export const CHANGE_LOCALITY_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change locality success'
export const CHANGE_CONTACT_INFO_ACTION_TYPE =
'[MY PROFILE] change contact info'
export const CHANGE_CONTACT_INFO_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change contact info success'
export const CHANGE_PROJECTS_ACTION_TYPE = '[MY PROFILE] change projects'
export const CHANGE_PROJECTS_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change projects success'
export const CHANGE_EXPERIENCE_ACTION_TYPE = '[MY PROFILE] change experience'
export const CHANGE_EXPERIENCE_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change experience success'
export const CHANGE_EDUCATION_ACTION_TYPE = '[MY PROFILE] change education'
export const CHANGE_EDUCATION_SUCCESS_ACTION_TYPE =
'[MY PROFILE] change education success'
export const JOIN_TO_CHAT = '[MY PROFILE] join to chat'
/* ACTIONS */
export class MyProfileGetInfoAction implements Action {
readonly type = GET_MY_PROFILE_INFO_ACTION_TYPE
constructor(
public payload: {
id: number
},
) {}
}
export class MyProfileGetInfoSuccessAction implements Action {
readonly type = GET_MY_PROFILE_INFO_SUCCESS_ACTION_TYPE
constructor(
public payload: {
profile: IUser
},
) {}
}
export class MyProfileAcceptConnectionAction implements Action {
readonly type = ACCEPT_CONNECTION_ACTION_TYPE
constructor(
public payload: {
senderId: number
userId: number
date: number
},
) {}
}
export class MyProfileDeclineConnectionAction implements Action {
readonly type = DECLINE_CONNECTION_ACTION_TYPE
constructor(
public payload: {
senderId: number
userId: number
},
) {}
}
export class MyProfileCancelConnectionAction implements Action {
readonly type = CANCEL_CONNECTION_ACTION_TYPE
constructor(
public payload: {
senderId: number
userId: number
},
) {}
}
export class MyProfileRemoveConnectionAction implements Action {
readonly type = REMOVE_CONNECTION_ACTION_TYPE
constructor(
public payload: {
senderId: number
userId: number
},
) {}
}
export class MyProfileAcceptConnectionSuccessAction implements Action {
readonly type = ACCEPT_CONNECTION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
senderId: number
date: number
},
) {}
}
export class MyProfileDeclineConnectionSuccessAction implements Action {
readonly type = DECLINE_CONNECTION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
senderId: number
},
) {}
}
export class MyProfileCancelConnectionSuccessAction implements Action {
readonly type = CANCEL_CONNECTION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
userId: number
},
) {}
}
export class MyProfileRemoveConnectionSuccessAction implements Action {
readonly type = REMOVE_CONNECTION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
userId: number
},
) {}
}
export class MyProfileChangeAvatarAction implements Action {
readonly type = CHANGE_AVATAR_ACTION_TYPE
constructor(
public payload: {
file: File
},
) {}
}
export class MyProfileChangeAvatarSuccessAction implements Action {
readonly type = CHANGE_AVATAR_SUCCESS_ACTION_TYPE
constructor(
public payload: {
url: string
},
) {}
}
export class MyProfileDeleteAvatarSuccessAction implements Action {
readonly type = DELETE_AVATAR_SUCCESS_ACTION_TYPE
}
export class MyProfileChangeRoleAction implements Action {
readonly type = CHANGE_ROLE_ACTION_TYPE
constructor(
public payload: {
role: string
id: number
},
) {}
}
export class MyProfileChangeRoleSuccessAction implements Action {
readonly type = CHANGE_ROLE_SUCCESS_ACTION_TYPE
constructor(
public payload: {
role: string
},
) {}
}
export class MyProfileChangeCompanyAction implements Action {
readonly type = CHANGE_COMPANY_ACTION_TYPE
constructor(
public payload: {
id: number
},
) {}
}
export class MyProfileChangeCompanySuccessAction implements Action {
readonly type = CHANGE_COMPANY_SUCCESS_ACTION_TYPE
constructor(public payload: {}) {}
}
export class MyProfileChangeAboutAction implements Action {
readonly type = CHANGE_ABOUT_ACTION_TYPE
constructor(
public payload: {
about: string
id: number
},
) {}
}
export class MyProfileChangeAboutSuccessAction implements Action {
readonly type = CHANGE_ABOUT_SUCCESS_ACTION_TYPE
constructor(
public payload: {
about: string
},
) {}
}
export class MyProfileChangeProfessionAction implements Action {
readonly type = CHANGE_PROFESSION_ACTION_TYPE
constructor(
public payload: {
profession: string
id: number
},
) {}
}
export class MyProfileChangeProfessionSuccessAction implements Action {
readonly type = CHANGE_PROFESSION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
profession: string
},
) {}
}
export class MyProfileChangeLocalityAction implements Action {
readonly type = CHANGE_LOCALITY_ACTION_TYPE
constructor(
public payload: {
locality: { country: string; city: string }
id: number
},
) {}
}
export class MyProfileChangeLocalitySuccessAction implements Action {
readonly type = CHANGE_LOCALITY_SUCCESS_ACTION_TYPE
constructor(
public payload: {
locality: { country: string; city: string }
},
) {}
}
export class MyProfileChangeContactInfoAction implements Action {
readonly type = CHANGE_CONTACT_INFO_ACTION_TYPE
constructor(
public payload: {
contactInfo: IContact[]
id: number
},
) {}
}
export class MyProfileChangeContactInfoSuccessAction implements Action {
readonly type = CHANGE_CONTACT_INFO_SUCCESS_ACTION_TYPE
constructor(
public payload: {
contactInfo: IContact[]
},
) {}
}
export class MyProfileChangeProjectsAction implements Action {
readonly type = CHANGE_PROJECTS_ACTION_TYPE
constructor(
public payload: {
projects: IProject[]
id: number
},
) {}
}
export class MyProfileChangeProjectsSuccessAction implements Action {
readonly type = CHANGE_PROJECTS_SUCCESS_ACTION_TYPE
constructor(
public payload: {
projects: IProject[]
},
) {}
}
export class MyProfileChangeExperienceAction implements Action {
readonly type = CHANGE_EXPERIENCE_ACTION_TYPE
constructor(
public payload: {
experience: IExp[]
id: number
},
) {}
}
export class MyProfileChangeExperienceSuccessAction implements Action {
readonly type = CHANGE_EXPERIENCE_SUCCESS_ACTION_TYPE
constructor(
public payload: {
experience: IExp[]
},
) {}
}
export class MyProfileChangeEducationAction implements Action {
readonly type = CHANGE_EDUCATION_ACTION_TYPE
constructor(
public payload: {
education: IUniversity[]
id: number
},
) {}
}
export class MyProfileChangeEducationSuccessAction implements Action {
readonly type = CHANGE_EDUCATION_SUCCESS_ACTION_TYPE
constructor(
public payload: {
education: IUniversity[]
},
) {}
}
export type MyProfileActions =
| MyProfileGetInfoAction
| MyProfileGetInfoSuccessAction
| MyProfileAcceptConnectionAction
| MyProfileAcceptConnectionSuccessAction
| MyProfileDeclineConnectionAction
| MyProfileDeclineConnectionSuccessAction
| MyProfileCancelConnectionAction
| MyProfileCancelConnectionSuccessAction
| MyProfileRemoveConnectionAction
| MyProfileRemoveConnectionSuccessAction
| MyProfileChangeAvatarAction
| MyProfileChangeAvatarSuccessAction
| MyProfileDeleteAvatarSuccessAction
| MyProfileChangeRoleAction
| MyProfileChangeRoleSuccessAction
| MyProfileChangeCompanyAction
| MyProfileChangeCompanySuccessAction
| MyProfileChangeAboutAction
| MyProfileChangeAboutSuccessAction
| MyProfileChangeProfessionAction
| MyProfileChangeProfessionSuccessAction
| MyProfileChangeLocalityAction
| MyProfileChangeLocalitySuccessAction
| MyProfileChangeContactInfoAction
| MyProfileChangeContactInfoSuccessAction
| MyProfileChangeProjectsAction
| MyProfileChangeProjectsSuccessAction
| MyProfileChangeExperienceAction
| MyProfileChangeExperienceSuccessAction
| MyProfileChangeEducationAction
| MyProfileChangeEducationSuccessAction
<file_sep>/server/src/interfaces/university.ts
import { IFile } from './file'
export interface IUniversity {
name: string
facultyAndDegree: string
comment: string
start: string
end: string
logo?: (IFile & { file: File }) | null
}
<file_sep>/server/src/interfaces/post/creator.ts
export interface ICreator {
id: number
fullName: string
avatar: string | number[] | null
profession: string
}
<file_sep>/client/src/app/views/chat/chat-main/chat-main.component.ts
import {Component, ElementRef, Input, OnDestroy, OnInit, ViewChild} from '@angular/core'
import { ChatService } from '../../../services/chat.service'
import {Observable, Subject} from 'rxjs'
import { select, Store } from '@ngrx/store'
import { MyProfileState } from '../../../store/my-profile/my-profile.reducer'
import {map, take, takeUntil} from 'rxjs/operators'
import { Chat, ChatState } from '../../../store/chat/chat.reducer'
import {
currentChatSelector,
messagesSelector,
} from '../../../store/chat/chat.selectors'
import { IMessages } from '../../../interfaces/chat/messages'
@Component({
selector: 'app-chat-main',
templateUrl: './chat-main.component.html',
styleUrls: ['./chat-main.component.less'],
})
export class ChatMainComponent implements OnInit, OnDestroy {
constructor(
private chatService: ChatService,
private store$: Store<MyProfileState | ChatState>,
) {}
unsub$ = new Subject()
@Input() profileId: number = -1
currentChatId: number = -1
// allChats$: Observable<IChat[]> = this.store$.pipe(
// select(chatsSelector)
// )
@ViewChild('messages') messages: ElementRef | null = null
currentChat$: Observable<Chat | null | undefined> = this.store$.pipe(
select(currentChatSelector),
)
messages$: Observable<IMessages[] | never[] | undefined> = this.store$.pipe(
select(messagesSelector),
)
buddy = {
isOnline: false,
lastOnline: Date.now() - 60 * 60 * 5,
}
Date = Date
messageContent: string = ''
sendMessage(): void {
console.log('chatId:', this.currentChatId)
console.log('profileID:', this.profileId)
console.log('message:', this.messageContent)
if (this.messageContent === '') return
this.chatService.sendMessage(
this.messageContent,
this.profileId,
this.currentChatId,
)
this.messageContent = ''
}
dateParser(now: number, last: number): string {
const deltaSec = (now - last) / 1000
const secondsPerDay = 60 * 60 * 24
const secondsPerHour = 60 * 60
const secondsPerMinute = 60
if (deltaSec > secondsPerDay) {
const days = Math.floor(deltaSec / secondsPerDay)
if (days < 2) return 'day ago'
return Math.floor(deltaSec / secondsPerDay) + ' days ago'
} else if (deltaSec > secondsPerHour) {
const hours = Math.floor(deltaSec / secondsPerDay)
if (hours < 2) return 'hour ago'
return Math.floor(deltaSec / secondsPerHour) + ' hours ago'
} else if (deltaSec > secondsPerMinute) {
const minutes = Math.floor(deltaSec / secondsPerDay)
if (minutes < 2) return 'minute ago'
return Math.floor(deltaSec / secondsPerMinute) + ' minutes ago'
} else return 'minute ago'
}
ngOnInit(): void {
this.currentChat$.pipe(takeUntil(this.unsub$)).subscribe(chat => {
this.currentChatId = chat?.chat.chatId ?? -1
})
this.messages$.pipe(takeUntil(this.unsub$)).subscribe(() => {
if (this.messages) {
setTimeout(() => {
const { nativeElement: messages } = this.messages as {
nativeElement: HTMLElement
}
messages.scrollTop = messages.scrollHeight
})
}
})
}
ngOnDestroy(): void {
this.unsub$.next()
this.unsub$.complete()
}
}
<file_sep>/client/src/app/store/chat/chat.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store'
import {
chatNode,
ChatState,
selectAllChats,
selectChatEntities,
selectChatIds,
selectChatTotal,
} from './chat.reducer'
export const chatFeatureSelector = createFeatureSelector<ChatState>(chatNode)
export const allChatsSelector = createSelector(
chatFeatureSelector,
selectAllChats,
)
export const chatIdsSelector = createSelector(
chatFeatureSelector,
selectChatIds,
)
export const currentChatIdSelector = createSelector(
chatFeatureSelector,
state => state.currentChat,
)
export const chatTotalSelector = createSelector(
chatFeatureSelector,
selectChatTotal,
)
export const chatEntitiesSelector = createSelector(
chatFeatureSelector,
selectChatEntities,
)
export const currentChatSelector = createSelector(
chatEntitiesSelector,
currentChatIdSelector,
(chatEntities, chatId) => {
if (chatId === null) return null
return chatEntities[chatId]
},
)
export const messagesSelector = createSelector(
chatFeatureSelector,
state => state.messages,
)
export const lastMessageSelector = createSelector(
chatFeatureSelector,
state => {},
)
export const messagesSelector1 = createSelector(
chatEntitiesSelector,
currentChatIdSelector,
(chatEntities, chatId) => {
if (!chatId && chatId !== 0) return []
return chatEntities[chatId]?.chat.messages
},
)
| 2bdaaaeea9d413c83aec9f5ddeb6b190b03b80d9 | [
"Markdown",
"TypeScript"
] | 118 | TypeScript | FuramyD/linkedin-redesign | 89e79859a81f593fb4d9630cd2e7b3d34abd7910 | 8b53ca5e21b4d30e605d36101b79a4e1cf80407c |
refs/heads/master | <file_sep>const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const bcrypt = require('bcryptjs')
const db = require('../models')
const User = db.User
const Restaurant = db.Restaurant
const Like = db.Like
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK
},
function (accessToken, refreshToken, profile, cb) {
User.findOrCreate({
where: { email: profile._json.email }, defaults: {
name: profile._json.name,
email: profile._json.email,
password: '<PASSWORD>',
isAdmin: false
}
}).then(user => {
return cb(null, user[0])
})
}
));
passport.use(new FacebookStrategy({
clientID: process.env.FACEBOOK_ID,
clientSecret: process.env.FACEBOOK_SECRET,
callbackURL: process.env.FACEBOOK_CALLBACK,
profileFields: ['name', 'email']
},
function (accessToken, refreshToken, profile, cb) {
User.findOrCreate({
where: { email: profile._json.email }, defaults: {
name: `${profile._json.last_name} ${profile._json.first_name}`,
email: profile._json.email,
password: '<PASSWORD>',
isAdmin: false
}
}).then(user => {
return cb(null, user[0])
})
}
));
passport.use(new LocalStrategy({
usernameField: 'email',
passReqToCallback: true
},
function (req, email, password, done) {
User.findOne({ where: { email: email } }).then(user => {
if (!user) {
//回傳無此帳號
return done(null, false, req.flash('error_messages', '查無此帳號'))
}
//確認密碼
if (!bcrypt.compareSync(password, user.password)) {
//回傳密碼錯誤
return done(null, false, req.flash('error_messages', '密碼輸入錯誤'))
}
return done(null, user)
})
}
));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findByPk(id, {
include: [
{ model: Restaurant, as: 'FavoritedRestaurants' },
{ model: Restaurant, as: 'LikeRestaurants' },
{ model: User, as: 'Followers' },
{ model: User, as: 'Followings' }
]
}).then(user => {
return done(null, user.get())
});
});
// JWT
const jwt = require('jsonwebtoken')
const passportJWT = require('passport-jwt')
const ExtractJwt = passportJWT.ExtractJwt
const JwtStrategy = passportJWT.Strategy
let jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
jwtOptions.secretOrKey = process.env.JWT_SECRET
let strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {
User.findByPk(jwt_payload.id, {
include: [
{ model: db.Restaurant, as: 'FavoritedRestaurants' },
{ model: db.Restaurant, as: 'LikeRestaurants' },
{ model: User, as: 'Followers' },
{ model: User, as: 'Followings' },
]
}).then(user => {
if (!user) return next(null, false)
return next(null, user)
})
})
passport.use(strategy)
module.exports = passport<file_sep>const express = require('express')
const router = express.Router()
const passport = require('../config/passport')
const adminController = require('../controllers/api/adminController')
const userController = require('../controllers/api/userController.js')
const resController = require('../controllers/api/resController.js')
const multer = require('multer')
const upload = multer({ dest: 'temp/' })
const authenticated = passport.authenticate('jwt', { session: false })
const authenticatedAdmin = (req, res, next) => {
if (req.user) {
if (req.user.isAdmin) { return next() }
return res.json({ status: 'error', message: 'permission denied' })
} else {
return res.json({ status: 'error', message: 'permission denied' })
}
}
// JWT 登入
router.post('/signin', userController.signIn)
//註冊
router.post('/signup', userController.signUp)
//管理員餐廳頁面
router.get('/admin/restaurant', authenticated, authenticatedAdmin, adminController.adminGetRes)
//新增餐廳頁面
router.get('/admin/restaurant/create', adminController.createResPage)
//管理員餐廳資訊頁面
router.get('/admin/restaurant/:id', authenticated, authenticatedAdmin, adminController.getRes)
//管理員餐廳類別頁面
router.get('/admin/category', authenticated, authenticatedAdmin, adminController.getAllCategory)
//新增一筆餐廳
router.post('/admin/restaurant', authenticated, authenticatedAdmin, upload.single('image'), adminController.createRes)
//修改餐廳頁面
router.get('/admin/restaurant/:id/edit', authenticated, authenticatedAdmin, adminController.editResPage)
//修改一筆餐廳
router.put('/admin/restaurant/:id/edit', authenticated, authenticatedAdmin, upload.single('image'), adminController.editRes)
//刪除一筆餐廳
router.delete('/admin/restaurant/:id', authenticated, authenticatedAdmin, adminController.deleteRes)
//所有餐廳類別頁面
router.get('/admin/category', authenticated, authenticatedAdmin, adminController.getAllCategory)
//新增餐廳類別
router.post('/admin/category/create', authenticated, authenticatedAdmin, adminController.createCategory)
//修改餐廳類別頁面
router.get('/admin/category/:id/edit', authenticated, authenticatedAdmin, adminController.editCategoryPage)
//修改餐廳類別
router.put('/admin/category/:id/edit', authenticated, authenticatedAdmin, adminController.editCategory)
//刪除餐廳類別
router.delete('/admin/category/:id/delete', authenticated, authenticatedAdmin, adminController.deleteCategory)
//使用者頁面
router.get('/admin/user', authenticated, authenticatedAdmin, adminController.getUser)
//修改使用者權限
router.put('/admin/user/:id', authenticated, authenticatedAdmin, adminController.putUser)
router.get('/', authenticated, (req, res) => { res.redirect('/restaurant') })
router.get('/restaurant', authenticated, resController.getRes)
// router.get('/restaurant/feeds', authenticate, resController.getFeeds)
// //熱門餐廳頁面
// router.get('/restaurant/top', authenticate, resController.popularRes)
// router.get('/restaurant/:id', authenticate, resController.getARes)
// //餐廳熱門度頁面
// router.get('/restaurant/:id/popular', authenticate, resController.getResPopular)
// router.get('/admin', isAdmin, (req, res) => { res.redirect('/admin/restaurant') })
// router.get('/admin/restaurant', isAdmin, adminController.adminGetRes)
// router.get('/signup', userController.signUpPage)
// router.post('/signup', userController.signUp)
// router.get('/signin', userController.signInPage)
// router.post('/signin', passport.authenticate('local', {
// failureRedirect: '/signin',
// failureFlash: true
// }), userController.signIn)
// router.get('/logout', userController.logOut)
// //新增一筆餐廳
// router.post('/admin/restaurant', isAdmin, upload.single('image'), adminController.createRes)
// //瀏覽一筆餐廳
// router.get('/admin/restaurant/:id', isAdmin, adminController.getRes)
// //刪除一筆餐廳
// router.delete('/admin/restaurant/:id', isAdmin, adminController.deleteRes)
// //修改一筆餐廳
// router.put('/admin/restaurant/:id/edit', isAdmin, upload.single('image'), adminController.editRes)
// //新增餐廳類別
// router.post('/admin/category/create', isAdmin, adminController.createCategory)
// //修改餐廳類別
// router.put('/admin/category/:id/edit', isAdmin, adminController.editCategory)
// //刪除餐廳類別
// router.delete('/admin/category/:id/delete', isAdmin, adminController.deleteCategory)
// //新增評論
// router.post('/comment', authenticate, commentController.createComment)
// //刪除評論
// router.delete('/comment/:id', isAdmin, commentController.deleteComment)
// //追隨人頁面
// router.get('/user/top', authenticate, userController.getTopUser)
// //追隨
// router.post('/following/:userId', authenticate, userController.follow)
// //取消追隨
// router.delete('/following/:userId', authenticate, userController.cancelFollow)
// //編輯個人資料
// router.put('/user/:id/edit', authenticate, upload.single('avatar'), userController.editUser)
// //個人資料頁面
// router.get('/user/:id', authenticate, userController.userPage)
// //編輯個人資料頁面
// router.get('/user/:id/edit', authenticate, userController.editUserPage)
// //加入最愛
// router.post('/user/:id/favorite', authenticate, userController.addFavorite)
// //刪除最愛
// router.delete('/user/:id/favorite', authenticate, userController.deleteFavorite)
// //按讚
// router.post('/like/:restaurantId', authenticate, userController.like)
// //取消讚
// router.delete('/cancellike/:restaurantId', authenticate, userController.cancelLike)
module.exports = router
<file_sep>const db = require('../models')
const Restaurant = db.Restaurant
const User = db.User
const Category = db.Category
const imgur = require('imgur-node-api')
const IMGUR_CLIENT_ID = process.env.IMGUR_CLIENT_ID
const adminService = require('../services/adminService')
const adminController = {
adminGetRes: (req, res) => {
adminService.adminGetRes(req, res, (data) => {
return res.render('admin/adminRes', data)
})
},
createResPage: (req, res) => {
adminService.createResPage(req, res, (data) => {
return res.render('admin/createResPage', JSON.parse(JSON.stringify(data)))
})
},
createRes: (req, res) => {
adminService.createRes(req, res, (data) => {
if (data['status'] === 'error') {
req.flash('error_messages', data['message'])
return res.render('back')
}
req.flash('success_messages', data['message'])
return res.redirect('/admin/restaurant')
})
},
getRes: (req, res) => {
adminService.getRes(req, res, (data) => {
return res.render(`admin/restaurant`, JSON.parse(JSON.stringify(data)))
})
},
deleteRes: (req, res) => {
adminService.deleteRes(req, res, (data) => {
return res.redirect('back')
})
},
editResPage: (req, res) => {
adminService.editResPage(req, res, (data) => {
return res.render('admin/editResPage', JSON.parse(JSON.stringify(data['message'])))
})
},
editRes: (req, res) => {
adminService.editRes(req, res, (data) => {
req.flash('success_messages', data['message'])
return res.redirect('/admin/restaurant')
})
},
getUser: (req, res) => {
adminService.getUser(req, res, (data) => {
return res.render('admin/getUserPage', JSON.parse(JSON.stringify(data['message'])))
})
},
putUser: (req, res) => {
adminService.putUser(req, res, (data) => {
req.flash('success_messages', '權限變更成功')
return res.redirect('back')
})
},
getAllCategory: (req, res) => {
adminService.getAllCategory(req, res, (data) => {
return res.render('admin/getAllCategory', JSON.parse(JSON.stringify(data['message'])))
})
},
createCategory: (req, res) => {
adminService.createCategory(req, res, (data) => {
if (data['status'] === 'error') {
req.flash("error_messages", data['message'])
return res.redirect('back')
}
req.flash("success_messages", data['message'])
return res.redirect('back')
})
},
editCategoryPage: (req, res) => {
adminService.editCategoryPage(req, res, (data) => {
return res.render('admin/getAllCategory', JSON.parse(JSON.stringify(data['message'])))
})
},
editCategory: (req, res) => {
adminService.editCategory(req, res, (data) => {
req.flash("success_messages", data['message'])
return res.redirect("/admin/category")
})
},
deleteCategory: (req, res) => {
adminService.deleteCategory(req, res, (data) => {
req.flash('success_messages', data['message'])
return res.redirect('back')
})
}
}
module.exports = adminController<file_sep>const resService = require('../../services/resService')
const resController = {
getRes: (req, res) => {
resService.getRes(req, res, (data) => {
return res.json(data)
})
},
}
module.exports = resController<file_sep>const db = require('../models')
const User = db.User
const Comment = db.Comment
const Restaurant = db.Restaurant
const Category = db.Category
const Favorite = db.Favorite
const Like = db.Like
const Followship = db.Followship
const sequelize = require('sequelize')
const bcrypt = require('bcryptjs')
var imgur = require('imgur-node-api')
const IMGUR_CLIENT_ID = process.env.IMGUR_CLIENT_ID
const userController = {
signUpPage: (req, res) => {
return res.render('signup')
},
signUp: (req, res) => {
if (req.body.password != req.body.<PASSWORD>) {
req.flash('error_messages', '密碼輸入不相同')
return res.redirect('/signup')
}
User.findOne({ where: { email: req.body.email } })
.then(user => {
if (user) {
req.flash('error_messages', '帳號已註冊')
return res.redirect('/signup')
}
else {
User.create({
name: req.body.name,
email: req.body.email,
password: <PASSWORD>(req.body.password, bcrypt.genSaltSync(10))
}).then(user => {
req.flash('success_messages', '成功註冊')
return res.redirect('/signin')
})
}
})
},
signInPage: (req, res) => {
return res.render('signin')
},
signIn: (req, res) => {
req.flash('success_messages', '登入成功')
if (req.user.isAdmin) { return res.redirect('/admin/user') }
else { return res.redirect('/restaurant') }
},
logOut: (req, res) => {
req.logout()
return res.redirect('/signin')
},
userPage: (req, res) => {
User.findByPk(req.params.id, {
include: [
Comment,
{ model: Comment, include: [Restaurant] }
]
})
.then(user => {
//console.log(user)
let commentNumber = user.Comments.length
//console.log(req.user.FavoritedRestaurants)
console.log(req.user.Followings)
let FavoritedRestaurants = req.user.FavoritedRestaurants
let Followers = req.user.Followers
let Followings = req.user.Followings
let FavoritedResNumber = req.user.FavoritedRestaurants.length
let FollowerNumber = req.user.Followers.length
let FollowingNumber = req.user.Followings.length
return res.render('userPage', JSON.parse(JSON.stringify({ user: user, commentNumber: commentNumber, reqUser: req.user.id, FavoritedResNumber: FavoritedResNumber, FollowerNumber: FollowerNumber, FollowingNumber: FollowingNumber, FavoritedRestaurants: FavoritedRestaurants, Followers: Followers, Followings: Followings })))
})
},
editUserPage: (req, res) => {
User.findByPk(req.user.id)
.then(user => {
return res.render('user', JSON.parse(JSON.stringify({ user: user })))
})
},
editUser: (req, res) => {
const { file } = req
if (file) {
imgur.setClientID(IMGUR_CLIENT_ID)
imgur.upload(file.path, (err, avatar) => {
User.findByPk(req.user.id)
.then(user => {
user.update({
name: req.body.name,
avatar: avatar.data.link
}).then(user => {
return res.redirect(`/user/${user.id}`)
})
})
})
}
else {
User.findByPk(req.user.id)
.then(user => {
user.update({
name: req.body.name,
avatar: 'https://via.placeholder.com/200'
}).then(user => {
return res.redirect(`/user/${user.id}`)
})
})
}
},
addFavorite: (req, res) => {
Favorite.create({
UserId: req.user.id,
RestaurantId: req.params.id
}).then(() => {
//req.flash('success_messages', '加入成功')
return res.redirect('back')
})
},
deleteFavorite: (req, res) => {
Favorite.findOne({
where: {
UserId: req.user.id,
RestaurantId: req.params.id
}
}).then(favorite => {
favorite.destroy()
.then(() => {
return res.redirect('back')
})
})
},
like: (req, res) => {
Like.create({
UserId: req.user.id,
RestaurantId: req.params.restaurantId
}).then(() => {
return res.redirect('back')
})
},
cancelLike: (req, res) => {
Like.findOne({
where: {
UserId: req.user.id,
RestaurantId: req.params.restaurantId
}
}).then((like) => {
like.destroy()
.then(() => {
return res.redirect('back')
})
})
},
getTopUser: (req, res) => {
User.findAll({
include: [
{ model: User, as: 'Followers' }
]
}).then((users) => {
users = users.map((user) => ({
...user.dataValues,
FollowerCount: user.Followers.length,
isFollowed: req.user.Followings.map(d => d.id).includes(user.id)
}))
users = users.sort((a, b) => b.FollowerCount - a.FollowerCount)
return res.render('topUser', { users: users })
})
},
follow: (req, res) => {
Followship.create({
FollowerId: req.user.id,
FollowingId: req.params.userId
}).then(() => {
return res.redirect('back')
})
},
cancelFollow: (req, res) => {
Followship.findOne({
where: {
FollowerId: req.user.id,
FollowingId: req.params.userId
}
}).then((following) => {
following.destroy()
.then(() => {
return res.redirect('back')
})
})
},
}
module.exports = userController
<file_sep>const db = require('../models')
const Category = db.Category
const Restaurant = db.Restaurant
const resService = {
getRes: (req, res, callback) => {
let wherequery = {}
let categoryId = ''
if (req.query.categoryId) {
categoryId = Number(req.query.categoryId)
wherequery['CategoryId'] = categoryId
}
let pageLimit = 10
let offSet = 0
if (req.query.page) {
offSet = (Number(req.query.page) - 1) * pageLimit
}
Restaurant.findAndCountAll({ include: [Category], where: wherequery, offset: offSet, limit: pageLimit }).then(result => {
let page = Number(req.query.page) || 1
let pages = Math.ceil(result.count / 10)
let totalPage = Array.from({ length: pages }, (value, index) => index + 1)
let prev = page - 1 < 0 ? 1 : page - 1
let next = page + 1 > pages ? pages : page + 1
let data = result.rows.map(r => (
{
...r.dataValues,
description: r.dataValues.description.substring(0, 50),
//加入最愛判斷
isFavorited: req.user.FavoritedRestaurants.map(d => d.id).includes(r.id),
isLike: req.user.LikeRestaurants.map(d => d.id).includes(r.id)
}
))
Category.findAll().then(categories => {
callback({ restaurants: data, categories: categories, categoryId: categoryId, totalPage: totalPage, prev: prev, next: next, page: page })
})
})
},
}
module.exports = resService<file_sep>const db = require('../models')
const Restaurant = db.Restaurant
const User = db.User
const Category = db.Category
const imgur = require('imgur-node-api')
const IMGUR_CLIENT_ID = process.env.IMGUR_CLIENT_ID
const adminService = {
adminGetRes: (req, res, callback) => {
return Restaurant.findAll({ include: [Category] }).then(restaurants => {
callback(JSON.parse(JSON.stringify({ restaurants: restaurants })))
})
},
getRes: (req, res, callback) => {
Restaurant.findByPk(req.params.id, { include: [Category] })
.then(restaurant => {
callback({ restaurant: restaurant })
})
},
createResPage: (req, res, callback) => {
Category.findAll().then(categories => {
callback({ categories: categories })
})
},
getAllCategory: (req, res, callback) => {
Category.findAll().then(categories => {
callback({ categories: categories })
})
},
deleteRes: (req, res, callback) => {
Restaurant.findByPk(req.params.id)
.then(restaurant => {
restaurant.destroy()
.then(() => {
callback({ status: 'success', message: '' })
})
})
},
createRes: (req, res, callback) => {
if (!req.body.name) {
callback({ status: 'error', message: '沒有輸入餐廳名稱' })
}
const { file } = req
if (file) {
imgur.setClientID(IMGUR_CLIENT_ID);
imgur.upload(file.path, (err, img) => {
return Restaurant.create({
name: req.body.name,
tel: req.body.tel,
address: req.body.address,
opening_hours: req.body.opening_hours,
description: req.body.description,
image: file ? img.data.link : null,
CategoryId: req.body.selectCategory
}).then(restaurant => {
callback({ status: 'success', message: '新增成功!' })
})
})
}
else {
Restaurant.create({
name: req.body.name,
tel: req.body.tel,
address: req.body.address,
opening_hours: req.body.opening_hours,
description: req.body.description,
image: file ? img.data.link : null,
CategoryId: req.body.selectCategory
}).then(restaurant => {
callback({ status: 'success', message: '新增成功!' })
})
}
},
editResPage: (req, res, callback) => {
Restaurant.findByPk(req.params.id, { include: [Category] })
.then(restaurant => {
Category.findAll().then(categories => {
callback({ status: 'success', message: { restaurant: restaurant, categories: categories } })
})
})
},
editRes: (req, res, callback) => {
const { file } = req
if (file) {
imgur.setClientID(IMGUR_CLIENT_ID);
imgur.upload(file.path, (err, img) => {
Restaurant.findByPk(req.params.id)
.then(restaurant => {
restaurant.update({
name: req.body.name,
tel: req.body.tel,
address: req.body.address,
opening_hours: req.body.opening_hours,
description: req.body.description,
image: file ? img.data.link : null,
CategoryId: req.body.selectCategory
}).then(restaurant => {
callback({ status: 'success', message: '修改成功!' })
})
})
})
}
else {
Restaurant.findByPk(req.params.id)
.then(restaurant => {
restaurant.update({
name: req.body.name,
tel: req.body.tel,
address: req.body.address,
opening_hours: req.body.opening_hours,
description: req.body.description,
image: file ? img.data.link : null,
CategoryId: req.body.selectCategory
}).then(restaurant => {
callback({ status: 'success', message: '修改成功!' })
})
})
}
},
createCategory: (req, res, callback) => {
if (!req.body.newCategory) {
callback({ status: 'error', message: '沒有輸入類別' })
}
else {
Category.create({
name: req.body.newCategory
}).then(() => {
callback({ status: 'success', message: '新增成功' })
})
}
},
editCategory: (req, res, callback) => {
Category.findByPk(req.params.id)
.then(category => {
category.update({
name: req.body.editCategory
}).then(() => {
callback({ status: 'success', message: '修改成功' })
})
})
},
deleteCategory: (req, res, callback) => {
Category.findByPk(req.params.id)
.then(category => {
category.destroy().then(() => {
callback({ status: 'success', message: '刪除成功' })
})
})
},
getUser: (req, res, callback) => {
User.findAll().then(users => {
callback({ status: 'success', message: { users: users } })
})
},
putUser: (req, res, callback) => {
User.findByPk(req.params.id).then(user => {
user.update({
isAdmin: !user.isAdmin
}).then(user => {
callback({ status: 'success', message: '權限變更成功' })
})
})
},
getAllCategory: (req, res, callback) => {
Category.findAll().then(categories => {
callback({ status: 'success', message: { categories: categories } })
})
},
editCategoryPage: (req, res, callback) => {
Category.findAll().then(categories => {
Category.findByPk(req.params.id)
.then(category => {
callback({ status: 'success', message: { categories: categories, category: category } })
})
})
},
}
module.exports = adminService
<file_sep>const db = require('../models')
const Restaurant = db.Restaurant
const Category = db.Category
const Comment = db.Comment
const User = db.User
const Like = db.Like
const resController = {
getRes: (req, res) => {
let wherequery = {}
let categoryId = ''
if (req.query.categoryId) {
categoryId = Number(req.query.categoryId)
wherequery['CategoryId'] = categoryId
}
let pageLimit = 10
let offSet = 0
if (req.query.page) {
offSet = (Number(req.query.page) - 1) * pageLimit
}
Restaurant.findAndCountAll({ include: [Category], where: wherequery, offset: offSet, limit: pageLimit }).then(result => {
//console.log(restaurants)
let page = Number(req.query.page) || 1
let pages = Math.ceil(result.count / 10)
let totalPage = Array.from({ length: pages }, (value, index) => index + 1)
let prev = page - 1 < 0 ? 1 : page - 1
let next = page + 1 > pages ? pages : page + 1
//console.log('next:', next)
//console.log('req.user.LikeRestaurants: ', req.user.LikeRestaurants)
// let aaa = req.user.FavoritedRestaurants.map(d => d.id)
// console.log('req.user.FavoritedRestaurants: ', aaa)
let data = result.rows.map(r => (
{
...r.dataValues,
description: r.dataValues.description.substring(0, 50),
//加入最愛判斷
isFavorited: req.user.FavoritedRestaurants.map(d => d.id).includes(r.id),
isLike: req.user.LikeRestaurants.map(d => d.id).includes(r.id)
}
))
Category.findAll().then(categories => {
return res.render('resList', JSON.parse(JSON.stringify({ restaurants: data, categories: categories, categoryId: categoryId, totalPage: totalPage, prev: prev, next: next, page: page })))
})
})
},
getARes: (req, res) => {
Restaurant.findByPk(req.params.id, {
include: [
Category,
{ model: Comment, include: [User] },
{ model: User, as: 'FavoritedUsers' },
{ model: User, as: 'LikeUsers' }
]
})
.then(restaurant => {
restaurant.update({
//點擊次數加一
clicks: restaurant.clicks + 1
}).then(restaurant => {
const isFavorited = restaurant.FavoritedUsers.map(d => d.id).includes(req.user.id)
const isLike = restaurant.LikeUsers.map(d => d.id).includes(req.user.id)
return res.render('guestRestaurant', JSON.parse(JSON.stringify({ restaurant: restaurant, isFavorited: isFavorited, isLike: isLike })))
})
})
},
getFeeds: (req, res) => {
return Restaurant.findAll({
limit: 10,
order: [['createdAt', 'DESC']],
include: [Category]
}).then(restaurants => {
Comment.findAll({
limit: 10,
order: [['createdAt', 'DESC']],
include: [User, Restaurant]
}).then(comments => {
return res.render('feeds', JSON.parse(JSON.stringify({
restaurants: restaurants,
comments: comments
})))
})
})
},
getResPopular: (req, res) => {
Restaurant.findByPk(req.params.id, { include: [Comment] }).then(restaurant => {
const commentNumber = restaurant.Comments.length
res.render('getResPopular', JSON.parse(JSON.stringify({ restaurant: restaurant, commentNumber: commentNumber })))
})
},
popularRes: (req, res) => {
Restaurant.findAll({
include: { model: User, as: 'FavoritedUsers' }
}).then(restaurants => {
//console.log('restaurants[0].FavoritedUsers.', restaurants[0].FavoritedUsers)
restaurants = restaurants.map(r => (
{
...r.dataValues,
FavoriteNumber: r.FavoritedUsers.length,
description: r.dataValues.description.substring(0, 50),
isFavorited: req.user.FavoritedRestaurants.map(d => d.id).includes(r.id)
}))
restaurants = restaurants.sort((a, b) => b.FavoriteNumber - a.FavoriteNumber).slice(1, 11)
//console.log('restaurants:', restaurants)
return res.render('popularRes', JSON.parse(JSON.stringify({ restaurants: restaurants })))
})
},
}
module.exports = resController<file_sep>var body = document.querySelector('body')
var whiteback = document.getElementById("whiteback")
body.addEventListener("click", function (event) {
console.log(event.target.id)
if (event.target.id === 'delete') {
event.preventDefault()
// console.log(event)
// console.log(event.target.attributes.href.value)
whiteback.querySelector('form').action = `/admin/restaurant/${event.target.attributes.href.value}?_method=DELETE`
whiteback.style.display = "block"
}
if (event.target.id == 'cancel' || event.target.id == "whiteback") {
whiteback.style.display = "none"
}
});<file_sep>const express = require('express')
const router = express.Router()
const passport = require('../config/passport')
const resController = require('../controllers/resController')
const adminController = require('../controllers/adminController')
const userController = require('../controllers/userController')
const commentController = require('../controllers/commentController')
const multer = require('multer')
const upload = multer({ dest: 'temp/' })
const authenticate = (req, res, next) => {
if (req.isAuthenticated()) { return next() }
res.redirect('/signin')
}
const isAdmin = (req, res, next) => {
if (req.isAuthenticated()) {
if (req.user.isAdmin) { return next() }
}
res.redirect('/signin')
}
router.get('/', authenticate, (req, res) => { res.redirect('/restaurant') })
router.get('/restaurant', authenticate, resController.getRes)
router.get('/restaurant/feeds', authenticate, resController.getFeeds)
//熱門餐廳頁面
router.get('/restaurant/top', authenticate, resController.popularRes)
router.get('/restaurant/:id', authenticate, resController.getARes)
//餐廳熱門度頁面
router.get('/restaurant/:id/popular', authenticate, resController.getResPopular)
router.get('/admin', isAdmin, (req, res) => { res.redirect('/admin/restaurant') })
router.get('/admin/restaurant', isAdmin, adminController.adminGetRes)
router.get('/signup', userController.signUpPage)
router.post('/signup', userController.signUp)
router.get('/signin', userController.signInPage)
router.post('/signin', passport.authenticate('local', {
failureRedirect: '/signin',
failureFlash: true
}), userController.signIn)
router.get('/logout', userController.logOut)
//新增餐廳頁面
router.get('/admin/restaurant/create', isAdmin, adminController.createResPage)
//新增一筆餐廳
router.post('/admin/restaurant', isAdmin, upload.single('image'), adminController.createRes)
//瀏覽一筆餐廳
router.get('/admin/restaurant/:id', isAdmin, adminController.getRes)
//刪除一筆餐廳
router.delete('/admin/restaurant/:id', isAdmin, adminController.deleteRes)
//修改餐廳頁面
router.get('/admin/restaurant/:id/edit', isAdmin, adminController.editResPage)
//修改一筆餐廳
router.put('/admin/restaurant/:id/edit', isAdmin, upload.single('image'), adminController.editRes)
//使用者頁面
router.get('/admin/user', isAdmin, adminController.getUser)
//修改使用者權限
router.put('/admin/user/:id', isAdmin, adminController.putUser)
//所有餐廳類別頁面
router.get('/admin/category', isAdmin, adminController.getAllCategory)
//新增餐廳類別
router.post('/admin/category/create', isAdmin, adminController.createCategory)
//修改餐廳類別頁面
router.get('/admin/category/:id/edit', isAdmin, adminController.editCategoryPage)
//修改餐廳類別
router.put('/admin/category/:id/edit', isAdmin, adminController.editCategory)
//刪除餐廳類別
router.delete('/admin/category/:id/delete', isAdmin, adminController.deleteCategory)
//新增評論
router.post('/comment', authenticate, commentController.createComment)
//刪除評論
router.delete('/comment/:id', isAdmin, commentController.deleteComment)
//追隨人頁面
router.get('/user/top', authenticate, userController.getTopUser)
//追隨
router.post('/following/:userId', authenticate, userController.follow)
//取消追隨
router.delete('/following/:userId', authenticate, userController.cancelFollow)
//編輯個人資料
router.put('/user/:id/edit', authenticate, upload.single('avatar'), userController.editUser)
//個人資料頁面
router.get('/user/:id', authenticate, userController.userPage)
//編輯個人資料頁面
router.get('/user/:id/edit', authenticate, userController.editUserPage)
//加入最愛
router.post('/user/:id/favorite', authenticate, userController.addFavorite)
//刪除最愛
router.delete('/user/:id/favorite', authenticate, userController.deleteFavorite)
//按讚
router.post('/like/:restaurantId', authenticate, userController.like)
//取消讚
router.delete('/cancellike/:restaurantId', authenticate, userController.cancelLike)
//fb登入
router.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'public_profile'] }));
router.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/signin' }), userController.signIn);
//google登入
router.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/signin' }), userController.signIn);
module.exports = router
| d915524770bd7961a4d63954d21d062eec496eb5 | [
"JavaScript"
] | 10 | JavaScript | duaifzn/res_forum | e4546e1b31fb47c4a100d161f234396895283c9c | be2d41e599cba14c784b5588700f108665d32fd1 |
refs/heads/master | <file_sep>let pronoun = ['the', 'our'];
let adj = ['great', 'big'];
let noun = ['jogger', 'racoon'];
var texto = ""
for (var i = 0; i < pronoun.length; i++) {
for (var j = 0; j < adj.length; j++) {
for (var a = 0; a < noun.length; a++) {
console.log(pronoun[i] + " " + adj[j] + " " + noun[a] + ".com")
}
}
} | 6beb45390d56b176029b654bccc7085636c935b0 | [
"JavaScript"
] | 1 | JavaScript | felipemat6767/DomGenerator | 5aab1c7ef5d8e022a15c92da0d76f3cdd26268a4 | f596d308866a74f18f4e08dca402c8da4c473d64 |
refs/heads/master | <repo_name>suzanamelomoraes/loan-calculator<file_sep>/README.md
# Loan calculator
Application in vanilla JS that allows the user to calculate loans.
The user can calculate loans after inform values of amount, interest and years to repay. The calculator returns the cost of the monthly payment and how much is going to be the total payment and total interest of the loan.
The main goal of this project is to practice to grab and manipulate classes and ids from HTML using vanilla JavaScript, manipulate the data and return the information the uses is waiting for.
This application is one of the projects developed in the course Modern JavaScript from the Beginning by Udemy/<NAME>.
### Technologies:
- JavaScript
- Bootstrap for styling
- JQuery(link included only as dependency)
<file_sep>/app.js
document.getElementById("loan-form").addEventListener("submit", function(e) {
document.getElementById("results").style.display = "none";
document.getElementById("loading").style.display = "block";
setTimeout(calculateResults, 2000);
e.preventDefault();
});
function calculateResults() {
const amountUI = document.getElementById("amount"),
interestUI = document.getElementById("interest"),
yearsUI = document.getElementById("years"),
monthlyPaymentUI = document.getElementById("monthly-payment"),
totalPaymentUI = document.getElementById("total-payment"),
totalInterestUI = document.getElementById("total-interest"),
initialAmount = parseFloat(amountUI.value),
calculatedInterest = interestUI.value / 100 / 12,
calculatedPayments = parseFloat(yearsUI.value) * 12,
x = Math.pow(1 + calculatedInterest, calculatedPayments),
monthly = (initialAmount * x * calculatedInterest) / (x - 1);
if (isFinite(monthly)) {
monthlyPaymentUI.value = monthly.toFixed(2);
totalPaymentUI.value = (monthly * calculatedPayments).toFixed(2);
totalInterestUI.value = (
monthly * calculatedPayments -
initialAmount
).toFixed(2);
document.getElementById("results").style.display = "block";
document.getElementById("loading").style.display = "none";
} else {
showError("Please check your numbers");
}
}
function showError(error) {
document.getElementById("results").style.display = "none";
document.getElementById("loading").style.display = "none";
const errorDiv = document.createElement("div"),
card = document.querySelector(".card"),
heading = document.querySelector(".heading");
errorDiv.className = "alert alert-danger";
errorDiv.appendChild(document.createTextNode(error));
card.insertBefore(errorDiv, heading);
setTimeout(clearError, 2000);
}
function clearError() {
document.querySelector(".alert").remove();
}
| 8be6e98e140282b96bbd6ddd78f7bf54c1ee5204 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | suzanamelomoraes/loan-calculator | aa9028aada3e4cbc159a7d3216d35f17eb3761f2 | b8d7c7827cd561813e91b06768cfbd5e186955ab |
refs/heads/master | <file_sep><div class ="index">
<h3>Listado de Productos</h3>
<table>
<tr>
<tr>
<th><?php echo $this -> Paginator -> sort('name', 'Name') ?></th>
<th><?php echo $this -> Paginator -> sort('id_local', 'Local') ?></th>
<th><?php echo $this -> Paginator -> sort('amount', 'Amount') ?></th>
</tr>
</tr>
<?php foreach ($Product as $k => $Product) :?>
<tr>
<td><?php echo h($Product['Product']['name']); ?></td>
<td><?php echo h($Product['Product']['id_local']); ?></td>
<td><?php echo h($Product['Product']['amount']) ;?></td>
</tr>
<?php endforeach;?>
</table>
</div>
<file_sep># Almacen
Trabajo para Ingenieria de software 2, modulo - almacen
# CakePHP Application Skeleton
[](https://travis-ci.org/cakephp/app)
[](https://packagist.org/packages/cakephp/app)
A skeleton for creating applications with [CakePHP](http://cakephp.org) 3.0.
## Installation
Step 1:
Open terminal.
Step 2:
Type cd /var/www/html
Step 3:
Type this command to download CakePHP:
$ sudo wget https://codeload.github.com/cakephp/cakephp/legacy.zip/2.5.2
where 2.5.2 is the latest stable version of CakePHP.
Step 4: It will be downloaded in zip format. To extract it type this command:
$ sudo unzip 2.5.2
Step 5:
Rename extracted folder.
$ mv cakephp-cakephp-736e999/ cake
where cakephp-cakephp-736e999 is the name of extracted folder.
To run CakePHP on browser use this path localhost/cake.
Step 6:
Go to cake folder.
$ cd cake
And change permissions to app/tmp folder.
$ sudo chown -R root:www-data app/tmp
$ sudo chmod -R 775 app/tmp
$sudo chmod 777 -R .
Step 7:
To make script writable perform these steps:
$ apache2ctl -M
If you see mod_rewrite in the list shown then script is writable. If not then to enable it type this command:
$ a2enmod rewrite
Step 8:
Type cd /etc/apache2
$ sudo nano apache2.conf
Set these lines in the file:
<Directory /var/www>
Option Indexes FollowSymlinks
AllowOverride All
Required all granted
</Directory>
Press ctrl+x, then press y and enter to save the file.
sudo nano/etc/apache2/httpd.conf
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
Enabling mod_rewrite
$ sudo a2enmod rewrite
$sudo nano /etc/apache2/sites-avaliable/default.conf (AllOverride None to AllOverride All)
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
<Directory /var/www>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order Allow,Deny
Allow from all
</Directory>
Restart apache:
$ sudo service apache2 restart
$ apt-get install php5-pgsql
$ sudo service apache2 restart
## Configuration
Configure Debug Kit
Step 1
Ensure require is present in composer.json. This will install the plugin into Plugin/DebugKit:
{
"require": {
"cakephp/debug_kit": "2.2.*"
}
}
STEP 2:
Then, in your app/Config/bootstrap.php, add (or un-comment) the following line:
CakePlugin::load('DebugKit');
STEP 3:
Ensure debug is 1 or more
In your Config/core.php file, make sure this line:
Configure::write('debug', 2);
has a value of 1 or 2. (read more about debug mode here)
Login
$ psql -U cakeuser -d cakedb
And finally in psql console, set password
Postgress:
cakedb=> \password cakeuser
Enter new password: secret
Enter it again: secret
In Cakephp root, rename the file Config\database.php.default to Config\database.php. Change the $default variable as below :-
public $default = array(
'datasource' => 'Database/Postgres',
'persistent' => false,
'host' => 'localhost',
'login' => 'cakeuser',
'password' => '<PASSWORD>',
'database' => 'cakedb',
'prefix' => '',
//'encoding' => 'utf8',
);
Step 4:
To remove the salt and seed error shown on top of the localhost/cake page we have to edit core.php file.
$ sudo nano core.php
Find this section and replace both the strings with any random strings or you can use these strings also.
/* A random string used in security hashing methods. */
Configure::write(‘Security.salt’, ‘fvjhdj8fvn85grg73fbrvfn9fjFGfnhvt758nADG‘);
/* A random numeric string (digits only) used to encrypt/decrypt strings. */
Configure::write(‘Security.cipherSeed’, ‘55857485748594575784348784787475‘);
Then press ctrl+x, press y and enter to save file.
Refresh localhost/cake page. And its done.
<file_sep><?php
class PurchaseOrderController extends AppController{
public $paginate = array(
'limit' => 10
);
public $helpers = array('Html', 'Form');
public $components = array('Session');
public function index(){
//$this->set('Orden_de_compra', $this->PurchaseOrder->find('all'));
$this -> PurchaseOrder -> recursive = 0;
$this -> set('Orden_de_compra', $this -> paginate());
}
public function add(){
if($this->request->is('post')):
if( $this -> PurchaseOrder->save($this -> request -> data) ):
$this -> Session -> setFlash('Orden guardada');
$this -> redirect(array('action' => 'index'));
endif;
endif;
}
}<file_sep>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php echo $this->Html->charset(); ?>
<title>
<?php echo $title_for_layout; ?>
</title>
<?php
echo $this->Html->meta('icon');
echo $this->Html->css('bootstrap');
echo $this->Html->css('style');
echo $this->Html->css('fonts');
echo $this->Html->css('reset');
echo $this->Html->css('clndr');
echo $this->Html->script('bootstrap');
echo $this->Html->script('clndr');
echo $this->Html->script('site');
echo $this->Html->script('underscore-min');
echo $this->Html->script('jquery.easing.1.3');
echo $this->Html->script('jquery.min');
echo $this->Html->script('responsiveslides.min');
echo $this->Html->script('mediaelement-and-player.min');
?>
</head>
<body>
<div class="main">
<div class="container">
<div class="logo">
<img src="img/almacen.png" alt="">
</div>
<div class="top-header">
<nav class="navbar navbar-default menu">
<!-- Brand and toggle get grouped for better mobile display -->
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav" id= "menu">
<li class="active"><a href="http://localhost/Almacen/Almacen2.0/">Home <span class="sr-only">(current)</span></a></li>
<li><?php echo $this->Html->link(__('Provider'), array('controller'=>'Providers')); ?></li>
<li><?php echo $this->Html->link(__('Product'), array('controller'=>'Products')); ?></li>
<li><?php echo $this->Form->postLink(__('Purchase Orders'), array('controller'=>'PurchaseOrders')); ?></li>
</ul>
</div><!-- /.navbar-collapse -->
<!-- /.container-fluid -->
<div id="content">
<?php echo $this->Session->flash(); ?>
<?php echo $this->fetch('content'); ?>
</div>
</nav>
</div>
<div class="banner">
<script>
$(function () {
$("#slider").responsiveSlides({
auto: true,
nav: true,
speed: 500,
namespace: "callbacks",
});
});
</script>
<div id="top" class="callbacks_container">
<ul class="rslides" id="slider">
<li>
<div class="banner-text">
<h4>UCSP </h4>
<h3> PROVIDER.</h3>
<a href="#"><i> </i>read more</a>
</div>
</li>
<li>
<div class="banner-text">
<h4> UCSP</h4>
<h3> PRODUCT.</h3>
<a href="#"><i> </i>read more</a>
</div>
</li>
<li>
<div class="banner-text">
<h4> UCSP</h4>
<h3> PURCHASE ORDERS.</h3>
<a href="#"><i> </i>read more</a>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div id="container">
<div class="footer-bottom">
<p>© <NAME> | <NAME> | <NAME> | <NAME> <a href="" target="_blank"> Ing. Soft. 2</a> </p>
<ul class="social in-social">
<li><a href="#"> <i></i></a></li>
<li><a href="#"> <i class="twitter"></i></a></li>
</ul>
<div class="clearfix"> </div>
</div>
</div>
</div>
<?php echo $this->element('sql_dump'); ?>
</body>
</html>
<file_sep><div class="purchaseOrders view">
<h2><?php echo __('Purchase Order'); ?></h2>
<dl>
<dt><?php echo __('Product: '); ?></dt>
<dd>
<?php echo $this->Html->link($purchaseOrder['Product']['name'], array('controller' => 'products', 'action' => 'view', $purchaseOrder['Product']['id'])); ?>
</dd>
<dt><?php echo __('Provider'); ?></dt>
<dd>
<?php echo $this->Html->link($purchaseOrder['Provider']['name'], array('controller' => 'providers', 'action' => 'view', $purchaseOrder['Provider']['id'])); ?>
</dd>
<dt><?php echo __('Date'); ?></dt>
<dd>
<?php echo h($purchaseOrder['PurchaseOrder']['date']); ?>
</dd>
<dt><?php echo __('Num Bill'); ?></dt>
<dd>
<?php echo h($purchaseOrder['PurchaseOrder']['num_bill']); ?>
</dd>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($purchaseOrder['PurchaseOrder']['id']); ?>
</dd>
<dt><?php echo __('Num Po'); ?></dt>
<dd>
<?php echo h($purchaseOrder['PurchaseOrder']['num_po']); ?>
</dd>
<dt><?php echo __('Modified'); ?></dt>
<dd>
<?php echo h($purchaseOrder['PurchaseOrder']['modified']); ?>
</dd>
<dt><?php echo __('Created'); ?></dt>
<dd>
<?php echo h($purchaseOrder['PurchaseOrder']['created']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Purchase Order'), array('action' => 'edit', $purchaseOrder['PurchaseOrder']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Purchase Order'), array('action' => 'delete', $purchaseOrder['PurchaseOrder']['id']), null, __('Are you sure you want to delete # %s?', $purchaseOrder['PurchaseOrder']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Purchase Orders'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Purchase Order'), array('action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Products'), array('controller' => 'products', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Product'), array('controller' => 'products', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Providers'), array('controller' => 'providers', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Provider'), array('controller' => 'providers', 'action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><?php
App::uses('AppController', 'Controller');
/**
* PurchaseOrders Controller
*
* @property PurchaseOrder $PurchaseOrder
*/
class PurchaseOrdersController extends AppController {
/**
* Helpers
*
* @var array
*/
public $helpers = array('Js');
/**
* index method
*
* @return void
*/
public function index() {
$this->PurchaseOrder->recursive = 0;
$this->set('purchaseOrders', $this->paginate());
}
/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
$this->PurchaseOrder->id = $id;
if (!$this->PurchaseOrder->exists()) {
throw new NotFoundException(__('Invalid purchase order'));
}
$this->set('purchaseOrder', $this->PurchaseOrder->read(null, $id));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->PurchaseOrder->create();
if ($this->PurchaseOrder->save($this->request->data)) {
$this->Session->setFlash(__('The purchase order has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The purchase order could not be saved. Please, try again.'));
}
}
$products = $this->PurchaseOrder->Product->find('list');
$providers = $this->PurchaseOrder->Provider->find('list');
$this->set(compact('products', 'providers'));
}
/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
$this->PurchaseOrder->id = $id;
if (!$this->PurchaseOrder->exists()) {
throw new NotFoundException(__('Invalid purchase order'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->PurchaseOrder->save($this->request->data)) {
$this->Session->setFlash(__('The purchase order has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The purchase order could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->PurchaseOrder->read(null, $id);
}
$products = $this->PurchaseOrder->Product->find('list');
$providers = $this->PurchaseOrder->Provider->find('list');
$this->set(compact('products', 'providers'));
}
/**
* delete method
*
* @throws MethodNotAllowedException
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->PurchaseOrder->id = $id;
if (!$this->PurchaseOrder->exists()) {
throw new NotFoundException(__('Invalid purchase order'));
}
if ($this->PurchaseOrder->delete()) {
$this->Session->setFlash(__('Purchase order deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Purchase order was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
<file_sep><?php
$this->layout = 'home';
?>
<h1> Bienvenido al almacén</h1>
<script type="text/javascript">
var js = jQuery.noConflict();
(function($){
js(document).ready(function(){
js('#noticia-principal').load('html/article.html', function(){});
js('#video').load('html/video.html', function(){});
//js('#noticias-rel').load('html/articles.html', function(){});
js('#podcast-rel').load('html/audio.html', function(){});
});
})(jQuery);
</script><file_sep><div class ="index">
<h3>Listado de Ordenes de Compra</h3>
<table>
<tr>
<tr>
<th><?php echo $this -> Paginator -> sort('id_product', 'Id Producto') ?></th>
<th><?php echo $this -> Paginator -> sort('id_provider', 'Id Provedor') ?></th>
<th><?php echo $this -> Paginator -> sort('date', 'Fecha') ?></th>
<th><?php echo $this -> Paginator -> sort('num_bill' , 'Numero de Factura') ?></th>
<th><?php echo $this -> Paginator -> sort('id', 'Id') ?></th>
</tr>
</tr>
<?php foreach ($Orden_de_compra as $k => $Orden_de_compra) :?>
<tr>
<td><?php echo h($Orden_de_compra['PurchaseOrder']['id_product']); ?></td>
<td><?php echo h($Orden_de_compra['PurchaseOrder']['id_provider']) ;?></td>
<td><?php echo h($Orden_de_compra['PurchaseOrder']['date']) ;?></td>
<td><?php echo h($Orden_de_compra['PurchaseOrder']['num_bill']) ;?></td>
<td><?php echo h($Orden_de_compra['PurchaseOrder']['id']) ;?></td>
</tr>
<?php endforeach;?>
</table>
<p>
<?php echo $this -> Paginator -> counter(
array('format' => 'Pagina {:page} de {:pages}, mostrando {:current} registros de {:count}'))
?>
</p>
<div class = "paging">
<?php echo $this -> Paginator -> prev('< anterior', array(), null, array('class' => 'prev disabled'));?>
<?php echo $this -> Paginator -> numbers(array('separador' => '')) ?>
<?php echo $this -> Paginator -> next('siguiente >' , array(), null, array('class' => 'next disabled')) ?>
</div>
</div>
<file_sep><?php
class PurchaseOrder extends AppModel{
public $displayField = 'num_op'
} <file_sep><div class = "add">
<?php echo $this->Form->create('Product'); ?>
<fieldset>
<legend> Agregar proveedor </legend>
<?php echo $this->Form->input('name', array('label' => 'Nombre del producto')); ?>
<?php echo $this->Form->input('id_local', array('label' => 'Local')); ?>
<?php echo $this->Form->input('amount', array('label' => 'Amount')); ?>
</fieldset>
<?php echo $this->Form->end('Guardar Proveedor'); ?>
</div><file_sep>
<!DOCTYPE html>
<html>
<head>
<?php echo $this->Html->charset(); ?>
<title>
<?php echo $this->fetch('title'); ?>
</title>
<?php
echo $this->Html->meta('icon');
echo $this->Html->css(array('reset','style','fonts','http://fonts.googleapis.
com/css?family=Amaranth,cake.generic'));
echo $this->Html->script(array('jquery-1.7.2.min'));
echo $this->fetch('meta');
echo $this->fetch('css');
echo $this->fetch('script');
?>
</head>
<body>
<header>
<h1>Módulo Almacen</h1>
<nav>
<ul>
<li><a href="Provider">Proveedor</a></li>
<li><a href="#">Producto</a></li>
<li><a href="#">Orden de entrega</a></li>
<li><a href="#">Login</a></li> </ul>
</nav>
</header>
<div class="wrapper_all">
<section class="content">
<section id="render_cake">
<?php echo $this->Session->flash(); ?>
<?php echo $this->fetch('content'); ?>
</section>
<section id="video">
</section>
<aside id="podcast-rel">
</aside>
</section>
<section class="content">
<section id="noticia-principal">
</section>
<aside id="noticias-rel">
<?php echo $this->element('ultimos')?>
</aside>
</section>
</div>
<footer>
</footer>
<?php echo $this->element('sql_dump'); ?>
</body>
</html>
<file_sep><?php
App::uses('AppModel', 'Model');
/**
* PurchaseOrder Model
*
* @property Product $Product
* @property Provider $Provider
*/
class PurchaseOrder extends AppModel {
/**
* Display field
*
* @var string
*/
public $displayField = 'num_po';
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'product_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Provider' => array(
'className' => 'Provider',
'foreignKey' => 'provider_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
<file_sep><div class ="index">
<h3>Listado de Proveedores</h3>
<table>
<tr>
<tr>
<th><?php echo $this -> Paginator -> sort('name', 'Name') ?></th>
<th><?php echo $this -> Paginator -> sort('adress', 'Adress') ?></th>
<th><?php echo $this -> Paginator -> sort('ruc', 'Fecha') ?></th>
</tr>
</tr>
<?php foreach ($Provider as $k => $Provider) :?>
<tr>
<td><?php echo h($Provider['Provider']['name']); ?></td>
<td><?php echo h($Provider['Provider']['adress']) ;?></td>
<td><?php echo h($Provider['Provider']['ruc']) ;?></td>
</tr>
<?php endforeach;?>
</table>
<p>
<?php echo $this->Paginator->counter(
array('fortmat' => 'Pagina {:page} de {:pages},mostrando {:current} registros de {:count}')
);?>
</p>
<div class="paging">
<?php echo $this->Paginator->prev('< anterior', array(), null, array('class'=>'prev disabled'
));?>
<?php echo $this->Paginator->numbers(array('separator'=>''));?>
<?php echo $this->Paginator->next('siguiente >', array(),null,array('class'=>'next disabled'));?>
<a href="Provider/add">Agregar</a>
</div>
<file_sep><?php
class ProductController extends AppController{
public $helpers = array('Html', 'Form');
public $components = array('Session');
public function index(){
//$this->set('Orden_de_compra', $this->PurchaseOrder->find('all'));
$this -> Product -> recursive = 0;
$this-> set('Product', $this -> paginate());
}
public function add(){
if($this->request->is('post')):
if( $this->Product->save($this->request->data) ):
$this->Session->setFlash('Producto guardado');
$this->redirect(array('action' => 'index'));
endif;
endif;
}
}<file_sep><?php
$this->layout='default';
?>
<file_sep><div class="providers view">
<h2><?php echo __('Provider'); ?></h2>
<dl>
<dt><?php echo __('Name'); ?></dt>
<dd>
<?php echo h($provider['Provider']['name']); ?>
</dd>
<dt><?php echo __('Adress'); ?></dt>
<dd>
<?php echo h($provider['Provider']['adress']); ?>
</dd>
<dt><?php echo __('Ruc'); ?></dt>
<dd>
<?php echo h($provider['Provider']['ruc']); ?>
</dd>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($provider['Provider']['id']); ?>
</dd>
<dt><?php echo __('Modified'); ?></dt>
<dd>
<?php echo h($provider['Provider']['modified']); ?>
</dd>
<dt><?php echo __('Created'); ?></dt>
<dd>
<?php echo h($provider['Provider']['created']); ?>
</dd>
<dt><?php echo __('Local Id'); ?></dt>
<dd>
<?php echo h($provider['Provider']['local_id']); ?>
</dd>
</dl>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('Edit Provider'), array('action' => 'edit', $provider['Provider']['id'])); ?> </li>
<li><?php echo $this->Form->postLink(__('Delete Provider'), array('action' => 'delete', $provider['Provider']['id']), null, __('Are you sure you want to delete # %s?', $provider['Provider']['id'])); ?> </li>
<li><?php echo $this->Html->link(__('List Providers'), array('action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Provider'), array('action' => 'add')); ?> </li>
</ul>
</div>
<file_sep><br>
<div class="purchaseOrders form">
<?php echo $this->Form->create('PurchaseOrder'); ?>
<fieldset>
<legend><?php echo __('Add Purchase Order'); ?></legend>
<br>
<?php
echo $this->Form->input('product_id');
echo $this->Form->input('provider_id');
echo $this->Form->input('date');
echo $this->Form->input('num_bill');
echo $this->Form->input('num_po');
?>
</fieldset><br>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<br>
<br>
<div class="row">
<div class="col-md-4 mid-load">
<div class="mid-content col-md1">
<h5><span><?php echo $this->Html->link(__('List Purchase Orders'), array('action' => 'index')); ?></span></h5>
<h5><span><?php echo $this->Html->link(__('List Products'), array('controller' => 'products', 'action' => 'index')); ?></span></h5>
<h5><span><?php echo $this->Html->link(__('List Providers'), array('controller' => 'providers', 'action' => 'index')); ?></span></h5>
</div>
</div>
<div class="col-md-4 mid-load">
<div class="mid-content col-md1">
<h5><span><?php echo $this->Html->link(__('+New Product'), array('controller' => 'products', 'action' => 'add')); ?></span></h5>
<h5><span><?php echo $this->Html->link(__('+New Provider'), array('controller' => 'providers', 'action' => 'add')); ?></span></h5>
</div>
</div>
</div>
<file_sep><?php
class Provider extends AppModel{
}
<file_sep><?php
class ProviderController extends AppController{
public $helpers = array('Html', 'Form');
public $components = array('Session');
public function index(){
$this -> Provider -> recursive = 0;
$Provider = $this -> paginate();
if($this->request->is('request')):
return $Provider;
else:
$this->set('Provider', $Provider);
endif;
}
public function add(){
if($this->request->is('post')):
if( $this->Provider->save($this->request->data) ):
$this->Session->setFlash('Proveedor guardado');
$this->redirect(array('action' => 'index'));
endif;
endif;
}
}<file_sep><h1>Proveedores</h1>
<file_sep><div class = "add">
<?php echo $this->Form->create('Provider'); ?>
<fieldset>
<legend> Agregar proveedor </legend>
<?php echo $this->Form->input('name', array('label' => 'Nombre del proveedor')); ?>
<?php echo $this->Form->input('address', array('label' => 'Direccion')); ?>
<?php echo $this->Form->input('ruc', array('label' => 'RUC')); ?>
</fieldset>
<?php echo $this->Form->end('Guardar Proveedor'); ?>
</div><file_sep><div class = "add">
<?php echo $this->Form->create('PurchaseOrder'); ?>
<fieldset>
<legend> Agregar orden de compra </legend>
<?php echo $this->Form->input('num_bill', array('label' => 'Numero de Factura')); ?>
</fieldset>
<?php echo $this->Form->end('Guardar Orden'); ?>
</div> | c61dcdd23bba516cb8e930dfeca5a42fd9c7cfb5 | [
"Markdown",
"PHP"
] | 22 | PHP | dantecarlo/Almacen | ea984e80eb6d148e0d291bf89b2414900d827ec1 | cfa2d8bf9a08656a3afb5d2da98c037f53abfa88 |
refs/heads/master | <repo_name>a139169370/Modify_Naserver_UsersPassword<file_sep>/ReadMe.md
在导入Excel的时候密码第一位为0时Excel自动将0抛弃;脚本将所有5位数密码更改为0+原5位数密码,即“<PASSWORD>”;
因避免密码泄露,未提交.class文件和user.java文件,若有需要请自己添加
-by 龙猫
-2018/10/16
<file_sep>/src/Main.java
/*
function:在导入Excel的时候密码第一位为0时Excel自动将0抛弃;脚本将所有5位数密码更改为0+原5位数密码,即“身份证后6位”;
author:龙猫
date:2018/10/16
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main implements user{
public static void main(String[] args) {
Connection conn = null ;
Statement myStatement = null;
ResultSet mySet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Class.forName("com.mysql.jdbc.Driver ");
conn = DriverManager.getConnection(url,user,password); //账号密码,自定义
myStatement = conn.createStatement(); //建立JDBC连接
}catch (Exception e){
e.printStackTrace();
}
try{
int time = 0,max = 1; //设置运行次数
mySet = myStatement.executeQuery("select * from users where length(password) < 6;"); //向数据库查询记录
while (mySet.next() & time < max) {
String uid = mySet.getString("uid"); //获取数据库的值
String password = mySet.getString("password");
System.out.println("重置前学号为:" + uid + ",密码为:" + password);
password = "0" + password; //将密码前面 + “0”
String sql = "update users set password = '" + password + "' where uid = '" + uid + "';"; //将要插入数据库的语句
myStatement.executeUpdate(sql); //将语句插入数据库
System.out.println("已成功重置学号为:" + uid + "的用户密码为:" + password);
time++;
mySet = myStatement.executeQuery("select * from users where length(password) < 6;"); //重新查询
}
}catch(Exception e){
e.printStackTrace();
}finally {
try {
mySet.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
| bd1807230d470d5c10e9f1d6e7f6c4a51ac35398 | [
"Markdown",
"Java"
] | 2 | Markdown | a139169370/Modify_Naserver_UsersPassword | 2fd145931146879aa158a715448e958cd8cf9de9 | f94a2573a3483a7f75cb5e977309750c1c1a9229 |
refs/heads/master | <repo_name>okayamarb/pheasant-app<file_sep>/middleman/Gemfile
source 'http://rubygems.org'
gem 'therubyracer'
gem 'uglifier', '>= 1.3.0'
gem 'slim', '~>2.0.2'
gem 'middleman', '~>3.2.2'
gem 'rack-cors', require: 'rack/cors'
# Live-reloading plugin
gem 'middleman-livereload', '~> 3.1.0'
# For faster file watcher updates on Windows:
gem "wdm", "~> 0.1.0", :platforms => [:mswin, :mingw]<file_sep>/middleman/config.rb
require 'cordova'
require 'uglifier'
set :debug_assets, true
after_configuration do
sprockets.append_path "#{root}/bower_components/"
end
activate :cordova
activate :automatic_image_sizes
activate :livereload
with_layout :plain do
page '/views/*'
end
configure :build do
ignore 'js/lib/*'
ignore 'css/lib/*'
activate :minify_css
activate :minify_javascript, compressor: Uglifier.new(mangle: false)
activate :asset_hash
activate :relative_assets
end
use Rack::Cors do
# allow do
# origins 'localhost:3000', '127.0.0.1:3000',
# /http:\/\/192\.168\.0\.\d{1,3}(:\d+)?/
# # regular expressions can be used here
#
# resource '/file/list_all/', :headers => 'x-domain-token'
# resource '/file/at/*',
# :methods => [:get, :post, :put, :delete, :options],
# :headers => 'x-domain-token',
# :expose => ['Some-Custom-Response-Header'],
# :max_age => 600
# # headers to expose
# end
#
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options],
credentials: true,
max_age: 86400
end
end
| 3bcc6cefe36a19812fbba68e6411a44d46d730f9 | [
"Ruby"
] | 2 | Ruby | okayamarb/pheasant-app | 3f7cae6fb3054325d93aa4f7b616544c92ac9a51 | cc3ca2c401de584e01d46dbc8ccbee1c7e7260cf |
refs/heads/master | <file_sep>from setuptools import setup
setup(name='rubiks_cube_gym',
version='0.0.1',
url="https://github.com/doublegremlin181/rubiks-cube-gym",
keywords='environment, agent, rl, openaigym, openai-gym, gym',
author="<NAME>",
author_email="<EMAIL>",
license="MIT",
install_requires=['gym', 'numpy', 'opencv-python', 'wget']
)
<file_sep>from gym.envs.registration import register
register(
id='rubiks-cube-222-v0',
entry_point='rubiks_cube_gym.envs:RubiksCube222Env',
max_episode_steps=250,
)
register(
id='rubiks-cube-222-lbl-v0',
entry_point='rubiks_cube_gym.envs:RubiksCube222EnvLBL',
max_episode_steps=250,
)
register(
id='rubiks-cube-222-ortega-v0',
entry_point='rubiks_cube_gym.envs:RubiksCube222EnvOrtega',
max_episode_steps=250,
)
<file_sep>from rubiks_cube_gym.envs.rubiks_cube_222 import RubiksCube222Env
from rubiks_cube_gym.envs.rubiks_cube_222_lbl import RubiksCube222EnvLBL
from rubiks_cube_gym.envs.rubiks_cube_222_ortega import RubiksCube222EnvOrtega
| ecd4dba6bc2881fe34af1bf891311fff47dbc5d7 | [
"Python"
] | 3 | Python | paritoshk/RubiksCubeGym | 28228c6a139197fdac4e0c113919d67aa16bb8da | f3b5ed2206fa897129eef71eb8cf57be6b41794c |
refs/heads/master | <file_sep>var assert = require('assert');
var otk = require('../lib/token.js');
var yesterday = new Date(Date.now() - (24 * 3600 * 1000));
var tomorrow = new Date(Date.now() + (24 * 3600 * 1000));
var testPassword = "<PASSWORD>";
var cipherId = 2;
// Test decode (token generated from 3rd party OpenToken lib)
!(function () {
var testToken = "<KEY>";
var testData = "subject=foobar\nfoo=bar\nbar=baz";
otk.decode(testToken, cipherId, testPassword, function (err, result) {
process.stdout.write("Test decode (3rd party token)... ");
assert.ifError(err);
assert.equal(result.toString(), testData);
process.stdout.write("OK\n");
});
}());
// Test decode (self generated from 3rd part OpenToken lib)
!(function () {
var testToken = "<KEY>";
var testData = "subject=foobar\nfizz=buzz\nqux=doo";
otk.decode(testToken, cipherId, testPassword, function (err, result) {
process.stdout.write("Test decode (self-generated token)... ");
assert.ifError(err);
assert.equal(result.toString(), testData);
process.stdout.write("OK\n");
});
}());
// Test Encode & Decode
!(function () {
var testData = "subject=foobar\nfizz=buzz\nqux=doo";
otk.encode(testData, cipherId, testPassword, function (err, token) {
assert.ifError(err);
otk.decode(token, cipherId, testPassword, function (err, data) {
process.stdout.write("Test encode/decode... ");
assert.equal(data, testData);
process.stdout.write("OK\n");
});
});
}());
// Test Decode w wrong cipherID
!(function () {
var testData = "subject=foobar\nfizz=buzz\nqux=doo";
otk.encode(testData, cipherId, testPassword, function (err, token) {
assert.ifError(err);
otk.decode(token, cipherId+1, testPassword, function (err, data) {
process.stdout.write("Test decode error... ");
if (err) {
assert.ok( (/doesn\'t match/).test(err.message) );
process.stdout.write("OK\n");
} else {
assert.fail(null, "Error", "Expected an error");
}
});
});
}());
// try parsing a token earlier than allowed
!(function() {
var testData = "subject=foobar\nnot-before=" + tomorrow.toISOString();
otk.encode(testData, cipherId, testPassword, function (err, token) {
assert.ifError(err);
otkapi.parseToken(token, function (err, data) {
process.stdout.write("Testing token prior to not-before date... ");
if (err) {
assert.ok( (/Must not use this token before/i).test(err.message) );
process.stdout.write("OK\n");
} else {
assert.fail(data, null, "Expected error 'Must not use this token...'");
}
});
});
}());
| ee0f8ac5fa56f897470b887312dcde9377026796 | [
"JavaScript"
] | 1 | JavaScript | airicyu/node-opentoken | d2d80133f1f8528d44138b6a2f191c802237f926 | 04ddf79aabb6820e54c5591a21e2b3e4f4793e18 |
refs/heads/master | <file_sep>using EjercicioPractico.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EjercicioPractico.Controllers
{
public class CocheController : Controller
{
// GET: Coche
private EjercicioPracticoContext db;
public CocheController()
{
db = new EjercicioPracticoContext();
}
public List<Coche> cochesList()
{
var coches = db.Coches.ToList();
return coches;
}
public ActionResult Coche()
{
List<Coche> coches = cochesList();
return View(coches);
}
public ActionResult CocheId(int id)
{
var coche = db.Coches.SingleOrDefault(C => C.Id == id);
if (coche == null)
{
return HttpNotFound();
}
return View(coche);
}
public ActionResult NewCoche()
{
return View();
}
[HttpPost]
public ActionResult CreateNewCoche(Coche coche)
{
db.Coches.Add(coche);
db.SaveChanges();
return RedirectToAction("Coche");
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace EjercicioPractico
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
"NewCoche",
"Coche/NewCoche", //Se agrega un nuevo URL
new { controller = "Coche", action = "NewCoche" }//Se dice a que funcion de que controlador se agregar ese URL
);
routes.MapRoute(
"User",
"User/User",
new { controller = "User", action = "User" }
);
routes.MapRoute(
"NewUser",
"User/NewUser",
new { controller = "User", action = "NewUser" }
);
routes.MapRoute(
"Alquiler",
"Alquiler/Alquiler",
new { controller = "Alquiler", action = "Alquiler" }
);
routes.MapRoute(
"ListAlquiler",
"Alquiler/ListaAlquiler",
new { controller = "Alquiler", action = "ListAlquiler" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Coche", action = "Coche", id = UrlParameter.Optional }
);
}
}
}
<file_sep>using EjercicioPractico.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EjercicioPractico.Controllers
{
public class AlquilerController : Controller
{
private EjercicioPracticoContext db;
public AlquilerController()
{
db = new EjercicioPracticoContext();
}
public ActionResult Alquiler()
{
var users = db.Users.ToList();
var coches = db.Coches.ToList();
var viewModel = new NewAlquilerViewModel
{
Users = users,
Coches = coches
};
return View(viewModel);
}
[HttpPost]
public ActionResult CreateAlquiler(Alquiler Alquiler)
{
db.Alquilers.Add(Alquiler);
db.SaveChanges();
return RedirectToAction("Alquiler");
}
public ActionResult ListAlquiler()
{
var alquiler = db.Alquilers.ToList();
List<User> user = new List<User>();
List<Coche> coche = new List<Coche>();
foreach(var num in alquiler)
{
user.Add(db.Users.Find(num.IdUser));
coche.Add(db.Coches.Find(num.IdCoche));
}
var list = new NewAlquilerViewModel
{
Users = user,
Coches = coche
};
return View(list);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EjercicioPractico.Models
{
public class NewAlquilerViewModel
{
public IEnumerable<User> Users { get; set; }
public IEnumerable<Coche> Coches { get; set; }
public Alquiler Alquiler { get; set; }
}
}<file_sep>namespace EjercicioPractico.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class actualizandocampos : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Alquilers", "coche_Id", "dbo.Coches");
DropForeignKey("dbo.Alquilers", "user_Id", "dbo.Users");
DropIndex("dbo.Alquilers", new[] { "coche_Id" });
DropIndex("dbo.Alquilers", new[] { "user_Id" });
AddColumn("dbo.Alquilers", "coche", c => c.String());
AddColumn("dbo.Alquilers", "user", c => c.String());
DropColumn("dbo.Alquilers", "coche_Id");
DropColumn("dbo.Alquilers", "user_Id");
}
public override void Down()
{
AddColumn("dbo.Alquilers", "user_Id", c => c.Int());
AddColumn("dbo.Alquilers", "coche_Id", c => c.Int());
DropColumn("dbo.Alquilers", "user");
DropColumn("dbo.Alquilers", "coche");
CreateIndex("dbo.Alquilers", "user_Id");
CreateIndex("dbo.Alquilers", "coche_Id");
AddForeignKey("dbo.Alquilers", "user_Id", "dbo.Users", "Id");
AddForeignKey("dbo.Alquilers", "coche_Id", "dbo.Coches", "Id");
}
}
}
<file_sep>namespace EjercicioPractico.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class actualizationnew : DbMigration
{
public override void Up()
{
AddColumn("dbo.Alquilers", "IdUser", c => c.Int(nullable: false));
AddColumn("dbo.Alquilers", "IdCoche", c => c.Int(nullable: false));
DropColumn("dbo.Alquilers", "Marca");
DropColumn("dbo.Alquilers", "Modelo");
DropColumn("dbo.Alquilers", "Color");
DropColumn("dbo.Alquilers", "Name");
DropColumn("dbo.Alquilers", "Cedula");
}
public override void Down()
{
AddColumn("dbo.Alquilers", "Cedula", c => c.String());
AddColumn("dbo.Alquilers", "Name", c => c.String());
AddColumn("dbo.Alquilers", "Color", c => c.String());
AddColumn("dbo.Alquilers", "Modelo", c => c.String());
AddColumn("dbo.Alquilers", "Marca", c => c.String());
DropColumn("dbo.Alquilers", "IdCoche");
DropColumn("dbo.Alquilers", "IdUser");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace EjercicioPractico.Models
{
public class Alquiler
{
[Key]
public int Id { get; set; }
public int IdUser { get; set; }
public int IdCoche { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Web.Mvc;
using EjercicioPractico.Controllers;
using EjercicioPractico.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EjercicioPractico.Test
{
[TestClass]
public class CocheControllerTest
{
[TestMethod]
public void Coche()
{
CocheController coche = new CocheController();
ViewResult result = coche.Coche() as ViewResult;
var coc = (Coche) result.ViewData.Model;
Assert.AreEqual("BMW", coc.Marca);
}
}
}
<file_sep>using EjercicioPractico.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EjercicioPractico.Controllers
{
public class UserController : Controller
{
private EjercicioPracticoContext db;
public UserController()
{
db = new EjercicioPracticoContext();
}
public ActionResult User()
{
var user = db.Users.ToList();
return View(user);
}
public ActionResult NewUser()
{
return View();
}
[HttpPost]
public ActionResult CreateNewUser(User user)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("User");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace EjercicioPractico.Models
{
public class EjercicioPracticoContext:DbContext
{
public EjercicioPracticoContext()
{
}
public DbSet<Coche> Coches { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Alquiler> Alquilers { get; set; }
private void FixEfProviderServicesProblem()
{
// The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer'
// for the 'System.Data.SqlClient' ADO.NET provider could not be loaded.
// Make sure the provider assembly is available to the running application.
// See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
}
}
}<file_sep>namespace EjercicioPractico.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class actu : DbMigration
{
public override void Up()
{
AddColumn("dbo.Alquilers", "Marca", c => c.String());
AddColumn("dbo.Alquilers", "Modelo", c => c.String());
AddColumn("dbo.Alquilers", "Color", c => c.String());
AddColumn("dbo.Alquilers", "Name", c => c.String());
AddColumn("dbo.Alquilers", "Cedula", c => c.String());
DropColumn("dbo.Alquilers", "coche");
DropColumn("dbo.Alquilers", "user");
}
public override void Down()
{
AddColumn("dbo.Alquilers", "user", c => c.String());
AddColumn("dbo.Alquilers", "coche", c => c.String());
DropColumn("dbo.Alquilers", "Cedula");
DropColumn("dbo.Alquilers", "Name");
DropColumn("dbo.Alquilers", "Color");
DropColumn("dbo.Alquilers", "Modelo");
DropColumn("dbo.Alquilers", "Marca");
}
}
}
| 56a6c89e2aea3fe03b3be2e0072ac108a9b4e9f4 | [
"C#"
] | 11 | C# | GersonCaballero/Ejercicio-MVC | 3f37c88586c45fb78ea80d532444c39c08185683 | 0949f9c18564b124e13d855c9ec654cea5760ad4 |
refs/heads/master | <repo_name>krunalmiracle/ReactJS-Tutorial<file_sep>/src/Tweet.js
import React from 'react';
import './Tweet.css';
function Tweet({name,message}){
//We can use the imported data anywhere
return(
<div className="Tweet">
<h2 className="tweet_inline">{name}: </h2>
<p className="tweet_inline">{message}</p>
</div>
);
}
export default Tweet;
| be7df8571b2f2bbc6751c98ced17517a86ce7dcf | [
"JavaScript"
] | 1 | JavaScript | krunalmiracle/ReactJS-Tutorial | 0895c17945da547d0977b7e9a0f6bd07f3f49784 | 6b8eb065852bf36c410232080b63eaf347722221 |
refs/heads/main | <file_sep>var hp=0;
function lumos_fn(){
if (hp==0){
document.getElementById("wand").src="https://cdn.instructables.com/ORIG/F8I/P58P/H82UF7YE/F8IP58PH82UF7YE.jpg?auto=webp";
document.getElementById("lumos").value="NOX";
hp = 1; }
else if (hp == 1){document.getElementById("wand").src="https://files.cults3d.com/uploaders/12510347/illustration-file/7647a11c-db30-4c14-bcb8-02d52bb248e6/Dumbledore-top_perspective.720_large.jpg"; document.getElementById("lumos").value="LUMOS"
hp = 0;
}
}
var i=Math.floor(Math.random() * 5);
var pecto=["https://vignette.wikia.nocookie.net/harrypotter/images/f/fe/Patronus_PM_SilverStagPatronus_MomentIllust.jpg/revision/latest?cb=20170314002945","https://66.media.tumblr.com/6d35758e4ba196a6d75595999d40bb65/tumblr_odykna82Ys1vgea2uo1_640.png","https://s-media-cache-ak0.pinimg.com/originals/e6/6b/0b/e66b0b650497f73c33015c9a7c75c7b9.png","https://i.pinimg.com/originals/ab/f3/07/abf3075bacd2d81ae15c14680d9d37f4.jpg"];
function pat(){
document.getElementById("wand").src=pecto[i];
}
function obli(){ document.getElementById("s1").style.display="none";
} | f8de7a21300a899c1359bb998433e58a63b996db | [
"JavaScript"
] | 1 | JavaScript | Christino2020/Project60 | 28f85ffffb3ff65d483a37f9078fa3446968c078 | bc006b72ad422c91a63bc6c7aeabfad1211f3237 |
refs/heads/main | <file_sep>import React, {Component} from 'react';
import { Bar } from 'react-chartjs-2';
class Chart extends Component{
constructor(props) {
super(props);
this.state = {
chartData:{
labels: ['Dog', 'Cat', 'Bird', 'Fish', 'Turtle', 'Rabbit'],
datasets: [
{
label: 'October Sales',
data:[
61,
50,
20,
30,
9,
15
],
/*backgroundColor:[
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)',
'rgba(75, 192, 192, 0.6)',
'rgba(153, 102, 255, 0.6)',
'rgba(255, 159, 64, 0.6)',
'rgba(255, 99, 132, 0.6)'
]*/
}
]
}
}
}
render() {
return (
<div className="chart">
<Bar
data={this.state.chartData}
options={{
title:{
display:true,
text:'Popular Pets',
fontSize:25
},
legend:{
display:true,
position:'right'
}
}}
/>
</div>
)
}
}
export default Chart; | 86f0919353baa522bd370f552cf19a97d671d658 | [
"JavaScript"
] | 1 | JavaScript | peter-newton/project_2 | 7017903a23d7bedf379e1eae7e2c319b0d8fa99b | 45ccfbfc6de5e7591abb287530c33cfc030c5924 |
refs/heads/master | <file_sep>using Newtonsoft.Json;
using System.IO;
/// <summary>
/// Author: <NAME>
/// Date: 2017-12-28
/// Most of this code found on: https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
/// </summary>
namespace GarageShopBooking
{
class FileHandler
{
/// <summary>
/// Write an object to a json file.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="filePath"></param>
/// <param name="objectToWrite"></param>
public static void WriteToFile<T>(string filePath, T objectToWrite) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
}
}
<file_sep>using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace GarageShopBooking
{
/// <summary>
/// Interaction logic for RegisterVehicle.xaml
/// </summary>
public partial class RegisterVehicle : Window
{
Vehicle vehicle;
VehicleTypes vehicleType;
internal Vehicle Vehicle { get => vehicle; }
/// <summary>
/// Constructor
/// </summary>
public RegisterVehicle()
{
InitializeComponent();
this.Title = "Register vehicle";
InitalizeGUI();
}
/// <summary>
/// Initialize the GUI.
/// </summary>
private void InitalizeGUI()
{
txtOwnerFirstName.Text = String.Empty;
txtOwnerLastName.Text = String.Empty;
txtMilage.Text = String.Empty;
txtRegNumber.Text = String.Empty;
txtModelYear.Text = String.Empty;
txtBrand.Text = String.Empty;
txtTires.Text = String.Empty;
txtDoors.Text = String.Empty;
cboxServiceLevel.ItemsSource = Enum.GetValues(typeof(ServiceLevel)).Cast<ServiceLevel>();
cboxVehicleType.ItemsSource = Enum.GetValues(typeof(VehicleTypes)).Cast<VehicleTypes>();
cboxLiftType.ItemsSource = Enum.GetValues(typeof(LiftType)).Cast<LiftType>();
txtDoors.Visibility = Visibility.Hidden;
lblDoors.Visibility = Visibility.Hidden;
lblMilage.Visibility = Visibility.Hidden;
txtMilage.Visibility = Visibility.Hidden;
}
/// <summary>
/// Creates a vehicle object and reads the input and sets the values.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOK_Click(object sender, RoutedEventArgs e)
{
if (cboxVehicleType.SelectedIndex > -1)
{
/// Perform different actions depending on what Vehicle type is selected.
/// Some parts are common for all.
/// TODO: Find a better solution to do this, where duplicated code can be avoided.
VehicleTypes vehicleType = (VehicleTypes)Enum.Parse(typeof(VehicleTypes), cboxVehicleType.SelectedValue.ToString(), true);
if (vehicleType == VehicleTypes.Trailer)
{
vehicle = new Trailer();
if (!ReadRegNumber())
MessageBox.Show("You need to specefiy a reg number");
else if (!ReadOwnerName())
MessageBox.Show("You need to specify an owner");
else if (!ReadModelYear())
MessageBox.Show("You need to specifye a model year");
else if (!ReadBrand())
MessageBox.Show("You need to specify a brand");
Trailer trailer = vehicle as Trailer;
trailer.LiftType = ReadLiftType();
trailer.Tires = ReadTires();
vehicle = trailer;
}
else if (vehicleType == VehicleTypes.Car)
{
vehicle = new Car();
if (!ReadRegNumber())
MessageBox.Show("You need to specefiy a reg number");
else if (!ReadOwnerName())
MessageBox.Show("You need to specify an owner");
else if (!ReadModelYear())
MessageBox.Show("You need to specifye a model year");
Car car = vehicle as Car;
car.LiftType = ReadLiftType();
car.Tires = ReadTires();
car.Doors = ReadDoors();
car.Height = ReadHeight();
vehicle = car;
if (int.TryParse(txtMilage.Text, out int milage))
{
vehicle.Milage = milage;
}
else
MessageBox.Show("You forgot to specefiy the milage");
}
else if (vehicleType == VehicleTypes.Truck)
{
vehicle = new Truck();
if (!ReadRegNumber())
MessageBox.Show("You need to specefiy a reg number");
else if (!ReadOwnerName())
MessageBox.Show("You need to specify an owner");
else if (!ReadModelYear())
MessageBox.Show("You need to specifye a model year");
Truck truck = vehicle as Truck;
truck.LiftType = ReadLiftType();
truck.Tires = ReadTires();
truck.Doors = ReadDoors();
truck.Height = ReadHeight();
vehicle = truck;
if (int.TryParse(txtMilage.Text, out int milage))
{
vehicle.Milage = milage;
}
else
MessageBox.Show("You forgot to specefiy the milage");
}
else if (vehicleType == VehicleTypes.TowedSled)
{
vehicle = new TowedSled();
if (!ReadRegNumber())
MessageBox.Show("You need to specefiy a reg number");
else if (!ReadOwnerName())
MessageBox.Show("You need to specify an owner");
else if (!ReadModelYear())
MessageBox.Show("You need to specifye a model year");
TowedSled sled = vehicle as TowedSled;
sled.NumOfSkids = ReadNumOfSkids();
sled.LiftType = ReadLiftType();
}
else if (vehicleType == VehicleTypes.MotorCycle)
{
vehicle = new MotorCycle();
if (!ReadRegNumber())
MessageBox.Show("You need to specefiy a reg number");
else if (!ReadOwnerName())
MessageBox.Show("You need to specify an owner");
else if (!ReadModelYear())
MessageBox.Show("You need to specifye a model year");
MotorCycle mc = vehicle as MotorCycle;
mc.Tires = ReadTires();
vehicle = mc;
if (int.TryParse(txtMilage.Text, out int milage))
{
vehicle.Milage = milage;
}
else
MessageBox.Show("You forgot to specefiy the milage");
}
vehicle.ServiceLevel = (ServiceLevel)Enum.Parse(typeof(ServiceLevel), cboxServiceLevel.SelectedValue.ToString(), true);
this.DialogResult = true;
}
else
MessageBox.Show("You need to select a Vehicle type");
}
/// <summary>
/// Close the window if cancel is clicked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
/// <summary>
/// Reads the owner name and creates an owner object.
/// </summary>
/// <returns></returns>
private bool ReadOwnerName()
{
if (! String.IsNullOrEmpty(txtOwnerFirstName.Text) && ! String.IsNullOrEmpty(txtOwnerLastName.Text))
{
Owner owner = new Owner(txtOwnerFirstName.Text, txtOwnerLastName.Text);
vehicle.Owner = owner;
return true;
}
else
return false;
}
/// <summary>
/// Reads the reg number
/// </summary>
/// <returns></returns>
private bool ReadRegNumber()
{
if (!String.IsNullOrEmpty(txtRegNumber.Text))
{
vehicle.RegNumber = txtRegNumber.Text;
return true;
}
else
return false;
}
/// <summary>
/// Tries to read the model year.
/// </summary>
/// <returns></returns>
private bool ReadModelYear()
{
if (! String.IsNullOrEmpty(txtModelYear.Text))
{
vehicle.ModelYear = txtModelYear.Text;
return true;
}
else
return false;
}
/// <summary>
/// Tries to read the brand.
/// </summary>
/// <returns></returns>
private bool ReadBrand()
{
if (!String.IsNullOrEmpty(txtBrand.Text))
{
vehicle.Brand = txtBrand.Text;
return true;
}
else
return false;
}
/// <summary>
/// Tries to parse the number of tires
/// </summary>
/// <returns></returns>
private int ReadTires()
{
if (int.TryParse(txtTires.Text, out int numTires))
{
return numTires;
}
else
return -1;
}
/// <summary>
/// Read the lifttype, if nothing was selected, return a Heavy lifttype.
/// </summary>
/// <returns></returns>
private LiftType ReadLiftType()
{
if (cboxLiftType.SelectedIndex >= 0)
{
return (LiftType)Enum.Parse(typeof(LiftType), cboxLiftType.SelectedValue.ToString(), true);
}
else
return LiftType.Heavy;
}
/// <summary>
/// Tries to parse the number of skids (instead of tires)
/// </summary>
/// <returns></returns>
private int ReadNumOfSkids()
{
if (int.TryParse(txtTires.Text, out int numSkids))
{
return numSkids;
}
else
return -1;
}
/// <summary>
/// Reads the numbers of doors, try to parse it, if not return -1
/// </summary>
/// <returns>int number of doors</returns>
private int ReadDoors()
{
if (int.TryParse(txtTires.Text, out int numDoors))
{
return numDoors;
}
else
return -1;
}
/// <summary>
/// Hard coded for now.
/// Returns one height for a car another for a truck and a third one for everything else.
/// </summary>
/// <returns>double height of vehicle</returns>
private double ReadHeight()
{
if (vehicleType == VehicleTypes.Car)
return 2.0;
else if (vehicleType == VehicleTypes.Truck)
return 4.0;
else
return 1.5;
}
/// <summary>
/// Hide different textBoxes and Labels based on what vehicle type is selected.
/// And renames tires for skids for towed sled.
/// TODO: Implement a better solution.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboxVehicleType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
vehicleType = (VehicleTypes)Enum.Parse(typeof(VehicleTypes), cboxVehicleType.SelectedValue.ToString(), true);
if (vehicleType == VehicleTypes.Trailer)
{
txtDoors.Visibility = Visibility.Hidden;
lblDoors.Visibility = Visibility.Hidden;
lblMilage.Visibility = Visibility.Hidden;
txtMilage.Visibility = Visibility.Hidden;
lblTires.Content = "Tires";
}
else if (vehicleType == VehicleTypes.Car)
{
txtDoors.Visibility = Visibility.Visible;
lblDoors.Visibility = Visibility.Visible;
lblMilage.Visibility = Visibility.Visible;
txtMilage.Visibility = Visibility.Visible;
lblTires.Content = "Tires";
}
else if (vehicleType == VehicleTypes.Truck)
{
lblDoors.Visibility = Visibility.Hidden;
txtDoors.Visibility = Visibility.Hidden;
lblMilage.Visibility = Visibility.Visible;
txtMilage.Visibility = Visibility.Visible;
lblTires.Content = "Tires";
}
else if (vehicleType == VehicleTypes.TowedSled)
{
txtDoors.Visibility = Visibility.Hidden;
lblDoors.Visibility = Visibility.Hidden;
lblMilage.Visibility = Visibility.Hidden;
txtMilage.Visibility = Visibility.Hidden;
lblTires.Content = "Skids";
}
else if (vehicleType == VehicleTypes.MotorCycle)
{
txtDoors.Visibility = Visibility.Hidden;
lblDoors.Visibility = Visibility.Hidden;
lblMilage.Visibility = Visibility.Visible;
txtMilage.Visibility = Visibility.Visible;
lblTires.Content = "Tires";
}
}
}
}
<file_sep>/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// What service levels can we offer and how much do they cost.
/// </summary>
enum ServiceLevel
{
Large = 10000,
Medium = 5000,
Small = 1000,
Premium = 20000
}
}
<file_sep>/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// Represeantation of a Trailer Trailers vehicle object.
/// </summary>
class Trailer : Trailers
{
private int tires;
/// <summary>
/// Sets num of tires to 0 and calls the base class.
/// </summary>
public Trailer() : base()
{
this.tires = 0;
}
/// <summary>
/// Creates and object with specefied values and calls the base class.
/// </summary>
/// <param name="regNumber">String of regnumber of vehicle</param>
/// <param name="brand">string brand name of vehicle</param>
/// <param name="modelYear">string with model year of behicle</param>
/// <param name="owner">Owner object of vehicle</param>
/// <param name="tires">int number of tires on vehicle</param>
/// <param name="liftType">LifType needed for vehicle</param>
public Trailer(string regNumber, string brand, string modelYear, Owner owner, int tires, LiftType liftType) : base(regNumber, brand, modelYear, owner, liftType)
{
this.Tires = tires;
}
/// <summary>
/// Gets and sets the number of tires.
/// </summary>
public int Tires { get => tires; set => tires = value; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GarageShopBooking
{
class Owner
{
private string firstName, lastName;
public Owner(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public string FirstName { get => firstName; set => firstName = value; }
public string FullName { get => firstName + lastName; }
}
}
<file_sep>/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// Representation of a Trailers Vehicle.
/// </summary>
class Trailers : Vehicle
{
private LiftType liftType;
/// <summary>
/// Sets the lifttype to Light.
/// </summary>
public Trailers () : base ()
{
this.LiftType = LiftType.Light;
}
/// <summary>
/// Creates and object with specefied values and calls the base class.
/// </summary>
/// <param name="regNumber">String of regnumber of vehicle</param>
/// <param name="brand">string brand name of vehicle</param>
/// <param name="modelYear">string with model year of behicle</param>
/// <param name="owner">Owner object of vehicle</param>
/// <param name="liftType">LifType needed for vehicle</param>
public Trailers(string regNumber, string brand, string modelYear, Owner owner, LiftType liftType) : base(regNumber, brand, modelYear, owner)
{
this.LiftType = liftType;
}
/// <summary>
/// Gets and sets the liftType
/// </summary>
public LiftType LiftType { get => liftType; set => liftType = value; }
}
}
<file_sep>/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// Representation of a TowedSled Trailer vehicle.
/// </summary>
class TowedSled : Trailers
{
private int numOfSkids;
/// <summary>
/// Sets numOfSkids to 0.
/// </summary>
public TowedSled() : base()
{
this.numOfSkids = 0;
}
/// <summary>
/// Creates an object with specefied values and calls the base class constructor.
/// </summary>
/// <param name="regNumber">String of regnumber of vehicle</param>
/// <param name="brand">string brand name of vehicle</param>
/// <param name="modelYear">string with model year of behicle</param>
/// <param name="owner">Owner object of vehicle</param>
/// <param name="numOfSkids">int number of skids on vehicle</param>
/// <param name="liftType">LifType needed for vehicle</param>
public TowedSled(string regNumber, string brand, string modelYear, Owner owner, int numOfSkids, LiftType liftType) : base(regNumber, brand, modelYear, owner, liftType)
{
this.NumOfSkids = numOfSkids;
}
/// <summary>
/// Get and set the numOfSkids.
/// </summary>
public int NumOfSkids { get => numOfSkids; set => numOfSkids = value; }
}
}
<file_sep>/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// Representation of a MotorCycle vehicle.
/// </summary>
class MotorCycle : Vehicle
{
private int tires;
/// <summary>
/// Create an object with no properties set.
/// </summary>
public MotorCycle() : base()
{
this.tires = 0;
}
/// <summary>
/// Creates an object with specefied values and calls the base class.
/// </summary>
/// <param name="regNumber">String of regnumber of vehicle</param>
/// <param name="brand">string brand name of vehicle</param>
/// <param name="modelYear">string with model year of behicle</param>
/// <param name="owner">Owner object of vehicle</param>
/// <param name="tires">int number of tires on vehicle</param>
public MotorCycle(string regNumber, string brand, string modelYear, Owner owner, int tires) : base(regNumber, brand, modelYear, owner)
{
this.Tires = tires;
}
/// <summary>
/// Sets and gets Tires.
/// </summary>
public int Tires { get => tires; set => tires = value; }
}
}
<file_sep>/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// What lifttypes can we support and what do the vehicle need.
/// </summary>
enum LiftType
{
Heavy,
Light
}
}
<file_sep>using System.Windows;
/// <summary>
/// Author: <NAME>
/// Date: 2017-12-28
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
RegisterVehicle registerVehicle;
GarageShop garageShop;
/// <summary>
/// Create a new RegisterVehicle and GarageShop object.
/// </summary>
public MainWindow()
{
InitializeComponent();
registerVehicle = new RegisterVehicle();
garageShop = new GarageShop();
garageShop.RestoreLists();
InitializeGUI();
UpdateGUI();
}
/// <summary>
/// Clear the interface.
/// </summary>
private void InitializeGUI()
{
lstReadyVehicles.Items.Clear();
lstVehicles.Items.Clear();
}
/// <summary>
/// Update the both lists with information about registered vehicles.
/// </summary>
private void UpdateGUI()
{
lstReadyVehicles.Items.Clear();
lstVehicles.Items.Clear();
foreach (Vehicle vehicle in garageShop.RepairObjects)
{
lstVehicles.Items.Add(vehicle.ToString());
}
foreach (Vehicle vehicle in garageShop.ReadyObjects)
{
lstReadyVehicles.Items.Add(vehicle.ToString());
}
}
/// <summary>
/// Add a vehicle when button is clicked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRegisterVehicle_Click(object sender, RoutedEventArgs e)
{
registerVehicle = new RegisterVehicle();
registerVehicle.ShowDialog();
if (registerVehicle.DialogResult.HasValue && registerVehicle.DialogResult.Value)
{
garageShop.AddVehicle(registerVehicle.Vehicle);
UpdateGUI();
}
}
/// <summary>
/// Add extra cost for work done when button is clicked.
/// Use a VisualBasic input box.
/// TODO: Implement a prettier window and add what work has been performed as well.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAddWorkDone_Click(object sender, RoutedEventArgs e)
{
if (lstVehicles.SelectedIndex >= 0)
{
string extraWork = Microsoft.VisualBasic.Interaction.InputBox("What is the cost of the extra work?", "Extra work", "");
if (int.TryParse(extraWork, out int price))
{
garageShop.RepairObjects[lstVehicles.SelectedIndex].AddWork(price);
}
else
MessageBox.Show("Failed to parse input to numbers");
}
else
MessageBox.Show("No vehicle selected");
}
/// <summary>
/// Use a Visual Basic component instead of creating a new WPF form to handle the input message box.
/// TODO: Make a prettier window to handle the search function. Perhaps even an option to search on owner name as well?
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnInfoVehicle_Click(object sender, RoutedEventArgs e)
{
string regNumber = Microsoft.VisualBasic.Interaction.InputBox("Search reg Number?", "Search vehicle", "");
Vehicle vehicle = garageShop.SearchVehicle(regNumber);
if (vehicle == null)
MessageBox.Show("No vehicle found");
else
MessageBox.Show(vehicle.ToString());
}
/// <summary>
/// Move the selected vehicle to the list of ready vehicles.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnVehicleReady_Click(object sender, RoutedEventArgs e)
{
if (lstVehicles.SelectedIndex >= 0)
{
garageShop.VehicleReady(lstVehicles.SelectedIndex);
UpdateGUI();
}
else
MessageBox.Show("No vehicle selected");
}
/// <summary>
/// Checkout and display the price for work that has been done on the car.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCheckoutVehicle_Click(object sender, RoutedEventArgs e)
{
if (lstReadyVehicles.SelectedIndex >= 0)
{
MessageBox.Show("The price for repairs is : " + garageShop.CheckOutVehicle(lstReadyVehicles.SelectedIndex));
UpdateGUI();
}
else
MessageBox.Show("No vehicle selected");
}
private void Window_Closing(object sender, System.EventArgs e)
{
garageShop.SaveLists();
}
}
}
<file_sep>using System;
/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// A representation of a vehicle object.
/// </summary>
class Vehicle
{
private string regNumber, brand, modelYear, formattedDate;
private ServiceLevel serviceLevel;
private int milage, repairTime;
private Owner owner;
private int extraWork;
/// <summary>
/// Sets extrawork to 0 and formattedDate to todays date.
/// </summary>
public Vehicle()
{
this.extraWork = 0;
formattedDate = DateTime.Today.ToString("YYMMDD");
}
/// <summary>
/// Sets extrawork to 0 and formattedDate to todays date. Reads the rest as input.
/// </summary>
/// <param name="regNumber"></param>
/// <param name="brand"></param>
/// <param name="modelYear"></param>
/// <param name="owner"></param>
public Vehicle(string regNumber, string brand, string modelYear, Owner owner)
{
this.regNumber = regNumber.ToLower(); ;
this.brand = brand;
this.modelYear = modelYear;
this.owner = owner;
this.extraWork = 0;
formattedDate = DateTime.Today.ToString("YYMMDD");
}
/// <summary>
/// Gets and sets the milage and all other properties.
/// </summary>
public int Milage { get => milage; set
{
milage = value;
}
}
public int RepairTime { get => repairTime; set => repairTime = value; }
/// <summary>
/// Converts the regnumber to lowecase.
/// </summary>
public string RegNumber { get => regNumber; set
{
regNumber = value.ToLower(); ;
}
}
public string Brand { get => brand; set => brand = value; }
public string ModelYear { get => modelYear; set => modelYear = value; }
public string FormattedDate { get => formattedDate; set => formattedDate = value; }
/// <summary>
/// For servicelevel, also set the repairtime depending on what service level is picked.
/// </summary>
public ServiceLevel ServiceLevel {
get
{
return serviceLevel;
}
set
{
serviceLevel = value;
if (value == ServiceLevel.Large)
{
SetRepairTime(3);
}
if (value == ServiceLevel.Premium)
{
SetRepairTime(4);
}
if (value == ServiceLevel.Medium)
{
SetRepairTime(2);
}
if (value == ServiceLevel.Small)
{
SetRepairTime(1);
}
}
}
public Owner Owner { get => owner; set => owner = value; }
/// <summary>
/// Returns the price cost of servicelevel + extra work that has been added.
/// </summary>
public int Price
{
get
{
return (int)serviceLevel + extraWork;
}
}
/// <summary>
/// Add extra cost and increase the numbers of days to work on the vehicle
/// </summary>
/// <param name="price"></param>
public void AddWork(int price)
{
extraWork += price;
repairTime++;
}
/// <summary>
/// Sends regnumber, brand, modelyear, owner.FullName as a string representation of the object.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("{0,7}, {1,-10} {2,-5}, {3},", regNumber, brand, modelYear, owner.FullName);
}
/// <summary>
/// Sets a new repair time.
/// </summary>
/// <param name="time"></param>
private void SetRepairTime(int time)
{
repairTime = time;
}
/// <summary>
/// Returns a string with detailed information of the object.
/// </summary>
/// <returns></returns>
public string DetailedInfo()
{
string output = "RegNumber: " + regNumber + "\nbrand: " + brand + "\nModel Year: " + modelYear + "\nOwner: " + owner.FullName
+ "\nServiceLevel: " + serviceLevel.ToString() + "\nDays to repair: " + repairTime + "\nPrice: " + Price + "\nRegister date: " + formattedDate;
return output;
}
}
}
<file_sep>/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// What vehicle types are we supporting.
/// </summary>
enum VehicleTypes
{
Car,
MotorCycle,
Truck,
TowedSled,
Trailer
}
}
<file_sep>/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// Representation of a Car Vehicle.
/// </summary>
class Car : Vehicle
{
private int doors, tires;
private LiftType liftType;
private double height;
/// <summary>
/// Emty constructor sets doors and height to 0 and liftype to Light.
/// </summary>
public Car() : base()
{
this.doors = 0;
this.height = 0.0;
liftType = LiftType.Light;
}
/// <summary>
/// Creates and object with specefied values adn calls the base class.
/// </summary>
/// <param name="regNumber">String of regnumber of vehicle</param>
/// <param name="brand">string brand name of vehicle</param>
/// <param name="modelYear">string with model year of behicle</param>
/// <param name="owner">Owner object of vehicle</param>
/// <param name="doors">int numbers of doors on vehicle</param>
/// <param name="tires">int number of tires on vehicle</param>
/// <param name="liftType">LifType needed for vehicle</param>
/// <param name="height">int height of vehicle</param>
public Car(string regNumber, string brand, string modelYear, Owner owner, int doors, int tires, LiftType liftType, double height) : base (regNumber, brand, modelYear, owner)
{
this.doors = doors;
this.tires = tires;
this.liftType = liftType;
this.height = height;
}
/// <summary>
/// Gets and sets doors, tires, liftype and Height.
/// </summary>
public int Doors { get => doors; set => doors = value; }
public int Tires { get => tires; set => tires = value; }
public LiftType LiftType { get => liftType; set => liftType = value; }
public double Height { get => height; set => height = value; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// Author: <NAME>
/// Date: 2017-12-28
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// A representation of a Garage shop
/// </summary>
class GarageShop
{
/// <summary>
/// Lists of objects in the garage.
/// </summary>
private List<Vehicle> repairObjects;
private List<Vehicle> readyObjects;
private string saveDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +"\\";
private const string readyObjectsFilleName = "readyObjects.json";
private const string repairObjectsFileNAme = "repairObjects.json";
/// <summary>
/// Initiates two lists when called.
/// </summary>
public GarageShop()
{
repairObjects = new List<Vehicle>();
readyObjects = new List<Vehicle>();
}
/// <summary>
/// Get and set RepairObjects and ReadyObjects.
/// </summary>
internal List<Vehicle> RepairObjects { get => repairObjects; set => repairObjects = value; }
internal List<Vehicle> ReadyObjects { get => readyObjects; set => readyObjects = value; }
/// <summary>
/// Add a vehicle to the repairobjects.
/// </summary>
/// <param name="vehicle"></param>
public void AddVehicle(Vehicle vehicle)
{
RepairObjects.Add(vehicle);
}
/// <summary>
/// Moves a vehicle from repairobjects to readyobjects.
/// </summary>
/// <param name="index"></param>
public void VehicleReady(int index)
{
readyObjects.Add(repairObjects[index]);
repairObjects.RemoveAt(index);
}
/// <summary>
/// Search for a vehicle with the specefied reg number.
/// </summary>
/// <param name="regNumber"></param>
/// <returns></returns>
public Vehicle SearchVehicle(String regNumber)
{
// Converts the regnumber to lowecase.
regNumber = regNumber.ToLower();
foreach (Vehicle vehicle in RepairObjects)
{
if (vehicle.RegNumber.Equals(regNumber))
{
return vehicle;
}
}
foreach (Vehicle vehicle in ReadyObjects)
{
if (vehicle.RegNumber.Equals(regNumber))
{
return vehicle;
}
}
return null;
}
/// <summary>
/// Checksout a vehicle by getting the price, displaying the price and removing from list.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public int CheckOutVehicle(int index)
{
int price = ReadyObjects[index].Price;
ReadyObjects.RemoveAt(index);
return price;
}
/// <summary>
/// Write the lists to a Json file.
/// </summary>
public void SaveLists()
{
// Write the contents of the variable someClass to a file.
FileHandler.WriteToFile<List<Vehicle>>(saveDirectory + repairObjectsFileNAme , repairObjects);
FileHandler.WriteToFile<List<Vehicle>>(saveDirectory + readyObjectsFilleName , readyObjects);
// Read the file contents back into a variable.
}
/// <summary>
/// Restore the lists from a json file.
/// </summary>
public void RestoreLists()
{
if (File.Exists(saveDirectory + readyObjectsFilleName))
{
readyObjects = FileHandler.ReadFromFile<List<Vehicle>>(saveDirectory + readyObjectsFilleName);
}
if (File.Exists(saveDirectory + repairObjectsFileNAme))
{
repairObjects = FileHandler.ReadFromFile<List<Vehicle>>(saveDirectory + repairObjectsFileNAme);
}
}
}
}
<file_sep>/// <summary>
/// Author: <NAME>
/// Data: 2017-12-27
/// </summary>
namespace GarageShopBooking
{
/// <summary>
/// Representation of a Truck vehicle.
/// </summary>
class Truck : Vehicle
{
private int doors, tires;
private LiftType liftType;
private double height;
/// <summary>
/// Empty constructor. Sets doors and tires to 0 and LiftType to Heavy.
/// </summary>
public Truck() : base ()
{
this.doors = 0;
this.tires = 0;
this.liftType = LiftType.Heavy;
}
/// <summary>
/// Creates and object with specefied values and calls the base class.
/// </summary>
/// <param name="regNumber">String of regnumber of vehicle</param>
/// <param name="brand">string brand name of vehicle</param>
/// <param name="modelYear">string with model year of behicle</param>
/// <param name="owner">Owner object of vehicle</param>
/// <param name="doors">int numbers of doors on vehicle</param>
/// <param name="tires">int number of tires on vehicle</param>
/// <param name="liftType">LifType needed for vehicle</param>
/// <param name="height">int height of vehicle</param>
public Truck(string regNumber, string brand, string modelYear, Owner owner, int doors, int tires, LiftType liftType, double height) : base(regNumber, brand, modelYear, owner)
{
this.doors = doors;
this.tires = tires;
this.liftType = liftType;
this.height = height;
}
/// <summary>
/// Gets and sets properties.
/// </summary>
public int Doors { get => doors; set => doors = value; }
public int Tires { get => tires; set => tires = value; }
public LiftType LiftType { get => liftType; set => liftType = value; }
public double Height { get => height; set => height = value; }
}
}
| 3a3eec3a6b5b29035970fd1c957b5f11f0534d0b | [
"C#"
] | 15 | C# | zarkroc/GarageShopBooking | 55de8c20c985db805f9d9e78715a7efe7403ac0c | 3f4bff78da4f911b0ec747f1b44351756e6d2238 |
refs/heads/master | <file_sep>module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
config:{
vendorsFilesToCopy : {src: 'bower_components/jquery/jquery.min.js', dest: 'www/scripts/jquery.min.js'},
assetsFilesToCopy : {expand: true, cwd: 'assets/', src: ['**'], dest: 'www/'},
filesToUglify : {'www/scripts/app.js': ['src/scripts/*.js']},
folderToClean : ['build/*', 'www/*']
},
clean: {
run: '<%= config.folderToClean %>'
},
compass: {
dist: {
options: {
require: 'susy',
sassDir: 'src/sass',
cssDir: 'build/css',
imagesDir: 'src/assets/images',
generatedImagesDir: "build/images",
generatedImagesPath: "www/images",
httpGeneratedImagesPath: "../images"
//http_fonts_path: '../fonts'
}
}
},
connect: {
server: {
options: {
hostname:"*",
port: 3000,
base: 'www',
livereload: true
}
}
},
assemble: {
html: {
options: {
layout: 'src/assets/layout.html'
},
src: ['*.html', '!layout.html'],
dest: 'build/html/',
expand: true,
cwd: 'src/assets/'
}
},
copy: {
assets: {
expand: true,
cwd: 'src/assets/',
src: ['**', '!*.html'],
dest: 'www/'
},
html: {
expand: true,
cwd: 'build/html/',
src: '*',
dest: 'www/'
},
styles: {
expand: true,
cwd: 'build/css/',
src: '*.css',
dest: 'www/css/'
},
resources: {
expand: true,
cwd: 'bower_components/bootstrap/fonts',
src: '*',
dest: 'www/fonts/'
}
},
watch: {
options: {
livereload: true
},
html: {
files: 'src/assets/**/*.html',
tasks: ['assemble:html', 'copy:html']
},
sass: {
files: 'src/sass/**/*.scss',
tasks: ['compass:dist', 'copy:styles']
}
}
});
/**
* loading npm tasks
*/
grunt.loadNpmTasks('grunt-contrib-clean');;
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-assemble');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
// grunt.loadNpmTasks('grunt-spritesmith');
/**
* register tasks
*/
grunt.registerTask('default', ['run']);
grunt.registerTask('build', ['compass', 'assemble']);
grunt.registerTask('rebuild', ['clean', 'build']);
grunt.registerTask('deploy', ['copy']);
grunt.registerTask('redeploy', ['rebuild', 'deploy']);
grunt.registerTask('run', ['rebuild', 'deploy', 'connect', 'watch']);
};
<file_sep>C-M
===
npm install
| 4513b38f962ed2b919d1c7acd1bfed90ddf9bffb | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | saadBanaoui/C-M | d817b3e47225be8e4b5615f8be8cfa72852baa80 | d1abaab3913138436e011e5a05eb18f883a0c074 |
refs/heads/master | <file_sep>//
// Author: Devil323
//
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
namespace Mobius
{
public class IniFileManager
{
private string myIniFileName="";
private bool myFileReaded = false;
private SortedList myFileLines = new SortedList();
private SortedList mySectionKeysLines = new SortedList();
private long MaxFileLines =0;
private long InsertedKeys =0;
enum iniLineType {empty,comment,section,keyValue};
public IniFileManager(string iniFileName)
{
Debug.Assert ( iniFileName != null && iniFileName != "");
myIniFileName = iniFileName;
myFileReaded = ReadIniFile();
}
public IniFileManager()
{
myFileReaded =false;
}
public string IniFileName
{
get { return myIniFileName; }
set
{
myFileReaded = false;
myIniFileName = value;
}
}
private string BuildSectionKeyToHKey(string section,string key) {
Debug.Assert(section != null && section!= "");
Debug.Assert(key !=null && key!="" && key.IndexOf("=")<0);
return (BuildSectionToHKey(section) + key.Trim());
}
private string BuildSectionToHKey(string section) {
Debug.Assert(section != null && section!= "");
return ("["+ section.Trim()+ "]");
}
private string BuildLineToHKey(string lineCount, string extension)
{
//To Build the valid index to be sorted by the SortList
return( lineCount.PadLeft(10,"0".ToCharArray()[0]) + extension);
}
private bool ReadIniFile()
{
if (myFileReaded==true) return (true);
if (!File.Exists(myIniFileName))
{
FileStream myNewFile = File.Create (myIniFileName);
myNewFile.Close();
}
string line = "";
long lineCount =0;
myFileLines = new SortedList();
mySectionKeysLines = new SortedList();
string currentSection="[Default]";
using (StreamReader readFileStream = new StreamReader(myIniFileName) )
{
try
{
while (readFileStream.Peek() > -1)
{
line = readFileStream.ReadLine().Trim();
lineCount ++ ;
if (this.GetIniLineType(line)== (int) iniLineType.section)
{
currentSection = line;
mySectionKeysLines.Add(currentSection,BuildLineToHKey(lineCount.ToString(), ".0"));
}
else if (this.GetIniLineType(line)== (int) iniLineType.keyValue)
{
mySectionKeysLines.Add(currentSection + GetKeyFromLine(line),BuildLineToHKey(lineCount.ToString(), ".0"));
}
myFileLines.Add(BuildLineToHKey(lineCount.ToString(), ".0"),line);
}
MaxFileLines = lineCount;
myFileReaded=true;
}
catch(System.Exception e)
{
throw new System.Exception("Error reading file: " + myIniFileName ,e);
}
}
return (myFileReaded);
}
private int GetIniLineType(string lineText)
{
int tempIniLineType =0;
Debug.Assert(lineText != null);
lineText = lineText.Trim();
if ( lineText =="" )
tempIniLineType = (int) iniLineType.empty; //Why? (int)
else if (lineText.StartsWith(";"))
tempIniLineType = (int) iniLineType.comment;
else if (lineText.StartsWith("[") && lineText.EndsWith("]") )
tempIniLineType = (int) iniLineType.section;
else
tempIniLineType= (int) iniLineType.keyValue;
Debug.Assert(tempIniLineType>=0 && tempIniLineType<=3 );
return (tempIniLineType);
}
private string GetKeyFromLine(string line)
{
Debug.Assert (line!= null);
string[] lineSplitted =line.Split("=".ToCharArray());
Debug.Assert (lineSplitted.Length>0);
return(lineSplitted[0]);
}
private string GetValueFromLine(string line)
{
Debug.Assert (line!= null);
string[] lineSplitted =line.Split("=".ToCharArray());
if (lineSplitted.Length>1)
return(lineSplitted[1]);
else
return ("");
}
private bool ModifyKeyValue(string section,string key, string keyValue)
{
Debug.Assert(ExistsSectionKey(section,key));
string posLine = mySectionKeysLines[BuildSectionKeyToHKey(section,key)].ToString();
myFileLines[posLine] = key + "=" + keyValue ;
return (true);
}
private bool InsertKeyValue(string section,string key, string keyValue)
{
Debug.Assert(!ExistsSectionKey(section,key));
InsertedKeys ++ ;
MaxFileLines ++ ;
string posLine = mySectionKeysLines[BuildSectionToHKey(section)].ToString();
mySectionKeysLines.Add( BuildSectionKeyToHKey(section,key) ,BuildLineToHKey(posLine , InsertedKeys.ToString()) );
myFileLines.Add (BuildLineToHKey(posLine , InsertedKeys.ToString()) ,key + "=" + keyValue );
return (true);
}
private bool InsertSection(string section)
{
Debug.Assert(!ExistsSection(section));
MaxFileLines++;
mySectionKeysLines.Add( BuildSectionToHKey(section) ,MaxFileLines.ToString() + "." + "0" );
myFileLines.Add (BuildLineToHKey(MaxFileLines.ToString() , ".0" ),BuildSectionToHKey(section) );
return (true);
}
//Public Methods
public bool WriteValue(string section,string key, string keyValue)
{
Debug.Assert(section != null && section!= "");
Debug.Assert(key !=null && key!="" && key.IndexOf("=")<0);// Char "=" not permit in key Name
Debug.Assert(keyValue!=null);
if (!ReadIniFile())return (false);
bool isWriteOK=false;
section = section.Trim();
key = key.Trim();
if (ExistsSectionKey(section,key))
{
isWriteOK = ModifyKeyValue(section,key,keyValue);
}
else if (ExistsSection(section))
{
isWriteOK = InsertKeyValue(section,key,keyValue);
}
else
{
isWriteOK = InsertSection(section);
if (isWriteOK) isWriteOK = InsertKeyValue(section,key,keyValue);
}
Debug.Assert (ExistsSectionKey(section,key));
Debug.Assert (this.ReadValue(section,key,"")==keyValue);
return (isWriteOK);
}
public bool WriteValue(string section,string key, int keyValue)
{
Debug.Assert(section != null && section!= "");
Debug.Assert(key !=null && key!="" && key.IndexOf("=")<0);
if (!ReadIniFile())return (false);
return (this.WriteValue(section,key,keyValue.ToString()));
}
public string ReadValue(string section,string key, string defaultValue)
{
Debug.Assert(section != null && section!= "");
Debug.Assert(key !=null && key!="" && key.IndexOf("=")<0);
string retValue = defaultValue;
try
{
if (!ReadIniFile()) return (defaultValue);
if (!this.ExistsSectionKey(section,key))
retValue = defaultValue;
else
{
string positionline = mySectionKeysLines[BuildSectionKeyToHKey(section,key)].ToString();
retValue = GetValueFromLine(myFileLines[positionline].ToString());
}
}
catch (System.Exception e)
{
throw new System.Exception("Error reading file: " + myIniFileName + ";section=" + section +";Key=" + key ,e);
}
return (retValue);
}
public int ReadValue(string section,string key, int defaultValue)
{
Debug.Assert(section != null && section!= "");
Debug.Assert(key !=null && key!="" && key.IndexOf("=")<0);
int retValue = defaultValue;
try
{
if (!ReadIniFile())return (retValue);
if (!this.ExistsSectionKey(section,key))
retValue = defaultValue;
else
retValue = int.Parse(this.ReadValue(section,key,defaultValue.ToString()),System.Globalization.NumberStyles.Integer);
}
catch(System.Exception e)
{
throw new System.Exception("Error reading value in file: " + myIniFileName + ";section=" + section +";Key=" + key ,e);
}
return (retValue);
}
public bool ExistsSectionKey (string section, string key)
{
Debug.Assert(section != null && section!= "");
Debug.Assert(key !=null && key!="" && key.IndexOf("=")<0);
if (!ReadIniFile()) return (false);
return (mySectionKeysLines.Contains(BuildSectionKeyToHKey(section,key)));
}
public bool EraseSectionKey(string section,string key)
{
Debug.Assert(section != null && section!= "");
Debug.Assert(key !=null && key!="" && key.IndexOf("=")<0);//char = not permit in key
try{
if (!ReadIniFile())return (false);
if (!ExistsSectionKey(section,key)) return (true); //If [section]+key not exists , nothing to do !
string positionLine = mySectionKeysLines[BuildSectionKeyToHKey(section,key)].ToString();
myFileLines.Remove(positionLine);
mySectionKeysLines.Remove(BuildSectionKeyToHKey(section,key));
return(true);
}
catch(System.Exception e)
{
throw new System.Exception("Error deleting key in file: " + myIniFileName + ";section=" + section +";Key=" + key ,e);
}
}
public bool ExistsSection (string section)
{
Debug.Assert(section != null && section!= "");
try {
if (!ReadIniFile())return (false);
return (mySectionKeysLines.Contains( BuildSectionToHKey( section.Trim()) ));
}
catch (System.Exception e){
throw new System.Exception("Error searching section in file: " + myIniFileName + ";section=" + section ,e);
}
}
public bool EraseSection (string section)
{
Debug.Assert(section != null && section!= "");
try {
if (!ReadIniFile())return (false);
if (!ExistsSection(section)) return (true); //If section not exists, nothing to do !
int indexOfSection = myFileLines.IndexOfValue(BuildSectionToHKey(section));
string line;
mySectionKeysLines.Remove(BuildSectionToHKey(section));
myFileLines.RemoveAt(indexOfSection);
while (indexOfSection < myFileLines.Count && GetIniLineType(myFileLines.GetByIndex(indexOfSection).ToString())!= (int) iniLineType.section )
{
line = myFileLines.GetByIndex(indexOfSection).ToString();
if (GetIniLineType(line)== (int) iniLineType.keyValue)
EraseSectionKey(section,GetKeyFromLine(line));
else
myFileLines.RemoveAt(indexOfSection);
}
return (true);
}
catch (System.Exception e) {
throw new System.Exception("Error deleting section in file: " + myIniFileName + ";section=" + section ,e);
}
}
public bool FlushToDisk()
{
try {
using (StreamWriter iniFileWriter = new StreamWriter(myIniFileName)){
for (int i = 0; i<myFileLines.Count ; i++)
iniFileWriter.WriteLine(myFileLines.GetByIndex(i));
}
}
catch (System.Exception e){
throw new System.Exception("Error saving file: " + myIniFileName,e);
}
return (true);
}
}
}<file_sep>/*
* Created by SharpDevelop.
* User: alex2308
* Date: 20.03.2005
* Time: 09:14
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace Mobius
{
/// <summary>
/// Description of Options.
/// </summary>
public class Options : System.Windows.Forms.Form
{
private System.Windows.Forms.CheckBox boxFallDamage;
private System.Windows.Forms.GroupBox groupBox8;
private System.Windows.Forms.CheckBox boxHerbs;
private System.Windows.Forms.TextBox txtProcess;
private System.Windows.Forms.CheckBox boxFollowNPC;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox7;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.CheckBox boxMountainClimb;
private System.Windows.Forms.CheckBox boxMinerals;
private System.Windows.Forms.CheckBox boxElementals;
private System.Windows.Forms.CheckBox boxWoWTeleport;
private System.Windows.Forms.CheckBox boxDragonkin;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.CheckBox boxLockSwim;
private System.Windows.Forms.CheckBox boxTreasure;
private System.Windows.Forms.Label lblProcessExe;
private System.Windows.Forms.CheckBox boxCritters;
private System.Windows.Forms.CheckBox boxUndead;
private System.Windows.Forms.CheckBox boxEnableHotkeys;
private System.Windows.Forms.CheckBox boxGiants;
private System.Windows.Forms.CheckBox boxHumanoids;
private System.Windows.Forms.CheckBox boxBeasts;
private System.Windows.Forms.CheckBox boxDemons;
public static bool[] hacks = {false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false};
public static string processName;
public Options()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
getSettings();
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
#region Windows Forms Designer generated code
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent() {
this.boxDemons = new System.Windows.Forms.CheckBox();
this.boxBeasts = new System.Windows.Forms.CheckBox();
this.boxHumanoids = new System.Windows.Forms.CheckBox();
this.boxGiants = new System.Windows.Forms.CheckBox();
this.boxEnableHotkeys = new System.Windows.Forms.CheckBox();
this.boxUndead = new System.Windows.Forms.CheckBox();
this.boxCritters = new System.Windows.Forms.CheckBox();
this.lblProcessExe = new System.Windows.Forms.Label();
this.boxTreasure = new System.Windows.Forms.CheckBox();
this.boxLockSwim = new System.Windows.Forms.CheckBox();
this.btnExit = new System.Windows.Forms.Button();
this.boxDragonkin = new System.Windows.Forms.CheckBox();
this.boxWoWTeleport = new System.Windows.Forms.CheckBox();
this.boxElementals = new System.Windows.Forms.CheckBox();
this.boxMinerals = new System.Windows.Forms.CheckBox();
this.boxMountainClimb = new System.Windows.Forms.CheckBox();
this.btnSave = new System.Windows.Forms.Button();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.groupBox7 = new System.Windows.Forms.GroupBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.boxFollowNPC = new System.Windows.Forms.CheckBox();
this.txtProcess = new System.Windows.Forms.TextBox();
this.boxHerbs = new System.Windows.Forms.CheckBox();
this.groupBox8 = new System.Windows.Forms.GroupBox();
this.boxFallDamage = new System.Windows.Forms.CheckBox();
this.groupBox5.SuspendLayout();
this.groupBox7.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox8.SuspendLayout();
this.SuspendLayout();
//
// boxDemons
//
this.boxDemons.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxDemons.Location = new System.Drawing.Point(8, 49);
this.boxDemons.Name = "boxDemons";
this.boxDemons.Size = new System.Drawing.Size(104, 15);
this.boxDemons.TabIndex = 2;
this.boxDemons.Text = "Demons";
this.boxDemons.Checked=hacks[7];
this.boxDemons.CheckedChanged += new System.EventHandler(this.BoxDemonsCheckedChanged);
//
// boxBeasts
//
this.boxBeasts.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxBeasts.Location = new System.Drawing.Point(8, 17);
this.boxBeasts.Name = "boxBeasts";
this.boxBeasts.Size = new System.Drawing.Size(104, 15);
this.boxBeasts.TabIndex = 0;
this.boxBeasts.Text = "Beasts";
this.boxBeasts.Checked=hacks[5];
this.boxBeasts.CheckedChanged += new System.EventHandler(this.BoxBeastsCheckedChanged);
//
// boxHumanoids
//
this.boxHumanoids.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxHumanoids.Location = new System.Drawing.Point(80, 49);
this.boxHumanoids.Name = "boxHumanoids";
this.boxHumanoids.Size = new System.Drawing.Size(80, 15);
this.boxHumanoids.TabIndex = 6;
this.boxHumanoids.Text = "Humanoids";
this.boxHumanoids.Checked=hacks[11];
this.boxHumanoids.CheckedChanged += new System.EventHandler(this.BoxHumanoidsCheckedChanged);
//
// boxGiants
//
this.boxGiants.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxGiants.Location = new System.Drawing.Point(80, 17);
this.boxGiants.Name = "boxGiants";
this.boxGiants.Size = new System.Drawing.Size(56, 15);
this.boxGiants.TabIndex = 4;
this.boxGiants.Text = "Giants";
this.boxGiants.CheckedChanged += new System.EventHandler(this.BoxGiantsCheckedChanged);
//
// boxEnableHotkeys
//
this.boxEnableHotkeys.Location = new System.Drawing.Point(8, 16);
this.boxEnableHotkeys.Name = "boxEnableHotkeys";
this.boxEnableHotkeys.Size = new System.Drawing.Size(104, 16);
this.boxEnableHotkeys.TabIndex = 1;
this.boxEnableHotkeys.Text = "Enable Hotkeys";
this.boxEnableHotkeys.Checked=hacks[16];
this.boxEnableHotkeys.CheckedChanged += new System.EventHandler(this.BoxEnableHotkeysCheckedChanged);
//
// boxUndead
//
this.boxUndead.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxUndead.Location = new System.Drawing.Point(80, 33);
this.boxUndead.Name = "boxUndead";
this.boxUndead.Size = new System.Drawing.Size(64, 15);
this.boxUndead.TabIndex = 5;
this.boxUndead.Text = "Undead";
this.boxUndead.Checked=hacks[10];
this.boxUndead.CheckedChanged += new System.EventHandler(this.BoxUndeadCheckedChanged);
//
// boxCritters
//
this.boxCritters.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxCritters.Location = new System.Drawing.Point(80, 65);
this.boxCritters.Name = "boxCritters";
this.boxCritters.Size = new System.Drawing.Size(64, 15);
this.boxCritters.TabIndex = 7;
this.boxCritters.Text = "Critters";
this.boxCritters.Checked=hacks[12];
this.boxCritters.CheckedChanged += new System.EventHandler(this.BoxCrittersCheckedChanged);
//
// lblProcessExe
//
this.lblProcessExe.Location = new System.Drawing.Point(104, 20);
this.lblProcessExe.Name = "lblProcessExe";
this.lblProcessExe.Size = new System.Drawing.Size(26, 16);
this.lblProcessExe.TabIndex = 1;
this.lblProcessExe.Text = ".exe";
//
// boxTreasure
//
this.boxTreasure.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxTreasure.Checked = hacks[15];
this.boxTreasure.CheckState = System.Windows.Forms.CheckState.Checked;
this.boxTreasure.Location = new System.Drawing.Point(8, 97);
this.boxTreasure.Name = "boxTreasure";
this.boxTreasure.Size = new System.Drawing.Size(72, 15);
this.boxTreasure.TabIndex = 10;
this.boxTreasure.Text = "Treasure";
this.boxTreasure.CheckedChanged += new System.EventHandler(this.BoxTreasureCheckedChanged);
//
// boxLockSwim
//
this.boxLockSwim.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.boxLockSwim.Location = new System.Drawing.Point(8, 49);
this.boxLockSwim.Name = "boxLockSwim";
this.boxLockSwim.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.boxLockSwim.Size = new System.Drawing.Size(120, 15);
this.boxLockSwim.TabIndex = 2;
this.boxLockSwim.Checked=hacks[2];
this.boxLockSwim.Text = "Lock Swim Speed";
//
// btnExit
//
this.btnExit.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnExit.Location = new System.Drawing.Point(96, 160);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(80, 24);
this.btnExit.TabIndex = 36;
this.btnExit.Text = "Exit";
this.btnExit.Click += new System.EventHandler(this.BtnExitClick);
//
// boxDragonkin
//
this.boxDragonkin.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxDragonkin.Location = new System.Drawing.Point(8, 33);
this.boxDragonkin.Name = "boxDragonkin";
this.boxDragonkin.Size = new System.Drawing.Size(104, 15);
this.boxDragonkin.TabIndex = 1;
this.boxDragonkin.Text = "Dragonkin";
this.boxDragonkin.Checked=hacks[6];
this.boxDragonkin.CheckedChanged += new System.EventHandler(this.BoxDragonkinCheckedChanged);
//
// boxWoWTeleport
//
this.boxWoWTeleport.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.boxWoWTeleport.Location = new System.Drawing.Point(8, 81);
this.boxWoWTeleport.Name = "boxWoWTeleport";
this.boxWoWTeleport.Size = new System.Drawing.Size(112, 14);
this.boxWoWTeleport.TabIndex = 2;
this.boxWoWTeleport.Checked=hacks[4];
this.boxWoWTeleport.Text = "Teleport to Plane";
//
// boxElementals
//
this.boxElementals.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxElementals.Location = new System.Drawing.Point(8, 65);
this.boxElementals.Name = "boxElementals";
this.boxElementals.Size = new System.Drawing.Size(104, 15);
this.boxElementals.TabIndex = 3;
this.boxElementals.Text = "Elementals";
this.boxElementals.Checked=hacks[8];
this.boxElementals.CheckedChanged += new System.EventHandler(this.BoxElementalsCheckedChanged);
//
// boxMinerals
//
this.boxMinerals.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxMinerals.Location = new System.Drawing.Point(80, 81);
this.boxMinerals.Name = "boxMinerals";
this.boxMinerals.Size = new System.Drawing.Size(64, 15);
this.boxMinerals.TabIndex = 9;
this.boxMinerals.Text = "Minerals";
this.boxMinerals.Checked=hacks[14];
this.boxMinerals.CheckedChanged += new System.EventHandler(this.BoxMineralsCheckedChanged);
//
// boxMountainClimb
//
this.boxMountainClimb.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.boxMountainClimb.Location = new System.Drawing.Point(8, 17);
this.boxMountainClimb.Name = "boxMountainClimb";
this.boxMountainClimb.Size = new System.Drawing.Size(120, 15);
this.boxMountainClimb.TabIndex = 0;
this.boxMountainClimb.Checked=hacks[0];
this.boxMountainClimb.Text = "Mountain Climb";
//
// btnSave
//
this.btnSave.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnSave.Enabled = false;
this.btnSave.Location = new System.Drawing.Point(0, 160);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(80, 24);
this.btnSave.TabIndex = 35;
this.btnSave.Text = "Save";
this.btnSave.Click += new System.EventHandler(this.BtnSaveClick);
//
// groupBox5
//
this.groupBox5.Controls.Add(this.lblProcessExe);
this.groupBox5.Controls.Add(this.txtProcess);
this.groupBox5.Location = new System.Drawing.Point(176, 104);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(136, 40);
this.groupBox5.TabIndex = 34;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Processname to hook on";
//
// groupBox7
//
this.groupBox7.Controls.Add(this.boxFollowNPC);
this.groupBox7.Controls.Add(this.boxWoWTeleport);
this.groupBox7.Controls.Add(this.boxMountainClimb);
this.groupBox7.Controls.Add(this.boxFallDamage);
this.groupBox7.Controls.Add(this.boxLockSwim);
this.groupBox7.Location = new System.Drawing.Point(176, 0);
this.groupBox7.Name = "groupBox7";
this.groupBox7.Size = new System.Drawing.Size(136, 104);
this.groupBox7.TabIndex = 33;
this.groupBox7.TabStop = false;
this.groupBox7.Text = "Hacks";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.boxEnableHotkeys);
this.groupBox1.Location = new System.Drawing.Point(0, 120);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(176, 40);
this.groupBox1.TabIndex = 37;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Hotkeys";
//
// boxFollowNPC
//
this.boxFollowNPC.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.boxFollowNPC.Location = new System.Drawing.Point(8, 63);
this.boxFollowNPC.Name = "boxFollowNPC";
this.boxFollowNPC.Size = new System.Drawing.Size(80, 17);
this.boxFollowNPC.TabIndex = 2;
this.boxFollowNPC.Checked=hacks[3];
this.boxFollowNPC.Text = "Follow NPC";
//
// txtProcess
//
this.txtProcess.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtProcess.Location = new System.Drawing.Point(8, 16);
this.txtProcess.Name = "txtProcess";
this.txtProcess.Size = new System.Drawing.Size(96, 20);
this.txtProcess.TabIndex = 0;
this.txtProcess.Text = processName;
this.txtProcess.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.txtProcess.TextChanged += new System.EventHandler(this.TxtProcessTextChanged);
//
// boxHerbs
//
this.boxHerbs.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.boxHerbs.Location = new System.Drawing.Point(8, 81);
this.boxHerbs.Name = "boxHerbs";
this.boxHerbs.Size = new System.Drawing.Size(104, 15);
this.boxHerbs.TabIndex = 8;
this.boxHerbs.Text = "Herbs";
this.boxHerbs.Checked=hacks[13];
this.boxHerbs.CheckedChanged += new System.EventHandler(this.BoxHerbsCheckedChanged);
//
// groupBox8
//
this.groupBox8.Controls.Add(this.boxTreasure);
this.groupBox8.Controls.Add(this.boxMinerals);
this.groupBox8.Controls.Add(this.boxHerbs);
this.groupBox8.Controls.Add(this.boxCritters);
this.groupBox8.Controls.Add(this.boxHumanoids);
this.groupBox8.Controls.Add(this.boxUndead);
this.groupBox8.Controls.Add(this.boxGiants);
this.groupBox8.Controls.Add(this.boxElementals);
this.groupBox8.Controls.Add(this.boxDemons);
this.groupBox8.Controls.Add(this.boxDragonkin);
this.groupBox8.Controls.Add(this.boxBeasts);
this.groupBox8.Location = new System.Drawing.Point(0, 0);
this.groupBox8.Name = "groupBox8";
this.groupBox8.Size = new System.Drawing.Size(176, 120);
this.groupBox8.TabIndex = 32;
this.groupBox8.TabStop = false;
this.groupBox8.Text = "MiniMap Hack";
//
// boxFallDamage
//
this.boxFallDamage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.boxFallDamage.Location = new System.Drawing.Point(8, 33);
this.boxFallDamage.Name = "boxFallDamage";
this.boxFallDamage.Size = new System.Drawing.Size(120, 15);
this.boxFallDamage.TabIndex = 1;
this.boxFallDamage.Checked=hacks[1];
this.boxFallDamage.Text = "No Fall Damage";
//
// Options
//
this.AcceptButton = this.btnSave;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnExit;
this.ClientSize = new System.Drawing.Size(314, 183);
this.ControlBox = false;
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.groupBox8);
this.Controls.Add(this.groupBox7);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.Name = "Options";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Mobius Options by alex2308";
this.groupBox5.ResumeLayout(false);
this.groupBox7.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox8.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public static bool[] getHacks() {
return(hacks);
}
public static string getProcessName() {
return(processName);
}
private void getSettings() {
try
{
int i=0;
FileStream fs = new FileStream("settings.ini", FileMode.Open);
StreamReader sr = new StreamReader(fs);
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith("#") == true) {}
else {
if (line=="1") {
hacks[i]=true;
i++;
}
if (line=="0") {
hacks[i]=false;
i++;
}
if (line!="0" & line!="1") processName=line;
}
}
//for (int j=0; j<=i; j++) MessageBox.Show(hacks[j].ToString(),"bool"+j , MessageBoxButtons.OK, MessageBoxIcon.Error);
//MessageBox.Show(processName,"processname" , MessageBoxButtons.OK, MessageBoxIcon.Error);
fs.Close();
}
catch (Exception e) {MessageBox.Show(e.ToString(),"Exception" , MessageBoxButtons.OK, MessageBoxIcon.Error);}
}
void BtnExitClick(object sender, System.EventArgs e)
{
this.Hide();
}
void BtnSaveClick(object sender, System.EventArgs e)
{
//SaveSettings();
}
private void boxMountainClimbCheckedChanged(object sender, System.EventArgs e)
{
hacks[0]=!hacks[0];
}
private void boxFallDamageCheckedChanged(object sender, System.EventArgs e)
{
hacks[1]=!hacks[1];
}
private void BoxLockSwimCheckedChanged(object sender, System.EventArgs e)
{
hacks[2]=!hacks[2];
}
private void boxFollowNPCCheckedChanged(object sender, System.EventArgs e)
{
hacks[3]=!hacks[3];
}
private void boxWoWTeleportCheckedChanged(object sender, System.EventArgs e)
{
hacks[4]=!hacks[4];
}
void BoxBeastsCheckedChanged(object sender, System.EventArgs e)
{
hacks[5]=!hacks[5];
}
void BoxDragonkinCheckedChanged(object sender, System.EventArgs e)
{
hacks[6]=!hacks[6];
}
void BoxDemonsCheckedChanged(object sender, System.EventArgs e)
{
hacks[7]=!hacks[7];
}
void BoxElementalsCheckedChanged(object sender, System.EventArgs e)
{
hacks[8]=!hacks[8];
}
void BoxGiantsCheckedChanged(object sender, System.EventArgs e)
{
hacks[9]=!hacks[9];
}
void BoxUndeadCheckedChanged(object sender, System.EventArgs e)
{
hacks[10]=!hacks[10];
}
void BoxHumanoidsCheckedChanged(object sender, System.EventArgs e)
{
hacks[11]=!hacks[11];
}
void BoxCrittersCheckedChanged(object sender, System.EventArgs e)
{
hacks[12]=!hacks[12];
}
void BoxHerbsCheckedChanged(object sender, System.EventArgs e)
{
hacks[13]=!hacks[13];
}
void BoxMineralsCheckedChanged(object sender, System.EventArgs e)
{
hacks[14]=!hacks[14];
}
void BoxTreasureCheckedChanged(object sender, System.EventArgs e)
{
hacks[15]=!hacks[15];
}
void BoxEnableHotkeysCheckedChanged(object sender, System.EventArgs e)
{
hacks[16]=!hacks[16];
}
void TxtProcessTextChanged(object sender, System.EventArgs e)
{
processName=this.txtProcess.Text;
}
}
}
<file_sep>using System;
using System.Xml;
namespace Mobius
{
public class SavedLoc
{
private string mName;
private string mKey;
private float mX;
private float mY;
private float mZ;
public SavedLoc()
{
this.mName = "None";
this.mX = 0;
this.mY = 0;
this.mZ = 0;
}
public SavedLoc(string name, float x, float y, float z, string key)
{
this.mName = name;
this.mX = x;
this.mY = y;
this.mZ = z;
this.mKey = key;
}
public string Name
{
get { return this.mName; }
set { this.mName = value; }
}
public float X
{
get { return this.mX; }
set { this.mX = value; }
}
public float Y
{
get { return this.mY; }
set { this.mY = value; }
}
public float Z
{
get { return this.mZ; }
set { this.mZ = value; }
}
public string Key
{
get { return this.mKey; }
set { this.mKey = value; }
}
public static SavedLoc[] LoadLocations(string filePath)
{
System.Collections.ArrayList list;
list = new System.Collections.ArrayList();
if (System.IO.File.Exists(filePath))
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNodeList nodes = doc.SelectNodes("//location");
foreach (XmlNode node in nodes)
{
SavedLoc loc = new SavedLoc();
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.Name == "name")
{
loc.Name = childNode.InnerText;
}
else if (childNode.Name == "x")
{
loc.X = float.Parse(childNode.InnerText);
}
else if (childNode.Name == "y")
{
loc.Y = float.Parse(childNode.InnerText);
}
else if (childNode.Name == "z")
{
loc.Z = float.Parse(childNode.InnerText);
}
else if (childNode.Name == "key")
{
loc.Key = childNode.InnerText;
}
}
list.Add(loc);
}
}
return (SavedLoc[])list.ToArray(typeof(SavedLoc));
}
public static void SaveLocations(string filePath, SavedLoc[] locations)
{
System.IO.FileStream stream = System.IO.File.Create(filePath);
XmlTextWriter xml = new XmlTextWriter(stream, System.Text.Encoding.ASCII);
xml.Formatting = Formatting.Indented;
xml.Indentation = 2;
xml.IndentChar = ' ';
xml.WriteStartDocument(true);
xml.WriteStartElement("saved");
foreach(SavedLoc loc in locations)
{
xml.WriteStartElement("location");
xml.WriteStartElement("name");
xml.WriteString(loc.Name);
xml.WriteEndElement();
xml.WriteStartElement("x");
xml.WriteString(loc.X.ToString());
xml.WriteEndElement();
xml.WriteStartElement("y");
xml.WriteString(loc.Y.ToString());
xml.WriteEndElement();
xml.WriteStartElement("z");
xml.WriteString(loc.Z.ToString());
xml.WriteEndElement();
xml.WriteStartElement("key");
xml.WriteString(loc.Key.ToString());
xml.WriteEndElement();
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.WriteEndDocument();
xml.Flush();
stream.Flush();
xml.Close();
stream.Close();
}
public static void RemoveLoc(string strXml, string strMember)
{
// Open the location xml
XmlDocument xdMembers = new XmlDocument();
xdMembers.Load(strXml);
XmlNodeList xnlList = xdMembers.GetElementsByTagName("location");
for (int intMember = 0; intMember < xnlList.Count; intMember++)
{
//Find the correct location
if(xnlList[intMember].FirstChild.InnerXml == strMember)
{
XmlElement xeRoot = xdMembers.DocumentElement;
xeRoot.RemoveChild(xnlList[intMember]);
//Write the xml
XmlTextWriter xtwMembers = new XmlTextWriter(strXml, null);
xtwMembers.Formatting = Formatting.Indented;
xdMembers.Save(xtwMembers);
xtwMembers.Close();
return;
}
}
}
public static void EditMember(string strXml, string strLocation, string strNewName, string strNewX, string strNewY,string strNewZ)
{
// Open the location xml
XmlDocument xdLocation = new XmlDocument();
xdLocation.Load(strXml);
XmlNodeList xnlList = xdLocation.GetElementsByTagName("location");
for (int intLocation = 0; intLocation < xnlList.Count; intLocation++)
{
//Find the correct location
if(xnlList[intLocation].FirstChild.InnerXml == strLocation)
{
xnlList[intLocation].FirstChild.InnerXml = strNewName;
xnlList[intLocation].ChildNodes[1].InnerXml = strNewX;
xnlList[intLocation].ChildNodes[2].InnerXml = strNewY;
xnlList[intLocation].ChildNodes[3].InnerXml = strNewZ;
//Write the xml
XmlTextWriter xtwLocation = new XmlTextWriter(strXml, null);
xtwLocation.Formatting = Formatting.Indented;
xdLocation.Save(xtwLocation);
xtwLocation.Close();
return;
}
}
}
}
}
<file_sep>using System;
namespace Mobius
{
public class ExpandedTreeNode : System.Windows.Forms.TreeNode
{
private object mAssociatedObject;
public ExpandedTreeNode() : base()
{
this.mAssociatedObject = null;
}
public ExpandedTreeNode(string text) : base(text)
{
this.mAssociatedObject = null;
}
public object AssociatedObject
{
get { return this.mAssociatedObject; }
set { this.mAssociatedObject = value; }
}
}
}
<file_sep>using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Threading;
namespace Mobius
{
public class MainForm : System.Windows.Forms.Form
{
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Button btnLoad;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.TextBox txtStatus;
private System.Windows.Forms.Label lblLocationName;
private System.Windows.Forms.TextBox txtY;
private System.Windows.Forms.TextBox txtX;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TextBox txtZ;
private System.Windows.Forms.Label lblCurZ;
private System.Windows.Forms.GroupBox groupBox6;
private System.Windows.Forms.Label lblCurX;
private System.Windows.Forms.Timer timRefreshCoords;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Label lblAuthors;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Button btnClearStatus;
private System.Windows.Forms.Label lblCurSpeed;
private System.Windows.Forms.TextBox txtKey;
private System.Windows.Forms.Label lblCurY;
private System.Windows.Forms.TextBox txtLocationName;
private System.Windows.Forms.Label lblHotkey;
private System.Windows.Forms.Button btnSaveLoc;
private System.Windows.Forms.TextBox txtSpeed;
private System.Windows.Forms.TreeView lstSavedLocs;
private System.Windows.Forms.Button btnOptions;
private System.Windows.Forms.Timer update;
private System.Windows.Forms.Button btnClearHotkey;
// Quickload/Quicksave variables by alex2308
float quicklocx = 0;
float quicklocy = 0;
float quicklocz = 0;
bool quicksaved = false;
bool addedLocations = false;
Options optionsForm = new Options();
#region Declarations
private MemoryLoc mX;
private MemoryLoc mY;
private MemoryLoc mZ;
private MemoryLoc mSpeed;
public MemoryLoc mSwimSpeed;
public MemoryLoc mMountainClimb;
public MemoryLoc mFallDamage;
public MemoryLoc mFollowNPC;
public MemoryLoc mWoWTeleport;
private MemoryLoc mMapHack;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private MemoryLoc mMapHackResources; //Herbs Minerals and Chests
#endregion
#region Auto-Code
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.components = new System.ComponentModel.Container();
this.btnClearHotkey = new System.Windows.Forms.Button();
this.update = new System.Windows.Forms.Timer(this.components);
this.btnOptions = new System.Windows.Forms.Button();
this.lstSavedLocs = new System.Windows.Forms.TreeView();
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.txtSpeed = new System.Windows.Forms.TextBox();
this.btnSaveLoc = new System.Windows.Forms.Button();
this.lblHotkey = new System.Windows.Forms.Label();
this.txtLocationName = new System.Windows.Forms.TextBox();
this.lblCurY = new System.Windows.Forms.Label();
this.txtKey = new System.Windows.Forms.TextBox();
this.lblCurSpeed = new System.Windows.Forms.Label();
this.btnClearStatus = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.lblAuthors = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.txtX = new System.Windows.Forms.TextBox();
this.lblCurZ = new System.Windows.Forms.Label();
this.lblCurX = new System.Windows.Forms.Label();
this.txtY = new System.Windows.Forms.TextBox();
this.txtZ = new System.Windows.Forms.TextBox();
this.timRefreshCoords = new System.Windows.Forms.Timer(this.components);
this.groupBox6 = new System.Windows.Forms.GroupBox();
this.txtStatus = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.btnLoad = new System.Windows.Forms.Button();
this.lblLocationName = new System.Windows.Forms.Label();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.groupBox3.SuspendLayout();
this.groupBox6.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox4.SuspendLayout();
this.SuspendLayout();
//
// btnClearHotkey
//
this.btnClearHotkey.Location = new System.Drawing.Point(152, 41);
this.btnClearHotkey.Name = "btnClearHotkey";
this.btnClearHotkey.Size = new System.Drawing.Size(16, 20);
this.btnClearHotkey.TabIndex = 23;
this.btnClearHotkey.Text = "C";
this.btnClearHotkey.Click += new System.EventHandler(this.BtnClearHotkeyClick);
//
// update
//
this.update.Interval = 1000;
this.update.Tick += new System.EventHandler(this.UpdateTick);
//
// btnOptions
//
this.btnOptions.Location = new System.Drawing.Point(0, 512);
this.btnOptions.Name = "btnOptions";
this.btnOptions.Size = new System.Drawing.Size(176, 24);
this.btnOptions.TabIndex = 33;
this.btnOptions.Text = "OPTIONS";
this.btnOptions.Click += new System.EventHandler(this.BtnOptionsClick);
//
// lstSavedLocs
//
this.lstSavedLocs.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lstSavedLocs.ContextMenu = this.contextMenu1;
this.lstSavedLocs.ImageIndex = -1;
this.lstSavedLocs.Location = new System.Drawing.Point(8, 16);
this.lstSavedLocs.Name = "lstSavedLocs";
this.lstSavedLocs.SelectedImageIndex = -1;
this.lstSavedLocs.Size = new System.Drawing.Size(160, 170);
this.lstSavedLocs.TabIndex = 13;
this.lstSavedLocs.DoubleClick += new System.EventHandler(this.lstSavedLocs_DoubleClick);
this.lstSavedLocs.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.LstSavedLocsAfterSelect);
//
// contextMenu1
//
this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem2});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.Text = "edit";
this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
//
// menuItem2
//
this.menuItem2.Index = 1;
this.menuItem2.Text = "delete";
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
//
// txtSpeed
//
this.txtSpeed.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtSpeed.Location = new System.Drawing.Point(96, 88);
this.txtSpeed.Name = "txtSpeed";
this.txtSpeed.Size = new System.Drawing.Size(72, 20);
this.txtSpeed.TabIndex = 35;
this.txtSpeed.Text = "";
this.txtSpeed.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtZ_KeyPress);
//
// btnSaveLoc
//
this.btnSaveLoc.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnSaveLoc.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.btnSaveLoc.Location = new System.Drawing.Point(136, 17);
this.btnSaveLoc.Name = "btnSaveLoc";
this.btnSaveLoc.Size = new System.Drawing.Size(32, 23);
this.btnSaveLoc.TabIndex = 18;
this.btnSaveLoc.Text = "Add";
this.btnSaveLoc.Click += new System.EventHandler(this.btnSaveLoc_Click);
//
// lblHotkey
//
this.lblHotkey.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblHotkey.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.lblHotkey.Location = new System.Drawing.Point(8, 40);
this.lblHotkey.Name = "lblHotkey";
this.lblHotkey.Size = new System.Drawing.Size(24, 16);
this.lblHotkey.TabIndex = 19;
this.lblHotkey.Text = "Key";
//
// txtLocationName
//
this.txtLocationName.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtLocationName.Location = new System.Drawing.Point(56, 17);
this.txtLocationName.MaxLength = 100;
this.txtLocationName.Name = "txtLocationName";
this.txtLocationName.Size = new System.Drawing.Size(80, 20);
this.txtLocationName.TabIndex = 17;
this.txtLocationName.Text = "";
//
// lblCurY
//
this.lblCurY.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.lblCurY.Location = new System.Drawing.Point(8, 48);
this.lblCurY.Name = "lblCurY";
this.lblCurY.Size = new System.Drawing.Size(80, 16);
this.lblCurY.TabIndex = 19;
this.lblCurY.Text = "Y placehold";
//
// txtKey
//
this.txtKey.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtKey.Location = new System.Drawing.Point(56, 40);
this.txtKey.Name = "txtKey";
this.txtKey.ReadOnly = true;
this.txtKey.Size = new System.Drawing.Size(96, 20);
this.txtKey.TabIndex = 20;
this.txtKey.Text = "";
//
// lblCurSpeed
//
this.lblCurSpeed.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.lblCurSpeed.Location = new System.Drawing.Point(8, 96);
this.lblCurSpeed.Name = "lblCurSpeed";
this.lblCurSpeed.Size = new System.Drawing.Size(88, 16);
this.lblCurSpeed.TabIndex = 23;
this.lblCurSpeed.Text = "Speed";
//
// btnClearStatus
//
this.btnClearStatus.Location = new System.Drawing.Point(94, 4);
this.btnClearStatus.Name = "btnClearStatus";
this.btnClearStatus.Size = new System.Drawing.Size(8, 8);
this.btnClearStatus.TabIndex = 1;
this.btnClearStatus.Click += new System.EventHandler(this.BtnClearStatusClick);
//
// btnSave
//
this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnSave.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.btnSave.Location = new System.Drawing.Point(8, 186);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(80, 23);
this.btnSave.TabIndex = 14;
this.btnSave.Text = "Save Locations";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// lblAuthors
//
this.lblAuthors.Location = new System.Drawing.Point(0, 0);
this.lblAuthors.Name = "lblAuthors";
this.lblAuthors.Size = new System.Drawing.Size(176, 24);
this.lblAuthors.TabIndex = 34;
this.lblAuthors.Text = "mods by alex2308, Devil323";
this.lblAuthors.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lblAuthors.Click += new System.EventHandler(this.lblAuthors_Click);
//
// groupBox3
//
this.groupBox3.Controls.Add(this.txtX);
this.groupBox3.Controls.Add(this.lblCurSpeed);
this.groupBox3.Controls.Add(this.lblCurZ);
this.groupBox3.Controls.Add(this.lblCurY);
this.groupBox3.Controls.Add(this.lblCurX);
this.groupBox3.Controls.Add(this.txtY);
this.groupBox3.Controls.Add(this.txtZ);
this.groupBox3.Controls.Add(this.txtSpeed);
this.groupBox3.Location = new System.Drawing.Point(0, 24);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(176, 120);
this.groupBox3.TabIndex = 26;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Position Control";
//
// txtX
//
this.txtX.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtX.Location = new System.Drawing.Point(96, 16);
this.txtX.Name = "txtX";
this.txtX.Size = new System.Drawing.Size(72, 20);
this.txtX.TabIndex = 29;
this.txtX.Text = "";
this.txtX.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtX_KeyPress);
//
// lblCurZ
//
this.lblCurZ.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.lblCurZ.Location = new System.Drawing.Point(8, 72);
this.lblCurZ.Name = "lblCurZ";
this.lblCurZ.Size = new System.Drawing.Size(80, 16);
this.lblCurZ.TabIndex = 20;
this.lblCurZ.Text = "Z placehold";
//
// lblCurX
//
this.lblCurX.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.lblCurX.Location = new System.Drawing.Point(8, 24);
this.lblCurX.Name = "lblCurX";
this.lblCurX.Size = new System.Drawing.Size(80, 16);
this.lblCurX.TabIndex = 18;
this.lblCurX.Text = "X placehold";
//
// txtY
//
this.txtY.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtY.Location = new System.Drawing.Point(96, 40);
this.txtY.Name = "txtY";
this.txtY.Size = new System.Drawing.Size(72, 20);
this.txtY.TabIndex = 33;
this.txtY.Text = "";
this.txtY.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtY_KeyPress);
//
// txtZ
//
this.txtZ.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtZ.Location = new System.Drawing.Point(96, 64);
this.txtZ.Name = "txtZ";
this.txtZ.Size = new System.Drawing.Size(72, 20);
this.txtZ.TabIndex = 34;
this.txtZ.Text = "";
this.txtZ.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtZ_KeyPress);
//
// timRefreshCoords
//
this.timRefreshCoords.Interval = 1000;
this.timRefreshCoords.Tick += new System.EventHandler(this.timRefreshCoords_Tick);
//
// groupBox6
//
this.groupBox6.Controls.Add(this.btnClearStatus);
this.groupBox6.Controls.Add(this.txtStatus);
this.groupBox6.Location = new System.Drawing.Point(0, 208);
this.groupBox6.Name = "groupBox6";
this.groupBox6.Size = new System.Drawing.Size(176, 88);
this.groupBox6.TabIndex = 29;
this.groupBox6.TabStop = false;
this.groupBox6.Text = "Status Messages";
//
// txtStatus
//
this.txtStatus.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtStatus.Location = new System.Drawing.Point(8, 16);
this.txtStatus.Multiline = true;
this.txtStatus.Name = "txtStatus";
this.txtStatus.ReadOnly = true;
this.txtStatus.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtStatus.Size = new System.Drawing.Size(160, 64);
this.txtStatus.TabIndex = 0;
this.txtStatus.Text = "Idle...\r\n";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.btnLoad);
this.groupBox2.Controls.Add(this.btnSave);
this.groupBox2.Controls.Add(this.lstSavedLocs);
this.groupBox2.Location = new System.Drawing.Point(0, 296);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(176, 216);
this.groupBox2.TabIndex = 25;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Location List";
//
// btnLoad
//
this.btnLoad.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnLoad.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.btnLoad.Location = new System.Drawing.Point(88, 186);
this.btnLoad.Name = "btnLoad";
this.btnLoad.Size = new System.Drawing.Size(80, 23);
this.btnLoad.TabIndex = 21;
this.btnLoad.Text = "Load Locations";
this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click);
//
// lblLocationName
//
this.lblLocationName.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblLocationName.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.lblLocationName.Location = new System.Drawing.Point(8, 16);
this.lblLocationName.Name = "lblLocationName";
this.lblLocationName.Size = new System.Drawing.Size(48, 16);
this.lblLocationName.TabIndex = 1;
this.lblLocationName.Text = "Name:";
//
// groupBox4
//
this.groupBox4.Controls.Add(this.btnClearHotkey);
this.groupBox4.Controls.Add(this.txtKey);
this.groupBox4.Controls.Add(this.lblHotkey);
this.groupBox4.Controls.Add(this.btnSaveLoc);
this.groupBox4.Controls.Add(this.txtLocationName);
this.groupBox4.Controls.Add(this.lblLocationName);
this.groupBox4.Location = new System.Drawing.Point(0, 144);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(176, 64);
this.groupBox4.TabIndex = 27;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Save new position";
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(178, 538);
this.Controls.Add(this.lblAuthors);
this.Controls.Add(this.btnOptions);
this.Controls.Add(this.groupBox6);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximumSize = new System.Drawing.Size(1200, 1000);
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Mobius v1.5";
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
this.Load += new System.EventHandler(this.MainForm_Load);
this.groupBox3.ResumeLayout(false);
this.groupBox6.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox4.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
//[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
#endregion
#region Constructors
public MainForm()
{
//About aboutForm = new Mobius.About();.
//aboutForm.ShowDialog();
InitializeComponent();
}
#endregion
#region Methods
private void AddNewLocation(SavedLoc loc)
{
ExpandedTreeNode node = new ExpandedTreeNode(loc.Name);
node.AssociatedObject = loc;
node.Nodes.Add(String.Format("X: {0}", loc.X));
node.Nodes.Add(String.Format("Y: {0}", loc.Y));
node.Nodes.Add(String.Format("Z: {0}", loc.Z));
node.Nodes.Add(String.Format("Key: {0}",loc.Key));
this.lstSavedLocs.Nodes.Add(node);
}
private bool RefreshPointers()
{
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(Mobius.Options.getProcessName());
//MessageBox.Show(Mobius.Options.getProcessName(),"processname2" , MessageBoxButtons.OK, MessageBoxIcon.Error);
bool found = false;
if (processes.Length > 0)
{
System.Diagnostics.Process wowProc = processes[0];
int i = 0;
int[] basePtrs = new int[] {
0x12C3EC,
0x12C3CC,
0x12C3B4,
0x12C3F0,
0x12E188,
0x13C3B4
};
while (!found & i < basePtrs.Length)
{
MemoryLoc stat = new MemoryLoc(wowProc, (int)basePtrs[i]);
if (stat.GetInt32().ToString("x").EndsWith("008"))
{
//txtStatus.Text = String.Format("Base pointer found at: {0}", stat.GetInt32().ToString("x"));
this.mX = new MemoryLoc(wowProc, stat.GetInt32() + 0x92C);
this.mY = new MemoryLoc(wowProc, stat.GetInt32() + 0x928);
this.mZ = new MemoryLoc(wowProc, stat.GetInt32() + 0x930);
this.mSpeed = new MemoryLoc(wowProc, stat.GetInt32() + 0x9A4);
this.mSwimSpeed = new MemoryLoc(wowProc, stat.GetInt32() + 0x9AC);
this.mMountainClimb = new MemoryLoc(wowProc, 0x632344);
this.mFallDamage = new MemoryLoc(wowProc, 0x486AAE);
this.mFollowNPC = new MemoryLoc(wowProc, 0x49643d);
this.mWoWTeleport = new MemoryLoc(wowProc, 0x4851E5);
this.mMapHack = new MemoryLoc(wowProc, stat.GetInt32() + 0x28A0);
this.mMapHackResources = new MemoryLoc(wowProc, stat.GetInt32() + 0x28A4);
found = true;
}
i++;
}
}
return found;
}
private void SaveLocationsToFile()
{
if (this.lstSavedLocs.Nodes.Count > 0)
{
SavedLoc[] locs = new SavedLoc[this.lstSavedLocs.Nodes.Count];
int i = 0;
foreach (ExpandedTreeNode node in this.lstSavedLocs.Nodes)
{
locs[i] = (SavedLoc)node.AssociatedObject;
i++;
}
SavedLoc.SaveLocations("saved.xml", locs);
}
}
public void LoadLocationsFromFile()
{
this.lstSavedLocs.Nodes.Clear();
SavedLoc[] locs = SavedLoc.LoadLocations("saved.xml");
foreach(SavedLoc loc in locs)
{
this.AddNewLocation(loc);
}
}
private void RefreshGUIValues()
{
if (this.mX != null & this.mY != null & this.mZ != null)
{
float x = this.mX.GetFloat();
float y = this.mY.GetFloat();
float z = this.mZ.GetFloat();
float s = this.mSpeed.GetFloat();
this.DoMapHack();
this.lblCurX.Text = String.Format("X: {0}", x.ToString());
this.lblCurY.Text = String.Format("Y: {0}", y.ToString());
this.lblCurZ.Text = String.Format("Z: {0}", z.ToString());
this.lblCurSpeed.Text = String.Format("Speed: {0}", s.ToString());
} else {
RefreshPointers();
}
}
private int FlipNum(int num, int min, int max)
{
int diff;
diff = max - num;
return min + diff;
}
public void DoMapHack()
{
byte bitmask = 0;
byte bitmaskresources = 0;
if (Mobius.Options.getHacks()[0] == true)
{
this.mMountainClimb.SetValueInt16(0x9090);
} else {
this.mMountainClimb.SetValueInt16(0x5576);
}
if (Mobius.Options.getHacks()[1] == true)
{
this.mFallDamage.SetValueInt16(0x45EB);
} else {
this.mFallDamage.SetValueInt16(0x4574);
}
if (Mobius.Options.getHacks()[2] == false){
this.mSwimSpeed.SetValue((float)4.72);
}
if (Mobius.Options.getHacks()[3] == true)
{
this.mFollowNPC.SetValueInt16(0x9090);
} else {
this.mFollowNPC.SetValueInt16(0x3374);
}
if (Mobius.Options.getHacks()[4] == true)
{
this.mWoWTeleport.SetValueInt32(0x89909090);
} else {
this.mWoWTeleport.SetValueInt32(0x8908498b);
}
if (Mobius.Options.getHacks()[5] == true) {
bitmask +=1;
}
if (Mobius.Options.getHacks()[6] == true) {
bitmask +=2;
}
if (Mobius.Options.getHacks()[7] == true) {
bitmask +=4;
}
if (Mobius.Options.getHacks()[8] == true) {
bitmask +=8;
}
if (Mobius.Options.getHacks()[9] == true) {
bitmask +=16;
}
if (Mobius.Options.getHacks()[10] == true) {
bitmask +=32;
}
if (Mobius.Options.getHacks()[11] == true) {
bitmask +=64;
}
if (Mobius.Options.getHacks()[12] == true) {
bitmask +=128;
}
if (Mobius.Options.getHacks()[13] == true) {
bitmaskresources +=2;
}
if (Mobius.Options.getHacks()[14] == true) {
bitmaskresources +=4;
}
if (Mobius.Options.getHacks()[15] == true) {
bitmaskresources +=32;
}
this.mMapHack.SetValueInt8(bitmask);
this.mMapHackResources.SetValueInt8(bitmaskresources);
}
#endregion
#region Event Handlers
private void MainForm_Load(object sender, System.EventArgs e)
{
actHook= new UserActivityHook();
actHook.KeyDown+=new KeyEventHandler(MyKeyUp);
actHook.KeyDown+=new KeyEventHandler(MyKeyDown);
if (!this.RefreshPointers()) {
//string msg = "Can't find WoW. Please run WoW and login to your character before using Mobius.";
//string caption = "Error! Can't find WoW";
//MessageBox.Show(msg, caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
//Application.Exit();
}
this.LoadLocationsFromFile();
this.RefreshGUIValues();
this.timRefreshCoords.Enabled = true;
this.update.Enabled = true;
}
UserActivityHook actHook;
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (addedLocations) {
DialogResult result = MessageBox.Show("Would you like to save your locations?", "Save Now?", MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Yes)
{
this.SaveLocationsToFile();
}
else if (result == DialogResult.No)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
}
public void MyKeyDown(object sender, KeyEventArgs e)
{
if(this.txtKey.Focused) this.txtKey.Text = e.KeyData.ToString();
}
private void quickload()
{
if (quicksaved) {
this.mX.SetValue(quicklocx);
this.mY.SetValue(quicklocy);
this.mZ.SetValue(quicklocz);
this.txtStatus.Text = this.txtStatus.Text + "Quickloaded Location\r\n";
}
else this.txtStatus.Text = this.txtStatus.Text + "No Quicksaved Location found!\r\n";
}
private void quicksave() {
SavedLoc loc = new SavedLoc(this.txtLocationName.Text, this.mX.GetFloat(), this.mY.GetFloat(), this.mZ.GetFloat(),this.txtKey.Text);
this.quicklocx = loc.X;
this.quicklocy = loc.Y;
this.quicklocz = loc.Z;
this.txtStatus.Text = this.txtStatus.Text + "Quicksaved Location:\r\n" + "X: " + this.quicklocx + "\r\n" + "Y: " + this.quicklocy + "\r\n" + "Z: " + this.quicklocz + "\r\n";
quicksaved = true;
}
public void MyKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyData.ToString() == "Insert") quicksave();
if (e.KeyData.ToString() == "Delete") quickload();
if (Mobius.Options.getHacks()[16]==true) {
SavedLoc[] locs = SavedLoc.LoadLocations("saved.xml");
foreach(SavedLoc loc in locs)
{
if(e.KeyData.ToString() == loc.Key.ToString())
{
this.mX.SetValue(loc.X);
this.mY.SetValue(loc.Y);
this.mZ.SetValue(loc.Z);
}
}
}
}
private void txtX_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((byte)e.KeyChar == 13)
{
try
{
float x = float.Parse(this.txtX.Text);
this.mX.SetValue(x);
}
catch
{
MessageBox.Show("I dont think WoW will like that 'number'.");
}
}
}
private void txtY_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((byte)e.KeyChar == 13)
{
try
{
float y = float.Parse(this.txtY.Text);
this.mY.SetValue(y);
}
catch
{
MessageBox.Show("I dont think WoW will like that 'number'.");
}
}
}
private void txtZ_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((byte)e.KeyChar == 13)
{
try
{
float z = float.Parse(this.txtZ.Text);
this.mZ.SetValue(z);
}
catch
{
MessageBox.Show("I dont think WoW will like that 'number'.");
}
}
}
private void txtSpeed_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((byte)e.KeyChar == 13)
{
try
{
float s = float.Parse(this.txtSpeed.Text);
this.mSpeed.SetValue(s);
}
catch
{
MessageBox.Show("I dont think WoW will like that 'number'.");
}
}
}
private void lstSavedLocs_DoubleClick(object sender, System.EventArgs e)
{
if (this.lstSavedLocs.SelectedNode is ExpandedTreeNode)
{
ExpandedTreeNode node = (ExpandedTreeNode)this.lstSavedLocs.SelectedNode;
if (this.mX != null & this.mY != null & this.mZ != null & node.AssociatedObject is SavedLoc)
{
SavedLoc loc = (SavedLoc)node.AssociatedObject;
this.mX.SetValue(loc.X);
this.mY.SetValue(loc.Y);
this.mZ.SetValue(loc.Z);
}
}
}
private void btnSave_Click(object sender, System.EventArgs e)
{
this.SaveLocationsToFile();
addedLocations=false;
}
private void btnLoad_Click(object sender, System.EventArgs e)
{
this.LoadLocationsFromFile();
}
private void btnSaveLoc_Click(object sender, System.EventArgs e)
{
if (this.mX != null & this.mY != null & this.mZ != null)
{
addedLocations=true;
SavedLoc loc = new SavedLoc(this.txtLocationName.Text, this.mX.GetFloat(), this.mY.GetFloat(), this.mZ.GetFloat(),this.txtKey.Text);
this.AddNewLocation(loc);
this.txtLocationName.Text = "";
}
}
private void timRefreshCoords_Tick(object sender, System.EventArgs e)
{
this.RefreshGUIValues();
}
private void btnRefreshPointers_Click(object sender, System.EventArgs e)
{
if (!this.RefreshPointers())
{
MessageBox.Show("Reload Failed!");
}
}
#endregion
void UpdateTick(object sender, System.EventArgs e)
{
if (!this.RefreshPointers())
{
if (this.mY!=null) this.txtStatus.Text = this.txtStatus.Text + "Reload failed !\r\n";
}
}
void LstSavedLocsAfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
}
void BtnOptionsClick(object sender, System.EventArgs e)
{
optionsForm.Show();
}
void BtnClearStatusClick(object sender, System.EventArgs e)
{
this.txtStatus.Text = "";
}
void BtnClearHotkeyClick(object sender, System.EventArgs e)
{
txtKey.Clear();
}
private void lblAuthors_Click(object sender, System.EventArgs e)
{
}
private void menuItem2_Click(object sender, System.EventArgs e)
{
SavedLoc.RemoveLoc("saved.xml" , this.lstSavedLocs.SelectedNode.Text);
this.lstSavedLocs.SelectedNode.Remove();
}
private void menuItem1_Click(object sender, System.EventArgs e)
{
if (this.lstSavedLocs.SelectedNode is ExpandedTreeNode)
{
frmLocEdit editForm = new frmLocEdit();
ExpandedTreeNode node = (ExpandedTreeNode)this.lstSavedLocs.SelectedNode;
SavedLoc loc = (SavedLoc)node.AssociatedObject;
editForm.editName = loc.Name;
editForm.editX = loc.X.ToString();
editForm.editY = loc.Y.ToString();
editForm.editZ = loc.Z.ToString();
editForm.ShowDialog();
}
LoadLocationsFromFile();
}
}
}
<file_sep>using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace Mobius
{
/// <summary>
/// Zusammenfassung für Form1.
/// </summary>
public class frmLocEdit : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtX;
private System.Windows.Forms.TextBox txtY;
private System.Windows.Forms.TextBox txtZ;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtName;
private string eX = "null";
private string eY = "null";
private string eZ = "null";
private string eName = "null";
MainForm frmMain = new MainForm();
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.Container components = null;
public frmLocEdit()
{
//
// Erforderlich für die Windows Form-Designerunterstützung
//
InitializeComponent();
//
// TODO: Fügen Sie den Konstruktorcode nach dem Aufruf von InitializeComponent hinzu
//
}
/// <summary>
/// Die verwendeten Ressourcen bereinigen.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.txtName = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.txtZ = new System.Windows.Forms.TextBox();
this.txtY = new System.Windows.Forms.TextBox();
this.txtX = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnSave = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.txtName);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.txtZ);
this.groupBox1.Controls.Add(this.txtY);
this.groupBox1.Controls.Add(this.txtX);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(360, 136);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Location";
//
// txtName
//
this.txtName.Location = new System.Drawing.Point(128, 24);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(216, 20);
this.txtName.TabIndex = 7;
this.txtName.Text = "";
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 24);
this.label4.Name = "label4";
this.label4.TabIndex = 6;
this.label4.Text = "Location :";
//
// txtZ
//
this.txtZ.Location = new System.Drawing.Point(128, 96);
this.txtZ.Name = "txtZ";
this.txtZ.TabIndex = 5;
this.txtZ.Text = "";
//
// txtY
//
this.txtY.Location = new System.Drawing.Point(128, 72);
this.txtY.Name = "txtY";
this.txtY.TabIndex = 4;
this.txtY.Text = "";
//
// txtX
//
this.txtX.Location = new System.Drawing.Point(128, 48);
this.txtX.Name = "txtX";
this.txtX.TabIndex = 3;
this.txtX.Text = "";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 96);
this.label3.Name = "label3";
this.label3.TabIndex = 2;
this.label3.Text = "Z Loc :";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 72);
this.label2.Name = "label2";
this.label2.TabIndex = 1;
this.label2.Text = "Y Loc :";
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 48);
this.label1.Name = "label1";
this.label1.TabIndex = 0;
this.label1.Text = "X Loc :";
//
// btnSave
//
this.btnSave.Location = new System.Drawing.Point(144, 144);
this.btnSave.Name = "btnSave";
this.btnSave.TabIndex = 1;
this.btnSave.Text = "Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// frmLocEdit
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(360, 173);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.groupBox1);
this.Name = "frmLocEdit";
this.Text = "Loc Edit";
this.Closing += new System.ComponentModel.CancelEventHandler(this.frmLocEdit_Closeing);
this.Load += new System.EventHandler(this.frmLocEdit_Load);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public string editName
{
get { return this.eName; }
set { this.eName = value; }
}
public string editX
{
get { return this.eX; }
set { this.eX = value; }
}
public string editY
{
get { return this.eY; }
set { this.eY = value; }
}
public string editZ
{
get { return this.eZ; }
set { this.eZ = value; }
}
private void frmLocEdit_Load(object sender, System.EventArgs e)
{
this.txtName.Text = this.editName;
this.txtX.Text = this.editX;
this.txtY.Text = this.editY;
this.txtZ.Text = this.editZ;
}
private void frmLocEdit_Closeing(object sender, System.ComponentModel.CancelEventArgs e)
{
}
private void btnSave_Click(object sender, System.EventArgs e)
{
SavedLoc.EditMember("saved.xml",this.editName ,this.txtName.Text,this.txtX.Text,this.txtY.Text,this.txtZ.Text);
this.Close();
}
}
}
<file_sep>/*
* Created by SharpDevelop.
* User: alex2308
* Date: 20.03.2005
* Time: 18:15
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Mobius
{
/// <summary>
/// Description of About.
/// </summary>
public class About : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Label lblTxt;
private System.Windows.Forms.Label lblAuthors;
private System.Windows.Forms.Label lblTitle;
public About()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
#region Windows Forms Designer generated code
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent() {
this.lblTitle = new System.Windows.Forms.Label();
this.lblAuthors = new System.Windows.Forms.Label();
this.lblTxt = new System.Windows.Forms.Label();
this.btnOK = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lblTitle
//
this.lblTitle.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblTitle.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblTitle.Location = new System.Drawing.Point(160, 40);
this.lblTitle.Name = "lblTitle";
this.lblTitle.Size = new System.Drawing.Size(108, 24);
this.lblTitle.TabIndex = 1;
this.lblTitle.Text = "Mobius 1.4";
this.lblTitle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lblAuthors
//
this.lblAuthors.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblAuthors.Location = new System.Drawing.Point(108, 76);
this.lblAuthors.Name = "lblAuthors";
this.lblAuthors.Size = new System.Drawing.Size(204, 12);
this.lblAuthors.TabIndex = 3;
this.lblAuthors.Text = "by Devil323 and alex2308";
this.lblAuthors.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lblTxt
//
this.lblTxt.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblTxt.Location = new System.Drawing.Point(12, 108);
this.lblTxt.Name = "lblTxt";
this.lblTxt.Size = new System.Drawing.Size(408, 72);
this.lblTxt.TabIndex = 2;
this.lblTxt.Text = "bla bla bla bla bla bla bla";
this.lblTxt.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.Location = new System.Drawing.Point(116, 240);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(216, 20);
this.btnOK.TabIndex = 0;
this.btnOK.Text = "Yeah, its OK, leave me alone!";
this.btnOK.Click += new System.EventHandler(this.BtnOKClick);
//
// About
//
this.AcceptButton = this.btnOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(432, 265);
this.ControlBox = false;
this.Controls.Add(this.lblAuthors);
this.Controls.Add(this.lblTxt);
this.Controls.Add(this.lblTitle);
this.Controls.Add(this.btnOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "About";
this.Text = "About";
this.ResumeLayout(false);
}
#endregion
void BtnOKClick(object sender, System.EventArgs e)
{
Close();
}
}
}
| ecc53e4b26821e8aaeaa7b57d908189a70509ad4 | [
"C#"
] | 7 | C# | BackupTheBerlios/mobius | bcd11d1e5581bc98e4ef17addab76606617bed2d | e5b0b26165f9f987d0ede849e852ada2ac32120a |
refs/heads/master | <repo_name>devloperrr/Myproject<file_sep>/conversion.php
<?php
$km=1;
$m=($km*1000);
$cm=($km*100000);
$in=($km*39370.08);
$ft=($km*3280.84);
print"Dear user 1km=$m meters and $cm centimeters and $in inches and $ft feets";
?> | e971f85ccc5e4d0fd181ec407102330e02aa6792 | [
"PHP"
] | 1 | PHP | devloperrr/Myproject | fae5bdd727e440147e0b44252c1ebe625bf2ff08 | 534e59f7464a3f19e696a05b6879dca282e7244a |
refs/heads/master | <file_sep>
import pandas as pd
import numpy as np
import traceback
def get_valid_dataframe_single_page(df,bank_name,page_num):
bank_name = bank_name.strip()
rows = df.values.tolist()
#################################### Header Extraction ###################################
headers = []
last_column = []
number_of_columns = []
for row in rows:
last_column.append(row[len(row)-1])
number_of_columns.append(len(row)-1)
number_of_columns = number_of_columns[0]
for i,row in enumerate(rows):
# print("*******",last_column[i])
number_of_columns = len(row)-1
# print("KKKKK",row[len(row)-1])
if str(row[len(row)-1]) == str(last_column[0]) and str(last_column[0]) != 'nan':
headers.append(row)
# print("IIIIIIIIIIII",headers)
if (str(last_column[1]) == 'nan' or last_column[1] is None )and i == 1:
headers.append(row)
# print("^^^^^^")
if i == 3:
break
# print(">>>>>>>",number_of_columns)
new_header = []
if headers:
header_length = len(headers[0])
for i in range(header_length):
if len(headers) == 2:
res2 = str(headers[0][i]) + ' ' + str(headers[1][i])
elif len(headers) == 3:
res2 = str(headers[0][i]) + ' ' + str(headers[1][i]) + ' ' +str(headers[2][i])
elif len(headers) == 1:
res2 = str(headers[0][i])
else:
res2 = ''
res2 = res2.replace("None","").replace('nan','')
new_header.insert(i,res2)
else:
headers = [None] * number_of_columns
# print('new_header',headers)
# print('new_headerrrrrrrrrrrrrrrrrrrrrr',new_header)
balance_key = ['balance(inr)','balance (inr)','balance','balance(in rs.)','balance amount','closing balance','account balance']
for index,item in enumerate(new_header):
for header_item in balance_key:
if header_item == item.lower().strip() or header_item.lower().__contains__(item.lower().strip()):
balance_index = index
################################# Valid Transaction ###########################
# valid_transactions = []
# for row in rows:
# if row not in headers:
# valid_transactions.append(row)
valid_transactions = rows
################################# Bank ########################################
transactions = []
if bank_name == "HDFC BANK":
d_i = 0
p_i = 1
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + ' ' + str(v_t[p_i])
except:
transactions.append(v_t)
# transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
else:
transactions.append(v_t)
# if new_header:
# transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
# print("XXXXXXXXXXXXXX",dfObj)
elif bank_name == "CANARA BANK" or bank_name == "BANK OF WIKI":
# if page_num > 0:
b_i = 6 #index of date column from BANK_DETAILS
p_i = 3 #index of particular(transaction) column from BANK_DETAILS
for v_t in valid_transactions:
# print("** v_t[b_i] **",v_t[b_i])
if v_t[b_i] is None or type(v_t[b_i]) == type(None) or str(v_t[b_i]) == 'nan' or v_t[b_i] == 'nan':
# print("KKK ",v_t[p_i])
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + ' ' + str(v_t[p_i])
except:
transactions.append(v_t)
# transactions[-1][p_i] = str(v_t[p_i])
# print("KKKlll ",transactions[-1][p_i])
# else:
# transactions[-1][p_i] = str(transactions[-1][p_i]) + ' ' + str(v_t[p_i])
else:
# print('++ ',v_t)
transactions.append(v_t)
# if new_header:
# transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
if bank_name == "<NAME> BANK":
if len(new_header) == 5:
d_i = 0
p_i = 1
c_n = 2
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
pass
if v_t[c_n] is not None :
if str(v_t[c_n]) != 'nan':
try:
transactions[-1][c_n] = str(transactions[-1][c_n]) + str(v_t[c_n])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
if len(new_header) == 8:
d_i = 1
p_i = 2
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
return dfObj
if not transactions or bank_name == "Unknown Bank" or dfObj.empty :
print("----------- Unknown Bank -----------")
transactions = []
try:
if balance_index:
b_i = balance_index
index_0 = 0
index_1 = 1
index_2 = 2
index_3 = 3
if header_length >4:
index_4 = 4
if header_length >5:
index_5 = 5
if header_length >6:
index_6 = 6
if header_length >7:
index_7 = 7
for v_t in valid_transactions:
if v_t[b_i] is None or type(v_t[b_i]) == type(None) or str(v_t[b_i]) == 'nan':
if v_t[index_0] is not None :
if str(v_t[index_0]) != 'nan':
try:
transactions[-1][index_0] = str(transactions[-1][index_0]) + str(v_t[index_0])
transactions[-1][index_0] = transactions[-1][index_0].replace('None','').replace('nan','')
except:
pass
if v_t[index_1] is not None :
if str(v_t[index_1]) != 'nan':
try:
transactions[-1][index_1] = str(transactions[-1][index_1]) + str(v_t[index_1])
transactions[-1][index_1] = transactions[-1][index_1].replace('None','').replace('nan','')
except:
pass
if v_t[index_2] is not None :
if str(v_t[index_2]) != 'nan':
try:
transactions[-1][index_2] = str(transactions[-1][index_2]) + str(v_t[index_2])
transactions[-1][index_2] = transactions[-1][index_2].replace('None','').replace('nan','')
except:
pass
if v_t[index_3] is not None :
if str(v_t[index_3]) != 'nan':
try:
transactions[-1][index_3] = str(transactions[-1][index_3]) + str(v_t[index_3])
transactions[-1][index_3] = transactions[-1][index_3].replace('None','').replace('nan','')
except:
pass
if header_length >4:
if v_t[index_4] is not None :
if str(v_t[index_4]) != 'nan':
try:
transactions[-1][index_4] = str(transactions[-1][index_4]) + str(v_t[index_4])
transactions[-1][index_4] = transactions[-1][index_4].replace('None','').replace('nan','')
except:
pass
if header_length >5:
if v_t[index_5] is not None :
if str(v_t[index_5]) != 'nan':
try:
transactions[-1][index_5] = str(transactions[-1][index_5]) + str(v_t[index_5])
transactions[-1][index_5] = transactions[-1][index_5].replace('None','').replace('nan','')
except:
pass
if header_length >6:
if v_t[index_6] is not None :
if str(v_t[index_6]) != 'nan':
try:
transactions[-1][index_6] = str(transactions[-1][index_6]) + str(v_t[index_6])
transactions[-1][index_6] = transactions[-1][index_6].replace('None','').replace('nan','')
except:
pass
if header_length >7:
if v_t[index_7] is not None :
if str(v_t[index_7]) != 'nan':
try:
transactions[-1][index_7] = str(transactions[-1][index_7]) + str(v_t[index_7])
transactions[-1][index_7] = transactions[-1][index_7].replace('None','').replace('nan','')
except:
pass
else:
transactions.append(v_t)
except:
print(traceback.print_exc())
d_i = 0
p_i = 2
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
return dfObj<file_sep>import os
import pandas as pd
import re
import csv
import traceback
import datetime
def date_formatting(csv_file):
df = pd.read_csv(csv_file)
for index, row in df.iterrows():
x = row['Txn Date']
x = x.replace("\n","").replace(" ","")
x = re.sub(r'([A-Za-z])(\d{1,2})', r'\1 \2', x)
x = re.sub(r'(\d{1,2})([A-Za-z])', r'\1 \2', x)
row['Txn Date'] = x
for index, row in df.iterrows():
x = row['Value Date']
x = x.replace("\n","").replace(" ","")
x = re.sub(r'([A-Za-z])(\d{1,2})', r'\1 \2', x)
x = re.sub(r'(\d{1,2})([A-Za-z])', r'\1 \2', x)
row['Value Date'] = x
return df
def get_monthly_balance_sheet(df,month):
new_ind = []
for index, row in df.iterrows():
row_value = row['Txn Date']
if row_value.__contains__(month):
x = row_value
# print(index)
# print(row_value)
new_ind.append(index)
y = df.loc[new_ind]
# print(y)
return y
def monthly_average_balance(dataframe,month):
total_balance = 0
# print(dataframe)
if month not in {'Apr','Jun','Sep','Nov'}:
number_of_days = 31
else:
number_of_days = 30
for index, row in dataframe.iterrows():
balance = row['Balance']
balance = balance.replace(",","")
total_balance = float(balance) + total_balance
monthly_average = total_balance/number_of_days
# print('Average Monthly Balance for {} is :'.format(month),monthly_average)
return monthly_average
def opening_closing_balance(df,month):
for index, row in df.iterrows():
balance = row['Balance']
balance = balance.replace(",","")
opening_balance = balance
break
for index, row in df.iterrows():
balance = row['Balance']
balance = balance.replace(",","")
closing_balance = balance
return opening_balance,closing_balance
def get_monthly_avg_balance(csv_file):
df = date_formatting(csv_file)
month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
try:
for item in month:
dataframe = get_monthly_balance_sheet(df,item)
if not dataframe.empty:
monthly_average = monthly_average_balance(dataframe,item)
opening_balance,closing_balance = opening_closing_balance(dataframe,item)
print("\nOpening Balance for {} month is ".format(item),opening_balance)
print("Closing Balance for {} month is ".format(item),closing_balance)
print('Average Monthly Balance for {} is :'.format(item),monthly_average,"\n")
except:
pass
def guess_date(string):
for fmt in ["%Y/%m/%d", "%d-%m-%Y", "%Y%m%d",'%d/%m/%Y']:
try:
return datetime.datetime.strptime(string, fmt).date()
except ValueError:
continue
raise ValueError(string)
def get_monthly_avg_bal(file_path,bank_name):
try:
statement = pd.read_excel(file_path,sheet_name='transaction_data')
except:
file_path = os.getcwd() + file_path
statement = pd.read_excel(file_path,sheet_name='transaction_data')
# print(statement)
list_of_date = statement['Date'].to_list()
list_of_balance = statement['Balance'].to_list()
# print(list_of_date)
# print(list_of_balance)
new_list_of_date = []
new_list_of_balance = []
for i,date in enumerate(list_of_date):
date = str(date).strip()
if new_list_of_date:
if str(new_list_of_date[-1]) == date:
new_list_of_date[-1] = date
new_list_of_balance[-1] = list_of_balance[i]
else:
new_list_of_date.append(date)
new_list_of_balance.append(list_of_balance[i])
elif i == 0:
new_list_of_date.append(date)
new_list_of_balance.append(list_of_balance[i])
df = pd.DataFrame({'Date':new_list_of_date,'Balance':new_list_of_balance})
# print(df)
# df['month'] = pd.DatetimeIndex(df['Date']).date
# df['month_year'] = pd.to_datetime(df['Date']).dt.to_period('D')
# print(df)
df = pd.DataFrame()
return df
if __name__ == "__main__":
file_path = '/home/rahul/Downloads/1_19.xlsx'
bank_name = 'HDFC BANK'
get_monthly_avg_bal(file_path,bank_name)
string = '11/03/20'
# d = guess_date(string)
# print("::::::::: ",d)
samples = "2017/5/23", "22-04-2015", "20150504",'10/03/20'
for sample in samples:
print(guess_date(sample))<file_sep>$(document).ready(function() {
sessionStorage.removeItem('table_coords');
sessionStorage.removeItem('table_data');
// $(document).ajaxStart(function () {
// $("#wait2").css("display", "block");
// });
// $(document).ajaxComplete(function () {
// $("#wait2").css("display", "none");
// });
$('.imagePlaceholer').hide();
const url_string = window.location.href;
const url = new URL(url_string);
const job_id = url.searchParams.get('job_id');
console.log(job_id);
$('#upload_documents').attr('href', 'dashboard.html?job_id='+job_id);
$('#localization').attr('href', 'localization.html?job_id='+job_id);
$('#digitization').attr('href', 'table_digitization.html?job_id='+job_id);
$('#download').attr('href', 'download_data.html?job_id='+job_id);
$('#calcutions').attr('href', 'calculations.html?job_id='+job_id);
const token = localStorage.getItem('token');
const data_attrs = {
'token': token,
'job_id': job_id,
};
doc_attributes(data_attrs);
$('#wait3').css('display', 'block');
// const success2 = {
// 'url': 'https://credit.in-d.ai/hdfc_life/credit/pdf_password_localization_status',
// 'headers': {
// 'content-type': 'application/json',
// },
// 'method': 'POST',
// 'processData': false,
// 'data': JSON.stringify(data_attrs),
// };
// $('#showPopup').hide();
// $.ajax(success2).done(function(data, textStatus, xhr) {
// console.log('xhr, textStatus', data, textStatus, xhr, xhr.status);
// $('#wait3').css('display', 'none');
// if (xhr.status === 200) {
// // sessionStorage.setItem('file_path', data.file_path);
// // console.log('check password done', data.result);
// doc_attributes(data_attrs);
// // alert("DOne")
// } else if (xhr.status === 201) {
// alert(data.message);
// } else {
// }
// }).fail(function(data) {
// alert(data);
// console.log('check password error', data);
// });
});
// if ("localization_data" in sessionStorage) {
// data = sessionStorage.getItem("localization_data");
// // console.log("data", data);
// data = JSON.parse(data);
// doc_attributes_function(data);
// } else {
// // alert("No");
// sessionStorage.removeItem("file_path");
// var data_attrs = {
// "token": token,
// "password": <PASSWORD>,
// };
// var success2 = {
// "url": "check_password",
// "headers": {
// "content-type": "application/json"
// },
// "method": "POST",
// "processData": false,
// "data": JSON.stringify(data_attrs)
// }
// $("#showPopup").hide();
// $.ajax(success2).done(function (data) {
// sessionStorage.setItem("file_path", data.file_path);
// console.log("check password done", data.result)
// if (data.result === true) {
// doc_attributes(data);
// } else {
// $('#myModal').modal('show');
// $("#showPopup").show();
// }
// }).fail(function (data) {
// console.log("check password error", data)
// });
// };
// $('#getpasswordBtn').click(function () {
// $('#popupMessage').show();
// setTimeout(function () {
// $('#myModal').modal('hide');
// $('.modal-backdrop').hide();
// }, 1500);
// let data = {
// 'file_path': sessionStorage.getItem('file_path'),
// 'doc_type': sessionStorage.getItem('doc_type'),
// 'bank_name': sessionStorage.getItem('bank_name'),
// 'readable_status': sessionStorage.getItem('readable_status'),
// };
// // doc_attributes(data);
// eslint-disable-next-line require-jsdoc
function doc_attributes(data_attrs) {
// const data_attrs = {
// 'token': token,
// // "password": <PASSWORD>,
// 'file_path': sessionStorage.getItem('file_path'),
// 'doc_type': sessionStorage.getItem('doc_type'),
// 'bank_name': sessionStorage.getItem('bank_name'),
// 'readable_status': sessionStorage.getItem('readable_status'),
// };
$('#wait3').css('display', 'block');
console.log('doc_attributes', JSON.stringify(data_attrs));
const success = {
'url': 'https://credit.in-d.ai/hdfc_life/credit/table_localization',
'headers': {
'content-type': 'application/json',
},
'method': 'POST',
'processData': false,
'data': JSON.stringify(data_attrs),
};
$.ajax(success).done(function(data, textStatus, xhr) {
// alert("HI")
if (xhr.status === 200) {
sessionStorage.setItem('localization_data', JSON.stringify(data));
doc_attributes_function(data);
} else if (xhr.status === 201) {
alert(data.message);
} else {
}
}).fail(function(data) {
console.log('data', data);
$('.imagePlaceholer').show();
if (data.responseJSON.message == 'Not successful!') {
};
if (data.responseJSON.message == 'Token is invalid!') {
$('#error').show();
$('#error').text('Session expired, It will redirect to login page.', data.responseJSON.message);
setTimeout(function() {
window.location.assign('index.html');
}, 2000);
localStorage.removeItem('token');
sessionStorage.clear();
};
});
};
function doc_attributes_function(data) {
$('#wait2').css('display', 'none');
$('#wait3').css('display', 'none');
$('.imagePlaceholer').show();
console.log('data', data);
const imageHeight = data['height'] + 5;
const imagewidth = data['width'];
const readable_status = data['readable_status'];
const reduced_percentage = data['reduced_percentage'];
data = data['response'];
const No_Quotes_string = eval(data);
console.log('No_Quotes_string', No_Quotes_string);
console.log('bank name', No_Quotes_string[0].bank_name);
sessionStorage.setItem('bank_name', No_Quotes_string[0].bank_name);
sessionStorage.setItem('readable_status', readable_status);
sessionStorage.setItem('reduced_percentage', reduced_percentage);
const counter11 = 1;
$.each(No_Quotes_string, function(obj, key, i) {
console.log('key.table_data.top', key.table_data[0].top);
const section = $('<div class=\'items' + obj + '\' style=\'position:relative; margin:50px 0px; border-bottom:2px solid #ccc; height:' + imageHeight + 'px;width:' + imagewidth + 'px\' />');
$(section).append('<div class=\'images\'> <img src=\'https://credit.in-d.ai/hdfc_life/' + key.corrected_imageName + '\' /> <input name=\'item' + obj + '.bankname\' value=\'' + key.bank_name + ' \' /> <input name=\'item' + obj + '.documentType\' value=\'' + key.documentType + '\' /> <input name=\'item' + obj + '.corrected_imageName\' value=\'' + key.corrected_imageName + ' \' /> </div>');
const table = $('<div class=\'table\'/>');
$.each(key.table_data, function(rowIndex, key, object, value) {
console.log('rowIndex + key', rowIndex);
if (rowIndex == 0) {
var row = $('<div class=\'DemoOuter' + obj + ' demo\' style=\'left:' + key.left + 'px;top:' + key.top + 'px;width:' + key.width + 'px;height:' + key.height + 'px' + ' \'> <input class=\'height\' id=\'height\' name=\'item' + obj + '.table_data' + obj + '.height\' value=\'' + key.height + ' \' /> <input class=\'width\' id=\'width\' name=\'item' + obj + '.table_data' + obj + '.width\' value=\'' + key.width + ' \' /> <input class=\'left\' id=\'left\' name=\'item' + obj + '.table_data' + obj + '.left\' value=\'' + key.left + ' \' /> <input class=\'top\' id=\'top\' name=\'item' + obj + '.table_data' + obj + '.top\' value=\'' + key.top + ' \' /> </div>');
$(function() {
$('.DemoOuter' + obj + '')
.draggable({
containment: $('.items' + obj + ''),
drag: function(event) {
o = $(this).offset();
p = $(this).position();
$(this).children('.left').val(p.left);
$(this).children('.top').val(p.top);
},
})
.resizable({
resize: function(event, ui) {
$(this).children('.height').val($(this).outerHeight());
$(this).children('.width').val($(this).outerWidth());
console.log('11111111', ($(this).outerWidth()));
console.log('11111111', ($(this).outerHeight()));
},
});
});
} else {
};
$.each(key.colItem, function(key, object, value, i) {
row.append($('<div class=\'DemoInner demo\' style=\'left:' + object.left + 'px;top:' + object.top + 'px;width:' + object.width + 'px;height:' + object.height + 'px' + ' \'> <input class=\'height\' id=\'height\' name=\'item' + obj + '.table_data' + obj + '.colItem' + key + '.height\' value=\'' + object.height + ' \' /> <input class=\'width\' id=\'width\' name=\'item' + obj + '.table_data' + obj + '.colItem' + key + '.width\' value=\'' + object.width + ' \' /> <input class=\'left\' id=\'left\' name=\'item' + obj + '.table_data' + obj + '.colItem' + key + '.left\' value=\'' + object.left + ' \' /> <input class=\'top\' id=\'top\' name=\'item' + obj + '.table_data' + obj + '.colItem' + key + '.top\' value=\'' + object.top + ' \' /> <div class=\'remove\'>Remove</div></div>'));
$(function() {
$('.DemoInner')
.draggable({
containment: $('.DemoOuter0'),
drag: function(event) {
o = $(this).offset();
p = $(this).position();
$(this).children('.left').val(p.left);
$(this).children('.top').val(p.top);
},
})
.resizable({
handles: 's',
resize: function(event, ui) {
$(this).children('.height').val($(this).outerHeight());
$(this).children('.width').val($(this).outerWidth());
},
});
});
});
table.append(row);
});
// tableDiv.append(table);
if (obj == 0) {
const buttontop = key.table_data[0].top - 100;
console.log('key.table_data.top', buttontop);
section.append('<div class=\'add btn btn-warning\' style=\'position:absolute; top:' + buttontop + 'px;\'>Add Column</div> <div style=\'display:none\' id=\'theCount\'></div>');
}
section.append(table);
section.append('<div class=\'clearfix\'/>');
$('#localization_multicol').append(section);
});
let counter = 100;
$('.add').click(function() {
counter++;
$('#theCount').text(counter);
const counterNew = $('#theCount').text();
console.log('added log', counterNew);
$('.items0 .demo:last').after('<div class=\'DemoAdded demo\' style=\'left:50%; top:0px; width:5px; height:100%;\'> <input class=\'height\' id=\'height\' name=\'item0.table_data0.colItem' + counterNew + '.height\' value=\'100%\' /> <input class=\'width\' id=\'width\' name=\'item0.table_data0.colItem' + counterNew + '.width\' value=\'5px\' /> <input class=\'left\' id=\'left\' name=\'item0.table_data0.colItem' + counterNew + '.left\' value=\'100\' /> <input class=\'top\' id=\'top\' name=\'item0.table_data0.colItem' + counterNew + '.top\' value=\'0px\' /> <div class=\'remove icon\'>Remove</div></div>');
$('.DemoAdded')
.draggable({
containment: $('.DemoOuter0'),
drag: function(event) {
o = $(this).offset();
p = $(this).position();
$(this).children('.left').val(p.left);
$(this).children('.top').val(p.top);
},
})
.resizable({
handles: 's',
resize: function(event, ui) {
$(this).children('.height').val($(this).outerHeight());
$(this).children('.width').val($(this).outerWidth());
},
});
$('.remove').click(function() {
$(this).parent().remove();
});
});
$('.remove').click(function() {
$(this).parent().remove();
});
}
$('#wait5').hide();
$('#BtnUpdateLocalizations').click(function() {
$('#wait5').show();
const url_string = window.location.href;
const url = new URL(url_string);
const job_id = url.searchParams.get('job_id');
console.log(job_id);
const obj = $('#updateLocalizations').serializeToJSON({
parseFloat: {
condition: '.number,.money',
},
useIntKeysAsArrayIndex: true,
});
console.log(obj);
const jsonString = obj;
console.log(jsonString);
sessionStorage.setItem('table_coords', JSON.stringify(jsonString));
$('#result').val(jsonString);
setTimeout(function() {
window.location.href = 'table_digitization.html?job_id='+job_id;
}, 3000);
});
// });
<file_sep>import os
import re
import time
from PIL import Image
import shutil
import traceback
import pikepdf
from .function_library import decrypt_pdf
# from .document_type import get_document_type
from pdf2image import convert_from_path
from .tabula_pdf import get_table_data
from .BST_Testing import get_table_coordinate,get_tabular_data
import pdftotext
import pandas as pd
from PyPDF2 import PdfFileMerger
def get_readable_status(file_name) :
with open(file_name, "rb") as f:
pdf = pdftotext.PDF(f)
# Iterate over all the pages
for page in pdf:
# print(page)
text = page
break
if text and len(text) > 40:
# print('PDF file is readable')
return 'readable'
else:
# print("PDF file is non-readable")
return 'non-readable'
###########################################################################################
# def get_first_page(file_path):
# try:
# if file_path.endswith('.pdf') or file_path.endswith('.PDF'):
# pages = convert_from_path(file_path,250,first_page=1, last_page=1)
# for page in pages:
# page.save("%s-page100.jpg" % (file_path[:-4]), "JPEG")
# return True,file_path
# else:
# return True,file_path
# except:
# print(traceback.print_exc())
# return False,file_path
###########################################################################################
def check_password_new(file_path):
try:
if file_path.endswith('.pdf') or file_path.endswith('.PDF'):
pages = convert_from_path(file_path,250,first_page=1, last_page=1)
for page in pages:
page.save("%s-page100.jpg" % (file_path[:-4]), "JPEG")
return True,file_path
else:
return True,file_path
except:
print(traceback.print_exc())
return False,file_path
################################################################
def get_password_status(password,file_path):
xxxx = file_path
output_directory = file_path.split('/')[:-1]
output_directory = "/".join(output_directory)
print('output_directory ',output_directory)
file_path = os.path.join(output_directory,file_path)
out_path = file_path.split(".")[0]+"_decrypt.pdf"
try:
decrypt_pdf(file_path,out_path,password)
os.remove(file_path)
shutil.copyfile(out_path, xxxx)
pages = convert_from_path(file_path,250,first_page=1, last_page=1)
for page in pages:
page.save("%s-page100.jpg" % (file_path[:-4]), "JPEG")
break
return True
except:
print(traceback.print_exc())
return False
########################################################################################
def get_file_name(file_list,folder_path):
# merger = PdfFileMerger()
# for pdf in file_list:
# print(">>>>$$$$$$$$$$$",pdf)
# file_name = os.path.join(folder_path,pdf)
# merger.append(file_name)
# file_path = os.path.join(folder_path,'merge_pdf.pdf')
# merger.write(file_path)
# merger.close()
# return file_path
pdf = pikepdf.Pdf.new()
# pdfs = ['bank_statement.pdf','bank_statement_new.pdf']
# pdfs = ['1100064792153.pdf', '1100064792153-1.pdf']
for file in file_list:
print(">>>>$$$$$$$$$$$",pdf)
file_name = os.path.join(folder_path,file)
src = pikepdf.Pdf.open(file_name)
pdf.pages.extend(src.pages)
file_path = os.path.join(folder_path,'merge_pdf.pdf')
pdf.save(file_path)
return file_path
##########################################################################################
def table_coordinate(documentType,bank_name,image_name,preprocess_list,page_index,number_of_pages):
try:
# print("++++++++++++ preprocess_list ++++++++++++",page_index,preprocess_list)
if page_index == 0 or (page_index ==1 and not preprocess_list):
outputDir = os.getcwd()
start_time = time.time()
left, top, width, height,columns_list = get_table_coordinate(image_name,page_index,preprocess_list)
print("****** TABLE DETECTION TIME COMPLEXITY for page {} is {} *******".format(page_index,time.time()-start_time))
income_preprocess_result = {}
income_preprocess_result["left"] = left
income_preprocess_result["top"] = top
income_preprocess_result["width"] = width
income_preprocess_result["height"] = height
income_preprocess_result["documentType"] = documentType
income_preprocess_result["bank_name"] = bank_name
corrected_imageName = image_name.split('/')[-5:]
corrected_imageName = "/".join(corrected_imageName)
income_preprocess_result["corrected_imageName"] = corrected_imageName
if not width:
columns_list = []
return preprocess_list, columns_list
preprocess_list.append(income_preprocess_result.copy())
return preprocess_list,columns_list
elif 1 < page_index < number_of_pages-1 :
first_image_value = preprocess_list[-1]
for key, value in first_image_value.items():
if key=='left':
inputleft = value
if key == 'top':
inputtop = value
if key == 'width':
inputwidth = value
if key == 'height':
inputheight = value
if key == 'documentType':
documentType = value
if key =='bank_name':
bank_name = value
new_income_preprocess_list = {}
new_income_preprocess_list["left"] = inputleft
new_income_preprocess_list["top"] = inputtop
new_income_preprocess_list["width"] = inputwidth
new_income_preprocess_list["height"] = inputheight
new_income_preprocess_list["documentType"] = 'Bank Statement'
new_income_preprocess_list["bank_name"] = bank_name
new_image_name = image_name.split('/')[-5:]
new_image_name = "/".join(new_image_name)
new_income_preprocess_list["corrected_imageName"] = new_image_name
if not inputwidth:
columns_list = []
return preprocess_list,columns_list
preprocess_list.append(new_income_preprocess_list.copy())
columns_list = []
return preprocess_list,columns_list
outputDir = os.getcwd()
start_time = time.time()
###################### Table Detection ########################
# corrected_imageName, (left, top, width, height) = get_borderdTable(image_name, outputDir)
columns_list = []
left, top, width, height,columns_list = get_table_coordinate(image_name,page_index,preprocess_list)
print("****** TABLE DETECTION TIME COMPLEXITY for page {} is {} *******".format(page_index,time.time()-start_time))
income_preprocess_result = {}
income_preprocess_result["left"] = left
income_preprocess_result["top"] = top
income_preprocess_result["width"] = width
income_preprocess_result["height"] = height
income_preprocess_result["documentType"] = documentType
income_preprocess_result["bank_name"] = bank_name
corrected_imageName = image_name.split('/')[-5:]
corrected_imageName = "/".join(corrected_imageName)
income_preprocess_result["corrected_imageName"] = corrected_imageName
if not width:
return preprocess_list,columns_list
preprocess_list.append(income_preprocess_result.copy())
return preprocess_list,columns_list
except:
print(traceback.print_exc())
preprocess_list = []
columns_list = []
return preprocess_list,columns_list
###########################################################################################
def get_bank_statement(file_path,doc_type,bank_name,readable_status):
preprocess_list = []
if file_path.endswith('.pdf') or file_path.endswith('.PDF'):
if readable_status == 'readable':
print('++++++++++++++ PDF file is readable +++++++++++++++++++')
try:
pages = convert_from_path(file_path,200)
except:
pages = convert_from_path(file_path,100)
file_path = file_path[:-4]
for page in pages:
page.save("%s-page%d.jpg" % (file_path,pages.index(page)), "JPEG")
print("+++++ Number of Pages in file : {} +++++".format(len(pages)))
number_of_pages = len(pages)
for i in range(0,number_of_pages):
image_path = file_path + '-page'+ str(i) +'.jpg'
img = Image.open(image_path)
width, height = img.size
# print("+++++++width, height +++++",width, height)
if width>1800:
basewidth = 1800
img = Image.open(image_path)
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
reduced_percentage = int(width)/1800
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save(image_path)
img = Image.open(image_path)
width, height = img.size
else:
reduced_percentage = 1
outer_table_coordinate_list,columns_list = table_coordinate(doc_type,bank_name,image_path,preprocess_list,i,number_of_pages)
# print('*************',outer_table_coordinate_list,columns_list)
if i == 0 or (i ==1 and columns_list):
final_column_list = []
final_column_list.append(columns_list)
reduced_percentage = 200/(72*reduced_percentage)
# print("outer_table_coordinate_list,width,height,reduced_percentage,final_column_list[0]\n",outer_table_coordinate_list,width,height,readable_status,reduced_percentage,final_column_list[0])
return outer_table_coordinate_list,width,height,reduced_percentage,final_column_list[0]
else:
print('+++++++++++++++++ PDF file is non-readable++++++++++++++++')
# pages = convert_from_path(file_path,250)
try:
pages = convert_from_path(file_path,200)
except:
pages = convert_from_path(file_path,100)
file_path = file_path[:-4]
for page in pages:
page.save("%s-page%d.jpg" % (file_path,pages.index(page)), "JPEG")
print("Number of Pages in file : ",len(pages))
number_of_pages = len(pages)
for i in range(0,number_of_pages):
image_path = file_path + '-page'+ str(i) +'.jpg'
img = Image.open(image_path)
width, height = img.size
if width>1800:
basewidth = 1800
img = Image.open(image_path)
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save(image_path)
outer_table_coordinate_list,columns_list = table_coordinate(doc_type,bank_name,image_path,preprocess_list,i,number_of_pages)
if i == 0:
final_column_list = []
final_column_list.append(columns_list)
return outer_table_coordinate_list,width,height,1,final_column_list[0]
else:
print('+++++++++++++++++ Image is non-readable +++++++++++++++++++')
# doc_type,bank_name = get_document_type(file_path)
img = Image.open(file_path)
width, height = img.size
# if width>5800:
# basewidth = 1800
# img = Image.open(file_path)
# wpercent = (basewidth / float(img.size[0]))
# hsize = int((float(img.size[1]) * float(wpercent)))
# img = img.resize((basewidth, hsize), Image.ANTIALIAS)
# img.save(file_path)
out,columns_list = table_coordinate(doc_type,bank_name,file_path,preprocess_list,0,1)
# readable_status = 'non-readable'
reduced_percentage = 1
return out,width,height,reduced_percentage,columns_list
###############################################################################################
def extraction_column(data):
outputDir = os.getcwd()
first_image_value = data[0]
for key, value in first_image_value.items():
if key=='left':
inputleft = value
if key == 'top':
inputtop = value
if key == 'width':
inputwidth = value
if key == 'height':
inputheight = value
if key == 'documentType':
documentType = value
# if key =='bank_name':
# bank_name = value
if key =='corrected_imageName':
income_document_image = value
income_document_image= income_document_image.strip()
final_df, columns_list = giveimage1(income_document_image, outputDir, documentType, inputleft, inputtop, inputwidth, inputheight)
return columns_list
def get_columns_distance_values(columns):
columns_distance_values = []
for column_data in columns:
for key2,value2 in column_data.items():
if key2 == 'left':
column_left = value2
distance_value = float(column_left)
columns_distance_values.append(distance_value)
return columns_distance_values
def get_columns_coordinates(columns,columns_distance_values,inputleft,inputtop,inputwidth,inputheight):
columns_distance_values.insert(0,0)
columns_distance_values = sorted(columns_distance_values)
final_column_coordinates = []
inputtop = int(float(inputtop))
for index,column_left in enumerate(columns_distance_values):
columns_coordinates = []
columns_coordinates.append(int(column_left))
if index == len(columns_distance_values)-1:
width = inputwidth
else:
width = columns_distance_values[index+1]
columns_coordinates.append(int(float(width)))
columns_coordinates.append(int(inputtop))
columns_coordinates.append(int(float(inputheight))+int(float(inputtop)))
final_column_coordinates.append(columns_coordinates)
# print("final_column_coordinates",final_column_coordinates)
return final_column_coordinates
def extraction_data(data,readable_status,reduced_percentage,pdf_file_path):
# print("::::::::::::::::::LLLLLLLLLLLLLLLL\n",data)
count = 0
final_output = []
# outputDir = os.getcwd()
columns_distance = data[0]
for key, value in columns_distance.items():
if key == 'table_data':
for item1 in value:
for key1,value1 in item1.items():
if key1 == 'colItem':
columns = value1
input_pdf = []
for item in data:
for key, value in item.items():
# if key == 'documentType':
# documentType = value
if key == 'bank_name':
bank_name = value
if key == 'corrected_imageName':
income_document_image = value
income_document_image= income_document_image.strip()
if key == 'table_data':
for item1 in value:
for key3,value3 in item1.items():
if key3 == 'left':
inputleft = value3
if key3 == 'top':
inputtop = value3
if key3 == 'height':
inputheight = value3
if key3 == 'width':
inputwidth = value3
columns_distance_values = get_columns_distance_values(columns)
# print(">>>>>>>>",income_document_image, inputleft, inputtop, inputwidth, inputheight, documentType, bank_name,columns_distance_values)
if readable_status == 'readable':
final_df = get_table_data(input_pdf,income_document_image, inputleft, inputtop, inputwidth, inputheight, bank_name,columns_distance_values,reduced_percentage,pdf_file_path)
else:
# print("+++++++++++++",columns,columns_distance_values,inputleft,inputtop,inputwidth,inputheight)
columns_coordinates = get_columns_coordinates(columns,columns_distance_values,inputleft,inputtop,inputwidth,inputheight)
# final_df = giveimage(income_document_image, outputDir, documentType, inputleft, inputtop, inputwidth, inputheight,columns_distance_values)
table_cords = (int(float(inputleft)),int(float(inputwidth)), int(float(inputtop)), int(float(inputheight))+int(float(inputtop)))
table_cords = list(table_cords)
income_document_image = os.getcwd() + '/webserverflask/'+ income_document_image
# print("+++++++++++++++++++",income_document_image,table_cords,columns_coordinates)
final_df = get_tabular_data(income_document_image,table_cords,columns_coordinates)
income_document_image = income_document_image.split('hdfc_credit/webserverflask')[-1]
# final_df = pd.DataFrame()
# print("this is the final purpose++++++++++++++++++\n", final_df)
excel_data = final_df.to_json(orient='index')
result = {}
result["image_path"] = income_document_image
result["page_num"] = count
result["excel_data"] = excel_data
count = count +1
final_output.append(result)
return final_output
<file_sep>import config.config as config
# import config.config as project_configs
from datetime import datetime
from datetime import timedelta
from pymongo import MongoClient
import traceback
import xlwt
import os
import datetime
import json
import pandas as pd
import pprint
from pytz import timezone
import re
# import admin_dbV8
mongo_db_client = None
fixed_secret_key = 'IntainAI@123'
uri = "mongodb://{}:{}/{}".format(config.DATABASE_CONFIG['db_vm'],config.DATABASE_CONFIG['db_port'],config.DATABASE_CONFIG['db_name'])
mongo_db_client = MongoClient(uri)
db = mongo_db_client[config.DATABASE_CONFIG['db_name']]
###############################################################################################
def userDashboardDetail(request_email):
#pprint.pprint(request_data)
job_collection = db['payslip_job']
job_response = job_collection.find(
{
'emailid': request_email
}, {
'emailid': 0,
'_id': 0,
})
if job_response:
api_response = []
for row in job_response:
if row['job_status'] == 'NULL':
row['job_status'] = 'In Process'
elif row['admin_submitted']:
row['job_status'] = 'Validated by Admin'
elif row['batch_submitted_status']:
row['job_status'] = 'Submitted to Admin'
api_response.append(row)
mongo_db_client.close()
return api_response
else:
mongo_db_client.close()
return -2
###############################################################################################
def delete_null_job(request_email):
collection = db['payslip_job']
collection.delete_many(
{
'emailid': request_email,
'job_status': 'NULL'
})
mongo_db_client.close()
###############################################################################################
def get_jobid(request_email):
try:
collection = db['payslip_job']
response = collection.count()
mongo_db_client.close()
return response
except Exception as e:
print(traceback.print_exc())
return -2
###############################################################################################
def get_batch_name(job_id):
try:
print(job_id)
collection = db['payslip_job']
response = collection.find_one({
"document_name": job_id
}, {
'_id': 0,
'emailid': 0,
'job_id': 0
})
print(response)
if response:
print("batchhhh name")
print(response['batch_name'])
return response['batch_name']
mongo_db_client.close()
except Exception as e:
print(traceback.print_exc())
return -2
################################################################################################
def insert_job(request_data):
try:
collection = db['payslip_job']
collection.insert_one(request_data)
mongo_db_client.close()
return 0
except Exception as e:
print(traceback.print_exc())
return -2
###############################################################################################
def digitise_document(request_email, request_data):
try:
list_folders = []
job_collection = db['payslip_job']
result_collection = db['payslip_result']
print(request_data)
response = result_collection.find_one({
'emailid': request_email,
"job_id": request_data['job_id']
}, {
'_id': 0,
'emailid': 0,
'job_id': 0
})
print("job_digitised response",response)
if response:
print("Job already digitised")
return -2
rows = request_data
if rows["batch_name"] == "":
batch_name = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
else:
batch_name = rows["batch_name"]
job_collection.update_one(
{
'emailid': request_email,
"document_name": rows["document_name"],
"job_id": rows["job_id"]
}, {
"$set": {
'batch_name': batch_name,
'batch_submitted_status': False
}
})
if rows['job_priority'] == "High":
list_folders.append(rows["job_id"])
if rows['job_priority'] == "Medium":
list_folders.append(rows["job_id"])
if rows['job_priority'] == "Auto":
list_folders.append(rows["job_id"])
if rows['job_priority'] == "Low":
list_folders.append(rows["job_id"])
mongo_db_client.close()
new_list_folders = []
for folders in list_folders:
if folders not in new_list_folders:
new_list_folders.append(folders)
return new_list_folders
except Exception as e:
print(traceback.print_exc())
return -2
###############################################################################################
def download_result(request_email, request_jobid):
collection = db['payslip_job']
response = collection.find_one(
{
'emailid': request_email,
'job_id': request_jobid
}, {
'emailid': 0,
'_id': 0,
})
if response:
# pprint.pprint(response)
mongo_db_client.close()
return response['excel_path']
else:
mongo_db_client.close()
return -2
def batch_submit(request_email, job_id):
collection = db['payslip_job']
job_id = job_id.replace("Job_", "")
response = collection.find_one({
'emailid': request_email,
"job_id": job_id,
'batch_submitted_status': False
}, {
'_id': 0,
'emailid': 0,
'job_id': 0
})
if response:
collection.update_one({
'emailid': request_email,
"job_id": job_id
}, {"$set": {
'batch_submitted_status': True
}})
inv_collection = db['payslip_result']
response = inv_collection.find(
{
'emailid': request_email,
'job_id': job_id
}, {
'emailid': 0,
'job_id': 0
})
if response:
api_response = [row for row in response]
mongo_db_client.close()
return api_response
else:
mongo_db_client.close()
return -2
return 1
###############################################################################################
def update_jobstatus(request_email, request_jobid, request_status):
try:
collection = db['payslip_job']
collection.update_one(
{
'emailid': request_email,
"job_id": request_jobid
}, {"$set": {
'job_status': request_status
}})
mongo_db_client.close()
return 0
except Exception as e:
print(traceback.print_exc())
return -2
###############################################################################################
def payslip_result(request_data,excel_path):
try:
collection = db['payslip_result']
response = collection.find_one({
'emailid': request_data['emailid'],
"job_id": request_data['job_id'],
'batch_submitted_status': False
}, {
'_id': 0,
'emailid': 0,
'job_id': 0
})
if response:
print("Job already digitised")
return -2
else:
collection.insert(request_data, check_keys=False)
job_collection=db['payslip_job']
job_collection.update_one(
{
'emailid': request_data['emailid'],
"job_id": request_data['job_id']
}, {"$set": {
'excel_path': excel_path
}})
mongo_db_client.close()
return 0
except Exception as e:
print(traceback.print_exc())
return -2
###############################################################################################
def adminDashboardDetail(admin_email,flag):
collection = db['payslip_job']
response = collection.find(
{
'admin_submitted':flag
},{
'_id':0,
'job_status':0,
'job_priority':0,
'job_size':0,
'document_name':0,
'batch_submitted_status':0
})
if response:
api_response = []
for row in response:
api_response.append(row)
mongo_db_client.close()
return api_response
else:
mongo_db_client.close()
return -2
###############################################################################################
def returnApplication(emailid,jobid):
collection = db['payslip_result']
response = collection.find(
{
'emailid':emailid,
'job_id':jobid
}
)
if response:
api_response = [row for row in response]
return api_response
return -1
###############################################################################################
def get_excel_data_by_date(user_email, day_start_date,day_end_date):
try:
job_collection = db['payslip_job']
base_dir = os.getcwd()
date_time_obj = datetime.datetime.strptime(day_end_date,'%Y-%m-%d')
day_end_date = str(date_time_obj.date() + timedelta(days=1))
job_id_query = { "emailid":user_email,"upload_date_time":{ "$gt": day_start_date,"$lte": day_end_date }}
response = job_collection.find(job_id_query)
if response:
write_excel_file=base_dir+'/webserverflask/static/data/excels/daily_report.xlsx'
if os.path.isfile(write_excel_file):
os.remove(write_excel_file)
df=pd.DataFrame()
for resp in response:
excel_file=base_dir+'/webserverflask/'+resp['excel_path']
df=df.append(pd.read_excel(excel_file))
# sheet_name=resp['batch_name']
# sheet_name = re.sub(r'[:?*//]', "",sheet_name)
with pd.ExcelWriter(write_excel_file, engine="openpyxl", mode="w") as writer:
df.to_excel(writer,sheet_name = "Results",index=False)
writer.save()
return 'static/data/excels/daily_report.xlsx'
else:
mongo_db_client.close()
return -2
except Exception as e:
print(traceback.print_exc())
return -2
###############################################################################################
def admin_review_job(user_email,job_id):
job_collection = db['payslip_job']
job_response = job_collection.find_one(
{
'emailid': user_email,
'job_id':job_id
}, {
'emailid': 0,
'_id': 0,
})
if job_response:
api_response = []
resp = returnApplication(user_email,job_id)
api_response.extend(resp)
mongo_db_client.close()
return api_response
else:
mongo_db_client.close()
return -2
###############################################################################################
def update_excel(request_email, request_data):
try:
base_dir = os.getcwd()
print(base_dir)
excel_file=base_dir+'/webserverflask/static/data/excels/Job_'+request_data['job_id']+'.xlsx'
file_name=request_data['file_name'].split("/")[-1]
df=pd.read_excel(excel_file)
print(df)
for attribute in request_data['text_fields']:
print(file_name,attribute['varname'],attribute['value'])
df.loc[df.file == file_name, attribute['varname']] = attribute['value']
print("updated",df['employer_name'])
with pd.ExcelWriter(excel_file, engine="openpyxl", mode="w") as writer:
df.to_excel(writer,sheet_name = 'Payslip Result',index=False)
writer.save()
return 1
except Exception as e:
print(traceback.print_exc())
###############################################################################################
def admin_submit(user_email,job_id):
collection = db['payslip_job']
response = collection.find_one({
'emailid': user_email,
'job_id':job_id
}, {
'_id': 0,
'emailid': 0
})
format_date = "%Y-%m-%d %H:%M"
now_utc = datetime.datetime.now(timezone('UTC'))
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
if response:
collection.update_one({
'emailid': user_email,
'job_id':job_id
}, {"$set": {
'admin_submitted': True,
'admin_submitted_time':now_asia.strftime(format_date)
}})
mongo_db_client.close()
return 1
return -2
###############################################################################################
def admin_update(admin_email, request_data):
try:
collection = db['payslip_result']
full_response = collection.find({
'emailid': request_data['user_email'],
"job_id": request_data['job_id'],
"Result":{"$elemMatch":{"image":request_data['file_name']}}
})
if full_response:
for row in full_response:
print(row)
flag=0
for response in row["Result"]:
print(response)
if request_data["file_name"] in response["image"]:
update_data = {}
for text_attribute in request_data['text_fields']:
attribute = text_attribute['varname']
try:
attrb_GT = response["Output"][attribute]
attrb_value = text_attribute['value']
print(attrb_GT,attrb_value)
if not attrb_value == attrb_GT:
response['Output'][attribute] = attrb_value
response['Output'][attribute + '_conf'] = 1
response['Output'][attribute + '_user_edited'] = 1
flag=1
except Exception as e:
print(traceback.print_exc())
return -2
if flag:
print(row["Result"])
collection.update(
{
'emailid': request_data['user_email'],
'job_id': request_data['job_id'],
'_id':row['_id']
}, {"$set": {"Result":row["Result"]}})
print("updates")
update_excel(request_data['user_email'],request_data)
print("excel_updated")
return 1
else:
mongo_db_client.close()
return -2
except Exception as e:
print(traceback.print_exc())
return -2
<file_sep>$(document).ready(function() {
$('#success').hide();
$('#error').hide();
sessionStorage.clear();
$(document).ajaxStart(function() {
$('#wait2').css('display', 'block');
});
$(document).ajaxComplete(function() {
$('#wait2').css('display', 'none');
});
$('#loginBtn').click(function() {
$('#loginForm').validate({
rules: {
emailid: 'required',
password: {
minlength: 5,
},
},
messages: {
emailid: 'Please enter your Email ID',
password: {
required: 'Please enter your Password',
minlength: 'Your password must be at least 8 characters long',
},
},
submitHandler: function(form) {
const data_attrs = {
'emailid': document.getElementById('emailid').value,
'password': <PASSWORD>('password').<PASSWORD>,
};
const success = {
'url': 'https://credit.in-d.ai/hdfc_life/credit/admin_login',
'headers': {
'content-type': 'application/json',
},
'method': 'POST',
'processData': false,
'data': JSON.stringify(data_attrs),
};
$.ajax(success).done(function(data, textStatus, xhr) {
if (xhr.status === 200) {
// alert(JSON.stringify(data));
// console.log(JSON.stringify(data));
// console.log(JSON.stringify(data.token));
const token2 = JSON.stringify(data.token);
const token = token2.slice(1, -1);
$('#success').fadeTo(5000, 3000).slideUp(500, function() {
});
var firstname = JSON.stringify(data.firstname);
localStorage.setItem('token', token);
var firstname = JSON.stringify(data.firstname);
var firstname = firstname.slice(1, -1);
sessionStorage.setItem('firstname', firstname);
window.location.href = 'main-dashboard.html';
} else if (xhr.status === 201) {
alert(JSON.stringify(data.message));
// location.reload();
} else {
alert(JSON.stringify(data.message));
// location.reload();
}
}).fail(function(data, textStatus, xhr) {
$('#error').show();
$('#error').text(data.responseJSON.message);
// console.log("Return" + JSON.stringify(data.responseJSON.message));
// console.log(data);
$('#error').fadeTo(5000, 3000).slideUp(500, function() {
});
if (data.responseJSON.message == 'Token is invalid!') {
setTimeout(function() {
window.location.assign('index.html');
}, 2000);
localStorage.removeItem('token');
sessionStorage.clear();
};
});
},
});
});
});
<file_sep>from pymongo import MongoClient
import traceback
import os,json
import re
import openpyxl
import pandas as pd
import shutil
from datetime import datetime
from datetime import timedelta
from flask import jsonify
from config.config import MONGODB_NAME,MONGODB_PORT,MONGODB_URL,API_KEY,RAZOR_KEY,RAZOR_SECRET,INTAIN_EMAIL,INTAIN_PASSWD,BASE_URL
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from .calculation_analysis import get_statement_analysis
from .function_library import get_valid_format
from .combining_dataframes import combined_dataframe
from datetime import datetime
from pytz import timezone
from .bank_statement import get_bank_statement,extraction_data,extraction_column,check_password_new,get_file_name,get_password_status
mongo_db_client = None
########################################################################################################################
def register_user(request_data,registration_type):
user_attributes = ['firstname','lastname','password','emailid','phone','companyname']
for attribute in user_attributes:
if attribute not in request_data:
return -1
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
resp = collection.find_one({'emailid':request_data['emailid'],'registration_type':registration_type})
if not resp:
secret_key = ""
for attribute in user_attributes[:6]:
if attribute != 'password':
secret_key = secret_key + str(request_data[attribute]).replace(' ','')
request_data['secretkey'] = secret_key
request_data['status']='Inactive'
request_data['registration_type'] = registration_type
collection.insert_one(request_data)
resp = collection.find_one({'secretkey':secret_key,'emailid':request_data['emailid']})
port = 465 # For SSL
sender_email=INTAIN_EMAIL
receiver_email = request_data['emailid']
activate_url = BASE_URL + "/activate_customer?emailid=" + receiver_email + "&secretkey=" + secret_key
print("Activate URL >>>> ",activate_url)
message = MIMEMultipart("alternative")
message["Subject"] = "IN-D Credit: Activation Required"
message["From"] = INTAIN_EMAIL
message["To"] = receiver_email
text = """\
click to activate """ + activate_url
htmltext = """\
<html>
<head></head>
<body>
<div class="container justify-content-center" style="margin: 50px 100px">
<h3 style="font-size: 26px; color: #2b2b2b; text-align: center ">
Activate your IN-D Credit account
</h3>
<hr style="border-top: 1px solid #b7b9bb; width: 100%; margin-top: 30px">
<p style="font-size: 18px; color: #4c4c4e; text-align: left;font-weight: bold; padding-top: 10px">
Hello ,
</p>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
To activate your IN-D Credit account simply click the button below.
Once clicked your request will be processed and verified and you
will be redirected to the IN-D Credit Web application.
</p>
<div class="wrapper" style="margin-top: 20px; margin-bottom: 20px; text-align: center">
<a href=" """ + activate_url + """ "><button style="background-color: #0085d8; border: 1px solid #0085d8; color: white; font-size: 14px; height: 35px; width: 200px; cursor: pointer;">
ACTIVATE ACCOUNT
</button></a>
</div>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
You are receiving this email because you created an IN-D Credit account.
If you believe you have received this email in error, please mail us
to <a href="#"><EMAIL></a>
</p>
<hr style="border-top: 1px solid #b7b9bb; width: 100%; margin-top: 30px">
</div>
</body>
</html>
"""
mail_body=MIMEText(htmltext,"html")
message.attach(mail_body)
# Create a secure SSL context
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(INTAIN_EMAIL, INTAIN_PASSWD)
server.sendmail(sender_email,receiver_email,message.as_string())
else:
mongo_db_client.close()
return -2
mongo_db_client.close()
return 1
########################################################################################################################
def register_admin(request_data,registration_type):
user_attributes = ['firstname','lastname','password','emailid','phone','companyname','jobtitle','answer','question']
for attribute in user_attributes:
if attribute not in request_data:
return -1
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
resp = collection.find_one({'emailid':request_data['emailid'],'registration_type':registration_type})
if not resp:
secret_key = ""
for attribute in user_attributes[:6]:
if attribute != 'password':
secret_key = secret_key + str(request_data[attribute]).replace(' ','')
request_data['secretkey'] = secret_key
request_data['status']='Inactive'
request_data['registration_type'] = registration_type
collection.insert_one(request_data)
resp = collection.find_one({'secretkey':secret_key,'emailid':request_data['emailid']})
port = 465 # For SSL
sender_email=INTAIN_EMAIL
receiver_email = request_data['emailid']
activate_url = BASE_URL + "/activate_admin?emailid=" + receiver_email + "&secretkey=" + secret_key
message = MIMEMultipart("alternative")
message["Subject"] = "IN-D Credit: Admin Activation Required"
message["From"] = INTAIN_EMAIL
message["To"] = receiver_email
text = """\
click to activate """ + activate_url
htmltext = """\
<html>
<head></head>
<body>
<div class="container justify-content-center" style="margin: 50px 100px">
<h3 style="font-size: 26px; color: #2b2b2b; text-align: center ">
Activate your IN-D Credit account
</h3>
<hr style="border-top: 1px solid #b7b9bb; width: 100%; margin-top: 30px">
<p style="font-size: 18px; color: #4c4c4e; text-align: left;font-weight: bold; padding-top: 10px">
Hello ,
</p>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
To activate your IN-D Credit account simply click the button below.
Once clicked your request will be processed and verified and you
will be redirected to the IN-D Credit Web application.
</p>
<div class="wrapper" style="margin-top: 20px; margin-bottom: 20px; text-align: center">
<a href=" """ + activate_url + """ "><button style="background-color: #0085d8; border: 1px solid #0085d8; color: white; font-size: 14px; height: 35px; width: 200px; cursor: pointer;">
ACTIVATE ACCOUNT
</button></a>
</div>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
You are receiving this email because you created an IN-D Credit account.
If you believe you have received this email in error, please mail us
to <a href="#"><EMAIL></a>
</p>
<hr style="border-top: 1px solid #b7b9bb; width: 100%; margin-top: 30px">
</div>
</body>
</html>
"""
mail_body=MIMEText(htmltext,"html")
message.attach(mail_body)
# Create a secure SSL context
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(INTAIN_EMAIL, INTAIN_PASSWD)
server.sendmail(sender_email,receiver_email,message.as_string())
else:
mongo_db_client.close()
return -2
mongo_db_client.close()
return 1
########################################################################################################################
def customer_activate(request_data):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
print(request_data)
#secretkey=request_data['companyname'][0:8].replace(' ','')
collection = db['user_detail']
print(request_data['secretkey'])
resp = collection.find_one({'secretkey':request_data['secretkey']})
if not resp:
print('Invalid Customer')
mongo_db_client.close()
return -2
else:
if resp['status'] != 'Active':
resp = collection.find_one({'secretkey':request_data['secretkey'],'emailid':request_data['emailid'],})
if not resp:
mongo_db_client.close()
return -1
else:
if resp['status'] != "Active":
print('Activating')
format_date = "%Y-%m-%d %H:%M"
now_utc = datetime.now(timezone('UTC'))
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
resp = collection.update_one({'secretkey':request_data['secretkey']},{"$set":{'status': 'Active','reg_date_time':now_asia.strftime(format_date)}})
port = 465 # For SSL
sender_email = INTAIN_EMAIL
receiver_email = request_data['emailid']
login_url = BASE_URL
message = MIMEMultipart("alternative")
message["Subject"] = "IN-D Credit: Welcome!!!!"
message["From"] = sender_email
message["To"] = receiver_email
htmltext = """
<html>
<head></head>
<body>
<div class="container justify-content-center" style="margin: 50px 100px">
<h3 style="font-size: 26px; color: #2b2b2b; text-align: center ">
IN-D Credit account activation confirmation
</h3>
<hr style="border-top: 1px solid #b7b9bb; width: 100%; margin-top: 30px">
<p style="font-size: 18px; color: #4c4c4e; text-align: left;font-weight: bold; padding-top: 10px">
Hello ,
</p>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
Your account has been actvated. You can now access the application with your credentials using the following link
</p>
<div class="wrapper" style="margin-top: 20px; margin-bottom: 20px; text-align: center">
<a href=" """ + login_url + """ "><button style="background-color: #0085d8; border: 1px solid #0085d8; color: white; font-size: 14px; height: 35px; width: 200px; cursor: pointer;">
Click To Login
</button></a>
</div>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
Please make a note of the customer key """ + request_data['secretkey'] + """ for API access
</p>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
You are receiving this email because you activated an IN-D Credit account.
If you believe you have received this email in error, please mail us
to <a href="#"><EMAIL></a>
</p>
<hr style="border-top: 1px solid #b7b9bb; width: 100%; margin-top: 30px">
</div>
</body>
</html>
"""
mail_body=MIMEText(htmltext,"html")
message.attach(mail_body)
# Create a secure SSL context
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(INTAIN_EMAIL, INTAIN_PASSWD)
server.sendmail(sender_email,receiver_email,message.as_string())
else:
mongo_db_client.close()
return -2
else:
print('already active')
mongo_db_client.close()
return -3
mongo_db_client.close()
return 1
########################################################################################################################
def admin_activate(request_data):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
print(request_data)
#secretkey=request_data['companyname'][0:8].replace(' ','')
collection = db['user_detail']
print(request_data['secretkey'])
resp = collection.find_one({'secretkey':request_data['secretkey']})
if not resp:
print('Invalid Customer')
mongo_db_client.close()
return -2
else:
if resp['status'] != 'Active':
resp = collection.find_one({'secretkey':request_data['secretkey'],'emailid':request_data['emailid'],})
if not resp:
mongo_db_client.close()
return -1
else:
if resp['status'] != "Active":
print('Activating')
format_date = "%Y-%m-%d %H:%M"
now_utc = datetime.now(timezone('UTC'))
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
resp = collection.update_one({'secretkey':request_data['secretkey']},{"$set":{'status': 'Active','reg_date_time':now_asia.strftime(format_date)}})
port = 465 # For SSL
sender_email = INTAIN_EMAIL
receiver_email = request_data['emailid']
login_url = BASE_URL +"/admin/index.html"
print(":::::::::::",login_url)
message = MIMEMultipart("alternative")
message["Subject"] = "IN-D Credit: Welcome Admin!!!!"
message["From"] = sender_email
message["To"] = receiver_email
htmltext = """
<html>
<head></head>
<body>
<div class="container justify-content-center" style="margin: 50px 100px">
<h3 style="font-size: 26px; color: #2b2b2b; text-align: center ">
IN-D Credit account activation confirmation
</h3>
<hr style="border-top: 1px solid #b7b9bb; width: 100%; margin-top: 30px">
<p style="font-size: 18px; color: #4c4c4e; text-align: left;font-weight: bold; padding-top: 10px">
Hello ,
</p>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
Your account has been actvated. You can now access the application with your credentials using the following link
</p>
<div class="wrapper" style="margin-top: 20px; margin-bottom: 20px; text-align: center">
<a href=" """ + login_url + """ "><button style="background-color: #0085d8; border: 1px solid #0085d8; color: white; font-size: 14px; height: 35px; width: 200px; cursor: pointer;">
Click To Login
</button></a>
</div>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
Please make a note of the customer key """ + request_data['secretkey'] + """ for API access
</p>
<p style="font-size: 16px; color:#777783; text-align: left; line-height: 23px">
You are receiving this email because you activated an IN-D Credit account.
If you believe you have received this email in error, please mail us
to <a href="#"><EMAIL></a>
</p>
<hr style="border-top: 1px solid #b7b9bb; width: 100%; margin-top: 30px">
</div>
</body>
</html>
"""
mail_body=MIMEText(htmltext,"html")
message.attach(mail_body)
# Create a secure SSL context
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(INTAIN_EMAIL, INTAIN_PASSWD)
server.sendmail(sender_email,receiver_email,message.as_string())
else:
mongo_db_client.close()
return -2
else:
print('already active')
mongo_db_client.close()
return -3
mongo_db_client.close()
return 1
########################################################################################################################
def login_user(request_data):
login_attributes = ['emailid', 'password']
for attribute in login_attributes:
if attribute not in request_data:
return -1,""
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
resp = collection.find_one({'emailid': request_data['emailid'], 'password': request_data['password'],
'registration_type':'user_registration'})
if resp:
if resp['status'] == "Inactive":
mongo_db_client.close()
return -3,""
else:
secret_key = resp['secretkey']
first_name = resp['firstname']
else:
mongo_db_client.close()
return -2,""
mongo_db_client.close()
return first_name, secret_key
########################################################################################################################
def login_admin(request_data):
login_attributes = ['emailid', 'password']
for attribute in login_attributes:
if attribute not in request_data:
return -1,""
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
resp = collection.find_one({'emailid': request_data['emailid'], 'password': request_data['password'],
'registration_type':'admin_registration'})
if resp:
if resp['status'] == "Inactive":
mongo_db_client.close()
return -3,""
else:
secret_key = resp['secretkey']
first_name = resp['firstname']
else:
mongo_db_client.close()
return -2,""
mongo_db_client.close()
return first_name, secret_key
########################################################################################################################
def update_token(request_email, request_token,registration_type):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['token_detail']
resp = collection.find_one(({'emailid': request_email}))
if resp:
collection.update_one({'emailid': request_email}, {"$set":{'token': request_token,'registration_type':registration_type}})
else:
collection.insert_one(({'emailid': request_email, 'token': request_token,'registration_type':registration_type}))
mongo_db_client.close()
return 1
########################################################################################################################
def forget_password(request_data):
if 'emailid' not in request_data:
return -1
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
resp = collection.find_one({'emailid': request_data['emailid']})
if resp:
secret_key = resp['secretkey']
else:
mongo_db_client.close()
return -2
mongo_db_client.close()
return secret_key
########################################################################################################################
def get_token_process_docs(request_data):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['token_detail']
resp = collection.find_one(({'token': request_data['token'],'registration_type':'user_registration'}))
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>",resp)
if resp:
email_id = resp['emailid']
mongo_db_client_new = MongoClient(MONGODB_URL, MONGODB_PORT)
db_new = mongo_db_client[MONGODB_NAME]
collection_new = db_new['user_detail']
resp_new = collection_new.find_one(({'emailid': email_id}))
secret_key = resp_new['secretkey']
else:
mongo_db_client.close()
return -2
mongo_db_client.close()
mongo_db_client_new.close()
return {'emailid': email_id, 'secretkey': secret_key}
########################################################################################################################
def get_token(request_data,registration_type):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['token_detail']
resp = collection.find_one(({'token': request_data['token'],'registration_type':registration_type}))
if resp:
email_id = resp['emailid']
mongo_db_client_new = MongoClient(MONGODB_URL, MONGODB_PORT)
db_new = mongo_db_client[MONGODB_NAME]
collection_new = db_new['user_detail']
resp_new = collection_new.find_one(({'emailid': email_id}))
secret_key = resp_new['secretkey']
else:
mongo_db_client.close()
return -2
mongo_db_client.close()
mongo_db_client_new.close()
return {'emailid': email_id, 'secretkey': secret_key}
#######################################################################################################################
def get_single_records(emailid,job_id,new_file_name,output_dataframe,excel_path,transaction_data,calculation_response,calculation_result_list,bank_type):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['analysis_detail']
collection_job_status = db['job_detail']
collection.insert_one(({'emailid':emailid,'job_id': job_id, 'file_name': new_file_name,
'excel_path': excel_path,'calculation_response': str(calculation_response) ,
'calculation_result_list':calculation_result_list}))
collection_job_status.update_one({'job_id': job_id}, {"$set":{'job_status': "Incomplete",'excel_path':excel_path,'bank_type':bank_type,'review_status':'Yes'}})
mongo_db_client.close()
return
########################################################################################################################
def reset_password(request_email, request_pwd):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
collection.update_one({'emailid': request_email}, {"$set": {'password': <PASSWORD>}})
mongo_db_client.close()
########################################################################################################################
def logout_user(request_email):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['token_detail']
collection.delete_one({'emailid': request_email})
mongo_db_client.close()
########################################################################################################################
def delete_by_job_id(request_email,job_id):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
collection_analysis = db['analysis_detail']
response = collection.find_one({'emailid': request_email,'job_id': job_id})
file_path = response['file_path']
folder_path = file_path.split('/')[-1]
folder_path = file_path.replace(folder_path,'')
if os.path.exists:
shutil.rmtree(folder_path)
collection.delete_one({'emailid': request_email,'job_id': job_id})
collection_analysis.delete_one({'emailid': request_email,'job_id': job_id})
mongo_db_client.close()
return
########################################################################################################################
def get_company_name(request_email):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
company_name = collection.find_one({'emailid':request_email})
company_name = company_name['companyname']
mongo_db_client.close()
return company_name
########################################################################################################################
def long_words(lst,dashboard):
words = []
for word in lst:
if dashboard == 'user':
word = {key: word[key] for key in word.keys()
& {'bank_name','upload_date_time','job_id','job_status','applicant_id','excel_path','comment'}}
words.append(word)
elif dashboard == 'admin':
word = {key: word[key] for key in word.keys()
& {'bank_name','upload_date_time','job_id','job_status','emailid','applicant_id','excel_path','document_name','review_status','comment'}}
words.append(word)
return words
def user_dashboard_detail(request_email,data):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find({'emailid': request_email}, { '_id': 0})
if response:
api_response = long_words(response,'user')
mongo_db_client.close()
return api_response
else:
mongo_db_client.close()
return -2
########################################################################################################################
def admin_dashboard_detail(request_email):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find({'job_status': 'Incomplete'}, { '_id': 0})
if response:
api_response = long_words(response,'admin')
mongo_db_client.close()
return api_response
else:
mongo_db_client.close()
return -2
########################################################################################################################
def get_reviewed_admin_dashboard(request_email):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find({'job_status': 'Completed'}, { '_id': 0})
if response:
api_response = long_words(response,'admin')
mongo_db_client.close()
return api_response
else:
mongo_db_client.close()
return -2
########################################################################################################################
def get_application_id_detail(applicant_id,emailid):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find_one(({'applicant_id':applicant_id,'emailid':emailid}))
if response:
mongo_db_client.close()
return response
else:
mongo_db_client.close()
return -2
########################################################################################################################
def get_Details_By_ID(request_email, request_jobid):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['analysis_detail']
response = collection.find_one({'emailid': request_email, 'job_id': request_jobid}, {'emailid': 0, '_id': 0, 'job_id': 0})
if response:
mongo_db_client.close()
return response
else:
mongo_db_client.close()
return -2
########################################################################################################################
def get_excel_data(lst):
words = []
indexes = []
for word in lst:
word_list = {key: word[key] for key in word.keys()
& {'upload_date_time','job_id','job_status','applicant_id','calculation_response'}}
word = word_list['calculation_response']
index = word_list['applicant_id']
indexes.append(index)
words.append(word)
return words,indexes
def get_excel_data_by_date(request_email, day_start_date,day_end_date):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
date_time_obj = datetime.strptime(day_end_date,'%Y-%m-%d')
day_end_date = str(date_time_obj.date() + timedelta(days=1))
myquery = { "emailid":request_email,'job_status':'Completed', "upload_date_time":{"$gt": day_start_date,"$lte": day_end_date }}
response = collection.find(myquery)
if response:
api_response,indexes = get_excel_data(response)
df = pd.DataFrame(api_response, index = indexes)
df = df.sort_index()
daily_data_csv_path = os.getcwd() + f'/webserverflask/static/data/input/daily_report_{day_start_date}.csv'
df.to_csv(daily_data_csv_path)
excel_path = daily_data_csv_path.split('/hdfc_credit/webserverflask')[-1]
mongo_db_client.close()
return excel_path
else:
mongo_db_client.close()
return -2
########################################################################################################################
def save_upload_file(emailid, job_id,file_name):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find_one({'emailid': emailid, 'job_id': job_id})
if response:
x = response['file_names']
x.append(file_name)
collection.update_one({'emailid': emailid,'job_id': job_id}, {"$set": {'file_names': x}})
mongo_db_client.close()
return x
else:
x = []
x.append(file_name)
collection.insert_one(({'emailid':emailid,'job_id': job_id, 'file_names': x}))
mongo_db_client.close()
return x
########################################################################################################################
def get_upload_file(emailid, job_id):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find_one({'emailid': emailid, 'job_id': job_id})
if response:
x = response['file_names']
collection.delete_one({'emailid': emailid,'job_id': job_id})
mongo_db_client.close()
return x
else:
collection.delete_one({'emailid': emailid,'job_id': job_id})
mongo_db_client.close()
return -2
########################################################################################################################
def get_localization_password_status(request_data):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find_one({'job_id': request_data['job_id']})
if response:
# file_path = response['file_path']
# password = response['<PASSWORD>']
# bank_name = response['bank_name']
localization_status = response['localization_status']
readable_status = response['readable_status']
collection.update_one({'job_id': request_data['job_id']}, {"$set": {'doc_type': 'Bank Statement'}})
mongo_db_client.close()
return [localization_status,readable_status]
else:
mongo_db_client.close()
return -2
########################################################################################################################
def get_localization_details(request_data):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find_one({'job_id': request_data['job_id'],'job_status': 'Incomplete'})
if response:
file_path = response['file_path']
# doc_type = response['doc_type']
doc_type = 'Bank Statement'
bank_name = response['bank_name']
readable_status = response['readable_status']
print("-------- Input File Name = {} -------".format(file_path))
try:
table_coordinate_list,width, height,reduced_percentage,columns_list = get_bank_statement(file_path,doc_type,bank_name,readable_status)
NewList1=[]
for ind_, temp in enumerate(table_coordinate_list):
keys_needed = ['left', 'top', 'width', 'height']
table__ = {k:temp[k] for k in keys_needed}
major_table = {k:temp[k] for k in temp if k not in keys_needed}
if ind_ == 0:
table__['colItem'] = columns_list
major_table['table_data'] = [table__]
NewList1.append(major_table)
table_coordinate_list = NewList1
collection.update_one({'job_id': request_data['job_id']}, {"$set": {'table_coordinate_list': table_coordinate_list,'width':width,
'height':height,'reduced_percentage':reduced_percentage,'columns_list':columns_list}})
mongo_db_client.close()
return [table_coordinate_list,width,height]
except:
print(traceback.print_exc())
return -2
else:
mongo_db_client.close()
return -2
#############################################################################################################################
def get_digitization_details(request_jobid,table_coords):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find_one({'job_id': request_jobid})
if response:
# data_input = response['table_coordinate_list']
data_input = table_coords
file_path = response['file_path']
readable_status = response['readable_status']
bank_name = response['bank_name']
reduced_percentage = response['reduced_percentage']
data = get_valid_format(bank_name,data_input)
try:
final_output = extraction_data(data,readable_status,reduced_percentage,file_path)
collection.update_one({'job_id': request_jobid}, {"$set": {'table_data': final_output}})
mongo_db_client.close()
return final_output
except:
print(traceback.print_exc())
return -2
else:
mongo_db_client.close()
return -2
#########################################################################################################################
def save_digitized_data(request_jobid):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.find_one({'job_id': request_jobid})
if response:
file_path = response['file_path']
bank_name = response['bank_name']
table_data = response['table_data']
try:
output_dataframe,bank_type,excel_path,transaction_data = combined_dataframe(bank_name,table_data,file_path)
final_combined = output_dataframe.to_json(orient='records')
collection.update_one({'job_id': request_jobid}, {"$set": {'final_combined': final_combined,'bank_type':bank_type,'excel_path':excel_path,'transaction_data':transaction_data}})
mongo_db_client.close()
return final_combined
except:
print(traceback.print_exc())
return -2
else:
mongo_db_client.close()
return -2
#########################################################################################################################
def get_calculation_data(request_jobid):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection_job_status = db['analysis_detail']
collection = db['job_detail']
comment = ''
response = collection.find_one({'job_id': request_jobid})
response_analysis = collection_job_status.find_one({'job_id': request_jobid})
if response_analysis:
if 'calculation_result_list' in response_analysis.keys() and 'calculation_response' in response_analysis.keys():
calculation_response = response_analysis['calculation_response']
return [calculation_response,response_analysis['excel_path'],response_analysis['calculation_result_list'],response_analysis['file_name'],comment]
if response:
file_path = response['file_path']
bank_name = response['bank_name']
bank_type = response['bank_type']
text = response['text']
word_order = response['word_order']
excel_path = response['excel_path']
emailid = response['emailid']
# transaction_data = response['transaction_data']
try:
calculation_response,calculation_result_list = get_statement_analysis(excel_path,bank_name,bank_type,file_path,text,word_order)
response = collection_job_status.find_one({'job_id': request_jobid})
excel_path = excel_path.split('/hdfc_credit/webserverflask')[-1]
file_path = file_path.split('/hdfc_credit/webserverflask')[-1]
if not response:
collection_job_status.insert_one(({'emailid':emailid,'job_id':request_jobid ,'excel_path': excel_path,'file_name':file_path,
'calculation_result_list':calculation_result_list,'comment':'',
'calculation_response':str(calculation_response)}))
else:
collection_job_status.update_one({'job_id': request_jobid}, {"$set":{'emailid':emailid,'job_id':request_jobid ,'excel_path': excel_path,'file_name':file_path,
'calculation_result_list':calculation_result_list,'comment':'',
'calculation_response':str(calculation_response)}})
collection.update_one({'job_id': request_jobid}, {"$set":{'job_status': "Completed",'calculation_csv':excel_path,'review_status':'Yes','comment':comment}})
mongo_db_client.close()
return [calculation_response,excel_path,calculation_result_list,file_path,comment]
except:
excel_path = excel_path.split('/hdfc_credit/webserverflask')[-1]
file_path = file_path.split('/hdfc_credit/webserverflask')[-1]
comment = ''
collection_job_status.insert_one(({'emailid':emailid,'job_id':request_jobid ,'excel_path': excel_path,'file_name':file_path,'review_status':'Yes','comment':comment}))
print(traceback.print_exc())
mongo_db_client.close()
return ['',excel_path,[],file_path,comment]
else:
mongo_db_client.close()
return -2
########################################################################################################################
def get_calculation_data_new(emailid,job_id):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['analysis_detail']
response = collection.find_one({'job_id': job_id})
if response:
print('calculation_response>',response['calculation_response'])
return response
mongo_db_client.close()
return
########################################################################################################################
def get_final_dict(input_dict):
final_result_list = []
final_result_id = {}
count = 1
for key,val in input_dict.items():
new_key = re.sub('[^A-Za-z]+', ' ', key)
new_key = new_key.strip()
final_result_id = {}
final_result_id['id'] = count
final_result_id['name'] = new_key
final_result_id['value'] = val
count += 1
final_result_list.append(final_result_id)
return final_result_list
def get_col_widths(dataframe):
idx_max = max([len(str(s)) for s in dataframe.index.values] + [len(str(dataframe.index.name))])
return [idx_max] + [max([len(str(s)) for s in dataframe[col].values] + [len(str(col))]) for col in dataframe.columns]
def bs_admin_update_job(emailid,data):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['analysis_detail']
job_collection = db['job_detail']
response = collection.find_one({'job_id': data['job_id']})
try:
excel_path = response['excel_path']
except:
excel_path = 'static/data/input/'
new_data = {}
new_data['Account Holder'] = data['Account Holder']
new_data['Account Opening Date'] = data['Account Opening Date']
new_data['Type of Account'] = data['Type of Account']
new_data['Monthly Average Balance'] = data['Monthly Average Balance']
new_data['Total Salary'] = data['Total Salary']
comment = data['comment']
final_result_list = get_final_dict(new_data)
key,val,values = [],[],[]
for name,cal in new_data.items():
name = re.sub('[^A-Za-z]+', ' ', name)
key.append(name.strip())
val.append(cal)
values.append(key); values.append(val)
df2 = pd.DataFrame(values,index=['Parameter', 'Result']).transpose()
excel_path_cwd = os.getcwd() + '/webserverflask'+ excel_path
# with pd.ExcelWriter(excel_path_cwd, engine="openpyxl", mode="a") as writer:
# workbook=openpyxl.load_workbook(excel_path_cwd)
# try:
# std=workbook.get_sheet_by_name('calculations and ratios')
# workbook.remove_sheet(std)
# except:
# pass
# df2.to_excel(writer,sheet_name = 'calculations and ratios',index=False)
try:
writer = pd.ExcelWriter(excel_path_cwd,engine='xlsxwriter')
df2.to_excel(writer, sheet_name='Bank Statement Result', header = True,index=False)
worksheet = writer.sheets['Bank Statement Result']
for i, width in enumerate(get_col_widths(df2)):
worksheet.set_column(i, i,width+5)
writer.save()
except:
print(traceback.print_exc())
pass
collection.update_one({'job_id': data['job_id']}, {"$set": {'calculation_result_list':final_result_list,'calculation_response':new_data,'excel_path':excel_path,'comment':comment}})
job_collection.update_one({'job_id': data['job_id']}, {"$set": {'job_status': "Completed",'comment':comment,'review_status':'Yes','excel_path':excel_path,'calculation_response':new_data}})
mongo_db_client.close()
return 'Successful'
########################################################################################################################
def profile_update(request_email):
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
response = collection.find({'emailid': request_email}, {'_id': 0, 'secretkey': 0})
if response:
api_response = [row for row in response]
mongo_db_client.close()
return api_response
else:
mongo_db_client.close()
return -2
########################################################################################################################
def update_secret(request_email):
user_attributes = ['firstname','lastname','password','emailid','phone','companyname']
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
resp = collection.find_one({'emailid':request_email})
if resp:
secret_key = ""
for attribute in user_attributes[:6]:
secret_key = secret_key + resp[attribute]
collection.update_one({'emailid': request_email}, {"$set": {'secretkey':secret_key}})
mongo_db_client.close()
return 1
########################################################################################################################
def user_update(request_email, request_data):
user_attributes = ['firstname','lastname','password','phone','companyname']
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['user_detail']
resp = collection.find_one({'emailid': request_email})
if resp:
update_data = {}
for attribute in user_attributes:
if attribute in request_data:
attrb_GT = resp[attribute]
attrb_value = request_data[attribute]
if not attrb_value == attrb_GT:
update_data[attribute] = attrb_value
if len(update_data):
collection.update_one({'emailid': request_email}, {"$set": update_data})
update_secret(request_email)
else:
mongo_db_client.close()
return -2
mongo_db_client.close()
return 1
########################################################################################################################
def get_jobid(request_email):
try:
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
response = collection.count()
mongo_db_client.close()
return response
except:
print(traceback.print_exc())
return -2
########################################################################################################################
def insert_job(request_data):
try:
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
collection.insert_one(request_data)
mongo_db_client.close()
return 0
except:
print(traceback.print_exc())
return -2
########################################################################################################################
def update_jobstatus(request_email, request_jobid, request_status):
try:
mongo_db_client = MongoClient(MONGODB_URL, MONGODB_PORT)
db = mongo_db_client[MONGODB_NAME]
collection = db['job_detail']
collection.update_one({'emailid': request_email, "job_id": request_jobid}, {"$set": {'job_status': request_status}})
mongo_db_client.close()
return 0
except:
print(traceback.print_exc())
return -2
########################################################################################################################
if __name__ == "__main__":
print("")
pass
<file_sep>import csv,json
import pandas as pd
from .valid_dataframe import get_valid_dataframe
import config.config as project_configs
txndata_json = project_configs.INTAIN_BANK_STATEMENT_TXNDATA_JSON
def combined_dataframe(bank_name,data,file_path):
try:
data_response = data['response']
except:
data_response = data
excel_data = []
for item in data_response:
excel_data.append(item['excel_data'])
first_df = excel_data[0]
first_df = pd.read_json(first_df)
first_df = first_df.T
data_list = []
for item in excel_data:
train = pd.read_json(item)
train = train.T
data_list.append(train)
new_path = file_path.split('.')[:-1]
new_file_path = ".".join(new_path)
# csv_path = new_file_path + ".csv"
excel_path = new_file_path + ".xlsx"
# print("++++ CSV Path = {} ++++".format(csv_path))
final_data = pd.concat(data_list, ignore_index = True)
final_dataframe,bank_type = get_valid_dataframe(bank_name,final_data)
original_dataframe = final_dataframe
if bank_name == "<NAME>ANK" or bank_type == 'AXIS BANK A' or bank_type == 'ICICI BANK 9':
# final_dataframe.to_csv(csv_path, encoding='utf-8',header=True, index=False)
final_dataframe.to_excel(excel_path,'transaction_data',header=True,index=False)
# writer.save()
else:
# final_dataframe.to_csv(csv_path, encoding='utf-8',header=False, index=False)
final_dataframe.to_excel(excel_path,'transaction_data',header=False,index=False)
new_header = final_dataframe.iloc[0] #grab the first row for the header
final_dataframe = final_dataframe[1:] #take the data less the header row
final_dataframe.columns = new_header
final_dataframe.fillna("", inplace = True)
final_dataframe.to_json(txndata_json,orient='records')
# csv_path_new = csv_path.split('hdfc_credit')[-1]
# excel_path = excel_path.split('hdfc_credit')[-1]
with open(txndata_json) as f:
final_combined = json.load(f)
return original_dataframe, bank_type, excel_path,final_combined
<file_sep>import io
import os
import re
import csv
import traceback
import pandas as pd
from google.cloud import vision
from google.cloud.vision import types
import config.config as project_configs
from .process_BS import ocr,group_ocr_words,generate_lines
from pdf2image import convert_from_path
from PIL import Image
# Image.MAX_IMAGE_PIXELS = None
apikey = project_configs.INTAIN_BANK_STATEMENT_GOOGLE_APPLICATION_CREDENTIALS
ifsc_code = project_configs.INTAIN_BANK_STATEMENT_IFSC_CODE_CSV
bank_tags = project_configs.INTAIN_BANK_STATEMENT_BANK_TAGS_CSV
def google_vision(file_name):
try:
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = apikey
client = vision.ImageAnnotatorClient()
with io.open(file_name, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response=client.text_detection(image=image)
texts = response.text_annotations
for text in texts:
vertices = (['{},{}'.format(vertex.x, vertex.y) for vertex in text.bounding_poly.vertices])
try:
return re.sub('[^A-Z a-z 0-9 -/:]+', '\n', texts[0].description)
# return texts[0].description
except:
return ""
return re.sub('[^A-Z a-z 0-9 -/:]+', '\n', texts[0].description)
# return texts[0].description
except:
print(traceback.print_exc())
def get_required_text(text):
key = ['txn date','txn','transaction date','post date','particulars','cheque/reference no','cheque no.','channel','chq./ref.no.','narration','naration','transaction remarks','remitter',
'chq/ref no','transaction date','description','value date','my portfolio','utr number','remarks']
flag = False
text_lower = text.lower()
for item in key:
if item in text_lower and not flag:
text = text_lower.split(item)[0]
flag = True
# return text
text2 = text.splitlines()
text = ' '.join(text2)
return text.lower()
def get_bank_name(text,ifsc_code):
new_text = get_required_text(text)
# print(new_text)
ifsc_list = re.findall(r'[a-z]{4}[0o][0-9]{6}',new_text)
print("--------detected IFSC Code-------",ifsc_list)
df = pd.read_excel(ifsc_code)
bank_tagline = pd.read_excel(bank_tags)
new_bank_name = ''
if ifsc_list:
bank_name = ifsc_list[0]
IFSC = bank_name[0:4]
for index, row in df.iterrows():
x = row['IFSC_CODE']
x = x.lower()
if x == IFSC:
new_bank_name = row['Bank_Name']
print('------bank name from IFSC------',new_bank_name)
return new_bank_name
else:
if new_text:
for index, row in df.iterrows():
x = row['Bank_Name']
if str(x) in new_text.upper():
new_bank_name = x.upper()
if new_bank_name == 'INDIAN BANK':
if 'experience next generation banking' in new_text.lower():
return 'SOUTH INDIAN BANK'
return new_bank_name
for index, row in bank_tagline.iterrows():
bank_tag = row['tag_line']
new_bank_name = row['bank_name']
if bank_tag.upper() in new_text.upper():
return new_bank_name
return 'Unknown Bank'
def get_document_type(file_name):
try:
if file_name.endswith('.pdf') or file_name.endswith('.PDF'):
pages = convert_from_path(file_name,250,first_page=1, last_page=1)
for page in pages:
page.save("%s-page100.jpg" % (file_name[:-4]), "JPEG")
file_path = file_name[:-4]
image_name = file_path + '-page100.jpg'
else:
image_name = file_name
except:
if file_name.endswith('.pdf') or file_name.endswith('.PDF'):
pages = convert_from_path(file_name,100,first_page=1, last_page=1)
print(pages)
for page in pages:
page.save("%s-page100.jpg" % (file_name[:-4]), "JPEG")
file_path = file_name[:-4]
image_name = file_path + '-page100.jpg'
else:
image_name = file_name
boxes = ocr(image_name,False,apikey)
# print(boxes)
df,word_order = group_ocr_words(boxes[0][1:])
# print(df)
lines = generate_lines(df,word_order)
text = '\n'.join(lines)
text = google_vision(image_name)
# print(text.split('\n'))
# readable_status = get_readable_status(im)
text_data_lower = text.lower()
Bank_statement_keywords = ['particulars','statement','account','income','credit','debit','Chq','ifsc code','naration','biaya']
flag = False
for item in Bank_statement_keywords:
if item in text_data_lower and not flag:
flag = True
document_type = "Bank Statement"
bank_name = get_bank_name(text,ifsc_code)
# try:
# document_type = document_type
# except:
# document_type = "Unknown"
# bank_name = bank_name.strip()
# print("------document_type = {},bank_name = {} ------".format(document_type,bank_name))
text_dataframe = df.to_json(orient='records')
# return document_type,bank_name,text_dataframe,str(word_order)
print(">>>>>>>>>>>> Bank Names is >>>>>>>>>>",bank_name)
return text_dataframe,str(word_order),bank_name
<file_sep>opencv-python
google-cloud-vision
celery==4.1.1
falcon==1.4.1
flower==0.9.2
gunicorn==19.7.1
redis==2.10.6
nltk==3.4.5
pyenchant==2.0.0
pandas
imutils
fuzzywuzzy
celery-with-mongodb
setuptools
google-cloud-vision==1.0.0
PyPDF2
tabula
textblob
wand
pillow
pikepdf
wheel
pdf2image
pdf2text
flask
PyJWT
pymongo
flask_cors
regex
xlwt
xlrd
xlsxwriter
pdftotext
pytesseract
tensorflow
scikit-learn==0.20.3
scikit-image
scipy
seaborn
openpyxl
default-jre
openjdk-11-jre-headless
openjdk-8-jre-headless<file_sep># base image
FROM ubuntu:18.04
RUN apt-get update
RUN apt-get -y install python3.7
RUN apt-get -y install python3-pip
RUN apt-get -y install tesseract-ocr
RUN apt-get -y install libmysqlclient-dev
RUN apt-get -y install enchant
RUN apt-get install -y libsm6 libxext6 libxrender-dev
RUN apt-get install -y libmagickwand-dev
RUN apt-get update && apt-get -y install poppler-utils && apt-get clean
ENV LANG C.UTF-8
# add requirements
COPY ./requirements.txt /usr/src/app/requirements.txt
# set working directory
WORKDIR /usr/src/app
# install requirements
RUN pip3 install -r requirements.txt
# RUN python3 -m spacy download en_core_web_md
# add app
COPY . /usr/src/app
#ENTRYPOINT ["python3","-W","ignore","wsgi.py"]
<file_sep>from flask import request, jsonify, render_template,send_file
from .flaskapp import app
from flask_cors import CORS
import jwt
import json
from pytz import timezone
import datetime
from functools import wraps
import traceback
from src.bank_statement import credit_db
from src.pay_slip import payslip_db
import os
import pandas as pd
import time
import shutil
from src.bank_statement.bank_statement import check_password_new,get_password_status,get_file_name
from src.bank_statement.combining_dataframes import combined_dataframe
from src.bank_statement.calculation_analysis import get_statement_analysis
from src.bank_statement.document_type import get_document_type
from src.bank_statement.localization import get_localization_status
from src.pay_slip.hr_processing import extract_images
import config.config as project_configs
import pprint
from absl import logging
logging._warn_preinit_stderr = 0
logging.warning('Worrying Stuff')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
cors = CORS(app)
basedir = os.path.abspath(os.path.dirname(__file__))
# rel_app_url = "http://0.0.0.0:5005"
# app_url = {"host": "0.0.0.0", "port": 5005}
app.config.update(
UPLOADED_PATH=os.path.join(basedir, 'static', 'data', 'input'),
UPLOADED_PATH_SS=os.path.join(basedir, 'static', 'data', 'ss_input'),
UPLOADED_PATH_NEW=os.path.join(basedir, 'static', 'data', 'temp'))
with open(project_configs.INTAIN_CREDIT_ATTRIBUTE_JSON) as jsFile:
attr_config_dict = json.load(jsFile)
attrs = []
#######################################################################################################################
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
data = request.get_json()
if not data:
data = {}
new_data = request.form
data['token'] = new_data['token']
if data is None:
print("USER Request has no body!")
return jsonify({'message': 'Request has no body!'}), 201
if 'token' in data:
token = data['token']
else:
print("USER Token is missing!!")
return jsonify({'message': 'Token is missing!'}), 201
try:
response = credit_db.get_token(data,'user_registration')
if response == -2:
print("USER Token is invalid!!")
return jsonify({'message': 'Token is invalid'}), 201
registered_user = response['emailid']
secret_key = response['secretkey']
datanew = jwt.decode(token, secret_key)
current_user = datanew['public_id']
if not current_user == registered_user:
return jsonify({'message': 'Not Authorized!'}), 201
except:
print(traceback.print_exc())
return jsonify({'message': 'Token is invalid'}), 201
return f(current_user, *args, **kwargs)
return decorated
########################################################################################################################
def token_required_admin(f):
@wraps(f)
def decorated(*args, **kwargs):
data = request.get_json()
if not data:
data = {}
new_data = request.form
data['token'] = new_data['token']
if data is None:
print("Admin Request has no body!")
return jsonify({'message': 'Request has no body!'}), 201
if 'token' in data:
token = data['token']
else:
print("ADMIN Token is missing!!")
return jsonify({'message': 'Token is missing!'}), 201
try:
registration_type = 'admin_registration'
response = credit_db.get_token(data,registration_type)
if response == -2:
print("ADMIN Token is invalid!!")
return jsonify({'message': 'Token is invalid'}), 201
registered_user = response['emailid']
secret_key = response['secretkey']
datanew = jwt.decode(token, secret_key)
current_user = datanew['public_id']
if not current_user == registered_user:
return jsonify({'message': 'Not Authorized!'}), 201
except:
print(traceback.print_exc())
return jsonify({'message': 'Token is invalid'}), 201
return f(current_user, *args, **kwargs)
return decorated
########################################################################################################################
@app.route('/credit/user_register', methods=['POST'])
def register_user():
data = request.get_json()
print('User register data', data)
if data is None:
return jsonify({'message': 'Request has no body!'}), 201
registration_type = 'user_registration'
response = credit_db.register_user(data, registration_type)
print('response',response)
if response == -1:
return jsonify({'message': 'User Details Missing!'}), 201
elif response == -2:
return jsonify({'message': 'User exists!'}), 201
elif response == -4:
return jsonify({'message': 'Mailing error!'}), 201
return jsonify({'message': 'Registered Successfully!'}), 200
########################################################################################################################
@app.route('/credit/admin_register', methods=['POST'])
def register_admin():
data = request.get_json()
print('regiser', data)
if data is None:
return jsonify({'message': 'Request has no body!'}), 201
registration_type = 'admin_registration'
response = credit_db.register_admin(data, registration_type)
if response == -1:
return jsonify({'message': 'User Details Missing!'}), 201
elif response == -2:
return jsonify({'message': 'User exists!'}), 201
elif response == -4:
return jsonify({'message': 'Mailing error!'}), 201
return jsonify({'message': 'Registered Successfully!'}), 200
######################################################################################################
@app.route('/credit/activate_customer', methods=['GET'])
def activate_customer():
data = request.args
response = credit_db.customer_activate(data)
print('User Testing')
if response == -2:
return jsonify({'message': 'Invalid Company'}), 201
elif response == -1:
return jsonify({'message': 'Invalid User'}), 201
elif response == -3:
return jsonify({'message': 'Company Already Active'}), 201
elif response == -4:
return jsonify({'message': 'Admin Already Active'}), 201
return jsonify({'message': 'Activated Successfully!'}), 200
######################################################################################################
@app.route('/credit/activate_admin', methods=['GET'])
def activate_admin():
data = request.args
response = credit_db.admin_activate(data)
print('Admin Testing')
if response == -2:
return jsonify({'message': 'Invalid Company'}), 201
elif response == -1:
return jsonify({'message': 'Invalid Admin'}), 201
elif response == -3:
return jsonify({'message': 'Company Already Active'}), 201
elif response == -4:
return jsonify({'message': 'Admin Already Active'}), 201
return jsonify({'message': 'Activated Successfully!'}), 200
########################################################################################################################
@app.route('/credit/user_login', methods=['POST'])
def login():
data = request.get_json()
print("Login Data", data)
if data is None:
return jsonify({'message': 'Request has no body!'}), 201
response,secret_key = credit_db.login_user(data)
if response == -1:
return jsonify({'message': 'Email ID or Password Missing!', 'secretkey': secret_key}), 201
elif response == -2:
return jsonify({'message': 'Incorrect Details!', 'secretkey': secret_key}), 201
elif response == -3:
return jsonify({'message': 'Company Inactive!', 'secretkey': secret_key}), 201
token = jwt.encode({'public_id': data['emailid'], 'exp': datetime.datetime.now() +
datetime.timedelta(minutes=600)}, secret_key)
credit_db.update_token(data['emailid'], token.decode('UTF-8'), 'user_registration')
return jsonify({'token': token.decode('UTF-8'), 'firstname': response, 'registration_type': 'user_registration'}), 200
########################################################################################################################
@app.route('/credit/admin_login', methods=['POST'])
def admin_login():
data = request.get_json()
print("Admin login checking", data)
if data is None:
return jsonify({'message': 'Request has no body!'}), 201
response, secret_key = credit_db.login_admin(data)
print("response,", response, secret_key)
if response == -1:
return jsonify({'message': 'Email ID or Password Missing!', 'secretkey': secret_key}), 201
elif response == -2:
return jsonify({'message': 'Incorrect Details!', 'secretkey': secret_key}), 201
elif response == -3:
return jsonify({'message': 'Company Inactive!', 'secretkey': secret_key}), 201
token = jwt.encode({'public_id': data['emailid'], 'exp': datetime.datetime.now() +
datetime.timedelta(minutes=600)}, secret_key)
credit_db.update_token(data['emailid'], token.decode('UTF-8'), 'admin_registration')
return jsonify({'token': token.decode('UTF-8'), 'firstname': response, 'registration_type': 'admin_registration'}), 200
########################################################################################################################
@app.route('/credit/updateprofile', methods=['POST'])
@token_required
def update_profile(current_user):
try:
response = credit_db.profile_update(current_user)
if not response == -2:
return jsonify({'result': response}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'message': 'User does not exist!'}), 201
########################################################################################################################
@app.route('/credit/updateuser', methods=['POST'])
@token_required
def update_user(emailid):
data = request.get_json()
try:
response = credit_db.user_update(emailid, data)
if not response == -2:
credit_db.logout_user(emailid)
return jsonify({'message': 'Successful!'}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'message': 'User does not exist!'}), 201
########################################################################################################################
@app.route('/credit/forgotpassword', methods=['POST'])
def forgotpassword():
data = request.get_json()
if data is None:
return jsonify({'message': 'Request has no body!'}), 201
response = credit_db.forget_password(data)
if response == -1:
return jsonify({'message': 'Email ID Missing!'}), 201
elif response == -2:
return jsonify({'message': 'User does not exist!'}), 201
secret_key = response
token = jwt.encode({'public_id': data['emailid'], 'exp': datetime.datetime.utcnow() +
datetime.timedelta(minutes=5)}, secret_key)
registration_type = 'NULL'
credit_db.update_token(data['emailid'], token.decode('UTF-8'), registration_type)
return jsonify({'token': token.decode('UTF-8')}), 200
########################################################################################################################
@app.route('/credit/resetpassword', methods=['POST'])
@token_required
def resetpassword(current_user):
data = request.get_json()
if 'password' in data:
password = data['password']
else:
return jsonify({'message': 'Password Missing!'}), 201
try:
emailid = current_user
credit_db.reset_password(emailid, password)
credit_db.logout_user(emailid)
credit_db.update_secret(emailid)
except:
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'message': 'Password Updated!'}), 200
########################################################################################################################
@app.route('/credit/logout', methods=['POST'])
@token_required
def logoutuser(current_user):
try:
emailid = current_user
credit_db.logout_user(emailid)
except:
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'message': 'Logged out!'}), 200
#########################################################################################################################
@app.route('/credit/user_dashboard', methods=['POST'])
@token_required
def user_dashboard(current_user):
try:
print("Cheking User Dashboard ")
data = request.get_json()
response = credit_db.user_dashboard_detail(current_user, data)
if not response == -2:
return jsonify({'result': response}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'result': []}), 200
#########################################################################################################################
@app.route('/credit/delete_job_data', methods=['POST'])
@token_required
def delete_job_data(current_user):
try:
data = request.get_json()
job_id = data['job_id']
credit_db.delete_by_job_id(current_user,job_id)
return jsonify({'result': 'Removed successfully'}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'result': []}), 200
#########################################################################################################################
@app.route('/credit/admin_dashboard', methods=['POST'])
@token_required_admin
def admin_dashboard(current_user):
try:
print("Checking Admin Dashboard ")
response = credit_db.admin_dashboard_detail(current_user)
if not response == -2:
return jsonify({'result': response}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'result': []}), 200
#########################################################################################################################
@app.route('/credit/review_admin_dashboard', methods=['POST'])
@token_required_admin
def reviewed_admin_dashboard(current_user):
try:
print("Checking Admin Dashboard ")
response = credit_db.get_reviewed_admin_dashboard(current_user)
if not response == -2:
return jsonify({'result': response}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'result': []}), 200
########################################################################################################################
@app.route('/credit/clear_documents', methods=['POST'])
@token_required
def clear_document(current_user):
try:
if request.method == 'POST':
folder_path = os.path.join(app.config['UPLOADED_PATH_NEW'],current_user)
if not os.path.isdir(folder_path):
os.makedirs(folder_path)
uploaded_files = os.listdir(folder_path)
if uploaded_files:
for f in uploaded_files:
f = os.path.join(folder_path,f)
os.remove(f)
return jsonify({'message': 'Cleared directory!'}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
########################################################################################################################
@app.route('/credit/delete_documents', methods=['POST'])
@token_required
def delete_document(current_user):
try:
if request.method == 'POST':
data = request.get_json()
file_name = data['file_name']
file_path = os.getcwd() + file_name
folder_path = os.path.join(app.config['UPLOADED_PATH_NEW'],current_user)
if not os.path.isdir(folder_path):
os.makedirs(folder_path)
uploaded_files = os.listdir(folder_path)
for f in uploaded_files:
f = os.path.join(folder_path,f)
if f == file_path:
os.remove(f)
return jsonify({'message': 'successful!'}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
########################################################################################################################
@app.route('/credit/upload_documents', methods=['POST'])
@token_required
def upload_document(current_user):
try:
if request.method == 'POST':
uploaded_files = request.files.getlist("file")
print('#######################',uploaded_files,len(uploaded_files))
folder_path = os.path.join(app.config['UPLOADED_PATH_NEW'],current_user)
if not os.path.isdir(folder_path):
os.makedirs(folder_path)
for file2 in uploaded_files:
file_name = file2.filename
file2.save(os.path.join(folder_path, file_name))
new_file_name1 = os.path.join(folder_path, file_name)
new_file_name = new_file_name1.replace("'", "").replace(" ","_")
os.rename(new_file_name1, new_file_name)
break
new_file_name2 = new_file_name.split('hdfc_credit/webserverflask')[-1]
new_file_name = new_file_name.split('/')[-1]
credit_db.save_upload_file(current_user, 'Job__0',new_file_name)
return jsonify({'message': 'Successful!','filename' :new_file_name2 }), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
########################################################################################################################
@app.route('/credit/process_documents', methods=['POST'])
@token_required
def process_document(emailid):
try:
if request.method == 'POST':
data = request.form
print( 'process_documentsdata',data)
applicant_id = data['applicantid']
statementtype = data['statementtype']
company_name = credit_db.get_company_name(emailid)
application_id_resp = credit_db.get_application_id_detail(applicant_id,emailid)
if application_id_resp != -2:
return jsonify({'message': 'applicant id already exits'}), 201
temp_folder_path = os.path.join(app.config['UPLOADED_PATH_NEW'],emailid)
jobid_counter = credit_db.get_jobid(emailid)
folder_name = "bank_statement_" + str(jobid_counter)
folder_path = os.path.join(app.config['UPLOADED_PATH'], folder_name)
if os.path.isdir(folder_path):
shutil.rmtree(folder_path)
os.makedirs(folder_path,mode=0o777)
file_size = 0
uploaded_files = credit_db.get_upload_file(emailid,'Job__0')
temp_files = os.listdir(temp_folder_path)
for f in temp_files:
f = os.path.join(temp_folder_path,f)
shutil.move(f, folder_path)
# uploaded_files = os.listdir(folder_path)
print('uploaded_files >>>>> ',uploaded_files)
if not uploaded_files:
return jsonify({'message': 'Please select a file to upload'}), 201
if len(uploaded_files)>1:
new_file_name = get_file_name(uploaded_files,folder_path)
file = os.stat(os.path.join(folder_path, new_file_name))
file_size += file.st_size
pdf_count = 'multiple'
else:
for file2 in uploaded_files:
new_file_name = os.path.join(folder_path, file2)
file = os.stat(os.path.join(folder_path, file2))
new_file_name = new_file_name.replace("'", "")
file_size += file.st_size
pdf_count = 'single'
if uploaded_files:
job_details = {}
file_size = file_size/1000
job_id = "Job_" + str(jobid_counter)
job_details['emailid'] = emailid
job_details['job_id'] = job_id
job_details['document_name'] = folder_name
format_date = "%Y-%m-%d %H:%M"
now_utc = datetime.datetime.now(timezone('UTC'))
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
job_details['upload_date_time'] = now_asia.strftime(format_date)
job_details['job_size'] = str(file_size) + " kB"
job_details['job_priority'] = 'NULL'
job_details['job_status'] = 'Incomplete'
job_details['pdf_count'] = pdf_count
job_details['file_path'] = new_file_name
job_details['review_status'] = 'No'
job_details['applicant_id'] = applicant_id
job_details['companyname'] = company_name
job_details['statementtype'] = statementtype
try:
text, word_order,bank_name = get_document_type(new_file_name)
except:
print(traceback.print_exc())
text, word_order,bank_name = '' , '', 'Unknown Bank'
job_details['bank_name'] = bank_name.upper()
print("bank_name = {} ,new_file_name = {}".format(bank_name,new_file_name))
localization_status,readable_status,final_output_json = get_localization_status(bank_name,new_file_name)
job_details['localization_status'] = localization_status
job_details['text'] = text
job_details['word_order'] = word_order
job_details['readable_status'] = readable_status
credit_db.insert_job(job_details)
if statementtype == 'scanned':
return jsonify({'message': 'Bank Name is not listed in processing bank list', 'job_id': job_id}), 201
if readable_status == 'non-readable':
return jsonify({'message': 'Bank Name is not listed in processing bank list', 'job_id': job_id}), 201
print('localization_status = {}, statementtype = {}, readable_status = {}'.format(localization_status, statementtype, readable_status))
if localization_status == False or not final_output_json:
return jsonify({'message': 'Bank Name is not listed in processing bank list', 'job_id': job_id}), 201
else:
output_dataframe, bank_type, excel_path, transaction_data = combined_dataframe(bank_name, final_output_json, new_file_name)
calculation_response, calculation_result_list = get_statement_analysis(excel_path, bank_name, bank_type, new_file_name, text, word_order)
new_file_name = new_file_name.split('hdfc_credit/webserverflask')[-1]
excel_path = excel_path.split('/hdfc_credit/webserverflask')[-1]
credit_db.get_single_records(emailid, job_id, new_file_name, output_dataframe,excel_path,
transaction_data, calculation_response,calculation_result_list,bank_type)
return jsonify({'message': 'Successful!', 'new_file_name': new_file_name, 'excel_path': excel_path,'job_id':job_id,'calculation_result_list':calculation_result_list}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Bank Name is not listed in processing bank list', 'job_id': job_id}), 201
# return jsonify({'message': 'Not successful!'}), 201
return render_template('upload_documents.html')
#########################################################################################################################
@app.route('/credit/bank_name_list', methods=['POST'])
@token_required
def bank_name_list(current_user):
try:
df = pd.read_excel(project_configs.INTAIN_BANK_STATEMENT_IFSC_CODE_CSV)
bank_names = []
for index, row in df.iterrows():
x = row['Bank_Name']
bank_names.append(x)
bank_names = sorted(list(set(bank_names)))
return jsonify({'bank_names_list': bank_names}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
############################################################################################################
@app.route('/credit/getdetailsbyid', methods=['POST'])
@token_required
def userGetDetailsByID(current_user):
data = request.get_json()
try:
data = request.get_json()
emailid = current_user
response = credit_db.get_Details_By_ID(emailid, data['job_id'])
print('Get Details By ID',response)
if not response == -2:
return jsonify({'result': response}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'result': []}), 200
############################################################################################################
@app.route('/credit/excel_data', methods=['POST'])
@token_required
def excel_data_by_date(emailid):
data = request.get_json()
try:
data = request.get_json()
day_start_date = data['day_start_date']
day_end_date = data['day_end_date']
response = credit_db.get_excel_data_by_date(emailid,day_start_date,day_end_date)
print('excel data by date',response)
if not response == -2:
return jsonify({'excel_path': response}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'result': []}), 200
############################################################################################################
@app.route('/check_password', methods=['POST'])
def check_password():
folder_path = app.config['UPLOADED_PATH']
response, file_path = check_password_new(folder_path)
return jsonify({'passowrd_check': response, 'file_path': file_path}), 200
@app.route('/enter_password', methods=['POST'])
def enter_password():
data = request.get_json()
password = data['<PASSWORD>']
file_path = data['file_path']
if password == "undefined" or not password:
status = False
else:
status = get_password_status(password, file_path)
return jsonify({'password_status': status, 'file_path': file_path}), 200
@app.route('/credit/pdf_password_localization_status', methods=['POST'])
@token_required_admin
def get_pdf_password_localization_status(current_user):
try:
data = request.get_json()
response = credit_db.get_localization_password_status(data)
if not response == -2:
return jsonify({'localization_status':response[0],'readable_status':response[1]}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful! get_pdf_password_localization_status'}), 201
return jsonify({'result': []}), 200
########################################################################################################################
@app.route('/credit/table_localization', methods=['POST'])
@token_required_admin
def document_attributes(current_user):
try:
data = request.get_json()
response = credit_db.get_localization_details(data)
if not response == -2:
return jsonify({'response': response[0], 'width': response[1], 'height': response[2]}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful! doc_attributes'}), 201
return jsonify({'result': []}), 200
################################################################################################################
@app.route('/credit/table_digitization', methods=['POST'])
@token_required_admin
def get_tablewise_data(current_user):
data = request.get_json()
job_id = data['job_id']
table_coords = data['table_coords']
try:
response = credit_db.get_digitization_details(job_id, table_coords)
if not response == -2:
return jsonify({'response': response}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful'}), 201
return jsonify({'result': []}), 200
################################################################################################################
@app.route('/credit/table_data', methods=['POST'])
@token_required_admin
def get_extraction_get_data(current_user):
data = request.get_json()
job_id = data['job_id']
try:
response = credit_db.save_digitized_data(job_id)
print("RRRRRRRRRR",response)
if not response == -2:
return jsonify({'response': 'Successful!', 'excel': response}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful! extraction_get_data'}), 201
# return jsonify({'result': []}), 200
###############################################################################################
@app.route('/credit/calculations_result', methods=['POST'])
@token_required_admin
def calculations_and_ratios(current_user):
data = request.get_json()
job_id = data['job_id']
try:
response = credit_db.get_calculation_data(job_id)
print(response)
if not response == -2:
return jsonify({'result': response[0],'pdf_file_path': response[3], 'calculation_csv_path': response[1],
'calculation_result_list':response[2],'comment':response[4]}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful! calculations_api'}), 201
return jsonify({'result': []}), 200
###############################################################################################
@app.route('/credit/calculations_result_new', methods=['POST'])
@token_required_admin
def calculations_and_ratios_new(current_user):
data = request.get_json()
job_id = data['job_id']
try:
response = credit_db.get_calculation_data_new(current_user,job_id)
print(response)
if not response == -2:
return jsonify({'result': response['calculation_response'],'pdf_file_path': response['file_name'],
'calculation_csv_path': response['excel_path'],'calculation_result_list':response['calculation_result_list']}), 200
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful! calculations_result_new'}), 201
return jsonify({'result': []}), 200
###############################################################################################
@app.route("/credit/admin_validate", methods=['POST'])
@token_required_admin
def admin_validation_bs(admin_email):
data = request.get_json()
try:
response = credit_db.bs_admin_update_job(admin_email, data)
print(response)
if not response == -2:
return jsonify({'message': 'Successful!'}), 200
except Exception as e:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 401
return jsonify({'message': 'Text-field not in DB!'}), 401
#################################################################################################
############################## Pay Slip API's #################################################
@app.route("/payslip/user_dashboard", methods=['POST'])
@token_required
def fs_payslip_dashboard(current_user):
try:
response = payslip_db.userDashboardDetail(current_user)
if not response == -2:
return jsonify({'result': response}), 200
except Exception as e:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 401
return jsonify({'result': []}), 200
###############################################################################################
@app.route("/payslip/upload", methods=['POST'])
@token_required
def fs_payslip_upload(current_user):
single_uploads = []
try:
payslip_db.delete_null_job(current_user)
freq = request.files
freq = list(freq._iter_hashitems())
emailid = current_user
job_details = {}
jobid_counter = payslip_db.get_jobid(emailid)
folder_name = "Job_" + str(jobid_counter)
folder_path = os.path.join(app.config['UPLOADED_PATH_SS'], folder_name)
print(folder_path)
if os.path.isdir(folder_path):
shutil.rmtree(folder_path)
os.makedirs(folder_path)
total_file_size = 0
print("UPLOADED FILES : ", end="")
for file_ind, (_, files_sent) in enumerate(freq):
file_name = files_sent.filename
file_name = file_name.encode('ascii', 'ignore').decode()
file_name = file_name.replace(" ", "")
print(file_name, end=", ")
splited_text = os.path.splitext(file_name)
file_name = splited_text[0] + "_" + str(file_ind) + splited_text[1]
files_sent.save(os.path.join(folder_path, file_name))
file_stat = os.stat(os.path.join(folder_path, file_name))
total_file_size += file_stat.st_size / 1000
print()
format_date = "%Y-%m-%d %H:%M"
now_utc = datetime.datetime.now(timezone('UTC'))
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
job_details['upload_date_time'] = now_asia.strftime(format_date)
job_details['emailid'] = emailid
job_details['job_id'] = str(jobid_counter)
job_details['document_name'] = "Job_" + str(jobid_counter)
job_details['job_size'] = str(total_file_size) + " kB"
job_details['job_priority'] = 'Medium'
job_details['job_status'] = 'In Process'
job_details['batch_submitted_status'] = False
job_details['admin_submitted'] = False
payslip_db.insert_job(job_details)
return jsonify({
'message': 'Successful!',
'job_id': str(jobid_counter),
'document_name': "Job_" + str(jobid_counter)
}), 200
except Exception as e:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 401
###############################################################################################
@app.route("/payslip/digitize", methods=['POST'])
@token_required
def fs_payslip_digitize(current_user):
data = request.get_json()
try:
emailid = current_user
job_dir_list = payslip_db.digitise_document(emailid, data)
print(job_dir_list)
if not job_dir_list == -2:
extract_images(emailid, job_dir_list[0])
result=payslip_db.batch_submit(emailid,data['job_id'])
if result!=-2:
return jsonify({'message': "Document Submitted Successfully"}), 200
else:
return jsonify({'message': 'Document already Digitised!'}), 401
except Exception as e:
print(traceback.print_exc())
return jsonify({'message':'Documents Not Submitted'}), 401
return jsonify({'message': 'No Data uploaded!'}), 401
###############################################################################################
@app.route("/payslip/download", methods=['POST'])
@token_required
def payslip_download(current_user):
data = request.get_json()
try:
emailid = current_user
result = payslip_db.download_result(emailid, data['job_id'])
if result!=-2:
file_name='Job_'+data['job_id']+'.xlsx'
return send_file(result,attachment_filename=file_name)
except Exception as e:
print(traceback.print_exc())
return jsonify({'message':'Error in File Download'}), 401
return jsonify({'message': 'No File Downloaded!'}), 401
###############################################################################################
@app.route('/payslip/excel_data', methods=['POST'])
@token_required
def aggregate_excel_data(current_user):
data = request.get_json()
try:
data = request.get_json()
day_start_date = data['day_start_date']
day_end_date = data['day_end_date']
response = payslip_db.get_excel_data_by_date(current_user,day_start_date,day_end_date)
if not response == -2:
# return jsonify({'excel_path': response}), 200
return send_file(response,attachment_filename='daily_report.xlsx')
except:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 201
return jsonify({'result': []}), 200
###############################################################################################
@app.route("/payslip/admin_dashboard", methods=['POST'])
@token_required_admin
def payslip_admin_dashboard(admin_email):
try:
response = payslip_db.adminDashboardDetail(admin_email,False)
if not response == -2:
return jsonify({'result': response}), 200
except Exception as e:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 401
return jsonify({'result': []}), 200
###############################################################################################
@app.route("/payslip/admin_submitted_dashboard", methods=['POST'])
@token_required_admin
def payslip_admin_submitted_dashboard(admin_email):
try:
response = payslip_db.adminDashboardDetail(admin_email,True)
if not response == -2:
return jsonify({'result': response}), 200
except Exception as e:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 401
return jsonify({'result': []}), 200
###############################################################################################
def format_review_response(response):
try:
payslip_attrs = attr_config_dict['attrs_payslip']
payslip_attrs_names = attr_config_dict['attrs_names_payslip']
payslip_thres_dict = attr_config_dict['thres_dict_payslip']
payslip_result = []
attrs = []
attrs_names = []
thres_dict = []
# print("response")
# pprint.pprint(response)
for resp in response:
# pprint.pprint(resp)
finalbatchresult = {}
finalbatchresult['fields'] = []
for output in resp['Result']:
fieldslist=[]
# print("output",output)
for j, attr in enumerate(payslip_attrs):
fields = {}
fields['varname'] = attr
fields['label'] = payslip_attrs_names[j]
fields['value'] = output["Output"][attr]
fields['order_id'] = j
fields['confidence_score'] = output["Output"][attr + '_conf']
fields['confidence_score_green'] = payslip_thres_dict[attr + '_thres'] * 100
fields['user_edited'] = 0
fieldslist.append(fields)
Page = {'Result':fieldslist,'file_name':output["image"]}
finalbatchresult['fields'].append(Page)
finalbatchresult['file_name'] = resp['file_name']
#finalbatchresult['fields']['Page_0'] = fieldslist
finalbatchresult['image_path'] = resp['image_path']
finalbatchresult['inv_level_conf'] = 10 # change accordingly
# finalbatchresult['tabledata'], finalbatchresult['tabledetails'] = findEmptyTable()
finalbatchresult['email_id'] = resp['emailid']
payslip_result.append(finalbatchresult)
return payslip_result
except Exception as e:
print(traceback.print_exc())
return []
###############################################################################################
@app.route("/payslip/admin_review_job", methods=['POST'])
@token_required_admin
def admin_review_job(admin_email):
data = request.get_json()
if 'user_email' in data:
emailid = data['user_email']
else:
return jsonify({'message': 'Email Id-Applicant is Missing!'}), 401
try:
response = payslip_db.admin_review_job(emailid,data['job_id'])
if not response == -2:
payslip_result = format_review_response(response)#, doc_type)
return jsonify({'result': payslip_result}), 200
except Exception as e:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 401
return jsonify({'result': []}), 200
###############################################################################################
@app.route("/payslip/admin_validate", methods=['POST'])
@token_required_admin
def admin_validation(admin_email):
data = request.get_json()
try:
#emailid = data['email_id']
response = payslip_db.admin_update(admin_email, data)
print(response)
if not response == -2:
return jsonify({'message': 'Successful!'}), 200
except Exception as e:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 401
return jsonify({'message': 'Text-field not in DB!'}), 401
###############################################################################################
@app.route("/payslip/admin_submit", methods=['POST'])
@token_required_admin
def admin_submit(admin_email):
data = request.get_json()
if 'user_email' in data and 'job_id' in data:
emailid = data['user_email']
jobid=data['job_id']
else:
return jsonify({'message': 'Email Id of Applicant or Job Id is Missing!'}), 401
try:
#emailid = data['email_id']
response = payslip_db.admin_submit(emailid, jobid)
print(response)
if not response == -2:
return jsonify({'message': 'Successful!'}), 200
except Exception as e:
print(traceback.print_exc())
return jsonify({'message': 'Not successful!'}), 401
return jsonify({'message': 'Job cannot be submitted'}), 401
# if __name__ == '__main__':
# app.run(host=app_url["host"], port=app_url["port"])
<file_sep>from datetime import datetime
import time
#import base64
import pickle
import nltk
# import spacy
import traceback
import pandas as pd
from .Pay_Slip import Utilityfunctions,FunctionLibrary,image_orientationandskew_correction
from .Pay_Slip.Testing import salaryslip_detection
from .Pay_Slip.Utilityfunctions import *
import config.config as project_configs
key = project_configs.INTAIN_BANK_STATEMENT_GOOGLE_APPLICATION_CREDENTIALS
def hr_payslip(file_path):
try:
output_folder_path = os.getcwd()+"/webserverflask/static/data/temp/"
# output_folder_path = os.getcwd()
print(file_path,output_folder_path)
out_imPath=image_orientationandskew_correction.orientation_correction(output_folder_path, file_path)
out_image_path=image_orientationandskew_correction.skewcorrect(out_imPath)
df, _ = Utilityfunctions.visionocr(out_image_path, key)
response = salaryslip_detection(out_image_path,df)
# print(response)
data={}
for i in response['Attribute_values']:
data[i['varname']]=i['value']
return(data)
except:
print(traceback.print_exc())
data = {}
data['employer_name'] = "NA"
data['employer_address'] = 'NA'
data['employee_name'] = 'NA'
data['employee_id'] = 'NA'
data['employee_panno'] = 'NA'
data['employee_uanno'] = 'NA'
data['employee_doj'] = 'NA'
data['employee_designation'] = 'NA'
data['bank_accoutnno'] = 'NA'
data['bank_name'] = "NA"
data['periodofpay'] = 'NA'
data['net_salary'] = 'NA'
return data
if __name__ == "__main__":
file_dir="/home/anuja/backup/Dropbox/Datasets/Salary Slip-20200909T060323Z-001/image-test/"
result=pd.DataFrame()
for file_name in os.listdir(file_dir):
response=hr_payslip(file_dir+file_name)
# print(response)
data={}
for i in response['Attribute_values']:
data[i['varname']]=i['value']
data['file']=file_name
print(data)
# print(type(data))
# result=result.append({'file':data['file'],'employer_name':data['employer_name'],'employee_name':data['employee_name'],'net_salary':data['net_salary'],'periodofpay':data['periodofpay']},ignore_index = True)
# print(result)
# excel_path="/home/anuja/backup/Dropbox/Datasets/Salary Slip-20200909T060323Z-001/resultsall.csv"
# writer = pd.ExcelWriter(excel_path,engine='xlsxwriter')
# df.to_excel(writer)
# result.to_csv(excel_path)
<file_sep>from flask import Flask
app = Flask(__name__)
# from .views import *
from .interface_bs_ss import *
def runapp():
# app.debug=True
app.run(host='0.0.0.0', port=5005,threaded=True)
<file_sep>from PIL import Image
from PIL import ExifTags
import pytesseract
import PIL
from pytesseract import Output
import glob
import os
import traceback
import re
import cv2
import numpy as np
from scipy.ndimage import interpolation as inter
def orientation_correction(output_folder_path, input_image_path):
head, tail = os.path.split(input_image_path)
out_imPath= output_folder_path +tail
im = Image.open(input_image_path)
try:
if im._getexif():
exif=dict((ExifTags.TAGS[k], v) for k, v in im._getexif().items() if k in ExifTags.TAGS)
print(exif)
if exif['Orientation'] == 3:
im=im.rotate(180, expand=True)
elif exif['Orientation'] == 6:
im=im.rotate(270, expand=True)
elif exif['Orientation'] == 8:
im=im.rotate(90, expand=True)
try:
newdata = pytesseract.image_to_osd(im, output_type=Output.DICT)
conf=newdata['orientation_conf']
if conf<1:
if newdata['orientation']==180:
im1=im
else:
im1 = im.rotate(360-newdata['orientation'], PIL.Image.NEAREST, expand = 1)
else:
if newdata['orientation']==180:
im1=im
else:
im1 = im.rotate(newdata['orientation'], PIL.Image.NEAREST, expand = 1)
im1.save(out_imPath)
except Exception as e:
im.save(out_imPath)
except Exception as e:
im.save(out_imPath)
finally:
return out_imPath
def find_score(arr, angle):
data = inter.rotate(arr, angle, reshape=False, order=0)
hist = np.sum(data, axis=1)
score = np.sum((hist[1:] - hist[:-1]) ** 2)
return hist, score
def skewcorrect(img_path):
print(img_path)
out_image_path = img_path
img = cv2.imread(img_path,0)
print(type(img))
delta = 1
limit = 5
angles = np.arange(-limit, limit + delta, delta)
scores = []
for angle in angles:
hist, score = find_score(img, angle)
scores.append(score)
best_score = max(scores)
best_angle = angles[scores.index(best_score)]
num_rows, num_cols = img.shape[:2]
rotation_matrix = cv2.getRotationMatrix2D((num_cols / 2, num_rows / 2), best_angle, 1)
img_rotation = cv2.warpAffine(img, rotation_matrix, (num_cols, num_rows), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_REPLICATE)
converted_img = cv2.cvtColor(img_rotation, cv2.COLOR_GRAY2BGR)
cv2.imwrite(out_image_path, converted_img)
return out_image_path
<file_sep>$(document).ready(function () {
sessionStorage.removeItem("file_path")
sessionStorage.removeItem("table_coords");
sessionStorage.removeItem("table_data");
$(document).ajaxStart(function () {
$("#wait2").css("display", "block");
});
$(document).ajaxComplete(function () {
$("#wait2").css("display", "none");
});
$(".imagePlaceholer").hide();
var token = localStorage.getItem("token");
var password = sessionStorage.getItem("password");
var data_attrs = {
"token": token,
"password": <PASSWORD>,
// "file_path":sessionStorage.getItem("file_path")
};
var success2 = {
"url": "check_password",
"headers": {
"content-type": "application/json"
},
"method": "POST",
"processData": false,
"data": JSON.stringify(data_attrs)
}
$("#showPopup").hide();
$.ajax(success2).done(function (data) {
// alert(JSON.stringify(data));
sessionStorage.setItem("file_path", data.file_path);
console.log("check password done",data.result)
if(data.result === true){
// alert("next api hit")
doc_attributes(data);
}else{
// alert("password popup");
$('#myModal').modal('show');
$("#showPopup").show();
}
}).fail(function (data) {
console.log("check password error",data)
});
// var token = "<KEY>";
$('#getpasswordBtn').click(function () {
$('#popupMessage').show();
setTimeout(function(){
$('#myModal').modal('hide');
$('.modal-backdrop').hide();
}, 1500);
// validate signup form on keyup and submit
$("#getPasswordForm").validate({
rules: {
password: "<PASSWORD>"
},
messages: {
password: "<PASSWORD>"
},
submitHandler: function (form) {
var data_attrs = {
"password": document.getElementById("password").value,
"token": token,
"file_path":sessionStorage.getItem("file_path")
};
console.log(JSON.stringify(data_attrs))
var success = {
"url": "doc_attributes",
"headers": {
"content-type": "application/json"
},
"method": "POST",
"processData": false,
"data": JSON.stringify(data_attrs)
}
$.ajax(success).done(function (data) {
// console.log("readable_status", data.readable_status);
// sessionStorage.setItem("readable_status", readable_status);
// sessionStorage.setItem("reduced_percentage", reduced_percentage);
doc_attributes_function(data);
}).fail(function (data) {
});
},
});
});
function doc_attributes(data){
var data_attrs = {
"token": token,
"password": <PASSWORD>,
"file_path":sessionStorage.getItem("file_path")
};
// alert("HI");
$("#wait3").css("display", "block");
console.log(JSON.stringify(data_attrs));
var success = {
"url": "doc_attributes",
"headers": {
"content-type": "application/json"
},
"method": "POST",
"processData": false,
"data": JSON.stringify(data_attrs)
}
$.ajax(success).done(function (data) {
doc_attributes_function(data);
// alert("Hi");
}).fail(function (data) {
console.log("data", data)
$(".imagePlaceholer").show();
if (data.responseJSON.message == "Not successful!") {
};
if (data.responseJSON.message == "Token is invalid!") {
$('#error').show();
$("#error").text("Session expired, It will redirect to login page.", data.responseJSON.message);
setTimeout(function () {
window.location.href = "index.html";
}, 2000);
sessionStorage.removeItem("token");
sessionStorage.clear();
};
});
};
function doc_attributes_function(data){
$("#wait2").css("display", "none");
$("#wait3").css("display", "none");
$(".imagePlaceholer").show();
console.log("data", data);
var imageHeight = data['height']+5;
var imagewidth = data['width'];
var readable_status = data['readable_status'];
var reduced_percentage = data['reduced_percentage'];
// var imagewidth = data['width'];
data = data['response'];
var No_Quotes_string= eval(data);
console.log("No_Quotes_string", No_Quotes_string)
console.log("bank name", No_Quotes_string[0].bank_name)
sessionStorage.setItem("bank_name", No_Quotes_string[0].bank_name);
sessionStorage.setItem("readable_status", readable_status);
sessionStorage.setItem("reduced_percentage", reduced_percentage);
var counter11 = 1
$.each(No_Quotes_string, function (obj, key, i) {
console.log("key.table_data.top", key.table_data[0].top);
var section = $("<div class='items"+obj+"' style='position:relative; margin:50px 0px; border-bottom:2px solid #ccc; height:" + imageHeight+"px;width:" + imagewidth+"px' />");
$(section).append("<div class='images'> <img src='" + key.corrected_imageName + "' /> <input name='item"+ obj+".readable_status' value='"+ readable_status +" ' /> <input name='item"+ obj+".reduced_percentage' value='"+ reduced_percentage +" ' /> <input name='item"+ obj+".bankname' value='"+ key.bank_name +" ' /> <input name='item"+ obj+".documentType' value='"+ key.documentType +"' /> <input name='item"+ obj+".corrected_imageName' value='"+ key.corrected_imageName +" ' /> </div>");
var table = $("<div class='table'/>");
$.each(key.table_data, function(rowIndex, key, object, value) {
console.log("rowIndex + key", rowIndex)
if(rowIndex == 0 ){
var row = $("<div class='DemoOuter"+obj+" demo' style='left:"+ key.left+"px;top:"+ key.top+"px;width:" +key.width+"px;height:"+ key.height+"px"+ " '> <input class='height' id='height' name='item"+ obj+".table_data"+ obj+".height' value='"+ key.height +" ' /> <input class='width' id='width' name='item"+ obj+".table_data"+ obj+".width' value='"+ key.width +" ' /> <input class='left' id='left' name='item"+ obj+".table_data"+ obj+".left' value='"+ key.left +" ' /> <input class='top' id='top' name='item"+ obj+".table_data"+ obj+".top' value='"+ key.top +" ' /> </div>");
$(function () {
$(".DemoOuter"+obj+"")
.draggable({
containment: $(".items"+obj+""),
drag: function (event) {
o = $(this).offset();
p = $(this).position();
$(this).children(".left").val(p.left);
$(this).children(".top").val(p.top);
}
})
.resizable({
// handles: 's',
resize: function (event, ui) {
$(this).children(".height").val($(this).outerHeight());
$(this).children(".width").val($(this).outerWidth());
console.log("11111111",($(this).outerWidth()))
console.log("11111111",($(this).outerHeight()))
}
});
});
} else {
};
$.each(key.colItem, function(key, object, value, i) {
row.append($("<div class='DemoInner demo' style='left:"+ object.left+"px;top:"+ object.top+"px;width:" +object.width+"px;height:"+ object.height+"px"+ " '> <input class='height' id='height' name='item"+ obj+".table_data"+ obj+".colItem"+key+".height' value='"+ object.height +" ' /> <input class='width' id='width' name='item"+ obj+".table_data"+ obj+".colItem"+key+".width' value='"+ object.width +" ' /> <input class='left' id='left' name='item"+ obj+".table_data"+ obj+".colItem"+ key+".left' value='"+ object.left +" ' /> <input class='top' id='top' name='item"+ obj+".table_data"+ obj+".colItem"+ key+".top' value='"+ object.top +" ' /> <div class='remove'>Remove</div></div>"));
$(function () {
$('.DemoInner')
.draggable({
containment: $(".DemoOuter0"),
drag: function (event) {
o = $(this).offset();
p = $(this).position();
$(this).children(".left").val(p.left);
$(this).children(".top").val(p.top);
}
})
.resizable({
handles: 's',
resize: function (event, ui) {
$(this).children(".height").val($(this).outerHeight());
$(this).children(".width").val($(this).outerWidth());
}
});
});
});
table.append(row);
});
// tableDiv.append(table);
if(obj == 0){
var buttontop = key.table_data[0].top - 100;
console.log("key.table_data.top", buttontop);
section.append("<div class='add btn btn-warning' style='position:absolute; top:"+ buttontop+"px;'>Add Column</div> <div style='display:none' id='theCount'></div>");
}
section.append(table);
section.append("<div class='clearfix'/>");
$("#localization_multicol").append(section);
});
var counter = 100;
$('.add').click(function() {
counter++;
$("#theCount").text(counter);
var counterNew = $("#theCount").text();
console.log("added log",counterNew);
$('.items0 .demo:last').after("<div class='DemoAdded demo' style='left:50%; top:0px; width:5px; height:100%;'> <input class='height' id='height' name='item0.table_data0.colItem"+ counterNew+".height' value='100%' /> <input class='width' id='width' name='item0.table_data0.colItem"+ counterNew+".width' value='5px' /> <input class='left' id='left' name='item0.table_data0.colItem"+ counterNew+".left' value='100' /> <input class='top' id='top' name='item0.table_data0.colItem"+ counterNew+".top' value='0px' /> <div class='remove icon'>Remove</div></div>");
$('.DemoAdded')
.draggable({
containment: $(".DemoOuter0"),
drag: function (event) {
o = $(this).offset();
p = $(this).position();
$(this).children(".left").val(p.left);
$(this).children(".top").val(p.top);
}
})
.resizable({
handles: 's',
resize: function (event, ui) {
$(this).children(".height").val($(this).outerHeight());
$(this).children(".width").val($(this).outerWidth());
}
});
$(".remove").click(function() {
$(this).parent().remove();
// alert("Removed");
});
});
$(".remove").click(function() {
$(this).parent().remove();
});
}
$("#wait5").hide();
$('#BtnUpdateLocalizations').click(function () {
$("#wait5").show();
var obj = $("#updateLocalizations").serializeToJSON({
parseFloat: {
condition: ".number,.money"
},
useIntKeysAsArrayIndex: true
});
console.log(obj);
// alert(typeof obj);
var jsonString = obj;
console.log(jsonString);
sessionStorage.setItem("table_coords", JSON.stringify(jsonString));
$("#result").val(jsonString);
// alert(typeof jsonString)
setTimeout(function () {
window.location.href = "table_digitization.html";
}, 3000);
});
});
<file_sep>version: '3.5'
services:
# intain_celery:
# build: .
# container_name: 'intain_celery'
# volumes:
# - '.:/usr/src/app'
# - './data/logs:/usr/src/app/logs'
# command: celery -A celery_tasks.tasks worker --loglevel=info --logfile=data/logs/celery.log
# environment:
# - CELERY_BROKER=mongodb://intain_mongodb:27017/celery
# - CELERY_BACKEND=mongodb://intain_mongodb:27017/celery
# depends_on:
# - intain_mongodb
# intain_celery_monitor:
# build: .
# container_name: 'intain_celery_monitor'
# ports:
# - '5555:5555'
# command: flower -A celery_tasks.tasks --port=5555 --broker=mongodb://intain_mongodb:27017/celery
# depends_on:
# - intain_mongodb
# intain_flask_server:
# build: .
# # image: flask
# container_name: intain_flask_server
# volumes:
# - '.:/usr/src/app'
# command: python run.py
# environment:
# - CELERY_BROKER=mongodb://intain_mongodb:27017/celery
# - CELERY_BACKEND=mongodb://intain_mongodb:27017/celery
# depends_on:
# - intain_mongodb
# ports:
# - '5050:5050'
ind_mongodb:
image: mongo
container_name: 'ind_mongodb'
ports:
- "27017:27017"
volumes:
- "./data/mongodb:/data/db"
<file_sep>from setuptools import setup, find_namespace_packages
setup(name="intain.bactrakai",
version="0.1",
package_dir={'': 'src'},
packages=find_namespace_packages(where='src'))<file_sep>import os
from google.cloud.vision import types
from google.cloud import vision
from pdf2image import convert_from_path
import io,re
import traceback
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import config.config as project_configs
apikey = project_configs.INTAIN_BANK_STATEMENT_GOOGLE_APPLICATION_CREDENTIALS
def pdf2jpg(pdf_file):
try:
c=0
if pdf_file.endswith(".pdf") or pdf_file.endswith(".PDF"):
pages = convert_from_path(pdf_file, 200)
pdf_file = pdf_file[:-4]
for page in pages:
c=c+1
page.save("%s-page%d.jpg" % (pdf_file,pages.index(page)), "JPEG")
return c
except:
return "pdf not found"
def IFSCAttr(lines):
IFSC = "NA"
for l in lines:
if "ifsc" in l.lower():
l_list = l.split(" ")
for l1 in l_list:
if l1[:4].isupper()==True and l1[-3:].isdigit()==True:
IFSC = l1
return IFSC
def DateAttr(lines):
Range = "NA"
# print("Hi")
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
months_SC = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
res_list = []
for l in lines:
if ("from" in l.lower() and "to" in l.lower()) or "period" in l.lower() or "between" in l.lower():
if Range == "NA":
# l_list = re.findall(r'[0-9]{2}/[0-9]{2}/[0-9]{2})|[0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{2}/[0-9]{2}/[0-9]{4}|[0-9]{2}-[0-9]{2}-[0-9]{4}|[0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}|[0-9]{1}\s[A-Za-z]{3}\s[0-9]{4}|[0-9]{2}-[A-Za-z]{3}-[0-9]{4}|[0-9]{1}-[A-Za-z]{3}-[0-9]{4}',l)
l_list = re.findall(r'([0-3]{0,1}[0-9]{1}[-]{1}[0-1]{1}[0-9]{1}[-]{1}[1-2]{1}[09]{1}\d{2})', l)
if len(l_list)!=0:
Range = l_list[0] + " " + "to" + " " + l_list[1]
if Range == "NA":
if "canara bank" not in lines[0].lower():
if "to" in l.lower():
# print("Date6",l)
l_list = re.findall(r'[0-9]{2}/[0-9]{2}/[0-9]{4}|[0-9]{2}/[0-9]{2}/[0-9]{2}|[0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{2}-[0-9]{2}-[0-9]{4}|[0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}|[0-9]{1}\s[A-Za-z]{3}\s[0-9]{4}|[0-9]{2}-[A-Za-z]{3}-[0-9]{4}|[0-9]{1}-[A-Za-z]{3}-[0-9]{4}',l)
# print(l_list)
if len(l_list)==2:
Range = l_list[0] + " " + "to" + " " + l_list[1]
if Range == "NA":
for m in months:
if m in l:
l_list = re.findall(r'[0-9]{2},\s[0-9]{4}',l)
if len(l_list)==2:
# print("Third2")
Range = m + " " + l_list[0] + " " + "to" + " " + m + " " + l_list[1]
if range == "NA" and "period" in l:
# print("Date3")
res = ''
date_list = l.split(" ")
index_of = date_list.index("period")
for i in date_list[index_of+1:]:
res = res + " " + i
Range = res
for i,l in enumerate(lines):
if Range == "NA":
# print("Date4")
if "from" in l.lower() and "to" in lines[i+1].lower():
l1_list = re.findall(r'[0-9]{2}/[0-9]{2}/[0-9]{2}|[0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{2}/[0-9]{2}/[0-9]{4}|[0-9]{2}-[0-9]{2}-[0-9]{4}|[0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}|[0-9]{1}\s[A-Za-z]{3}\s[0-9]{4}|[0-9]{2}-[A-Za-z]{3}-[0-9]{4}|[0-9]{1}-[A-Za-z]{3}-[0-9]{4}',l)
l2_list = re.findall(r'[0-9]{2}/[0-9]{2}/[0-9]{2}|[0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{2}/[0-9]{2}/[0-9]{4}|[0-9]{2}-[0-9]{2}-[0-9]{4}|[0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}|[0-9]{1}\s[A-Za-z]{3}\s[0-9]{4}|[0-9]{2}-[A-Za-z]{3}-[0-9]{4}|[0-9]{1}-[A-Za-z]{3}-[0-9]{4}',lines[i+1])
if len(l1_list)!=0 and len(l2_list)!=0:
Range = l1_list[0] + " " + "to" + " " + l2_list[0]
return Range
def NameAttr(df,lines):
Name = "NA"
temp = lines
name_list = []
# for i,l in enumerate(lines[10]):
# # Axis
# print("lines[10]lines[10]lines[10]lines[10]\n",lines)
# if Name == "NA" or Name == '':
# if "axis" in l.lower():
# print("First13")
# for t in temp:
# if "joint holder" in t.lower():
# Name = lines[1]
for i,l in enumerate(lines):
# VIJAYA BANK
if Name == "NA" or Name == '':
if "VIJAYA BANK" in lines[0:2]:
if "user details" in l.lower():
Name = lines[i+1]
if Name == "NA" or Name == '':
if "AXIS BANK" in lines[0:2]:
if "joint holder" in l.lower():
Name = lines[i-1]
# Kotak mahindra bank
if Name == "NA" or Name == '':
if "kotak mahindra bank" in l.lower():
print("Second1")
if "date" in lines[i+1].lower():
Name = lines[i+2]
elif "page" in lines[i+1].lower():
Name = lines[i+3]
elif "account" not in lines[i+1].lower():
Name = lines[i+1]
Name = re.sub('[^A-Za-z\s]+','',Name)
Name = Name.replace("Period",'').replace("to",'')
# Tamilnad Merchant
if Name == "NA" or Name == '':
if "my transactions" in l.lower():
print("First3")
Name = lines[i+1]
Name = Name.replace("Account",'').replace("Number",'')
if Name == "NA" or Name == '':
if "bank of india" not in lines[0].lower():
if "account type" in l.lower() or "product type" in l.lower():
print("First",l)
if lines[i+1].isupper()==True and "personal" not in lines[i+1].lower():
lines[i+1] = lines[i+1].replace("CUSTOMER",'').replace("DETAILS",'')
Name = lines[i+1]
# Central Bank of India
if Name == "NA" or Name == '':
if "central bank of india" in lines[0].lower():
if "account type" in l.lower() or "product type" in l.lower():
print("First",l)
if lines[i+1].isupper()==True and "personal" not in lines[i+1].lower():
lines[i+1] = lines[i+1].replace("CUSTOMER",'').replace("DETAILS",'')
Name = lines[i+1]
# Indusland bank
if Name == "NA" or Name == '':
name = ''
if "indusland bank" in l.lower() or "induslnd bank" in l.lower() or "indusind bank" in l.lower():
print("Indusland Bank",l)
# print(lines[i+2])
Name = lines[i+2]
if "Address" in Name:
name_list = Name.split(" ")
index_of = name_list.index("Address")
for l1 in name_list[:index_of]:
name = name + " " + l1
Name = name
# RBL BANK
if Name == "NA" or Name == '':
if "accountholder" in l.lower():
print("First6")
l_list = l.split(":")
for l1 in l_list:
l1 = l1.replace("Home",'').replace("Branch",'')
l1 = l1.strip()
if l1.isupper()==True:
Name = l1
break
# Federal bank
if Name == "NA" or Name == '':
if "name and address" in l.lower():
print("First2")
Name = lines[i+1] + " " + lines[i+2]
if Name == "NA" or Name == '':
if "account name" in l.lower() or "customer name" in l.lower():
print("First8")
# print(l)
l = l.replace("Account",'').replace("Name",'').replace("No",'').replace("Customer",'').replace("Nickname",'').replace("Number",'')
print(l)
Name = l
if bool(re.search(r'[0-9]',Name))==True:
Name = "NA"
# Indusland bank
if Name == "NA" or Name == '':
print("Inside")
name = ''
for row in df.itertuples():
# print(row)
if "indusind" in row[1].lower() or "induslnd" in row[1].lower() or "indusland" in row[1].lower():
print("Indusland Bank-2",l)
y_coord = row[3]
mask = df['y0']<y_coord+200
coord_list = df[mask]['word'].tolist()
print(coord_list)
for c in coord_list:
if c.isupper()==True:
name = name + ' ' + c
Name = name
break
# UNION
if Name == "NA" or Name == '':
for i,l in enumerate(lines[:10]):
if "to" in l.lower() and "date:" in l.lower():
print("First4")
Name = lines[i+1]
Name = Name.replace("CD GENRAL",'')
Name = Name.strip()
if Name == "NA" or Name == '':
for l in lines:
if "name" in l.lower() and "branch" in l.lower():
l_list = l.split(":")
for l1 in l_list:
l1 = l1.replace("Branch",'').replace("Name",'')
l1 = l1.strip()
if l1.isupper()==True:
Name = l1
break
for l in lines:
if Name == "NA" or Name == '':
if ("m/s" in l.lower() or "mr" in l.lower() or "mrs" in l.lower() or "ms." in l.lower()) and "generated by" not in l.lower():
print("Firs7",l)
l = l.replace("Account",'').replace("Name",'').replace("No",'').replace("OD Limit",'').replace("Your",'').replace("Details",'').replace("Address",'')
name_list.append(l)
Name = " ".join(n for n in name_list)
if Name == "NA" or Name == '':
if "customer details" in l.lower():
l = l.replace("CUSTOMER DETAILS",'')
Name = l
if Name == "NA" or Name == '':
if "name" in l.lower() and "branch" not in l.lower() and "account" not in l.lower() and "customer" not in l.lower():
print("First11",l)
if ":" in l:
list_ = l.split(":")
for l1 in list_:
if l1.isupper()==True:
Name = l1
else:
print("First12",l)
l1 = l.replace("Name",'')
if l1.isupper()==True:
Name = l1
# ICICI
if Name == "NA" or Name == '':
name = ''
if "account number" in l.lower() and "-" in l:
l_list = l.split("-")
for l1 in l_list:
if l1.isupper()==True:
name = name + " " + l1
Name = name
if ('transactions list') in l.lower() :
l_list = l.split("-")
for l1 in l_list:
if l1.isupper()==True:
name = name + " " + l1
Name = name
# BOI
if Name == "NA" or Name == '':
if "bank of india" in lines[0].lower():
if "name" in l.lower() and "account" in l.lower():
l = l.replace("Account",'').replace("No",'')
print("First20",l)
if ":" in l:
list_ = l.split(":")
for l1 in list_:
if l1.isupper()==True:
Name = l1
else:
print("First21",l)
l1 = l.replace("Name",'')
if l1.isupper()==True:
Name = l1
if Name == "NA" or Name == '':
for i,l in enumerate(lines[:10]):
if "statement of account" in l.lower():
print("First5")
Name = lines[i+1]
Name = Name.strip()
if "account statement" in l.lower() and bool(re.search(r'[0-9]',l))==False:
print("First14",l)
if "as of" in lines[i+1].lower():
Name = lines[i+2]
else:
Name = lines[i+1]
Name = Name.strip()
return Name
def Account_num(lines):
Account = "NA"
for l in lines:
# print("LLL",l)
if "account number" in l.lower() and bool(re.search(r'[0-9]',l))==True and Account == "NA":
print("Account1",l)
l_list = l.split(" ")
for i in l_list:
i = re.sub('[^0-9]+','',i)
if len(i)>=9:
Account = i
elif "account no" in l.lower() and bool(re.search(r'[0-9]',l))==True and Account == "NA":
print("Account2",l)
l_list = l.split(" ")
for i in l_list:
i = re.sub('[^0-9]+','',i)
if len(i)>=9:
Account = i
elif ("account" in l.lower() or 'ccount' in l.lower() or "a/c" in l.lower()) and bool(re.search(r'[0-9]',l))==True and Account == "NA" and "cust id :" not in l.lower() and "a/c type" not in l.lower():
print("Account3",l)
l_list = l.split(" ")
for i in l_list:
i = re.sub('[^0-9]+','',i)
if len(i)>=9:
Account = i
break
elif "number" in l.lower() and bool(re.search(r'[0-9]',l))==True and Account == "NA":
print("Account4",l)
l_list = l.split(" ")
for i in l_list:
i = re.sub('[^0-9]+','',i)
if len(i)>=9:
Account = i
elif "transactions list" in l.lower() and bool(re.search(r'[0-9]',l))==True and Account == "NA":
print("Account5",l)
l_list = l.split(" ")
for i in l_list:
i = re.sub('[^0-9]+','',i)
if len(i)>=9:
Account = i
elif "statement for alc" in l.lower() and bool(re.search(r'[0-9]',l))==True and Account == "NA":
print("Account6",l)
l_list = l.split(" ")
for i in l_list:
i = re.sub('[^0-9]+','',i)
if len(i)>=9:
Account = i
# Indian Overseas bank
for i,l in enumerate(lines):
if "indian overseas bank" in l.lower():
l_list = lines[i+2].split(" ")
for l1 in l_list:
if len(l1)>9 and bool(re.search(r'[0-9]',l1))==True:
Account = l1
return Account
def ocr(image_path,lang_hint,apikey_path):
'''
Accepts image path and language hint
Returns two items:
(i) list of list containing words and their corresponding 4 vertices(x,y)
(ii) blocks of ocr text
'''
bboxes = None
blocks = None
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = apikey_path
vision_client = vision.ImageAnnotatorClient()
try:
with io.open(image_path, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
kwargs = {}
if lang_hint:
kwargs = {"image_context": {"language_hints": ["en", "hi", "mr", "bn", "ta",'te','kn','gu','or']}}
response = vision_client.text_detection(image=image,**kwargs)
texts = response.text_annotations
bboxes = []
for text in texts:
bbox = []
bbox.append(text.description)
for vertice in text.bounding_poly.vertices:
bbox.extend([vertice.x,vertice.y])
bboxes.append(bbox)
document = response.full_text_annotation
paratext = ""
blocktext = ""
blocks = []
for page in document.pages:
for block in page.blocks:
blocktext = ""
for paragraph in block.paragraphs:
paratext = ""
for word in paragraph.words:
strWord = ""
for symbol in word.symbols:
strWord = strWord + symbol.text
paratext = paratext + " " + strWord
# print(strWord)
blocktext = blocktext + " " + paratext
# print(paratext)
blocks.append(blocktext.strip())
except:
traceback.print_exc()
bboxes = None
blocks=None
finally:
return bboxes,blocks
def group_ocr_words(ocr_list,min_word_length=4,line_split=0.8,debug=False):
'''
Accepts word list with coordinates. All eight points of vertices need to be passed
Returns grouped df with line number and word ascending order (bool)
'''
df = pd.DataFrame(ocr_list,columns=('word','x0','y0','x1','y1','x2','y2','x3','y3'))
##############################################################################
# Slope and intercept for each of the words
##############################################################################
df['slope'] = (df['y1']+df['y2']-df['y0']-df['y3'])/(df['x1']+df['x2']-df['x0']-df['x3'])
# Words with len >=4 are considered as significant
slopes = df[df['word'].str.len()>=min_word_length]['slope']
# To remove infinity and outlier slopes; Two iterations of std of slopes
if slopes[np.isinf(slopes)].shape[0] <= slopes.shape[0]//3:
slopes = slopes[~np.isinf(slopes)]
slopes = slopes[abs(slopes - np.mean(slopes)) <= np.std(slopes)]
mean_slope = slopes[abs(slopes - np.mean(slopes)) <= np.std(slopes)].mean()
else:
mean_slope = slopes[np.isinf(slopes)].mode()
mean_slope = mean_slope.tolist()[0]
if np.isinf(mean_slope):
df['intercept'] = df['x0']+df['x1']
else:
df['intercept'] = df['y1']+df['y2']-(mean_slope*(df['x1']+df['x2']))
##############################################################################
# For determining word order and line order
# True - Ascending, False - Descending
##############################################################################
df['x_diff'] = df['x1']>df['x0']
df['y_diff'] = df['y1']>df['y0']
if mean_slope > -1 and mean_slope < 1:
word_order = df[df['word'].str.len()>=min_word_length]['x_diff'].mode()[0]
df['order'] = df['x0']
else:
word_order = df[df['word'].str.len()>=min_word_length]['y_diff'].mode()[0]
df['order'] = df['y0']
if mean_slope > -1 and not np.isinf(mean_slope):
line_order = word_order
else:
line_order = not word_order
##############################################################################
# To separate lines based on the intercept
##############################################################################
scaler = MinMaxScaler()
df['fit'] = scaler.fit_transform(df[['intercept']])
if not line_order:
df['fit'] = 1.0-df['fit']
df = df.sort_values(by=['fit'])
df['fit_diff'] = df['fit'].diff()
mean_diff = df['fit_diff'].mean()
line_no = 1
for index, row in df.iterrows():
if row['fit_diff'] > mean_diff*line_split:
line_no += 1
df.loc[index, 'line'] = line_no
else:
df.loc[index, 'line'] = line_no
if debug:
print(mean_diff,' ',mean_slope)
else:
df = df.drop(['slope','intercept','fit','fit_diff','x_diff','y_diff'],axis=1)
return df,word_order
def generate_lines(df,word_order):
'''
Accepts grouped df and word_order(bool)
Returns list of lines in the df
'''
list_df = [df_g for name_g, df_g in df.groupby('line')]
new_list_df = [l.sort_values('order',ascending=word_order) for l in list_df]
lines = []
for ldf in new_list_df:
line = ' '.join([re.sub(r'[^A-Za-z0-9,.\-\:/ ]','',w) for w in ldf['word'].to_list()]).strip()
if line:
lines.append(line)
return lines
def BS_attributes(filename,df,word_order):
# df = pd.read_csv("/home/anirudh/Documents/AxisBank_cheque/Cheque_final/Result_cheque.csv")
BS_SCHEMA = {
'Account':'',
'Name':'',
'Date':'',
'IFSC':''}
# image_path = filename.split(".pdf")
# image_path = image_path[0] + "-page0" + ".jpg"
# print(image_path)
# file_path_deskewed = imagedeskewing(file_path)
# boxes = ocr(filename,False,apikey)
# print("boxes,boxes",boxes)
# word_order = True
df = pd.read_json(df)
# print(df)
# df,word_order = group_ocr_words(boxes[0][1:])
# print('+++++++++++++++++++++++++++++++++++++++++++',df,'---------------------------------',word_order)
lines = generate_lines(df,word_order)
# print(lines)
Account = Account_num(lines)
Account = re.sub('[^0-9]+','',Account)
Name = NameAttr(df,lines)
dirt_list = ["Branch","No","STATEMENT","OF ","ACCOUNT","Account","Name"]
Name = re.sub('[^a-zA-Z\s,.()]+','',Name)
name_list = Name.split(" ")
for d in dirt_list:
for n in name_list:
if d in n:
name_list.remove(n)
Name = " ".join(name_list)
Name = Name.strip()
Name = Name.replace('MS.','').replace('MR.','')
Name = Name.replace('MS','').replace('MR','')
Range = DateAttr(lines)
IFSC = IFSCAttr(lines)
BS_SCHEMA['Account']=Account
BS_SCHEMA['Name']=Name
BS_SCHEMA['Date']=Range
BS_SCHEMA['IFSC']=IFSC
print("++++++++++++ BS_SCHEMA +++++++++",BS_SCHEMA)
return BS_SCHEMA
# filename = "/home/rahul/workspace/bank_statement_analyser/static/data/input/bank_statement_518/BS_Sample-page0.jpg"
# #c = pdf2jpg(filename)
# BS_attributes(filename) <file_sep>$(document).ready(function () {
$(".parentHorizontalTab").hide();
$(".Identity").hide();
$(".Income").hide();
$(".Unknown").hide();
$("#IdentityWrapper").hide();
$("#IncomeWrapper").hide();
$("#UnknownWrapper").hide();
$(document).ajaxStart(function () {
$("#wait2").css("display", "block");
});
$(document).ajaxComplete(function () {
$("#wait2").css("display", "none");
});
var token = localStorage.getItem("token");
var data_attrs = {
"token": token,
};
console.log(JSON.stringify(data_attrs))
var success = {
"url": "doc_attributes",
"headers": {
"content-type": "application/json"
},
"method": "POST",
"processData": false,
"data": JSON.stringify(data_attrs)
}
$.ajax(success).done(function (data) {
$(".parentHorizontalTab").show();
//console.log("1",JSON.stringify(data));
data = data['result'];
console.log("Full data", JSON.stringify(data));
//console.log("Income", JSON.stringify(data.Income));
sessionStorage.setItem("doc_attributes", JSON.stringify(data));
$.each(data, function (key, value) {
console.log("Key",key);
// console.log("value",value);
// console.log("value PAN",value.PAN);
// console.log("value Aadhar",value.Aadhar);
// console.log("value DL",data.Identity.PAN);
// console.log("Income",data.Income);
// var keyIdentity = key.Identity.length;
// console.log(keyIdentity)
// if (key.Identity == undefined) {
// $(".Identity").show();
// $("#IdentityWrapper").show();
// };
if (key == "Identity") {
$(".Identity").show();
$("#IdentityWrapper").show();
if (data.Identity.PAN != undefined) {
// alert("pann");
$.each(data.Identity.PAN, function (key, value) {
$("#job_details1").css("display", "block");
$('#IdentityOutput1').append("<div class='row "+key+"'> <div class='col-12 col-sm-12 col-md-5 label'>"+key.replace(/_/g, " ")+"</div> <div class='col-12 col-sm-12 col-md-7'> <input type='text' class='form-control' value='"+value+"'> </div> </div> </div> </div> </div>");
if (key == "FILE_PATH") {
$(".FILE_PATH").hide();
$(".imagePath").attr('src',value);
};
if (key == "DOC_TYPE") {
$(".title1").text(value);
};
});
};
if (data.Identity.Aadhar!= undefined) {
// alert("Aadhar");
$.each(data.Identity.Aadhar, function (key, value) {
$("#job_details2").css("display", "block");
$('#IdentityOutput2').append("<div class='row "+key+"'> <div class='col-12 col-sm-12 col-md-5 label'>"+key.replace(/_/g, " ")+"</div> <div class='col-12 col-sm-12 col-md-7'> <input type='text' class='form-control' value='"+value+"'> </div> </div> </div> </div> </div>");
if (key == "FILE_PATH") {
$(".FILE_PATH").hide();
$(".imagePath2").attr('src',value);
};
if (key == "DOC_TYPE") {
$(".title2").text(value);
};
});
};
if (data.Identity.RC!= undefined) {
// alert("RC");
$.each(data.Identity.RC, function (key, value) {
$("#job_details3").css("display", "block");
$('#IdentityOutput3').append("<div class='row "+key+"'> <div class='col-12 col-sm-12 col-md-5 label'>"+key.replace(/_/g, " ")+"</div> <div class='col-12 col-sm-12 col-md-7'> <input type='text' class='form-control' value='"+value+"'> </div> </div> </div> </div> </div>");
if (key == "FILE_PATH") {
$(".FILE_PATH").hide();
$(".imagePath3").attr('src',value);
};
if (key == "DOC_TYPE") {
$(".title3").text(value);
};
});
};
if (data.Identity.DL!= undefined) {
// alert("DL");
$.each(data.Identity.DL, function (key, value) {
$("#job_details4").css("display", "block");
$('#IdentityOutput4').append("<div class='row "+key+"'> <div class='col-12 col-sm-12 col-md-5 label'>"+key.replace(/_/g, " ")+"</div> <div class='col-12 col-sm-12 col-md-7'> <input type='text' class='form-control' value='"+value+"'> </div> </div> </div> </div> </div>");
if (key == "FILE_PATH") {
$(".FILE_PATH").hide();
$(".imagePath4").attr('src',value);
};
if (key == "DOC_TYPE") {
$(".title4").text(value);
};
});
};
};
// console.log("data.Income", data.Income);
if (data.Income != undefined) {
// alert("Income");
$.each(data.Income, function (key, value) {
// console.log("key", key);
// console.log("value", value)
// $("#job_details4").css("display", "block");
$('#FinancialStatement').append("<tr class='"+key+"'> <td class='labelFormat'> "+key.replace(/_/g, " ")+"</td> <td><input type='text' class='form-control' value='"+value+"'></td> </tr>");
if (key == "FILE_PATH") {
$(".FILE_PATH").hide();
$("#FinancialStatementImage").attr('src',value);
};
if (key == "DOC_TYPE") {
$(".title4").text(value);
};
});
};
if (key == "Income") {
$(".Income").show();
$("#IncomeWrapper").show();
};
if (key == "Unknown") {
alert("Unknown Found")
$(".Unknown").show();
$("#UnknownWrapper").show();
};
});
}).fail(function (data) {
// alert("error")
// window.location.assign("upload_documents.html");
$('#error').show();
$("#error").text("Session expired, please wait 2 min, it will redirect to login page.", data.responseJSON.message);
if (data.responseJSON.message == "Token is invalid!") {
setTimeout(function () {
window.location.href = "index.html";
}, 2000);
sessionStorage.removeItem("token");
sessionStorage.clear();
};
});
});<file_sep># hdfc_credit
<file_sep>$(document).ready(function () {
const download_CSV = sessionStorage.getItem('download_CSV');
const bank_name = sessionStorage.getItem('bank_name');
const bank_type = sessionStorage.getItem('bank_type');
const word_order = sessionStorage.getItem('word_order');
const text = JSON.parse(sessionStorage.getItem('text'));
const file_path = sessionStorage.getItem('file_path');
// var data_attrs2 = [{ "bank_name": bank_name }, { "csv_path": download_CSV }, { "bank_type": bank_type }, { "file_path": file_path },{ "text": text },{"word_order":word_order}]
// let data_attrs2 = [{'bank_name': bank_name, 'csv_path': download_CSV, 'bank_type': bank_type, 'file_path': file_path,'text': text,'word_order': word_order}];
// var download_CSV = sessionStorage.getItem("download_CSV")
$('#downloadCSV').attr('href', download_CSV);
const url_string = window.location.href;
const url = new URL(url_string);
const job_id = url.searchParams.get('job_id');
console.log(job_id);
$('#upload_documents').attr('href', 'dashboard.html?job_id=' + job_id);
$('#localization').attr('href', 'localization.html?job_id=' + job_id);
$('#digitization').attr('href', 'table_digitization.html?job_id=' + job_id);
$('#download').attr('href', 'download_data.html?job_id=' + job_id);
$('#calcutions').attr('href', 'calculations.html?job_id=' + job_id);
const token = localStorage.getItem('token');
const data_attrs2 = {
'token': token,
'job_id': job_id,
};
const success = {
'url': 'https://credit.in-d.ai/hdfc_life/credit/calculations_result',
'headers': {
'content-type': 'application/json',
},
'method': 'POST',
'processData': false,
'data': JSON.stringify(data_attrs2),
};
$.ajax(success).done(function (data, textStatus, xhr) {
if (xhr.status === 200) {
console.log("data.pdf_file_path", data.pdf_file_path);
console.log("data.result", data.result);
// console.log("data.result['Total amount spent through payment gateways']", data.result['Total amount spent through payment gateways']);
// console.log("data.result[0]",data.result[0]);
// alert(typeof data.result)
$('.pdfPath').attr('src', "https://credit.in-d.ai/hdfc_life/" + data.pdf_file_path);
$('#downloadCSV2').attr('href', "https://credit.in-d.ai/hdfc_life" + data.calculation_csv_path);
if(typeof data.result == 'string'){
var newdata = data.result.replace(/'/g, '"');
console.log("adasdasda asdasdasd", newdata);
var newObjData= JSON.parse(newdata);
console.log("obj", newObjData);
// alert(typeof data.result)
// const dataparse = JSON.parse(data.result)
// alert(dataparse['01. Account Holder'])
// var newdata = data.result;
// alert(eval(data.result))
// var No_Quotes_string= JSON.parse(newdata);
// "Account Holder": "<NAME>",
// "Account Opening Date": "02-03-2020",
// "Monthly Average Balance": "5555555",
// "Total Salary": "0",
// "Type of Account": "Individual Account"
// alert(No_Quotes_string)
$('#account_holder').val(newObjData['Account Holder']);
$('#total_salary').val(newObjData['Total Salary']);
$('#type_of_account').val(newObjData['Type of Account']);
$('#account_opening_date').val(newObjData['Account Opening Date']);
$('#monthly_average_balance').val(newObjData['Monthly Average Balance']);
} else {
$('#account_holder').val(data.result['Account Holder']);
$('#total_salary').val(data.result['Total Salary']);
$('#type_of_account').val(data.result['Type of Account']);
$('#account_opening_date').val(data.result['Account Opening Date']);
$('#monthly_average_balance').val(data.result['Monthly Average Balance']);
}
} else if (xhr.status === 201) {
alert(JSON.stringify(data.message));
// // location.reload();
} else {
alert(JSON.stringify(data.message));
// // location.reload();
}
}).fail(function (data) {
console.log('data', data);
});
$('#BtnUpdatetableDetaills').click(function () {
sessionStorage.removeItem('table_data');
setTimeout(function () {
window.location.href = 'calculations.html';
}, 1000);
});
$('#validate').click(function () {
// alert("Hi")
const data = {
'token': token,
"job_id": job_id,
"Account Opening Date": $('#account_opening_date').val(),
"Account Holder": $('#account_holder').val(),
"Type of Account": $('#type_of_account').val(),
"Total Salary": $('#total_salary').val(),
"Monthly Average Balance": $('#monthly_average_balance').val(),
"comment": $('#comments').val(),
}
const success = {
'url': 'https://credit.in-d.ai/hdfc_life/credit/admin_validate',
'headers': {
'content-type': 'application/json',
},
'method': 'POST',
'processData': false,
'data': JSON.stringify(data),
};
$.ajax(success).done(function (data, textStatus, xhr) {
console.log("data.pdf_file_path", data.message);
if (xhr.status === 200) {
alert(data.message)
window.location.assign('dashboard.html')
} else if (xhr.status === 201) {
alert(JSON.stringify(data.message));
// // location.reload();
} else {
alert(JSON.stringify(data.message));
// // location.reload();
}
}).fail(function (data) {
console.log('data', data);
});
});
});
<file_sep>import os,time
import re
import cv2
import pytesseract
from pdf2image import convert_from_path
import io
import json
import base64
import sys
from google.cloud import vision
from google.cloud.vision import types
import traceback
import config.config as project_configs
key = project_configs.INTAIN_BANK_STATEMENT_GOOGLE_APPLICATION_CREDENTIALS
def google_ocr(file_name):
try:
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = key
client = vision.ImageAnnotatorClient()
with io.open(file_name, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
kwargs = {"image_context": {"language_hints": ["en", "hi", "mr", "bn", "ta"]}}
response = client.document_text_detection(image=image,**kwargs)
res = response.full_text_annotation
#print(re•••••s)
# print('#####################OCR DF CALLED#######################')
bboxes = []
for page in res.pages:
for block in page.blocks:
for paragraph in block.paragraphs:
p=""
for word in paragraph.words:
w = ""
for symbol in word.symbols:
w+=symbol.text
if w.strip() in ['|','||','| |',':','-']:
continue
bboxes.append([(word.bounding_box.vertices[0].x,word.bounding_box.vertices[0].y),
(word.bounding_box.vertices[2].x,word.bounding_box.vertices[2].y),w])
return (bboxes)
except:
print(traceback.print_exc())
return ""
def sort_bboxes(bboxes):
# cluster lines after sorting based on y-position
lines = {}
for box in bboxes:
key = list(filter(lambda x:x in lines,range(box[0][1]-10,box[0][1]+11)))
if len(key):
key = key[0]
lines[key] += [box]
else:
lines[box[0][1]] = [box]
text=""
for k in lines:
lines[k].sort()
w = ""
for m in lines[k]:
w+=m[2]+" "
#print(w)
text=text+w
return (text)
def get_ocr(filename):
# filename = cv2.imread(filename)
# text = pytesseract.image_to_string(filename)
bboxes = google_ocr(filename)
text=sort_bboxes(bboxes)
# print("1")
#print(text)
text = re.sub('[^A-Z a-z 0-9 -/:]+', '\n', text)
text = re.sub(r'(?m)^\s+', "", text)
#print("********* Start ********\n",text,"\n******** END ********")
# output_directory = os.path.dirname(filename)
# filename = filename.split("/")[-1]
# filename = os.path.splitext(filename)[0]
# txtFileName = os.path.join(output_directory,filename +'.txt')
# with open(txtFileName,'w') as f:
# f.write(text)
return (bboxes,text)
def pdf2jpg(pdf_file):
try:
pages = convert_from_path(pdf_file, 200,first_page=1,last_page=1 ,fmt="jpg")
except:
pages = convert_from_path(pdf_file, 100,first_page=1,last_page=1 ,fmt="jpg")
pdf_file = pdf_file[:-4]
for page in pages:
page.save("%s.jpg" % (pdf_file), "JPEG")
break
print('***** Number of Pages in pdf file: ',len(pages),'*******')
return len(pages)
def pdf2jpg2text(filename):
if filename.endswith('.pdf') or filename.endswith('.PDF'):
pages = pdf2jpg(filename)
coordinates = []
blocks = []
for i in range(pages):
filename = filename.split('.')[:-1]
filename = '.'.join(filename) + '.jpg'
c,b = get_ocr(filename)
coordinates+=c
blocks+=b
# print (coordinates,blocks)
text="".join(blocks)
# print(text)
return (coordinates,text)
else:
return get_ocr(filename)
# if __name__ == "__main__":
# file="/home/anuja/backup/Dropbox/hr/Bactrak_Documents/Employment/PAY/pay-2.jpg"
# bboxes,text=pdf2jpg2text(file)
# print(bboxes,text)<file_sep>import tabula
import pandas as pd
import numpy as np
import traceback
from .correct_df import get_correct_df
from .valid_dataframe_single_page import get_valid_dataframe_single_page
def get_table_data(input_pdf,income_document_image, inputleft, inputtop, inputwidth, inputheight, bank_name,columns_distance_values,reduced_percentage,pdf_file_path):
input_pdf.append(income_document_image)
# reduced_percentage = reduced_percentage.strip()
reduced_percentage = float(reduced_percentage)
page_num = len(input_pdf)
if input_pdf[0].endswith('-page1.jpg'):
page_num += 1
print ('++++ inputleft,inputtop,inputwidth,inputheight == {} ,columns_distance_values == {} -----'.format((inputleft, inputtop, inputwidth, inputheight),columns_distance_values))
top = float(inputtop)/reduced_percentage
left = float(inputleft)/reduced_percentage
bottom = float(inputheight)+float(inputtop)
bottom = float(bottom)/reduced_percentage
right_width = float(inputleft) + float(inputwidth)
right_width = float(right_width)/reduced_percentage
for i, val in enumerate(columns_distance_values):
columns_distance_values[i] = (float(val)/reduced_percentage + float(inputleft)/reduced_percentage)
columns_distance_values = sorted(columns_distance_values)
columns_distance_values = tuple(columns_distance_values)
df = tabula.read_pdf(pdf_file_path, guess=False, pages= page_num , silent=True,
pandas_options={
'header': None,
'error_bad_lines': False,
'warn_bad_lines': False
}, encoding="utf-8",area = (top,left,bottom,right_width), columns = columns_distance_values)
try:
rows = df.values.tolist()
df = pd.DataFrame(rows)
bank_name = bank_name.strip()
if bank_name == "CANARA BANK" or bank_name == "BANK OF WIKI" or bank_name=="HDFC BANK":
df = get_valid_dataframe_single_page(df,bank_name,page_num)
except:
df = pd.DataFrame()
return df
def get_direct_table_data(pdf_file,page_count,bank_name):
pagewise_dataframes = []
for page_number in range(1,page_count+1):
print('Statement is processing for page number : ',page_number)
try:
df = get_page_df(pdf_file,bank_name,page_number)
print(" DataFrame for page number {} is\n".format(page_number),df)
except:
print(traceback.print_exc())
df = pd.DataFrame()
if isinstance(df, pd.DataFrame):
if not df.empty:
df = get_correct_df(df,bank_name)
pagewise_dataframes.append(df)
final_data = pd.concat(pagewise_dataframes, ignore_index = True)
print("++++++++++++++++++++++++ final Data ++++++++++++++++++++++++\n",final_data)
return final_data
def get_page_df(pdf_file,bank_name,page_number):
if bank_name == 'ICICI BANK':
df = tabula.read_pdf(pdf_file,index= False,pages = page_number,multiple_tables=True,pandas_options={
'header': None,
})
count_row0 = df[0].shape[0]
if len(df)==3:
count_row1 = df[1].shape[0]
count_row2 = df[2].shape[0]
elif len(df)==2:
count_row1 = df[1].shape[0]
if count_row1>count_row0:
df = df[1]
else:
df = df[0]
else:
df = df[0]
elif bank_name == 'KARUR VYSYA BANK':
df = tabula.read_pdf(pdf_file,index= False,pages = page_number,multiple_tables=True,pandas_options={
'header': None,
})
count_row0 = df[0].shape[0]
if len(df)==2:
count_row1 = df[1].shape[0]
if count_row1>count_row0:
df = df[1]
else:
df = df[0]
else:
df = df[0]
elif bank_name == 'UJJIVAN SMALL FINANCE BANK':
df = tabula.read_pdf(pdf_file,index= False,pages = page_number,multiple_tables=True,pandas_options={
'header': None,
})
try:
count_row0 = df[0].shape[0]
if len(df)==2:
count_row1 = df[1].shape[0]
if count_row1>count_row0:
df = df[1]
else:
df = df[0]
else:
df = df[0]
except:
df = pd.DataFrame()
elif bank_name == 'BANDHAN BANK':
df = tabula.read_pdf(pdf_file,index= False,pages = page_number,multiple_tables=True,pandas_options={
'header': None,
})
try:
count_row0 = df[0].shape[0]
if len(df)==2:
count_row1 = df[1].shape[0]
if count_row1>count_row0:
df = df[1]
else:
df = df[0]
else:
df = df[0]
except:
df = pd.DataFrame()
elif bank_name == 'BANK OF BARODA':
df = tabula.read_pdf(pdf_file,index= False,pages = page_number,multiple_tables=True,pandas_options={
'header': None,
})
try:
count_row0 = df[0].shape[0]
# print(" ",len(df),'\n',df)
if len(df)==3:
count_row1 = df[1].shape[0]
count_row2 = df[2].shape[0]
elif len(df)==2:
count_row1 = df[1].shape[0]
if count_row1>count_row0:
df = df[1]
else:
df = df[0]
else:
df = df[0]
except:
df = pd.DataFrame()
elif bank_name == "AXIS BANK":
df = tabula.read_pdf(pdf_file,index= False,pages = page_number,pandas_options={
'header': None,
'error_bad_lines': False,
'warn_bad_lines': False
})
bank_name_list = []
if page_number == 1 and df.shape[1] == 8:
if str(df.loc[0][7]) == 'Branch Name':
bank_name = "AXIS BANK A"
bank_name_list.append(bank_name)
else:
bank_name = "AXIS BANK"
bank_name_list.append(bank_name)
else:
bank_name_list.append(bank_name)
bank_name = bank_name_list[0]
elif bank_name == 'HDFC BANK':
df = tabula.read_pdf(pdf_file,index= False,pages = page_number,multiple_tables=True,pandas_options={
'header': None,
})
count_row0 = df[0].shape[0]
if len(df)==3:
count_row1 = df[1].shape[0]
count_row2 = df[2].shape[0]
elif len(df)==2:
count_row1 = df[1].shape[0]
if count_row1>count_row0:
df = df[1]
else:
df = df[0]
else:
df = df[0]
elif bank_name == 'DBS BANK':
if page_number >2:
df = tabula.read_pdf(pdf_file,index= False,pages = page_number,pandas_options={
'header': None,
'error_bad_lines': False,
'warn_bad_lines': False
})
else:
df = pd.DataFrame()
else:
df = tabula.read_pdf(pdf_file,index= False,pages = page_number,pandas_options={
'header': None,
'error_bad_lines': False,
'warn_bad_lines': False
})
if df is None:
df = pd.DataFrame()
return df
# data = df.dropna(axis='columns', how='all')<file_sep>import pandas as pd
import xlrd
import os
from google.cloud import vision
from google.cloud.vision import types
from scipy.ndimage import interpolation as inter
import numpy as np
import io
import cv2
from wand.image import Image, Color
import gc
import traceback
import config.config as project_configs
key = project_configs.INTAIN_BANK_STATEMENT_GOOGLE_APPLICATION_CREDENTIALS
########################################################################################################################
def skewcorrect(img_path):
out_image_path = img_path
img = cv2.imread(img_path,0)
def find_score(arr, angle):
data = inter.rotate(arr, angle, reshape=False, order=0)
hist = np.sum(data, axis=1)
score = np.sum((hist[1:] - hist[:-1]) ** 2)
return hist, score
delta = 1
limit = 5
angles = np.arange(-limit, limit + delta, delta)
scores = []
for angle in angles:
hist, score = find_score(img, angle)
scores.append(score)
best_score = max(scores)
best_angle = angles[scores.index(best_score)]
# print('Best angle', best_angle)
#correct skew
num_rows, num_cols = img.shape[:2]
rotation_matrix = cv2.getRotationMatrix2D((num_cols / 2, num_rows / 2), best_angle, 1)
img_rotation = cv2.warpAffine(img, rotation_matrix, (num_cols, num_rows), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_REPLICATE)
converted_img = cv2.cvtColor(img_rotation, cv2.COLOR_GRAY2BGR)
cv2.imwrite(out_image_path, converted_img)
########################################################################################################################
def wandPdfSplit(filename, output_path):
try:
all_pages = Image(filename=filename, resolution=300)
for i, page in enumerate(all_pages.sequence):
with Image(page) as img:
img.format = 'jpg'
img.background_color = Color('white')
img.alpha_channel = 'remove'
image_filename = os.path.splitext(os.path.basename(filename))[0]
image_filename = '{}_{}.jpg'.format(image_filename, i)
image_filename = os.path.join(output_path, image_filename)
img.save(filename=image_filename)
skewcorrect(image_filename)
num_images = len(all_pages.sequence)
del all_pages
gc.collect()
return num_images
except:
print(traceback.print_exc())
return -1
########################################################################################################################
def visionocr(imagein, csvfile, outputFilePath, outputFilePath_Coords):
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = key
client = vision.ImageAnnotatorClient()
with io.open(imagein, 'rb') as image_file:
content = image_file.read()
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
image = types.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations
document = response.full_text_annotation
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
with open(csvfile, 'w') as file:
for text in texts[1:]:
vertices = (['{}\t{}'.format(vertex.x, vertex.y) for vertex in text.bounding_poly.vertices])
file.write(str(text.description).replace('"', '') + '\t' + '\t'.join(vertices) + '\n')
file.close()
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
file = open(outputFilePath, "w", encoding="utf-8")
fileWords = open(outputFilePath_Coords, "w", encoding="utf-8")
bounds = []; words = []; paragraphs = []
for page in document.pages:
for block in page.blocks:
for paragraph in block.paragraphs:
strPara = ""; coordinates = ""
for word in paragraph.words:
strWord = ""
for symbol in word.symbols:
strWord = strWord + symbol.text
x1y1 = str(word.bounding_box.vertices[0].x) + "," + str(word.bounding_box.vertices[0].y)
x2y2 = str(word.bounding_box.vertices[2].x) + "," + str(word.bounding_box.vertices[2].y)
coords = [x1y1, x2y2]
strCoords = "|".join(coords)
words.append(strWord)
strPara = strPara + " " + strWord
coordinates = coordinates + "@#@" + strCoords
bounds.append(word.bounding_box)
coordinates = coordinates[3:]
strPara = strPara[1:]
fileWords.write(strPara + "<-->" + coordinates + "\n")
file.write(strPara + "\n")
paragraphs.append(strPara)
file.close(); fileWords.close()
########################################################################################################################
def readcsv(csvfile):
df = pd.read_csv(csvfile, names=['Token', 'x0', 'y0', 'x1', 'y1', 'x2', 'y2', 'x3', 'y3'], delimiter='\t')
df['Token'] = df['Token'].astype(str)
return df
###############################################################################################
def getDataFromXL(path, sheet_index, column_number): # To read data from *.xlsx file
workbook = xlrd.open_workbook(path)
worksheet = workbook.sheet_by_index(sheet_index)
list_word = []
for row in range(1, worksheet.nrows):
row_value = worksheet.cell_value(row, column_number)
if not str(row_value).strip() == "NA":
list_word.append(str(row_value).strip())
return list_word
###############################################################################################
def addheight(dataframe):
docDF = dataframe
for index, row in docDF.iterrows():
height = max(row['y2'], row['y3']) - min(row['y0'], row['y1'])
docDF.loc[index, 'ht'] = height
maxW = max(row['x3'], row['x1'])
docDF.loc[index, 'maxW'] = maxW
return docDF
###############################################################################################
def addrownoNew(dataframe):
docDF = dataframe
docDF = docDF.sort_values(by=['y0'])
lineStartNo = 1
currenLIneNo = lineStartNo
row_iterator = docDF.iterrows()
loc , first = next(row_iterator)
docDF.loc[loc, 'linNo'] = currenLIneNo
y_min = min(first['y0'], first['y1'])
ht = first['ht']
for index, row in row_iterator:
if y_min-5 <= row['y0'] < y_min+ht:
docDF.loc[index, 'linNo'] = currenLIneNo
else:
currenLIneNo = currenLIneNo + 1
docDF.loc[index, 'linNo'] = currenLIneNo
y_min = min(row['y0'], row['y1'])
ht = row['ht']
return docDF
###############################################################################################
def ParaCode(df, paracsvfile):
docDF = df
docDF = addheight(dataframe=docDF)
docDF = addrownoNew(dataframe=docDF)
docDF.fillna(0, inplace=True)
####To sort data with respect to line no and x0
docDF = docDF.sort_values(by=['linNo', 'x0'])
###To find out the space
docDF['x0_shift'] = docDF.x0.shift(periods=-1)
docDF['xdiff'] = (docDF['x0_shift'] - docDF['maxW'])
docDF['xdiff'] = docDF.xdiff.shift(periods=1)
docDF = docDF.assign(xdiff=lambda x: x.xdiff.where(x.xdiff.ge(0)))
docDF.fillna(0, inplace=True)
medianxdiff = docDF['xdiff'].median()
medianxdiff = int(medianxdiff)
newdf = docDF.groupby('linNo')
newdf.fillna(0, inplace=True)
with open(paracsvfile, 'w') as file:
for linNo, linNo_df in newdf:
for index, row in linNo_df.iterrows():
space = row['xdiff']
space = int(space)
text = row['Token']
newLineSpace = row['x0']
newLineSpace = int(newLineSpace)
if medianxdiff == 0:
medianxdiff = 12
if space == 0:
file.write(' ' * round(newLineSpace / medianxdiff) + str(text) + ' ')
else:
file.write(' ' * round(space / medianxdiff) + str(text) + ' ')
file.write('\n')
file.close()
df = pd.read_csv(paracsvfile, delimiter='\t', sep=None, header=None,error_bad_lines=False)
pd.set_option('display.max_colwidth', -1)
return df
###############################################################################################
def cleantext(text):
cleanedtext = []
for text in text:
text = text.split()
cleaned_string = []
for text in text:
text = text.strip()
cleaned_string.append(text)
cleaned_string = ' '.join(cleaned_string)
cleanedtext.append(cleaned_string)
return cleanedtext
###############################################################################################
def extracttext(df):
df = df.replace(' ', ' ', regex=True)
df = df.astype(str)
textlist = df[0].values
cleanedtext = cleantext(textlist)
text = ' '.join(cleanedtext)
return text #cleanedtext textlist,
###############################################################################################
<file_sep>import os
from PyPDF2 import PdfFileReader, PdfFileWriter
from pdf2image import convert_from_path
def decrypt_pdf(input_path, output_path, password):
with open(input_path, 'rb') as input_file, \
open(output_path, 'wb') as output_file:
reader = PdfFileReader(input_file)
reader.decrypt(password)
writer = PdfFileWriter()
for i in range(reader.getNumPages()):
writer.addPage(reader.getPage(i))
writer.write(output_file)
def number_of_pages(file_path):
try:
pdf = PdfFileReader(open(file_path,'rb'))
page_count = pdf.getNumPages()
return page_count
except:
pages = convert_from_path(file_path,200)
return len(pages)
def get_valid_format(bank_name,data):
temp = []
total_result = []
for key in data.keys():
temp.append(data[key])
number_of_pages = len(temp)
for index,item in enumerate(temp):
bankname = bank_name
documentType = item["documentType"]
corrected_imageName = item["corrected_imageName"]
table_data = []
initial_result = []
final_output = {}
new_dict = {}
final_result = {}
if 1 < index < number_of_pages-1:
xxxx = temp[1]
xxxx.update({'corrected_imageName': corrected_imageName})
item = xxxx
value_at_index = list(list(item.items())[3])
new_dict= value_at_index[1]
for x in new_dict:
initial_result.append(new_dict[x])
final_output["left"] = new_dict["left"]
final_output["top"] = new_dict["top"]
final_output["width"] = new_dict["width"]
final_output["height"] = new_dict['height']
column_list = []
length_initial_result = len(initial_result)
if len(initial_result) > 4:
for i in range(4,length_initial_result):
column_list.append(initial_result[i])
final_output["colItem"] = column_list
# print("index -----++ {} ++---------".format(index),final_output)
table_data.append(final_output)
final_result["bank_name"] = bankname
final_result["documentType"] = documentType
final_result["corrected_imageName"] = corrected_imageName
final_result["table_data"] = table_data
else:
value_at_index = list(list(item.items())[3])
new_dict = value_at_index[1]
for x in new_dict:
initial_result.append(new_dict[x])
final_output["left"] = new_dict["left"]
final_output["top"] = new_dict["top"]
final_output["width"] = new_dict["width"]
final_output["height"] = new_dict['height']
column_list = []
length_initial_result = len(initial_result)
if len(initial_result) > 4:
for i in range(4,length_initial_result):
column_list.append(initial_result[i])
final_output["colItem"] = column_list
# print("index ------- {} -----------".format(index),final_output)
table_data.append(final_output)
final_result["bank_name"] = bankname
final_result["documentType"] = documentType
final_result["corrected_imageName"] = corrected_imageName
final_result["table_data"] = table_data
total_result.append(final_result)
# print(total_result)
return total_result<file_sep>$(document).ready(function() {
$('#success').hide();
$('#error').hide();
$(document).ajaxStart(function() {
$('#wait2').css('display', 'block');
});
$(document).ajaxComplete(function() {
$('#wait2').css('display', 'none');
});
$('#registerBtn').click(function() {
$('#regsiterForm').validate({
rules: {
firstname: 'required',
lastname: 'required',
password: {
required: true,
minlength: 5,
},
cpassword: {
required: true,
minlength: 5,
equalTo: '#password',
},
emailid: 'required',
phone: 'required',
companyname: 'required',
jobtitle: 'required',
question: 'required',
answer: 'required',
},
messages: {
firstname: 'Please enter your first name',
lastname: 'Please enter your last name',
password: {
required: 'Please enter your password',
minlength: 'Your password must be at least 8 characters long',
},
cpassword: {
required: 'Please enter your confirm password',
minlength: 'Your password must be at least 8 characters long',
equalTo: 'Please enter same Password',
},
emailid: 'Please enter your email id',
phone: 'Please enter your phone number',
companyname: 'Please enter your company name',
jobtitle: 'Please enter your job title',
question: 'Please select your question',
answer: 'Please enter your answer',
},
submitHandler: function(form) {
const data_attrs = {
'firstname': document.getElementById('firstname').value,
'lastname': document.getElementById('lastname').value,
'password': document.getElementById('password').value,
'emailid': document.getElementById('emailid').value,
'phone': document.getElementById('phone').value,
'companyname': document.getElementById('companyname').value,
'jobtitle': document.getElementById('jobtitle').value,
'question': document.getElementById('question').value,
'answer': document.getElementById('answer').value,
};
console.log(JSON.stringify(data_attrs));
const success = {
'url': 'https://credit.in-d.ai/hdfc_life/credit/admin_register',
'headers': {
'content-type': 'application/json',
},
'method': 'POST',
'processData': false,
'data': JSON.stringify(data_attrs),
};
$.ajax(success).done(function(data, textStatus, xhr) {
if (xhr.status === 200) {
console.log('Return' + JSON.stringify(data));
$('#success').show();
$('#success').text(data.message);
$('#regsiterForm').trigger('reset');
// console.log("Return" + JSON.stringify(data.message));
$('#success').fadeTo(5000, 3000).slideUp(500, function() { });
} else if (xhr.status === 201) {
alert(JSON.stringify(data.message));
// location.reload();
} else {
alert(JSON.stringify(data.message));
// location.reload();
}
}).fail(function(data, textStatus, xhr) {
$('#error').show();
$('#error').text(data.responseJSON.message);
// console.log(data);
$('#error').fadeTo(5000, 3000).slideUp(500, function() {
});
if (data.responseJSON.message == 'Token is invalid!') {
setTimeout(function() {
window.location.assign('index.html');
}, 2000);
localStorage.removeItem('token');
sessionStorage.clear();
};
});
},
});
});
});
<file_sep>import numpy as np
import os
import sys
import tensorflow as tf
import io
import re
import pandas as pd
from collections import defaultdict
from io import StringIO
from PIL import Image
from google.cloud import vision
from google.cloud.vision import types
from utils import ops as utils_ops
# This is needed to display the images.
from utils import label_map_util
from utils import visualization_utils as vis_util
# What model to download.
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = 'frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('trial_label_map.pbtxt')
NUM_CLASSES = 10
print('Loading model')
detection_graph = tf.Graph()
with detection_graph.as_default():
# od_graph_def = tf.GraphDef()
od_graph_def = tf.compat.v1.GraphDef()
# with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
with tf.compat.v2.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
print('Model loaded successfully.')
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,use_display_name=True)
category_index = label_map_util.create_category_index(categories)
def image_resize(img):
basewidth = 700
# img = Image.open('somepic.jpg')
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
return img
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
def get_cords(output_dict, image, label):
label_index = np.isin(output_dict['detection_classes'], label)
boxes_data = output_dict['detection_boxes'][label_index]
# output_dict['detection_classes'] = output_dict['detection_classes'][label_index]
boxes_score = output_dict['detection_scores'][label_index]
boxes = np.squeeze(boxes_data)
scores = np.squeeze(boxes_score)
# set a min thresh score, say 0.8
min_score_thresh = 0.85
bboxes = boxes[scores > min_score_thresh]
# get image size
im_width, im_height = image.size
final_box = []
for box in bboxes:
ymin, xmin, ymax, xmax = box
final_box.append([xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height])
final_box = sorted(final_box, key=lambda x: x[0])
return final_box
def visionocr(imagePath, apikey):
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = apikey
client = vision.ImageAnnotatorClient()
with io.open(imagePath, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
# Performs text detection on image
# kwargs = {"image_context": {"language_hints": ["en", "hi", "mr", "bn", "ta"]}}
# response = client.document_text_detection(image, **kwargs)
response = client.text_detection(image)
texts = response.text_annotations
imvertices = []
resp = ''
for text in texts[1:]:
vertices = (['{}\t{}'.format(vertex.x, vertex.y) for vertex in text.bounding_poly.vertices])
vertices = ' '.join(vertices)
vertices = vertices.split()
vertices = [int(x) for x in vertices]
vertices.insert(0, text.description)
imvertices.append(vertices)
resp += re.sub('[^A-Za-z0-9]+', ' ', str(text.description)) + ' '
df = pd.DataFrame(imvertices, columns=['Token', 'x0', 'y0', 'x1', 'y1', 'x2', 'y2', 'x3', 'y3'])
textlist = resp.split()
# print('===============text list================')
# print(textlist)
# print('===============text list================')
return df, textlist
def extract_table(df, table_cords):
df = df.sort_values(by=['x0', 'y0'])
table_cords = table_cords[0]
x0 = int(table_cords[0]) - 10
x1 = int(table_cords[1]) + 10
y0 = int(table_cords[2])
y1 = int(table_cords[3])
tabledf = df[(df['x0'] > x0) & (df['y0'] > y0) & (df['x2'] < x1) & (df['y2'] < y1)]
# print('*******************8')
# print(tabledf)
return tabledf
def add_col(tabledf, column_cords):
columnNo = 0
tabledf = tabledf.sort_values(by=['x0', 'y0'])
for columnNo, i in enumerate(column_cords):
tabledf.loc[tabledf['x0'] > int(i[0]), 'columnNo'] = columnNo + 1
return tabledf
def addrowno(dataframe):
docDF = dataframe
docDF = docDF.sort_values(by=['y0']) # type: object
docDF['ydiff'] = docDF['y0'].diff()
meanYDiff = docDF['ydiff'].mean()
lineStartNo = 1
currenLIneNo = lineStartNo
for index, row in docDF.iterrows():
if row['ydiff'] > meanYDiff:
currenLIneNo = currenLIneNo + 1 # type: Union[int, Any]
docDF.loc[index, 'linNo'] = currenLIneNo
else:
docDF.loc[index, 'linNo'] = currenLIneNo
return docDF
def run_inference_for_single_image(image, graph):
with graph.as_default():
with tf.Session() as sess:
# Get handles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes',
'detection_masks']:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)
if 'detection_masks' in tensor_dict:
# The following processing is only for single image
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, image.shape[0], image.shape[1])
detection_masks_reframed = tf.cast(
tf.greater(detection_masks_reframed, 0.5), tf.uint8)
# Follow the convention by adding back the batch dimension
tensor_dict['detection_masks'] = tf.expand_dims(detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
# Run inference
output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)})
# all outputs are float32 numpy arrays, so convert types as appropriate
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.uint8)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
return output_dict
def table_reconstruct(tabledf):
tabledf = tabledf.sort_values(['linNo', 'columnNo'])
rowdf = tabledf.groupby('linNo')
rowdf.fillna(0, inplace=True)
lines = []
for linNo, linNo_df in rowdf:
column_iter = 1
final_text = []
# print(linNo_df)
coldf = linNo_df.groupby('columnNo')
for columnNo, column_df in coldf:
textline = []
# print(columnNo)
for index, space in column_df.iterrows():
# print(text)
text = column_df['Token'].get(index)
textline.append(text)
textline = [' '.join(textline)]
if columnNo - column_iter != 0:
for i in range(int(columnNo - column_iter)):
final_text.append(' ')
column_iter += 1
final_text.append(textline[0])
# print(final_text)
column_iter += 1
lines.append(final_text)
final_table = pd.DataFrame(lines)
return final_table
def table_detection(image_path):
# imagename = image_path.split('/')[-1]
# print(imagename)
# savepath = path + imagename
table_label = [5]
tablehead_label = [10]
label = [5,10]
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
# Actual detection.
output_dict = run_inference_for_single_image(image_np, detection_graph)
label_index = np.isin(output_dict['detection_classes'], label)
x = output_dict['detection_boxes'][label_index]
y = output_dict['detection_classes'][label_index]
z = output_dict['detection_scores'][label_index]
table_cords = get_cords(output_dict, image, table_label)
tablehead_cords = get_cords(output_dict, image, tablehead_label)
if table_cords and tablehead_cords:
# df, _ = visionocr(image_path, 'apikey.json')
# tabledf = extract_table(df, table_cords)
# tabledf = addrowno(tabledf)
# tabledf = add_col(tabledf, column_cords)
# # print(tabledf)
# final_table = table_reconstruct(tabledf)
table_cords=table_cords
tablehead_cords=tablehead_cords
else:
print('Coordinates not detected')
table_cords=''
tablehead_cords=''
# Visualization of the results of a detection.
image = vis_util.visualize_boxes_and_labels_on_image_array(image_np, x, y, z, category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True, line_thickness=2)
# plt.figure(figsize=IMAGE_SIZE)
# plt.imshow(image_np)
# count+=1
im = Image.fromarray(image)
im = image_resize(im)
im.show()
return table_cords,tablehead_cords
image_path = '/home/jyoti/Desktop/BankDetails/sample/satatement_images/axis-1.jpg'
table = table_detection(image_path)
print(table)
<file_sep>from .tabula_pdf import get_direct_table_data
from .bank_statement import get_readable_status
from .function_library import number_of_pages
import pandas as pd
import traceback
import config.config as project_configs
localization_bank = project_configs.INTAIN_BANK_STATEMENT_LOCALIZATION_BANK_CSV
def get_localization_status(bank_name,pdf_file_name):
if pdf_file_name.endswith('.pdf') or pdf_file_name.endswith('.PDF'):
readable_status = get_readable_status(pdf_file_name)
page_count = number_of_pages(pdf_file_name)
if readable_status == 'non-readable':
return False,readable_status,[]
localization_banks = pd.read_csv(localization_bank,header=None)
for index, row in localization_banks.iterrows():
if bank_name == row[0]:
try:
final_output_json = get_final_dataframe(bank_name,pdf_file_name,page_count)
return True,readable_status,final_output_json
except:
print(traceback.print_exc())
return True,readable_status,[]
return False,readable_status,[]
else:
readable_status = 'non-readable'
return False,readable_status,[]
def get_final_dataframe(bank_name,pdf_file_name,page_count):
result ={}
final_output_json =[]
df = get_direct_table_data(pdf_file_name,page_count,bank_name)
excel_data = df.to_json(orient='index')
result["excel_data"] = excel_data
final_output_json.append(result)
return final_output_json
<file_sep>import collections
import tensorflow as tf
import pandas as pd
from PIL import Image
import os
import io
import re
import cv2
import numpy as np
from pdf2image import convert_from_path
from flask import jsonify
import config.config as project_configs
from .image_orientationandskew_correction import *
from .Utilityfunctions import *
import traceback
import sys
import os
# What model to download.
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = project_configs.INTAIN_CREDIT_INTERFACE_GRAPH
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = project_configs.INTAIN_BANK_STATEMENT_LABEL_MAP
NUM_CLASSES = 19
print('Pay Slip Loading model')
print(os.getcwd())
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
print('Pay Slip Model loaded successfully.')
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,use_display_name=True)
category_index = label_map_util.create_category_index(categories)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
size= (600,800)
#def pdf2jpg(pdf_file):
def salaryslip_detection(img_file,df):
try:
im= Image.open(img_file)
im_resized = im.resize(size, Image.ANTIALIAS)
salaryslipattributes= salaryslip_extraction(df,img_file,im_resized,detection_graph,label_map,category_index)
print(salaryslipattributes)
final_data = []
# labels = ['EMPLOYER NAME','EMPLOYER ADDRESS','EMPLOYEE NAME','EMPLOYEE ID','EMPLOYEE PANNO','EMPLOYEE UANNO','EMPLOYEE DOJ','EMPLOYEE DESIGNATION','BANKACCTNO','BANKNAME','PERIODOFPAY','NETSALARY']
# varnames=['employer_name','employer_address','employee_name','employee_id','employee_panno','employee_uanno','employee_doj','employee_designation','bank_accoutnno','bank_name','periodofpay','net_salary']
# labels = ['EMPLOYER NAME','EMPLOYER ADDRESS','EMPLOYEE NAME','EMPLOYEE ID','EMPLOYEE PANNO','EMPLOYEE UANNO','EMPLOYEE DOJ','EMPLOYEE DESIGNATION','BANKACCTNO','BANKNAME','PERIODOFPAY','NETSALARY']
# varnames=['employer_name','employer_address','employee_name','employee_id','employee_panno','employee_uanno','employee_doj','employee_designation','bank_accoutnno','bank_name','periodofpay','net_salary']
labels = ['EMPLOYER NAME','EMPLOYEE NAME','PERIODOFPAY','NETSALARY','GROSSSALARY']
varnames=['employer_name','employee_name','periodofpay','net_salary','gross_salary']
dickey = ['confidence_score','confidence_score_green','label','order_id','value','varname']
for i, data in enumerate(salaryslipattributes):
dicvalue = [data[1], 70, labels[i],i,data[0],varnames[i]]
res = {dickey[i]: dicvalue[i] for i in range(len(dickey))}
final_data.append(res)
response={}
response["Attribute_values"]=final_data
return response
except Exception as e:
print(e)
print(traceback.print_exc())
return "NA"
if __name__ == "__main__":
# input_image_path = '/home/jyoti/Desktop/GraphCNN/Payslips/payslip-data21april/payslip-data/24.jpg'
# output_folder_path = '/home/jyoti/Desktop/GraphCNN/Payslips/payslip-data21april/Testfolder'
input_image_path = '/home/anuja/backup/Dropbox/Datasets/Salary Slip-20200909T060323Z-001/image-test/20_0.jpg'
output_folder_path = '/home/anuja/backup/Dropbox/Datasets/Salary Slip-20200909T060323Z-001/bank/'
out_imPath=orientation_correction(output_folder_path, input_image_path)
out_image_path=skewcorrect(out_imPath)
df, _ = visionocr(out_image_path, 'apikey.json')
response=salaryslip_detection(out_image_path,df)
print(response)
<file_sep>import os
from webserverflask import flaskapp
if __name__ == '__main__':
flaskapp.runapp()<file_sep>import pandas as pd
import config.config as project_configs
txndata_csv = project_configs.INTAIN_BANK_STATEMENT_TXNDATA_CSV
def get_correct_df(df,bank_name):
# if bank_name == 'ANDHRA BANK':
# all_transaction = df.values.tolist()
# for i,item in enumerate(all_transaction[0]):
# if str(item) == 'nan' or item == None:
# print('INDEX ',i)
# df.drop(columns=[i])
if bank_name == "ANDHRA BANK":
if (str(df.loc[0][2]) == 'nan' or df.loc[0][2] is None):
df = df[[0,2,1,3,4,5]]
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
elif bank_name == 'ALLAHABAD BANK':
if df.shape[1] > 6:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
elif bank_name == "AXIS BANK A":
if df.shape[1] > 8:
df = df.dropna(axis='columns', how='all')
elif df.shape[1] == 7:
df[7] = pd.Series()
df = df[[0,1,2,7,3,4,5,6]]
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6,7])
elif bank_name == "AXIS BANK":
if df.shape[1] > 7:
df = df.dropna(axis='columns', how='all')
elif df.shape[1] == 6:
df[6] = pd.Series()
df = df[[0,6,1,2,3,4,5]]
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6])
elif bank_name == 'BANK OF BARODA':
all_transaction = df.values.tolist()
for i,item in enumerate(all_transaction[0]):
if str(item) == 'nan' or item == None:
if sum(pd.isnull(df[i])) == df.shape[0]:
df = df.drop([i], axis=1)
if (str(df.loc[0][2]) == 'nan' or df.loc[0][2] is None) and str(df.loc[0][3]) == 'Description':
df[2] = df[2].astype(str).replace('nan','') + df[3].astype(str).replace('nan','')
df = df.drop([3], axis=1)
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6,7])
elif bank_name == 'BANK OF INDIA':
if str(df.loc[0][2]) == 'Description Cheque No' and (str(df.loc[0][3]) == 'nan' or df.loc[0][3] is None):
df.iloc[0,3] = 'Cheque No'
df.iloc[0,2] = 'Description'
elif str(df.loc[0][3]) == 'Description Cheque No' and (str(df.loc[0][2]) == 'nan' or df.loc[0][2] is None):
df.iloc[0,3] = 'Cheque No'
df.iloc[0,2] = 'Description'
elif str(df.loc[0][3]) == 'Description' and (str(df.loc[0][2]) == 'nan' or df.loc[0][2] is None):
df.iloc[0,2] = 'Description'
df = df.drop([3], axis=1)
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6])
elif bank_name == 'DBS BANK':
if str(df.loc[0][2]) == 'Details of transaction' and (str(df.loc[0][1]) == 'nan' or df.loc[0][1] is None):
df.iloc[0,1] = 'Details of transaction'
df = df.drop([2], axis=1)
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4])
elif bank_name == "GREATER BANK":
if df.shape[1] > 7:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6])
elif bank_name == "HDFC BANK":
if df.shape[1] > 7:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6])
if df.shape[1] == 6:
col_one_list = df[5].tolist()
col_one_list_new =[]
credit_col = []
bal_col = []
for i,val in enumerate(col_one_list):
val = str(val).strip()
if 'Closing Bal' in val:
break
elif ' ' in val:
val_list = val.split()
credit_col.append(val_list[0])
bal_col.append(val_list[1])
else:
credit_col.append('')
bal_col.append(val)
df[5] = pd.DataFrame(credit_col)
df[6] = pd.DataFrame(bal_col)
if not credit_col:
for i,val in enumerate(col_one_list):
val = str(val).strip()
if val and val != 'nan' :
s = val.replace(',','')
s = int(float(s))
col_one_list_new.append(s)
if col_one_list_new[0] > col_one_list_new[1]:
df[6] = ""
cols = list(df)
cols[5], cols[6] = cols[6], cols[5]
df = df.loc[:,cols]
else:
df[6] = ""
cols = list(df)
cols[4], cols[6] = cols[6], cols[4]
df = df.loc[:,cols]
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6])
elif bank_name == "ICICI BANK":
if str(df.loc[0][2]) == 'nan' or df.loc[0][2] is None:
df[2] = df[2].astype(str).replace('nan','') + df[3].astype(str).replace('nan','')
df = df.drop([3], axis=1)
if str(df.loc[0][4]) == 'nan' or df.loc[0][4] is None:
df[4] = df[4].astype(str).replace('nan','') + df[5].astype(str).replace('nan','')
df = df.drop([5], axis=1)
elif bank_name == 'INDUSIND BANK':
if str(df.loc[0][2]) == 'nan' or df.loc[0][2] is None:
df = df.drop([2], axis=1)
if str(df.loc[0][3]) == 'nan' or df.loc[0][3] is None:
df = df.drop([3], axis=1)
if str(df.loc[0][4]) == 'nan' or df.loc[0][4] is None:
df = df.drop([4], axis=1)
if (str(df.loc[0][5]) == 'nan' or df.loc[0][5] is None) and df.shape[1]>6:
df[5] = df[5].astype(str).replace('nan','') + df[5].astype(str).replace('nan','')
df = df.drop([5], axis=1)
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
elif bank_name == "YES BANK":
if str(df.loc[0][2]) == 'nan' or df.loc[0][2] is None:
df[2] = df[2].astype(str).replace('nan','') + df[3].astype(str).replace('nan','')
df = df.drop([3], axis=1)
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
elif bank_name == "ANDHRA BANK":
if (str(df.loc[0][2]) == 'nan' or df.loc[0][2] is None):
df = df[[0,2,1,3,4,5]]
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
elif bank_name == "CANARA BANK":
if df.shape[1] > 7:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6])
elif bank_name == "CENTRAL BANK OF INDIA":
if df.shape[1] > 8:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6,7])
elif bank_name == "INDIAN BANK":
if df.shape[1] > 8:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6,7])
elif bank_name == "INDIAN OVERSEAS BANK":
if df.shape[1] == 6:
df[6] = pd.Series()
df = df[[0,6,1,2,3,4,5]]
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6])
elif bank_name == 'MAHARASHTRA GRAMIN BANK':
if df.shape[1] > 5:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4])
elif bank_name == "PUNJAB NATIONAL BANK":
if df.shape[1] == 5:
df[5] = pd.Series()
df = df[[0,5,1,2,3,4]]
elif df.shape[1] > 6:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
elif bank_name == "STATE BANK OF INDIA":
if df.shape[1] > 7:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6])
elif bank_name == "UNION BANK OF INDIA":
if df.shape[1] == 6:
df[6] = pd.Series()
df[7] = pd.Series()
df = df[[0,1,2,3,7,4,6,5]]
elif df.shape[1] == 7:
df[7] = pd.Series()
df = df[[0,1,2,3,7,4,5,6]]
elif df.shape[1] > 8:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6,7])
elif bank_name == "UNITED BANK OF INDIA":
if df.shape[1] == 5:
df[5] = pd.Series()
df[6] = pd.Series()
df = df[[0,1,2,5,3,4,6]]
elif df.shape[1] == 6:
df[6] = pd.Series()
df = df[[0,1,2,6,3,4,5]]
elif df.shape[1] > 7:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6])
elif bank_name == "AHMEDNAGAR MERCHANTS CO-OP BANK LTD":
if df.shape[1] > 6:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
elif bank_name == "SARASWAT CO-OPERATIVE BANK LTD.":
if df.shape[1] == 5:
df[5] = pd.Series()
df = df[[0,5,1,2,5,3,4]]
if df.shape[1] > 6:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
elif bank_name == "UJJIVAN SMALL FINANCE BANK":
if df.shape[1] > 6:
df = df.dropna(axis='columns', how='all')
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
elif bank_name == "IDBI BANK":
for i in range(0,8):
if str(df.loc[0][i]) == 'nan':
df = df.drop([i], axis=1)
df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5,6,7,8])
# else:
# df = df.dropna(axis='columns', how='all')
# df.to_csv(txndata_csv, encoding='utf-8',header=False, index=False)
# df = pd.read_csv(txndata_csv,names=[0,1,2,3,4,5])
return df<file_sep>$(document).ready(function() {
if ('tokenReset' in sessionStorage) {
} else {
window.location.href = 'forgot-password.html';
};
$('#success').hide();
$('#error').hide();
let token = sessionStorage.getItem('tokenReset');
$(document).ajaxStart(function() {
$('#wait2').css('display', 'block');
});
$(document).ajaxComplete(function() {
$('#wait2').css('display', 'none');
});
$('#forgotpasswordBtn').click(function() {
// validate signup form on keyup and submit
$('#forgotpasswordForm').validate({
rules: {
password: {
minlength: 5,
},
cpassword: {
minlength: 5,
equalTo: '#password',
},
},
messages: {
password: {
required: 'Enter a Password',
minlength: 'Enter at least {5} characters',
},
cpassword: {
required: 'Enter a Password',
minlength: 'Enter at least {5} characters',
equalTo: 'Please enter same password',
},
},
submitHandler: function(form) {
let data_attrs = {
'token': token,
'password': document.getElementById('password').value,
};
console.log(JSON.stringify(data_attrs));
let success = {
'url': 'resetpassword',
'headers': {
'content-type': 'application/json',
},
'method': 'POST',
'processData': false,
'data': JSON.stringify(data_attrs),
};
$.ajax(success).done(function(data) {
// console.log(JSON.stringify(data));
// console.log(JSON.stringify(data.message));
$('#success').text(data.message);
$('#success').show();
sessionStorage.removeItem('tokenReset', token);
$('#success').fadeTo(5000, 3000).slideUp(500, function() {
});
setTimeout(function() {
window.location.assign('index.html');
}, 2000);
}).fail(function(data) {
$('#error').show();
$('#error').text(data.responseJSON.message);
// console.log("Return" + JSON.stringify(data.responseJSON.message));
// console.log(data);
$('#error').fadeTo(5000, 3000).slideUp(500, function() {
});
if (data.responseJSON.message == 'Token is invalid!') {
setTimeout(function() {
window.location.assign('index.html');
}, 2000);
localStorage.removeItem('token');
sessionStorage.clear();
};
});
},
});
});
});
<file_sep>#!/bin/sh
export OLD_LD_LIBRARY_PATH=$LD_LIBRARY_PATH
unset LD_LIBRARY_PATH
if ! echo "$0" | grep '\.sh$' > /dev/null; then
printf 'Please run using "bash" or "sh", but not "." or "source"\\n' >&2
return 1
fi
# Determine RUNNING_SHELL; if SHELL is non-zero use that.
if [ -n "$SHELL" ]; then
RUNNING_SHELL="$SHELL"
else
if [ "$(uname)" = "Darwin" ]; then
RUNNING_SHELL=/bin/bash
else
if [ -d /proc ] && [ -r /proc ] && [ -d /proc/$$ ] && [ -r /proc/$$ ] && [ -L /proc/$$/exe ] && [ -r /proc/$$/exe ]; then
RUNNING_SHELL=$(readlink /proc/$$/exe)
fi
if [ -z "$RUNNING_SHELL" ] || [ ! -f "$RUNNING_SHELL" ]; then
RUNNING_SHELL=$(ps -p $$ -o args= | sed 's|^-||')
case "$RUNNING_SHELL" in
*/*)
;;
default)
RUNNING_SHELL=$(which "$RUNNING_SHELL")
;;
esac
fi
fi
fi
# Some final fallback locations
if [ -z "$RUNNING_SHELL" ] || [ ! -f "$RUNNING_SHELL" ]; then
if [ -f /bin/bash ]; then
RUNNING_SHELL=/bin/bash
else
if [ -f /bin/sh ]; then
RUNNING_SHELL=/bin/sh
fi
fi
fi
if [ -z "$RUNNING_SHELL" ] || [ ! -f "$RUNNING_SHELL" ]; then
printf 'Unable to determine your shell. Please set the SHELL env. var and re-run\\n' >&2
exit 1
fi
THIS_DIR=$(DIRNAME=$(dirname "$0"); cd "$DIRNAME"; pwd)
THIS_FILE=$(basename "$0")
THIS_PATH="$THIS_DIR/$THIS_FILE"
THIS_DIR_PARENT=$(dirname $(DIRNAME=$(dirname "$0"); cd "$DIRNAME"; pwd))
INTAIN_CARDEKHO_PROJECT_NAME='intain_cardekho_ai'
INTAIN_CARDEKHO_DEPLOYMENT_ROOT_DIR=$THIS_DIR_PARENT
INTAIN_CARDEKHO_DEPLOYMENT_UPLOAD_DIR_ABS="$THIS_DIR_PARENT/webserverflask/static/uploads"
INTAIN_CARDEKHO_TEMP_DIR="/tmp/$INTAIN_CARDEKHO_PROJECT_NAME"
if [ -d "$INTAIN_CARDEKHO_DEPLOYMENT_UPLOAD_DIR_ABS" ]
then
echo "$INTAIN_CARDEKHO_DEPLOYMENT_UPLOAD_DIR_ABS directory exists."
else
echo "$INTAIN_CARDEKHO_DEPLOYMENT_UPLOAD_DIR_ABS directory not found. Creating it"
mkdir -p $INTAIN_CARDEKHO_DEPLOYMENT_UPLOAD_DIR_ABS
chmod -R 777 $INTAIN_CARDEKHO_DEPLOYMENT_UPLOAD_DIR_ABS
fi
if [ -d "$INTAIN_CARDEKHO_TEMP_DIR" ]
then
echo "$INTAIN_CARDEKHO_TEMP_DIR directory exists. Cleaning it."
chmod -R 777 $INTAIN_CARDEKHO_TEMP_DIR
else
echo "$INTAIN_CARDEKHO_TEMP_DIR directory not found. Creating it"
mkdir -p $INTAIN_CARDEKHO_TEMP_DIR
chmod -R 777 $INTAIN_CARDEKHO_TEMP_DIR
fi
<file_sep>sudo apt-get update
sudo apt-get -y install python3.7
sudo apt-get -y install python3-pip
sudo apt-get -y install tesseract-ocr
sudo apt-get -y install libmysqlclient-dev
sudo apt-get -y install enchant
sudo apt-get install -y libsm6 libxext6 libxrender-dev
sudo apt-get install -y libmagickwand-dev libopencv-dev
sudo apt-get install poppler-utils
sudo apt-get update && apt-get -y install poppler-utils && apt-get clean
sudo apt install -y docker-compose nodejs gcc enchant
sudo apt install build-essential libpoppler-cpp-dev pkg-config python3-dev
sudo apt install -y nginx
sudo ufw allow 'Nginx Full'
sudo service nginx start
sudo ufw allow ssh
sudo ufw --force enable
pip3 install -r requirements.txt
<file_sep>$(document).ready(function () {
var token = localStorage.getItem("token");
var data_attrs = {
"token": token,
};
var success = {
"url": "updateprofile",
"headers": {
"content-type": "application/json"
},
"method": "POST",
"processData": false,
"data": JSON.stringify(data_attrs)
}
$.ajax(success).done(function (data) {
// console.log(JSON.stringify(data));
data = data['result'];
// console.log(JSON.stringify(data));
$("#firstname").val(data[0].firstname);
$("#lastname").val(data[0].lastname);
$("#password").val(data[0].password);
$("#cpassword").val(data[0].password);
$("#emailid").val(data[0].emailid);
$("#phone").val(data[0].phone);
$("#jobtitle").val(data[0].jobtitle);
$("#companyname").val(data[0].companyname);
$("#question").val(data[0].question);
$('#answer').val(data[0].answer);
}).fail(function (data) {
$('#error').show();
$("#error").text("Session expired, please wait 2 min, it will redirect to login page.", data.responseJSON.message);
if (data.responseJSON.message == "Token is invalid!") {
setTimeout(function () {
window.location.href = "index.html";
}, 2000);
sessionStorage.removeItem("token");
sessionStorage.clear();
};
});
$('#registerBtn').click(function () {
$("#regsiterForm").validate({
rules: {
firstname: "required",
lastname: "required",
password: {
minlength: 5
},
cpassword: {
minlength: 5,
equalTo: "#password"
},
emailid: "required",
phone: "required",
companyname: "required",
jobtitle: "required",
question: "required",
answer: "required"
},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Enter a username",
minlength: "Enter at least {5} characters"
},
cpassword: {
required: "Enter a username",
minlength: "Enter at least {5} characters",
equalTo: "Please enter same password"
},
emailid: "Please enter your email id",
phone: "Please enter your phone number",
companyname: "Please enter your Company name",
jobtitle: "Please enter your job title",
question: "Please select your question",
answer: "Please enter your answer"
},
submitHandler: function (form) {
var data_attrs = {
"token": token,
"firstname": document.getElementById("firstname").value,
"lastname": document.getElementById("lastname").value,
"password": document.getElementById("<PASSWORD>").value,
"emailid": document.getElementById("emailid").value,
"phone": document.getElementById("phone").value,
"companyname": document.getElementById("companyname").value,
"jobtitle": document.getElementById("jobtitle").value,
"question": document.getElementById("question").value,
"answer": document.getElementById("answer").value
};
console.log(JSON.stringify(data_attrs))
var success = {
"url": "updateuser",
"headers": {
"content-type": "application/json"
},
"method": "POST",
"processData": false,
"data": JSON.stringify(data_attrs)
}
$.ajax(success).done(function (data) {
// console.log("Return" + JSON.stringify(data));
$('#success').show();
$("#success").text(data.message);
$("#regsiterForm").trigger("reset");
// console.log("Return" + JSON.stringify(data.message));
sessionStorage.removeItem("token");
setTimeout(function () {
window.location.href = "index.html";
}, 1500);
}).fail(function (data) {
$('#error').show();
$("#error").text(data.statusText);
// console.log("Return" + JSON.stringify(data.responseJSON.message));
// console.log(data);
// console.log("show error " + data.responseText);
console.log("Data" + JSON.stringify(data));
// $("#regsiterForm").trigger("reset");
// console.log("Return" + JSON.parse(data.message));
if (data.responseJSON.message == "Token is invalid!") {
setTimeout(function () {
window.location.href = "index.html";
}, 2000);
sessionStorage.removeItem("token");
sessionStorage.clear();
};
});
},
});
});
});<file_sep>import os
DATABASE_CONFIG = {
'db_vm': 'localhost',
'db_port': '27017',
'db_name': 'ind_credit'
}
API_KEY = ["<KEY>","<KEY>"]
RAZOR_KEY="<KEY>"
RAZOR_SECRET="<KEY>"
# INTAIN_EMAIL="<EMAIL>"
# INTAIN_PASSWD="<PASSWORD>"
INTAIN_EMAIL = "<EMAIL>"
INTAIN_PASSWD = "<PASSWORD>"
# BASE_URL = os.environ.get('BASE_URL',"http://0.0.0.0:5005")
# BASE_URL = os.environ.get('BASE_URL',"http://3172.16.31.10:3000")
BASE_URL = os.environ.get('BASE_URL',"https://credit.in-d.ai/hdfc")
MONGODB_URL = os.environ.get('MONGODB_URL','localhost')
MONGODB_PORT = int(os.environ.get('MONGODB_PORT', 27017))
MONGODB_NAME = 'ind_credit'
# Project_variables
INTAIN_BANK_STATEMENT_PROJECT_NAME = 'ind_credit'
# MongoDB variables
INTAIN_BANK_STATEMENT_MONGODB_URL='localhost'
INTAIN_BANK_STATEMENT_MONGODB_PORT=27017
INTAIN_BANK_STATEMENT_MONGODB_DATABASE_NAME='intain_db'
INTAIN_BANK_STATEMENT_MONGODB_COLLECTION_NAME='cert_extract_col'
# Project variables
INTAIN_BANK_STATEMENT_ROOT_DIR=os.getcwd()
INTAIN_BANK_STATEMENT_TEMP_DIR=os.path.join('/tmp',INTAIN_BANK_STATEMENT_PROJECT_NAME)
# Google vision variables
INTAIN_BANK_STATEMENT_GOOGLE_APPLICATION_CREDENTIALS = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/apikey.json')
# Upload dir variables
INTAIN_BANK_STATEMENT_UPLOAD_DIR_FLASK_REL='static/uploads'
INTAIN_BANK_STATEMENT_UPLOAD_DIR_ABS = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'webserverflask',INTAIN_BANK_STATEMENT_UPLOAD_DIR_FLASK_REL)
#Template Folder
INTAIN_BANK_STATEMENT_TEMPLATES=os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'webserverflask/templates/')
# Required CSV files
INTAIN_BANK_STATEMENT_IFSC_CODE_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/IFSC_Code.xlsx')
INTAIN_BANK_STATEMENT_LOCALIZATION_BANK_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/localization_bank.csv')
# INTAIN_BANK_STATEMENT_IFSC_CODE_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/IFSC_Code.csv')
INTAIN_BANK_STATEMENT_FILE_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/coordinates.csv')
INTAIN_BANK_STATEMENT_TABLE_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/table.csv')
INTAIN_BANK_STATEMENT_PARA_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/para.csv')
INTAIN_BANK_STATEMENT_TXNDATA_JSON = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config','txndata.json')
INTAIN_BANK_STATEMENT_COORDINATE_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/coordinate.csv')
INTAIN_BANK_STATEMENT_TXNDATA_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config','txn_data.csv')
INTAIN_BANK_STATEMENT_DOCUMENT_HTML = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/documentselection.html')
# Calculation CSV
INTAIN_BANK_STATEMENT_KEYWORDS_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/keywords.xlsx')
INTAIN_BANK_STATEMENT_BANK_TAGS_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/bank_taglines.xlsx')
# INTAIN_BANK_STATEMENt_HEADERS_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/headers.csv')
INTAIN_BANK_STATEMENt_HEADERS_CSV = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/headers.csv')
INTAIN_BANK_STATEMENt_FORMULA = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/formula.ods')
INTAIN_BANK_STATEMENT_INTERFACE_GRAPH = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/model_weights/frozen_inference_graph.pb')
INTAIN_BANK_STATEMENT_LABEL_MAP = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/model_weights/trial_label_map.pbtxt')
INTAIN_CREDIT_INTERFACE_GRAPH = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/model_weights/frozen_inference_graph_payslip.pb')
INTAIN_CREDIT_LABEL_MAP = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config/model_weights/objectdetection_payslip.pbtxt')
INTAIN_CREDIT_ATTRIBUTE_JSON = os.path.join(INTAIN_BANK_STATEMENT_ROOT_DIR,'config','attribute_config.json')
<file_sep># TableDetection_Invoices
<file_sep>
import pandas as pd
import traceback
import re
# from pandas import ExcelWriter
def get_new_bank_name(header,bank_name):
try:
if bank_name == 'ICICI BANK':
for column_name in header:
column_name = str(column_name).strip().lower()
if column_name.__contains__('mode'):
bank_type = 'ICICI BANK 6'
elif column_name == 'autosweep' or column_name.__contains__('reverse'):
bank_type = 'ICICI BANK 80'
elif column_name == 'location' :
bank_type = 'ICICI BANK 81'
elif column_name == 'transaction id':
bank_type = 'ICICI BANK 9'
elif column_name.__contains__('s no'):
bank_type = 'ICICI BANK 82'
elif bank_name == 'AXIS BANK':
for column_name in header:
if column_name == 'Branch Name' :
bank_type = 'AXIS BANK A'
elif bank_name == 'INDUSIND BANK':
for column_name in header:
if column_name == 'Particulars' :
bank_type = 'INDUSIND BANK A'
elif bank_name == "KOTAK MAHINDRA BANK":
if len(header) == 8:
bank_type = "KOTAK MAHINDRA BANK 8"
else:
bank_type = bank_name
return bank_type
except:
print(traceback.print_exc())
return bank_name
def get_balance_index(new_header):
balance_key = ['balance(inr)','balance (inr','balance','balance(in rs.)','balance amount','closing balance','account balance']
for index,item in enumerate(new_header):
if item:
for header_item in balance_key:
if header_item == item.lower().strip() or header_item.__contains__(item.lower().strip()):
balance_index = index
return balance_index
return len(new_header)-1
def get_description_index(new_header):
balance_key = ['description']
for index,item in enumerate(new_header):
item = item.lower().strip()
for header_item in balance_key:
if header_item == item or header_item.lower().__contains__(item):
balance_index = index
return balance_index
return len(new_header)-1
def get_valid_dataframe(bank_name,df):
# df = df.dropna(axis=0, how='all', thresh=None, subset=None, inplace=False)
# converting to list
# print(bank_name)
# print("************************-------------------- \n",df)
bank_name = bank_name.strip()
all_transaction = df.values.tolist()
all_transaction_new = []
rows = []
for row in all_transaction:
nan_list_first = []
for item in row:
if str(item) == 'nan':
nan_list_first.append(item)
if len(nan_list_first) != len(row):
all_transaction_new.append(row)
empty_list = []
for row in all_transaction_new:
if str(row[0]) == 'nan' or row[0] == None:
empty_list.append(item)
if len(all_transaction_new) == len(empty_list):
for row in all_transaction_new:
row.pop(0)
rows.append(row)
else:
rows = all_transaction_new
#################################### Header Extraction ###################################
headers = []
last_column = []
for i,row in enumerate(rows):
if i<3:
last_column.append(row[len(row)-1])
else:
break
print('last_column',last_column)
if bank_name == "INDUSIND BANK" or bank_name == "PUNJAB NATIONAL BANK" or bank_name == "AXIS BANK" or bank_name == 'YES BANK':
for i,row in enumerate(rows):
if bank_name == "AXIS BANK" and i < 2:
if len(row) == 8 and i == 0:
headers.append(row)
break
elif len(row) == 7:
headers.append(row)
elif bank_name == 'INDUSIND BANK' and i<2:
if str(row[1]).__contains__('Particulars'):
headers.append(row)
break
else:
headers.append(row)
elif bank_name == 'PUNJAB NATIONAL BANK' and i<3:
if i==0:
headers.append(row)
elif i == 1 and str(row[5]).__contains__('Narration'):
headers.append(row)
elif i == 2:
headers.append(row)
else:
break
elif i<2:
headers.append(row)
elif i == 2:
break
elif bank_name == "UNION BANK OF INDIA" or bank_name == "HDFC BANK":
for i,row in enumerate(rows):
if i==0:
headers.append(row)
else:
break
else:
for i,row in enumerate(rows):
if i >2:
break
elif i==0 and row[len(row)-1] == last_column[0]:
headers.append(row)
elif (str(last_column[1]) == 'nan' or last_column[1] is None or any(i.isdigit() for i in str(last_column[1])) == False or str(last_column[1]).lower().__contains__('balance') == True) and str(last_column[1]).lower().__contains__('cr') == False and i == 1 :
headers.append(row)
elif (str(last_column[2]) == 'nan' or last_column[2] is None or any(i.isdigit() for i in str(last_column[1])) == False) and str(last_column[1]).lower().__contains__('cr') == False and any(i.isdigit() for i in str(last_column[2])) == False and str(last_column[2]).lower().__contains__('cr') == False and i == 2 :
headers.append(row)
print("--------------- ",headers)
initial_header = []
new_header = []
header_length = len(headers[0])
for i in range(header_length):
if len(headers) == 2:
res2 = str(headers[0][i]).strip() + ' ' + str(headers[1][i]).strip()
elif len(headers) == 3:
res2 = str(headers[0][i]).strip() + ' ' + str(headers[1][i]).strip() + ' ' +str(headers[2][i]).strip()
elif len(headers) == 1:
res2 = str(headers[0][i]).strip()
else:
res2 = ''
res2 = res2.replace("None","").replace('nan','')
initial_header.insert(i,res2)
print('initial_header',initial_header)
for i,item in enumerate(initial_header):
item = str(item).lower()
item = re.sub(r"\s\s+" , " ", item)
if item.__contains__('txn date') or item.__contains__('txn. date') or item.__contains__('transaction date') or item.__contains__('post date') :
new_header.append('Date')
elif item.__contains__('tran date') :
new_header.append('Date')
elif item.__contains__('cr') and item.__contains__('dr'):
new_header.append('Dr/Cr')
elif item.__contains__('dr') or item.__contains__('withdrawal'):
new_header.append('Debit')
elif item.__contains__('particular') or item.__contains__('description') or item.__contains__('naration') or item.__contains__('narration'):
new_header.append('Description')
elif item.__contains__('details') or item.__contains__('transaction remarks') or item == 'remarks':
new_header.append('Description')
elif any(re.findall(r'(\bcr\b)',item.lower())) or any(re.findall(r'(eposit)',item)):
new_header.append('Credit')
elif item.__contains__('value dt'):
new_header.append('Value Date')
elif i == len(initial_header)-1 and (item.__contains__('balance') or item.__contains__('balace') or item.__contains__('closing bal')) :
new_header.append('Balance')
elif i == len(initial_header)-2 and item.__contains__('balance') :
new_header.append('Balance')
elif item.__contains__('amount') :
new_header.append('Amount')
elif item.__contains__('value date'):
new_header.append('Value Date')
# elif item.lower().__contains__('chq') :
# new_header.append('Cheque No')
# elif (item.lower().__contains__('cr')and item.lower().__contains__('dr')) or (item.lower().__contains__('deposit')and item.lower().__contains__('withdrawal')) :
# new_header.append('Amount')
else:
column_item = item.strip().title()
new_header.append(column_item)
bank_type = get_new_bank_name(new_header,bank_name)
print('new_header',new_header,bank_name, bank_type)
balance_index = get_balance_index(new_header)
description_index = get_description_index(new_header)
################################# Valid Transaction ###########################
valid_transactions_new = []
valid_transactions = []
opening_closing_row = []
for row in rows:
try:
row[description_index] = str(row[description_index]).lower()
if row[description_index].__contains__('debit:0') or row[description_index].__contains__('number of credit') or row[description_index].__contains__('opening balance') or row[description_index].__contains__('closing balance'):
opening_closing_row.append(row)
except:
pass
for row in rows:
if row not in headers and row not in opening_closing_row :
valid_transactions_new.append(row)
for row in valid_transactions_new:
nan_list = []
for item in row:
if str(item) == 'nan':
nan_list.append(item)
if len(nan_list) != len(row):
valid_transactions.append(row)
################################# Bank ########################################
transactions = []
dfObj = pd.DataFrame() # list to store single row entries
# print(":::::::::::::::::;valid_transactions:::::::::::::::::::::",valid_transactions)
if bank_name == "ALLAHABAD BANK":
print("++++++++++++++++++++++++ ALLAHABAD BANK ++++++++++++++++")
d_i = 0
p_i = 2
for index,v_t in enumerate(valid_transactions):
if index == len(valid_transactions) - 1:
print('last_row',v_t)
elif v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
print(traceback.print_exc())
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
if bank_name == "AHMEDNAGAR MERCHANTS CO-OP BANK LTD":
print("++++++++++++++++++++++++ AHMEDNAGAR MERCHANTS CO-OP BANK LTD ++++++++++++++++")
d_i = 0
p_i = 2
for index,v_t in enumerate(valid_transactions):
if index == len(valid_transactions) - 2 or index == len(valid_transactions) - 1:
print('last_row',v_t)
elif v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
print(traceback.print_exc())
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "CITY UNION BANK":
print("++++++++++++++++++++++++ CITY UNION BANK ++++++++++++++++")
d_i = 0
p_i = 1
for index,v_t in enumerate(valid_transactions):
if index == len(valid_transactions) - 1:
print('last_row',v_t)
elif v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
print(traceback.print_exc())
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "<NAME> BANK":
if len(new_header) == 5:
d_i = 0
p_i = 1
c_n = 2
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
pass
if v_t[c_n] is not None :
if str(v_t[c_n]) != 'nan':
try:
transactions[-1][c_n] = str(transactions[-1][c_n]) + str(v_t[c_n])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
# dfObj.loc[2,list(statement.columns.values)]=1
dfObj.xs(0)[7] = "CR_DR"
# print("+++++++++++++++++++++++++++ dfObj ++++++++++++++++++++++++++\n",dfObj)
# dfObj.to_csv('xxx.csv', encoding='utf-8',header=False, index=False)
# statement = pd.read_csv('xxx.csv')
statement =dfObj
statement.rename(columns=statement.iloc[0], inplace = True)
statement.drop([0], inplace = True)
statement.rename(columns = {7: 'col_1_new_name'}, inplace = True)
print("statement\n",statement)
statement['Credit'] = ""
print("list(statement.columns.values)\n",list(statement.columns.values))
xx = statement['Dr/Cr'].values.tolist()
for item in xx:
if item.lower().__contains__('cr'):
statement.loc[statement['Dr/Cr'] == item , 'Credit'] = statement['Dr/Cr']
statement.loc[statement['Dr/Cr'] == item, 'Dr/Cr'] = ''
statement.rename(columns = {'Dr/Cr': 'Amount'}, inplace = True)
dfObj = statement
print("***************************\n",statement)
if len(new_header) == 8:
d_i = 1
p_i = 2
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
# dfObj.loc[2,list(statement.columns.values)]=1
dfObj.xs(0)[7] = "CR_DR"
print("+++++++++++++++++++++++++++ dfObj ++++++++++++++++++++++++++\n",dfObj)
# dfObj.to_csv('xxx.csv', encoding='utf-8',header=False, index=False)
# statement = pd.read_csv('xxx.csv')
statement =dfObj
statement.rename(columns=statement.iloc[0], inplace = True)
statement.drop([0], inplace = True)
statement.rename(columns = {7: 'col_1_new_name'}, inplace = True)
print("statement\n",statement)
statement['Credit'] = ""
print("list(statement.columns.values)",list(statement.columns.values))
statement.loc[statement['Dr/Cr'] == 'CR', 'Credit'] = statement['Amount']
statement.loc[statement['Dr/Cr'] == 'CR', 'Amount'] = ''
dfObj = statement
# print("***************************\n",statement)
elif bank_name == "AXIS BANK":
print("----------- Axis Bank -----------")
transactions = []
# try:
yyy = ''
zzz = ''
if header_length == 7:
b_i = 5
index_2 = 2
for v_t in valid_transactions:
if v_t[b_i] is None or type(v_t[b_i]) == type(None) or str(v_t[b_i]) == 'nan':
if v_t[index_2] is not None :
if str(v_t[index_2]) != 'nan':
try:
yyy = str(v_t[index_2])
except:
print(traceback.print_exc())
pass
else:
try:
transactions.append(v_t)
if yyy:
transactions[-1][index_2] = yyy + ' ' + transactions[-1][index_2]
yyy = ''
except:
print(traceback.print_exc())
pass
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif header_length == 8:
b_i = 6
index_2 = 2
index_7 = 7
for v_t in valid_transactions:
if v_t[b_i] is None or type(v_t[b_i]) == type(None) or str(v_t[b_i]) == 'nan':
if v_t[index_2] is not None :
if str(v_t[index_2]) != 'nan':
try:
yyy = str(v_t[index_2])
except:
print(traceback.print_exc())
pass
if v_t[index_7] is not None :
if str(v_t[index_7]) != 'nan':
try:
zzz = str(v_t[index_7])
except:
print(traceback.print_exc())
pass
else:
try:
transactions.append(v_t)
if yyy:
transactions[-1][index_2] = yyy + ' ' + transactions[-1][index_2]
yyy = ''
if zzz:
transactions[-1][index_7] = zzz + ' ' + transactions[-1][index_7]
zzz = ''
except:
print(traceback.print_exc())
pass
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
statement =dfObj
statement.rename(columns=statement.iloc[0], inplace = True)
statement.drop([0], inplace = True)
statement.rename(columns = {7: 'col_1_new_name'}, inplace = True)
print("statement\n",statement)
statement['Credit'] = ""
print("list(statement.columns.values)",list(statement.columns.values))
statement.loc[statement['Dr/Cr'] == 'CR', 'Credit'] = statement['Amount']
statement.loc[statement['Dr/Cr'] == 'Cr', 'Credit'] = statement['Amount']
statement.loc[statement['Dr/Cr'] == 'CR', 'Amount'] = ''
statement.loc[statement['Dr/Cr'] == 'Cr', 'Amount'] = ''
# statement.rename(columns = {7: 'col_1_new_name'}, inplace = True)
statement.rename(columns={"Amount": "Debit"},inplace = True)
dfObj = statement
# except:
# print(traceback.print_exc())
# d_i = 0
# p_i = 2
# for v_t in valid_transactions:
# if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
# if v_t[p_i] is not None:
# if str(v_t[p_i]) != 'nan':
# try:
# transactions[-1][p_i] += str(v_t[p_i])
# except:
# pass
# else:
# transactions.append(v_t)
elif bank_name == "BANK OF BARODA":
d_i = 1 #index of date column from BANK_DETAILS
p_i = 2 #index of particular(transaction) column from BANK_DETAILS
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None):
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "COSMOS BANK":
print("++++++++++++++++++++++++ COSMOS BANK ++++++++++++++++")
d_i = 0
p_i = 1
for index,v_t in enumerate(valid_transactions):
if str(v_t[1]).__contains__('Sub Total') or str(v_t[1]).__contains__('GrandTotal') :
print('last_row',v_t)
elif v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + ' '+str(v_t[p_i])
except:
print(traceback.print_exc())
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "INDUSIND BANK":
print("--------------- INDUSIND BANK ------------------")
if bank_type == 'INDUSIND BANK A':
d_i = 5 #index of date column from BANK_DETAILS
p_i = 1 #index of particular(transaction) column from BANK_DETAILS
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None):
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
transactions[-1][p_i] = str(transactions[-1][p_i]).replace('None','').replace('nan','')
except:
pass
else:
transactions.append(v_t)
else:
b_i = 0
index_1 = 1
index_2 = 2
index_5 = 5
yyy = ''
zzz = ''
for v_t in valid_transactions:
if v_t[b_i] is None or type(v_t[b_i]) == type(None) or str(v_t[b_i]) == 'nan':
try:
yyy = str(v_t[index_2])
except:
print(traceback.print_exc())
pass
try:
zzz = str(v_t[index_1])
except:
print(traceback.print_exc())
pass
try:
balance = str(v_t[index_5])
except:
print(traceback.print_exc())
pass
else:
try:
transactions.append(v_t)
if yyy:
transactions[-1][index_2] = yyy + ' ' + str(transactions[-1][index_2])
transactions[-1][index_2] = str(transactions[-1][index_2]).replace('None','').replace('nan','')
yyy = ''
if zzz:
transactions[-1][index_1] = zzz + ' ' + str(transactions[-1][index_1])
transactions[-1][index_1] = str(transactions[-1][index_1]).replace('None','').replace('nan','')
zzz = ''
if balance:
transactions[-1][index_5] = balance + ' ' + str(transactions[-1][index_5])
transactions[-1][index_5] = str(transactions[-1][index_5]).replace('None','').replace('nan','')
except:
print(traceback.print_exc())
pass
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
print(dfObj)
elif bank_name == "IDBI BANK":
print("++++++++++++++++++++++++ IDBI BANK ++++++++++++++++")
d_i = 1
p_i = 3
for index,v_t in enumerate(valid_transactions):
if index == len(valid_transactions) - 2 or index == len(valid_transactions) - 1:
print('last_row',v_t)
elif v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
print(traceback.print_exc())
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
# dfObj.loc[2,list(statement.columns.values)]=1
dfObj.xs(0)[9] = "CR_DR"
statement =dfObj
statement.rename(columns=statement.iloc[0], inplace = True)
statement.drop([0], inplace = True)
statement.rename(columns = {9: 'col_1_new_name'}, inplace = True)
statement['Credit'] = ""
print("list(statement.columns.values)\n",list(statement.columns.values))
xx = statement['Dr/Cr'].values.tolist()
statement.loc[statement['Dr/Cr'] == 'CR', 'Credit'] = statement['Amount']
statement.loc[statement['Dr/Cr'] == 'CR', 'Amount'] = ''
statement.rename(columns = {'Amount': 'Debit'}, inplace = True)
dfObj = statement.copy()
elif bank_name == "BANK OF INDIA":
if len(new_header) == 7:
d_i = 1 #index of date column from BANK_DETAILS
p_i = 2 #index of particular(transaction) column from BANK_DETAILS
for v_t in valid_transactions:
if str(v_t[0]).__contains__('Name') or str(v_t[0]).__contains__('Address') :
print('last_row',v_t)
break
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
if len(new_header) == 6:
d_i = 0 #index of date column from BANK_DETAILS
p_i = 1 #index of particular(transaction) column from BANK_DETAILS
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) != 'nan':
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "ANDHRA BANK":
d_i = 0
p_i = 2
for v_t in valid_transactions:
if type(v_t[d_i]) == type(None) or v_t[d_i] is None or str(v_t[d_i]) == 'nan' or v_t[d_i] == 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "GREATER BANK":
d_i = 0
p_i = 3
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "HDFC BANK":
d_i = 0
p_i = 1
for v_t in valid_transactions:
if str(v_t[p_i]).__contains__('statement summary'):
print('last_row',v_t)
break
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try :
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "CANARA BANK" or bank_name == 'BANK OF WIKI':
d_i = 0
p_i = 3
for v_t in valid_transactions:
if v_t[d_i] is not None or type(v_t[d_i]) != type(None) :
transactions.append(v_t)
else:
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
# elif bank_name == "BANK OF MAHARASHTRA":
# d_i = 0
# p_i = 3
# for v_t in valid_transactions:
# if v_t[d_i] is not None or type(v_t[d_i]) != type(None) :
# transactions.append(v_t)
# else:
# try:
# transactions[-1][p_i] += str(v_t[p_i])
# except:
# pass
# if new_header:
# transactions.insert(0, new_header)
# dfObj = pd.DataFrame(transactions)
elif bank_name == "ICICI BANK":
if len(new_header) == 9:
d_i = 0
p_i = 1
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
statement =dfObj
statement.rename(columns=statement.iloc[0], inplace = True)
statement.drop([0], inplace = True)
statement['Credit'] = ""
print("list(statement.columns.values)",list(statement.columns.values))
statement.loc[statement['Dr/Cr'] == 'CR', 'Credit'] = statement['Amount']
statement.loc[statement['Dr/Cr'] == 'CR', 'Amount'] = ''
# print(statement)
dfObj = statement
elif bank_type == 'ICICI BANK 80':
d_i = 0
p_i = 1
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_type == 'ICICI BANK 81':
d_i = 0
p_i = 1
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_type == 'ICICI BANK 82':
d_i = 7
p_i = 4
index_0 = 0
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
if v_t[index_0] is not None :
if str(v_t[index_0]) != 'nan':
try:
transactions[-1][index_0] = str(transactions[-1][index_0]) + str(v_t[index_0])
transactions[-1][index_0] = transactions[-1][index_0].replace('None','').replace('nan','')
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif len(new_header) == 6:
d_i = 0
p_i = 2
for v_t in valid_transactions:
print(">>>>",v_t[d_i],type(v_t[d_i]),len(v_t[d_i]))
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' or not str(v_t[d_i]).replace(" ",""):
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + ' '+ str(v_t[p_i])
except:
print(traceback.print_exc())
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "PAYTM PAYMENTS BANK":
d_i = 3
p_i = 1
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
# dfObj.loc[2,list(statement.columns.values)]=1
dfObj.xs(0)[4] = "CR_DR"
# print("+++++++++++++++++++++++++++ dfObj ++++++++++++++++++++++++++\n",dfObj)
# dfObj.to_csv('xxx.csv', encoding='utf-8',header=False, index=False)
# statement = pd.read_csv('xxx.csv')
statement =dfObj
statement.rename(columns=statement.iloc[0], inplace = True)
statement.drop([0], inplace = True)
statement.rename(columns = {4: 'col_1_new_name'}, inplace = True)
print("statement\n",statement)
statement['Credit'] = ""
print("list(statement.columns.values)\n",list(statement.columns.values))
xx = statement['Amount'].values.tolist()
for item in xx:
if item.lower().__contains__('+'):
statement.loc[statement['Amount'] == item , 'Credit'] = statement['Amount']
statement.loc[statement['Amount'] == item, 'Amount'] = ''
statement.rename(columns = {'Amount': 'Debit'}, inplace = True)
dfObj = statement.copy()
print("***************************\n",statement)
# if new_header:
# transactions.insert(0, new_header)
# dfObj = pd.DataFrame(transactions)
elif bank_name == "PUNJAB NATIONAL BANK":
if len(new_header) == 6:
d_i = 4
p_i = 5
for v_t in valid_transactions:
# print("..>>",v_t[d_i])
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' or not v_t[d_i] :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
transactions[-1][p_i] = transactions[-1][p_i].replace('None','').replace('nan','')
except:
pass
else:
transactions.append(v_t)
elif len(new_header) == 8:
d_i = 4
p_i = 5
for v_t in valid_transactions:
# print("..>>",v_t[d_i])
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' or not v_t[d_i] :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "STATE BANK OF INDIA":
d_i = 6 #index of date column from BANK_DETAILS
p_i = 2 #index of particular(transaction) column from BANK_DETAILS
index_0=0
index_1 = 1
index_3 = 3
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
if v_t[index_0] is not None:
if str(v_t[index_0]) != 'nan':
try:
transactions[-1][index_0] = str(transactions[-1][index_0])+' '+ str(v_t[index_0])
transactions[-1][index_0] = transactions[-1][index_0].replace('None','').replace('nan','')
except:
pass
if v_t[p_i] is not None:
if str(v_t[index_1]) != 'nan':
try:
transactions[-1][index_1] = str(transactions[-1][index_1])+' '+ str(v_t[index_1])
transactions[-1][index_1] = transactions[-1][index_1].replace('None','').replace('nan','')
except:
pass
if v_t[p_i] is not None:
if str(v_t[index_3]) != 'nan':
try:
transactions[-1][index_3] = str(transactions[-1][index_3])+' '+ str(v_t[index_3])
transactions[-1][index_3] = transactions[-1][index_3].replace('None','').replace('nan','')
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "TAMILNAD MERCANTILE BANK LTD":
d_i = 0 #index of date column from BANK_DETAILS
p_i = 2 #index of particular(transaction) column from BANK_DETAILS
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None):
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "SARASWAT CO-OPERATIVE BANK LTD.":
print("----------- SARASWAT CO-OPERATIVE BANK LTD. -----------")
transactions = []
# try:
yyy = ''
b_i = 5
index_2 = 2
for v_t in valid_transactions:
if v_t[b_i] is None or type(v_t[b_i]) == type(None) or str(v_t[b_i]) == 'nan':
if v_t[index_2] is not None :
if str(v_t[index_2]) != 'nan':
try:
yyy = str(v_t[index_2])
except:
print(traceback.print_exc())
pass
else:
try:
transactions.append(v_t)
if yyy:
transactions[-1][index_2] = yyy + ' ' + str(transactions[-1][index_2])
transactions[-1][index_2] = transactions[-1][index_2].replace('None','').replace('nan','')
yyy = ''
except:
print(traceback.print_exc())
pass
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "UNION BANK OF INDIA":
print("++++++++++++++++++++++++ UNION BANK OF INDIA ++++++++++++++++")
d_i = 0
p_i = 1
utr_no = 3
if len(new_header) == 8:
for index,v_t in enumerate(valid_transactions):
# if index == len(valid_transactions) - 1:
# print('last_row',v_t)
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan' :
if v_t[p_i] is not None :
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] = str(transactions[-1][p_i]) + str(v_t[p_i])
transactions[-1][p_i] = transactions[-1][p_i].replace('None','').replace('nan','')
except:
print(traceback.print_exc())
pass
if v_t[utr_no] is not None:
if str(v_t[utr_no]) != 'nan':
try:
transactions[-1][utr_no] = str(transactions[-1][utr_no])+' '+ str(v_t[utr_no])
transactions[-1][utr_no] = transactions[-1][utr_no].replace('None','').replace('nan','')
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "YES BANK":
d_i = 0 #index of date column from BANK_DETAILS
p_i = 2 #index of particular(transaction) column from BANK_DETAILS
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None):
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
elif bank_name == "UJJIVAN SMALL FINANCE BANK":
d_i = 0 #index of date column from BANK_DETAILS
p_i = 1 #index of particular(transaction) column from BANK_DETAILS
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None):
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
if not transactions or bank_name == "Unknown Bank" or dfObj.empty :
print("----------- Unknown Bank -----------")
transactions = []
print("+++++++++++ Balance Index +++++++++",balance_index)
try:
if balance_index:
b_i = balance_index
index_0 = 0
index_1 = 1
index_2 = 2
index_3 = 3
# if header_length >4:
index_4 = 4
# if header_length >5:
index_5 = 5
# if header_length >6:
index_6 = 6
# if header_length >7:
index_7 = 7
for v_t in valid_transactions:
if v_t[b_i] is None or type(v_t[b_i]) == type(None) or str(v_t[b_i]) == 'nan':
if v_t[index_0] is not None :
if str(v_t[index_0]) != 'nan':
try:
transactions[-1][index_0] = str(transactions[-1][index_0]) + str(v_t[index_0])
transactions[-1][index_0] = transactions[-1][index_0].replace('None','').replace('nan','')
except:
pass
if v_t[index_1] is not None :
if str(v_t[index_1]) != 'nan':
try:
transactions[-1][index_1] = str(transactions[-1][index_1]) + str(v_t[index_1])
transactions[-1][index_1] = transactions[-1][index_1].replace('None','').replace('nan','')
except:
pass
if v_t[index_2] is not None :
if str(v_t[index_2]) != 'nan':
try:
transactions[-1][index_2] = str(transactions[-1][index_2]) + ' ' + str(v_t[index_2])
transactions[-1][index_2] = transactions[-1][index_2].replace('None','').replace('nan','')
except:
pass
if v_t[index_3] is not None :
if str(v_t[index_3]) != 'nan':
try:
transactions[-1][index_3] = str(transactions[-1][index_3]) + ' ' + str(v_t[index_3])
transactions[-1][index_3] = transactions[-1][index_3].replace('None','').replace('nan','')
except:
pass
if header_length >4:
if v_t[index_4] is not None :
if str(v_t[index_4]) != 'nan':
try:
transactions[-1][index_4] = str(transactions[-1][index_4]) + str(v_t[index_4])
transactions[-1][index_4] = transactions[-1][index_4].replace('None','').replace('nan','')
except:
pass
if header_length >5:
if v_t[index_5] is not None :
if str(v_t[index_5]) != 'nan':
try:
transactions[-1][index_5] = str(transactions[-1][index_5]) + str(v_t[index_5])
transactions[-1][index_5] = transactions[-1][index_5].replace('None','').replace('nan','')
except:
pass
if header_length >6:
if v_t[index_6] is not None :
if str(v_t[index_6]) != 'nan':
try:
transactions[-1][index_6] = str(transactions[-1][index_6]) + str(v_t[index_6])
transactions[-1][index_6] = transactions[-1][index_6].replace('None','').replace('nan','')
except:
pass
if header_length >7:
if v_t[index_7] is not None :
if str(v_t[index_7]) != 'nan':
try:
transactions[-1][index_7] = str(transactions[-1][index_7]) + str(v_t[index_7])
transactions[-1][index_7] = transactions[-1][index_7].replace('None','').replace('nan','')
except:
pass
else:
transactions.append(v_t)
except:
print(traceback.print_exc())
d_i = 0
p_i = 2
for v_t in valid_transactions:
if v_t[d_i] is None or type(v_t[d_i]) == type(None) or str(v_t[d_i]) == 'nan':
if v_t[p_i] is not None:
if str(v_t[p_i]) != 'nan':
try:
transactions[-1][p_i] += str(v_t[p_i])
except:
pass
else:
transactions.append(v_t)
if new_header:
transactions.insert(0, new_header)
dfObj = pd.DataFrame(transactions)
return dfObj,bank_type<file_sep>$(document).ready(function () {
var token = localStorage.getItem("token");
document.getElementById("token2").value = localStorage.getItem("token");
});<file_sep>import os
import cv2 as cv
import traceback
import shutil
import time
import pandas as pd
from PIL import Image
import json
from .payslip import hr_payslip
from . import payslip_db
from . import functions_library
import config.config as project_configs
import pprint
base_dir = os.getcwd()
print(base_dir)
data_dir = os.path.join(base_dir, "webserverflask","static", "data")
if not os.path.isdir(data_dir):
os.makedirs(data_dir)
input_dir = os.path.join(data_dir, "ss_input")
if not os.path.isdir(input_dir):
os.makedirs(input_dir)
images_dir = os.path.join(data_dir, "images")
if not os.path.isdir(images_dir):
os.makedirs(images_dir)
excel_dir = os.path.join(data_dir, "excels")
if not os.path.isdir(excel_dir):
os.makedirs(excel_dir)
with open(project_configs.INTAIN_CREDIT_ATTRIBUTE_JSON) as jsFile:
attr_config_dict = json.load(jsFile)
attrs = []
########################################################################################################################
def extract_images(emailid, job_dir):
job_dir = "Job_"+job_dir
job_status = "In Process"
payslip_db.update_jobstatus(emailid, job_dir.replace("Job_", ""), job_status)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
print("Processing Job |", job_dir)
job_dir_path = os.path.join(input_dir, job_dir)
pdf_inv_list = os.listdir(job_dir_path)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
images_job_dir = os.path.join(images_dir, job_dir)
if os.path.isdir(images_job_dir):
shutil.rmtree(images_job_dir)
os.makedirs(images_job_dir)
index=0
excel_result=pd.DataFrame()
excel_path=os.path.join("static","data","excels", job_dir+'.xlsx')
full_path=os.path.join(excel_dir,job_dir+'.xlsx')
batch_name=payslip_db.get_batch_name(job_dir)
for pdf_inv in pdf_inv_list:
try:
database_data = {}
database_data['emailid'] = emailid
database_data['job_id'] = job_dir.replace("Job_", "")
database_data['file_name'] = pdf_inv
# database_data['user_edited'] = False
curtime=time.time()
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
print("Processing Document |", pdf_inv)
pdf_filepath = os.path.join(job_dir_path, pdf_inv)
database_data['image_path'] = os.path.join("static","data", "ss_input", job_dir, pdf_inv)
output_dir_name = os.path.splitext(pdf_inv)[0]
output_dir_path = os.path.join(images_job_dir, output_dir_name)
if os.path.isdir(output_dir_path):
shutil.rmtree(output_dir_path)
os.makedirs(output_dir_path)
print("Splitting Document...")
# if pdf_filepath.split(".")[-1]=="pdf":
num_images = functions_library.wandPdfSplit(pdf_filepath, output_dir_path)
print("Splitting done. Document has", str(num_images), "images")
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
print("Running AI...")
imagelist=[]
inv_img_list = sorted(os.listdir(output_dir_path))
# inv_img_list = [f for f in inv_img_list if f.lower().endswith(".jpg")]
resultlist=[]
for inv_img in inv_img_list:
img_path = os.path.join(output_dir_path, inv_img)
imgpath1='static' + img_path.split('static')[1]
imagelist.append(imgpath1)
database_data['images'] = sorted(imagelist)
excel_result.at[index,'file']=inv_img
excel_result.at[index,'Applicant ID']=batch_name
final_output={}
input_img_path = os.path.join(output_dir_path, inv_img)
inv_img_name = os.path.splitext(inv_img)[0]
response = hr_payslip(input_img_path)
attrs = attr_config_dict['attrs_payslip']
base_dir = os.getcwd()
data_dir = os.path.join(base_dir, "static", "data")
result={}
input_image_path = 'static' + input_img_path.split('static')[1]
for i in range(len(list(attrs))):
attrib = attrs[i]
result[attrib] = response[attrib]
excel_result.at[index,attrib]=response[attrib]
# database_data[attrib + "_X0"] = 0
# database_data[attrib + "_Y0"] = 0
# database_data[attrib + "_W"] = 0
# database_data[attrib + "_H"] = 0
result[attrib + "_user_edited"] = 0 # user edited flag
if response[attrib] == 'NA':
result[attrib + "_conf"] = 0
else:
result[attrib + "_conf"] = .7
# print(result,inv_img)
final_output["Output"]=result
print("imgpath1",imgpath1)
final_output["image"]=imgpath1
resultlist.append(final_output)
print("final_output",final_output)
index=index+1
database_data["Result"]=resultlist
database_data['image_path'] = os.path.join("static","data", "ss_input", job_dir, pdf_inv)
payslip_db.payslip_result(database_data,excel_path)
except Exception as e:
database_data = {}
database_data['emailid'] = emailid
database_data['job_id'] = job_dir.replace("Job_", "")
database_data['file_name'] = pdf_inv
database_data['image_path'] = os.path.join("static","data", "ss_input", job_dir, pdf_inv)
# database_data['excel_path'] = "static/data/excels/"+job_dir+"_"+ output_dir_name + '_table.csv'
#database_data['excel_path'] = "static/data/excels/"+job_dir+"_"+ output_dir_name + '_table.xlsx'
for attrib in attrs:
database_data[attrib] = "NA"
database_data[attrib + "_conf"] = 0.0
excel_result.at[index,attrib]="NA"
# database_data[attrib + "_X0"] = 0.0
# database_data[attrib + "_Y0"] = 0.0
# database_data[attrib + "_W"] = 0.0
# database_data[attrib + "_H"] = 0.0
# database_data[attrib + "_image"] = os.path.join("static","data", "input", job_dir, pdf_inv)
index=index+1
# Handle few other keys
try:
database_data['images'] = sorted(imagelist)
except NameError:
database_data['images'] = []
print(traceback.print_exc())
payslip_db.payslip_result(database_data,excel_path)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
curtime1=time.time()
print("----------Document Processed----------",curtime1-curtime)
job_status = "Complete"
print("excel result",excel_result)
writer = pd.ExcelWriter(full_path,engine='openpyxl')
excel_result.to_excel(writer,sheet_name = 'Payslip Result',index=False)
writer.save()
payslip_db.update_jobstatus(emailid, job_dir.replace("Job_", ""), job_status)
print("----------Job Processed----------")
# access_db.update_excel(emailid, job_dir)
print("------------END------------")
if __name__ == "__main__":
pass
| 66bbd89a09bc51ff97d4d7451aa8ce5b29e132e8 | [
"YAML",
"JavaScript",
"Markdown",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 41 | Python | tayalanuja/hdfc | 29a0b01a5c40f9badfe6edd710266546a81cf089 | f468d049bf338863053a3450d5f085f1addac612 |
refs/heads/master | <repo_name>Simplesmente/calculadora-js-bdd<file_sep>/spec/calculadora/subtracaoSpec.js
describe("Suite de testes de subtração", function(){
var calculadora = require('../../src/js/calculadora.js');
it('deve retornar 5 para 8 e 3', function(){
expect(calculadora.subtrair(8,3)).toEqual(5);
})
it('deve retornar 12 para 9 e -3 no formato texto', function(){
expect(calculadora.subtrair('9','-3')).toEqual(12);
})
it('deve retornar -3.5 para 1.5 e 5 no formato texto', function(){
expect(calculadora.subtrair(1.5,5)).toEqual(-3.5);
})
it('deve retornar 0 quando valor 1 for inválido', function(){
expect(calculadora.subtrair(undefined,10)).toEqual(0);
})
it('deve retornar 0 quando valor 2 for inválido', function(){
expect(calculadora.subtrair(10,undefined)).toEqual(0);
})
});<file_sep>/README.md
# calculadora-js-bdd
[](https://travis-ci.org/Simplesmente/calculadora-js-bdd)
Curso testes unitários com jasmine
| b788e8633231d6ed812f53e0ec28864f5dd65535 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Simplesmente/calculadora-js-bdd | 0321f1a17bbdc512b9fb956efc1ac9ada707585c | e08b654d193dd1988e964910c548845ab63b251a |
refs/heads/master | <repo_name>StevenRParker/ServletJSP<file_sep>/src/casestudy1/Student.java
package casestudy1;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
public String id;
public String name;
public String subject;
public int score;
public Student(String id, String name, String subject, int score){
this.id= id;
this.name= name;
this.subject= subject;
this.score = score;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
| 331b8b0ea57f6e2817c3ab2bdfface2b11c6b05a | [
"Java"
] | 1 | Java | StevenRParker/ServletJSP | b8562ce8218a3bc8d09861d5814cffa25e7e6249 | c040aeea02ff956a497e05b579510573cbbe3b30 |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import { withRouter } from 'react-router'
import { Menu, Segment } from 'semantic-ui-react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { logoutUser } from '../../actions/auth'
class LoggedInNavBar extends Component {
logoutUser = () => {
this.props.history.push('/')
this.props.logoutUser()
}
render() {
return (
<Segment inverted>
<Menu inverted pointing secondary>
<Menu.Item name='Home' onClick={() => this.props.history.push('/')} />
<Menu.Item name='Listening Profile' onClick={ () => this.props.history.push('/listening-profile')}/>
<Menu.Item name='Playlists' onClick={ () => this.props.history.push('/playlists')}/>
<Menu.Item name='Spotify Web Player' href={this.props.user.spotify_url} target='_blank' />
<Menu.Item name='Logout' onClick={this.logoutUser}/>
<Menu.Item position="right" name='GitHub' href='https://github.com/jtynerbryan' target="_blank"/>
</Menu>
</Segment>
)
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
logoutUser
}, dispatch)
}
function mapStateToProps(state) {
return {
user: state.auth.user
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(LoggedInNavBar))
<file_sep>import { combineReducers } from 'redux'
import tracksReducer from './tracksReducer'
import authReducer from './authReducer'
import audioFeaturesReducer from './audioFeaturesReducer'
import relatedArtistsReducer from './relatedArtistsReducer'
import topArtistsReducer from './topArtistsReducer'
import playlistReducer from './playlistReducer'
const appReducer = combineReducers({
auth: authReducer,
tracks: tracksReducer,
audioFeatures: audioFeaturesReducer,
relatedArtists: relatedArtistsReducer,
topArtists: topArtistsReducer,
playlists: playlistReducer
})
export default appReducer
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import appReducer from './reducers/index';
import { BrowserRouter as Router } from 'react-router-dom';
import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import persistState from 'redux-localstorage';
import 'semantic-ui-css/semantic.min.css';
import './index.css';
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT_USER') {
state = undefined
localStorage.removeItem('jwt');
}
return appReducer(state, action)
}
const store = createStore(rootReducer, compose(applyMiddleware(thunk), persistState()))
ReactDOM.render(
<Provider store={store}>
<Router>
<App/>
</Router>
</Provider>, document.getElementById('root')
);
registerServiceWorker();
<file_sep>export function addTopArtists(user_id) {
const body = {
method: 'GET',
mode: 'cors'
}
return (dispatch) => {
return fetch(`//better-sounds-api.herokuapp.com/api/v1/top_artists?user_id=${user_id}`, body)
.then(res => res.json())
.then(res => {
dispatch({type:"ADD_TOP_ARTISTS", payload: res.top_artists.items})
})
}
}
<file_sep>import React from 'react';
import { authorize } from '../actions/auth';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
class Login extends React.Component {
componentDidMount() {
// after being redirected from Spotify login,
// capture response code from url, use it to authorize user and then push history to data fetching component
const code = this.props.location.search.split('=')[1];
this.props.authorize(code);
this.props.history.push('/loading');
}
render() {
return <div />;
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ authorize }, dispatch);
};
export default connect(null, mapDispatchToProps)(Login);
<file_sep>export function addRelatedArtists(user_id,artist_id) {
const body = {
method: 'GET',
mode: 'cors'
}
return (dispatch) => {
return fetch(`//better-sounds-api.herokuapp.com/api/v1/related_artists?user_id=${user_id}&artist_id=${artist_id}`, body)
.then(res => res.json())
.then(res => {
dispatch({type: "ADD_RELATED_ARTISTS", payload: res.related_artists.artists})
})
}
}
export function addRelatedArtistsTopTracks(user_id,artist_id) {
const body = {
method: 'GET',
mode: 'cors'
}
return (dispatch) => {
return fetch(`//better-sounds-api.herokuapp.com/api/v1/related_artists_top_tracks?user_id=${user_id}&artist_id=${artist_id}`, body)
.then(res => res.json())
.then(res => {
dispatch({type: "ADD_RELATED_ARTISTS_TOP_TRACKS", payload: res.top_tracks.tracks})
})
}
}
export function addRelatedArtistsAudioFeatures(user_id, tracks) {
const trackIds = tracks.map(track => track.id)
const body = {
method: 'GET',
mode: 'cors'
}
return (dispatch) => {
return fetch(`//better-sounds-api.herokuapp.com/api/v1/audio_features?id=${user_id}&ids=${trackIds}`, body)
.then(res => res.json())
.then(res => {
dispatch({type: "ADD_RELATED_ARTISTS_AUDIO_FEATURES", payload: res.features.audio_features})
})
}
}
export function mapRelatedArtistsFeaturesToTracks(tracks, features) {
const mapFeaturesToTracks = tracks.map(track => {
let attributes = features.filter(features => features.id === track.id)
return {
track: track,
features: attributes
}
})
return (dispatch) => {
dispatch({
type: 'MAP_FEATURES_TO_TRACKS', payload: mapFeaturesToTracks
})
}
}
export function clearAllRelatedArtistsData() {
return (dispatch) => {
dispatch({
type: 'CLEAR_ALL_RELATED_ARTISTS_DATA'
})
}
}
<file_sep>import React from 'react'
import { Menu, Segment } from 'semantic-ui-react'
const HomeNavBar = (props) => {
return (
<Segment inverted className="navbar">
<Menu inverted pointing secondary>
<Menu.Item name='Login' href='https://better-sounds-api.herokuapp.com/api/v1/login'/>
<Menu.Item position="right" name='GitHub' href='https://github.com/jtynerbryan' target="_blank"/>
</Menu>
</Segment>
)
}
export default HomeNavBar
<file_sep>import React from 'react';
import PlaylistForm from './PlaylistForm';
import PlaylistGrid from './PlaylistGrid';
import LoggedInNavBar from '../NavBars/LoggedInNavBar';
import { connect } from 'react-redux';
import { Modal, Button } from 'semantic-ui-react';
class Playlists extends React.Component {
componentWillMount() {
if (!this.props.isLoggedIn) {
this.props.history.push('/');
}
}
render() {
if (this.props.playlists.length > 0) {
return (
<div className="playlist">
<LoggedInNavBar />
<h1 style={{ fontFamily: 'Roboto, sans-serif', fontStyle: 'italic' }}>Playlists</h1>
<Modal style={{ backgroundColor: '#FAFAFA' }} trigger={<Button style={{ fontFamily: 'Roboto, sans-serif' }}>Create a Playlist</Button>}>
<Modal.Header style={{ backgroundColor: '#1b1c1d', color: '#fff', borderRadius: 0 }}>New Playlist</Modal.Header>
<PlaylistForm />
</Modal>
<PlaylistGrid playlists={this.props.playlists} user={this.props.user} />
</div>
);
} else {
return (
<div className="empty-playlist">
<LoggedInNavBar />
<h1 style={{ fontFamily: 'Roboto, sans-serif', fontStyle: 'italic' }}>Playlists</h1>
<h3>You haven't created any playlists yet</h3>
<PlaylistForm />
</div>
);
}
}
}
function mapStateToProps(state) {
return {
isLoggedIn: state.auth.isLoggedIn,
user: state.auth.user,
playlists: state.playlists.playlists
};
}
export default connect(mapStateToProps, null)(Playlists);
<file_sep>import React from 'react';
import Track from './Track'
import { Grid } from 'semantic-ui-react'
const TopTracksList = (props) => {
const mapTracksToFeatures = props.topTracks.map(track => {
const attributes = props.topTracksAudioFeatures.filter(features => features.id === track.id)
return { info: track, attributes: attributes }
})
return (
<Grid centered>
<Grid.Row columns={4}>
{mapTracksToFeatures.map((song, index) => <Track key={index} song={song} />)}
</Grid.Row>
</Grid>
)
}
export default TopTracksList
<file_sep># Better Sounds
* Gain insight into your Spotify listening habits and create playlists of new music based on your needs
* View live site [here](https://bettersoundz.herokuapp.com) (please be patient while Heroku wakes up)
* Relies on Rails API back end ([repo](https://github.com/jtynerbryan/better-sounds-api))
## Features
* Authorizes users through [Spotify's Web API Authorization](https://developer.spotify.com/web-api/authorization-guide/) to access user's top tracks, top artists, audio features and playlists
* Users are able to view their top played tracks with [audio features](https://developer.spotify.com/web-api/get-audio-features/) information for each track using Chart.js
* User's Top Artists are displayed with images, follower count and related genres
* Aggregate Audio Features for top tracks are displayed using Chart.js to give Users greater understanding of their listening habits
* Users can create new playlists of previously undiscovered music based on their top artists' related artists
* New playlists feature a specific audio feature prominently, as selected by Users
* Embedded Spotify player allows users to listen to newly created playlists directly on the page
* Redux provides persistent state across all app pages
* [redux-localstorage](https://github.com/elgerlambert/redux-localstorage) copies Redux store into localstorage and re-hydrates Redux store on User page refresh. This minimizes Rails API requests and avoids rate-limiting issues with Spotify's API
## Architecture
* This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app)
<file_sep>function audioFeaturesReducer(state = {
topTracksAudioFeatures: [],
aggregateFeaturesOfTopTracks: {
danceability: 0,
energy: 0,
speechiness: 0,
acousticness: 0,
instrumentalness: 0,
liveness: 0,
valence: 0
}
}, action) {
switch (action.type) {
case 'ADD_TOP_TRACKS_AUDIO_FEATURES':
const topFeatures = action.payload
return Object.assign({}, state, {
topTracksAudioFeatures: topFeatures
})
case 'SET_AGGREGATE_FEATURES_FOR_TOP_TRACKS':
const aggregateTopFeatures = action.payload
return Object.assign({}, state, {
aggregateFeaturesOfTopTracks: aggregateTopFeatures
})
default:
return state
}
}
export default audioFeaturesReducer
<file_sep>import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { addRelatedArtists } from '../../actions/relatedArtists'
import { addRelatedArtistsTopTracks } from '../../actions/relatedArtists'
import { addRelatedArtistsAudioFeatures } from '../../actions/relatedArtists'
import { mapRelatedArtistsFeaturesToTracks } from '../../actions/relatedArtists'
var Spinner = require('react-spinkit');
class RefreshSpotifyData extends React.Component {
componentWillMount() {
if (!this.props.isLoggedIn) {
this.props.history.push('/')
}
}
componentDidMount() {
if (this.props.topArtists.length > 0 && this.props.relatedArtists.length === 0) {
const topTenArtists = this.props.topArtists.slice(0, 10)
const randomtopTenArtist = topTenArtists[Math.floor(Math.random() * topTenArtists.length)]
this.props.addRelatedArtists(this.props.user.id, randomtopTenArtist.id)
}
}
componentDidUpdate() {
if (this.props.relatedArtistsTopTracks.length === 0 && this.props.relatedArtistsAudioFeatures.length === 0) {
const topEightRelatedArtists = this.props.relatedArtists.slice(0, 8)
topEightRelatedArtists.map(artist => this.props.addRelatedArtistsTopTracks(this.props.user.id, artist.id))
}
if (this.props.relatedArtistsTopTracks.length === 80 && this.props.relatedArtistsAudioFeatures.length === 0) {
this.props.addRelatedArtistsAudioFeatures(this.props.user.id, this.props.relatedArtistsTopTracks)
}
if (this.props.relatedArtistsAudioFeatures.length > 0 && this.props.relatedArtistsTracksWithFeatures.length === 0) {
this.props.mapRelatedArtistsFeaturesToTracks(this.props.relatedArtistsTopTracks, this.props.relatedArtistsAudioFeatures)
}
if(this.props.relatedArtistsTracksWithFeatures.length > 0) {
setTimeout(() => this.props.history.push('/playlists'), 2500)
}
}
render() {
return (
<div className="loader">
<Spinner className="spinner" name="cube-grid" color="white" />
</div>
)
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators ({
addRelatedArtists,
addRelatedArtistsTopTracks,
addRelatedArtistsAudioFeatures,
mapRelatedArtistsFeaturesToTracks
}, dispatch)
}
function mapStateToProps(state) {
return {
isLoggedIn: state.auth.isLoggedIn,
user: state.auth.user,
topTracks: state.tracks.topTracks,
topTracksAudioFeatures: state.audioFeatures.topTracksAudioFeatures,
aggregateFeaturesOfTopTracks: state.audioFeatures.aggregateFeaturesOfTopTracks,
relatedArtists: state.relatedArtists.relatedArtists,
relatedArtistsAudioFeatures: state.relatedArtists.relatedArtistsAudioFeatures,
topArtists: state.topArtists.topArtists,
relatedArtistsTopTracks: state.relatedArtists.relatedArtistsTopTracks,
relatedArtistsTracksWithFeatures: state.relatedArtists.tracksWithFeatures,
playlists: state.playlists.playlists
}
}
export default connect(mapStateToProps, mapDispatchToProps)(RefreshSpotifyData)
<file_sep>import React, { Component } from 'react';
import { Route } from 'react-router-dom'
import './App.css';
import Login from './components/Login'
import Welcome from './components/Welcome'
import FetchUserData from './components/Loaders/FetchUserData'
import UserResults from './components/UserResults'
import RefreshSpotifyData from './components/Loaders/RefreshSpotifyData'
import Playlists from './components/Playlists/Playlists'
class App extends Component {
render() {
return (
<div>
<Route exact path='/' component={Welcome}/>
<Route exact path='/success' component={Login}/>
<Route exact path='/loading' component={FetchUserData}/>
<Route exact path='/listening-profile' component={UserResults}/>
<Route exact path='/playlists' component={Playlists}/>
<Route exact path='/re-loading' component={RefreshSpotifyData}/>
</div>
);
}
}
export default App;
<file_sep>import React from 'react'
import AudioFeaturesChart from './AudioFeaturesChart'
import TopArtists from './Artists/TopArtists'
import TopTracksList from './Tracks/TopTracksList'
import LoggedInNavBar from './NavBars/LoggedInNavBar'
import ArtistsFeaturesCarousel from './Carousel'
import { bindActionCreators } from 'redux'
import { addRelatedArtistsTopTracks } from '../actions/relatedArtists'
import { addRelatedArtistsAudioFeatures } from '../actions/relatedArtists'
import { mapRelatedArtistsFeaturesToTracks } from '../actions/relatedArtists'
import { connect } from 'react-redux'
class UserResults extends React.Component {
componentWillMount() {
if (!this.props.isLoggedIn) {
this.props.history.push('/')
}
}
componentDidMount() {
// fetch relatedArtistsTopTracks for playlist creation later
if (this.props.relatedArtistsTopTracks.length === 0 && this.props.relatedArtistsAudioFeatures.length === 0) {
const topEightRelatedArtists = this.props.relatedArtists.slice(0, 8)
topEightRelatedArtists.map(artist => this.props.addRelatedArtistsTopTracks(this.props.user.id, artist.id))
}
}
componentDidUpdate() {
// fetch relatedArtistsAudioFeatures using trackIds fetched in componentDidMount()
if (this.props.relatedArtistsTopTracks.length === 80 && this.props.relatedArtistsAudioFeatures.length === 0) {
this.props.addRelatedArtistsAudioFeatures(this.props.user.id, this.props.relatedArtistsTopTracks)
}
// map relatedArtists' audioFeatures to tracks for filtering after playlist form submission
if (this.props.relatedArtistsAudioFeatures.length > 0 && this.props.relatedArtistsTracksWithFeatures.length === 0) {
this.props.mapRelatedArtistsFeaturesToTracks(this.props.relatedArtistsTopTracks, this.props.relatedArtistsAudioFeatures)
}
}
render() {
return (
<div>
<div>
<LoggedInNavBar />
<ArtistsFeaturesCarousel slides={[
<div className='chart-container'>
<h2 className='chart-header' style={{marginTop: '30px'}}>Audio Features from Top Tracks</h2>
<AudioFeaturesChart classname='big-chart' chartData={Object.values(this.props.aggregateFeaturesOfTopTracks).map(val => val * 2)} />
</div>,
<div>
<h2 className='artist-header' style={{marginTop: '30px'}}>Top Artists</h2>
<TopArtists artists={this.props.topArtists} />
</div>
]}/>
</div>
<div className="tracks">
<h1 className="top-tracks-header">Top Tracks</h1>
<TopTracksList topTracks={this.props.topTracks} topTracksAudioFeatures={this.props.topTracksAudioFeatures} />
</div>
</div>
)
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
addRelatedArtistsTopTracks,
addRelatedArtistsAudioFeatures,
mapRelatedArtistsFeaturesToTracks
}, dispatch)
}
function mapStateToProps(state) {
return {
user: state.auth.user,
isLoggedIn: state.auth.isLoggedIn,
aggregateFeaturesOfTopTracks: state.audioFeatures.aggregateFeaturesOfTopTracks,
relatedArtists: state.relatedArtists.relatedArtists,
relatedArtistsAudioFeatures: state.relatedArtists.relatedArtistsAudioFeatures,
topArtists: state.topArtists.topArtists,
relatedArtistsTopTracks: state.relatedArtists.relatedArtistsTopTracks,
relatedArtistsTracksWithFeatures: state.relatedArtists.tracksWithFeatures,
topTracks: state.tracks.topTracks,
topTracksAudioFeatures: state.audioFeatures.topTracksAudioFeatures
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UserResults)
<file_sep>function relatedArtistsReducer(state = {
relatedArtists: [],
relatedArtistsTopTracks: [],
relatedArtistsAudioFeatures: [],
tracksWithFeatures: []
}, action) {
switch (action.type) {
case 'ADD_RELATED_ARTISTS':
return Object.assign({}, state, {
relatedArtists: action.payload
})
case 'ADD_RELATED_ARTISTS_TOP_TRACKS':
return Object.assign({}, state, {
relatedArtistsTopTracks: state.relatedArtistsTopTracks.concat(action.payload)
})
case 'ADD_RELATED_ARTISTS_AUDIO_FEATURES':
return Object.assign({}, state, {
relatedArtistsAudioFeatures: state.relatedArtistsAudioFeatures.concat(action.payload)
})
case 'MAP_FEATURES_TO_TRACKS':
return Object.assign({}, state, {
tracksWithFeatures: action.payload
})
case 'CLEAR_ALL_RELATED_ARTISTS_DATA':
return Object.assign({}, state, {
relatedArtists: [],
relatedArtistsTopTracks: [],
relatedArtistsAudioFeatures: [],
tracksWithFeatures: []
})
default:
return state
}
}
export default relatedArtistsReducer
<file_sep>export default(state = {
isLoggedIn: false,
user: {
username: null,
spotify_url: null,
id: null
}
}, action) => {
switch(action.type) {
case 'AUTHORIZE':
localStorage.setItem("jwt", action.payload.jwt)
return Object.assign({}, state, {
user: action.payload.user,
isLoggedIn: true
})
default:
return state
}
}
<file_sep>export function addTopTracksAudioFeatures(id, tracks) {
const trackIds = tracks.map(track => track.id)
const body = {
method: 'GET',
mode: 'cors'
}
return (dispatch) => {
return fetch(`//better-sounds-api.herokuapp.com/api/v1/audio_features?id=${id}&ids=${trackIds}`, body)
.then(res => res.json())
.then(res => {
dispatch({type: "ADD_TOP_TRACKS_AUDIO_FEATURES", payload: res.features.audio_features})
})
}
}
// reduce top tracks audio features to create AudioFeaturesChart
export function sumFeaturesOfTopTracks(tracksFeatures) {
const aggregate = tracksFeatures.reduce((a, b) => {
return {
danceability: a.danceability + b.danceability,
energy: a.energy + b.energy,
speechiness: a.speechiness + b.speechiness,
acousticness: a.acousticness + b.acousticness,
instrumentalness: a.instrumentalness + b.instrumentalness,
liveness: a.liveness + b.liveness,
valence: a.valence + b.valence
}
})
return (dispatch) => {
dispatch({type: 'SET_AGGREGATE_FEATURES_FOR_TOP_TRACKS', payload: aggregate})
}
}
<file_sep>import React from 'react';
import { Image, Modal, Grid } from 'semantic-ui-react';
const Artist = (props) => {
return (
<div style={{ fontFamily: 'Roboto, sans-serif' }}>
<Grid.Column>
<Modal trigger={<img className="scale artist-modal" src={props.artist.images[0].url} alt={props.artist.name} />}>
<Modal.Header style={{ fontFamily: 'Roboto, sans-serif' }}>{props.artist.name}</Modal.Header>
<Modal.Content image scrolling>
<Image size="medium" src={props.artist.images[0].url} wrapped />
<Modal.Description>
<h3>Followers: {props.artist.followers.total}</h3>
<h3>Genres: {props.artist.genres.join(', ')}</h3>
<a href={props.artist.external_urls.spotify} target="_blank">
<h3>Spotify Profile</h3>
</a>
</Modal.Description>
</Modal.Content>
</Modal>
</Grid.Column>
</div>
);
};
export default Artist;
<file_sep>function playlistReducer(state = {
playlists: []
}, action) {
switch(action.type) {
case 'GET_PLAYLISTS':
return Object.assign({}, state, {
playlists: state.playlists.concat(action.payload)
})
case 'ADD_NEW_PLAYLIST':
return Object.assign({}, state, {
playlists: state.playlists.concat(action.payload)
})
default:
return state
}
}
export default playlistReducer
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import HomeNavBar from './NavBars/HomeNavBar';
import LoggedInNavBar from './NavBars/LoggedInNavBar';
import { Container } from 'semantic-ui-react';
const Welcome = (props) => {
return (
<div className="welcome">
{props.isLoggedIn ? <LoggedInNavBar /> : <HomeNavBar />}
<Container textAlign="center" className="welcome-header">
<h1 className="home">Better Sounds</h1>
<h2>Analyze your Spotify listening habits</h2>
<h2>Create playlists of new music tailored to your needs</h2>
</Container>
</div>
);
};
const mapStateToProps = (state) => {
return {
isLoggedIn: state.auth.isLoggedIn
};
};
export default connect(mapStateToProps, null)(Welcome);
<file_sep>import React from 'react';
import { Image, Modal, Header, Grid } from 'semantic-ui-react'
import AudioFeaturesChart from '../AudioFeaturesChart'
const Track = (props) => {
const chartData = [
props.song.attributes[0].danceability * 100,
props.song.attributes[0].energy * 100,
props.song.attributes[0].speechiness * 100,
props.song.attributes[0].acousticness * 100,
props.song.attributes[0].instrumentalness * 100,
props.song.attributes[0].liveness * 100,
props.song.attributes[0].valence * 100,
]
return (
<div>
<Grid.Column>
<Modal trigger={<Image className='scale'src={props.song.info.album.images[1].url} size='medium' verticalAlign='middle' />}>
<Modal.Header>{props.song.info.name} by {props.song.info.artists[0].name}</Modal.Header>
<Modal.Content image scrolling>
<Image size='large' src={props.song.info.album.images[1].url} wrapped />
<Modal.Description>
<Header>Audio Features</Header>
</Modal.Description>
<AudioFeaturesChart chartData={chartData} style={{ paddingBottom: 5 }}/>
</Modal.Content>
<Modal.Actions>
</Modal.Actions>
</Modal>
</Grid.Column>
</div>
)
}
export default Track
<file_sep>export function addTopTracks(id) {
const body = {
method: 'GET',
mode: 'cors'
}
return (dispatch) => {
return fetch(`//better-sounds-api.herokuapp.com/api/v1/top_tracks?id=${id}`, body)
.then(res => res.json())
.then(res => {
dispatch({type:"ADD_TOP_TRACKS", payload: res.tracks.items})
})
}
}
<file_sep>import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { addPlaylist } from '../../actions/playlists';
import { clearAllRelatedArtistsData } from '../../actions/relatedArtists';
import { Form, Select } from 'semantic-ui-react';
const audioFeatures = ['Acousticness', 'Danceability', 'Energy', 'Instrumentalness', 'Liveness', 'Speechiness', 'Valence'];
class PlaylistForm extends React.Component {
state = {
playlistTitle: ''
};
handleChange = (e, { value }) => this.setState({ value });
handleTitle = (e) => {
this.setState({
playlistTitle: e.target.value
});
};
handleSubmit = (e) => {
e.preventDefault();
if (this.state.playlistTitle === '' || !this.state.value) {
alert('Please enter a title and select and audio feature');
} else {
// create playlst based on data collected from form
this.props.addPlaylist(this.state.playlistTitle, this.state.value, this.props.relatedArtistsTracksWithFeatures, this.props.user.id);
// clearAllRelatedArtistsData() so the next playlist is created with different music
this.props.clearAllRelatedArtistsData();
// re-fetch relatedArtists, their topTracks and audioFeatures
this.props.history.push('/re-loading');
}
};
render() {
// create options for semantic UI Select Component
const audioFeatureOptions = audioFeatures.map((feature) => {
return { text: feature, value: feature };
});
return (
<Form onSubmit={this.handleSubmit}>
<Form.Group widths="equal" style={{ width: '40%', margin: 'auto', marginTop: '20px' }}>
<Form.Input placeholder="My Playlist" label="Playlist Name" onChange={this.handleTitle} />
</Form.Group>
<Form.Group widths="equal" style={{ width: '50%', margin: 'auto', marginTop: '20px' }}>
<Form.Input control={Select} options={audioFeatureOptions} label="Select an audio feature to appear prominently in your playlist" onChange={this.handleChange} />
</Form.Group>
<Form.Button id="submit-button" style={{ marginTop: '20px' }}>
Submit
</Form.Button>
</Form>
);
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(
{
addPlaylist,
clearAllRelatedArtistsData
},
dispatch
);
};
const mapStateToProps = (state) => {
return {
user: state.auth.user,
relatedArtistsTracksWithFeatures: state.relatedArtists.tracksWithFeatures
};
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(PlaylistForm));
<file_sep>import React from 'react';
import { Doughnut } from 'react-chartjs-2';
const AudioFeaturesChart = (props) => {
const data = {
labels: ['danceability', 'energy', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence'],
datasets: [
{
label: 'Aggregate Audio Features',
data: props.chartData,
backgroundColor: ['rgb(244,67,54)', 'rgb(103,58,183)', 'rgb(63,81,181)', 'rgb(33,150,243)', 'rgb(255,152,0)', 'rgb(0,150,136)', 'rgb(255,235,59)']
}
]
};
return (
<div className="chart">
<Doughnut
data={data}
width={650}
height={500}
options={{
maintainAspectRatio: false
}}
/>
</div>
);
};
export default AudioFeaturesChart;
| 8bfaaa710116328cb2a0e1e08e8324bac5afa770 | [
"JavaScript",
"Markdown"
] | 24 | JavaScript | jtynerbryan/better-sounds | 3936dbbd6bba6b211557f49ee0ce1e53b4b394fe | 7a02cb1763851da42c1992a947750023c67bf8d7 |
refs/heads/master | <repo_name>chuandajiba/ShouBei<file_sep>/src/main/java/com/wx/microprogram/Entity/OneTask.java
//package com.wx.microprogram.Entity;
//
//import com.wx.microprogram.Pojo.OneTaskMutiId;
//
//import javax.persistence.*;
//
//@Entity
//@IdClass(OneTaskMutiId.class)
//@Table(name = "one_task")
//public class OneTask {
// @Id
// private String userId; //用户ID
// @Id
// private String publisherId; //发布者ID
// @Id
// private String taskId; //任务ID
// private boolean finish; //是否完成
// private String address; //文件地址
// private String[] fileNameList; //本人提交的文件名称
// private String groupId; //工作组ID
//// private String taskType; //提交文件类型
//// private String startTime; //开始时间
//// private String deadLine; //截止时间
//// private String numPeople; //人数
//// private String name; //任务名称
//// private String description; //任务描述
//
// public OneTask(){}
//
// @Column(name = "user_id")
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// @Column(name = "publisher_id")
// public String getPublisherId() {
// return publisherId;
// }
//
// public void setPublisherId(String publisherId) {
// this.publisherId = publisherId;
// }
//
// @Column(name = "task_id")
// public String getTaskId() {
// return taskId;
// }
//
// public void setTaskId(String taskId) {
// this.taskId = taskId;
// }
//
// @Column(name = "finish")
// public boolean isFinish() {
// return finish;
// }
//
// public void setFinish(boolean finish) {
// this.finish = finish;
// }
//
// @Column(name = "address")
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// @Column(name = "file_name_list")
// public String[] getFileNameList() {
// return fileNameList;
// }
//
// public void setFileNameList(String[] fileNameList) {
// this.fileNameList = fileNameList;
// }
//
// @Column(name = "group_id")
// public String getGroupId() {
// return groupId;
// }
//
// public void setGroupId(String groupId) {
// this.groupId = groupId;
// }
////
//// @Column(name = "task_type")
//// public String getTaskType() {
//// return taskType;
//// }
////
//// public void setTaskType(String taskType) {
//// this.taskType = taskType;
//// }
////
//// @Column(name = "start_time")
//// public String getStartTime() {
//// return startTime;
//// }
////
//// public void setStartTime(String startTime) {
//// this.startTime = startTime;
//// }
////
//// @Column(name = "dead_line")
//// public String getDeadLine() {
//// return deadLine;
//// }
////
//// public void setDeadLine(String deadLine) {
//// this.deadLine = deadLine;
//// }
////
//// @Column(name = "num_people")
//// public String getNumPeople() {
//// return numPeople;
//// }
////
//// public void setNumPeople(String numPeople) {
//// this.numPeople = numPeople;
//// }
////
//// @Column(name = "name")
//// public String getName() {
//// return name;
//// }
////
//// public void setName(String name) {
//// this.name = name;
//// }
////
//// @Column(name = "description")
//// public String getDescription() {
//// return description;
//// }
////
//// public void setDescription(String description) {
//// this.description = description;
//// }
//}
<file_sep>/src/main/java/com/wx/microprogram/Service/TaskService.java
//package com.wx.microprogram.Service;
//
//import com.wx.microprogram.Dao.TaskDao;
//import com.wx.microprogram.Entity.Task;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.util.List;
//
//@Service
//public class TaskService {
// @Autowired
// TaskDao taskDao;
//
// public List<Task> findByPublisherId(String publisherId){
// return taskDao.findByPublisherId(publisherId);
// }
//
// public Task findByPublisherIdAndTaskId(String publisherId,String taskId){
// return taskDao.findByPublisherIdAndTaskId(publisherId, taskId);
// }
//
// public void delete(Task task){
// taskDao.delete(task);
// }
//
// public void save(Task task) {taskDao.save(task);}
//}
<file_sep>/src/main/java/com/wx/microprogram/Service/UserService.java
//package com.wx.microprogram.Service;
//
//import com.wx.microprogram.Dao.UserDao;
//import com.wx.microprogram.Entity.User;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//@Service
//public class UserService {
// @Autowired
// UserDao userDao;
//
// public User findById(String id){
// return userDao.findById(id);
// }
// public void save(User user){userDao.save(user);}
//}
<file_sep>/src/main/java/com/wx/microprogram/Controller/TaskConroller.java
///**
// * @Author wangzhaoyu
// * @Date 2019/6/21 20:42
// */
//
//
//package com.wx.microprogram.Controller;
//
//import com.wx.microprogram.Entity.Task;
//import com.wx.microprogram.Pojo.RespPojo;
//import com.wx.microprogram.Service.TaskService;
//import com.wx.microprogram.Service.UserInTaskService;
//import com.wx.microprogram.Vo.PublishedTask;
//import com.wx.microprogram.mode.UserNameAndGroupName;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.util.ArrayList;
//import java.util.List;
//
//@RestController
//public class TaskConroller {
// @Autowired
// UserInTaskService userInTaskService; //寻找任务参与人员的服务
//
// @Autowired
// TaskService taskService; //任务服务
//
// /**
// * 获取我参与的任务列表--接口
// * @param userId
// * @return RespPojo(code,message,data)
// */
//// @ResponseBody
//// @RequestMapping("/showParticipatedTask")
//// public RespPojo showParticipatedTask(String userId){
//// List<TaskAndOneTask> taskAndOneTaskList = userInTaskService.findTaskAndOneTask(userId);
//// return new RespPojo(0,"SUCCESS",taskAndOneTaskList);
//// }
//
// /**
// * 获取我发布的任务列表--接口
// * @param publisherId
// * @return RespPojo(code,message,data)
// */
// @ResponseBody
// @RequestMapping("/showPublishedTask")
// public RespPojo showPublishedTask(String publisherId){
// List<Task> taskList = taskService.findByPublisherId(publisherId); //我发布的任务列表
// List<PublishedTask> publishedTasks = new ArrayList<>();
// for(Task task:taskList){
//// List<UserInTask> userInTaskList = userInTaskService.findByPublisherIdAndTaskId(task.getPublisherId(),task.getTaskId());
// //这里要对数据格式进行处理,每个userInTaskList的结构为对象列表 每个对象的内容为 GroupId + userIdLists
// List<UserNameAndGroupName> userNameAndGroupNames = userInTaskService.findByTaskId(task.getTaskId());
// publishedTasks.add(new PublishedTask(task,userNameAndGroupNames));
// }
// return new RespPojo(0,"SUCCESS",publishedTasks);
// }
//
// /**
// * 删除我发布的任务--接口
// * 这里删除之后,获取我参与的任务列表将不会显示与该任务有关的信息
// * @param publisherId
// * @param taskId
// * @return RespPojo(code,message,data)
// */
// @ResponseBody
// @RequestMapping("/deleteMyPublishTask")
// public RespPojo deleteMyPublishTask(String publisherId,String taskId){
// Task task = taskService.findByPublisherIdAndTaskId(publisherId, taskId);
// taskService.delete(task);
// return new RespPojo(0,"SUCCESS",null);
// }
//}
<file_sep>/src/main/java/com/wx/microprogram/mode/UserNameAndGroupName.java
//package com.wx.microprogram.mode;
//
//import com.wx.microprogram.Entity.User;
//import com.wx.microprogram.Entity.WorkingGroup;
//
//import java.io.Serializable;
//
///**
// * Created by wangzhaoyu.
// */
//public class UserNameAndGroupName implements Serializable{
// private static final long serialVersionUID = 1L;
//
// private String userName;
// private String groupName;
// public UserNameAndGroupName() {
// }
//
// public static long getSerialVersionUID() {
// return serialVersionUID;
// }
//
// public UserNameAndGroupName(User u, WorkingGroup wg) {
// this.userName = u.getName();
// this.groupName = wg.getGroupName();
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getGroupName() {
// return groupName;
// }
//
// public void setGroupName(String groupName) {
// this.groupName = groupName;
// }
//}
<file_sep>/schema.sql
-- schema.sql
drop database if exists webapp;
create database webapp;
use webapp;
create user 'webapp'@'localhost' identified by 'webapp';
grant select, insert, update, delete on webapp.* to 'webapp'@'localhost' with grant option;
/*
grant select, insert, update, delete on webapp.* to 'webapp'@'localhost' identified by 'webapp';
该sql语句在mysql5.0中可用,但是在8.0中已经不可用了。需要先创建用户,再授权,不能在一条sql语句中操作,新写法如下。
官网说明: https://dev.mysql.com/doc/refman/8.0/en/adding-users.html
*/
create table user(
`user_id` varchar(50) not null,
`nick_iame` varchar(50) not null comment '微信名',
`user_name` varchar(50) comment '真实姓名',
`image` varchar(500) not null comment '头像',
`school_num` varchar(50) comment '学号',
`phone_num` varchar(50) comment '手机号',
primary key (`user_id`)
)engine=innodb default charset=utf8;
create table fileOwner(
`task_id` varchar(50) not null,
`file_id` varchar(50) not null,
primary key (`task_id`)
)engine=innodb default charset=utf8;
create table userInGroup(
`user_id` varchar(50) not null,
`group_id` varchar(50) not null,
primary key (`user_id`,`group_id`)
)engine=innodb default charset=utf8;
create table workinggroup(
`publisher_id` varchar(50) not null,
`group_id` varchar(50) not null,
`group_name` varchar(50) not null,
primary key (`publisher_id`,`group_id`)
)engine=innodb default charset=utf8;
create table userInTask(
`user_id` varchar(50) not null,
`group_id` varchar(50) not null,
`task_id` varchar(50) not null,
primary key (`user_id`,`task_id`)
)engine=innodb default charset=utf8;
create table task(
`publisher_id` varchar(50) not null,
`task_id` varchar(50) not null,
`task_type` varchar(50) not null,
`start_time` varchar(50) not null,
`dead_line` varchar(50) not null,
`task_name` varchar(50) not null,
`description` varchar(50) not null,
primary key (`publisher_id`,`task_id`)
)engine=innodb default charset=utf8;
create table file(
`owner_id` varchar(50) not null,
`file_id` varchar(500) not null,
`file_name` varchar(500) not null,
`file_url` varchar(500) not null comment '文件地址',
`up_load_time` varchar(500) not null comment '上传时间',
unique key (`file_url`),
primary key (`owner_id`,`file_id`)
)engine=innodb default charset=utf8;<file_sep>/src/main/java/com/wx/microprogram/Entity/fileOwner.java
//package com.wx.microprogram.Entity;
//
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.Id;
//import javax.persistence.Table;
//
//@Entity
////@IdClass(MyFileMutiId.class)
//@Table(name = "fileOwner")
//public class fileOwner {
// @Id
// private String taskId;
// private String fileId;
//
// public fileOwner(){}
// @Column(name = "file_id")
// public String getFileId() {
// return fileId;
// }
//
// public void setFileId(String fileId) {
// this.fileId = fileId;
// }
//
// @Column(name = "task_id")
// public String getTaskId() {
//
// return taskId;
// }
//
// public void setTaskId(String taskId) {
// this.taskId = taskId;
// }
//}
<file_sep>/src/main/java/com/wx/microprogram/Entity/UserInGroup.java
//package com.wx.microprogram.Entity;
//
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.Id;
//import javax.persistence.Table;
//import java.io.Serializable;
//
//@Entity
//@Table(name = "userInGroup")
//public class UserInGroup implements Serializable{
// public UserInGroup() {
// }
// private String userId;
// @Id
// private String groupId;
//
// @Column(name = "user_id")
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// @Column(name = "group_id")
// public String getGroupId() {
// return groupId;
// }
//
// public void setGroupId(String groupId) {
// this.groupId = groupId;
// }
//}
<file_sep>/src/main/java/com/wx/microprogram/Entity/File.java
//package com.wx.microprogram.Entity;
//
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.Id;
//import javax.persistence.Table;
//import java.io.Serializable;
//
//@Entity
//@Table(name = "file")
//public class File implements Serializable{
//
//
// private String fileName;
// private String upLoadTime;
// @Id
// private String fileID;
// private String ownerID;
// private String fileUrl;
//
// @Column(name = "file_url")
// public String getFileUrl() {
// return fileUrl;
// }
//
// public void setFileUrl(String fileUrl) {
// this.fileUrl = fileUrl;
// }
//
// @Column(name = "file_id")
// public String getFileID() {
// return fileID;
// }
//
// public void setFileID(String fileID) {
// this.fileID = fileID;
// }
//
// @Column(name = "up_load_time")
// public String getUpLoadTime() {
// return upLoadTime;
// }
//
// public void setUpLoadTime(String upLoadTime) {
// this.upLoadTime = upLoadTime;
// }
//
// @Column(name = "file_name")
// public String getFileName() {
// return fileName;
// }
//
// public void setFileName(String fileName) {
// this.fileName = fileName;
// }
//
// @Column(name = "owner_id")
// public String getOwnerID() {
// return ownerID;
// }
//
// public void setOwnerID(String ownerID) {
// this.ownerID = ownerID;
// }
//}
<file_sep>/README.md
# test2019
only for test
<file_sep>/src/main/java/com/wx/microprogram/Dao/UserDao.java
//package com.wx.microprogram.Dao;
//
//import com.wx.microprogram.Entity.User;
//import org.springframework.data.jpa.repository.JpaRepository;
//import org.springframework.stereotype.Repository;
//
//@Repository
//public interface UserDao extends JpaRepository<User, Long> {
// public User findById(String id);
//}
<file_sep>/src/main/java/com/wx/microprogram/Dao/UserInTaskDao.java
//package com.wx.microprogram.Dao;
//
//import com.wx.microprogram.Pojo.TaskAndOneTask;
//import com.wx.microprogram.mode.UserNameAndGroupName;
//import org.springframework.data.jpa.repository.JpaRepository;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.stereotype.Repository;
//
//import java.util.List;
//
//@Repository
//public interface UserInTaskDao extends JpaRepository<com.wx.microprogram.Entity.UserInTask,Long> {
//// public List<UserInTask> findByUserId(String userId);
//// public UserInTask findByUserIdAndPublisherIdAndTaskId(String userId, String publisherId, String taskId);
//// public List<UserInTask> findByPublisherIdAndTaskId(String publisherId, String taskId);
//
//
//
//// public List<UserInTask> findByTaskId(String taskId);
//
//
// //获取我发布的某个任务中的工作组数量
// @Query(value = "select count(groupId) from UserInTask o where o.taskId = ?1")
// int findNumByTaskId(String taskId);
//
// //获取我发布的某个任务中的人员及其所在组别
// @Query(value = "select new com.wx.microprogram.mode.UserNameAndGroupName(u1,g) from UserInTask u,User u1, WorkingGroup g where u.taskId = ?1 and u.userId = u1.userId and g.groupId = u.groupId")
// List<UserNameAndGroupName> findByTaskId(String taskId);
//
//
//// @Query(value = "select t from UserInTask o,UserInGroup t where o.taskId = ?1 and o.userId=t.userId")
//// List<UserInGroup> findByTaskId(String taskId);
//
// /*
// 获取我参与的任务,sql语句封装
// */
// @Query(value = "select new TaskAndOneTask(t,o) from UserInTask o,Task t where o.userId=?1 and o.taskId=t.taskId ")
// List<TaskAndOneTask> findTaskAndOneTask(String userId);
//
//}
<file_sep>/src/main/java/com/wx/microprogram/Dao/UserConstantUserface.java
//package com.wx.microprogram.Dao;
//
//public interface UserConstantUserface {
//
// // 请求的网址
// public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
// // 你的appid
// public static final String WX_LOGIN_APPID = "wx27c54d63710dabc8";
// // 你的密匙
// public static final String WX_LOGIN_SECRET = "<KEY>";
// // 固定参数
// public static final String WX_LOGIN_GRANT_TYPE = "authorization_code";
//
//}
<file_sep>/src/main/java/com/wx/microprogram/Service/UserInTaskService.java
//package com.wx.microprogram.Service;
//
//
//import com.wx.microprogram.Dao.UserInTaskDao;
//import com.wx.microprogram.mode.UserNameAndGroupName;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.util.List;
//
//@Service
//public class UserInTaskService {
// @Autowired
// UserInTaskDao userInTaskDao;
//
//// public List<OneTask> findByUserId(String userId){
//// return oneTaskDao.findByUserId(userId);
//// }
////
//// public OneTask findByUserIdAndPublisherIdAndTaskId(String userId,String publisherId,String taskId){
//// return oneTaskDao.findByUserIdAndPublisherIdAndTaskId(userId, publisherId, taskId);
//// }
//// 查找我发布的某个任务中人员分布的情况
// public List<UserNameAndGroupName> findByTaskId(String taskId){
// return userInTaskDao.findByTaskId(taskId);
//
// }
//// public List<UserInTask> findByPublisherIdAndTaskId(String publisherId,String taskId){
//// return userInTaskDao.findByPublisherIdAndTaskId(publisherId, taskId);
//// }
//
// //查找我参与的任务
//// public List<TaskAndOneTask> findTaskAndOneTask(String userId){
//// return userInTaskDao.findTaskAndOneTask(userId);
//// }
////
//// public void save(OneTask oneTask){
//// oneTaskDao.save(oneTask);
//// }
//}
<file_sep>/src/main/java/com/wx/microprogram/Entity/User.java
package com.wx.microprogram.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
@Id
private String userId; //用户ID
private String phoneNum; //用户手机号码
private String schoolNum; //用户学号
private String userName; //用户姓名
private String image; //用户头像
private String nickName; //用户微信名称
public User(){}
@Column(name = "user_id")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Column(name = "phone_num")
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
@Column(name = "school_num")
public String getSchoolNum() {
return schoolNum;
}
public void setSchoolNum(String schoolNum) {
this.schoolNum = schoolNum;
}
@Column(name = "user_name")
public String getName() {
return userName;
}
public void setName(String name) {
this.userName = name;
}
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Column(name = "nick_name")
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
<file_sep>/src/main/java/com/wx/microprogram/Controller/OneTaskController.java
//package com.wx.microprogram.Controller;
//
//
//import org.springframework.web.bind.annotation.RestController;
//
//@RestController
//public class OneTaskController {
//// @Autowired
//// OneTaskService oneTaskService;
////
////
//// /**
//// * 获取我参与的任务列表--接口
//// * @param userId
//// * @return RespPojo(code,message,data)
//// */
//// @ResponseBody
//// @RequestMapping("/showParticipatedTask")
//// public RespPojo showParticipatedTask(String userId){
//// List<OneTask> oneTaskList = oneTaskService.findByUserId(userId);
//// return new RespPojo(0,"SUCCESS",oneTaskList);
//// }
////
////
//// /**
//// * 获取我发布的任务列表--接口
//// * @param userId
//// * @return RespPojo(code,message,data)
//// */
//// @ResponseBody
//// @RequestMapping("/showMyPublishTask")
//// public RespPojo showMyPublishTask(String userId){
//// List<OneTask> oneTaskList = oneTaskService.findByPublisherId(userId);
////
////
////
//// return new RespPojo();
//// }
////
//// /**
//// * 删除我发布的任务--接口
//// * @param userId
//// * @param taskId
//// * @return RespPojo(code,message,data)
//// */
//// @ResponseBody
//// @RequestMapping("/deleteMyPublishTask")
//// public RespPojo deleteMyPublishTask(String userId,String taskId){
//// List<OneTask> oneTaskList = oneTaskService.findByPublisherIdAndTaskId(userId,taskId);
//// oneTaskService.deleteInBatch(oneTaskList);
//// return new RespPojo(0,"SUCCESS",null);
//// }
//
//}
<file_sep>/src/main/java/com/wx/microprogram/Pojo/OneTaskMutiId.java
//package com.wx.microprogram.Pojo;
//
//import java.io.Serializable;
//
//public class OneTaskMutiId implements Serializable {
// private String userId;
// private String taskId;
// private String publisherId;
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getTaskId() {
// return taskId;
// }
//
// public void setTaskId(String taskId) {
// this.taskId = taskId;
// }
//
// public String getPublisherId() {
// return publisherId;
// }
//
// public void setPublisherId(String publisherId) {
// this.publisherId = publisherId;
// }
//}
<file_sep>/src/main/java/com/wx/microprogram/Form/PublishTaskForm.java
//package com.wx.microprogram.Form;
//
//import lombok.Data;
//
//import javax.validation.constraints.NotEmpty;
//
///**
// * @author <NAME>
// * @create 2019-05-27 下午8:51
// */
//@Data
//public class PublishTaskForm {
// String publisherId;
//
// String taskType;
//
// String deadLine;
//
// String description;
// @NotEmpty(message = "名称必填")
// String name;
//
// String groupId;
//
// String numPeople;
//
// public String getPublisherId() {
// return publisherId;
// }
//
// public String getTaskType() {
// return taskType;
// }
//
// public @NotEmpty(message = "名称必填") String getName() {
// return name;
// }
//
// public String getGroupId() {
// return groupId;
// }
//
// public String getDeadLine() {
// return deadLine;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getNumPeople() {
// return numPeople;
// }
//}
<file_sep>/src/main/java/com/wx/microprogram/Service/WorkingGroupService.java
//package com.wx.microprogram.Service;
//
//import com.wx.microprogram.Dao.WorkingGroupDao;
//import com.wx.microprogram.Entity.WorkingGroup;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.util.List;
//
//@Service
//public class WorkingGroupService {
// @Autowired
// WorkingGroupDao workingGroupDao;
//
// public WorkingGroup findByPublisherIdAndGroupId(String publisherId, String groupId){
// return workingGroupDao.findByPublisherIdAndGroupId(publisherId,groupId);
// }
//
//// public WorkingGroup findByPublisherIdAndGroupIdAndUserId(String publisherId, String groupId, String userId){
//// return workingGroupDao.findByPublisherIdAndGroupIdAndUserId(publisherId, groupId, userId);
//// }
//
// public List<WorkingGroup> findall(){
// return workingGroupDao.findall();
// }
//
// public List<WorkingGroup> findAllByGroupId(String groupId){
// return workingGroupDao.findAllByGroupId(groupId);
// }
//
// public List<WorkingGroup> findByPublisherId(String publisherId){
// return workingGroupDao.findByPublisherId(publisherId);
// }
// public List<WorkingGroup> findByGroupId(String groupId){
// return workingGroupDao.findByGroupId(groupId);
// }
// public void save(WorkingGroup workingGroup){
// workingGroupDao.save(workingGroup);
// }
//
//// public WorkingGroup findByUserId(String userId){
//// return workingGroupDao.findByUserId(userId);
//// }
//}
<file_sep>/src/main/java/com/wx/microprogram/Entity/UserInTask.java
//package com.wx.microprogram.Entity;
//
//import javax.persistence.*;
//import java.io.Serializable;
//
//@Entity
//@Table(name = "userInTask")
//public class UserInTask implements Serializable{
// @Id
// private String taskId;
// private String userId;
// private String groupId;
//
// public UserInTask() {
// }
// @Column(name = "task_id")
// public String getTaskId() {
// return taskId;
// }
// public void setTaskId(String taskId) {
// this.taskId = taskId;
// }
//
// @Column(name = "user_id")
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// @Column(name = "group_id")
// public String getGroupId() {
// return groupId;
// }
//
// public void setGroupId(String groupId) {
// this.groupId = groupId;
// }
//}
<file_sep>/src/main/java/com/wx/microprogram/Pojo/TaskAndOneTask.java
//package com.wx.microprogram.Pojo;
//
//import com.wx.microprogram.Entity.UserInTask;
//import com.wx.microprogram.Entity.Task;
//
//import java.io.Serializable;
//
//public class TaskAndOneTask implements Serializable {
// private static final long serialVersionUID = -6347911007178390219L;
//
// private UserInTask userInTask;
// private Task task;
//
// public TaskAndOneTask(Task task, UserInTask userInTask){
// this.userInTask = userInTask;
// this.task = task;
// }
//
// public static long getSerialVersionUID() {
// return serialVersionUID;
// }
//
// public UserInTask getUserInTask() {
// return userInTask;
// }
//
// public void setUserInTask(UserInTask userInTask) {
// this.userInTask = userInTask;
// }
//
// public Task getTask() {
// return task;
// }
//
// public void setTask(Task task) {
// this.task = task;
// }
//}
| a239c662979de3e726ff3ef1c329be100ec62737 | [
"Markdown",
"Java",
"SQL"
] | 21 | Java | chuandajiba/ShouBei | 29091d4591c86ca9cc08e795eeab04d610b0103c | 8c710444832e5979e52d5e71fabb2c1ac923af59 |
refs/heads/master | <file_sep>/*
package com.phoenix.service.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
*/
/**
* @author tianFeng
* @version 1.0, 2018/07/30
*//*
public class CommandHelloWorld extends HystrixCommand<String> {
private String name;
*/
/*protected CommandHelloWorld(HystrixCommandGroupKey group) {
super(group);
}*//*
public CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
@Override
protected String run() throws Exception {
return "hello " + name;
}
}
*/
<file_sep>
package com.phoenix.common.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class UserVO implements Serializable {
private static final long serialVersionUID = -125375525997353959L;
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private Boolean sex;
private Date birthday;
private Date created;
private Date updated;
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.example</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>web</artifactId>
<packaging>war</packaging>
<name>web Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>service</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>dao</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.4</version>
</dependency>-->
<dependency>
<groupId>com.netflix.rxjava</groupId>
<artifactId>rxjava-core</artifactId>
<version>0.20.7</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--my config-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!--<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>-->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>org.roaringbitmap</groupId>
<artifactId>RoaringBitmap</artifactId>
</dependency>
<!-- swagger-mvc -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
<exclusion>
<artifactId>spring-context</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-beans</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-aop</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<!--<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>RELEASE</version>
</dependency>-->
<!-- swagger-mvc -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!--<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
</dependency>-->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>64.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.roaringbitmap</groupId>
<artifactId>RoaringBitmap</artifactId>
<version>0.9.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
</dependencies>
</project>
<file_sep>package com.phoenix.web;
import lombok.Data;
/**
* @author tianFeng
* @date 2022-11-07 18:38
*/
@Data
public class MyClass {
private Integer a;
}
<file_sep>package utils;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
/**
* @author foolish-bird
* @date 2023/1/6
*/
public class WeakCache<K, V> {
private Map<K, V> cache;
private ReentrantReadWriteLock reentrantLock = new ReentrantReadWriteLock();
private ReadLock readLock = reentrantLock.readLock();
private WriteLock writeLock = reentrantLock.writeLock();
public WeakCache() {
cache = new WeakHashMap<>(16);
}
public WeakCache(int capacity) {
cache = new WeakHashMap<>(capacity);
}
public V get(K key) {
readLock.lock();
try {
return cache.get(key);
} finally {
readLock.unlock();
}
}
public void put(K key, V value) {
writeLock.lock();
try {
cache.put(key, value);
} finally {
writeLock.unlock();
}
}
public void putAll(Map<? extends K, ? extends V> map) {
if (map == null || map.isEmpty()) {
return;
}
writeLock.lock();
try {
map.forEach((k, v) -> cache.put(k, v));
} finally {
writeLock.unlock();
}
}
public void remove(K key) {
writeLock.lock();
try {
cache.remove(key);
} finally {
writeLock.unlock();
}
}
}
<file_sep>/*
package com.phoenix.service.hystrix;
import com.netflix.hystrix.HystrixCommand;
*/
/**
* @author tianFeng
* @version 1.0, 2018/07/30
*//*
public class RemoteServiceTestCommand extends HystrixCommand<String> {
private RemoteServiceTestSimulator remoteServiceTestSimulator;
public RemoteServiceTestCommand(Setter setter, RemoteServiceTestSimulator remoteServiceTestSimulator) {
super(setter);
this.remoteServiceTestSimulator = remoteServiceTestSimulator;
}
@Override
protected String run() throws Exception {
return remoteServiceTestSimulator.execute();
}
}
*/
<file_sep>package com.phoenix.web;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/**
* @Auther: tianfeng
* @Date: 2020-08-17 20:12
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class Student{
int stuId;
int stuAge;
String stuName;
List<String> boxCodes;
Student(int id, int age, String name){
this.stuId = id;
this.stuAge = age;
this.stuName = name;
}
public int getStuId() {
return stuId;
}
public int getStuAge() {
return stuAge;
}
public String getStuName() {
return stuName;
}
public static List<Student> getStudents(){
List<Student> list = new ArrayList<>();
list.add(new Student(11, 28, "Lucy"));
//list.add(new Student(28, 27, "Kiku"));
//list.add(new Student(32, 30, "Dani"));
//list.add(new Student(49, 27, "Steve"));
return list;
}
public List<String> getBoxCodes() {
return boxCodes;
}
public void setBoxCodes(List<String> boxCodes) {
this.boxCodes = boxCodes;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
}
class Example {
public static void main(String[] args) {
Student student = new Student();
student.setStuName("123");
List<String> stringList = new ArrayList<>();
stringList.add("abc");
stringList.add("efg");
student.setBoxCodes(stringList);
System.out.println(JSON.toJSONString(student));
Predicate<Student> p1 = s -> s.stuName.startsWith("L");
//Predicate<Student> p2 = s -> s.stuAge < 28 && s.stuName.startsWith("P");
List<Student> list = Student.getStudents();
/* noneMatch() method returns true if none of the stream elements matches
* the given predicate
*/
/* This will return false because there is a element in the stream that
* matches the condition specified in the predicate p1.
* Condition: Student Name should start with letter "L"
* Stream element matched: Lucy
*/
boolean b1 = list.stream().noneMatch(s -> judge(s,"L"));
System.out.println("list.stream().noneMatch(p1): "+b1);
/* This will return true because none of the elements
* matches the condition specified in the predicate p2.
* Condition: Student Name should start with letter "P" and age must be <28
* Stream element matched: none
*/
//boolean b2 = list.stream().noneMatch(p2);
//System.out.println("list.stream().noneMatch(p2): "+b2);
}
private static boolean judge(Student s, String l) {
String name = s.getStuName();
return name.startsWith(l);
}
}
<file_sep>package service;
import entity.BdLivePlanProduct;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
/**
* (BdLivePlanProduct)表服务接口
*
* @author makejava
* @since 2022-11-02 15:10:24
*/
public interface BdLivePlanProductService {
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
BdLivePlanProduct queryById(Long id);
/**
* 分页查询
*
* @param bdLivePlanProduct 筛选条件
* @param pageRequest 分页对象
* @return 查询结果
*/
Page<BdLivePlanProduct> queryByPage(BdLivePlanProduct bdLivePlanProduct, PageRequest pageRequest);
/**
* 新增数据
*
* @param bdLivePlanProduct 实例对象
* @return 实例对象
*/
BdLivePlanProduct insert(BdLivePlanProduct bdLivePlanProduct);
/**
* 修改数据
*
* @param bdLivePlanProduct 实例对象
* @return 实例对象
*/
BdLivePlanProduct update(BdLivePlanProduct bdLivePlanProduct);
/**
* 通过主键删除数据
*
* @param id 主键
* @return 是否成功
*/
boolean deleteById(Long id);
}
<file_sep>package com.phoenix.web.controller;
import org.springframework.stereotype.Component;
/**
* @author phoenix
* @Auther: tianfeng
* @Date: 2021-02-19 10:03
*/
@StrategyType(PayStrategyEnum.ALI_PAY)
@Component
public class AliPayStrategy implements PayStrategy {
@Override
public String pay(String method) {
return "调用阿里支付...AliPayStrategy";
}
}
<file_sep>package com.phoenix.common.dto;
import lombok.Data;
import java.io.Serializable;
/**
* @author tianFeng
* @version 1.0, 2018/06/15
*/
@Data
public class PageQuery implements Serializable {
private static final long serialVersionUID = -2261297137167970438L;
private Integer offset = 0;
private Integer limit = 10;
}
<file_sep>package com.phoenix.web.controller;
import com.github.pagehelper.PageHelper;
import com.phoenix.common.dto.UserForm;
import com.phoenix.common.model.User;
import com.phoenix.common.model.UserVO;
import com.phoenix.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author tianFeng
* @version 1.0, 2018/06/15
*/
@Controller
@RequestMapping(value = "user")
public class UserController {
private static final Logger LOG = LoggerFactory.getLogger(UserController.class);
@Resource
private UserService userService;
@ApiOperation(value = "test", httpMethod = "GET", notes = "test")
@RequestMapping(value = "list", method = RequestMethod.GET)
@ResponseBody
public UserVO test() {
User user = new User();
user.setUserName("phoenix");
user.setAge(24);
user.setCreated(new Date());
UserVO userVO = new UserVO();
BeanUtils.copyProperties(user, userVO);
LOG.trace("-----------------------------------trace");
LOG.debug("-----------------------------------debug");
LOG.info("-----------------------------------info");
LOG.warn("-----------------------------------warn");
LOG.error("-----------------------------------error");
return userVO;
}
@ApiOperation(value="获取用户列表", notes="")
@RequestMapping(value = "getAll", method= RequestMethod.GET)
@ResponseBody
public List<UserVO> getAll(UserForm userForm) {
List<User> userList = userService.getAll(userForm);
List<UserVO> userVOList = new ArrayList<>();
UserVO userVO = null;
if (!CollectionUtils.isEmpty(userList)) {
for (User user : userList) {
userVO = new UserVO();
BeanUtils.copyProperties(user, userVO);
userVOList.add(userVO);
}
}
return userVOList;
}
@ApiOperation(value="获取用户分页列表", notes="")
@RequestMapping(value = "getUserList", method= RequestMethod.GET)
@ResponseBody
public List<UserVO> getUserList(UserForm userForm) {
List<User> userList = userService.getListWithPage(userForm);
List<UserVO> userVOList = new ArrayList<>();
UserVO userVO = null;
if (!CollectionUtils.isEmpty(userList)) {
for (User user : userList) {
userVO = new UserVO();
BeanUtils.copyProperties(user, userVO);
userVOList.add(userVO);
}
}
PageHelper.startPage(1, 10);
return userVOList;
}
@ApiOperation(value="获取用户详情", notes="")
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
@ResponseBody
public UserVO getById(@PathVariable Long id) {
User user = userService.getById(id);
UserVO userVO = new UserVO();
BeanUtils.copyProperties(user, userVO);
return userVO;
}
@ApiOperation(value="新增用户", notes="")
@RequestMapping(value = "",method = RequestMethod.POST)
@ResponseBody
public int add(@RequestBody UserForm userForm) {
userForm.setCreated(new Date());
return userService.save(userForm);
}
@ApiOperation(value="更新用户", notes="")
@RequestMapping(value = "",method = RequestMethod.PUT)
@ResponseBody
public int update(@RequestBody UserForm userForm) {
userForm.setUpdated(new Date());
return userService.update(userForm);
}
@ApiOperation(value="删除用户", notes="")
@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
@ResponseBody
public int delete(@PathVariable Long id) {
return userService.deleteById(id);
}
}
<file_sep>package service.impl;
import com.github.pagehelper.Page;
import dao.LiveOrderItemDao;
import entity.LiveOrderItem;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import service.LiveOrderItemService;
import javax.annotation.Resource;
import java.awt.print.Pageable;
/**
* (LiveOrderItem)表服务实现类
*
* @author makejava
* @since 2022-09-02 15:37:47
*/
@Service("liveOrderItemService")
public class LiveOrderItemServiceImpl implements LiveOrderItemService {
@Resource
private LiveOrderItemDao liveOrderItemDao;
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
@Override
public LiveOrderItem queryById(Long id) {
return this.liveOrderItemDao.queryById(id);
}
/**
* 分页查询
*
* @param liveOrderItem 筛选条件
* @param pageRequest 分页对象
* @return 查询结果
*/
@Override
public Page<LiveOrderItem> queryByPage(LiveOrderItem liveOrderItem, PageRequest pageRequest) {
long total = this.liveOrderItemDao.count(liveOrderItem);
return null;
}
/**
* 新增数据
*
* @param liveOrderItem 实例对象
* @return 实例对象
*/
@Override
public LiveOrderItem insert(LiveOrderItem liveOrderItem) {
this.liveOrderItemDao.insert(liveOrderItem);
return liveOrderItem;
}
/**
* 修改数据
*
* @param liveOrderItem 实例对象
* @return 实例对象
*/
@Override
public LiveOrderItem update(LiveOrderItem liveOrderItem) {
this.liveOrderItemDao.update(liveOrderItem);
return this.queryById(liveOrderItem.getId());
}
/**
* 通过主键删除数据
*
* @param id 主键
* @return 是否成功
*/
@Override
public boolean deleteById(Long id) {
return this.liveOrderItemDao.deleteById(id) > 0;
}
}
<file_sep>package com.phoenix.web.controller;
import java.lang.annotation.*;
/**
* @author phoenix
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface StrategyType {
PayStrategyEnum value();
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.example</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service</artifactId>
<packaging>jar</packaging>
<name>service Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>dao</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.4</version>
</dependency>-->
<dependency>
<groupId>com.netflix.rxjava</groupId>
<artifactId>rxjava-core</artifactId>
<version>0.20.7</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.25.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--my config-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!--<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>-->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
</dependency>
</dependencies>
<!--<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<!– 配置文件的位置–>
<configurationFile>service/src/main/resources/mybatis-generator-config.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>-->
<!--<repositories>
<repository>
<id>aliyun-nexus</id>
<name>Aliyun Maven Repository</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>-->
</project>
<file_sep>/*
package com.phoenix.service.hystrix;
*/
/**
* @author tianFeng
* @version 1.0, 2018/07/30
*//*
public class RemoteServiceTestSimulator {
private long wait;
public RemoteServiceTestSimulator(long wait) throws InterruptedException {
this.wait = wait;
}
String execute() throws InterruptedException {
Thread.sleep(wait);
return "Success";
}
}
*/
<file_sep>package com.phoenix.web.controller;
/**
* @author phoenix
*/
public enum PayStrategyEnum {
/**
* 阿里支付
*/
ALI_PAY(1,"com.ultiwill.strategy.impl.AliPayStrategy"),
/**
* 微信支付
*/
WECHAT_PAY(2,"com.ultiwill.strategy.impl.WeChatPayStrategy")
;
private Integer type;
private String desc;
PayStrategyEnum(Integer type, String desc) {
this.type = type;
this.desc = desc;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
<file_sep>package com.phoenix.web.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
/**
* @author tianfeng
* @date 2022-01-13 15:07
*/
@Component
@Slf4j
public class StrategyFactory implements ApplicationContextAware {
@Resource
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
applicationContext = this.applicationContext;
}
public PayStrategy getPayStrategy(PayStrategyEnum payStrategyEnum) {
//Map<String, PayStrategy> beansOfType = applicationContext.getBeansOfType(PayStrategy.class);
//applicationContext.findAnnotationOnBean()
// Getting annotated beans with names
Map<String, Object> allBeansWithNames = applicationContext.getBeansWithAnnotation(StrategyType.class);
//If you want the annotated data
PayStrategy result = null;
for (Map.Entry<String, Object> entry : allBeansWithNames.entrySet()) {
String beanName = entry.getKey();
Object bean = entry.getValue();
StrategyType strategyType = applicationContext.findAnnotationOnBean(beanName, StrategyType.class);
log.info("testDetails: {}", strategyType);
PayStrategyEnum value = strategyType.value();
if (Objects.equals(value, payStrategyEnum)) {
result = (PayStrategy) bean;
break;
}
}
return result;
}
}
<file_sep>package com.phoenix.web;
/**
* @Auther: tianFeng
* @Date: 2023-02-10 11:30
*/
public class Demo {
public String hello() {
//System.out.println("hello world!");
return "hello world!";
}
// 用户登录系统方法:
/*public String LoginSystem(String userName, String password) {
String result = "";
// 根据用户名从数据库中获取密码信息,判断密码是否正确。
// SQL语句:SELECT password FROM users WHERE username=username;
ResultSet rs = statement.executeQuery("SELECT password FROM users WHERE username=" + userName);
if (rs.next()) {
// 验证用户密码是否正确。
if (password.equals(rs.getString("password"))) {
// 登录成功
result = "success";
} else {
// 密码错误,登录失败
result = "failure";
}
} else {
result = "notfound"; // 用户名不存在,用户未注册
}
return result;
}*/
}
<file_sep>package com.phoenix.service;
import com.phoenix.common.dto.UserForm;
import com.phoenix.common.model.User;
import java.util.List;
/**
* @author tianFeng
* @version 1.0, 2018/06/15
*/
public interface UserService {
User getById(Long id);
int deleteById(Long id);
int save(UserForm userForm);
int update(UserForm userForm);
/* define */
List<User> getListWithPage(UserForm userForm);
List<User> getAll(UserForm userForm);
}
<file_sep>package com.phoenix.web;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.StringUtils;
import org.roaringbitmap.RoaringBitmap;
import org.springframework.util.DigestUtils;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
/**
* @author tianFeng
* @date 2022-10-28 11:03
*/
public class Test1028 {
public static void test(Integer a) {
a++;
}
public static void test1(MyClass myClass) {
Integer a = myClass.getA();
myClass.setA(++a);
}
public static void main(String[] args) {
String regex = "_";
String[] split = "hello_world".split(regex);
System.out.println(split[0]);
System.out.println(split[1]);
MyClass myClass = new MyClass();
myClass.setA(0);
Integer abc = 0;
for (int i = 0; i < 10; i++) {
test(abc);
test1(myClass);
}
System.out.println("abc:"+ abc);
System.out.println("myClass.a:" + myClass.getA());
String str = "";
System.out.println(str.length());
System.out.println("2022-07-31".length());
System.out.println(StringUtils.isNotBlank(str));
System.out.println(StringUtils.isNotEmpty(str));
System.out.println(StringUtils.isNotBlank(null));
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate ld = LocalDate.parse("2022-07-31", dateTimeFormatter);
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(23, 59, 59));
System.out.println(ldt);
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld2 = LocalDate.parse("20221104", dateTimeFormatter2);
LocalDateTime ldt2 = LocalDateTime.of(ld2, LocalTime.of(23, 59, 59));
System.out.println(ldt2);
System.out.println("2022-07-31 compare 20221104:" + ldt.compareTo(ldt2));
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String text = date.format(formatter);
System.out.println(text);
String hello_world = stringToMD5("hello world");
System.out.println(hello_world);
RoaringBitmap rr = RoaringBitmap.bitmapOf(1,2,3,1000);
RoaringBitmap rr2 = new RoaringBitmap();
rr2.add(4000L,4255L);
LocalDate localDate = LocalDate.of(2022, 11, 3);
BigDecimal bigDecimal = new BigDecimal("1.11");
BigDecimal bigDecimal2 = new BigDecimal("1.110");
Integer i = 333;
String hello = Joiner.on(";").skipNulls().join(localDate, "hello", i, null, "", bigDecimal);
System.out.println(hello);
String world = Joiner.on(";").skipNulls().join(localDate, "hello", 333L, null, "", bigDecimal2);
System.out.println(world);
LocalDate before = LocalDate.of(2022, 9, 1);
LocalDate now = LocalDate.now();
LocalDate param = before;
while (param.isBefore(now)) {
System.out.println(param);
param = param.plusDays(1);
}
}
/**
* 使用springboot自带MD5加密
* 需要引入包 import org.springframework.util.DigestUtils;
* @param str
* @return String
*/
public static String stringToMD5(String str)
{
return DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8));
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springboot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<modules>
<module>web</module>
<module>dao</module>
<module>common</module>
<module>service</module>
</modules>
<packaging>pom</packaging>
<name>springboot-demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring.version>2.2.1.RELEASE</spring.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
<!--<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.1.0</version>
</dependency>-->
<!--<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.4</version>
</dependency>-->
<dependency>
<groupId>com.netflix.rxjava</groupId>
<artifactId>rxjava-core</artifactId>
<version>0.20.7</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.25.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>2.2.1.RELEASE</version>
</dependency>
<!--my config-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
<!--<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.9.10</version>
</dependency>-->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.11.4</version>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!-- swagger-mvc -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
<exclusion>
<artifactId>spring-context</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-beans</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-aop</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<!-- swagger-mvc -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.1</version>
</dependency>
<!--<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.69</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>64.2</version>
</dependency>
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>commons-chain</groupId>
<artifactId>commons-chain</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.roaringbitmap</groupId>
<artifactId>RoaringBitmap</artifactId>
<version>0.9.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>aliyun-nexus</id>
<name>Aliyun Maven Repository</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<!--<build>
<finalName>service</finalName>
<pluginManagement><!– lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) –>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!– see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging –>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<!–<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>–>
</plugins>
</pluginManagement>
</build>-->
</project>
| 72267bdacbd9c1de48a6a799d998ff86ebc8bf15 | [
"Java",
"Maven POM"
] | 21 | Java | parkdifferent/springboot-demo | 004d580667bd027a526fae0c96ebe3bf50e6a2c6 | 27a3e2a4e435eef8c256b2c810d2005822063589 |
refs/heads/master | <file_sep>import React from 'react';
import Sider from './Sider';
import {Layout} from 'antd';
import { withRouter } from 'react-router-dom';
import './Experience.css';
import banner from "../Images/beach.jpg";
const {Content} = Layout;
const Experience = props =>(
<Layout className = "layout">
<Sider menuKey={'2'} />
<Content>
<div style={{
minHeight: '100vh',
backgroundImage: `url(${banner})`,
backgroundSize: 'cover',
padding: 150
}}>
<h1>Hello World!!!</h1>
</div>
</Content>
</Layout>
);
export default withRouter(Experience);<file_sep>import React from 'react';
import {Menu, Icon, Button, Layout} from 'antd';
import './Sider.css';
import {Link, NavLink} from 'react-router-dom';
import Pdf from '../Documents/Derek_Ortega_Resume.pdf';
class Sider extends React.Component{
state = {
collapsed: false,
};
props = {
menuKey: '1',
};
toggleCollapsed = () => {
this.setState({
collapsed: !this.state.collapsed,
});
};
// menuSelect = e => {
// this.setState( {
// menuKey: e.key,
// });
// };
render(){
const SubMenu = Menu.SubMenu;
return(
<Layout.Sider trigger={null}
collapsible
collapsed={this.state.collapsed}>
<div style={{ width: 200 }}>
<Menu
onClick={this.menuSelect}
selectedKeys={[this.props.menuKey]}
defaultOpenKeys={['sub1']}
mode="inline"
theme="dark"
inlineCollapsed={this.state.collapsed}
>
<Button type="primary" onClick={this.toggleCollapsed} style={{ marginBottom: 16 }}>
<Icon type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'} />
</Button>
<Menu.Item key="1" >
<Icon type="home" />
<span>Home</span>
<Link to= "."/>
</Menu.Item>
<Menu.Item key="2" >
<Icon type="laptop" />
<span>Experience</span>
<Link to= './Experience'></Link>
</Menu.Item>
<Menu.Item key="3">
<Icon type="code" />
<span>Projects</span>
<Link to={'./Projects'}/>
</Menu.Item>
<Menu.Item key = '4'>
<Icon type = 'github'/>
<span>Github</span>
<a href = "https://github.com/bamfman22"></a>
</Menu.Item>
<Menu.Item key = '5'>
<Icon type = 'linkedin'/>
<span>LinkedIn</span>
<a href = "https://www.linkedin.com/in/derek-ortega-6a4549124/"></a>
</Menu.Item>
<Menu.Item key = '6'>
<Icon type = 'file-pdf'/>
<span>Resume PDF</span>
<a href = {Pdf} target = "_blank">Download Pdf</a>
</Menu.Item>
</Menu>
</div>
</Layout.Sider>
)
}}
export default Sider;<file_sep>import React, { Component } from 'react';
import Home from './Components/Home';
import Experience from './Components/Experience';
import './App.css';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Projects from "./Components/Projects";
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/Experience" component={Experience}/>
<Route exact path={'/Projects'} component={Projects}/>
</Switch>
</Router>
);
}
}
export default App;
| 9f747afea3421cc7eb0b69e3ca463140c65d7233 | [
"JavaScript"
] | 3 | JavaScript | bamfman22/my-resume | 10dccb898dcee0c2dcd72a727d7ec7f52ed22f5f | 2c31e2c7a997225047dcf8cc384fefbba121f6a9 |
refs/heads/master | <repo_name>vdoraira/MERN<file_sep>/MovieAppInReact/UI/src/js/components/GetAllMovies.js
var MovieList=require('./MovieList');
var GetAllMovies = React.createClass({
getInitialState:function(){
return{
data: null
};
},
loadCommentsFromServer:function(){
$.ajax({
url: '/api/movies',
type:'get',
dataType: 'json',
cache: false,
success: function(movies) {
// console.log('---ajax---'+movies);
this.setState({data: movies});
}.bind(this),
error: function(xhr, status, err) {
console.error('/api/movies', status, err.toString());
}.bind(this),
});
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, 500);
},
render: function(){
return (
<MovieList data={this.state.data} />
);
}
});
module.exports=GetAllMovies;
<file_sep>/MovieAppInReact/UI/src/js/components/SearchMovie.js
var BasicInputBox=require('./BasicInputBox');
var SearchMovie=React.createClass({
getInitialState: function(){
return {
name:'',
data:{},
msg:''
}
},
handleSubmit:function(){
//alert(this.props.data.Year);
$.ajax({
url: '/api/movies/',
type:'post',
data:$('#saveMovie').serialize(),
cache: false,
success: function(data) {
// console.log('---moviedata---'+data);
}.bind(this)
});
this.setState({msg: 'Movie Added Successfully'}),
this.setState({data: {}})
},
submit: function (e){
var self
e.preventDefault()
self = this
// alert(this.state.name);
$.ajax({
url: '/api/search/'+this.state.name,
type:'get',
cache: false,
success: function(data) {
this.setState({data:data});
// console.log('---moviedata---'+data);
}.bind(this)
})
.fail(function(fail) {
console.log('failed to register');
});
},
clearForm: function() {
this.setState({
name: "",
});
},
nameChange: function(e){
this.setState({name: e.target.value})
//this.setState({msg: 'Please Enter A Movie Title'})
},
render: function (){
return (
<div className="container col-md-12">
<div className=" row well" >
<form onSubmit={this.submit} >
<div className='searchBar'>
<BasicInputBox label="Name:" valChange={this.nameChange} val={this.state.name}/>
<button type="submit" className='form-control btn-info'>Search</button>
</div>
</form>
</div>
{this.state.data.Title!=undefined ? <form id="saveMovie">
<div className={'form-group row'}>
<label for="title" className={'col-sm-6 form-control-label'}>Title: </label>
<div className={'col-sm-6 title'}>
<input type="text" className={'form-control input-tag'} name="Title" defaultValue={this.state.data.Title} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="releasedate" className={'col-sm-6 form-control-label'}>Year: </label>
<div className={'col-sm-6 date'}>
<input type="number" className={'form-control input-tag'} name="Year" defaultValue={this.state.data.Year} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="director" className={'col-sm-6 form-control-label'}>Release Date: </label>
<div className={'col-sm-6 director'}>
<input type="text" className={'form-control input-tag'} name="Released" defaultValue={this.state.data.Released} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Runtime: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Runtime" defaultValue={this.state.data.Runtime} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Genre: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Genre" defaultValue={this.state.data.Genre} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Director: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Director" defaultValue={this.state.data.Director} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Writer: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Writer" defaultValue={this.state.data.Writer} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Actors: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Actors" defaultValue={this.state.data.Actors} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="about" className={'col-sm-6 form-control-label'}>Plot: </label>
<div className={'col-sm-6 about'}>
<textarea className={'form-control input-tag'} name="Plot" defaultValue={this.state.data.Plot} rows="5" cols="10">
</textarea>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Language: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Language" defaultValue={this.state.data.Language} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Country: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Country" defaultValue={this.state.data.Country} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Awards: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Awards" defaultValue={this.state.data.Awards} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Poster: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Poster" defaultValue={this.state.data.Poster} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Metascore: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Metascore" defaultValue={this.state.data.Metascore} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>IMDB rating: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="imdbRating" defaultValue={this.state.data.imdbRating} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>IMDB Votes: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="imdbVotes" defaultValue={this.state.data.imdbVotes} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>IMDB ID: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="imdbID" defaultValue={this.state.data.imdbID} required="required"/>
</div>
</div>
<div className={'form-group row'}>
<label for="actors" className={'col-sm-6 form-control-label'}>Type: </label>
<div className={'col-sm-6 actors'}>
<input type="text" className={'form-control input-tag'} name="Type" defaultValue={this.state.data.Type} required="required"/>
</div>
</div>
<input type="hidden" className={'form-control input-tag'} name="Rated" defaultValue={this.state.data.Rated} />
<input type="hidden" className={'form-control input-tag'} name="Response" defaultValue={this.state.data.Response} />
<div className={'form-group row adbt'}>
<div className={'col-sm-offset-4 col-sm-6'}>
<button type="button" onClick={this.handleSubmit} className={'btn btn-info pull-right'}>Save</button>
</div>
</div>
</form>
: this.state.msg!=''?<div><h3 className='text-center'>Movie Added Successfully</h3></div>:<div></div>}
</div>
);
}
});
module.exports=SearchMovie
<file_sep>/node/myServer.js
var Http=require('http'),
fs=require('fs'),
url=require('url'),
path=require('path');
var server=Http.createServer(function (req,res) {
var pathName=url.parse(req.url).pathname;
var fileName=path.basename(pathName);
console.log("Request for " + fileName + " received");
fs.readFile(fileName,function(err,data){
if (err) {
res.writeHead(404,{'content-type':'text/plain'});
res.write(fileName + " is not found in server");
}
else {
res.writeHead(200,{'content-type':'text/html'});
res.write(data.toString());
}
res.end();
}//function to process data
); // readFile
//res.end(fileName);
}); // http createServer
server.listen(8080);
console.log("Server started and listening on port:8080 ");
<file_sep>/MovieAppInReact/UI/src/js/components/MovieList.js
var DeleteMovie=require('./DeleteMovie');
var MovieList = React.createClass ({
getInitialState: function(){
return(<div></div>)
},
render: function (){
var data=this.props.data;
//console.log('---MovieList---'+data);
if(data!=null){
var out=data.map(function(movie){
return(
<div key={movie._id} className='container'>
<div key={movie._id} className='row well'>
<div key={movie._id} className="col-md-4">
<img id="bgposter" alt={movie.Title} src={movie.Poster} className="img-rounded center-block"/>
</div>
<div className="col-md-8">
<h3>{movie.Title}</h3>
<h4>Year :{movie.Year} </h4>
<h4>Actors :{movie.Actors}</h4>
<h4>Director :{movie.Director}</h4>
<h4>Description :{movie.Plot}</h4>
<h4>Language :{movie.Language}</h4>
<h4>Country :{movie.Country}</h4>
<h4>Released on :{movie.Released}</h4>
<h4>ImdbRating :{movie.imdbRating}</h4>
<h4>Awards :{movie.Awards}</h4>
<DeleteMovie movie_id={movie._id}/>
</div>
</div>
</div>
)
})
}
return (
<div>{out}</div>
);
}
});
module.exports=MovieList;
<file_sep>/MovieAppInReact/UI/src/js/components/Navigationbar.js
var NavigationBar=React.createClass({
render:function()
{return(
<div className="navbar navbar-fixed-top navbar-default mynav">
<div className="container ">
<div className=" navbar-collapse collapse navbar-responsive-collapse">
<ul className="nav navbar-nav ">
<li className=""><Link to="/home" >Home</Link></li>
<li><Link to="/movies">Movie</Link></li>
<li><Link to="/searchAndSave">Add Movie</Link></li>
</ul>
</div>
</div>
</div>
);
}
});
module.exports=NavigationBar;
<file_sep>/MovieAppInReact/UI/src/js/components/AddMovie.js
var BasicInputBox=require('./BasicInputBox');
var AddMovie = React.createClass({
getInitialState: function(){
return {
}
},
submit: function (e){
var self
e.preventDefault()
self = this
//console.log("this.state "+this.state);
var data = {
name: this.state.name.trim()
}
$.ajax({
type: 'post',
url: '/api/movies',
data: data
})
.done(function(data) {
self.clearForm()
})
.fail(function(fail) {
console.log('failed to register');
});
},
clearForm: function() {
this.setState({
name: "",
});
},
nameChange: function(e){
this.setState({name: e.target.value})
},
render: function(){
return (
<div className="container col-md-12">
<div className=" row well" >
<form onSubmit={this.submit} >
<div className='searchBar'>
<BasicInputBox label="Name:" valChange={this.nameChange} val={this.state.name}/>
<button type="submit" className='form-control btn-info'>Search</button>
</div>
</form>
</div>
</div>
);
}
});
module.exports=AddMovie;
<file_sep>/myTest/data.js
var express=require('express');
var router=express.Router();
router.get('/',function(rq,rs){
var obj={name:"Ram",age:39};
rs.json(obj);
});
module.exports=router;
<file_sep>/myReact/app/js/src/main.jsx
var React=require('react');
var ReactDOM=require('react-dom');
/*** @jsx React.DOM */
var App = React.createClass({
getInitialState: function() {
return {
result: []
};
},
render: function() {
return (
<div>
<SearchInput onClick={this.handleResult} />
<SearchResultList results={this.state.result} />
</div>
);
},
/** Expected to be used only by the searchInput-component */
handleResult: function(term) {
var updateResult = function(response, textStatus, jqXHR) {
this.setState({
result: (response instanceof Array) ? response : [response]
});
}.bind(this);
$.ajax('http://www.omdbapi.com', {
method: 'GET',
data: {
't': term,
'type': 'movie',
'plot': 'full'
},
success: updateResult
});
}
});
ReactDOM.render(<App />, document.getElementById('main-container'));
<file_sep>/d3-pjt/myGraph.js
/*
* Function to draw multi-series line chart
*/
function drawLineChart() {
function population(rurData,urbData) {
var oWidth=1060,
oHeight=500;
var margin={left:100,top:30,right:30,bottom:20};
var iWidth= (oWidth-margin.left-margin.right);
var iHeight= (oHeight-margin.top-margin.bottom);
var svgCont=d3.select("body").append("svg");
svgCont.attr("width",oWidth);
svgCont.attr("height",oHeight);
var xScale=d3.scale.linear();
xScale.domain([1960,2015]);
xScale.range([0,800]);
var yScale=d3.scale.linear();
yScale.domain([100,0]);
yScale.range([0,400]);
var xAx=d3.svg.axis().scale(xScale).orient("bottom");
var yAx=d3.svg.axis().scale(yScale).orient("left");
var g=svgCont.append("g");
g.attr("transform","translate("+margin.left+","+margin.top+")");
var xAxG=g.append("g").attr("transform","translate(0,400)");
var yAxG=g.append("g");
xAxG.call(xAx);
yAxG.call(yAx);
var div = d3.select("body")
.append("div")
.style("opacity", 0);
svgCont.append("text")
.attr("class","yaxis_label")
.attr("text-anchor","middle")
// .attr("transform","translate(20,"+(oHeight/2)+")rotate(-90)")
.attr("transform","translate(50,300)rotate(-90)")
.attr("font-size","xx-large")
.text("Population (%)");
svgCont.append("text")
.attr("class","xaxis_label")
.attr("text-anchor","middle")
// .attr("transform","translate("+(oWidth/2)+","+(oHeight-18)+")")
.attr("transform","translate(200,480)")
.attr("font-size","xx-large")
.text("Year");
svgCont.append("text")
.attr("text-anchor","middle")
//.attr("transform","translate("+(oWidth/2)+","+(oHeight-3)+")")
.attr("transform","translate(500,480)")
.text(" Rural Population (Orange) - Urban Population (Yellow)");
var urbFunc=d3.svg.line ();
urbFunc.x(function (d) {return 100 + (d.Year-1960)*(800/55);})
.y(function (d) {return (400 - (d.Value*4) +10);});
var urbGraph=svgCont.append("path")
.attr("d",urbFunc(urbData))
.attr("stroke","yellow")
.attr("stroke-width",2)
.attr("data-legend", "Urban Population" )
.attr("fill","none");
var rurFunc=d3.svg.line();
rurFunc.x(function (d) {return 100 + (d.Year-1960)*(800/55);})
.y(function (d) {return (400 - (d.Value*4) +10);});
var rurGraph=svgCont.append("path")
.attr("d",rurFunc(rurData))
.attr("stroke","orange")
.attr("stroke-width",2)
.attr("fill","none")
.attr("data-legend", "Rural Population" );
svgCont.selectAll("circle").data(inpData).enter().append("circle")
.transition()
.attr("cx",function (d) {return 100 + (d.Year-1960)*(800/55);})
.attr("cy",function (d) {return (400 - (d.Value*4) +10);})
.attr("r",3)
.style("fill","none")
.style("stroke","blue")
.style("stroke-width",2)
.duration(2000);
//.on();
var legend=svgCont.append("g")
.attr("class","legend")
.attr("transform","translate(500,50)")
.style("font-size","12px")
.call(d3.legend);
//svgCont.selectAll("circle").exit().remove();
}
var inpData=[];
var rurData=[];
var urbData=[];
d3.json("India_Population.json",function (d) {
inpData=d;
var urbLen=inpData.length;
for (var i=0;i<urbLen;i++) {
if (inpData[i].IndicatorCode==="SP.URB.TOTL.IN.ZS") {
urbData.push(inpData[i]);
} else if (inpData[i].IndicatorCode==="SP.RUR.TOTL.ZS") {
rurData.push(inpData[i]);
}
}
population(rurData,urbData);
});
} // drawLineChart
/*
* Function to draw stacked bar chart
*/
function drawStackChart() {
d3.json("Asia_Population.json",function (d) {
type (d);
var dLen=d.length;
var prepData=[];
//create array of objects
for (var i=0;i<dLen;i++) {
var myYear=d[i].Year;
var indx=(myYear-1960);
var myVal=d[i].Value;
var myPrefix=(d[i].IndicatorCode==="SP.RUR.TOTL"?"R":"U");
if (!prepData[indx]) {prepData[indx]=[];}
if (myPrefix=="R") {
if (!prepData[indx][0]) {prepData[indx][0]=[];}
prepData[indx][0].push(myVal);
} else {
if (!prepData[indx][1]) {prepData[indx][1]=[];}
prepData[indx][1].push(myVal);
}
}
//console.log(prepData);
var inMatrix=[];
var len=prepData.length;
//console.log("len" +len);
for (var i=0;i<len;i++) {
var rSum=0,uSum=0;
len1=prepData[i].length;
for (var j=0;j<len1;j++) {
var sum=0;
len2=prepData[i][j].length;
for (var k=0;k<len2;k++) {
sum +=prepData[i][j][k];
(j==0?rSum=sum:uSum=sum);
} //k loop
// console.log( "rSum" + rSum);
// console.log("uSum" + uSum);
} // j loop
inMatrix[i]=[i,rSum,uSum];
} // i loop
console.log(inMatrix);
asiaPopulation(inMatrix);
}
); // d3.json call
function type (d) {
d.forEach (function (d1) {
// console.log("in type" + d1);
d1.Year= +d1.Year;
d1.Value=+d1.Value;
} ) ;
return d;
}
function asiaPopulation(inMatrix) {
var remapped=["c1","c2"].map(function (dat,i) {
return inMatrix.map(function (d,j) {
return {x:j,y:d[i+1]};
});
});
console.log(remapped);
var stacked=d3.layout.stack()(remapped);
console.log(stacked);
var ow=1060,oh=500;
var margin={left:30,top:20,right:20,bottom:20};
var iw=(ow-margin.left-margin.right);
var ih=(oh-margin.top-margin.bottom);
var svg=d3.select("body").append("svg:svg")
.attr("width",ow)
.attr("height",oh)
.append("svg:g");
//.attr("transform","translate("+margin.left+","+ih+")");
var x=d3.scale.linear().range([0,iw-200]);
var y=d3.scale.linear().range([ih-100,0]);
x.domain([1960,2015]);
y.domain([0,d3.max(stacked[stacked.length - 1], function(d) { return (d.y + d.y0)/100000000; })]);
//var revDomain=d3.extent(stacked[stacked.length - 1], function(d) { return (d.y0 + d.y)/100000000; });
//y.domain(revDomain.reverse());
// console.log(y.domain());
//return;
// y.domain(y.domain().reverse);
var colors=d3.scale.category10();
var xAx=d3.svg.axis().orient("bottom").scale(x);
var yAx=d3.svg.axis().orient("left").scale(y);
var xAxG=svg.append("g").attr("transform","translate(100,410)");
var yAxG=svg.append("g").attr("transform","translate(100,50)");
xAxG.call(xAx);
yAxG.call(yAx);
svg.append("text")
// .attr("x","-200")
// .attr("y","40")
.attr("class", "yaxis_label")
.attr("text-anchor", "middle")
.attr("transform", "translate (50,300) rotate(-90)")
.attr("font-size","xx-large")
.text("Population");
svg.append("text")
.attr("class", "xaxis_label")
.attr("text-anchor", "middle")
.attr("transform", "translate(200,470)")
.attr("font-size","xx-large")
.text("Year");
svg.append("text")
// .attr("text-anchor", "middle")
.attr("transform", "translate(400,470)")
// .attr("font-size","xx-large")
.text("Asian countries Rural-Urban population");
// Add a group for each column.
var valG=svg.selectAll("g.valG")
.data(stacked)
.enter().append("svg:g")
.attr("class","valG")
.attr("transform", "translate(100,+410)")
.style("fill",function (d,i) {return colors(i);})
.style("stroke",function (d,i){return d3.rgb(colors(i)).darker();});
// Add a rect for each date.
var rect=valG.selectAll("rect")
.data(function (d) { return d;})
.enter().append("svg:rect")
.attr("data-legend", function (d) { return (d.y0==0?"Rural-Population":"Urban-Population");})
.transition()
.attr("x",function (d){return (d.x*810/55);})
.attr("y",function(d) {return ((y(d.y + d.y0))/100000000);})
.attr("height",function(d){return ((y(d.y0) - y(d.y + d.y0))/100000000);})
.attr("width",(810/55/2))
.duration(1000);
//.attr("width",x.rangeBand());
var legend=svg.append("g")
.attr("class","legend")
.attr("transform","translate(500,50)")
.style("font-size","12px")
.call(d3.legend);
// rect.exit().remove();
;
} //asiaPopulation function
} // drawStackChart
<file_sep>/MovieAppInReact/UI/src/js/routes.js
var React = require('react');
var Router = require('react-router');
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var Master = require('./components/Master');
/*var Home = require('./pages/Home/Home');
var Login = require('./pages/Login/Login');
var MovieBox = require('./components/MovieBox');
var HomePage = require('./components/Home');
var ViewMovieBox = require('./components/ViewMovieBox');
var LoginRequired = require('./utils/RouteHelpers');
*/
var NavigationBar=require('./components/NavigationBar');
var AddMovie=require('./components/AddMovie');
var BasicInputBox=require('./components/BasicInputBox');
var DeleteMovie=require('./components/DeleteMovie');
var GetAllMovies=require('./components/GetAllMovies');
var Home=require('./components/Home');
var MainLayout=require('./components/MainLayout');
var MovieList=require('./components/MovieList');
var SearchAndSave=require('./components/SearchAndSave');
var SearchMovie=require('./components/SearchMovie');
module.exports = (
<Route>
<Route handler={Login} name="Login" path="/Login"/>
<Route handler={LoginRequired}>
<Route handler={Master}>
<DefaultRoute handler={Home} name="Home"/>
</Route>
<Route handler={Home} name="HomePage" path="/home"/>
</Route>
</Route>
);
<file_sep>/jQuery-pjt/myJQuery.js
(
function() {
var jsonData='';
var table=$(".table-area");
var file=table.data("file");
var template = $.trim($('#rowTemplate').html());
//console.log(template);
$.getJSON(file,function(data) {
jsonData=data;
var matrix=drawChart(data);
//console.log(matrix);
updateTable(matrix);
asiaPopulation(matrix);
// To remove table rows on clicking delete button
//$('table').on('click','button',function (e) {
$('.existingTable').on('click','button',function (e) {
//alert("testing table click");
self=$(this);
var gp=$(self).closest("tr").css("background-color","red");
var yr=gp.children().eq(0).html();
var rmYr=parseFloat(yr)-1960;
//console.log("Before" + jsonData.length);
jsonData=$.grep(jsonData,function(e){
// console.log("e.year" + e.Year + "yr" + yr);
return e.Year != yr;
});
matrix=drawChart(jsonData);
setTimeout(function (){gp.remove();},3000);
//gp.remove();
//console.log(matrix);
// console.log("data" + data);
d3.select("body svg").data([]).exit().remove();
asiaPopulation(matrix);
}); // Remove table rows on delete function
// To add rows in table
$('.add').click(function(e) {
// alert("check");
e.preventDefault();
//console.log("values entered " + $('#yearIP').val() + " " + $('#ruralIP').val() + " " + $('#urbanIP').val());
var x,y,z,tableString="";
x=$('#yearIP').val();
y=parseFloat($('#ruralIP').val());
z=parseFloat($('#urbanIP').val());
if (x<1960 || x>2015) {
alert ("Eneter year value between 1960 and 2015");
}
else {
// Insert new record/row in JSON and update table
var adYr=parseFloat(x)-1960;
matrix[adYr]=[adYr,y,z];
updateTable(matrix);
d3.select("body svg").data([]).exit().remove();
asiaPopulation(matrix);
}
}
);
// Add table rows function
} ); // getJson
} // function
)(); // self invoking main jQuery call
//var jsonData="Asia_Population.json";
//drawStackChart(jsonData);
<file_sep>/myTest/app.js
express=require('express');
//var bodyParser = require('body-parser');
app=express();
var data=require('./data');
app.use('/data',data);
app.get('/',function(rq,rs){
rs.send("Hello!");
});
app.get('/:id',function(rq,rs){
var i=rq.params['id'];
rs.send(i);
});
app.listen(8080);
//module.exports=app;
<file_sep>/jQuery-pjt/myGraph.js
/*
* Function to draw stacked bar chart
*/
function drawChart (d) {
type (d);
var dLen=d.length;
var prepData=[];
//create array of objects
for (var i=0;i<dLen;i++) {
var myYear=d[i].Year;
var indx=(myYear-1960);
var myVal=d[i].Value;
var myPrefix=(d[i].IndicatorCode==="SP.RUR.TOTL"?"R":"U");
if (!prepData[indx]) {prepData[indx]=[];}
if (myPrefix=="R") {
if (!prepData[indx][0]) {prepData[indx][0]=[];}
prepData[indx][0].push(myVal);
} else {
if (!prepData[indx][1]) {prepData[indx][1]=[];}
prepData[indx][1].push(myVal);
}
}
//console.log(prepData);
var inMatrix=[];
var len=(prepData.length);
//console.log("len" +len);
for (var i=0;i<len;i++) {
var rSum=0,uSum=0;
if (!prepData[i]) {inMatrix[i]=[i,rSum,uSum];continue;}
len1=prepData[i].length;
for (var j=0;j<len1;j++) {
var sum=0;
len2=prepData[i][j].length;
for (var k=0;k<len2;k++) {
sum +=prepData[i][j][k];
(j==0?rSum=sum:uSum=sum);
} //k loop
// console.log( "rSum" + rSum);
// console.log("uSum" + uSum);
} // j loop
inMatrix[i]=[i,rSum,uSum];
} // i loop
//console.log(inMatrix);
// asiaPopulation(inMatrix);
return (inMatrix);
}
function type (d) {
d.forEach (function (d1) {
// console.log("in type" + d1);
d1.Year= +d1.Year;
d1.Value=+d1.Value;
} ) ;
return d;
}
function asiaPopulation(inMatrix) {
var remapped=["c1","c2"].map(function (dat,i) {
return inMatrix.map(function (d,j) {
return {x:j,y:d[i+1]};
});
});
// console.log(remapped);
var stacked=d3.layout.stack()(remapped);
console.log(stacked);
var ow=560,oh=500;
var margin={left:30,top:20,right:20,bottom:20};
var iw=(ow-margin.left-margin.right);
var ih=(oh-margin.top-margin.bottom);
var svg=d3.select(".graph-top").append("svg:svg")
.attr("width",ow)
.attr("height",oh)
.append("svg:g");
//.attr("transform","translate("+margin.left+","+ih+")");
//Clearing svg area (if its already drawn)
// d3.select("body svg").data([]).exit().remove();
var x=d3.scale.linear().range([0,iw-100]);
var y=d3.scale.linear().range([ih-100,0]);
x.domain([1960,2015]);
y.domain([0,d3.max(stacked[stacked.length - 1], function(d) { return (d.y + d.y0)/100000000; })]);
//var revDomain=d3.extent(stacked[stacked.length - 1], function(d) { return (d.y0 + d.y)/100000000; });
//y.domain(revDomain.reverse());
// console.log(y.domain());
//return;
// y.domain(y.domain().reverse);
var colors=d3.scale.category10();
var xAx=d3.svg.axis().orient("bottom").scale(x);
var yAx=d3.svg.axis().orient("left").scale(y);
var xAxG=svg.append("g").attr("transform","translate(100,410)");
var yAxG=svg.append("g").attr("transform","translate(100,50)");
xAxG.call(xAx);
yAxG.call(yAx);
svg.append("text")
// .attr("x","-200")
// .attr("y","40")
.attr("class", "yaxis_label")
.attr("text-anchor", "middle")
.attr("transform", "translate (50,200) rotate(-90)")
// .attr("font-size","xx-large")
.text("Population");
svg.append("text")
.attr("class", "xaxis_label")
.attr("text-anchor", "middle")
.attr("transform", "translate(150,470)")
//.attr("font-size","xx-large")
.text("Year");
svg.append("text")
// .attr("text-anchor", "middle")
.attr("transform", "translate(200,470)")
// .attr("font-size","xx-large")
.text("Asian countries Rural-Urban population");
// Add a group for each column.
var valG=svg.selectAll("g.valG")
.data(stacked)
.enter().append("svg:g")
.attr("class","valG")
.attr("transform", "translate(100,+410)")
.style("fill",function (d,i) {return colors(i);})
.style("stroke",function (d,i){return d3.rgb(colors(i)).darker();});
// Add a rect for each date.
var rect=valG.selectAll("rect")
.data(function (d) { return d;})
.enter().append("svg:rect")
.attr("data-legend", function (d) { return (d.y0==0?"Rural-Population":"Urban-Population");})
.transition()
.attr("x",function (d){return (d.x*410/55);})
.attr("y",function(d) {return ((y(d.y + d.y0))/100000000);})
.attr("height",function(d){return ((y(d.y0) - y(d.y + d.y0))/100000000);})
.attr("width",(410/55/2))
.duration(1000);
//.attr("width",x.rangeBand());
var legend=svg.append("g")
.attr("class","legend")
.attr("transform","translate(200,50)")
.style("font-size","12px")
.call(d3.legend);
// rect.exit().remove();
;
} //asiaPopulation function
<file_sep>/index.html
<!doctype html>
<html>
<head>
<title> My Friends </title>
<link rel="stylesheet" href="960_12_col.css" />
<link rel="stylesheet" href="text.css" />
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="wrap container_12">
<header class="clearfix">
<h1 class="grid_8"> My Best Friends </h1>
<div class="nav grid_4">
<ul>
<li> <a href="#"> Home </a> </li>
<li> <a href="#"> About </a> </li>
<li> <a href="#"> Photos </a> </li>
<li> <a href="#"> Contact </a> </li>
</ul>
</div> <!-- NAV -->
</header>
<div class="main">
<section class="grid_4 alpha" >
<h3> School </h3>
<p>
<img src="/img/school.jpg" alt="School">
<blockquote>
The difference between school and life? In school, you are taught a lesson and then given a test. In life, you are given a test that teaches you a lesson. – <NAME>
</blockquote>
</p>
</section>
<section class="grid_4">
<h3> College </h3>
<p>
<img src="/img/college.jpg" alt="College" >
<blockquote>
You might think that college is just high school continued, but its not. College opens doors for you that high school doesnot. And college can change you and shape you in ways that you might not imagine.
</blockquote>
</p>
</section>
<section class="work grid_4 omega" >
<h3> Work </h3>
<p>
<img src="/img/office.png" alt="Work" >
<blockquote>
A great place to work is one in which you trust the people you work for, have pride in what you do, and enjoy the people you work with - Robert Levering, Co-Founder, Great Place to Work
</blockquote>
</p>
</section>
<div class="hero grid_12 clearfix">
<p>
<h4 > Keep reading throught life </h4>
</p>
</div> <!--hero-->
</div> <!--main-->
<footer class="grid_12 foot">
<ul>
<li> <a href="#"> twitter </a> </li>
<li> <a href="#"> facebook </a> </li>
<li> <a href="#"> linkedIn </a> </li>
<li> <a href="#"> Google </a> </li>
</ul>
</footer>
</div> <!-- wrap -->
</body>
</html>
<file_sep>/myTest/test/indexspec.js
var should=require("chai").should(),
supertest=require('supertest'),
app=require("../app");
var url=supertest("http://localhost:8080");
describe ("Testing first route",function (err) {
it("should handle request",function(done) {
url
.get("/")
.expect(200)
.end(function(err,res){
if (err) {throw err;}
res.text.should.be.equal("Hello!");
done();
})
});
it("get with params",function(done){
url
.get('/100')
.expect(200)
.end(function(err, res){
should.not.exist(err);
parseFloat(res.text).should.be.equal(100);
done();
})
});
});
describe.only("Test suite 2",function(err){
it("Test case 1",function(done){
url.get('/data')
.expect(200)
.end(function(err,res){
should.not.exist(err);
var obj=JSON.parse(res.text);
obj.name.should.be.equal("Ram");
done();
})
}); //test 1
it("Test case 2",function(done){
done();
}); // test 2
});
<file_sep>/myExpress/simple/routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
/*
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
*/
var m=require('mongoose');
m.connect('mongodb://localhost/test');
var dbSchema=m.Schema({
Title: String,
Year:String,
Director:String,
Actors:String,
Language:String,
imdbID:String
});
var movieM=m.model('movie',dbSchema);
router.get('/',function (rq,rs) {
//rs.send("Received GET request on / ");
movieM.find({},function(err,a) {
if (err) {console.log(err);}
else {
//console.log("no error" + a);
//rs.send(a);
rs.json(a);
}
});
});
router.post('/',function (rq,rs) {
var ip=rq.body;
rs.send("Received POST request on / " );
var m1=new movieM(ip);
m1.save();
console.log(movieM.find());
});
router.put('/:old-:new',function (rq,rs) {
var id1=rq.params['old'];
var id2=rq.params['new'];
console.log(id1,id2);
movieM.findOneAndUpdate({Title : id1}, {Title: id2} ,function(err,a) {
rs.send("Received Update request " + a);
});
});
router.delete('/:Title',function (rq,rs) {
var title=rq.params['Title'];
console.log(title);
movieM.findOneAndRemove({Title: title},function(err,a){
console.log("deleting " + a);
});
rs.send("Received Delete request for Title= " + title);
});
module.exports = router;
<file_sep>/myExpress/simple/m2.js
var m=require('mongoose'),
mdb='mongodb://localhost/test';
m.connect(mdb);
var dbSchema=m.Schema({
Title: String,
Year:String,
Director:String,
Actors:String,
Language:String,
imdbID:String
});
var movieM=m.model('movie',dbSchema);
var movie1=new movieM({
Title: "roja",
Year:"1992",
Director:"<NAME>",
Actors:"<NAME>, Madhoo, <NAME>, Nasser",
Language:"Hindi, Telugu, Tamil,Marathi",
imdbID:"tt0105271"
});
var db=m.connection;
db.once('open',function() {
console.log("DB connected");
//movie1.save();
movieM.find({},function(err,a) {console.log(a)});
}); //db once
<file_sep>/MovieAppInReact/UI/src/js/components/SearchAndSave.js
var SearchAndSave=React.createClass({
render:function(){
return(<div><h4>You are in Seach and save</h4>
</div>)
}
});
module.exports=SearchAndSave;
<file_sep>/myexpressapp1/index.js
var express = require("express");
var app = express();
var routes = require("./routes/index");
var adroutes = require("./routes/admin");
app.use("/", routes);
app.use("/admin", adroutes);
app.listen(8080, function(err){
console.log("Listening at port 8080");
})
<file_sep>/node/e1.js
var Http=require('http');
var Router=require('router'),router;
router = new Router();
//function requestHandler (request,response) { }
function requestHandler(request,response) {
var message,
status=200;
count+=1;
switch (request.url) {
case '/path':
message=count.toString();
break;
case '/hello':
message='Hello World';
break;
default:
message="Not Found";
status=404;
break;
}
//message=("Visitor number : " + count + " path : " + request.url);
response.writeHead(201,{'content-type': 'text/plain'});
console.log(request.url,status,message);
response.end(message);
}
var count=0;
var server=Http.createServer(requestHandler);
server.listen(8080,function() {console.log("Listening on port 8080");});
<file_sep>/MovieAppInReact/UI/src/js/components/MainLayout.js
var NavigationBar=require('./NavigationBar');
var MainLayout=React.createClass({
render:function()
{
return(
<div className="container" id="main">
<NavigationBar />
<main>
{this.props.children}
</main>
</div>
);
}
});
module.exports=MainLayout;
| 1f8f30ac33adf40cf052d3cfe1c201630672d740 | [
"JavaScript",
"HTML"
] | 21 | JavaScript | vdoraira/MERN | 7a7827ff6bf6409a2aed2f4121274685d1af78f6 | 676bef921a00edd09d84ae47a47fcb373fdbc5a2 |
refs/heads/main | <repo_name>HieroDesteen/social_network<file_sep>/social_network/engine/urls.py
from rest_framework import routers
from engine.views import PostViewSet
router = routers.DefaultRouter(trailing_slash=True)
router.register('posts', PostViewSet)
urlpatterns = router.urls
<file_sep>/social_network/users/urls.py
from django.urls.conf import path
from rest_framework_jwt.views import obtain_jwt_token
from users.views import CreateUserAPIView, authenticate_user
urlpatterns = [
path('signup/', CreateUserAPIView.as_view()),
path('login/', authenticate_user),
]
<file_sep>/social_network/users/views.py
import jwt
from django.contrib.auth.signals import user_logged_in
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.serializers import jwt_payload_handler
from users.models import User
from users.serializers import UserSerializer
from users.utils import ClearbitUserEnrichment
class CreateUserAPIView(APIView):
permission_classes = (AllowAny,)
def post(self, request):
user = ClearbitUserEnrichment(data=request.data)
serializer = UserSerializer(data=user.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
@api_view(['POST'])
@permission_classes([AllowAny, ])
def authenticate_user(request):
email = request.data.get('email')
password = request.data.get('password')
if not email and password:
res = {'error': 'Please provide an email and password'}
return Response(res, status=status.HTTP_400_BAD_REQUEST)
try:
user = User.objects.get(email=email, password=password)
except ObjectDoesNotExist:
res = {
'error': 'Can not authenticate with the given credentials or the account has been deactivated'}
return Response(res, status=status.HTTP_403_FORBIDDEN)
payload = jwt_payload_handler(user)
token = jwt.encode(payload, settings.SECRET_KEY)
user_details = {}
user_details['name'] = "%s %s" % (
user.first_name, user.last_name)
user_details['token'] = token
user_logged_in.send(sender=user.__class__,
request=request, user=user)
return Response(user_details, status=status.HTTP_200_OK)
<file_sep>/social_network/engine/views.py
from rest_framework import viewsets
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.permissions import SAFE_METHODS
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from engine.serializers import PostsSerializer
from engine.models import Posts, PostLikes
class PostViewSet(viewsets.ModelViewSet):
queryset = Posts.objects.all().order_by('-id')
serializer_class = PostsSerializer
permission_classes = (IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(author=self.request.user)
@action(detail=True, methods=['POST'])
def like(self, request, pk):
"""
Здесь логика была следующей. Я думаю, что вью не должна возвращать
одинаковый респонс(пост+200) при выполнении разных действий(like/unlike). Также нужно было решить проблему
с тем, что функция не должна выполнять два разных(даже противоположных) действия like/unlike
Я решил вынести логику во вью и разделить в итоге у поста есть две функции выполняющие свое предназначение,
а сама вью возвращает результат зависящий от выполненного дейтсвия.
PS. Это можно также было разделить на фронте и создать две вью /posts/1/like & /posts/1/unlike
(может тоже жизнеспособный вариант)
"""
post = self.get_object()
like = post.likes.filter(owner=request.user).first()
if like:
post.unlike(like)
response_status = status.HTTP_204_NO_CONTENT
else:
post.like(owner=request.user)
response_status = status.HTTP_200_OK
serializer = self.get_serializer(post)
return Response(data=serializer.data, status=response_status)
<file_sep>/automated_bot/bot.py
import random
import string
import logging
import logging.config
import sys
import yaml
import collections
from api import UserSocialNetworkApi, PostSocialNetworkApi
Like = collections.namedtuple('Like', ['owner'])
class User:
def __init__(self, email, api_url, password=None):
self.email = email
self.password = password if password else self._make_random_password()
self._api = UserSocialNetworkApi(api_url)
self._api_url = api_url
self.posts = []
self.setted_likes = 0
def signup(self):
self._api.signup({"email": self.email, "password": self.password})
def login(self):
self._api.login({"email": self.email, "password": self.password})
def create_post(self, text=None):
post = Post(self, self._api_url, text)
post.create(self._api.auth)
self.posts.append(post)
def send_like(self, post):
post.like(owner=self, user_auth=self._api.auth)
self.setted_likes += 1
@staticmethod
def _make_random_password():
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for _ in range(8))
@property
def posts_count(self):
return len(self.posts)
@property
def likes_count(self):
return sum([len(post.likes) for post in self.posts])
@property
def is_zero_liked_post(self):
return not all([post.likes for post in self.posts])
class Post:
def __init__(self, author, api_url, text=None):
self.author = author
self._api = PostSocialNetworkApi(api_url)
self.text = text if text else self._get_text()
self.likes = []
self._post_id = None
@staticmethod
def _get_text():
return "Hello World!"
def create(self, user_auth):
data = {"text": self.text}
self._api.create(data=data, auth=user_auth)
def like(self, owner, user_auth):
self._api.like(owner, user_auth)
like = Like(owner=owner)
self.likes.append(like)
class AutomatedBot:
def __init__(self):
self.config = self._read_configurations()
self._url = self.config['site_url']
self._users = []
def start(self):
logging.info(' Bot started '.center(60, '*'))
logging.info(' Start users initializing '.center(60, '*'))
self.init_users()
for user in self._users:
user.login()
self.create_posts(user)
logging.info(' Start likes activity by users '.center(60, '*'))
self.likes_engine()
def likes_engine(self):
try:
sender = self._get_curr_user()
logging.info(f' Start likes activity by user {sender.email} '.center(60, '*'))
for i in range(self.config['max_likes_per_user']):
receiver = self._get_user_with_zero_likes(sender)
self._send_like_by_user(sender, receiver)
self.likes_engine()
except Exception as e:
logging.error(e)
def _send_like_by_user(self, sender, receiver):
post = self._get_post(sender, receiver.posts)
sender.send_like(post)
logging.info(f'User {sender.email} send like for user {receiver.email}')
def _get_post(self, sender, posts):
post = random.choice(posts)
if sender not in [like.owner for like in post.likes]:
return post
return self._get_post(sender, posts)
def _get_user_with_zero_likes(self, curr_user):
users_list = sorted(self._users, key=lambda u: not u.is_zero_liked_post)
users_list.remove(curr_user)
user = users_list[0] if users_list else None
if user is None or not user.is_zero_liked_post:
raise Exception("Bot stopped.")
return user
def _get_curr_user(self):
users_list = [user for user in self._users if user.setted_likes < self.config['max_likes_per_user']]
if not users_list:
raise Exception('Bot stopped.')
users_list = sorted(users_list, key=lambda u: (u.posts_count, -u.likes_count), reverse=True)
return users_list[0]
def create_posts(self, user):
posts_count = random.randrange(1, self.config['max_posts_per_user'])
logging.info(f'Creation of {posts_count} posts for user {user.email} started')
for i in range(posts_count):
user.create_post()
logging.info(f'Post {i} created.')
def init_users(self):
for k in range(0, self.config['number_of_users']):
email = f'<EMAIL>'
user = User(email, self._url)
user.signup()
self._users.append(user)
logging.info(f'User {email} created.')
@staticmethod
def _read_configurations():
with open('bot_config.yaml') as fh:
cfg = yaml.load(fh, Loader=yaml.FullLoader)
return cfg['settings']
def main():
logging.basicConfig(level=logging.INFO, format='%(message)s', handlers=[
logging.FileHandler("automated_bot.log"),
logging.StreamHandler()
])
bot = AutomatedBot()
bot.start()
if __name__ == '__main__':
main()
<file_sep>/social_network/requirements.txt
asgiref==3.3.0
Django==3.1.3
djangorestframework==3.12.1
djangorestframework-jwt==1.11.0
psycopg2-binary==2.8.6
PyJWT==1.7.1
pytz==2020.4
sqlparse==0.4.1
requests==2.24.0
clearbit==0.1.7
<file_sep>/social_network/engine/serializers.py
from rest_framework import serializers
from engine.models import Posts, PostLikes
from users.serializers import UserSerializer
class PostLikesSerializer(serializers.ModelSerializer):
owner = UserSerializer(read_only=True, default=None)
class Meta:
model = PostLikes
fields = ('owner',)
class PostsSerializer(serializers.ModelSerializer):
author = UserSerializer(read_only=True, default=None)
likes = PostLikesSerializer(read_only=True, many=True, default=[])
class Meta:
model = Posts
fields = ('id', 'author', 'text', 'likes', 'likes_count', 'created_at')
<file_sep>/README.md
# Social Network
### Production deploying
* Pull git repository:
```bash
git pull http://
```
* Enter work folder
```
cd test_app/
```
* Make docker-compose file
```bash
cp ./docker-compose.prod.yml.sample ./docker-compose.prod.yml
```
* Set environment variables in docker-compose.prod.yml file
Run command
```dockerfile
docker-compose -f docker-compose.prod.yml -d --build
```
## Local deploying
* Make local environment
```bash
python3 -m venv env
source env/bin/activate
```
* Enter django project work folder
```bash
cd social_network/
```
* Install project requirements
```bash
pip install -r requrements.txt
```
* Migrate changes to db
```bash
python3 manage.py migrate
```
* Run django server
```bash
python3 manage.py runserver
```
## Notes
* For create admin
```bash
docker exec -it api python3 manage.py createsuperuser
```
* Check api container logs
```bash
docker logs -f api
```
* Enter the api container with bash
```bash
docker exec -it api bash
```
* Enter postgres db with psql
```bash
docker exec -it api_db psql -U root test_db
```
# Automated bot
* Enter bot work folder
```bash
cd automated_bot
```
* Make local environment
```bash
python3 -m venv env
source env/bin/activate
```
* Install bot requirements
```bash
pip install -r requrements.txt
```
* Run bot
```bash
python3 bot.py
```
<file_sep>/social_network/users/utils.py
import requests
import clearbit
from django.conf import settings
from django.core.exceptions import ValidationError
def verify_email(email):
email_verification = HunterEmailVerification(email=email)
email_verification.verify_email()
class HunterEmailVerification:
def __init__(self, email):
self._api_key = settings.HUNTER_API_KEY
self._email = email
self.email_verification_data = self._get_email_verification_data()
def get_email_status(self):
return self.email_verification_data.json()['data']['status']
def _get_email_verification_data(self):
response = requests.get("https://api.hunter.io/v2/email-verifier",
params={'email': self._email, 'api_key': self._api_key})
return response
def verify_email(self):
status = self.get_email_status()
if status == "invalid":
raise ValidationError("Invalid email")
class ClearbitUserEnrichment:
def __init__(self, data):
clearbit.key = settings.CLEARBIT_API_KEY
self._data = data
self._email = self._data.get('email')
self._clearbit_data = self._get_data_by_email()
def _get_data_by_email(self):
response = clearbit.Person.find(email=self._email, stream=True)
print(response)
return response
def _update_user_data(self):
if self._field_validation('first_name'):
self._data['first_name'] = self._clearbit_data['name']['givenName']
if self._field_validation('last_name'):
self._data['last_name'] = self._clearbit_data['name']['familyName']
def _field_validation(self, field_name):
return field_name not in self._data or not self._data[field_name]
@property
def data(self):
if self._clearbit_data:
self._update_user_data()
return self._data
<file_sep>/automated_bot/auth.py
from requests.auth import AuthBase
class CustomAuth(AuthBase):
def __init__(self, token):
self._token = token
def __call__(self, request):
request.headers['Authorization'] = 'Bearer %s' % self._token
return request
<file_sep>/automated_bot/api.py
import requests
from requests.exceptions import HTTPError
from auth import CustomAuth
class SocialNetworkApi:
def __init__(self, api_url):
self._api_url = api_url
def post_request(self, path, data=None, auth=None):
try:
response = requests.post(f'{self._api_url}{path}', data=data, auth=auth)
response.raise_for_status()
except HTTPError as e:
raise Exception(e)
return response.json()
class UserSocialNetworkApi(SocialNetworkApi):
def __init__(self, api_url, auth=None):
self.auth = auth
super(UserSocialNetworkApi, self).__init__(api_url)
def signup(self, data):
path = '/user/signup/'
self.post_request(path=path, data=data)
def login(self, credentials):
token = self._get_token(credentials)
self.auth = CustomAuth(token)
def _get_token(self, credentials):
path = '/user/login/'
response = self.post_request(path=path, data=credentials)
return response['token']
class PostSocialNetworkApi(SocialNetworkApi):
def __init__(self, api_url):
self._db_id = None
super(PostSocialNetworkApi, self).__init__(api_url)
def create(self, data, auth):
path = '/api/posts/'
response_data = self.post_request(path=path, data=data, auth=auth)
self._db_id = response_data['id']
def like(self, owner, auth):
path = f'/api/posts/{self._db_id}/like/'
self.post_request(path=path, auth=auth)
<file_sep>/social_network/users/serializers.py
from django.core.exceptions import ValidationError
from rest_framework import serializers
from users.models import User
from users.utils import verify_email
class UserSerializer(serializers.ModelSerializer):
date_joined = serializers.ReadOnlyField()
class Meta(object):
model = User
fields = ('id', 'email', 'first_name', 'last_name',
'date_joined', 'password')
extra_kwargs = {'password': {'write_<PASSWORD>': True}}
def validate(self, data):
"""
Check email verification.
"""
# Отключил тк лимит запросов был ичерпан
# try:
# verify_email(data.get('email'))
# except ValidationError:
# raise serializers.ValidationError({"email": "Email verification failed."})
return data
<file_sep>/social_network/engine/admin.py
from django.contrib import admin
from engine.models import Posts, PostLikes
admin.site.register(Posts)
admin.site.register(PostLikes)
# Register your models here.
<file_sep>/social_network/engine/models.py
from django.db import models
from users.models import User
class Posts(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
text = models.CharField(max_length=256)
created_at = models.DateTimeField(auto_now_add=True, null=True)
@property
def likes_count(self):
return self.likes.all().count()
def like(self, owner):
like = PostLikes(owner=owner, post=self)
like.save()
@staticmethod
def unlike(like):
like.delete()
class PostLikes(models.Model):
owner = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='likes', null=True)
post = models.ForeignKey(Posts, on_delete=models.CASCADE, related_name='likes')
class Meta:
unique_together = ('owner', 'post')
| 16695d0f9646d66a6a99221fc44aba539c0f3125 | [
"Markdown",
"Python",
"Text"
] | 14 | Python | HieroDesteen/social_network | c17e5ae464201a1d6898b600293104dbeb897247 | 8dc0b34403471bd0c94e0b6b4fea45fd90f443af |
refs/heads/main | <file_sep>#![allow(clippy::blacklisted_name)]
use crate::BoxError;
use crate::{
extract,
handler::{any, delete, get, on, patch, post, Handler},
response::IntoResponse,
routing::MethodFilter,
service, Router,
};
use bytes::Bytes;
use http::{
header::{HeaderMap, AUTHORIZATION},
Request, Response, StatusCode, Uri,
};
use hyper::{Body, Server};
use serde::Deserialize;
use serde_json::json;
use std::future::Ready;
use std::{
collections::HashMap,
convert::Infallible,
future::ready,
net::{SocketAddr, TcpListener},
task::{Context, Poll},
time::Duration,
};
use tower::{make::Shared, service_fn};
use tower_service::Service;
mod get_to_head;
mod handle_error;
mod nest;
mod or;
#[tokio::test]
async fn hello_world() {
async fn root(_: Request<Body>) -> &'static str {
"Hello, World!"
}
async fn foo(_: Request<Body>) -> &'static str {
"foo"
}
async fn users_create(_: Request<Body>) -> &'static str {
"users#create"
}
let app = Router::new()
.route("/", get(root).post(foo))
.route("/users", post(users_create));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "Hello, World!");
let res = client
.post(format!("http://{}", addr))
.send()
.await
.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "foo");
let res = client
.post(format!("http://{}/users", addr))
.send()
.await
.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "users#create");
}
#[tokio::test]
async fn consume_body() {
let app = Router::new().route("/", get(|body: String| async { body }));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}", addr))
.body("foo")
.send()
.await
.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "foo");
}
#[tokio::test]
async fn deserialize_body() {
#[derive(Debug, Deserialize)]
struct Input {
foo: String,
}
let app = Router::new().route(
"/",
post(|input: extract::Json<Input>| async { input.0.foo }),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.post(format!("http://{}", addr))
.json(&json!({ "foo": "bar" }))
.send()
.await
.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "bar");
}
#[tokio::test]
async fn consume_body_to_json_requires_json_content_type() {
#[derive(Debug, Deserialize)]
struct Input {
foo: String,
}
let app = Router::new().route(
"/",
post(|input: extract::Json<Input>| async { input.0.foo }),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.post(format!("http://{}", addr))
.body(r#"{ "foo": "bar" }"#)
.send()
.await
.unwrap();
let status = res.status();
dbg!(res.text().await.unwrap());
assert_eq!(status, StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn body_with_length_limit() {
use std::iter::repeat;
#[derive(Debug, Deserialize)]
struct Input {
foo: String,
}
const LIMIT: u64 = 8;
let app = Router::new().route(
"/",
post(|_body: extract::ContentLengthLimit<Bytes, LIMIT>| async {}),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.post(format!("http://{}", addr))
.body(repeat(0_u8).take((LIMIT - 1) as usize).collect::<Vec<_>>())
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post(format!("http://{}", addr))
.body(repeat(0_u8).take(LIMIT as usize).collect::<Vec<_>>())
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post(format!("http://{}", addr))
.body(repeat(0_u8).take((LIMIT + 1) as usize).collect::<Vec<_>>())
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
let res = client
.post(format!("http://{}", addr))
.body(reqwest::Body::wrap_stream(futures_util::stream::iter(
vec![Ok::<_, std::io::Error>(bytes::Bytes::new())],
)))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::LENGTH_REQUIRED);
}
#[tokio::test]
async fn routing() {
let app = Router::new()
.route(
"/users",
get(|_: Request<Body>| async { "users#index" })
.post(|_: Request<Body>| async { "users#create" }),
)
.route("/users/:id", get(|_: Request<Body>| async { "users#show" }))
.route(
"/users/:id/action",
get(|_: Request<Body>| async { "users#action" }),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
assert_eq!(res.status(), StatusCode::NOT_FOUND);
let res = client
.get(format!("http://{}/users", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "users#index");
let res = client
.post(format!("http://{}/users", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "users#create");
let res = client
.get(format!("http://{}/users/1", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "users#show");
let res = client
.get(format!("http://{}/users/1/action", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "users#action");
}
#[tokio::test]
async fn extracting_url_params() {
let app = Router::new().route(
"/users/:id",
get(|extract::Path(id): extract::Path<i32>| async move {
assert_eq!(id, 42);
})
.post(
|extract::Path(params_map): extract::Path<HashMap<String, i32>>| async move {
assert_eq!(params_map.get("id").unwrap(), &1337);
},
),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/users/42", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post(format!("http://{}/users/1337", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn extracting_url_params_multiple_times() {
let app = Router::new().route(
"/users/:id",
get(|_: extract::Path<i32>, _: extract::Path<String>| async {}),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/users/42", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn boxing() {
let app = Router::new()
.route(
"/",
on(MethodFilter::GET, |_: Request<Body>| async {
"hi from GET"
})
.on(MethodFilter::POST, |_: Request<Body>| async {
"hi from POST"
}),
)
.layer(tower_http::compression::CompressionLayer::new())
.boxed();
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "hi from GET");
let res = client
.post(format!("http://{}", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "hi from POST");
}
#[tokio::test]
async fn routing_between_services() {
use std::convert::Infallible;
use tower::service_fn;
async fn handle(_: Request<Body>) -> &'static str {
"handler"
}
let app = Router::new()
.route(
"/one",
service::get(service_fn(|_: Request<Body>| async {
Ok::<_, Infallible>(Response::new(Body::from("one get")))
}))
.post(service_fn(|_: Request<Body>| async {
Ok::<_, Infallible>(Response::new(Body::from("one post")))
}))
.on(
MethodFilter::PUT,
service_fn(|_: Request<Body>| async {
Ok::<_, Infallible>(Response::new(Body::from("one put")))
}),
),
)
.route("/two", service::on(MethodFilter::GET, any(handle)));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/one", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "one get");
let res = client
.post(format!("http://{}/one", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "one post");
let res = client
.put(format!("http://{}/one", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "one put");
let res = client
.get(format!("http://{}/two", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "handler");
}
#[tokio::test]
async fn middleware_on_single_route() {
use tower::ServiceBuilder;
use tower_http::{compression::CompressionLayer, trace::TraceLayer};
async fn handle(_: Request<Body>) -> &'static str {
"Hello, World!"
}
let app = Router::new().route(
"/",
get(handle.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CompressionLayer::new())
.into_inner(),
)),
);
let addr = run_in_background(app).await;
let res = reqwest::get(format!("http://{}", addr)).await.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "Hello, World!");
}
#[tokio::test]
async fn service_in_bottom() {
async fn handler(_req: Request<hyper::Body>) -> Result<Response<hyper::Body>, hyper::Error> {
Ok(Response::new(hyper::Body::empty()))
}
let app = Router::new().route("/", service::get(service_fn(handler)));
run_in_background(app).await;
}
#[tokio::test]
async fn test_extractor_middleware() {
struct RequireAuth;
#[async_trait::async_trait]
impl<B> extract::FromRequest<B> for RequireAuth
where
B: Send,
{
type Rejection = StatusCode;
async fn from_request(req: &mut extract::RequestParts<B>) -> Result<Self, Self::Rejection> {
if let Some(auth) = req
.headers()
.expect("headers already extracted")
.get("authorization")
.and_then(|v| v.to_str().ok())
{
if auth == "secret" {
return Ok(Self);
}
}
Err(StatusCode::UNAUTHORIZED)
}
}
async fn handler() {}
let app = Router::new().route(
"/",
get(handler.layer(extract::extractor_middleware::<RequireAuth>())),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
let res = client
.get(format!("http://{}/", addr))
.header(AUTHORIZATION, "secret")
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn wrong_method_handler() {
let app = Router::new()
.route("/", get(|| async {}).post(|| async {}))
.route("/foo", patch(|| async {}));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.patch(format!("http://{}", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
let res = client
.patch(format!("http://{}/foo", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post(format!("http://{}/foo", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
let res = client
.get(format!("http://{}/bar", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn wrong_method_service() {
#[derive(Clone)]
struct Svc;
impl<R> Service<R> for Svc {
type Response = Response<http_body::Empty<Bytes>>;
type Error = Infallible;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _req: R) -> Self::Future {
ready(Ok(Response::new(http_body::Empty::new())))
}
}
let app = Router::new()
.route("/", service::get(Svc).post(Svc))
.route("/foo", service::patch(Svc));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.patch(format!("http://{}", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
let res = client
.patch(format!("http://{}/foo", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post(format!("http://{}/foo", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
let res = client
.get(format!("http://{}/bar", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn multiple_methods_for_one_handler() {
async fn root(_: Request<Body>) -> &'static str {
"Hello, World!"
}
let app = Router::new().route("/", on(MethodFilter::GET | MethodFilter::POST, root));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post(format!("http://{}", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn handler_into_service() {
async fn handle(body: String) -> impl IntoResponse {
format!("you said: {}", body)
}
let addr = run_in_background(handle.into_service()).await;
let client = reqwest::Client::new();
let res = client
.post(format!("http://{}", addr))
.body("hi there!")
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "you said: hi there!");
}
#[tokio::test]
async fn when_multiple_routes_match() {
let app = Router::new()
.route("/", post(|| async {}))
.route("/", get(|| async {}))
.route("/foo", get(|| async {}))
.nest("/foo", Router::new().route("/bar", get(|| async {})));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post(format!("http://{}", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.get(format!("http://{}/foo/bar", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.get(format!("http://{}/foo", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn captures_dont_match_empty_segments() {
let app = Router::new().route("/:key", get(|| async {}));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
assert_eq!(res.status(), StatusCode::NOT_FOUND);
let res = client
.get(format!("http://{}/foo", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
/// Run a `tower::Service` in the background and get a URI for it.
pub(crate) async fn run_in_background<S, ResBody>(svc: S) -> SocketAddr
where
S: Service<Request<Body>, Response = Response<ResBody>> + Clone + Send + 'static,
ResBody: http_body::Body + Send + 'static,
ResBody::Data: Send,
ResBody::Error: Into<BoxError>,
S::Future: Send,
S::Error: Into<BoxError>,
{
let listener = TcpListener::bind("127.0.0.1:0").expect("Could not bind ephemeral socket");
let addr = listener.local_addr().unwrap();
println!("Listening on {}", addr);
let (tx, rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
let server = Server::from_tcp(listener).unwrap().serve(Shared::new(svc));
tx.send(()).unwrap();
server.await.expect("server error");
});
rx.await.unwrap();
addr
}
pub(crate) fn assert_send<T: Send>() {}
pub(crate) fn assert_sync<T: Sync>() {}
pub(crate) fn assert_unpin<T: Unpin>() {}
pub(crate) struct NotSendSync(*const ());
<file_sep>//! Handler future types.
use crate::body::{box_body, BoxBody};
use crate::util::{Either, EitherProj};
use futures_util::{
future::{BoxFuture, Map},
ready,
};
use http::{Method, Request, Response};
use http_body::Empty;
use pin_project_lite::pin_project;
use std::{
convert::Infallible,
fmt,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tower::util::Oneshot;
use tower_service::Service;
pin_project! {
/// The response future for [`OnMethod`](super::OnMethod).
pub struct OnMethodFuture<F, B>
where
F: Service<Request<B>>
{
#[pin]
pub(super) inner: Either<
BoxFuture<'static, Response<BoxBody>>,
Oneshot<F, Request<B>>,
>,
pub(super) req_method: Method,
}
}
impl<F, B> Future for OnMethodFuture<F, B>
where
F: Service<Request<B>, Response = Response<BoxBody>>,
{
type Output = Result<Response<BoxBody>, F::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let response = match this.inner.project() {
EitherProj::A { inner } => ready!(inner.poll(cx)),
EitherProj::B { inner } => ready!(inner.poll(cx))?,
};
if this.req_method == &Method::HEAD {
let response = response.map(|_| box_body(Empty::new()));
Poll::Ready(Ok(response))
} else {
Poll::Ready(Ok(response))
}
}
}
impl<F, B> fmt::Debug for OnMethodFuture<F, B>
where
F: Service<Request<B>>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OnMethodFuture").finish()
}
}
opaque_future! {
/// The response future for [`IntoService`](super::IntoService).
pub type IntoServiceFuture =
Map<
BoxFuture<'static, Response<BoxBody>>,
fn(Response<BoxBody>) -> Result<Response<BoxBody>, Infallible>,
>;
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-multipart-form
//! ```
use axum::{
extract::{ContentLengthLimit, Multipart},
handler::get,
response::Html,
Router,
};
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_multipart_form=debug,tower_http=debug")
}
tracing_subscriber::fmt::init();
// build our application with some routes
let app = Router::new()
.route("/", get(show_form).post(accept_form))
.layer(tower_http::trace::TraceLayer::new_for_http());
// run it with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn show_form() -> Html<&'static str> {
Html(
r#"
<!doctype html>
<html>
<head></head>
<body>
<form action="/" method="post" enctype="multipart/form-data">
<label>
Upload file:
<input type="file" name="file" multiple>
</label>
<input type="submit" value="Upload files">
</form>
</body>
</html>
"#,
)
}
async fn accept_form(
ContentLengthLimit(mut multipart): ContentLengthLimit<
Multipart,
{
250 * 1024 * 1024 /* 250mb */
},
>,
) {
while let Some(field) = multipart.next_field().await.unwrap() {
let name = field.name().unwrap().to_string();
let data = field.bytes().await.unwrap();
println!("Length of `{}` is {} bytes", name, data.len());
}
}
<file_sep>//! Future types.
use crate::{body::BoxBody, buffer::MpscBuffer, routing::FromEmptyRouter, BoxError};
use futures_util::ready;
use http::{Request, Response};
use pin_project_lite::pin_project;
use std::{
convert::Infallible,
fmt,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tower::{
util::{BoxService, Oneshot},
ServiceExt,
};
use tower_service::Service;
pub use super::or::ResponseFuture as OrResponseFuture;
opaque_future! {
/// Response future for [`EmptyRouter`](super::EmptyRouter).
pub type EmptyRouterFuture<E> =
std::future::Ready<Result<Response<BoxBody>, E>>;
}
pin_project! {
/// The response future for [`BoxRoute`](super::BoxRoute).
pub struct BoxRouteFuture<B, E>
where
E: Into<BoxError>,
{
#[pin]
pub(super) inner: Oneshot<
MpscBuffer<
BoxService<Request<B>, Response<BoxBody>, E >,
Request<B>
>,
Request<B>,
>,
}
}
impl<B, E> Future for BoxRouteFuture<B, E>
where
E: Into<BoxError>,
{
type Output = Result<Response<BoxBody>, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.project().inner.poll(cx)
}
}
impl<B, E> fmt::Debug for BoxRouteFuture<B, E>
where
E: Into<BoxError>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BoxRouteFuture").finish()
}
}
pin_project! {
/// The response future for [`Route`](super::Route).
#[derive(Debug)]
pub struct RouteFuture<S, F, B>
where
S: Service<Request<B>>,
F: Service<Request<B>>
{
#[pin]
state: RouteFutureInner<S, F, B>,
}
}
impl<S, F, B> RouteFuture<S, F, B>
where
S: Service<Request<B>>,
F: Service<Request<B>>,
{
pub(crate) fn a(a: Oneshot<S, Request<B>>, fallback: F) -> Self {
RouteFuture {
state: RouteFutureInner::A {
a,
fallback: Some(fallback),
},
}
}
pub(crate) fn b(b: Oneshot<F, Request<B>>) -> Self {
RouteFuture {
state: RouteFutureInner::B { b },
}
}
}
pin_project! {
#[project = RouteFutureInnerProj]
#[derive(Debug)]
enum RouteFutureInner<S, F, B>
where
S: Service<Request<B>>,
F: Service<Request<B>>,
{
A {
#[pin]
a: Oneshot<S, Request<B>>,
fallback: Option<F>,
},
B {
#[pin]
b: Oneshot<F, Request<B>>
},
}
}
impl<S, F, B> Future for RouteFuture<S, F, B>
where
S: Service<Request<B>, Response = Response<BoxBody>>,
F: Service<Request<B>, Response = Response<BoxBody>, Error = S::Error>,
B: Send + Sync + 'static,
{
type Output = Result<Response<BoxBody>, S::Error>;
#[allow(warnings)]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let mut this = self.as_mut().project();
let new_state = match this.state.as_mut().project() {
RouteFutureInnerProj::A { a, fallback } => {
let mut response = ready!(a.poll(cx))?;
let req = if let Some(ext) =
response.extensions_mut().remove::<FromEmptyRouter<B>>()
{
ext.request
} else {
return Poll::Ready(Ok(response));
};
RouteFutureInner::B {
b: fallback
.take()
.expect("future polled after completion")
.oneshot(req),
}
}
RouteFutureInnerProj::B { b } => return b.poll(cx),
};
this.state.set(new_state);
}
}
}
pin_project! {
/// The response future for [`Nested`](super::Nested).
#[derive(Debug)]
pub struct NestedFuture<S, F, B>
where
S: Service<Request<B>>,
F: Service<Request<B>>
{
#[pin]
pub(super) inner: RouteFuture<S, F, B>,
}
}
impl<S, F, B> Future for NestedFuture<S, F, B>
where
S: Service<Request<B>, Response = Response<BoxBody>>,
F: Service<Request<B>, Response = Response<BoxBody>, Error = S::Error>,
B: Send + Sync + 'static,
{
type Output = Result<Response<BoxBody>, S::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.project().inner.poll(cx)
}
}
opaque_future! {
/// Response future from [`MakeRouteService`] services.
pub type MakeRouteServiceFuture<S> =
std::future::Ready<Result<S, Infallible>>;
}
<file_sep>//! Example chat application.
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-chat
//! ```
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::Extension;
use axum::handler::get;
use axum::response::{Html, IntoResponse};
use axum::AddExtensionLayer;
use axum::Router;
use futures::{sink::SinkExt, stream::StreamExt};
use std::collections::HashSet;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use tokio::sync::broadcast;
// Our shared state
struct AppState {
user_set: Mutex<HashSet<String>>,
tx: broadcast::Sender<String>,
}
#[tokio::main]
async fn main() {
let user_set = Mutex::new(HashSet::new());
let (tx, _rx) = broadcast::channel(100);
let app_state = Arc::new(AppState { user_set, tx });
let app = Router::new()
.route("/", get(index))
.route("/websocket", get(websocket_handler))
.layer(AddExtensionLayer::new(app_state));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn websocket_handler(
ws: WebSocketUpgrade,
Extension(state): Extension<Arc<AppState>>,
) -> impl IntoResponse {
ws.on_upgrade(|socket| websocket(socket, state))
}
async fn websocket(stream: WebSocket, state: Arc<AppState>) {
// By splitting we can send and receive at the same time.
let (mut sender, mut receiver) = stream.split();
// Username gets set in the receive loop, if its valid
let mut username = String::new();
// Loop until a text message is found.
while let Some(Ok(message)) = receiver.next().await {
if let Message::Text(name) = message {
// If username that is sent by client is not taken, fill username string.
check_username(&state, &mut username, &name);
// If not empty we want to quit the loop else we want to quit function.
if !username.is_empty() {
break;
} else {
// Only send our client that username is taken.
let _ = sender
.send(Message::Text(String::from("Username already taken.")))
.await;
return;
}
}
}
// Subscribe before sending joined message.
let mut rx = state.tx.subscribe();
// Send joined message to all subscribers.
let msg = format!("{} joined.", username);
let _ = state.tx.send(msg);
// This task will receive broadcast messages and send text message to our client.
let mut send_task = tokio::spawn(async move {
while let Ok(msg) = rx.recv().await {
// In any websocket error, break loop.
if sender.send(Message::Text(msg)).await.is_err() {
break;
}
}
});
// Clone things we want to pass to the receiving task.
let tx = state.tx.clone();
let name = username.clone();
// This task will receive messages from client and send them to broadcast subscribers.
let mut recv_task = tokio::spawn(async move {
while let Some(Ok(Message::Text(text))) = receiver.next().await {
// Add username before message.
let _ = tx.send(format!("{}: {}", name, text));
}
});
// If any one of the tasks exit, abort the other.
tokio::select! {
_ = (&mut send_task) => recv_task.abort(),
_ = (&mut recv_task) => send_task.abort(),
};
// Send user left message.
let msg = format!("{} left.", username);
let _ = state.tx.send(msg);
// Remove username from map so new clients can take it.
state.user_set.lock().unwrap().remove(&username);
}
fn check_username(state: &AppState, string: &mut String, name: &str) {
let mut user_set = state.user_set.lock().unwrap();
if !user_set.contains(name) {
user_set.insert(name.to_owned());
string.push_str(name);
}
}
// Include utf-8 file at **compile** time.
async fn index() -> Html<&'static str> {
Html(std::include_str!("../chat.html"))
}
<file_sep>//! Provides a RESTful web server managing some Todos.
//!
//! API will be:
//!
//! - `GET /todos`: return a JSON list of Todos.
//! - `POST /todos`: create a new Todo.
//! - `PUT /todos/:id`: update a specific Todo.
//! - `DELETE /todos/:id`: delete a specific Todo.
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-todos
//! ```
use axum::{
extract::{Extension, Path, Query},
handler::{get, patch},
http::StatusCode,
response::IntoResponse,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
convert::Infallible,
net::SocketAddr,
sync::{Arc, RwLock},
time::Duration,
};
use tower::{BoxError, ServiceBuilder};
use tower_http::{add_extension::AddExtensionLayer, trace::TraceLayer};
use uuid::Uuid;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_todos=debug,tower_http=debug")
}
tracing_subscriber::fmt::init();
let db = Db::default();
// Compose the routes
let app = Router::new()
.route("/todos", get(todos_index).post(todos_create))
.route("/todos/:id", patch(todos_update).delete(todos_delete))
// Add middleware to all routes
.layer(
ServiceBuilder::new()
.timeout(Duration::from_secs(10))
.layer(TraceLayer::new_for_http())
.layer(AddExtensionLayer::new(db))
.into_inner(),
)
.handle_error(|error: BoxError| {
let result = if error.is::<tower::timeout::error::Elapsed>() {
Ok(StatusCode::REQUEST_TIMEOUT)
} else {
Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
))
};
Ok::<_, Infallible>(result)
})
// Make sure all errors have been handled
.check_infallible();
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
// The query parameters for todos index
#[derive(Debug, Deserialize, Default)]
pub struct Pagination {
pub offset: Option<usize>,
pub limit: Option<usize>,
}
async fn todos_index(
pagination: Option<Query<Pagination>>,
Extension(db): Extension<Db>,
) -> impl IntoResponse {
let todos = db.read().unwrap();
let Query(pagination) = pagination.unwrap_or_default();
let todos = todos
.values()
.cloned()
.skip(pagination.offset.unwrap_or(0))
.take(pagination.limit.unwrap_or(usize::MAX))
.collect::<Vec<_>>();
Json(todos)
}
#[derive(Debug, Deserialize)]
struct CreateTodo {
text: String,
}
async fn todos_create(
Json(input): Json<CreateTodo>,
Extension(db): Extension<Db>,
) -> impl IntoResponse {
let todo = Todo {
id: Uuid::new_v4(),
text: input.text,
completed: false,
};
db.write().unwrap().insert(todo.id, todo.clone());
(StatusCode::CREATED, Json(todo))
}
#[derive(Debug, Deserialize)]
struct UpdateTodo {
text: Option<String>,
completed: Option<bool>,
}
async fn todos_update(
Path(id): Path<Uuid>,
Json(input): Json<UpdateTodo>,
Extension(db): Extension<Db>,
) -> Result<impl IntoResponse, StatusCode> {
let mut todo = db
.read()
.unwrap()
.get(&id)
.cloned()
.ok_or(StatusCode::NOT_FOUND)?;
if let Some(text) = input.text {
todo.text = text;
}
if let Some(completed) = input.completed {
todo.completed = completed;
}
db.write().unwrap().insert(todo.id, todo.clone());
Ok(Json(todo))
}
async fn todos_delete(Path(id): Path<Uuid>, Extension(db): Extension<Db>) -> impl IntoResponse {
if db.write().unwrap().remove(&id).is_some() {
StatusCode::NO_CONTENT
} else {
StatusCode::NOT_FOUND
}
}
type Db = Arc<RwLock<HashMap<Uuid, Todo>>>;
#[derive(Debug, Serialize, Clone)]
struct Todo {
id: Uuid,
text: String,
completed: bool,
}
<file_sep>//! Types and traits for extracting data from requests.
//!
//! A handler function is an async function that takes any number of
//! "extractors" as arguments. An extractor is a type that implements
//! [`FromRequest`](crate::extract::FromRequest).
//!
//! For example, [`Json`] is an extractor that consumes the request body and
//! deserializes it as JSON into some target type:
//!
//! ```rust,no_run
//! use axum::{
//! Json,
//! handler::{post, Handler},
//! Router,
//! };
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct CreateUser {
//! email: String,
//! password: String,
//! }
//!
//! async fn create_user(payload: Json<CreateUser>) {
//! let payload: CreateUser = payload.0;
//!
//! // ...
//! }
//!
//! let app = Router::new().route("/users", post(create_user));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! # Defining custom extractors
//!
//! You can also define your own extractors by implementing [`FromRequest`]:
//!
//! ```rust,no_run
//! use axum::{
//! async_trait,
//! extract::{FromRequest, RequestParts},
//! handler::get,
//! Router,
//! };
//! use http::{StatusCode, header::{HeaderValue, USER_AGENT}};
//!
//! struct ExtractUserAgent(HeaderValue);
//!
//! #[async_trait]
//! impl<B> FromRequest<B> for ExtractUserAgent
//! where
//! B: Send,
//! {
//! type Rejection = (StatusCode, &'static str);
//!
//! async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
//! let user_agent = req.headers().and_then(|headers| headers.get(USER_AGENT));
//!
//! if let Some(user_agent) = user_agent {
//! Ok(ExtractUserAgent(user_agent.clone()))
//! } else {
//! Err((StatusCode::BAD_REQUEST, "`User-Agent` header is missing"))
//! }
//! }
//! }
//!
//! async fn handler(user_agent: ExtractUserAgent) {
//! let user_agent: HeaderValue = user_agent.0;
//!
//! // ...
//! }
//!
//! let app = Router::new().route("/foo", get(handler));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! # Multiple extractors
//!
//! Handlers can also contain multiple extractors:
//!
//! ```rust,no_run
//! use axum::{
//! extract::{Path, Query},
//! handler::get,
//! Router,
//! };
//! use std::collections::HashMap;
//!
//! async fn handler(
//! // Extract captured parameters from the URL
//! params: Path<HashMap<String, String>>,
//! // Parse query string into a `HashMap`
//! query_params: Query<HashMap<String, String>>,
//! // Buffer the request body into a `Bytes`
//! bytes: bytes::Bytes,
//! ) {
//! // ...
//! }
//!
//! let app = Router::new().route("/foo", get(handler));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! Note that only one extractor can consume the request body. If multiple body extractors are
//! applied a `500 Internal Server Error` response will be returned.
//!
//! # Optional extractors
//!
//! Wrapping extractors in `Option` will make them optional:
//!
//! ```rust,no_run
//! use axum::{
//! extract::Json,
//! handler::post,
//! Router,
//! };
//! use serde_json::Value;
//!
//! async fn create_user(payload: Option<Json<Value>>) {
//! if let Some(payload) = payload {
//! // We got a valid JSON payload
//! } else {
//! // Payload wasn't valid JSON
//! }
//! }
//!
//! let app = Router::new().route("/users", post(create_user));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! Wrapping extractors in `Result` makes them optional and gives you the reason
//! the extraction failed:
//!
//! ```rust,no_run
//! use axum::{
//! extract::{Json, rejection::JsonRejection},
//! handler::post,
//! Router,
//! };
//! use serde_json::Value;
//!
//! async fn create_user(payload: Result<Json<Value>, JsonRejection>) {
//! match payload {
//! Ok(payload) => {
//! // We got a valid JSON payload
//! }
//! Err(JsonRejection::MissingJsonContentType(_)) => {
//! // Request didn't have `Content-Type: application/json`
//! // header
//! }
//! Err(JsonRejection::InvalidJsonBody(_)) => {
//! // Couldn't deserialize the body into the target type
//! }
//! Err(JsonRejection::BodyAlreadyExtracted(_)) => {
//! // Another extractor had already consumed the body
//! }
//! Err(_) => {
//! // `JsonRejection` is marked `#[non_exhaustive]` so match must
//! // include a catch-all case.
//! }
//! }
//! }
//!
//! let app = Router::new().route("/users", post(create_user));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! # Reducing boilerplate
//!
//! If you're feeling adventurous you can even deconstruct the extractors
//! directly on the function signature:
//!
//! ```rust,no_run
//! use axum::{
//! extract::Json,
//! handler::post,
//! Router,
//! };
//! use serde_json::Value;
//!
//! async fn create_user(Json(value): Json<Value>) {
//! // `value` is of type `Value`
//! }
//!
//! let app = Router::new().route("/users", post(create_user));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! # Request body extractors
//!
//! Most of the time your request body type will be [`body::Body`] (a re-export
//! of [`hyper::Body`]), which is directly supported by all extractors.
//!
//! However if you're applying a tower middleware that changes the response you
//! might have to apply a different body type to some extractors:
//!
//! ```rust
//! use std::{
//! task::{Context, Poll},
//! pin::Pin,
//! };
//! use tower_http::map_request_body::MapRequestBodyLayer;
//! use axum::{
//! extract::{self, BodyStream},
//! body::Body,
//! handler::get,
//! http::{header::HeaderMap, Request},
//! Router,
//! };
//!
//! struct MyBody<B>(B);
//!
//! impl<B> http_body::Body for MyBody<B>
//! where
//! B: http_body::Body + Unpin,
//! {
//! type Data = B::Data;
//! type Error = B::Error;
//!
//! fn poll_data(
//! mut self: Pin<&mut Self>,
//! cx: &mut Context<'_>,
//! ) -> Poll<Option<Result<Self::Data, Self::Error>>> {
//! Pin::new(&mut self.0).poll_data(cx)
//! }
//!
//! fn poll_trailers(
//! mut self: Pin<&mut Self>,
//! cx: &mut Context<'_>,
//! ) -> Poll<Result<Option<HeaderMap>, Self::Error>> {
//! Pin::new(&mut self.0).poll_trailers(cx)
//! }
//! }
//!
//! let app = Router::new()
//! .route(
//! "/string",
//! // `String` works directly with any body type
//! get(|_: String| async {})
//! )
//! .route(
//! "/body",
//! // `extract::Body` defaults to `axum::body::Body`
//! // but can be customized
//! get(|_: extract::RawBody<MyBody<Body>>| async {})
//! )
//! .route(
//! "/body-stream",
//! // same for `extract::BodyStream`
//! get(|_: extract::BodyStream| async {}),
//! )
//! .route(
//! // and `Request<_>`
//! "/request",
//! get(|_: Request<MyBody<Body>>| async {})
//! )
//! // middleware that changes the request body type
//! .layer(MapRequestBodyLayer::new(MyBody));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! [`body::Body`]: crate::body::Body
use crate::{response::IntoResponse, Error};
use async_trait::async_trait;
use http::{header, Extensions, HeaderMap, Method, Request, Uri, Version};
use rejection::*;
use std::convert::Infallible;
pub mod connect_info;
pub mod extractor_middleware;
pub mod rejection;
#[cfg(feature = "ws")]
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
pub mod ws;
mod content_length_limit;
mod extension;
mod form;
mod path;
mod query;
mod raw_query;
mod request_parts;
mod tuple;
#[doc(inline)]
#[allow(deprecated)]
pub use self::{
connect_info::ConnectInfo,
content_length_limit::ContentLengthLimit,
extension::Extension,
extractor_middleware::extractor_middleware,
form::Form,
path::Path,
query::Query,
raw_query::RawQuery,
request_parts::OriginalUri,
request_parts::{BodyStream, RawBody},
};
#[doc(no_inline)]
pub use crate::Json;
#[cfg(feature = "multipart")]
#[cfg_attr(docsrs, doc(cfg(feature = "multipart")))]
pub mod multipart;
#[cfg(feature = "multipart")]
#[cfg_attr(docsrs, doc(cfg(feature = "multipart")))]
#[doc(inline)]
pub use self::multipart::Multipart;
#[cfg(feature = "ws")]
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
#[doc(inline)]
pub use self::ws::WebSocketUpgrade;
#[cfg(feature = "headers")]
#[cfg_attr(docsrs, doc(cfg(feature = "headers")))]
mod typed_header;
#[cfg(feature = "headers")]
#[cfg_attr(docsrs, doc(cfg(feature = "headers")))]
#[doc(inline)]
pub use self::typed_header::TypedHeader;
/// Types that can be created from requests.
///
/// See the [module docs](crate::extract) for more details.
///
/// # What is the `B` type parameter?
///
/// `FromRequest` is generic over the request body (the `B` in
/// [`http::Request<B>`]). This is to allow `FromRequest` to be usable with any
/// type of request body. This is necessary because some middleware change the
/// request body, for example to add timeouts.
///
/// If you're writing your own `FromRequest` that wont be used outside your
/// application, and not using any middleware that changes the request body, you
/// can most likely use `axum::body::Body`. Note that this is also the default.
///
/// If you're writing a library that's intended for others to use, it's recommended
/// to keep the generic type parameter:
///
/// ```rust
/// use axum::{
/// async_trait,
/// extract::{FromRequest, RequestParts},
/// };
///
/// struct MyExtractor;
///
/// #[async_trait]
/// impl<B> FromRequest<B> for MyExtractor
/// where
/// B: Send, // required by `async_trait`
/// {
/// type Rejection = http::StatusCode;
///
/// async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
/// // ...
/// # unimplemented!()
/// }
/// }
/// ```
///
/// This ensures your extractor is as flexible as possible.
///
/// [`http::Request<B>`]: http::Request
#[async_trait]
pub trait FromRequest<B = crate::body::Body>: Sized {
/// If the extractor fails it'll use this "rejection" type. A rejection is
/// a kind of error that can be converted into a response.
type Rejection: IntoResponse;
/// Perform the extraction.
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection>;
}
/// The type used with [`FromRequest`] to extract data from requests.
///
/// Has several convenience methods for getting owned parts of the request.
#[derive(Debug)]
pub struct RequestParts<B = crate::body::Body> {
method: Method,
uri: Uri,
version: Version,
headers: Option<HeaderMap>,
extensions: Option<Extensions>,
body: Option<B>,
}
impl<B> RequestParts<B> {
/// Create a new `RequestParts`.
///
/// You generally shouldn't need to construct this type yourself, unless
/// using extractors outside of axum for example to implement a
/// [`tower::Service`].
pub fn new(req: Request<B>) -> Self {
let (
http::request::Parts {
method,
uri,
version,
headers,
extensions,
..
},
body,
) = req.into_parts();
RequestParts {
method,
uri,
version,
headers: Some(headers),
extensions: Some(extensions),
body: Some(body),
}
}
/// Convert this `RequestParts` back into a [`Request`].
///
/// Fails if
///
/// - The full [`HeaderMap`] has been extracted, that is [`take_headers`]
/// have been called.
/// - The full [`Extensions`] has been extracted, that is
/// [`take_extensions`] have been called.
/// - The request body has been extracted, that is [`take_body`] have been
/// called.
///
/// [`take_headers`]: RequestParts::take_headers
/// [`take_extensions`]: RequestParts::take_extensions
/// [`take_body`]: RequestParts::take_body
pub fn try_into_request(self) -> Result<Request<B>, Error> {
let Self {
method,
uri,
version,
mut headers,
mut extensions,
mut body,
} = self;
let mut req = if let Some(body) = body.take() {
Request::new(body)
} else {
return Err(Error::new(RequestAlreadyExtracted::BodyAlreadyExtracted(
BodyAlreadyExtracted,
)));
};
*req.method_mut() = method;
*req.uri_mut() = uri;
*req.version_mut() = version;
if let Some(headers) = headers.take() {
*req.headers_mut() = headers;
} else {
return Err(Error::new(
RequestAlreadyExtracted::HeadersAlreadyExtracted(HeadersAlreadyExtracted),
));
}
if let Some(extensions) = extensions.take() {
*req.extensions_mut() = extensions;
} else {
return Err(Error::new(
RequestAlreadyExtracted::ExtensionsAlreadyExtracted(ExtensionsAlreadyExtracted),
));
}
Ok(req)
}
/// Gets a reference the request method.
pub fn method(&self) -> &Method {
&self.method
}
/// Gets a mutable reference to the request method.
pub fn method_mut(&mut self) -> &mut Method {
&mut self.method
}
/// Gets a reference the request URI.
pub fn uri(&self) -> &Uri {
&self.uri
}
/// Gets a mutable reference to the request URI.
pub fn uri_mut(&mut self) -> &mut Uri {
&mut self.uri
}
/// Get the request HTTP version.
pub fn version(&self) -> Version {
self.version
}
/// Gets a mutable reference to the request HTTP version.
pub fn version_mut(&mut self) -> &mut Version {
&mut self.version
}
/// Gets a reference to the request headers.
///
/// Returns `None` if the headers has been taken by another extractor.
pub fn headers(&self) -> Option<&HeaderMap> {
self.headers.as_ref()
}
/// Gets a mutable reference to the request headers.
///
/// Returns `None` if the headers has been taken by another extractor.
pub fn headers_mut(&mut self) -> Option<&mut HeaderMap> {
self.headers.as_mut()
}
/// Takes the headers out of the request, leaving a `None` in its place.
pub fn take_headers(&mut self) -> Option<HeaderMap> {
self.headers.take()
}
/// Gets a reference to the request extensions.
///
/// Returns `None` if the extensions has been taken by another extractor.
pub fn extensions(&self) -> Option<&Extensions> {
self.extensions.as_ref()
}
/// Gets a mutable reference to the request extensions.
///
/// Returns `None` if the extensions has been taken by another extractor.
pub fn extensions_mut(&mut self) -> Option<&mut Extensions> {
self.extensions.as_mut()
}
/// Takes the extensions out of the request, leaving a `None` in its place.
pub fn take_extensions(&mut self) -> Option<Extensions> {
self.extensions.take()
}
/// Gets a reference to the request body.
///
/// Returns `None` if the body has been taken by another extractor.
pub fn body(&self) -> Option<&B> {
self.body.as_ref()
}
/// Gets a mutable reference to the request body.
///
/// Returns `None` if the body has been taken by another extractor.
pub fn body_mut(&mut self) -> Option<&mut B> {
self.body.as_mut()
}
/// Takes the body out of the request, leaving a `None` in its place.
pub fn take_body(&mut self) -> Option<B> {
self.body.take()
}
}
#[async_trait]
impl<T, B> FromRequest<B> for Option<T>
where
T: FromRequest<B>,
B: Send,
{
type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Option<T>, Self::Rejection> {
Ok(T::from_request(req).await.ok())
}
}
#[async_trait]
impl<T, B> FromRequest<B> for Result<T, T::Rejection>
where
T: FromRequest<B>,
B: Send,
{
type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
Ok(T::from_request(req).await)
}
}
pub(crate) fn has_content_type<B>(
req: &RequestParts<B>,
expected_content_type: &str,
) -> Result<bool, HeadersAlreadyExtracted> {
let content_type = if let Some(content_type) = req
.headers()
.ok_or(HeadersAlreadyExtracted)?
.get(header::CONTENT_TYPE)
{
content_type
} else {
return Ok(false);
};
let content_type = if let Ok(content_type) = content_type.to_str() {
content_type
} else {
return Ok(false);
};
Ok(content_type.starts_with(expected_content_type))
}
pub(crate) fn take_body<B>(req: &mut RequestParts<B>) -> Result<B, BodyAlreadyExtracted> {
req.take_body().ok_or(BodyAlreadyExtracted)
}
<file_sep>mod starwars;
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql::{EmptyMutation, EmptySubscription, Request, Response, Schema};
use axum::response::IntoResponse;
use axum::{extract::Extension, handler::get, response::Html, AddExtensionLayer, Json, Router};
use starwars::{QueryRoot, StarWars, StarWarsSchema};
async fn graphql_handler(schema: Extension<StarWarsSchema>, req: Json<Request>) -> Json<Response> {
schema.execute(req.0).await.into()
}
async fn graphql_playground() -> impl IntoResponse {
Html(playground_source(GraphQLPlaygroundConfig::new("/")))
}
#[tokio::main]
async fn main() {
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
.data(StarWars::new())
.finish();
let app = Router::new()
.route("/", get(graphql_playground).post(graphql_handler))
.layer(AddExtensionLayer::new(schema));
println!("Playground: http://localhost:3000");
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-print-request-response
//! ```
use axum::{
body::{Body, BoxBody, Bytes},
handler::post,
http::{Request, Response},
Router,
};
use std::net::SocketAddr;
use tower::{filter::AsyncFilterLayer, util::AndThenLayer, BoxError};
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var(
"RUST_LOG",
"example_print_request_response=debug,tower_http=debug",
)
}
tracing_subscriber::fmt::init();
let app = Router::new()
.route("/", post(|| async move { "Hello from `POST /`" }))
.layer(AsyncFilterLayer::new(map_request))
.layer(AndThenLayer::new(map_response));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn map_request(req: Request<Body>) -> Result<Request<Body>, BoxError> {
let (parts, body) = req.into_parts();
let bytes = buffer_and_print("request", body).await?;
let req = Request::from_parts(parts, Body::from(bytes));
Ok(req)
}
async fn map_response(res: Response<BoxBody>) -> Result<Response<Body>, BoxError> {
let (parts, body) = res.into_parts();
let bytes = buffer_and_print("response", body).await?;
let res = Response::from_parts(parts, Body::from(bytes));
Ok(res)
}
async fn buffer_and_print<B>(direction: &str, body: B) -> Result<Bytes, BoxError>
where
B: axum::body::HttpBody<Data = Bytes>,
B::Error: Into<BoxError>,
{
let bytes = hyper::body::to_bytes(body).await.map_err(Into::into)?;
if let Ok(body) = std::str::from_utf8(&bytes) {
tracing::debug!("{} body = {:?}", direction, body);
}
Ok(bytes)
}
<file_sep>//! Example websocket server.
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-websockets
//! ```
use axum::{
extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
TypedHeader,
},
handler::get,
http::StatusCode,
response::IntoResponse,
Router,
};
use std::net::SocketAddr;
use tower_http::{
services::ServeDir,
trace::{DefaultMakeSpan, TraceLayer},
};
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_websockets=debug,tower_http=debug")
}
tracing_subscriber::fmt::init();
// build our application with some routes
let app = Router::new()
.nest(
"/",
axum::service::get(
ServeDir::new("examples/websockets/assets").append_index_html_on_directories(true),
)
.handle_error(|error: std::io::Error| {
Ok::<_, std::convert::Infallible>((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
))
}),
)
// routes are matched from bottom to top, so we have to put `nest` at the
// top since it matches all routes
.route("/ws", get(ws_handler))
// logging so we can see whats going on
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::default().include_headers(true)),
);
// run it with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn ws_handler(
ws: WebSocketUpgrade,
user_agent: Option<TypedHeader<headers::UserAgent>>,
) -> impl IntoResponse {
if let Some(TypedHeader(user_agent)) = user_agent {
println!("`{}` connected", user_agent.as_str());
}
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
if let Some(msg) = socket.recv().await {
if let Ok(msg) = msg {
println!("Client says: {:?}", msg);
} else {
println!("client disconnected");
return;
}
}
loop {
if socket
.send(Message::Text(String::from("Hi!")))
.await
.is_err()
{
println!("client disconnected");
return;
}
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
}
}
<file_sep>use bitflags::bitflags;
use http::Method;
bitflags! {
/// A filter that matches one or more HTTP methods.
pub struct MethodFilter: u16 {
/// Match `CONNECT` requests.
const CONNECT = 0b000000001;
/// Match `DELETE` requests.
const DELETE = 0b000000010;
/// Match `GET` requests.
const GET = 0b000000100;
/// Match `HEAD` requests.
const HEAD = 0b000001000;
/// Match `OPTIONS` requests.
const OPTIONS = 0b000010000;
/// Match `PATCH` requests.
const PATCH = 0b000100000;
/// Match `POSt` requests.
const POST = 0b001000000;
/// Match `PUT` requests.
const PUT = 0b010000000;
/// Match `TRACE` requests.
const TRACE = 0b100000000;
}
}
impl MethodFilter {
#[allow(clippy::match_like_matches_macro)]
pub(crate) fn matches(self, method: &Method) -> bool {
let method = match *method {
Method::CONNECT => Self::CONNECT,
Method::DELETE => Self::DELETE,
Method::GET => Self::GET,
Method::HEAD => Self::HEAD,
Method::OPTIONS => Self::OPTIONS,
Method::PATCH => Self::PATCH,
Method::POST => Self::POST,
Method::PUT => Self::PUT,
Method::TRACE => Self::TRACE,
_ => return false,
};
self.contains(method)
}
}
<file_sep>use crate::routing::UrlParams;
use crate::util::ByteStr;
use serde::{
de::{self, DeserializeSeed, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor},
forward_to_deserialize_any, Deserializer,
};
use std::fmt::{self, Display};
/// This type represents errors that can occur when deserializing.
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct PathDeserializerError(pub(crate) String);
impl de::Error for PathDeserializerError {
#[inline]
fn custom<T: Display>(msg: T) -> Self {
PathDeserializerError(msg.to_string())
}
}
impl std::error::Error for PathDeserializerError {
#[inline]
fn description(&self) -> &str {
"path deserializer error"
}
}
impl fmt::Display for PathDeserializerError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PathDeserializerError(msg) => write!(f, "{}", msg),
}
}
}
macro_rules! unsupported_type {
($trait_fn:ident, $name:literal) => {
fn $trait_fn<V>(self, _: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(PathDeserializerError::custom(concat!(
"unsupported type: ",
$name
)))
}
};
}
macro_rules! parse_single_value {
($trait_fn:ident, $visit_fn:ident, $tp:literal) => {
fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.url_params.0.len() != 1 {
return Err(PathDeserializerError::custom(
format!(
"wrong number of parameters: {} expected 1",
self.url_params.0.len()
)
.as_str(),
));
}
let value = self.url_params.0[0].1.parse().map_err(|_| {
PathDeserializerError::custom(format!(
"can not parse `{:?}` to a `{}`",
self.url_params.0[0].1.as_str(),
$tp
))
})?;
visitor.$visit_fn(value)
}
};
}
pub(crate) struct PathDeserializer<'de> {
url_params: &'de UrlParams,
}
impl<'de> PathDeserializer<'de> {
#[inline]
pub(crate) fn new(url_params: &'de UrlParams) -> Self {
PathDeserializer { url_params }
}
}
impl<'de> Deserializer<'de> for PathDeserializer<'de> {
type Error = PathDeserializerError;
unsupported_type!(deserialize_any, "'any'");
unsupported_type!(deserialize_bytes, "bytes");
unsupported_type!(deserialize_option, "Option<T>");
unsupported_type!(deserialize_identifier, "identifier");
unsupported_type!(deserialize_ignored_any, "ignored_any");
parse_single_value!(deserialize_bool, visit_bool, "bool");
parse_single_value!(deserialize_i8, visit_i8, "i8");
parse_single_value!(deserialize_i16, visit_i16, "i16");
parse_single_value!(deserialize_i32, visit_i32, "i32");
parse_single_value!(deserialize_i64, visit_i64, "i64");
parse_single_value!(deserialize_u8, visit_u8, "u8");
parse_single_value!(deserialize_u16, visit_u16, "u16");
parse_single_value!(deserialize_u32, visit_u32, "u32");
parse_single_value!(deserialize_u64, visit_u64, "u64");
parse_single_value!(deserialize_f32, visit_f32, "f32");
parse_single_value!(deserialize_f64, visit_f64, "f64");
parse_single_value!(deserialize_string, visit_string, "String");
parse_single_value!(deserialize_byte_buf, visit_string, "String");
parse_single_value!(deserialize_char, visit_char, "char");
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.url_params.0.len() != 1 {
return Err(PathDeserializerError::custom(format!(
"wrong number of parameters: {} expected 1",
self.url_params.0.len()
)));
}
visitor.visit_str(&self.url_params.0[0].1)
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_unit_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_seq(SeqDeserializer {
params: &self.url_params.0,
})
}
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.url_params.0.len() < len {
return Err(PathDeserializerError::custom(
format!(
"wrong number of parameters: {} expected {}",
self.url_params.0.len(),
len
)
.as_str(),
));
}
visitor.visit_seq(SeqDeserializer {
params: &self.url_params.0,
})
}
fn deserialize_tuple_struct<V>(
self,
_name: &'static str,
len: usize,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.url_params.0.len() < len {
return Err(PathDeserializerError::custom(
format!(
"wrong number of parameters: {} expected {}",
self.url_params.0.len(),
len
)
.as_str(),
));
}
visitor.visit_seq(SeqDeserializer {
params: &self.url_params.0,
})
}
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_map(MapDeserializer {
params: &self.url_params.0,
value: None,
})
}
fn deserialize_struct<V>(
self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_map(visitor)
}
fn deserialize_enum<V>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.url_params.0.len() != 1 {
return Err(PathDeserializerError::custom(format!(
"wrong number of parameters: {} expected 1",
self.url_params.0.len()
)));
}
visitor.visit_enum(EnumDeserializer {
value: &self.url_params.0[0].1,
})
}
}
struct MapDeserializer<'de> {
params: &'de [(ByteStr, ByteStr)],
value: Option<&'de str>,
}
impl<'de> MapAccess<'de> for MapDeserializer<'de> {
type Error = PathDeserializerError;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: DeserializeSeed<'de>,
{
match self.params.split_first() {
Some(((key, value), tail)) => {
self.value = Some(value);
self.params = tail;
seed.deserialize(KeyDeserializer { key }).map(Some)
}
None => Ok(None),
}
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: DeserializeSeed<'de>,
{
match self.value.take() {
Some(value) => seed.deserialize(ValueDeserializer { value }),
None => Err(serde::de::Error::custom("value is missing")),
}
}
}
struct KeyDeserializer<'de> {
key: &'de str,
}
macro_rules! parse_key {
($trait_fn:ident) => {
fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_str(self.key)
}
};
}
impl<'de> Deserializer<'de> for KeyDeserializer<'de> {
type Error = PathDeserializerError;
parse_key!(deserialize_identifier);
parse_key!(deserialize_str);
parse_key!(deserialize_string);
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(PathDeserializerError::custom("Unexpected"))
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char bytes
byte_buf option unit unit_struct seq tuple
tuple_struct map newtype_struct struct enum ignored_any
}
}
macro_rules! parse_value {
($trait_fn:ident, $visit_fn:ident, $ty:literal) => {
fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
let v = self.value.parse().map_err(|_| {
PathDeserializerError::custom(format!(
"can not parse `{:?}` to a `{}`",
self.value, $ty
))
})?;
visitor.$visit_fn(v)
}
};
}
struct ValueDeserializer<'de> {
value: &'de str,
}
impl<'de> Deserializer<'de> for ValueDeserializer<'de> {
type Error = PathDeserializerError;
unsupported_type!(deserialize_any, "any");
unsupported_type!(deserialize_seq, "seq");
unsupported_type!(deserialize_map, "map");
unsupported_type!(deserialize_identifier, "identifier");
parse_value!(deserialize_bool, visit_bool, "bool");
parse_value!(deserialize_i8, visit_i8, "i8");
parse_value!(deserialize_i16, visit_i16, "i16");
parse_value!(deserialize_i32, visit_i32, "i16");
parse_value!(deserialize_i64, visit_i64, "i64");
parse_value!(deserialize_u8, visit_u8, "u8");
parse_value!(deserialize_u16, visit_u16, "u16");
parse_value!(deserialize_u32, visit_u32, "u32");
parse_value!(deserialize_u64, visit_u64, "u64");
parse_value!(deserialize_f32, visit_f32, "f32");
parse_value!(deserialize_f64, visit_f64, "f64");
parse_value!(deserialize_string, visit_string, "String");
parse_value!(deserialize_byte_buf, visit_string, "String");
parse_value!(deserialize_char, visit_char, "char");
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_borrowed_str(self.value)
}
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_borrowed_bytes(self.value.as_bytes())
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_some(self)
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_unit_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn deserialize_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(PathDeserializerError::custom("unsupported type: tuple"))
}
fn deserialize_tuple_struct<V>(
self,
_name: &'static str,
_len: usize,
_visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(PathDeserializerError::custom(
"unsupported type: tuple struct",
))
}
fn deserialize_struct<V>(
self,
_name: &'static str,
_fields: &'static [&'static str],
_visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(PathDeserializerError::custom("unsupported type: struct"))
}
fn deserialize_enum<V>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_enum(EnumDeserializer { value: self.value })
}
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
}
struct EnumDeserializer<'de> {
value: &'de str,
}
impl<'de> EnumAccess<'de> for EnumDeserializer<'de> {
type Error = PathDeserializerError;
type Variant = UnitVariant;
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: de::DeserializeSeed<'de>,
{
Ok((
seed.deserialize(KeyDeserializer { key: self.value })?,
UnitVariant,
))
}
}
struct UnitVariant;
impl<'de> VariantAccess<'de> for UnitVariant {
type Error = PathDeserializerError;
fn unit_variant(self) -> Result<(), Self::Error> {
Ok(())
}
fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
where
T: DeserializeSeed<'de>,
{
Err(PathDeserializerError::custom("not supported"))
}
fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(PathDeserializerError::custom("not supported"))
}
fn struct_variant<V>(
self,
_fields: &'static [&'static str],
_visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(PathDeserializerError::custom("not supported"))
}
}
struct SeqDeserializer<'de> {
params: &'de [(ByteStr, ByteStr)],
}
impl<'de> SeqAccess<'de> for SeqDeserializer<'de> {
type Error = PathDeserializerError;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
match self.params.split_first() {
Some(((_, value), tail)) => {
self.params = tail;
Ok(Some(seed.deserialize(ValueDeserializer { value })?))
}
None => Ok(None),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::util::ByteStr;
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Deserialize, Eq, PartialEq)]
enum MyEnum {
A,
B,
#[serde(rename = "c")]
C,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
struct Struct {
c: String,
b: bool,
a: i32,
}
fn create_url_params<I, K, V>(values: I) -> UrlParams
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
UrlParams(
values
.into_iter()
.map(|(k, v)| (ByteStr::new(k), ByteStr::new(v)))
.collect(),
)
}
macro_rules! check_single_value {
($ty:ty, $value_str:literal, $value:expr) => {
#[allow(clippy::bool_assert_comparison)]
{
let url_params = create_url_params(vec![("value", $value_str)]);
let deserializer = PathDeserializer::new(&url_params);
assert_eq!(<$ty>::deserialize(deserializer).unwrap(), $value);
}
};
}
#[test]
fn test_parse_single_value() {
check_single_value!(bool, "true", true);
check_single_value!(bool, "false", false);
check_single_value!(i8, "-123", -123);
check_single_value!(i16, "-123", -123);
check_single_value!(i32, "-123", -123);
check_single_value!(i64, "-123", -123);
check_single_value!(u8, "123", 123);
check_single_value!(u16, "123", 123);
check_single_value!(u32, "123", 123);
check_single_value!(u64, "123", 123);
check_single_value!(f32, "123", 123.0);
check_single_value!(f64, "123", 123.0);
check_single_value!(String, "abc", "abc");
check_single_value!(char, "a", 'a');
let url_params = create_url_params(vec![("a", "B")]);
assert_eq!(
MyEnum::deserialize(PathDeserializer::new(&url_params)).unwrap(),
MyEnum::B
);
let url_params = create_url_params(vec![("a", "1"), ("b", "2")]);
assert_eq!(
i32::deserialize(PathDeserializer::new(&url_params)).unwrap_err(),
PathDeserializerError::custom("wrong number of parameters: 2 expected 1".to_string())
);
}
#[test]
fn test_parse_seq() {
let url_params = create_url_params(vec![("a", "1"), ("b", "true"), ("c", "abc")]);
assert_eq!(
<(i32, bool, String)>::deserialize(PathDeserializer::new(&url_params)).unwrap(),
(1, true, "abc".to_string())
);
#[derive(Debug, Deserialize, Eq, PartialEq)]
struct TupleStruct(i32, bool, String);
assert_eq!(
TupleStruct::deserialize(PathDeserializer::new(&url_params)).unwrap(),
TupleStruct(1, true, "abc".to_string())
);
let url_params = create_url_params(vec![("a", "1"), ("b", "2"), ("c", "3")]);
assert_eq!(
<Vec<i32>>::deserialize(PathDeserializer::new(&url_params)).unwrap(),
vec![1, 2, 3]
);
let url_params = create_url_params(vec![("a", "c"), ("a", "B")]);
assert_eq!(
<Vec<MyEnum>>::deserialize(PathDeserializer::new(&url_params)).unwrap(),
vec![MyEnum::C, MyEnum::B]
);
}
#[test]
fn test_parse_struct() {
let url_params = create_url_params(vec![("a", "1"), ("b", "true"), ("c", "abc")]);
assert_eq!(
Struct::deserialize(PathDeserializer::new(&url_params)).unwrap(),
Struct {
c: "abc".to_string(),
b: true,
a: 1,
}
);
}
#[test]
fn test_parse_map() {
let url_params = create_url_params(vec![("a", "1"), ("b", "true"), ("c", "abc")]);
assert_eq!(
<HashMap<String, String>>::deserialize(PathDeserializer::new(&url_params)).unwrap(),
[("a", "1"), ("b", "true"), ("c", "abc")]
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect()
);
}
}
<file_sep>mod de;
use super::{rejection::*, FromRequest};
use crate::{extract::RequestParts, routing::UrlParams};
use async_trait::async_trait;
use serde::de::DeserializeOwned;
use std::ops::{Deref, DerefMut};
/// Extractor that will get captures from the URL and parse them using
/// [`serde`].
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// extract::Path,
/// handler::get,
/// Router,
/// };
/// use uuid::Uuid;
///
/// async fn users_teams_show(
/// Path((user_id, team_id)): Path<(Uuid, Uuid)>,
/// ) {
/// // ...
/// }
///
/// let app = Router::new().route("/users/:user_id/team/:team_id", get(users_teams_show));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// If the path contains only one parameter, then you can omit the tuple.
///
/// ```rust,no_run
/// use axum::{
/// extract::Path,
/// handler::get,
/// Router,
/// };
/// use uuid::Uuid;
///
/// async fn user_info(Path(user_id): Path<Uuid>) {
/// // ...
/// }
///
/// let app = Router::new().route("/users/:user_id", get(user_info));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// Path segments also can be deserialized into any type that implements
/// [`serde::Deserialize`]. Path segment labels will be matched with struct
/// field names.
///
/// ```rust,no_run
/// use axum::{
/// extract::Path,
/// handler::get,
/// Router,
/// };
/// use serde::Deserialize;
/// use uuid::Uuid;
///
/// #[derive(Deserialize)]
/// struct Params {
/// user_id: Uuid,
/// team_id: Uuid,
/// }
///
/// async fn users_teams_show(
/// Path(Params { user_id, team_id }): Path<Params>,
/// ) {
/// // ...
/// }
///
/// let app = Router::new().route("/users/:user_id/team/:team_id", get(users_teams_show));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// If you wish to capture all path parameters you can use `HashMap` or `Vec`:
///
/// ```rust,no_run
/// use axum::{
/// extract::Path,
/// handler::get,
/// Router,
/// };
/// use std::collections::HashMap;
///
/// async fn params_map(
/// Path(params): Path<HashMap<String, String>>,
/// ) {
/// // ...
/// }
///
/// async fn params_vec(
/// Path(params): Path<Vec<(String, String)>>,
/// ) {
/// // ...
/// }
///
/// let app = Router::new()
/// .route("/users/:user_id/team/:team_id", get(params_map).post(params_vec));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// [`serde`]: https://crates.io/crates/serde
/// [`serde::Deserialize`]: https://docs.rs/serde/1.0.127/serde/trait.Deserialize.html
#[derive(Debug)]
pub struct Path<T>(pub T);
impl<T> Deref for Path<T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for Path<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[async_trait]
impl<T, B> FromRequest<B> for Path<T>
where
T: DeserializeOwned + Send,
B: Send,
{
type Rejection = PathParamsRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
const EMPTY_URL_PARAMS: &UrlParams = &UrlParams(Vec::new());
let url_params = if let Some(params) = req
.extensions_mut()
.and_then(|ext| ext.get::<Option<UrlParams>>())
{
params.as_ref().unwrap_or(EMPTY_URL_PARAMS)
} else {
return Err(MissingRouteParams.into());
};
T::deserialize(de::PathDeserializer::new(url_params))
.map_err(|err| PathParamsRejection::InvalidPathParam(InvalidPathParam::new(err.0)))
.map(Path)
}
}
<file_sep>use super::{FromRequest, RequestParts};
use crate::response::IntoResponse;
use async_trait::async_trait;
use bytes::Bytes;
use headers::HeaderMapExt;
use http_body::Full;
use std::{convert::Infallible, ops::Deref};
/// Extractor that extracts a typed header value from [`headers`].
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// extract::TypedHeader,
/// handler::get,
/// Router,
/// };
/// use headers::UserAgent;
///
/// async fn users_teams_show(
/// TypedHeader(user_agent): TypedHeader<UserAgent>,
/// ) {
/// // ...
/// }
///
/// let app = Router::new().route("/users/:user_id/team/:team_id", get(users_teams_show));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
#[cfg(feature = "headers")]
#[cfg_attr(docsrs, doc(cfg(feature = "headers")))]
#[derive(Debug, Clone, Copy)]
pub struct TypedHeader<T>(pub T);
#[async_trait]
impl<T, B> FromRequest<B> for TypedHeader<T>
where
T: headers::Header,
B: Send,
{
type Rejection = TypedHeaderRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let headers = if let Some(headers) = req.headers() {
headers
} else {
return Err(TypedHeaderRejection {
name: T::name(),
reason: Reason::Missing,
});
};
match headers.typed_try_get::<T>() {
Ok(Some(value)) => Ok(Self(value)),
Ok(None) => Err(TypedHeaderRejection {
name: T::name(),
reason: Reason::Missing,
}),
Err(err) => Err(TypedHeaderRejection {
name: T::name(),
reason: Reason::Error(err),
}),
}
}
}
impl<T> Deref for TypedHeader<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Rejection used for [`TypedHeader`](super::TypedHeader).
#[cfg(feature = "headers")]
#[cfg_attr(docsrs, doc(cfg(feature = "headers")))]
#[derive(Debug)]
pub struct TypedHeaderRejection {
name: &'static http::header::HeaderName,
reason: Reason,
}
#[derive(Debug)]
enum Reason {
Missing,
Error(headers::Error),
}
impl IntoResponse for TypedHeaderRejection {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> http::Response<Self::Body> {
let mut res = self.to_string().into_response();
*res.status_mut() = http::StatusCode::BAD_REQUEST;
res
}
}
impl std::fmt::Display for TypedHeaderRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.reason {
Reason::Missing => {
write!(f, "Header of type `{}` was missing", self.name)
}
Reason::Error(err) => {
write!(f, "{} ({})", err, self.name)
}
}
}
}
impl std::error::Error for TypedHeaderRejection {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.reason {
Reason::Error(err) => Some(err),
Reason::Missing => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{handler::get, response::IntoResponse, tests::*, Router};
#[tokio::test]
async fn typed_header() {
async fn handle(
TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
) -> impl IntoResponse {
user_agent.to_string()
}
let app = Router::new().route("/", get(handle));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}", addr))
.header("user-agent", "foobar")
.send()
.await
.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "foobar");
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "Header of type `user-agent` was missing");
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-sessions
//! ```
use async_session::{MemoryStore, Session, SessionStore as _};
use axum::{
async_trait,
extract::{Extension, FromRequest, RequestParts},
handler::get,
http::{
self,
header::{HeaderMap, HeaderValue},
StatusCode,
},
response::IntoResponse,
AddExtensionLayer, Router,
};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use uuid::Uuid;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_sessions=debug")
}
tracing_subscriber::fmt::init();
// `MemoryStore` just used as an example. Don't use this in production.
let store = MemoryStore::new();
let app = Router::new()
.route("/", get(handler))
.layer(AddExtensionLayer::new(store));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler(user_id: UserIdFromSession) -> impl IntoResponse {
let (headers, user_id) = match user_id {
UserIdFromSession::FoundUserId(user_id) => (HeaderMap::new(), user_id),
UserIdFromSession::CreatedFreshUserId { user_id, cookie } => {
let mut headers = HeaderMap::new();
headers.insert(http::header::SET_COOKIE, cookie);
(headers, user_id)
}
};
dbg!(user_id);
headers
}
enum UserIdFromSession {
FoundUserId(UserId),
CreatedFreshUserId {
user_id: UserId,
cookie: HeaderValue,
},
}
#[async_trait]
impl<B> FromRequest<B> for UserIdFromSession
where
B: Send,
{
type Rejection = (StatusCode, &'static str);
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let Extension(store) = Extension::<MemoryStore>::from_request(req)
.await
.expect("`MemoryStore` extension missing");
let headers = req.headers().expect("other extractor taken headers");
let cookie = if let Some(cookie) = headers
.get(http::header::COOKIE)
.and_then(|value| value.to_str().ok())
.map(|value| value.to_string())
{
cookie
} else {
let user_id = UserId::new();
let mut session = Session::new();
session.insert("user_id", user_id).unwrap();
let cookie = store.store_session(session).await.unwrap().unwrap();
return Ok(Self::CreatedFreshUserId {
user_id,
cookie: cookie.parse().unwrap(),
});
};
let user_id = if let Some(session) = store.load_session(cookie).await.unwrap() {
if let Some(user_id) = session.get::<UserId>("user_id") {
user_id
} else {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"No `user_id` found in session",
));
}
} else {
return Err((StatusCode::BAD_REQUEST, "No session found for cookie"));
};
Ok(Self::FoundUserId(user_id))
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
struct UserId(Uuid);
impl UserId {
fn new() -> Self {
Self(Uuid::new_v4())
}
}
<file_sep>use super::{has_content_type, rejection::*, take_body, FromRequest, RequestParts};
use crate::BoxError;
use async_trait::async_trait;
use bytes::Buf;
use http::Method;
use serde::de::DeserializeOwned;
use std::ops::Deref;
/// Extractor that deserializes `application/x-www-form-urlencoded` requests
/// into some type.
///
/// `T` is expected to implement [`serde::Deserialize`].
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// extract::Form,
/// handler::post,
/// Router,
/// };
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct SignUp {
/// username: String,
/// password: <PASSWORD>,
/// }
///
/// async fn accept_form(form: Form<SignUp>) {
/// let sign_up: SignUp = form.0;
///
/// // ...
/// }
///
/// let app = Router::new().route("/sign_up", post(accept_form));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// Note that `Content-Type: multipart/form-data` requests are not supported.
#[derive(Debug, Clone, Copy, Default)]
pub struct Form<T>(pub T);
#[async_trait]
impl<T, B> FromRequest<B> for Form<T>
where
T: DeserializeOwned,
B: http_body::Body + Send,
B::Data: Send,
B::Error: Into<BoxError>,
{
type Rejection = FormRejection;
#[allow(warnings)]
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
if req.method() == Method::GET {
let query = req.uri().query().unwrap_or_default();
let value = serde_urlencoded::from_str(query)
.map_err(FailedToDeserializeQueryString::new::<T, _>)?;
Ok(Form(value))
} else {
if !has_content_type(&req, "application/x-www-form-urlencoded")? {
Err(InvalidFormContentType)?;
}
let body = take_body(req)?;
let chunks = hyper::body::aggregate(body)
.await
.map_err(FailedToBufferBody::from_err)?;
let value = serde_urlencoded::from_reader(chunks.reader())
.map_err(FailedToDeserializeQueryString::new::<T, _>)?;
Ok(Form(value))
}
}
}
impl<T> Deref for Form<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::extract::RequestParts;
use http::Request;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Pagination {
size: Option<u64>,
page: Option<u64>,
}
async fn check_query<T: DeserializeOwned + PartialEq + Debug>(uri: impl AsRef<str>, value: T) {
let mut req = RequestParts::new(
Request::builder()
.uri(uri.as_ref())
.body(http_body::Empty::<bytes::Bytes>::new())
.unwrap(),
);
assert_eq!(Form::<T>::from_request(&mut req).await.unwrap().0, value);
}
async fn check_body<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
let mut req = RequestParts::new(
Request::builder()
.uri("http://example.com/test")
.method(Method::POST)
.header(
http::header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.body(http_body::Full::<bytes::Bytes>::new(
serde_urlencoded::to_string(&value).unwrap().into(),
))
.unwrap(),
);
assert_eq!(Form::<T>::from_request(&mut req).await.unwrap().0, value);
}
#[tokio::test]
async fn test_form_query() {
check_query(
"http://example.com/test",
Pagination {
size: None,
page: None,
},
)
.await;
check_query(
"http://example.com/test?size=10",
Pagination {
size: Some(10),
page: None,
},
)
.await;
check_query(
"http://example.com/test?size=10&page=20",
Pagination {
size: Some(10),
page: Some(20),
},
)
.await;
}
#[tokio::test]
async fn test_form_body() {
check_body(Pagination {
size: None,
page: None,
})
.await;
check_body(Pagination {
size: Some(10),
page: None,
})
.await;
check_body(Pagination {
size: Some(10),
page: Some(20),
})
.await;
}
#[tokio::test]
async fn test_incorrect_content_type() {
let mut req = RequestParts::new(
Request::builder()
.uri("http://example.com/test")
.method(Method::POST)
.header(http::header::CONTENT_TYPE, "application/json")
.body(http_body::Full::<bytes::Bytes>::new(
serde_urlencoded::to_string(&Pagination {
size: Some(10),
page: None,
})
.unwrap()
.into(),
))
.unwrap(),
);
assert!(matches!(
Form::<Pagination>::from_request(&mut req)
.await
.unwrap_err(),
FormRejection::InvalidFormContentType(InvalidFormContentType)
));
}
}
<file_sep>//! Async functions that can be used to handle requests.
use crate::{
body::{box_body, BoxBody},
extract::FromRequest,
response::IntoResponse,
routing::{EmptyRouter, MethodFilter},
service::HandleError,
util::Either,
BoxError,
};
use async_trait::async_trait;
use bytes::Bytes;
use http::{Request, Response};
use std::{
convert::Infallible,
fmt,
future::Future,
marker::PhantomData,
task::{Context, Poll},
};
use tower::ServiceExt;
use tower_layer::Layer;
use tower_service::Service;
pub mod future;
mod into_service;
pub use self::into_service::IntoService;
/// Route requests to the given handler regardless of the HTTP method of the
/// request.
///
/// # Example
///
/// ```rust
/// use axum::{
/// handler::any,
/// Router,
/// };
///
/// async fn handler() {}
///
/// // All requests to `/` will go to `handler` regardless of the HTTP method.
/// let app = Router::new().route("/", any(handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn any<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::all(), handler)
}
/// Route `CONNECT` requests to the given handler.
///
/// See [`get`] for an example.
pub fn connect<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::CONNECT, handler)
}
/// Route `DELETE` requests to the given handler.
///
/// See [`get`] for an example.
pub fn delete<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::DELETE, handler)
}
/// Route `GET` requests to the given handler.
///
/// # Example
///
/// ```rust
/// use axum::{
/// handler::get,
/// Router,
/// };
///
/// async fn handler() {}
///
/// // Requests to `GET /` will go to `handler`.
/// let app = Router::new().route("/", get(handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// Note that `get` routes will also be called for `HEAD` requests but will have
/// the response body removed. Make sure to add explicit `HEAD` routes
/// afterwards.
pub fn get<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::GET | MethodFilter::HEAD, handler)
}
/// Route `HEAD` requests to the given handler.
///
/// See [`get`] for an example.
pub fn head<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::HEAD, handler)
}
/// Route `OPTIONS` requests to the given handler.
///
/// See [`get`] for an example.
pub fn options<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::OPTIONS, handler)
}
/// Route `PATCH` requests to the given handler.
///
/// See [`get`] for an example.
pub fn patch<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::PATCH, handler)
}
/// Route `POST` requests to the given handler.
///
/// See [`get`] for an example.
pub fn post<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::POST, handler)
}
/// Route `PUT` requests to the given handler.
///
/// See [`get`] for an example.
pub fn put<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::PUT, handler)
}
/// Route `TRACE` requests to the given handler.
///
/// See [`get`] for an example.
pub fn trace<H, B, T>(handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::TRACE, handler)
}
/// Route requests with the given method to the handler.
///
/// # Example
///
/// ```rust
/// use axum::{
/// handler::on,
/// Router,
/// routing::MethodFilter,
/// };
///
/// async fn handler() {}
///
/// // Requests to `POST /` will go to `handler`.
/// let app = Router::new().route("/", on(MethodFilter::POST, handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn on<H, B, T>(method: MethodFilter, handler: H) -> OnMethod<H, B, T, EmptyRouter>
where
H: Handler<B, T>,
{
OnMethod {
method,
handler,
fallback: EmptyRouter::method_not_allowed(),
_marker: PhantomData,
}
}
pub(crate) mod sealed {
#![allow(unreachable_pub, missing_docs, missing_debug_implementations)]
pub trait HiddentTrait {}
pub struct Hidden;
impl HiddentTrait for Hidden {}
}
/// Trait for async functions that can be used to handle requests.
///
/// You shouldn't need to depend on this trait directly. It is automatically
/// implemented to closures of the right types.
///
/// See the [module docs](crate::handler) for more details.
#[async_trait]
pub trait Handler<B, T>: Clone + Send + Sized + 'static {
// This seals the trait. We cannot use the regular "sealed super trait"
// approach due to coherence.
#[doc(hidden)]
type Sealed: sealed::HiddentTrait;
/// Call the handler with the given request.
async fn call(self, req: Request<B>) -> Response<BoxBody>;
/// Apply a [`tower::Layer`] to the handler.
///
/// All requests to the handler will be processed by the layer's
/// corresponding middleware.
///
/// This can be used to add additional processing to a request for a single
/// handler.
///
/// Note this differs from [`routing::Layered`](crate::routing::Layered)
/// which adds a middleware to a group of routes.
///
/// # Example
///
/// Adding the [`tower::limit::ConcurrencyLimit`] middleware to a handler
/// can be done like so:
///
/// ```rust
/// use axum::{
/// handler::{get, Handler},
/// Router,
/// };
/// use tower::limit::{ConcurrencyLimitLayer, ConcurrencyLimit};
///
/// async fn handler() { /* ... */ }
///
/// let layered_handler = handler.layer(ConcurrencyLimitLayer::new(64));
/// let app = Router::new().route("/", get(layered_handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// When adding middleware that might fail its recommended to handle those
/// errors. See [`Layered::handle_error`] for more details.
fn layer<L>(self, layer: L) -> Layered<L::Service, T>
where
L: Layer<OnMethod<Self, B, T, EmptyRouter>>,
{
Layered::new(layer.layer(any(self)))
}
/// Convert the handler into a [`Service`].
///
/// This allows you to serve a single handler if you don't need any routing:
///
/// ```rust
/// use axum::{
/// Server, handler::Handler, http::{Uri, Method}, response::IntoResponse,
/// };
/// use tower::make::Shared;
/// use std::net::SocketAddr;
///
/// async fn handler(method: Method, uri: Uri, body: String) -> impl IntoResponse {
/// format!("received `{} {}` with body `{:?}`", method, uri, body)
/// }
///
/// let service = handler.into_service();
///
/// # async {
/// Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000)))
/// .serve(Shared::new(service))
/// .await?;
/// # Ok::<_, hyper::Error>(())
/// # };
/// ```
fn into_service(self) -> IntoService<Self, B, T> {
IntoService::new(self)
}
}
#[async_trait]
impl<F, Fut, Res, B> Handler<B, ()> for F
where
F: FnOnce() -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Res> + Send,
Res: IntoResponse,
B: Send + 'static,
{
type Sealed = sealed::Hidden;
async fn call(self, _req: Request<B>) -> Response<BoxBody> {
self().await.into_response().map(box_body)
}
}
macro_rules! impl_handler {
() => {
};
( $head:ident, $($tail:ident),* $(,)? ) => {
#[async_trait]
#[allow(non_snake_case)]
impl<F, Fut, B, Res, $head, $($tail,)*> Handler<B, ($head, $($tail,)*)> for F
where
F: FnOnce($head, $($tail,)*) -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Res> + Send,
B: Send + 'static,
Res: IntoResponse,
$head: FromRequest<B> + Send,
$( $tail: FromRequest<B> + Send,)*
{
type Sealed = sealed::Hidden;
async fn call(self, req: Request<B>) -> Response<BoxBody> {
let mut req = crate::extract::RequestParts::new(req);
let $head = match $head::from_request(&mut req).await {
Ok(value) => value,
Err(rejection) => return rejection.into_response().map(box_body),
};
$(
let $tail = match $tail::from_request(&mut req).await {
Ok(value) => value,
Err(rejection) => return rejection.into_response().map(box_body),
};
)*
let res = self($head, $($tail,)*).await;
res.into_response().map(crate::body::box_body)
}
}
impl_handler!($($tail,)*);
};
}
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
/// A [`Service`] created from a [`Handler`] by applying a Tower middleware.
///
/// Created with [`Handler::layer`]. See that method for more details.
pub struct Layered<S, T> {
svc: S,
_input: PhantomData<fn() -> T>,
}
impl<S, T> fmt::Debug for Layered<S, T>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Layered").field("svc", &self.svc).finish()
}
}
impl<S, T> Clone for Layered<S, T>
where
S: Clone,
{
fn clone(&self) -> Self {
Self::new(self.svc.clone())
}
}
#[async_trait]
impl<S, T, ReqBody, ResBody> Handler<ReqBody, T> for Layered<S, T>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone + Send + 'static,
S::Error: IntoResponse,
S::Future: Send,
T: 'static,
ReqBody: Send + 'static,
ResBody: http_body::Body<Data = Bytes> + Send + Sync + 'static,
ResBody::Error: Into<BoxError> + Send + Sync + 'static,
{
type Sealed = sealed::Hidden;
async fn call(self, req: Request<ReqBody>) -> Response<BoxBody> {
match self
.svc
.oneshot(req)
.await
.map_err(IntoResponse::into_response)
{
Ok(res) => res.map(box_body),
Err(res) => res.map(box_body),
}
}
}
impl<S, T> Layered<S, T> {
pub(crate) fn new(svc: S) -> Self {
Self {
svc,
_input: PhantomData,
}
}
/// Create a new [`Layered`] handler where errors will be handled using the
/// given closure.
///
/// This is used to convert errors to responses rather than simply
/// terminating the connection.
///
/// It works similarly to [`routing::Router::handle_error`]. See that for more details.
///
/// [`routing::Router::handle_error`]: crate::routing::Router::handle_error
pub fn handle_error<F, ReqBody, ResBody, Res, E>(
self,
f: F,
) -> Layered<HandleError<S, F, ReqBody>, T>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
F: FnOnce(S::Error) -> Result<Res, E>,
Res: IntoResponse,
{
let svc = HandleError::new(self.svc, f);
Layered::new(svc)
}
}
/// A handler [`Service`] that accepts requests based on a [`MethodFilter`] and
/// allows chaining additional handlers.
pub struct OnMethod<H, B, T, F> {
pub(crate) method: MethodFilter,
pub(crate) handler: H,
pub(crate) fallback: F,
pub(crate) _marker: PhantomData<fn() -> (B, T)>,
}
#[test]
fn traits() {
use crate::tests::*;
assert_send::<OnMethod<(), NotSendSync, NotSendSync, ()>>();
assert_sync::<OnMethod<(), NotSendSync, NotSendSync, ()>>();
}
impl<H, B, T, F> fmt::Debug for OnMethod<H, B, T, F>
where
T: fmt::Debug,
F: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OnMethod")
.field("method", &self.method)
.field("handler", &format_args!("{}", std::any::type_name::<H>()))
.field("fallback", &self.fallback)
.finish()
}
}
impl<H, B, T, F> Clone for OnMethod<H, B, T, F>
where
H: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
method: self.method,
handler: self.handler.clone(),
fallback: self.fallback.clone(),
_marker: PhantomData,
}
}
}
impl<H, B, T, F> Copy for OnMethod<H, B, T, F>
where
H: Copy,
F: Copy,
{
}
impl<H, B, T, F> OnMethod<H, B, T, F> {
/// Chain an additional handler that will accept all requests regardless of
/// its HTTP method.
///
/// See [`OnMethod::get`] for an example.
pub fn any<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::all(), handler)
}
/// Chain an additional handler that will only accept `CONNECT` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn connect<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::CONNECT, handler)
}
/// Chain an additional handler that will only accept `DELETE` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn delete<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::DELETE, handler)
}
/// Chain an additional handler that will only accept `GET` requests.
///
/// # Example
///
/// ```rust
/// use axum::{handler::post, Router};
///
/// async fn handler() {}
///
/// async fn other_handler() {}
///
/// // Requests to `GET /` will go to `handler` and `POST /` will go to
/// // `other_handler`.
/// let app = Router::new().route("/", post(handler).get(other_handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// Note that `get` routes will also be called for `HEAD` requests but will have
/// the response body removed. Make sure to add explicit `HEAD` routes
/// afterwards.
pub fn get<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::GET | MethodFilter::HEAD, handler)
}
/// Chain an additional handler that will only accept `HEAD` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn head<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::HEAD, handler)
}
/// Chain an additional handler that will only accept `OPTIONS` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn options<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::OPTIONS, handler)
}
/// Chain an additional handler that will only accept `PATCH` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn patch<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::PATCH, handler)
}
/// Chain an additional handler that will only accept `POST` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn post<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::POST, handler)
}
/// Chain an additional handler that will only accept `PUT` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn put<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::PUT, handler)
}
/// Chain an additional handler that will only accept `TRACE` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn trace<H2, T2>(self, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
self.on(MethodFilter::TRACE, handler)
}
/// Chain an additional handler that will accept requests matching the given
/// `MethodFilter`.
///
/// # Example
///
/// ```rust
/// use axum::{
/// handler::get,
/// Router,
/// routing::MethodFilter
/// };
///
/// async fn handler() {}
///
/// async fn other_handler() {}
///
/// // Requests to `GET /` will go to `handler` and `DELETE /` will go to
/// // `other_handler`
/// let app = Router::new().route("/", get(handler).on(MethodFilter::DELETE, other_handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn on<H2, T2>(self, method: MethodFilter, handler: H2) -> OnMethod<H2, B, T2, Self>
where
H2: Handler<B, T2>,
{
OnMethod {
method,
handler,
fallback: self,
_marker: PhantomData,
}
}
}
impl<H, B, T, F> Service<Request<B>> for OnMethod<H, B, T, F>
where
H: Handler<B, T>,
F: Service<Request<B>, Response = Response<BoxBody>, Error = Infallible> + Clone,
B: Send + 'static,
{
type Response = Response<BoxBody>;
type Error = Infallible;
type Future = future::OnMethodFuture<F, B>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<B>) -> Self::Future {
let req_method = req.method().clone();
let fut = if self.method.matches(req.method()) {
let fut = Handler::call(self.handler.clone(), req);
Either::A { inner: fut }
} else {
let fut = self.fallback.clone().oneshot(req);
Either::B { inner: fut }
};
future::OnMethodFuture {
inner: fut,
req_method,
}
}
}
<file_sep># Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
# Unreleased
- None.
# 0.2.4 (10. September, 2021)
- Document using `StreamExt::split` with `WebSocket` ([#291])
- Document adding middleware to multiple groups of routes ([#293])
[#291]: https://github.com/tokio-rs/axum/pull/291
[#293]: https://github.com/tokio-rs/axum/pull/293
# 0.2.3 (26. August, 2021)
- **fixed:** Fix accidental breaking change introduced by internal refactor.
`BoxRoute` used to be `Sync` but was accidental made `!Sync` ([#273](https://github.com/tokio-rs/axum/pull/273))
# 0.2.2 (26. August, 2021)
- **fixed:** Fix URI captures matching empty segments. This means requests with
URI `/` will no longer be matched by `/:key` ([#264](https://github.com/tokio-rs/axum/pull/264))
- **fixed:** Remove needless trait bounds from `Router::boxed` ([#269](https://github.com/tokio-rs/axum/pull/269))
# 0.2.1 (24. August, 2021)
- **added:** Add `Redirect::to` constructor ([#255](https://github.com/tokio-rs/axum/pull/255))
- **added:** Document how to implement `IntoResponse` for custom error type ([#258](https://github.com/tokio-rs/axum/pull/258))
# 0.2.0 (23. August, 2021)
- Overall:
- **fixed:** Overall compile time improvements. If you're having issues with compile time
please file an issue! ([#184](https://github.com/tokio-rs/axum/pull/184)) ([#198](https://github.com/tokio-rs/axum/pull/198)) ([#220](https://github.com/tokio-rs/axum/pull/220))
- **changed:** Remove `prelude`. Explicit imports are now required ([#195](https://github.com/tokio-rs/axum/pull/195))
- Routing:
- **added:** Add dedicated `Router` to replace the `RoutingDsl` trait ([#214](https://github.com/tokio-rs/axum/pull/214))
- **added:** Add `Router::or` for combining routes ([#108](https://github.com/tokio-rs/axum/pull/108))
- **fixed:** Support matching different HTTP methods for the same route that aren't defined
together. So `Router::new().route("/", get(...)).route("/", post(...))` now
accepts both `GET` and `POST`. Previously only `POST` would be accepted ([#224](https://github.com/tokio-rs/axum/pull/224))
- **fixed:** `get` routes will now also be called for `HEAD` requests but will always have
the response body removed ([#129](https://github.com/tokio-rs/axum/pull/129))
- **changed:** Replace `axum::route(...)` with `axum::Router::new().route(...)`. This means
there is now only one way to create a new router. Same goes for
`axum::routing::nest`. ([#215](https://github.com/tokio-rs/axum/pull/215))
- **changed:** Implement `routing::MethodFilter` via [`bitflags`](https://crates.io/crates/bitflags) ([#158](https://github.com/tokio-rs/axum/pull/158))
- **changed:** Move `handle_error` from `ServiceExt` to `service::OnMethod` ([#160](https://github.com/tokio-rs/axum/pull/160))
With these changes this app using 0.1:
```rust
use axum::{extract::Extension, prelude::*, routing::BoxRoute, AddExtensionLayer};
let app = route("/", get(|| async { "hi" }))
.nest("/api", api_routes())
.layer(AddExtensionLayer::new(state));
fn api_routes() -> BoxRoute<Body> {
route(
"/users",
post(|Extension(state): Extension<State>| async { "hi from nested" }),
)
.boxed()
}
```
Becomes this in 0.2:
```rust
use axum::{
extract::Extension,
handler::{get, post},
routing::BoxRoute,
Router,
};
let app = Router::new()
.route("/", get(|| async { "hi" }))
.nest("/api", api_routes());
fn api_routes() -> Router<BoxRoute> {
Router::new()
.route(
"/users",
post(|Extension(state): Extension<State>| async { "hi from nested" }),
)
.boxed()
}
```
- Extractors:
- **added:** Make `FromRequest` default to being generic over `body::Body` ([#146](https://github.com/tokio-rs/axum/pull/146))
- **added:** Implement `std::error::Error` for all rejections ([#153](https://github.com/tokio-rs/axum/pull/153))
- **added:** Add `OriginalUri` for extracting original request URI in nested services ([#197](https://github.com/tokio-rs/axum/pull/197))
- **added:** Implement `FromRequest` for `http::Extensions` ([#169](https://github.com/tokio-rs/axum/pull/169))
- **added:** Make `RequestParts::{new, try_into_request}` public so extractors can be used outside axum ([#194](https://github.com/tokio-rs/axum/pull/194))
- **added:** Implement `FromRequest` for `axum::body::Body` ([#241](https://github.com/tokio-rs/axum/pull/241))
- **changed:** Removed `extract::UrlParams` and `extract::UrlParamsMap`. Use `extract::Path` instead ([#154](https://github.com/tokio-rs/axum/pull/154))
- **changed:** `extractor_middleware` now requires `RequestBody: Default` ([#167](https://github.com/tokio-rs/axum/pull/167))
- **changed:** Convert `RequestAlreadyExtracted` to an enum with each possible error variant ([#167](https://github.com/tokio-rs/axum/pull/167))
- **changed:** `extract::BodyStream` is no longer generic over the request body ([#234](https://github.com/tokio-rs/axum/pull/234))
- **changed:** `extract::Body` has been renamed to `extract::RawBody` to avoid conflicting with `body::Body` ([#233](https://github.com/tokio-rs/axum/pull/233))
- **changed:** `RequestParts` changes ([#153](https://github.com/tokio-rs/axum/pull/153))
- `method` new returns an `&http::Method`
- `method_mut` new returns an `&mut http::Method`
- `take_method` has been removed
- `uri` new returns an `&http::Uri`
- `uri_mut` new returns an `&mut http::Uri`
- `take_uri` has been removed
- **changed:** Remove several rejection types that were no longer used ([#153](https://github.com/tokio-rs/axum/pull/153)) ([#154](https://github.com/tokio-rs/axum/pull/154))
- Responses:
- **added:** Add `Headers` for easily customizing headers on a response ([#193](https://github.com/tokio-rs/axum/pull/193))
- **added:** Add `Redirect` response ([#192](https://github.com/tokio-rs/axum/pull/192))
- **added:** Add `body::StreamBody` for easily responding with a stream of byte chunks ([#237](https://github.com/tokio-rs/axum/pull/237))
- **changed:** Add associated `Body` and `BodyError` types to `IntoResponse`. This is
required for returning responses with bodies other than `hyper::Body` from
handlers. See the docs for advice on how to implement `IntoResponse` ([#86](https://github.com/tokio-rs/axum/pull/86))
- **changed:** `tower::util::Either` no longer implements `IntoResponse` ([#229](https://github.com/tokio-rs/axum/pull/229))
This `IntoResponse` from 0.1:
```rust
use axum::{http::Response, prelude::*, response::IntoResponse};
struct MyResponse;
impl IntoResponse for MyResponse {
fn into_response(self) -> Response<Body> {
Response::new(Body::empty())
}
}
```
Becomes this in 0.2:
```rust
use axum::{body::Body, http::Response, response::IntoResponse};
struct MyResponse;
impl IntoResponse for MyResponse {
type Body = Body;
type BodyError = <Self::Body as axum::body::HttpBody>::Error;
fn into_response(self) -> Response<Self::Body> {
Response::new(Body::empty())
}
}
```
- SSE:
- **added:** Add `response::sse::Sse`. This implements SSE using a response rather than a service ([#98](https://github.com/tokio-rs/axum/pull/98))
- **changed:** Remove `axum::sse`. Its been replaced by `axum::response::sse` ([#98](https://github.com/tokio-rs/axum/pull/98))
Handler using SSE in 0.1:
```rust
use axum::{
prelude::*,
sse::{sse, Event},
};
use std::convert::Infallible;
let app = route(
"/",
sse(|| async {
let stream = futures::stream::iter(vec![Ok::<_, Infallible>(
Event::default().data("hi there!"),
)]);
Ok::<_, Infallible>(stream)
}),
);
```
Becomes this in 0.2:
```rust
use axum::{
handler::get,
response::sse::{Event, Sse},
Router,
};
use std::convert::Infallible;
let app = Router::new().route(
"/",
get(|| async {
let stream = futures::stream::iter(vec![Ok::<_, Infallible>(
Event::default().data("hi there!"),
)]);
Sse::new(stream)
}),
);
```
- WebSockets:
- **changed:** Change WebSocket API to use an extractor plus a response ([#121](https://github.com/tokio-rs/axum/pull/121))
- **changed:** Make WebSocket `Message` an enum ([#116](https://github.com/tokio-rs/axum/pull/116))
- **changed:** `WebSocket` now uses `Error` as its error type ([#150](https://github.com/tokio-rs/axum/pull/150))
Handler using WebSockets in 0.1:
```rust
use axum::{
prelude::*,
ws::{ws, WebSocket},
};
let app = route(
"/",
ws(|socket: WebSocket| async move {
// do stuff with socket
}),
);
```
Becomes this in 0.2:
```rust
use axum::{
extract::ws::{WebSocket, WebSocketUpgrade},
handler::get,
Router,
};
let app = Router::new().route(
"/",
get(|ws: WebSocketUpgrade| async move {
ws.on_upgrade(|socket: WebSocket| async move {
// do stuff with socket
})
}),
);
```
- Misc
- **added:** Add default feature `tower-log` which exposes `tower`'s `log` feature. ([#218](https://github.com/tokio-rs/axum/pull/218))
- **changed:** Replace `body::BoxStdError` with `axum::Error`, which supports downcasting ([#150](https://github.com/tokio-rs/axum/pull/150))
- **changed:** `EmptyRouter` now requires the response body to implement `Send + Sync + 'static'` ([#108](https://github.com/tokio-rs/axum/pull/108))
- **changed:** `Router::check_infallible` now returns a `CheckInfallible` service. This
is to improve compile times ([#198](https://github.com/tokio-rs/axum/pull/198))
- **changed:** `Router::into_make_service` now returns `routing::IntoMakeService` rather than
`tower::make::Shared` ([#229](https://github.com/tokio-rs/axum/pull/229))
- **changed:** All usage of `tower::BoxError` has been replaced with `axum::BoxError` ([#229](https://github.com/tokio-rs/axum/pull/229))
- **changed:** Several response future types have been moved into dedicated
`future` modules ([#133](https://github.com/tokio-rs/axum/pull/133))
- **changed:** `EmptyRouter`, `ExtractorMiddleware`, `ExtractorMiddlewareLayer`,
and `QueryStringMissing` no longer implement `Copy` ([#132](https://github.com/tokio-rs/axum/pull/132))
- **changed:** `service::OnMethod`, `handler::OnMethod`, and `routing::Nested` have new response future types ([#157](https://github.com/tokio-rs/axum/pull/157))
# 0.1.3 (06. August, 2021)
- Fix stripping prefix when nesting services at `/` ([#91](https://github.com/tokio-rs/axum/pull/91))
- Add support for WebSocket protocol negotiation ([#83](https://github.com/tokio-rs/axum/pull/83))
- Use `pin-project-lite` instead of `pin-project` ([#95](https://github.com/tokio-rs/axum/pull/95))
- Re-export `http` crate and `hyper::Server` ([#110](https://github.com/tokio-rs/axum/pull/110))
- Fix `Query` and `Form` extractors giving bad request error when query string is empty. ([#117](https://github.com/tokio-rs/axum/pull/117))
- Add `Path` extractor. ([#124](https://github.com/tokio-rs/axum/pull/124))
- Fixed the implementation of `IntoResponse` of `(HeaderMap, T)` and `(StatusCode, HeaderMap, T)` would ignore headers from `T` ([#137](https://github.com/tokio-rs/axum/pull/137))
- Deprecate `extract::UrlParams` and `extract::UrlParamsMap`. Use `extract::Path` instead ([#138](https://github.com/tokio-rs/axum/pull/138))
# 0.1.2 (01. August, 2021)
- Implement `Stream` for `WebSocket` ([#52](https://github.com/tokio-rs/axum/pull/52))
- Implement `Sink` for `WebSocket` ([#52](https://github.com/tokio-rs/axum/pull/52))
- Implement `Deref` most extractors ([#56](https://github.com/tokio-rs/axum/pull/56))
- Return `405 Method Not Allowed` for unsupported method for route ([#63](https://github.com/tokio-rs/axum/pull/63))
- Add extractor for remote connection info ([#55](https://github.com/tokio-rs/axum/pull/55))
- Improve error message of `MissingExtension` rejections ([#72](https://github.com/tokio-rs/axum/pull/72))
- Improve documentation for routing ([#71](https://github.com/tokio-rs/axum/pull/71))
- Clarify required response body type when routing to `tower::Service`s ([#69](https://github.com/tokio-rs/axum/pull/69))
- Add `axum::body::box_body` to converting an `http_body::Body` to `axum::body::BoxBody` ([#69](https://github.com/tokio-rs/axum/pull/69))
- Add `axum::sse` for Server-Sent Events ([#75](https://github.com/tokio-rs/axum/pull/75))
- Mention required dependencies in docs ([#77](https://github.com/tokio-rs/axum/pull/77))
- Fix WebSockets failing on Firefox ([#76](https://github.com/tokio-rs/axum/pull/76))
# 0.1.1 (30. July, 2021)
- Misc readme fixes.
# 0.1.0 (30. July, 2021)
- Initial release.
<file_sep>//! Extractor for getting connection information from a client.
//!
//! See [`Router::into_make_service_with_connect_info`] for more details.
//!
//! [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
use super::{Extension, FromRequest, RequestParts};
use async_trait::async_trait;
use hyper::server::conn::AddrStream;
use std::future::ready;
use std::{
convert::Infallible,
fmt,
marker::PhantomData,
net::SocketAddr,
task::{Context, Poll},
};
use tower_http::add_extension::AddExtension;
use tower_service::Service;
/// A [`MakeService`] created from a router.
///
/// See [`Router::into_make_service_with_connect_info`] for more details.
///
/// [`MakeService`]: tower::make::MakeService
/// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
pub struct IntoMakeServiceWithConnectInfo<S, C> {
svc: S,
_connect_info: PhantomData<fn() -> C>,
}
#[test]
fn traits() {
use crate::tests::*;
assert_send::<IntoMakeServiceWithConnectInfo<(), NotSendSync>>();
assert_sync::<IntoMakeServiceWithConnectInfo<(), NotSendSync>>();
}
impl<S, C> IntoMakeServiceWithConnectInfo<S, C> {
pub(crate) fn new(svc: S) -> Self {
Self {
svc,
_connect_info: PhantomData,
}
}
}
impl<S, C> fmt::Debug for IntoMakeServiceWithConnectInfo<S, C>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IntoMakeServiceWithConnectInfo")
.field("svc", &self.svc)
.finish()
}
}
/// Trait that connected IO resources implement and use to produce information
/// about the connection.
///
/// The goal for this trait is to allow users to implement custom IO types that
/// can still provide the same connection metadata.
///
/// See [`Router::into_make_service_with_connect_info`] for more details.
///
/// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
pub trait Connected<T> {
/// The connection information type the IO resources generates.
type ConnectInfo: Clone + Send + Sync + 'static;
/// Create type holding information about the connection.
fn connect_info(target: T) -> Self::ConnectInfo;
}
impl Connected<&AddrStream> for SocketAddr {
type ConnectInfo = SocketAddr;
fn connect_info(target: &AddrStream) -> Self::ConnectInfo {
target.remote_addr()
}
}
impl<S, C, T> Service<T> for IntoMakeServiceWithConnectInfo<S, C>
where
S: Clone,
C: Connected<T>,
{
type Response = AddExtension<S, ConnectInfo<C::ConnectInfo>>;
type Error = Infallible;
type Future = ResponseFuture<Self::Response>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, target: T) -> Self::Future {
let connect_info = ConnectInfo(C::connect_info(target));
let svc = AddExtension::new(self.svc.clone(), connect_info);
ResponseFuture {
future: ready(Ok(svc)),
}
}
}
opaque_future! {
/// Response future for [`IntoMakeServiceWithConnectInfo`].
pub type ResponseFuture<T> =
std::future::Ready<Result<T, Infallible>>;
}
/// Extractor for getting connection information produced by a [`Connected`].
///
/// Note this extractor requires you to use
/// [`Router::into_make_service_with_connect_info`] to run your app
/// otherwise it will fail at runtime.
///
/// See [`Router::into_make_service_with_connect_info`] for more details.
///
/// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
#[derive(Clone, Copy, Debug)]
pub struct ConnectInfo<T>(pub T);
#[async_trait]
impl<B, T> FromRequest<B> for ConnectInfo<T>
where
B: Send,
T: Clone + Send + Sync + 'static,
{
type Rejection = <Extension<Self> as FromRequest<B>>::Rejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let Extension(connect_info) = Extension::<Self>::from_request(req).await?;
Ok(connect_info)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Server;
use crate::{handler::get, Router};
use std::net::{SocketAddr, TcpListener};
#[tokio::test]
async fn socket_addr() {
async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
format!("{}", addr)
}
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
let app = Router::new().route("/", get(handler));
let server = Server::from_tcp(listener)
.unwrap()
.serve(app.into_make_service_with_connect_info::<SocketAddr, _>());
tx.send(()).unwrap();
server.await.expect("server error");
});
rx.await.unwrap();
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
let body = res.text().await.unwrap();
assert!(body.starts_with("127.0.0.1:"));
}
#[tokio::test]
async fn custom() {
#[derive(Clone, Debug)]
struct MyConnectInfo {
value: &'static str,
}
impl Connected<&AddrStream> for MyConnectInfo {
type ConnectInfo = Self;
fn connect_info(_target: &AddrStream) -> Self::ConnectInfo {
Self {
value: "it worked!",
}
}
}
async fn handler(ConnectInfo(addr): ConnectInfo<MyConnectInfo>) -> &'static str {
addr.value
}
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
let app = Router::new().route("/", get(handler));
let server = Server::from_tcp(listener)
.unwrap()
.serve(app.into_make_service_with_connect_info::<MyConnectInfo, _>());
tx.send(()).unwrap();
server.await.expect("server error");
});
rx.await.unwrap();
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "it worked!");
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-global-404-handler
//! ```
use axum::{
handler::{get, Handler},
http::StatusCode,
response::{Html, IntoResponse},
Router,
};
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_global_404_handler=debug")
}
tracing_subscriber::fmt::init();
// build our application with a route
let app = Router::new().route("/", get(handler));
// make sure this is added as the very last thing
let app = app.or(handler_404.into_service());
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}
async fn handler_404() -> impl IntoResponse {
(StatusCode::NOT_FOUND, "nothing to see here")
}
<file_sep>[advisories]
vulnerability = "deny"
unmaintained = "warn"
notice = "warn"
ignore = []
[licenses]
unlicensed = "deny"
allow = []
deny = []
copyleft = "warn"
allow-osi-fsf-free = "either"
confidence-threshold = 0.8
exceptions = [
# ring uses code from multiple libraries but all with permissive licenses
# https://tldrlegal.com/license/openssl-license-(openssl)
{ allow = ["ISC", "MIT", "OpenSSL"], name = "ring" },
]
[[licenses.clarify]]
name = "ring"
# SPDX considers OpenSSL to encompass both the OpenSSL and SSLeay licenses
# https://spdx.org/licenses/OpenSSL.html
# ISC - Both BoringSSL and ring use this for their new files
# MIT - "Files in third_party/ have their own licenses, as described therein. The MIT
# license, for third_party/fiat, which, unlike other third_party directories, is
# compiled into non-test libraries, is included below."
# OpenSSL - Obviously
expression = "ISC AND MIT AND OpenSSL"
license-files = [
{ path = "LICENSE", hash = 0xbd0eed23 },
]
[bans]
multiple-versions = "deny"
highlight = "all"
skip-tree = []
skip = [
# rustls uses old version (dev dep)
{ name = "spin", version = "=0.5.2" },
# tokio-postgres uses old version (dev dep)
{ name = "hmac", version = "=0.10.1" },
{ name = "crypto-mac" },
# async-session uses old version (dev dep)
{ name = "cfg-if", version = "=0.1.10" },
# async-graphql has a few outdated deps (dev dep)
{ name = "sha-1", version = "=0.8.2" },
{ name = "opaque-debug", version = "=0.2.3" },
{ name = "generic-array", version = "=0.12.4" },
{ name = "digest", version = "=0.8.1" },
{ name = "block-buffer", version = "=0.7.3" },
]
[sources]
unknown-registry = "warn"
unknown-git = "warn"
allow-git = []
<file_sep>use super::IntoResponse;
use crate::{
body::{box_body, BoxBody},
BoxError,
};
use bytes::Bytes;
use http::header::{HeaderMap, HeaderName, HeaderValue};
use http::{Response, StatusCode};
use http_body::{Body, Full};
use std::{convert::TryInto, fmt};
use tower::util::Either;
/// A response with headers.
///
/// # Example
///
/// ```rust
/// use axum::{
/// Router,
/// response::{IntoResponse, Headers},
/// handler::get,
/// };
/// use http::header::{HeaderName, HeaderValue};
///
/// // It works with any `IntoIterator<Item = (Key, Value)>` where `Key` can be
/// // turned into a `HeaderName` and `Value` can be turned into a `HeaderValue`
/// //
/// // Such as `Vec<(HeaderName, HeaderValue)>`
/// async fn just_headers() -> impl IntoResponse {
/// Headers(vec![
/// (HeaderName::from_static("X-Foo"), HeaderValue::from_static("foo")),
/// ])
/// }
///
/// // Or `Vec<(&str, &str)>`
/// async fn from_strings() -> impl IntoResponse {
/// Headers(vec![("X-Foo", "foo")])
/// }
///
/// // Or `[(&str, &str)]` if you're on Rust 1.53+
///
/// let app = Router::new()
/// .route("/just-headers", get(just_headers))
/// .route("/from-strings", get(from_strings));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// If a conversion to `HeaderName` or `HeaderValue` fails a `500 Internal
/// Server Error` response will be returned.
///
/// You can also return `(Headers, impl IntoResponse)` to customize the headers
/// of a response, or `(StatusCode, Headeres, impl IntoResponse)` to customize
/// the status code and headers.
#[derive(Clone, Copy, Debug)]
pub struct Headers<H>(pub H);
impl<H> Headers<H> {
fn try_into_header_map<K, V>(self) -> Result<HeaderMap, Response<Full<Bytes>>>
where
H: IntoIterator<Item = (K, V)>,
K: TryInto<HeaderName>,
K::Error: fmt::Display,
V: TryInto<HeaderValue>,
V::Error: fmt::Display,
{
self.0
.into_iter()
.map(|(key, value)| {
let key = key.try_into().map_err(Either::A)?;
let value = value.try_into().map_err(Either::B)?;
Ok((key, value))
})
.collect::<Result<_, _>>()
.map_err(|err| {
let err = match err {
Either::A(err) => err.to_string(),
Either::B(err) => err.to_string(),
};
let body = Full::new(Bytes::copy_from_slice(err.as_bytes()));
let mut res = Response::new(body);
*res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
res
})
}
}
impl<H, K, V> IntoResponse for Headers<H>
where
H: IntoIterator<Item = (K, V)>,
K: TryInto<HeaderName>,
K::Error: fmt::Display,
V: TryInto<HeaderValue>,
V::Error: fmt::Display,
{
type Body = Full<Bytes>;
type BodyError = <Self::Body as Body>::Error;
fn into_response(self) -> http::Response<Self::Body> {
let headers = self.try_into_header_map();
match headers {
Ok(headers) => {
let mut res = Response::new(Full::new(Bytes::new()));
*res.headers_mut() = headers;
res
}
Err(err) => err,
}
}
}
impl<H, T, K, V> IntoResponse for (Headers<H>, T)
where
T: IntoResponse,
T::Body: Body<Data = Bytes> + Send + Sync + 'static,
<T::Body as Body>::Error: Into<BoxError>,
H: IntoIterator<Item = (K, V)>,
K: TryInto<HeaderName>,
K::Error: fmt::Display,
V: TryInto<HeaderValue>,
V::Error: fmt::Display,
{
type Body = BoxBody;
type BodyError = <Self::Body as Body>::Error;
// this boxing could be improved with a EitherBody but thats
// an issue for another time
fn into_response(self) -> Response<Self::Body> {
let headers = match self.0.try_into_header_map() {
Ok(headers) => headers,
Err(res) => return res.map(box_body),
};
(headers, self.1).into_response().map(box_body)
}
}
impl<H, T, K, V> IntoResponse for (StatusCode, Headers<H>, T)
where
T: IntoResponse,
T::Body: Body<Data = Bytes> + Send + Sync + 'static,
<T::Body as Body>::Error: Into<BoxError>,
H: IntoIterator<Item = (K, V)>,
K: TryInto<HeaderName>,
K::Error: fmt::Display,
V: TryInto<HeaderValue>,
V::Error: fmt::Display,
{
type Body = BoxBody;
type BodyError = <Self::Body as Body>::Error;
fn into_response(self) -> Response<Self::Body> {
let headers = match self.1.try_into_header_map() {
Ok(headers) => headers,
Err(res) => return res.map(box_body),
};
(self.0, headers, self.2).into_response().map(box_body)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures_util::FutureExt;
use http::header::USER_AGENT;
#[test]
fn vec_of_header_name_and_value() {
let res = Headers(vec![(USER_AGENT, HeaderValue::from_static("axum"))]).into_response();
assert_eq!(res.headers()["user-agent"], "axum");
assert_eq!(res.status(), StatusCode::OK);
}
#[test]
fn vec_of_strings() {
let res = Headers(vec![("user-agent", "axum")]).into_response();
assert_eq!(res.headers()["user-agent"], "axum");
}
#[test]
fn with_body() {
let res = (Headers(vec![("user-agent", "axum")]), "foo").into_response();
assert_eq!(res.headers()["user-agent"], "axum");
let body = hyper::body::to_bytes(res.into_body())
.now_or_never()
.unwrap()
.unwrap();
assert_eq!(&body[..], b"foo");
}
#[test]
fn with_status_and_body() {
let res = (
StatusCode::NOT_FOUND,
Headers(vec![("user-agent", "axum")]),
"foo",
)
.into_response();
assert_eq!(res.headers()["user-agent"], "axum");
assert_eq!(res.status(), StatusCode::NOT_FOUND);
let body = hyper::body::to_bytes(res.into_body())
.now_or_never()
.unwrap()
.unwrap();
assert_eq!(&body[..], b"foo");
}
#[test]
fn invalid_header_name() {
let bytes: &[u8] = &[0, 159, 146, 150]; // invalid utf-8
let res = Headers(vec![(bytes, "axum")]).into_response();
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test]
fn invalid_header_value() {
let bytes: &[u8] = &[0, 159, 146, 150]; // invalid utf-8
let res = Headers(vec![("user-agent", bytes)]).into_response();
assert!(res.headers().get("user-agent").is_none());
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
}
<file_sep>//! Simple in-memory key/value store showing features of axum.
//!
//! Run with:
//!
//! ```not_rust
//! cargo run -p example-key-value-store
//! ```
use axum::{
body::Bytes,
extract::{ContentLengthLimit, Extension, Path},
handler::{delete, get, Handler},
http::StatusCode,
response::IntoResponse,
routing::BoxRoute,
Router,
};
use std::{
borrow::Cow,
collections::HashMap,
convert::Infallible,
net::SocketAddr,
sync::{Arc, RwLock},
time::Duration,
};
use tower::{BoxError, ServiceBuilder};
use tower_http::{
add_extension::AddExtensionLayer, auth::RequireAuthorizationLayer,
compression::CompressionLayer, trace::TraceLayer,
};
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_key_value_store=debug,tower_http=debug")
}
tracing_subscriber::fmt::init();
// Build our application by composing routes
let app = Router::new()
.route(
"/:key",
// Add compression to `kv_get`
get(kv_get.layer(CompressionLayer::new()))
// But don't compress `kv_set`
.post(kv_set),
)
.route("/keys", get(list_keys))
// Nest our admin routes under `/admin`
.nest("/admin", admin_routes())
// Add middleware to all routes
.layer(
ServiceBuilder::new()
.load_shed()
.concurrency_limit(1024)
.timeout(Duration::from_secs(10))
.layer(TraceLayer::new_for_http())
.layer(AddExtensionLayer::new(SharedState::default()))
.into_inner(),
)
// Handle errors from middleware
.handle_error(handle_error)
.check_infallible();
// Run our app with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
type SharedState = Arc<RwLock<State>>;
#[derive(Default)]
struct State {
db: HashMap<String, Bytes>,
}
async fn kv_get(
Path(key): Path<String>,
Extension(state): Extension<SharedState>,
) -> Result<Bytes, StatusCode> {
let db = &state.read().unwrap().db;
if let Some(value) = db.get(&key) {
Ok(value.clone())
} else {
Err(StatusCode::NOT_FOUND)
}
}
async fn kv_set(
Path(key): Path<String>,
ContentLengthLimit(bytes): ContentLengthLimit<Bytes, { 1024 * 5_000 }>, // ~5mb
Extension(state): Extension<SharedState>,
) {
state.write().unwrap().db.insert(key, bytes);
}
async fn list_keys(Extension(state): Extension<SharedState>) -> String {
let db = &state.read().unwrap().db;
db.keys()
.map(|key| key.to_string())
.collect::<Vec<String>>()
.join("\n")
}
fn admin_routes() -> Router<BoxRoute> {
async fn delete_all_keys(Extension(state): Extension<SharedState>) {
state.write().unwrap().db.clear();
}
async fn remove_key(Path(key): Path<String>, Extension(state): Extension<SharedState>) {
state.write().unwrap().db.remove(&key);
}
Router::new()
.route("/keys", delete(delete_all_keys))
.route("/key/:key", delete(remove_key))
// Require bearer auth for all admin routes
.layer(RequireAuthorizationLayer::bearer("secret-token"))
.boxed()
}
fn handle_error(error: BoxError) -> Result<impl IntoResponse, Infallible> {
if error.is::<tower::timeout::error::Elapsed>() {
return Ok((StatusCode::REQUEST_TIMEOUT, Cow::from("request timed out")));
}
if error.is::<tower::load_shed::error::Overloaded>() {
return Ok((
StatusCode::SERVICE_UNAVAILABLE,
Cow::from("service is overloaded, try again later"),
));
}
Ok((
StatusCode::INTERNAL_SERVER_ERROR,
Cow::from(format!("Unhandled internal error: {}", error)),
))
}
<file_sep>use super::*;
use crate::body::box_body;
use std::collections::HashMap;
#[tokio::test]
async fn nesting_apps() {
let api_routes = Router::new()
.route(
"/users",
get(|| async { "users#index" }).post(|| async { "users#create" }),
)
.route(
"/users/:id",
get(
|params: extract::Path<HashMap<String, String>>| async move {
format!(
"{}: users#show ({})",
params.get("version").unwrap(),
params.get("id").unwrap()
)
},
),
)
.route(
"/games/:id",
get(
|params: extract::Path<HashMap<String, String>>| async move {
format!(
"{}: games#show ({})",
params.get("version").unwrap(),
params.get("id").unwrap()
)
},
),
);
let app = Router::new()
.route("/", get(|| async { "hi" }))
.nest("/:version/api", api_routes);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "hi");
let res = client
.get(format!("http://{}/v0/api/users", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "users#index");
let res = client
.get(format!("http://{}/v0/api/users/123", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "v0: users#show (123)");
let res = client
.get(format!("http://{}/v0/api/games/123", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "v0: games#show (123)");
}
#[tokio::test]
async fn wrong_method_nest() {
let nested_app = Router::new().route("/", get(|| async {}));
let app = Router::new().nest("/", nested_app);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post(format!("http://{}", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
let res = client
.patch(format!("http://{}/foo", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn nesting_at_root() {
let app = Router::new().nest("/", get(|uri: Uri| async move { uri.to_string() }));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client.get(format!("http://{}", addr)).send().await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "/");
let res = client
.get(format!("http://{}/foo", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "/foo");
let res = client
.get(format!("http://{}/foo/bar", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "/foo/bar");
}
#[tokio::test]
async fn nested_url_extractor() {
let app = Router::new().nest(
"/foo",
Router::new().nest(
"/bar",
Router::new()
.route("/baz", get(|uri: Uri| async move { uri.to_string() }))
.route(
"/qux",
get(|req: Request<Body>| async move { req.uri().to_string() }),
),
),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/foo/bar/baz", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "/baz");
let res = client
.get(format!("http://{}/foo/bar/qux", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "/qux");
}
#[tokio::test]
async fn nested_url_original_extractor() {
let app = Router::new().nest(
"/foo",
Router::new().nest(
"/bar",
Router::new().route(
"/baz",
get(|uri: extract::OriginalUri| async move { uri.0.to_string() }),
),
),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/foo/bar/baz", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "/foo/bar/baz");
}
#[tokio::test]
async fn nested_service_sees_stripped_uri() {
let app = Router::new().nest(
"/foo",
Router::new().nest(
"/bar",
Router::new().route(
"/baz",
service_fn(|req: Request<Body>| async move {
let body = box_body(Body::from(req.uri().to_string()));
Ok::<_, Infallible>(Response::new(body))
}),
),
),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/foo/bar/baz", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await.unwrap(), "/baz");
}
#[tokio::test]
async fn nest_static_file_server() {
let app = Router::new().nest(
"/static",
service::get(tower_http::services::ServeDir::new(".")).handle_error(|error| {
Ok::<_, Infallible>((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
))
}),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/static/README.md", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
<file_sep># Patch dependencies to run all tests against versions of the crate in the
# repository.
[patch.crates-io]
axum = { path = "axum" }
<file_sep>[package]
name = "axum"
version = "0.2.4"
authors = ["<NAME> <<EMAIL>>"]
categories = ["asynchronous", "network-programming", "web-programming"]
description = "Web framework that focuses on ergonomics and modularity"
edition = "2018"
homepage = "https://github.com/tokio-rs/axum"
keywords = ["http", "web", "framework"]
license = "MIT"
readme = "README.md"
repository = "https://github.com/tokio-rs/axum"
[workspace]
members = ["examples/*"]
[features]
default = ["tower-log"]
http2 = ["hyper/http2"]
multipart = ["multer", "mime"]
tower-log = ["tower/log"]
ws = ["tokio-tungstenite", "sha-1", "base64"]
[dependencies]
async-trait = "0.1"
bitflags = "1.0"
bytes = "1.0"
futures-util = { version = "0.3", default-features = false, features = ["alloc"] }
http = "0.2"
http-body = "0.4.3"
hyper = { version = "0.14", features = ["server", "tcp", "http1", "stream"] }
pin-project-lite = "0.2.7"
regex = "1.5"
serde = "1.0"
serde_json = "1.0"
serde_urlencoded = "0.7"
tokio = { version = "1", features = ["time"] }
tokio-util = "0.6"
tower = { version = "0.4", default-features = false, features = ["util", "buffer", "make"] }
tower-service = "0.3"
tower-layer = "0.3"
tower-http = { version = "0.1", features = ["add-extension", "map-response-body"] }
sync_wrapper = "0.1.1"
# optional dependencies
tokio-tungstenite = { optional = true, version = "0.15" }
sha-1 = { optional = true, version = "0.9.6" }
base64 = { optional = true, version = "0.13" }
headers = { optional = true, version = "0.3" }
multer = { optional = true, version = "2.0.0" }
mime = { optional = true, version = "0.3" }
[dev-dependencies]
futures = "0.3"
reqwest = { version = "0.11", features = ["json", "stream"] }
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.6.1", features = ["macros", "rt", "rt-multi-thread", "net"] }
uuid = { version = "0.8", features = ["serde", "v4"] }
tokio-stream = "0.1"
[dev-dependencies.tower]
package = "tower"
version = "0.4"
features = [
"util",
"timeout",
"limit",
"load-shed",
"steer",
"filter",
]
[dev-dependencies.tower-http]
version = "0.1"
features = ["full"]
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[package.metadata.playground]
features = ["ws", "multipart", "headers"]
<file_sep>//! Example OAuth (Discord) implementation.
//!
//! Run with
//!
//! ```not_rust
//! CLIENT_ID=123 CLIENT_SECRET=secret cargo run -p example-oauth
//! ```
use async_session::{MemoryStore, Session, SessionStore};
use axum::{
async_trait,
body::{Bytes, Empty},
extract::{Extension, FromRequest, Query, RequestParts, TypedHeader},
handler::get,
http::{header::SET_COOKIE, HeaderMap, Response},
response::{IntoResponse, Redirect},
AddExtensionLayer, Router,
};
use oauth2::{
basic::BasicClient, reqwest::async_http_client, AuthUrl, AuthorizationCode, ClientId,
ClientSecret, CsrfToken, RedirectUrl, Scope, TokenResponse, TokenUrl,
};
use serde::{Deserialize, Serialize};
use std::{env, net::SocketAddr};
// Quick instructions:
// 1) create a new application at https://discord.com/developers/applications
// 2) visit the OAuth2 tab to get your CLIENT_ID and CLIENT_SECRET
// 3) add a new redirect URI (For this example: http://localhost:3000/auth/authorized)
// 4) AUTH_URL and TOKEN_URL may stay the same for discord.
// More information: https://discord.com/developers/applications/792730475856527411/oauth2
static COOKIE_NAME: &str = "SESSION";
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_oauth=debug")
}
tracing_subscriber::fmt::init();
// `MemoryStore` just used as an example. Don't use this in production.
let store = MemoryStore::new();
let oauth_client = oauth_client();
let app = Router::new()
.route("/", get(index))
.route("/auth/discord", get(discord_auth))
.route("/auth/authorized", get(login_authorized))
.route("/protected", get(protected))
.route("/logout", get(logout))
.layer(AddExtensionLayer::new(store))
.layer(AddExtensionLayer::new(oauth_client));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
fn oauth_client() -> BasicClient {
// Environment variables (* = required):
// *"CLIENT_ID" "123456789123456789";
// *"CLIENT_SECRET" "rAn60Mch4ra-CTErsSf-r04utHcLienT";
// "REDIRECT_URL" "http://127.0.0.1:3000/auth/authorized";
// "AUTH_URL" "https://discord.com/api/oauth2/authorize?response_type=code";
// "TOKEN_URL" "https://discord.com/api/oauth2/token";
let client_id = env::var("CLIENT_ID").expect("Missing CLIENT_ID!");
let client_secret = env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET!");
let redirect_url = env::var("REDIRECT_URL")
.unwrap_or_else(|_| "http://127.0.0.1:3000/auth/authorized".to_string());
let auth_url = env::var("AUTH_URL").unwrap_or_else(|_| {
"https://discord.com/api/oauth2/authorize?response_type=code".to_string()
});
let token_url = env::var("TOKEN_URL")
.unwrap_or_else(|_| "https://discord.com/api/oauth2/token".to_string());
BasicClient::new(
ClientId::new(client_id),
Some(ClientSecret::new(client_secret)),
AuthUrl::new(auth_url).unwrap(),
Some(TokenUrl::new(token_url).unwrap()),
)
.set_redirect_uri(RedirectUrl::new(redirect_url).unwrap())
}
// The user data we'll get back from Discord.
// https://discord.com/developers/docs/resources/user#user-object-user-structure
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: String,
avatar: Option<String>,
username: String,
discriminator: String,
}
// Session is optional
async fn index(user: Option<User>) -> impl IntoResponse {
match user {
Some(u) => format!(
"Hey {}! You're logged in!\nYou may now access `/protected`.\nLog out with `/logout`.",
u.username
),
None => "You're not logged in.\nVisit `/auth/discord` to do so.".to_string(),
}
}
async fn discord_auth(Extension(client): Extension<BasicClient>) -> impl IntoResponse {
let (auth_url, _csrf_token) = client
.authorize_url(CsrfToken::new_random)
.add_scope(Scope::new("identify".to_string()))
.url();
// Redirect to Discord's oauth service
Redirect::found(auth_url.to_string().parse().unwrap())
}
// Valid user session required. If there is none, redirect to the auth page
async fn protected(user: User) -> impl IntoResponse {
format!(
"Welcome to the protected area :)\nHere's your info:\n{:?}",
user
)
}
async fn logout(
Extension(store): Extension<MemoryStore>,
TypedHeader(cookies): TypedHeader<headers::Cookie>,
) -> impl IntoResponse {
let cookie = cookies.get(COOKIE_NAME).unwrap();
let session = match store.load_session(cookie.to_string()).await.unwrap() {
Some(s) => s,
// No session active, just redirect
None => return Redirect::found("/".parse().unwrap()),
};
store.destroy_session(session).await.unwrap();
Redirect::found("/".parse().unwrap())
}
#[derive(Debug, Deserialize)]
struct AuthRequest {
code: String,
state: String,
}
async fn login_authorized(
Query(query): Query<AuthRequest>,
Extension(store): Extension<MemoryStore>,
Extension(oauth_client): Extension<BasicClient>,
) -> impl IntoResponse {
// Get an auth token
let token = oauth_client
.exchange_code(AuthorizationCode::new(query.code.clone()))
.request_async(async_http_client)
.await
.unwrap();
// Fetch user data from discord
let client = reqwest::Client::new();
let user_data: User = client
// https://discord.com/developers/docs/resources/user#get-current-user
.get("https://discordapp.com/api/users/@me")
.bearer_auth(token.access_token().secret())
.send()
.await
.unwrap()
.json::<User>()
.await
.unwrap();
// Create a new session filled with user data
let mut session = Session::new();
session.insert("user", &user_data).unwrap();
// Store session and get corresponding cookie
let cookie = store.store_session(session).await.unwrap().unwrap();
// Build the cookie
let cookie = format!("{}={}; SameSite=Lax; Path=/", COOKIE_NAME, cookie);
// Set cookie
let mut headers = HeaderMap::new();
headers.insert(SET_COOKIE, cookie.parse().unwrap());
(headers, Redirect::found("/".parse().unwrap()))
}
struct AuthRedirect;
impl IntoResponse for AuthRedirect {
type Body = Empty<Bytes>;
type BodyError = <Self::Body as axum::body::HttpBody>::Error;
fn into_response(self) -> Response<Self::Body> {
Redirect::found("/auth/discord".parse().unwrap()).into_response()
}
}
#[async_trait]
impl<B> FromRequest<B> for User
where
B: Send,
{
// If anything goes wrong or no session is found, redirect to the auth page
type Rejection = AuthRedirect;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let Extension(store) = Extension::<MemoryStore>::from_request(req)
.await
.expect("`MemoryStore` extension is missing");
let cookies = TypedHeader::<headers::Cookie>::from_request(req)
.await
.expect("could not get cookies");
let session_cookie = cookies.get(COOKIE_NAME).ok_or(AuthRedirect)?;
let session = store
.load_session(session_cookie.to_string())
.await
.unwrap()
.ok_or(AuthRedirect)?;
let user = session.get::<User>("user").ok_or(AuthRedirect)?;
Ok(user)
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-versioning
//! ```
use axum::{
async_trait,
body::{Bytes, Full},
extract::{FromRequest, Path, RequestParts},
handler::get,
http::{Response, StatusCode},
response::IntoResponse,
Router,
};
use std::collections::HashMap;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_versioning=debug")
}
tracing_subscriber::fmt::init();
// build our application with some routes
let app = Router::new().route("/:version/foo", get(handler));
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler(version: Version) {
println!("received request with version {:?}", version);
}
#[derive(Debug)]
enum Version {
V1,
V2,
V3,
}
#[async_trait]
impl<B> FromRequest<B> for Version
where
B: Send,
{
type Rejection = Response<Full<Bytes>>;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let params = Path::<HashMap<String, String>>::from_request(req)
.await
.map_err(IntoResponse::into_response)?;
let version = params
.get("version")
.ok_or_else(|| (StatusCode::NOT_FOUND, "version param missing").into_response())?;
match version.as_str() {
"v1" => Ok(Version::V1),
"v2" => Ok(Version::V2),
"v3" => Ok(Version::V3),
_ => Err((StatusCode::NOT_FOUND, "unknown version").into_response()),
}
}
}
<file_sep>use super::{rejection::*, FromRequest, RequestParts};
use async_trait::async_trait;
use std::ops::Deref;
/// Extractor that gets a value from request extensions.
///
/// This is commonly used to share state across handlers.
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// AddExtensionLayer,
/// extract::Extension,
/// handler::get,
/// Router,
/// };
/// use std::sync::Arc;
///
/// // Some shared state used throughout our application
/// struct State {
/// // ...
/// }
///
/// async fn handler(state: Extension<Arc<State>>) {
/// // ...
/// }
///
/// let state = Arc::new(State { /* ... */ });
///
/// let app = Router::new().route("/", get(handler))
/// // Add middleware that inserts the state into all incoming request's
/// // extensions.
/// .layer(AddExtensionLayer::new(state));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// If the extension is missing it will reject the request with a `500 Internal
/// Server Error` response.
#[derive(Debug, Clone, Copy)]
pub struct Extension<T>(pub T);
#[async_trait]
impl<T, B> FromRequest<B> for Extension<T>
where
T: Clone + Send + Sync + 'static,
B: Send,
{
type Rejection = ExtensionRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let value = req
.extensions()
.ok_or(ExtensionsAlreadyExtracted)?
.get::<T>()
.ok_or_else(|| {
MissingExtension::from_err(format!(
"Extension of type `{}` was not found. Perhaps you forgot to add it?",
std::any::type_name::<T>()
))
})
.map(|x| x.clone())?;
Ok(Extension(value))
}
}
impl<T> Deref for Extension<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-tokio-postgres
//! ```
use axum::{
async_trait,
extract::{Extension, FromRequest, RequestParts},
handler::get,
http::StatusCode,
AddExtensionLayer, Router,
};
use bb8::{Pool, PooledConnection};
use bb8_postgres::PostgresConnectionManager;
use std::net::SocketAddr;
use tokio_postgres::NoTls;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_tokio_postgres=debug")
}
tracing_subscriber::fmt::init();
// setup connection pool
let manager =
PostgresConnectionManager::new_from_stringlike("host=localhost user=postgres", NoTls)
.unwrap();
let pool = Pool::builder().build(manager).await.unwrap();
// build our application with some routes
let app = Router::new()
.route(
"/",
get(using_connection_pool_extractor).post(using_connection_extractor),
)
.layer(AddExtensionLayer::new(pool));
// run it with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
type ConnectionPool = Pool<PostgresConnectionManager<NoTls>>;
// we can exact the connection pool with `Extension`
async fn using_connection_pool_extractor(
Extension(pool): Extension<ConnectionPool>,
) -> Result<String, (StatusCode, String)> {
let conn = pool.get().await.map_err(internal_error)?;
let row = conn
.query_one("select 1 + 1", &[])
.await
.map_err(internal_error)?;
let two: i32 = row.try_get(0).map_err(internal_error)?;
Ok(two.to_string())
}
// we can also write a custom extractor that grabs a connection from the pool
// which setup is appropriate depends on your application
struct DatabaseConnection(PooledConnection<'static, PostgresConnectionManager<NoTls>>);
#[async_trait]
impl<B> FromRequest<B> for DatabaseConnection
where
B: Send,
{
type Rejection = (StatusCode, String);
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let Extension(pool) = Extension::<ConnectionPool>::from_request(req)
.await
.map_err(internal_error)?;
let conn = pool.get_owned().await.map_err(internal_error)?;
Ok(Self(conn))
}
}
async fn using_connection_extractor(
DatabaseConnection(conn): DatabaseConnection,
) -> Result<String, (StatusCode, String)> {
let row = conn
.query_one("select 1 + 1", &[])
.await
.map_err(internal_error)?;
let two: i32 = row.try_get(0).map_err(internal_error)?;
Ok(two.to_string())
}
/// Utility function for mapping any error into a `500 Internal Server Error`
/// response.
fn internal_error<E>(err: E) -> (StatusCode, String)
where
E: std::error::Error,
{
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}
<file_sep>//! Convert an extractor into a middleware.
//!
//! See [`extractor_middleware`] for more details.
use super::{FromRequest, RequestParts};
use crate::BoxError;
use crate::{body::BoxBody, response::IntoResponse};
use bytes::Bytes;
use futures_util::{future::BoxFuture, ready};
use http::{Request, Response};
use pin_project_lite::pin_project;
use std::{
fmt,
future::Future,
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};
use tower_layer::Layer;
use tower_service::Service;
/// Convert an extractor into a middleware.
///
/// If the extractor succeeds the value will be discarded and the inner service
/// will be called. If the extractor fails the rejection will be returned and
/// the inner service will _not_ be called.
///
/// This can be used to perform validation of requests if the validation doesn't
/// produce any useful output, and run the extractor for several handlers
/// without repeating it in the function signature.
///
/// Note that if the extractor consumes the request body, as `String` or
/// [`Bytes`] does, an empty body will be left in its place. Thus wont be
/// accessible to subsequent extractors or handlers.
///
/// # Example
///
/// ```rust
/// use axum::{
/// extract::{extractor_middleware, FromRequest, RequestParts},
/// handler::{get, post},
/// Router,
/// };
/// use http::StatusCode;
/// use async_trait::async_trait;
///
/// // An extractor that performs authorization.
/// struct RequireAuth;
///
/// #[async_trait]
/// impl<B> FromRequest<B> for RequireAuth
/// where
/// B: Send,
/// {
/// type Rejection = StatusCode;
///
/// async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
/// let auth_header = req
/// .headers()
/// .and_then(|headers| headers.get(http::header::AUTHORIZATION))
/// .and_then(|value| value.to_str().ok());
///
/// if let Some(value) = auth_header {
/// if value == "secret" {
/// return Ok(Self);
/// }
/// }
///
/// Err(StatusCode::UNAUTHORIZED)
/// }
/// }
///
/// async fn handler() {
/// // If we get here the request has been authorized
/// }
///
/// async fn other_handler() {
/// // If we get here the request has been authorized
/// }
///
/// let app = Router::new()
/// .route("/", get(handler))
/// .route("/foo", post(other_handler))
/// // The extractor will run before all routes
/// .layer(extractor_middleware::<RequireAuth>());
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn extractor_middleware<E>() -> ExtractorMiddlewareLayer<E> {
ExtractorMiddlewareLayer(PhantomData)
}
/// [`Layer`] that applies [`ExtractorMiddleware`] that runs an extractor and
/// discards the value.
///
/// See [`extractor_middleware`] for more details.
///
/// [`Layer`]: tower::Layer
pub struct ExtractorMiddlewareLayer<E>(PhantomData<fn() -> E>);
impl<E> Clone for ExtractorMiddlewareLayer<E> {
fn clone(&self) -> Self {
Self(PhantomData)
}
}
impl<E> fmt::Debug for ExtractorMiddlewareLayer<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExtractorMiddleware")
.field("extractor", &format_args!("{}", std::any::type_name::<E>()))
.finish()
}
}
impl<E, S> Layer<S> for ExtractorMiddlewareLayer<E> {
type Service = ExtractorMiddleware<S, E>;
fn layer(&self, inner: S) -> Self::Service {
ExtractorMiddleware {
inner,
_extractor: PhantomData,
}
}
}
/// Middleware that runs an extractor and discards the value.
///
/// See [`extractor_middleware`] for more details.
pub struct ExtractorMiddleware<S, E> {
inner: S,
_extractor: PhantomData<fn() -> E>,
}
#[test]
fn traits() {
use crate::tests::*;
assert_send::<ExtractorMiddleware<(), NotSendSync>>();
assert_sync::<ExtractorMiddleware<(), NotSendSync>>();
}
impl<S, E> Clone for ExtractorMiddleware<S, E>
where
S: Clone,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_extractor: PhantomData,
}
}
}
impl<S, E> fmt::Debug for ExtractorMiddleware<S, E>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExtractorMiddleware")
.field("inner", &self.inner)
.field("extractor", &format_args!("{}", std::any::type_name::<E>()))
.finish()
}
}
impl<S, E, ReqBody, ResBody> Service<Request<ReqBody>> for ExtractorMiddleware<S, E>
where
E: FromRequest<ReqBody> + 'static,
ReqBody: Default + Send + 'static,
S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone,
ResBody: http_body::Body<Data = Bytes> + Send + Sync + 'static,
ResBody::Error: Into<BoxError>,
{
type Response = Response<BoxBody>;
type Error = S::Error;
type Future = ResponseFuture<ReqBody, S, E>;
#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
let extract_future = Box::pin(async move {
let mut req = super::RequestParts::new(req);
let extracted = E::from_request(&mut req).await;
(req, extracted)
});
ResponseFuture {
state: State::Extracting {
future: extract_future,
},
svc: Some(self.inner.clone()),
}
}
}
pin_project! {
/// Response future for [`ExtractorMiddleware`].
#[allow(missing_debug_implementations)]
pub struct ResponseFuture<ReqBody, S, E>
where
E: FromRequest<ReqBody>,
S: Service<Request<ReqBody>>,
{
#[pin]
state: State<ReqBody, S, E>,
svc: Option<S>,
}
}
pin_project! {
#[project = StateProj]
enum State<ReqBody, S, E>
where
E: FromRequest<ReqBody>,
S: Service<Request<ReqBody>>,
{
Extracting { future: BoxFuture<'static, (RequestParts<ReqBody>, Result<E, E::Rejection>)> },
Call { #[pin] future: S::Future },
}
}
impl<ReqBody, S, E, ResBody> Future for ResponseFuture<ReqBody, S, E>
where
E: FromRequest<ReqBody>,
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
ReqBody: Default,
ResBody: http_body::Body<Data = Bytes> + Send + Sync + 'static,
ResBody::Error: Into<BoxError>,
{
type Output = Result<Response<BoxBody>, S::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let mut this = self.as_mut().project();
let new_state = match this.state.as_mut().project() {
StateProj::Extracting { future } => {
let (req, extracted) = ready!(future.as_mut().poll(cx));
match extracted {
Ok(_) => {
let mut svc = this.svc.take().expect("future polled after completion");
let req = req.try_into_request().unwrap_or_default();
let future = svc.call(req);
State::Call { future }
}
Err(err) => {
let res = err.into_response().map(crate::body::box_body);
return Poll::Ready(Ok(res));
}
}
}
StateProj::Call { future } => {
return future
.poll(cx)
.map(|result| result.map(|response| response.map(crate::body::box_body)));
}
};
this.state.set(new_state);
}
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-tracing-aka-logging
//! ```
use axum::{
body::Bytes,
handler::get,
http::{HeaderMap, Request, Response},
response::Html,
Router,
};
use std::{net::SocketAddr, time::Duration};
use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer};
use tracing::Span;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var(
"RUST_LOG",
"example_tracing_aka_logging=debug,tower_http=debug",
)
}
tracing_subscriber::fmt::init();
// build our application with a route
let app = Router::new()
.route("/", get(handler))
// `TraceLayer` is provided by tower-http so you have to add that as a dependency.
// It provides good defaults but is also very customizable.
//
// See https://docs.rs/tower-http/0.1.1/tower_http/trace/index.html for more details.
.layer(TraceLayer::new_for_http())
// If you want to customize the behavior using closures here is how
//
// This is just for demonstration, you don't need to add this middleware twice
.layer(
TraceLayer::new_for_http()
.on_request(|_request: &Request<_>, _span: &Span| {
// ...
})
.on_response(
|_response: &Response<_>, _latency: Duration, _span: &Span| {
// ...
},
)
.on_body_chunk(|_chunk: &Bytes, _latency: Duration, _span: &Span| {
// ..
})
.on_eos(
|_trailers: Option<&HeaderMap>, _stream_duration: Duration, _span: &Span| {
// ...
},
)
.on_failure(
|_error: ServerErrorsFailureClass, _latency: Duration, _span: &Span| {
// ...
},
),
);
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}
<file_sep>//! [`Or`] used to combine two services into one.
use super::FromEmptyRouter;
use crate::body::BoxBody;
use futures_util::ready;
use http::{Request, Response};
use pin_project_lite::pin_project;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tower::{util::Oneshot, ServiceExt};
use tower_service::Service;
/// [`tower::Service`] that is the combination of two routers.
///
/// See [`Router::or`] for more details.
///
/// [`Router::or`]: super::Router::or
#[derive(Debug, Clone, Copy)]
pub struct Or<A, B> {
pub(super) first: A,
pub(super) second: B,
}
#[test]
fn traits() {
use crate::tests::*;
assert_send::<Or<(), ()>>();
assert_sync::<Or<(), ()>>();
}
#[allow(warnings)]
impl<A, B, ReqBody> Service<Request<ReqBody>> for Or<A, B>
where
A: Service<Request<ReqBody>, Response = Response<BoxBody>> + Clone,
B: Service<Request<ReqBody>, Response = Response<BoxBody>, Error = A::Error> + Clone,
ReqBody: Send + Sync + 'static,
A: Send + 'static,
B: Send + 'static,
A::Future: Send + 'static,
B::Future: Send + 'static,
{
type Response = Response<BoxBody>;
type Error = A::Error;
type Future = ResponseFuture<A, B, ReqBody>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
let original_uri = req.uri().clone();
ResponseFuture {
state: State::FirstFuture {
f: self.first.clone().oneshot(req),
},
second: Some(self.second.clone()),
original_uri: Some(original_uri),
}
}
}
pin_project! {
/// Response future for [`Or`].
pub struct ResponseFuture<A, B, ReqBody>
where
A: Service<Request<ReqBody>>,
B: Service<Request<ReqBody>>,
{
#[pin]
state: State<A, B, ReqBody>,
second: Option<B>,
// Some services, namely `Nested`, mutates the request URI so we must
// restore it to its original state before calling `second`
original_uri: Option<http::Uri>,
}
}
pin_project! {
#[project = StateProj]
enum State<A, B, ReqBody>
where
A: Service<Request<ReqBody>>,
B: Service<Request<ReqBody>>,
{
FirstFuture { #[pin] f: Oneshot<A, Request<ReqBody>> },
SecondFuture {
#[pin]
f: Oneshot<B, Request<ReqBody>>,
}
}
}
impl<A, B, ReqBody> Future for ResponseFuture<A, B, ReqBody>
where
A: Service<Request<ReqBody>, Response = Response<BoxBody>>,
B: Service<Request<ReqBody>, Response = Response<BoxBody>, Error = A::Error>,
ReqBody: Send + Sync + 'static,
{
type Output = Result<Response<BoxBody>, A::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let mut this = self.as_mut().project();
let new_state = match this.state.as_mut().project() {
StateProj::FirstFuture { f } => {
let mut response = ready!(f.poll(cx)?);
let mut req = if let Some(ext) = response
.extensions_mut()
.remove::<FromEmptyRouter<ReqBody>>()
{
ext.request
} else {
return Poll::Ready(Ok(response));
};
*req.uri_mut() = this.original_uri.take().unwrap();
let second = this.second.take().expect("future polled after completion");
State::SecondFuture {
f: second.oneshot(req),
}
}
StateProj::SecondFuture { f } => return f.poll(cx),
};
this.state.set(new_state);
}
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-hello-world
//! ```
use axum::{handler::get, response::Html, Router};
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// build our application with a route
let app = Router::new().route("/", get(handler));
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}
<file_sep>//! Example JWT authorization/authentication.
//!
//! Run with
//!
//! ```not_rust
//! JWT_SECRET=secret cargo run -p example-jwt
//! ```
use axum::{
async_trait,
body::{Bytes, Full},
extract::{FromRequest, RequestParts, TypedHeader},
handler::{get, post},
http::{Response, StatusCode},
response::IntoResponse,
Json, Router,
};
use headers::{authorization::Bearer, Authorization};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{convert::Infallible, fmt::Display, net::SocketAddr};
// Quick instructions
//
// - get an authorization token:
//
// curl -s \
// -w '\n' \
// -H 'Content-Type: application/json' \
// -d '{"client_id":"foo","client_secret":"bar"}' \
// http://localhost:3000/authorize
//
// - visit the protected area using the authorized token
//
// curl -s \
// -w '\n' \
// -H 'Content-Type: application/json' \
// -H 'Authorization: Bearer <KEY>' \
// http://localhost:3000/protected
//
// - try to visit the protected area using an invalid token
//
// curl -s \
// -w '\n' \
// -H 'Content-Type: application/json' \
// -H 'Authorization: Bearer blahblahblah' \
// http://localhost:3000/protected
static KEYS: Lazy<Keys> = Lazy::new(|| {
let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set");
Keys::new(secret.as_bytes())
});
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_jwt=debug")
}
tracing_subscriber::fmt::init();
let app = Router::new()
.route("/protected", get(protected))
.route("/authorize", post(authorize));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn protected(claims: Claims) -> Result<String, AuthError> {
// Send the protected data to the user
Ok(format!(
"Welcome to the protected area :)\nYour data:\n{}",
claims
))
}
async fn authorize(Json(payload): Json<AuthPayload>) -> Result<Json<AuthBody>, AuthError> {
// Check if the user sent the credentials
if payload.client_id.is_empty() || payload.client_secret.is_empty() {
return Err(AuthError::MissingCredentials);
}
// Here you can check the user credentials from a database
if payload.client_id != "foo" || payload.client_secret != "bar" {
return Err(AuthError::WrongCredentials);
}
let claims = Claims {
sub: "<EMAIL>".to_owned(),
company: "ACME".to_owned(),
exp: 10000000000,
};
// Create the authorization token
let token = encode(&Header::default(), &claims, &KEYS.encoding)
.map_err(|_| AuthError::TokenCreation)?;
// Send the authorized token
Ok(Json(AuthBody::new(token)))
}
impl Display for Claims {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Email: {}\nCompany: {}", self.sub, self.company)
}
}
impl AuthBody {
fn new(access_token: String) -> Self {
Self {
access_token,
token_type: "Bearer".to_string(),
}
}
}
#[async_trait]
impl<B> FromRequest<B> for Claims
where
B: Send,
{
type Rejection = AuthError;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
// Extract the token from the authorization header
let TypedHeader(Authorization(bearer)) =
TypedHeader::<Authorization<Bearer>>::from_request(req)
.await
.map_err(|_| AuthError::InvalidToken)?;
// Decode the user data
let token_data = decode::<Claims>(bearer.token(), &KEYS.decoding, &Validation::default())
.map_err(|_| AuthError::InvalidToken)?;
Ok(token_data.claims)
}
}
impl IntoResponse for AuthError {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let (status, error_message) = match self {
AuthError::WrongCredentials => (StatusCode::UNAUTHORIZED, "Wrong credentials"),
AuthError::MissingCredentials => (StatusCode::BAD_REQUEST, "Missing credentials"),
AuthError::TokenCreation => (StatusCode::INTERNAL_SERVER_ERROR, "Token creation error"),
AuthError::InvalidToken => (StatusCode::BAD_REQUEST, "Invalid token"),
};
let body = Json(json!({
"error": error_message,
}));
(status, body).into_response()
}
}
#[derive(Debug)]
struct Keys {
encoding: EncodingKey,
decoding: DecodingKey<'static>,
}
impl Keys {
fn new(secret: &[u8]) -> Self {
Self {
encoding: EncodingKey::from_secret(secret),
decoding: DecodingKey::from_secret(secret).into_static(),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String,
company: String,
exp: usize,
}
#[derive(Debug, Serialize)]
struct AuthBody {
access_token: String,
token_type: String,
}
#[derive(Debug, Deserialize)]
struct AuthPayload {
client_id: String,
client_secret: String,
}
#[derive(Debug)]
enum AuthError {
WrongCredentials,
MissingCredentials,
TokenCreation,
InvalidToken,
}
<file_sep>//! Server-Sent Events (SSE) responses.
//!
//! # Example
//!
//! ```
//! use axum::{
//! Router,
//! handler::get,
//! response::sse::{Event, KeepAlive, Sse},
//! };
//! use std::{time::Duration, convert::Infallible};
//! use tokio_stream::StreamExt as _ ;
//! use futures::stream::{self, Stream};
//!
//! let app = Router::new().route("/sse", get(sse_handler));
//!
//! async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
//! // A `Stream` that repeats an event every second
//! let stream = stream::repeat_with(|| Event::default().data("hi!"))
//! .map(Ok)
//! .throttle(Duration::from_secs(1));
//!
//! Sse::new(stream).keep_alive(KeepAlive::default())
//! }
//! # async {
//! # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
use crate::response::IntoResponse;
use crate::BoxError;
use bytes::Bytes;
use futures_util::{
ready,
stream::{Stream, TryStream},
};
use http::Response;
use http_body::Body as HttpBody;
use pin_project_lite::pin_project;
use serde::Serialize;
use std::{
borrow::Cow,
fmt,
fmt::Write,
future::Future,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use sync_wrapper::SyncWrapper;
use tokio::time::Sleep;
/// An SSE response
#[derive(Clone)]
pub struct Sse<S> {
stream: S,
keep_alive: Option<KeepAlive>,
}
impl<S> Sse<S> {
/// Create a new [`Sse`] response that will respond with the given stream of
/// [`Event`]s.
///
/// See the [module docs](self) for more details.
pub fn new(stream: S) -> Self
where
S: TryStream<Ok = Event> + Send + 'static,
S::Error: Into<BoxError>,
{
Sse {
stream,
keep_alive: None,
}
}
/// Configure the interval between keep-alive messages.
///
/// Defaults to no keep-alive messages.
pub fn keep_alive(mut self, keep_alive: KeepAlive) -> Self {
self.keep_alive = Some(keep_alive);
self
}
}
impl<S> fmt::Debug for Sse<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Sse")
.field("stream", &format_args!("{}", std::any::type_name::<S>()))
.field("keep_alive", &self.keep_alive)
.finish()
}
}
impl<S, E> IntoResponse for Sse<S>
where
S: Stream<Item = Result<Event, E>> + Send + 'static,
E: Into<BoxError>,
{
type Body = Body<S>;
type BodyError = E;
fn into_response(self) -> Response<Self::Body> {
let body = Body {
event_stream: SyncWrapper::new(self.stream),
keep_alive: self.keep_alive.map(KeepAliveStream::new),
};
Response::builder()
.header(http::header::CONTENT_TYPE, "text/event-stream")
.header(http::header::CACHE_CONTROL, "no-cache")
.body(body)
.unwrap()
}
}
pin_project! {
/// The body of an SSE response.
#[derive(Debug)]
pub struct Body<S> {
#[pin]
event_stream: SyncWrapper<S>,
#[pin]
keep_alive: Option<KeepAliveStream>,
}
}
impl<S, E> HttpBody for Body<S>
where
S: Stream<Item = Result<Event, E>>,
{
type Data = Bytes;
type Error = E;
fn poll_data(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
let this = self.project();
match this.event_stream.get_pin_mut().poll_next(cx) {
Poll::Pending => {
if let Some(keep_alive) = this.keep_alive.as_pin_mut() {
keep_alive
.poll_event(cx)
.map(|e| Some(Ok(Bytes::from(e.to_string()))))
} else {
Poll::Pending
}
}
Poll::Ready(Some(Ok(event))) => {
if let Some(keep_alive) = this.keep_alive.as_pin_mut() {
keep_alive.reset();
}
Poll::Ready(Some(Ok(Bytes::from(event.to_string()))))
}
Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
Poll::Ready(None) => Poll::Ready(None),
}
}
fn poll_trailers(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Result<Option<http::HeaderMap>, Self::Error>> {
Poll::Ready(Ok(None))
}
}
/// Server-sent event
#[derive(Default, Debug)]
pub struct Event {
name: Option<String>,
id: Option<String>,
data: Option<DataType>,
event: Option<String>,
comment: Option<String>,
retry: Option<Duration>,
}
// Server-sent event data type
#[derive(Debug)]
enum DataType {
Text(String),
Json(String),
}
impl Event {
/// Set Server-sent event data
/// data field(s) ("data:<content>")
pub fn data<T>(mut self, data: T) -> Event
where
T: Into<String>,
{
self.data = Some(DataType::Text(data.into()));
self
}
/// Set Server-sent event data
/// data field(s) ("data:<content>")
pub fn json_data<T>(mut self, data: T) -> Result<Event, serde_json::Error>
where
T: Serialize,
{
self.data = Some(DataType::Json(serde_json::to_string(&data)?));
Ok(self)
}
/// Set Server-sent event comment
/// Comment field (":<comment-text>")
pub fn comment<T>(mut self, comment: T) -> Event
where
T: Into<String>,
{
self.comment = Some(comment.into());
self
}
/// Set Server-sent event event
/// Event name field ("event:<event-name>")
pub fn event<T>(mut self, event: T) -> Event
where
T: Into<String>,
{
self.event = Some(event.into());
self
}
/// Set Server-sent event retry
/// Retry timeout field ("retry:<timeout>")
pub fn retry(mut self, duration: Duration) -> Event {
self.retry = Some(duration);
self
}
/// Set Server-sent event id
/// Identifier field ("id:<identifier>")
pub fn id<T>(mut self, id: T) -> Event
where
T: Into<String>,
{
self.id = Some(id.into());
self
}
}
impl fmt::Display for Event {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(comment) = &self.comment {
":".fmt(f)?;
comment.fmt(f)?;
f.write_char('\n')?;
}
if let Some(event) = &self.event {
"event:".fmt(f)?;
event.fmt(f)?;
f.write_char('\n')?;
}
match &self.data {
Some(DataType::Text(data)) => {
for line in data.split('\n') {
"data:".fmt(f)?;
line.fmt(f)?;
f.write_char('\n')?;
}
}
Some(DataType::Json(data)) => {
"data:".fmt(f)?;
data.fmt(f)?;
f.write_char('\n')?;
}
None => {}
}
if let Some(id) = &self.id {
"id:".fmt(f)?;
id.fmt(f)?;
f.write_char('\n')?;
}
if let Some(duration) = &self.retry {
"retry:".fmt(f)?;
let secs = duration.as_secs();
let millis = duration.subsec_millis();
if secs > 0 {
// format seconds
secs.fmt(f)?;
// pad milliseconds
if millis < 10 {
f.write_str("00")?;
} else if millis < 100 {
f.write_char('0')?;
}
}
// format milliseconds
millis.fmt(f)?;
f.write_char('\n')?;
}
f.write_char('\n')?;
Ok(())
}
}
/// Configure the interval between keep-alive messages, the content
/// of each message, and the associated stream.
#[derive(Debug, Clone)]
pub struct KeepAlive {
comment_text: Cow<'static, str>,
max_interval: Duration,
}
impl KeepAlive {
/// Create a new `KeepAlive`.
pub fn new() -> Self {
Self {
comment_text: Cow::Borrowed(""),
max_interval: Duration::from_secs(15),
}
}
/// Customize the interval between keep-alive messages.
///
/// Default is 15 seconds.
pub fn interval(mut self, time: Duration) -> Self {
self.max_interval = time;
self
}
/// Customize the text of the keep-alive message.
///
/// Default is an empty comment.
pub fn text<I>(mut self, text: I) -> Self
where
I: Into<Cow<'static, str>>,
{
self.comment_text = text.into();
self
}
}
impl Default for KeepAlive {
fn default() -> Self {
Self::new()
}
}
pin_project! {
#[derive(Debug)]
struct KeepAliveStream {
keep_alive: KeepAlive,
#[pin]
alive_timer: Sleep,
}
}
impl KeepAliveStream {
fn new(keep_alive: KeepAlive) -> Self {
Self {
alive_timer: tokio::time::sleep(keep_alive.max_interval),
keep_alive,
}
}
fn reset(self: Pin<&mut Self>) {
let this = self.project();
this.alive_timer
.reset(tokio::time::Instant::now() + this.keep_alive.max_interval);
}
fn poll_event(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Event> {
let this = self.as_mut().project();
ready!(this.alive_timer.poll(cx));
let comment_str = this.keep_alive.comment_text.clone();
let event = Event::default().comment(comment_str);
self.reset();
Poll::Ready(event)
}
}
<file_sep>use crate::response::IntoResponse;
use super::{rejection::*, FromRequest, RequestParts};
use async_trait::async_trait;
use std::ops::Deref;
/// Extractor that will reject requests with a body larger than some size.
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// extract::ContentLengthLimit,
/// handler::post,
/// Router,
/// };
///
/// async fn handler(body: ContentLengthLimit<String, 1024>) {
/// // ...
/// }
///
/// let app = Router::new().route("/", post(handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// This requires the request to have a `Content-Length` header.
#[derive(Debug, Clone)]
pub struct ContentLengthLimit<T, const N: u64>(pub T);
#[async_trait]
impl<T, B, const N: u64> FromRequest<B> for ContentLengthLimit<T, N>
where
T: FromRequest<B>,
T::Rejection: IntoResponse,
B: Send,
{
type Rejection = ContentLengthLimitRejection<T::Rejection>;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let content_length = req
.headers()
.ok_or(ContentLengthLimitRejection::HeadersAlreadyExtracted(
HeadersAlreadyExtracted,
))?
.get(http::header::CONTENT_LENGTH);
let content_length =
content_length.and_then(|value| value.to_str().ok()?.parse::<u64>().ok());
if let Some(length) = content_length {
if length > N {
return Err(ContentLengthLimitRejection::PayloadTooLarge(
PayloadTooLarge,
));
}
} else {
return Err(ContentLengthLimitRejection::LengthRequired(LengthRequired));
};
let value = T::from_request(req)
.await
.map_err(ContentLengthLimitRejection::Inner)?;
Ok(Self(value))
}
}
impl<T, const N: u64> Deref for ContentLengthLimit<T, N> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-form
//! ```
use axum::{extract::Form, handler::get, response::Html, Router};
use serde::Deserialize;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_form=debug")
}
tracing_subscriber::fmt::init();
// build our application with some routes
let app = Router::new().route("/", get(show_form).post(accept_form));
// run it with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn show_form() -> Html<&'static str> {
Html(
r#"
<!doctype html>
<html>
<head></head>
<body>
<form action="/" method="post">
<label for="name">
Enter your name:
<input type="text" name="name">
</label>
<label>
Enter your email:
<input type="text" name="email">
</label>
<input type="submit" value="Subscribe!">
</form>
</body>
</html>
"#,
)
}
#[derive(Deserialize, Debug)]
struct Input {
name: String,
email: String,
}
async fn accept_form(Form(input): Form<Input>) {
dbg!(&input);
}
<file_sep>use crate::BoxError;
use crate::{
extract::{has_content_type, rejection::*, take_body, FromRequest, RequestParts},
response::IntoResponse,
};
use async_trait::async_trait;
use bytes::Bytes;
use http::{
header::{self, HeaderValue},
StatusCode,
};
use http_body::Full;
use hyper::Response;
use serde::{de::DeserializeOwned, Serialize};
use std::{
convert::Infallible,
ops::{Deref, DerefMut},
};
/// JSON Extractor/Response
///
/// When used as an extractor, it can deserialize request bodies into some type that
/// implements [`serde::Serialize`]. If the request body cannot be parsed, or it does not contain
/// the `Content-Type: application/json` header, it will reject the request and return a
/// `400 Bad Request` response.
///
/// # Extractor example
///
/// ```rust,no_run
/// use axum::{
/// extract,
/// handler::post,
/// Router,
/// };
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct CreateUser {
/// email: String,
/// password: String,
/// }
///
/// async fn create_user(extract::Json(payload): extract::Json<CreateUser>) {
/// // payload is a `CreateUser`
/// }
///
/// let app = Router::new().route("/users", post(create_user));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// When used as a response, it can serialize any type that implements [`serde::Serialize`] to `JSON`,
/// and will automatically set `Content-Type: application/json` header.
///
/// # Response example
///
/// ```
/// use axum::{
/// extract::Path,
/// handler::get,
/// Router,
/// Json,
/// };
/// use serde::Serialize;
/// use uuid::Uuid;
///
/// #[derive(Serialize)]
/// struct User {
/// id: Uuid,
/// username: String,
/// }
///
/// async fn get_user(Path(user_id) : Path<Uuid>) -> Json<User> {
/// let user = find_user(user_id).await;
/// Json(user)
/// }
///
/// async fn find_user(user_id: Uuid) -> User {
/// // ...
/// # unimplemented!()
/// }
///
/// let app = Router::new().route("/users/:id", get(get_user));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct Json<T>(pub T);
#[async_trait]
impl<T, B> FromRequest<B> for Json<T>
where
T: DeserializeOwned,
B: http_body::Body + Send,
B::Data: Send,
B::Error: Into<BoxError>,
{
type Rejection = JsonRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
use bytes::Buf;
if has_content_type(req, "application/json")? {
let body = take_body(req)?;
let buf = hyper::body::aggregate(body)
.await
.map_err(InvalidJsonBody::from_err)?;
let value = serde_json::from_reader(buf.reader()).map_err(InvalidJsonBody::from_err)?;
Ok(Json(value))
} else {
Err(MissingJsonContentType.into())
}
}
}
impl<T> Deref for Json<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for Json<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> From<T> for Json<T> {
fn from(inner: T) -> Self {
Self(inner)
}
}
impl<T> IntoResponse for Json<T>
where
T: Serialize,
{
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let bytes = match serde_json::to_vec(&self.0) {
Ok(res) => res,
Err(err) => {
return Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(header::CONTENT_TYPE, "text/plain")
.body(Full::from(err.to_string()))
.unwrap();
}
};
let mut res = Response::new(Full::from(bytes));
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
res
}
}
<file_sep>//! Types and traits for generating responses.
use crate::{
body::{box_body, BoxBody},
BoxError, Error,
};
use bytes::Bytes;
use http::{header, HeaderMap, HeaderValue, Response, StatusCode};
use http_body::{
combinators::{MapData, MapErr},
Empty, Full,
};
use std::{borrow::Cow, convert::Infallible};
mod headers;
mod redirect;
pub mod sse;
#[doc(no_inline)]
pub use crate::Json;
#[doc(inline)]
pub use self::{headers::Headers, redirect::Redirect, sse::Sse};
/// Trait for generating responses.
///
/// Types that implement `IntoResponse` can be returned from handlers.
///
/// # Implementing `IntoResponse`
///
/// You generally shouldn't have to implement `IntoResponse` manually, as axum
/// provides implementations for many common types.
///
/// However it might be necessary if you have a custom error type that you want
/// to return from handlers:
///
/// ```rust
/// use axum::{
/// Router,
/// body::Body,
/// handler::get,
/// http::{Response, StatusCode},
/// response::IntoResponse,
/// };
///
/// enum MyError {
/// SomethingWentWrong,
/// SomethingElseWentWrong,
/// }
///
/// impl IntoResponse for MyError {
/// type Body = Body;
/// type BodyError = <Self::Body as axum::body::HttpBody>::Error;
///
/// fn into_response(self) -> Response<Self::Body> {
/// let body = match self {
/// MyError::SomethingWentWrong => {
/// Body::from("something went wrong")
/// },
/// MyError::SomethingElseWentWrong => {
/// Body::from("something else went wrong")
/// },
/// };
///
/// Response::builder()
/// .status(StatusCode::INTERNAL_SERVER_ERROR)
/// .body(body)
/// .unwrap()
/// }
/// }
///
/// // `Result<impl IntoResponse, MyError>` can now be returned from handlers
/// let app = Router::new().route("/", get(handler));
///
/// async fn handler() -> Result<(), MyError> {
/// Err(MyError::SomethingWentWrong)
/// }
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// Or if you have a custom body type you'll also need to implement
/// `IntoResponse` for it:
///
/// ```rust
/// use axum::{
/// handler::get,
/// response::IntoResponse,
/// Router,
/// };
/// use http_body::Body;
/// use http::{Response, HeaderMap};
/// use bytes::Bytes;
/// use std::{
/// convert::Infallible,
/// task::{Poll, Context},
/// pin::Pin,
/// };
///
/// struct MyBody;
///
/// // First implement `Body` for `MyBody`. This could for example use
/// // some custom streaming protocol.
/// impl Body for MyBody {
/// type Data = Bytes;
/// type Error = Infallible;
///
/// fn poll_data(
/// self: Pin<&mut Self>,
/// cx: &mut Context<'_>
/// ) -> Poll<Option<Result<Self::Data, Self::Error>>> {
/// # unimplemented!()
/// // ...
/// }
///
/// fn poll_trailers(
/// self: Pin<&mut Self>,
/// cx: &mut Context<'_>
/// ) -> Poll<Result<Option<HeaderMap>, Self::Error>> {
/// # unimplemented!()
/// // ...
/// }
/// }
///
/// // Now we can implement `IntoResponse` directly for `MyBody`
/// impl IntoResponse for MyBody {
/// type Body = Self;
/// type BodyError = <Self as Body>::Error;
///
/// fn into_response(self) -> Response<Self::Body> {
/// Response::new(self)
/// }
/// }
///
/// // We don't need to implement `IntoResponse for Response<MyBody>` as that is
/// // covered by a blanket implementation in axum.
///
/// // `MyBody` can now be returned from handlers.
/// let app = Router::new().route("/", get(|| async { MyBody }));
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub trait IntoResponse {
/// The body type of the response.
///
/// Unless you're implementing this trait for a custom body type, these are
/// some common types you can use:
///
/// - [`axum::body::Body`]: A good default that supports most use cases.
/// - [`axum::body::Empty<Bytes>`]: When you know your response is always
/// empty.
/// - [`axum::body::Full<Bytes>`]: When you know your response always
/// contains exactly one chunk.
/// - [`axum::body::BoxBody`]: If you need to unify multiple body types into
/// one, or return a body type that cannot be named. Can be created with
/// [`box_body`].
///
/// [`axum::body::Body`]: crate::body::Body
/// [`axum::body::Empty<Bytes>`]: crate::body::Empty
/// [`axum::body::Full<Bytes>`]: crate::body::Full
/// [`axum::body::BoxBody`]: crate::body::BoxBody
type Body: http_body::Body<Data = Bytes, Error = Self::BodyError> + Send + Sync + 'static;
/// The error type `Self::Body` might generate.
///
/// Generally it should be possible to set this to:
///
/// ```rust,ignore
/// type BodyError = <Self::Body as axum::body::HttpBody>::Error;
/// ```
///
/// This associated type exists mainly to make returning `impl IntoResponse`
/// possible and to simplify trait bounds internally in axum.
type BodyError: Into<BoxError>;
/// Create a response.
fn into_response(self) -> Response<Self::Body>;
}
impl IntoResponse for () {
type Body = Empty<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
Response::new(Empty::new())
}
}
impl IntoResponse for Infallible {
type Body = Empty<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
match self {}
}
}
impl<T, E> IntoResponse for Result<T, E>
where
T: IntoResponse,
E: IntoResponse,
{
type Body = BoxBody;
type BodyError = Error;
fn into_response(self) -> Response<Self::Body> {
match self {
Ok(value) => value.into_response().map(box_body),
Err(err) => err.into_response().map(box_body),
}
}
}
impl<B> IntoResponse for Response<B>
where
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError>,
{
type Body = B;
type BodyError = <B as http_body::Body>::Error;
fn into_response(self) -> Self {
self
}
}
macro_rules! impl_into_response_for_body {
($body:ty) => {
impl IntoResponse for $body {
type Body = $body;
type BodyError = <$body as http_body::Body>::Error;
fn into_response(self) -> Response<Self> {
Response::new(self)
}
}
};
}
impl_into_response_for_body!(hyper::Body);
impl_into_response_for_body!(Full<Bytes>);
impl_into_response_for_body!(Empty<Bytes>);
impl<E> IntoResponse for http_body::combinators::BoxBody<Bytes, E>
where
E: Into<BoxError> + 'static,
{
type Body = Self;
type BodyError = E;
fn into_response(self) -> Response<Self> {
Response::new(self)
}
}
impl<B, F> IntoResponse for MapData<B, F>
where
B: http_body::Body + Send + Sync + 'static,
F: FnMut(B::Data) -> Bytes + Send + Sync + 'static,
B::Error: Into<BoxError>,
{
type Body = Self;
type BodyError = <B as http_body::Body>::Error;
fn into_response(self) -> Response<Self::Body> {
Response::new(self)
}
}
impl<B, F, E> IntoResponse for MapErr<B, F>
where
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
F: FnMut(B::Error) -> E + Send + Sync + 'static,
E: Into<BoxError>,
{
type Body = Self;
type BodyError = E;
fn into_response(self) -> Response<Self::Body> {
Response::new(self)
}
}
impl IntoResponse for &'static str {
type Body = Full<Bytes>;
type BodyError = Infallible;
#[inline]
fn into_response(self) -> Response<Self::Body> {
Cow::Borrowed(self).into_response()
}
}
impl IntoResponse for String {
type Body = Full<Bytes>;
type BodyError = Infallible;
#[inline]
fn into_response(self) -> Response<Self::Body> {
Cow::<'static, str>::Owned(self).into_response()
}
}
impl IntoResponse for std::borrow::Cow<'static, str> {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let mut res = Response::new(Full::from(self));
res.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));
res
}
}
impl IntoResponse for Bytes {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let mut res = Response::new(Full::from(self));
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
res
}
}
impl IntoResponse for &'static [u8] {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let mut res = Response::new(Full::from(self));
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
res
}
}
impl IntoResponse for Vec<u8> {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let mut res = Response::new(Full::from(self));
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
res
}
}
impl IntoResponse for std::borrow::Cow<'static, [u8]> {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let mut res = Response::new(Full::from(self));
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
res
}
}
impl IntoResponse for StatusCode {
type Body = Empty<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
Response::builder().status(self).body(Empty::new()).unwrap()
}
}
impl<T> IntoResponse for (StatusCode, T)
where
T: IntoResponse,
{
type Body = T::Body;
type BodyError = T::BodyError;
fn into_response(self) -> Response<T::Body> {
let mut res = self.1.into_response();
*res.status_mut() = self.0;
res
}
}
impl<T> IntoResponse for (HeaderMap, T)
where
T: IntoResponse,
{
type Body = T::Body;
type BodyError = T::BodyError;
fn into_response(self) -> Response<T::Body> {
let mut res = self.1.into_response();
res.headers_mut().extend(self.0);
res
}
}
impl<T> IntoResponse for (StatusCode, HeaderMap, T)
where
T: IntoResponse,
{
type Body = T::Body;
type BodyError = T::BodyError;
fn into_response(self) -> Response<T::Body> {
let mut res = self.2.into_response();
*res.status_mut() = self.0;
res.headers_mut().extend(self.1);
res
}
}
impl IntoResponse for HeaderMap {
type Body = Empty<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let mut res = Response::new(Empty::new());
*res.headers_mut() = self;
res
}
}
/// An HTML response.
///
/// Will automatically get `Content-Type: text/html`.
#[derive(Clone, Copy, Debug)]
pub struct Html<T>(pub T);
impl<T> IntoResponse for Html<T>
where
T: Into<Full<Bytes>>,
{
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let mut res = Response::new(self.0.into());
res.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/html"));
res
}
}
impl<T> From<T> for Html<T> {
fn from(inner: T) -> Self {
Self(inner)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::body::Body;
use http::header::{HeaderMap, HeaderName};
#[test]
fn test_merge_headers() {
struct MyResponse;
impl IntoResponse for MyResponse {
type Body = Body;
type BodyError = <Self::Body as http_body::Body>::Error;
fn into_response(self) -> Response<Body> {
let mut resp = Response::new(String::new().into());
resp.headers_mut()
.insert(HeaderName::from_static("a"), HeaderValue::from_static("1"));
resp
}
}
fn check(resp: impl IntoResponse) {
let resp = resp.into_response();
assert_eq!(
resp.headers().get(HeaderName::from_static("a")).unwrap(),
&HeaderValue::from_static("1")
);
assert_eq!(
resp.headers().get(HeaderName::from_static("b")).unwrap(),
&HeaderValue::from_static("2")
);
}
let headers: HeaderMap =
std::iter::once((HeaderName::from_static("b"), HeaderValue::from_static("2")))
.collect();
check((headers.clone(), MyResponse));
check((StatusCode::OK, headers, MyResponse));
}
}
<file_sep>//! [`Service`](tower::Service) future types.
use crate::{
body::{box_body, BoxBody},
response::IntoResponse,
util::{Either, EitherProj},
BoxError,
};
use bytes::Bytes;
use futures_util::ready;
use http::{Method, Request, Response};
use http_body::Empty;
use pin_project_lite::pin_project;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tower::util::Oneshot;
use tower_service::Service;
pin_project! {
/// Response future for [`HandleError`](super::HandleError).
#[derive(Debug)]
pub struct HandleErrorFuture<Fut, F> {
#[pin]
pub(super) inner: Fut,
pub(super) f: Option<F>,
}
}
impl<Fut, F, E, E2, B, Res> Future for HandleErrorFuture<Fut, F>
where
Fut: Future<Output = Result<Response<B>, E>>,
F: FnOnce(E) -> Result<Res, E2>,
Res: IntoResponse,
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError> + Send + Sync + 'static,
{
type Output = Result<Response<BoxBody>, E2>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
match ready!(this.inner.poll(cx)) {
Ok(res) => Ok(res.map(box_body)).into(),
Err(err) => {
let f = this.f.take().unwrap();
match f(err) {
Ok(res) => Ok(res.into_response().map(box_body)).into(),
Err(err) => Err(err).into(),
}
}
}
}
}
pin_project! {
/// The response future for [`OnMethod`](super::OnMethod).
pub struct OnMethodFuture<S, F, B>
where
S: Service<Request<B>>,
F: Service<Request<B>>
{
#[pin]
pub(super) inner: Either<
Oneshot<S, Request<B>>,
Oneshot<F, Request<B>>,
>,
// pub(super) inner: crate::routing::future::RouteFuture<S, F, B>,
pub(super) req_method: Method,
}
}
impl<S, F, B, ResBody> Future for OnMethodFuture<S, F, B>
where
S: Service<Request<B>, Response = Response<ResBody>> + Clone,
ResBody: http_body::Body<Data = Bytes> + Send + Sync + 'static,
ResBody::Error: Into<BoxError>,
F: Service<Request<B>, Response = Response<BoxBody>, Error = S::Error>,
{
type Output = Result<Response<BoxBody>, S::Error>;
#[allow(warnings)]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let response = match this.inner.project() {
EitherProj::A { inner } => ready!(inner.poll(cx))?.map(box_body),
EitherProj::B { inner } => ready!(inner.poll(cx))?,
};
if this.req_method == &Method::HEAD {
let response = response.map(|_| box_body(Empty::new()));
Poll::Ready(Ok(response))
} else {
Poll::Ready(Ok(response))
}
}
}
<file_sep>//! Internal macros
macro_rules! opaque_future {
($(#[$m:meta])* pub type $name:ident = $actual:ty;) => {
opaque_future! {
$(#[$m])*
pub type $name<> = $actual;
}
};
($(#[$m:meta])* pub type $name:ident<$($param:ident),*> = $actual:ty;) => {
pin_project_lite::pin_project! {
$(#[$m])*
pub struct $name<$($param),*> {
#[pin] pub(crate) future: $actual,
}
}
impl<$($param),*> std::fmt::Debug for $name<$($param),*> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple(stringify!($name)).field(&format_args!("...")).finish()
}
}
impl<$($param),*> std::future::Future for $name<$($param),*>
where
$actual: std::future::Future,
{
type Output = <$actual as std::future::Future>::Output;
#[inline]
fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
self.project().future.poll(cx)
}
}
};
}
macro_rules! define_rejection {
(
#[status = $status:ident]
#[body = $body:expr]
$(#[$m:meta])*
pub struct $name:ident;
) => {
$(#[$m])*
#[derive(Debug)]
#[non_exhaustive]
pub struct $name;
#[allow(deprecated)]
impl $crate::response::IntoResponse for $name {
type Body = http_body::Full<bytes::Bytes>;
type BodyError = std::convert::Infallible;
fn into_response(self) -> http::Response<Self::Body> {
let mut res = http::Response::new(http_body::Full::from($body));
*res.status_mut() = http::StatusCode::$status;
res
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", $body)
}
}
impl std::error::Error for $name {}
};
(
#[status = $status:ident]
#[body = $body:expr]
$(#[$m:meta])*
pub struct $name:ident (Error);
) => {
$(#[$m])*
#[derive(Debug)]
pub struct $name(pub(crate) crate::Error);
impl $name {
pub(crate) fn from_err<E>(err: E) -> Self
where
E: Into<crate::BoxError>,
{
Self(crate::Error::new(err))
}
}
impl IntoResponse for $name {
type Body = http_body::Full<bytes::Bytes>;
type BodyError = std::convert::Infallible;
fn into_response(self) -> http::Response<Self::Body> {
let mut res =
http::Response::new(http_body::Full::from(format!(concat!($body, ": {}"), self.0)));
*res.status_mut() = http::StatusCode::$status;
res
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", $body)
}
}
impl std::error::Error for $name {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.0)
}
}
};
}
macro_rules! composite_rejection {
(
$(#[$m:meta])*
pub enum $name:ident {
$($variant:ident),+
$(,)?
}
) => {
$(#[$m])*
#[derive(Debug)]
#[non_exhaustive]
pub enum $name {
$(
#[allow(missing_docs, deprecated)]
$variant($variant)
),+
}
impl $crate::response::IntoResponse for $name {
type Body = http_body::Full<bytes::Bytes>;
type BodyError = std::convert::Infallible;
fn into_response(self) -> http::Response<Self::Body> {
match self {
$(
Self::$variant(inner) => inner.into_response(),
)+
}
}
}
$(
#[allow(deprecated)]
impl From<$variant> for $name {
fn from(inner: $variant) -> Self {
Self::$variant(inner)
}
}
)+
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
$(
Self::$variant(inner) => write!(f, "{}", inner),
)+
}
}
}
impl std::error::Error for $name {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
$(
Self::$variant(inner) => Some(inner),
)+
}
}
}
};
}
<file_sep>//! Routing between [`Service`]s.
use self::future::{BoxRouteFuture, EmptyRouterFuture, NestedFuture, RouteFuture};
use crate::{
body::{box_body, BoxBody},
buffer::MpscBuffer,
extract::{
connect_info::{Connected, IntoMakeServiceWithConnectInfo},
OriginalUri,
},
service::HandleError,
util::ByteStr,
BoxError,
};
use bytes::Bytes;
use http::{Request, Response, StatusCode, Uri};
use regex::Regex;
use std::{
borrow::Cow,
convert::Infallible,
fmt,
future::ready,
marker::PhantomData,
sync::Arc,
task::{Context, Poll},
};
use tower::{
util::{BoxService, ServiceExt},
ServiceBuilder,
};
use tower_http::map_response_body::MapResponseBodyLayer;
use tower_layer::Layer;
use tower_service::Service;
pub mod future;
mod method_filter;
mod or;
pub use self::{method_filter::MethodFilter, or::Or};
/// The router type for composing handlers and services.
#[derive(Debug, Clone)]
pub struct Router<S> {
svc: S,
}
impl<E> Router<EmptyRouter<E>> {
/// Create a new `Router`.
///
/// Unless you add additional routes this will respond to `404 Not Found` to
/// all requests.
pub fn new() -> Self {
Self {
svc: EmptyRouter::not_found(),
}
}
}
impl<E> Default for Router<EmptyRouter<E>> {
fn default() -> Self {
Self::new()
}
}
impl<S, R> Service<R> for Router<S>
where
S: Service<R>,
{
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.svc.poll_ready(cx)
}
#[inline]
fn call(&mut self, req: R) -> Self::Future {
self.svc.call(req)
}
}
impl<S> Router<S> {
/// Add another route to the router.
///
/// `path` is a string of path segments separated by `/`. Each segment
/// can be either concrete or a capture:
///
/// - `/foo/bar/baz` will only match requests where the path is `/foo/bar/bar`.
/// - `/:foo` will match any route with exactly one segment _and_ it will
/// capture the first segment and store it at the key `foo`.
///
/// `service` is the [`Service`] that should receive the request if the path
/// matches `path`.
///
/// # Example
///
/// ```rust
/// use axum::{handler::{get, delete}, Router};
///
/// let app = Router::new()
/// .route("/", get(root))
/// .route("/users", get(list_users).post(create_user))
/// .route("/users/:id", get(show_user))
/// .route("/api/:version/users/:id/action", delete(do_thing));
///
/// async fn root() { /* ... */ }
///
/// async fn list_users() { /* ... */ }
///
/// async fn create_user() { /* ... */ }
///
/// async fn show_user() { /* ... */ }
///
/// async fn do_thing() { /* ... */ }
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// # Panics
///
/// Panics if `path` doesn't start with `/`.
pub fn route<T>(self, path: &str, svc: T) -> Router<Route<T, S>> {
self.map(|fallback| Route {
pattern: PathPattern::new(path),
svc,
fallback,
})
}
/// Nest a group of routes (or a [`Service`]) at some path.
///
/// This allows you to break your application into smaller pieces and compose
/// them together.
///
/// ```
/// use axum::{
/// handler::get,
/// Router,
/// };
/// use http::Uri;
///
/// async fn users_get(uri: Uri) {
/// // `uri` will be `/users` since `nest` strips the matching prefix.
/// // use `OriginalUri` to always get the full URI.
/// }
///
/// async fn users_post() {}
///
/// async fn careers() {}
///
/// let users_api = Router::new().route("/users", get(users_get).post(users_post));
///
/// let app = Router::new()
/// .nest("/api", users_api)
/// .route("/careers", get(careers));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// Note that nested routes will not see the orignal request URI but instead
/// have the matched prefix stripped. This is necessary for services like static
/// file serving to work. Use [`OriginalUri`] if you need the original request
/// URI.
///
/// Take care when using `nest` together with dynamic routes as nesting also
/// captures from the outer routes:
///
/// ```
/// use axum::{
/// extract::Path,
/// handler::get,
/// Router,
/// };
/// use std::collections::HashMap;
///
/// async fn users_get(Path(params): Path<HashMap<String, String>>) {
/// // Both `version` and `id` were captured even though `users_api` only
/// // explicitly captures `id`.
/// let version = params.get("version");
/// let id = params.get("id");
/// }
///
/// let users_api = Router::new().route("/users/:id", get(users_get));
///
/// let app = Router::new().nest("/:version/api", users_api);
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// `nest` also accepts any [`Service`]. This can for example be used with
/// [`tower_http::services::ServeDir`] to serve static files from a directory:
///
/// ```
/// use axum::{
/// Router,
/// service::get,
/// };
/// use tower_http::services::ServeDir;
///
/// // Serves files inside the `public` directory at `GET /public/*`
/// let serve_dir_service = ServeDir::new("public");
///
/// let app = Router::new().nest("/public", get(serve_dir_service));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// If necessary you can use [`Router::boxed`] to box a group of routes
/// making the type easier to name. This is sometimes useful when working with
/// `nest`.
///
/// [`OriginalUri`]: crate::extract::OriginalUri
pub fn nest<T>(self, path: &str, svc: T) -> Router<Nested<T, S>> {
self.map(|fallback| Nested {
pattern: PathPattern::new(path),
svc,
fallback,
})
}
/// Create a boxed route trait object.
///
/// This makes it easier to name the types of routers to, for example,
/// return them from functions:
///
/// ```rust
/// use axum::{
/// body::Body,
/// handler::get,
/// Router,
/// routing::BoxRoute
/// };
///
/// async fn first_handler() { /* ... */ }
///
/// async fn second_handler() { /* ... */ }
///
/// async fn third_handler() { /* ... */ }
///
/// fn app() -> Router<BoxRoute> {
/// Router::new()
/// .route("/", get(first_handler).post(second_handler))
/// .route("/foo", get(third_handler))
/// .boxed()
/// }
/// ```
///
/// It also helps with compile times when you have a very large number of
/// routes.
pub fn boxed<ReqBody, ResBody>(self) -> Router<BoxRoute<ReqBody, S::Error>>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>> + Send + 'static,
S::Error: Into<BoxError> + Send,
S::Future: Send,
ReqBody: Send + 'static,
ResBody: http_body::Body<Data = Bytes> + Send + Sync + 'static,
ResBody::Error: Into<BoxError>,
{
self.map(|svc| {
ServiceBuilder::new()
.layer_fn(BoxRoute)
.layer_fn(MpscBuffer::new)
.layer(BoxService::layer())
.layer(MapResponseBodyLayer::new(box_body))
.service(svc)
})
}
/// Apply a [`tower::Layer`] to the router.
///
/// All requests to the router will be processed by the layer's
/// corresponding middleware.
///
/// This can be used to add additional processing to a request for a group
/// of routes.
///
/// Note this differs from [`handler::Layered`](crate::handler::Layered)
/// which adds a middleware to a single handler.
///
/// # Example
///
/// Adding the [`tower::limit::ConcurrencyLimit`] middleware to a group of
/// routes can be done like so:
///
/// ```rust
/// use axum::{
/// handler::get,
/// Router,
/// };
/// use tower::limit::{ConcurrencyLimitLayer, ConcurrencyLimit};
///
/// async fn first_handler() { /* ... */ }
///
/// async fn second_handler() { /* ... */ }
///
/// async fn third_handler() { /* ... */ }
///
/// // All requests to `handler` and `other_handler` will be sent through
/// // `ConcurrencyLimit`
/// let app = Router::new().route("/", get(first_handler))
/// .route("/foo", get(second_handler))
/// .layer(ConcurrencyLimitLayer::new(64))
/// // Request to `GET /bar` will go directly to `third_handler` and
/// // wont be sent through `ConcurrencyLimit`
/// .route("/bar", get(third_handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// This is commonly used to add middleware such as tracing/logging to your
/// entire app:
///
/// ```rust
/// use axum::{
/// handler::get,
/// Router,
/// };
/// use tower_http::trace::TraceLayer;
///
/// async fn first_handler() { /* ... */ }
///
/// async fn second_handler() { /* ... */ }
///
/// async fn third_handler() { /* ... */ }
///
/// let app = Router::new()
/// .route("/", get(first_handler))
/// .route("/foo", get(second_handler))
/// .route("/bar", get(third_handler))
/// .layer(TraceLayer::new_for_http());
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn layer<L>(self, layer: L) -> Router<Layered<L::Service>>
where
L: Layer<S>,
{
self.map(|svc| Layered::new(layer.layer(svc)))
}
/// Convert this router into a [`MakeService`], that is a [`Service`] who's
/// response is another service.
///
/// This is useful when running your application with hyper's
/// [`Server`](hyper::server::Server):
///
/// ```
/// use axum::{
/// handler::get,
/// Router,
/// };
///
/// let app = Router::new().route("/", get(|| async { "Hi!" }));
///
/// # async {
/// axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
/// .serve(app.into_make_service())
/// .await
/// .expect("server failed");
/// # };
/// ```
///
/// [`MakeService`]: tower::make::MakeService
pub fn into_make_service(self) -> IntoMakeService<S>
where
S: Clone,
{
IntoMakeService::new(self.svc)
}
/// Convert this router into a [`MakeService`], that will store `C`'s
/// associated `ConnectInfo` in a request extension such that [`ConnectInfo`]
/// can extract it.
///
/// This enables extracting things like the client's remote address.
///
/// Extracting [`std::net::SocketAddr`] is supported out of the box:
///
/// ```
/// use axum::{
/// extract::ConnectInfo,
/// handler::get,
/// Router,
/// };
/// use std::net::SocketAddr;
///
/// let app = Router::new().route("/", get(handler));
///
/// async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
/// format!("Hello {}", addr)
/// }
///
/// # async {
/// axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
/// .serve(
/// app.into_make_service_with_connect_info::<SocketAddr, _>()
/// )
/// .await
/// .expect("server failed");
/// # };
/// ```
///
/// You can implement custom a [`Connected`] like so:
///
/// ```
/// use axum::{
/// extract::connect_info::{ConnectInfo, Connected},
/// handler::get,
/// Router,
/// };
/// use hyper::server::conn::AddrStream;
///
/// let app = Router::new().route("/", get(handler));
///
/// async fn handler(
/// ConnectInfo(my_connect_info): ConnectInfo<MyConnectInfo>,
/// ) -> String {
/// format!("Hello {:?}", my_connect_info)
/// }
///
/// #[derive(Clone, Debug)]
/// struct MyConnectInfo {
/// // ...
/// }
///
/// impl Connected<&AddrStream> for MyConnectInfo {
/// type ConnectInfo = MyConnectInfo;
///
/// fn connect_info(target: &AddrStream) -> Self::ConnectInfo {
/// MyConnectInfo {
/// // ...
/// }
/// }
/// }
///
/// # async {
/// axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
/// .serve(
/// app.into_make_service_with_connect_info::<MyConnectInfo, _>()
/// )
/// .await
/// .expect("server failed");
/// # };
/// ```
///
/// See the [unix domain socket example][uds] for an example of how to use
/// this to collect UDS connection info.
///
/// [`MakeService`]: tower::make::MakeService
/// [`Connected`]: crate::extract::connect_info::Connected
/// [`ConnectInfo`]: crate::extract::connect_info::ConnectInfo
/// [uds]: https://github.com/tokio-rs/axum/blob/main/examples/unix_domain_socket.rs
pub fn into_make_service_with_connect_info<C, Target>(
self,
) -> IntoMakeServiceWithConnectInfo<S, C>
where
S: Clone,
C: Connected<Target>,
{
IntoMakeServiceWithConnectInfo::new(self.svc)
}
/// Merge two routers into one.
///
/// This is useful for breaking apps into smaller pieces and combining them
/// into one.
///
/// ```
/// use axum::{
/// handler::get,
/// Router,
/// };
/// #
/// # async fn users_list() {}
/// # async fn users_show() {}
/// # async fn teams_list() {}
///
/// // define some routes separately
/// let user_routes = Router::new()
/// .route("/users", get(users_list))
/// .route("/users/:id", get(users_show));
///
/// let team_routes = Router::new().route("/teams", get(teams_list));
///
/// // combine them into one
/// let app = user_routes.or(team_routes);
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn or<S2>(self, other: S2) -> Router<Or<S, S2>> {
self.map(|first| Or {
first,
second: other,
})
}
/// Handle errors services in this router might produce, by mapping them to
/// responses.
///
/// Unhandled errors will close the connection without sending a response.
///
/// # Example
///
/// ```
/// use axum::{
/// handler::get,
/// http::StatusCode,
/// Router,
/// };
/// use tower::{BoxError, timeout::TimeoutLayer};
/// use std::{time::Duration, convert::Infallible};
///
/// // This router can never fail, since handlers can never fail.
/// let app = Router::new().route("/", get(|| async {}));
///
/// // Now the router can fail since the `tower::timeout::Timeout`
/// // middleware will return an error if the timeout elapses.
/// let app = app.layer(TimeoutLayer::new(Duration::from_secs(10)));
///
/// // With `handle_error` we can handle errors `Timeout` might produce.
/// // Our router now cannot fail, that is its error type is `Infallible`.
/// let app = app.handle_error(|error: BoxError| {
/// if error.is::<tower::timeout::error::Elapsed>() {
/// Ok::<_, Infallible>((
/// StatusCode::REQUEST_TIMEOUT,
/// "request took too long to handle".to_string(),
/// ))
/// } else {
/// Ok::<_, Infallible>((
/// StatusCode::INTERNAL_SERVER_ERROR,
/// format!("Unhandled error: {}", error),
/// ))
/// }
/// });
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// You can return `Err(_)` from the closure if you don't wish to handle
/// some errors:
///
/// ```
/// use axum::{
/// handler::get,
/// http::StatusCode,
/// Router,
/// };
/// use tower::{BoxError, timeout::TimeoutLayer};
/// use std::time::Duration;
///
/// let app = Router::new()
/// .route("/", get(|| async {}))
/// .layer(TimeoutLayer::new(Duration::from_secs(10)))
/// .handle_error(|error: BoxError| {
/// if error.is::<tower::timeout::error::Elapsed>() {
/// Ok((
/// StatusCode::REQUEST_TIMEOUT,
/// "request took too long to handle".to_string(),
/// ))
/// } else {
/// // return the error as is
/// Err(error)
/// }
/// });
/// # async {
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn handle_error<ReqBody, F>(self, f: F) -> Router<HandleError<S, F, ReqBody>> {
self.map(|svc| HandleError::new(svc, f))
}
/// Check that your service cannot fail.
///
/// That is, its error type is [`Infallible`].
pub fn check_infallible(self) -> Router<CheckInfallible<S>> {
self.map(CheckInfallible)
}
fn map<F, S2>(self, f: F) -> Router<S2>
where
F: FnOnce(S) -> S2,
{
Router { svc: f(self.svc) }
}
}
/// A route that sends requests to one of two [`Service`]s depending on the
/// path.
#[derive(Debug, Clone)]
pub struct Route<S, F> {
pub(crate) pattern: PathPattern,
pub(crate) svc: S,
pub(crate) fallback: F,
}
impl<S, F, B> Service<Request<B>> for Route<S, F>
where
S: Service<Request<B>, Response = Response<BoxBody>> + Clone,
F: Service<Request<B>, Response = Response<BoxBody>, Error = S::Error> + Clone,
B: Send + Sync + 'static,
{
type Response = Response<BoxBody>;
type Error = S::Error;
type Future = RouteFuture<S, F, B>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, mut req: Request<B>) -> Self::Future {
if let Some(captures) = self.pattern.full_match(&req) {
insert_url_params(&mut req, captures);
let fut = self.svc.clone().oneshot(req);
RouteFuture::a(fut, self.fallback.clone())
} else {
let fut = self.fallback.clone().oneshot(req);
RouteFuture::b(fut)
}
}
}
#[derive(Debug)]
pub(crate) struct UrlParams(pub(crate) Vec<(ByteStr, ByteStr)>);
fn insert_url_params<B>(req: &mut Request<B>, params: Vec<(String, String)>) {
let params = params
.into_iter()
.map(|(k, v)| (ByteStr::new(k), ByteStr::new(v)));
if let Some(current) = req.extensions_mut().get_mut::<Option<UrlParams>>() {
let mut current = current.take().unwrap();
current.0.extend(params);
req.extensions_mut().insert(Some(current));
} else {
req.extensions_mut()
.insert(Some(UrlParams(params.collect())));
}
}
/// A [`Service`] that responds with `404 Not Found` or `405 Method not allowed`
/// to all requests.
///
/// This is used as the bottom service in a router stack. You shouldn't have to
/// use it manually.
pub struct EmptyRouter<E = Infallible> {
status: StatusCode,
_marker: PhantomData<fn() -> E>,
}
impl<E> EmptyRouter<E> {
pub(crate) fn not_found() -> Self {
Self {
status: StatusCode::NOT_FOUND,
_marker: PhantomData,
}
}
pub(crate) fn method_not_allowed() -> Self {
Self {
status: StatusCode::METHOD_NOT_ALLOWED,
_marker: PhantomData,
}
}
}
impl<E> Clone for EmptyRouter<E> {
fn clone(&self) -> Self {
Self {
status: self.status,
_marker: PhantomData,
}
}
}
impl<E> fmt::Debug for EmptyRouter<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("EmptyRouter").finish()
}
}
impl<B, E> Service<Request<B>> for EmptyRouter<E>
where
B: Send + Sync + 'static,
{
type Response = Response<BoxBody>;
type Error = E;
type Future = EmptyRouterFuture<E>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, mut request: Request<B>) -> Self::Future {
if self.status == StatusCode::METHOD_NOT_ALLOWED {
// we're inside a route but there was no method that matched
// so record that so we can override the status if no other
// routes match
request.extensions_mut().insert(NoMethodMatch);
}
if self.status == StatusCode::NOT_FOUND
&& request.extensions().get::<NoMethodMatch>().is_some()
{
self.status = StatusCode::METHOD_NOT_ALLOWED;
}
let mut res = Response::new(crate::body::empty());
res.extensions_mut().insert(FromEmptyRouter { request });
*res.status_mut() = self.status;
EmptyRouterFuture {
future: ready(Ok(res)),
}
}
}
#[derive(Clone, Copy)]
struct NoMethodMatch;
/// Response extension used by [`EmptyRouter`] to send the request back to [`Or`] so
/// the other service can be called.
///
/// Without this we would loose ownership of the request when calling the first
/// service in [`Or`]. We also wouldn't be able to identify if the response came
/// from [`EmptyRouter`] and therefore can be discarded in [`Or`].
struct FromEmptyRouter<B> {
request: Request<B>,
}
#[derive(Debug, Clone)]
pub(crate) struct PathPattern(Arc<Inner>);
#[derive(Debug)]
struct Inner {
full_path_regex: Regex,
capture_group_names: Box<[Bytes]>,
}
impl PathPattern {
pub(crate) fn new(pattern: &str) -> Self {
assert!(pattern.starts_with('/'), "Route path must start with a `/`");
let mut capture_group_names = Vec::new();
let pattern = pattern
.split('/')
.map(|part| {
if let Some(key) = part.strip_prefix(':') {
capture_group_names.push(Bytes::copy_from_slice(key.as_bytes()));
Cow::Owned(format!("(?P<{}>[^/]+)", key))
} else {
Cow::Borrowed(part)
}
})
.collect::<Vec<_>>()
.join("/");
let full_path_regex =
Regex::new(&format!("^{}", pattern)).expect("invalid regex generated from route");
Self(Arc::new(Inner {
full_path_regex,
capture_group_names: capture_group_names.into(),
}))
}
pub(crate) fn full_match<B>(&self, req: &Request<B>) -> Option<Captures> {
self.do_match(req).and_then(|match_| {
if match_.full_match {
Some(match_.captures)
} else {
None
}
})
}
pub(crate) fn prefix_match<'a, B>(&self, req: &'a Request<B>) -> Option<(&'a str, Captures)> {
self.do_match(req)
.map(|match_| (match_.matched, match_.captures))
}
fn do_match<'a, B>(&self, req: &'a Request<B>) -> Option<Match<'a>> {
let path = req.uri().path();
self.0.full_path_regex.captures(path).map(|captures| {
let matched = captures.get(0).unwrap();
let full_match = matched.as_str() == path;
let captures = self
.0
.capture_group_names
.iter()
.map(|bytes| {
std::str::from_utf8(bytes)
.expect("bytes were created from str so is valid utf-8")
})
.filter_map(|name| captures.name(name).map(|value| (name, value.as_str())))
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<Vec<_>>();
Match {
captures,
full_match,
matched: matched.as_str(),
}
})
}
}
struct Match<'a> {
captures: Captures,
// true if regex matched whole path, false if it only matched a prefix
full_match: bool,
matched: &'a str,
}
type Captures = Vec<(String, String)>;
/// A boxed route trait object.
///
/// See [`Router::boxed`] for more details.
pub struct BoxRoute<B = crate::body::Body, E = Infallible>(
MpscBuffer<BoxService<Request<B>, Response<BoxBody>, E>, Request<B>>,
);
impl<B, E> Clone for BoxRoute<B, E> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<B, E> fmt::Debug for BoxRoute<B, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BoxRoute").finish()
}
}
impl<B, E> Service<Request<B>> for BoxRoute<B, E>
where
E: Into<BoxError>,
{
type Response = Response<BoxBody>;
type Error = E;
type Future = BoxRouteFuture<B, E>;
#[inline]
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
#[inline]
fn call(&mut self, req: Request<B>) -> Self::Future {
BoxRouteFuture {
inner: self.0.clone().oneshot(req),
}
}
}
/// A [`Service`] created from a router by applying a Tower middleware.
///
/// Created with [`Router::layer`]. See that method for more details.
pub struct Layered<S> {
inner: S,
}
impl<S> Layered<S> {
fn new(inner: S) -> Self {
Self { inner }
}
}
impl<S> Clone for Layered<S>
where
S: Clone,
{
fn clone(&self) -> Self {
Self::new(self.inner.clone())
}
}
impl<S> fmt::Debug for Layered<S>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Layered")
.field("inner", &self.inner)
.finish()
}
}
impl<S, R> Service<R> for Layered<S>
where
S: Service<R>,
{
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
#[inline]
fn call(&mut self, req: R) -> Self::Future {
self.inner.call(req)
}
}
/// A [`Service`] that has been nested inside a router at some path.
///
/// Created with [`Router::nest`].
#[derive(Debug, Clone)]
pub struct Nested<S, F> {
pattern: PathPattern,
svc: S,
fallback: F,
}
impl<S, F, B> Service<Request<B>> for Nested<S, F>
where
S: Service<Request<B>, Response = Response<BoxBody>> + Clone,
F: Service<Request<B>, Response = Response<BoxBody>, Error = S::Error> + Clone,
B: Send + Sync + 'static,
{
type Response = Response<BoxBody>;
type Error = S::Error;
type Future = NestedFuture<S, F, B>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, mut req: Request<B>) -> Self::Future {
if req.extensions().get::<OriginalUri>().is_none() {
let original_uri = OriginalUri(req.uri().clone());
req.extensions_mut().insert(original_uri);
}
let f = if let Some((prefix, captures)) = self.pattern.prefix_match(&req) {
let without_prefix = strip_prefix(req.uri(), prefix);
*req.uri_mut() = without_prefix;
insert_url_params(&mut req, captures);
let fut = self.svc.clone().oneshot(req);
RouteFuture::a(fut, self.fallback.clone())
} else {
let fut = self.fallback.clone().oneshot(req);
RouteFuture::b(fut)
};
NestedFuture { inner: f }
}
}
fn strip_prefix(uri: &Uri, prefix: &str) -> Uri {
let path_and_query = if let Some(path_and_query) = uri.path_and_query() {
let new_path = if let Some(path) = path_and_query.path().strip_prefix(prefix) {
path
} else {
path_and_query.path()
};
let new_path = if new_path.starts_with('/') {
Cow::Borrowed(new_path)
} else {
Cow::Owned(format!("/{}", new_path))
};
if let Some(query) = path_and_query.query() {
Some(
format!("{}?{}", new_path, query)
.parse::<http::uri::PathAndQuery>()
.unwrap(),
)
} else {
Some(new_path.parse().unwrap())
}
} else {
None
};
let mut parts = http::uri::Parts::default();
parts.scheme = uri.scheme().cloned();
parts.authority = uri.authority().cloned();
parts.path_and_query = path_and_query;
Uri::from_parts(parts).unwrap()
}
/// Middleware that statically verifies that a service cannot fail.
///
/// Created with [`check_infallible`](Router::check_infallible).
#[derive(Debug, Clone, Copy)]
pub struct CheckInfallible<S>(S);
impl<R, S> Service<R> for CheckInfallible<S>
where
S: Service<R, Error = Infallible>,
{
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.poll_ready(cx)
}
#[inline]
fn call(&mut self, req: R) -> Self::Future {
self.0.call(req)
}
}
/// A [`MakeService`] that produces axum router services.
///
/// [`MakeService`]: tower::make::MakeService
#[derive(Debug, Clone)]
pub struct IntoMakeService<S> {
service: S,
}
impl<S> IntoMakeService<S> {
fn new(service: S) -> Self {
Self { service }
}
}
impl<S, T> Service<T> for IntoMakeService<S>
where
S: Clone,
{
type Response = S;
type Error = Infallible;
type Future = future::MakeRouteServiceFuture<S>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _target: T) -> Self::Future {
future::MakeRouteServiceFuture {
future: ready(Ok(self.service.clone())),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_routing() {
assert_match("/", "/");
assert_match("/foo", "/foo");
assert_match("/foo/", "/foo/");
refute_match("/foo", "/foo/");
refute_match("/foo/", "/foo");
assert_match("/foo/bar", "/foo/bar");
refute_match("/foo/bar/", "/foo/bar");
refute_match("/foo/bar", "/foo/bar/");
assert_match("/:value", "/foo");
assert_match("/users/:id", "/users/1");
assert_match("/users/:id/action", "/users/42/action");
refute_match("/users/:id/action", "/users/42");
refute_match("/users/:id", "/users/42/action");
}
fn assert_match(route_spec: &'static str, path: &'static str) {
let route = PathPattern::new(route_spec);
let req = Request::builder().uri(path).body(()).unwrap();
assert!(
route.full_match(&req).is_some(),
"`{}` doesn't match `{}`",
path,
route_spec
);
}
fn refute_match(route_spec: &'static str, path: &'static str) {
let route = PathPattern::new(route_spec);
let req = Request::builder().uri(path).body(()).unwrap();
assert!(
route.full_match(&req).is_none(),
"`{}` did match `{}` (but shouldn't)",
path,
route_spec
);
}
#[test]
fn traits() {
use crate::tests::*;
assert_send::<Router<()>>();
assert_sync::<Router<()>>();
assert_send::<Route<(), ()>>();
assert_sync::<Route<(), ()>>();
assert_send::<EmptyRouter<NotSendSync>>();
assert_sync::<EmptyRouter<NotSendSync>>();
assert_send::<BoxRoute<(), ()>>();
assert_sync::<BoxRoute<(), ()>>();
assert_send::<Layered<()>>();
assert_sync::<Layered<()>>();
assert_send::<Nested<(), ()>>();
assert_sync::<Nested<(), ()>>();
assert_send::<CheckInfallible<()>>();
assert_sync::<CheckInfallible<()>>();
assert_send::<IntoMakeService<()>>();
assert_sync::<IntoMakeService<()>>();
}
}
<file_sep>mod model;
use async_graphql::{EmptyMutation, EmptySubscription, Schema};
use model::Episode;
use slab::Slab;
use std::collections::HashMap;
pub use model::QueryRoot;
pub type StarWarsSchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;
pub struct StarWarsChar {
id: &'static str,
name: &'static str,
friends: Vec<usize>,
appears_in: Vec<Episode>,
home_planet: Option<&'static str>,
primary_function: Option<&'static str>,
}
pub struct StarWars {
luke: usize,
artoo: usize,
chars: Slab<StarWarsChar>,
human_data: HashMap<&'static str, usize>,
droid_data: HashMap<&'static str, usize>,
}
impl StarWars {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
let mut chars = Slab::new();
let luke = chars.insert(StarWarsChar {
id: "1000",
name: "<NAME>",
friends: vec![],
appears_in: vec![],
home_planet: Some("Tatooine"),
primary_function: None,
});
let vader = chars.insert(StarWarsChar {
id: "1001",
name: "<NAME>",
friends: vec![],
appears_in: vec![],
home_planet: Some("Tatooine"),
primary_function: None,
});
let han = chars.insert(StarWarsChar {
id: "1002",
name: "<NAME>",
friends: vec![],
appears_in: vec![Episode::Empire, Episode::NewHope, Episode::Jedi],
home_planet: None,
primary_function: None,
});
let leia = chars.insert(StarWarsChar {
id: "1003",
name: "<NAME>",
friends: vec![],
appears_in: vec![Episode::Empire, Episode::NewHope, Episode::Jedi],
home_planet: Some("Alderaa"),
primary_function: None,
});
let tarkin = chars.insert(StarWarsChar {
id: "1004",
name: "<NAME>",
friends: vec![],
appears_in: vec![Episode::Empire, Episode::NewHope, Episode::Jedi],
home_planet: None,
primary_function: None,
});
let threepio = chars.insert(StarWarsChar {
id: "2000",
name: "C-3PO",
friends: vec![],
appears_in: vec![Episode::Empire, Episode::NewHope, Episode::Jedi],
home_planet: None,
primary_function: Some("Protocol"),
});
let artoo = chars.insert(StarWarsChar {
id: "2001",
name: "R2-D2",
friends: vec![],
appears_in: vec![Episode::Empire, Episode::NewHope, Episode::Jedi],
home_planet: None,
primary_function: Some("Astromech"),
});
chars[luke].friends = vec![han, leia, threepio, artoo];
chars[vader].friends = vec![tarkin];
chars[han].friends = vec![luke, leia, artoo];
chars[leia].friends = vec![luke, han, threepio, artoo];
chars[tarkin].friends = vec![vader];
chars[threepio].friends = vec![luke, han, leia, artoo];
chars[artoo].friends = vec![luke, han, leia];
let mut human_data = HashMap::new();
human_data.insert("1000", luke);
human_data.insert("1001", vader);
human_data.insert("1002", han);
human_data.insert("1003", leia);
human_data.insert("1004", tarkin);
let mut droid_data = HashMap::new();
droid_data.insert("2000", threepio);
droid_data.insert("2001", artoo);
Self {
luke,
artoo,
chars,
human_data,
droid_data,
}
}
pub fn human(&self, id: &str) -> Option<usize> {
self.human_data.get(id).cloned()
}
pub fn droid(&self, id: &str) -> Option<usize> {
self.droid_data.get(id).cloned()
}
pub fn humans(&self) -> Vec<usize> {
self.human_data.values().cloned().collect()
}
pub fn droids(&self) -> Vec<usize> {
self.droid_data.values().cloned().collect()
}
}
<file_sep>use super::Handler;
use crate::body::BoxBody;
use http::{Request, Response};
use std::{
convert::Infallible,
fmt,
marker::PhantomData,
task::{Context, Poll},
};
use tower_service::Service;
/// An adapter that makes a [`Handler`] into a [`Service`].
///
/// Created with [`Handler::into_service`].
pub struct IntoService<H, B, T> {
handler: H,
_marker: PhantomData<fn() -> (B, T)>,
}
#[test]
fn traits() {
use crate::tests::*;
assert_send::<IntoService<(), NotSendSync, NotSendSync>>();
assert_sync::<IntoService<(), NotSendSync, NotSendSync>>();
}
impl<H, B, T> IntoService<H, B, T> {
pub(super) fn new(handler: H) -> Self {
Self {
handler,
_marker: PhantomData,
}
}
}
impl<H, B, T> fmt::Debug for IntoService<H, B, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("IntoService")
.field(&format_args!("..."))
.finish()
}
}
impl<H, B, T> Clone for IntoService<H, B, T>
where
H: Clone,
{
fn clone(&self) -> Self {
Self {
handler: self.handler.clone(),
_marker: PhantomData,
}
}
}
impl<H, T, B> Service<Request<B>> for IntoService<H, B, T>
where
H: Handler<B, T> + Clone + Send + 'static,
B: Send + 'static,
{
type Response = Response<BoxBody>;
type Error = Infallible;
type Future = super::future::IntoServiceFuture;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
// `IntoService` can only be constructed from async functions which are always ready, or from
// `Layered` which bufferes in `<Layered as Handler>::call` and is therefore also always
// ready.
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<B>) -> Self::Future {
use futures_util::future::FutureExt;
let handler = self.handler.clone();
let future = Handler::call(handler, req).map(Ok::<_, Infallible> as _);
super::future::IntoServiceFuture { future }
}
}
<file_sep>use super::{FromRequest, RequestParts};
use crate::{
body::{box_body, BoxBody},
response::IntoResponse,
};
use async_trait::async_trait;
use http::Response;
use std::convert::Infallible;
#[async_trait]
impl<B> FromRequest<B> for ()
where
B: Send,
{
type Rejection = Infallible;
async fn from_request(_: &mut RequestParts<B>) -> Result<(), Self::Rejection> {
Ok(())
}
}
macro_rules! impl_from_request {
() => {
};
( $head:ident, $($tail:ident),* $(,)? ) => {
#[async_trait]
#[allow(non_snake_case)]
impl<B, $head, $($tail,)*> FromRequest<B> for ($head, $($tail,)*)
where
$head: FromRequest<B> + Send,
$( $tail: FromRequest<B> + Send, )*
B: Send,
{
type Rejection = Response<BoxBody>;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let $head = $head::from_request(req).await.map_err(|err| err.into_response().map(box_body))?;
$( let $tail = $tail::from_request(req).await.map_err(|err| err.into_response().map(box_body))?; )*
Ok(($head, $($tail,)*))
}
}
impl_from_request!($($tail,)*);
};
}
impl_from_request!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
<file_sep>use super::{FromRequest, RequestParts};
use async_trait::async_trait;
use std::convert::Infallible;
/// Extractor that extracts the raw query string, without parsing it.
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// extract::RawQuery,
/// handler::get,
/// Router,
/// };
/// use futures::StreamExt;
///
/// async fn handler(RawQuery(query): RawQuery) {
/// // ...
/// }
///
/// let app = Router::new().route("/users", get(handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
#[derive(Debug)]
pub struct RawQuery(pub Option<String>);
#[async_trait]
impl<B> FromRequest<B> for RawQuery
where
B: Send,
{
type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let query = req.uri().query().map(|query| query.to_string());
Ok(Self(query))
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-static-file-server
//! ```
use axum::{http::StatusCode, service, Router};
use std::{convert::Infallible, net::SocketAddr};
use tower_http::{services::ServeDir, trace::TraceLayer};
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var(
"RUST_LOG",
"example_static_file_server=debug,tower_http=debug",
)
}
tracing_subscriber::fmt::init();
let app = Router::new()
.nest(
"/static",
service::get(ServeDir::new(".")).handle_error(|error: std::io::Error| {
Ok::<_, Infallible>((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
))
}),
)
.layer(TraceLayer::new_for_http());
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-tls-rustls
//! ```
use axum::{handler::get, Router};
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_tls_rustls=debug")
}
tracing_subscriber::fmt::init();
let app = Router::new().route("/", get(handler));
axum_server::bind_rustls("127.0.0.1:3000")
.private_key_file("examples/tls-rustls/self_signed_certs/key.pem")
.certificate_file("examples/tls-rustls/self_signed_certs/cert.pem")
.serve(app)
.await
.unwrap();
}
async fn handler() -> &'static str {
"Hello, World!"
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-templates
//! ```
use askama::Template;
use axum::{
body::{Bytes, Full},
extract,
handler::get,
http::{Response, StatusCode},
response::{Html, IntoResponse},
Router,
};
use std::{convert::Infallible, net::SocketAddr};
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_templates=debug")
}
tracing_subscriber::fmt::init();
// build our application with some routes
let app = Router::new().route("/greet/:name", get(greet));
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn greet(extract::Path(name): extract::Path<String>) -> impl IntoResponse {
let template = HelloTemplate { name };
HtmlTemplate(template)
}
#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate {
name: String,
}
struct HtmlTemplate<T>(T);
impl<T> IntoResponse for HtmlTemplate<T>
where
T: Template,
{
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
match self.0.render() {
Ok(html) => Html(html).into_response(),
Err(err) => Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Full::from(format!(
"Failed to render template. Error: {}",
err
)))
.unwrap(),
}
}
}
<file_sep>[package]
name = "example-error-handling-and-dependency-injection"
version = "0.1.0"
edition = "2018"
publish = false
[dependencies]
axum = { path = "../.." }
tokio = { version = "1.0", features = ["full"] }
tower = { version = "0.4", features = ["util"] }
tracing = "0.1"
tracing-subscriber = "0.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
uuid = { version = "0.8", features = ["v4", "serde"] }
<file_sep>use super::{rejection::*, FromRequest, RequestParts};
use async_trait::async_trait;
use serde::de::DeserializeOwned;
use std::ops::Deref;
/// Extractor that deserializes query strings into some type.
///
/// `T` is expected to implement [`serde::Deserialize`].
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// extract::Query,
/// handler::get,
/// Router,
/// };
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Pagination {
/// page: usize,
/// per_page: usize,
/// }
///
/// // This will parse query strings like `?page=2&per_page=30` into `Pagination`
/// // structs.
/// async fn list_things(pagination: Query<Pagination>) {
/// let pagination: Pagination = pagination.0;
///
/// // ...
/// }
///
/// let app = Router::new().route("/list_things", get(list_things));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// If the query string cannot be parsed it will reject the request with a `400
/// Bad Request` response.
#[derive(Debug, Clone, Copy, Default)]
pub struct Query<T>(pub T);
#[async_trait]
impl<T, B> FromRequest<B> for Query<T>
where
T: DeserializeOwned,
B: Send,
{
type Rejection = QueryRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let query = req.uri().query().unwrap_or_default();
let value = serde_urlencoded::from_str(query)
.map_err(FailedToDeserializeQueryString::new::<T, _>)?;
Ok(Query(value))
}
}
impl<T> Deref for Query<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::extract::RequestParts;
use http::Request;
use serde::Deserialize;
use std::fmt::Debug;
async fn check<T: DeserializeOwned + PartialEq + Debug>(uri: impl AsRef<str>, value: T) {
let mut req = RequestParts::new(Request::builder().uri(uri.as_ref()).body(()).unwrap());
assert_eq!(Query::<T>::from_request(&mut req).await.unwrap().0, value);
}
#[tokio::test]
async fn test_query() {
#[derive(Debug, PartialEq, Deserialize)]
struct Pagination {
size: Option<u64>,
page: Option<u64>,
}
check(
"http://example.com/test",
Pagination {
size: None,
page: None,
},
)
.await;
check(
"http://example.com/test?size=10",
Pagination {
size: Some(10),
page: None,
},
)
.await;
check(
"http://example.com/test?size=10&page=20",
Pagination {
size: Some(10),
page: Some(20),
},
)
.await;
}
}
<file_sep>use bytes::Bytes;
use pin_project_lite::pin_project;
use std::ops::Deref;
/// A string like type backed by `Bytes` making it cheap to clone.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct ByteStr(Bytes);
impl Deref for ByteStr {
type Target = str;
#[inline]
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl ByteStr {
pub(crate) fn new<S>(s: S) -> Self
where
S: AsRef<str>,
{
Self(Bytes::copy_from_slice(s.as_ref().as_bytes()))
}
pub(crate) fn as_str(&self) -> &str {
// `ByteStr` can only be constructed from strings which are always valid
// utf-8 so this wont panic.
std::str::from_utf8(&self.0).unwrap()
}
}
pin_project! {
#[project = EitherProj]
pub(crate) enum Either<A, B> {
A { #[pin] inner: A },
B { #[pin] inner: B },
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-low-level-rustls
//! ```
use axum::{handler::get, Router};
use hyper::server::conn::Http;
use std::{fs::File, io::BufReader, sync::Arc};
use tokio::net::TcpListener;
use tokio_rustls::{
rustls::{
internal::pemfile::certs, internal::pemfile::pkcs8_private_keys, NoClientAuth, ServerConfig,
},
TlsAcceptor,
};
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_tls_rustls=debug")
}
tracing_subscriber::fmt::init();
let rustls_config = rustls_server_config(
"examples/tls-rustls/self_signed_certs/key.pem",
"examples/tls-rustls/self_signed_certs/cert.pem",
);
let acceptor = TlsAcceptor::from(rustls_config);
let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
let app = Router::new().route("/", get(handler));
loop {
let (stream, _addr) = listener.accept().await.unwrap();
let acceptor = acceptor.clone();
let app = app.clone();
tokio::spawn(async move {
if let Ok(stream) = acceptor.accept(stream).await {
let _ = Http::new().serve_connection(stream, app).await;
}
});
}
}
async fn handler() -> &'static str {
"Hello, World!"
}
fn rustls_server_config(key: &str, cert: &str) -> Arc<ServerConfig> {
let mut config = ServerConfig::new(NoClientAuth::new());
let mut key_reader = BufReader::new(File::open(key).unwrap());
let mut cert_reader = BufReader::new(File::open(cert).unwrap());
let key = pkcs8_private_keys(&mut key_reader).unwrap().remove(0);
let certs = certs(&mut cert_reader).unwrap();
config.set_single_cert(certs, key).unwrap();
config.set_protocols(&[b"h2".to_vec(), b"http/1.1".to_vec()]);
Arc::new(config)
}
<file_sep>//! Use Tower [`Service`]s to handle requests.
//!
//! Most of the time applications will be written by composing
//! [handlers](crate::handler), however sometimes you might have some general
//! [`Service`] that you want to route requests to. That is enabled by the
//! functions in this module.
//!
//! # Example
//!
//! Using [`Redirect`] to redirect requests can be done like so:
//!
//! ```
//! use tower_http::services::Redirect;
//! use axum::{
//! body::Body,
//! handler::get,
//! http::Request,
//! Router,
//! service,
//! };
//!
//! async fn handler(request: Request<Body>) { /* ... */ }
//!
//! let redirect_service = Redirect::<Body>::permanent("/new".parse().unwrap());
//!
//! let app = Router::new()
//! .route("/old", service::get(redirect_service))
//! .route("/new", get(handler));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! # Regarding backpressure and `Service::poll_ready`
//!
//! Generally routing to one of multiple services and backpressure doesn't mix
//! well. Ideally you would want ensure a service is ready to receive a request
//! before calling it. However, in order to know which service to call, you need
//! the request...
//!
//! One approach is to not consider the router service itself ready until all
//! destination services are ready. That is the approach used by
//! [`tower::steer::Steer`].
//!
//! Another approach is to always consider all services ready (always return
//! `Poll::Ready(Ok(()))`) from `Service::poll_ready` and then actually drive
//! readiness inside the response future returned by `Service::call`. This works
//! well when your services don't care about backpressure and are always ready
//! anyway.
//!
//! axum expects that all services used in your app wont care about
//! backpressure and so it uses the latter strategy. However that means you
//! should avoid routing to a service (or using a middleware) that _does_ care
//! about backpressure. At the very least you should [load shed] so requests are
//! dropped quickly and don't keep piling up.
//!
//! It also means that if `poll_ready` returns an error then that error will be
//! returned in the response future from `call` and _not_ from `poll_ready`. In
//! that case, the underlying service will _not_ be discarded and will continue
//! to be used for future requests. Services that expect to be discarded if
//! `poll_ready` fails should _not_ be used with axum.
//!
//! One possible approach is to only apply backpressure sensitive middleware
//! around your entire app. This is possible because axum applications are
//! themselves services:
//!
//! ```rust
//! use axum::{
//! handler::get,
//! Router,
//! };
//! use tower::ServiceBuilder;
//! # let some_backpressure_sensitive_middleware =
//! # tower::layer::util::Identity::new();
//!
//! async fn handler() { /* ... */ }
//!
//! let app = Router::new().route("/", get(handler));
//!
//! let app = ServiceBuilder::new()
//! .layer(some_backpressure_sensitive_middleware)
//! .service(app);
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! However when applying middleware around your whole application in this way
//! you have to take care that errors are still being handled with
//! appropriately.
//!
//! Also note that handlers created from async functions don't care about
//! backpressure and are always ready. So if you're not using any Tower
//! middleware you don't have to worry about any of this.
//!
//! [`Redirect`]: tower_http::services::Redirect
//! [load shed]: tower::load_shed
use crate::BoxError;
use crate::{
body::BoxBody,
response::IntoResponse,
routing::{EmptyRouter, MethodFilter},
};
use bytes::Bytes;
use http::{Request, Response};
use std::{
fmt,
marker::PhantomData,
task::{Context, Poll},
};
use tower::{util::Oneshot, ServiceExt as _};
use tower_service::Service;
pub mod future;
/// Route requests to the given service regardless of the HTTP method.
///
/// See [`get`] for an example.
pub fn any<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::all(), svc)
}
/// Route `CONNECT` requests to the given service.
///
/// See [`get`] for an example.
pub fn connect<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::CONNECT, svc)
}
/// Route `DELETE` requests to the given service.
///
/// See [`get`] for an example.
pub fn delete<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::DELETE, svc)
}
/// Route `GET` requests to the given service.
///
/// # Example
///
/// ```rust
/// use axum::{
/// http::Request,
/// Router,
/// service,
/// };
/// use http::Response;
/// use std::convert::Infallible;
/// use hyper::Body;
///
/// let service = tower::service_fn(|request: Request<Body>| async {
/// Ok::<_, Infallible>(Response::new(Body::empty()))
/// });
///
/// // Requests to `GET /` will go to `service`.
/// let app = Router::new().route("/", service::get(service));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// Note that `get` routes will also be called for `HEAD` requests but will have
/// the response body removed. Make sure to add explicit `HEAD` routes
/// afterwards.
pub fn get<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::GET | MethodFilter::HEAD, svc)
}
/// Route `HEAD` requests to the given service.
///
/// See [`get`] for an example.
pub fn head<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::HEAD, svc)
}
/// Route `OPTIONS` requests to the given service.
///
/// See [`get`] for an example.
pub fn options<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::OPTIONS, svc)
}
/// Route `PATCH` requests to the given service.
///
/// See [`get`] for an example.
pub fn patch<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::PATCH, svc)
}
/// Route `POST` requests to the given service.
///
/// See [`get`] for an example.
pub fn post<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::POST, svc)
}
/// Route `PUT` requests to the given service.
///
/// See [`get`] for an example.
pub fn put<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::PUT, svc)
}
/// Route `TRACE` requests to the given service.
///
/// See [`get`] for an example.
pub fn trace<S, B>(svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
on(MethodFilter::TRACE, svc)
}
/// Route requests with the given method to the service.
///
/// # Example
///
/// ```rust
/// use axum::{
/// http::Request,
/// handler::on,
/// service,
/// Router,
/// routing::MethodFilter,
/// };
/// use http::Response;
/// use std::convert::Infallible;
/// use hyper::Body;
///
/// let service = tower::service_fn(|request: Request<Body>| async {
/// Ok::<_, Infallible>(Response::new(Body::empty()))
/// });
///
/// // Requests to `POST /` will go to `service`.
/// let app = Router::new().route("/", service::on(MethodFilter::POST, service));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn on<S, B>(method: MethodFilter, svc: S) -> OnMethod<S, EmptyRouter<S::Error>, B>
where
S: Service<Request<B>> + Clone,
{
OnMethod {
method,
svc,
fallback: EmptyRouter::method_not_allowed(),
_request_body: PhantomData,
}
}
/// A [`Service`] that accepts requests based on a [`MethodFilter`] and allows
/// chaining additional services.
#[derive(Debug)] // TODO(david): don't require debug for B
pub struct OnMethod<S, F, B> {
pub(crate) method: MethodFilter,
pub(crate) svc: S,
pub(crate) fallback: F,
pub(crate) _request_body: PhantomData<fn() -> B>,
}
impl<S, F, B> Clone for OnMethod<S, F, B>
where
S: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
method: self.method,
svc: self.svc.clone(),
fallback: self.fallback.clone(),
_request_body: PhantomData,
}
}
}
impl<S, F, B> OnMethod<S, F, B> {
/// Chain an additional service that will accept all requests regardless of
/// its HTTP method.
///
/// See [`OnMethod::get`] for an example.
pub fn any<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::all(), svc)
}
/// Chain an additional service that will only accept `CONNECT` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn connect<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::CONNECT, svc)
}
/// Chain an additional service that will only accept `DELETE` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn delete<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::DELETE, svc)
}
/// Chain an additional service that will only accept `GET` requests.
///
/// # Example
///
/// ```rust
/// use axum::{
/// http::Request,
/// handler::on,
/// service,
/// Router,
/// routing::MethodFilter,
/// };
/// use http::Response;
/// use std::convert::Infallible;
/// use hyper::Body;
///
/// let service = tower::service_fn(|request: Request<Body>| async {
/// Ok::<_, Infallible>(Response::new(Body::empty()))
/// });
///
/// let other_service = tower::service_fn(|request: Request<Body>| async {
/// Ok::<_, Infallible>(Response::new(Body::empty()))
/// });
///
/// // Requests to `GET /` will go to `service` and `POST /` will go to
/// // `other_service`.
/// let app = Router::new().route("/", service::post(service).get(other_service));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// Note that `get` routes will also be called for `HEAD` requests but will have
/// the response body removed. Make sure to add explicit `HEAD` routes
/// afterwards.
pub fn get<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::GET | MethodFilter::HEAD, svc)
}
/// Chain an additional service that will only accept `HEAD` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn head<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::HEAD, svc)
}
/// Chain an additional service that will only accept `OPTIONS` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn options<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::OPTIONS, svc)
}
/// Chain an additional service that will only accept `PATCH` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn patch<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::PATCH, svc)
}
/// Chain an additional service that will only accept `POST` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn post<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::POST, svc)
}
/// Chain an additional service that will only accept `PUT` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn put<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::PUT, svc)
}
/// Chain an additional service that will only accept `TRACE` requests.
///
/// See [`OnMethod::get`] for an example.
pub fn trace<T>(self, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
self.on(MethodFilter::TRACE, svc)
}
/// Chain an additional service that will accept requests matching the given
/// `MethodFilter`.
///
/// # Example
///
/// ```rust
/// use axum::{
/// http::Request,
/// handler::on,
/// service,
/// Router,
/// routing::MethodFilter,
/// };
/// use http::Response;
/// use std::convert::Infallible;
/// use hyper::Body;
///
/// let service = tower::service_fn(|request: Request<Body>| async {
/// Ok::<_, Infallible>(Response::new(Body::empty()))
/// });
///
/// let other_service = tower::service_fn(|request: Request<Body>| async {
/// Ok::<_, Infallible>(Response::new(Body::empty()))
/// });
///
/// // Requests to `DELETE /` will go to `service`
/// let app = Router::new().route("/", service::on(MethodFilter::DELETE, service));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn on<T>(self, method: MethodFilter, svc: T) -> OnMethod<T, Self, B>
where
T: Service<Request<B>> + Clone,
{
OnMethod {
method,
svc,
fallback: self,
_request_body: PhantomData,
}
}
/// Handle errors this service might produce, by mapping them to responses.
///
/// Unhandled errors will close the connection without sending a response.
///
/// Works similarly to [`Router::handle_error`]. See that for more
/// details.
///
/// [`Router::handle_error`]: crate::routing::Router::handle_error
pub fn handle_error<ReqBody, H>(self, f: H) -> HandleError<Self, H, ReqBody> {
HandleError::new(self, f)
}
}
// this is identical to `routing::OnMethod`'s implementation. Would be nice to find a way to clean
// that up, but not sure its possible.
impl<S, F, B, ResBody> Service<Request<B>> for OnMethod<S, F, B>
where
S: Service<Request<B>, Response = Response<ResBody>> + Clone,
ResBody: http_body::Body<Data = Bytes> + Send + Sync + 'static,
ResBody::Error: Into<BoxError>,
F: Service<Request<B>, Response = Response<BoxBody>, Error = S::Error> + Clone,
{
type Response = Response<BoxBody>;
type Error = S::Error;
type Future = future::OnMethodFuture<S, F, B>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<B>) -> Self::Future {
use crate::util::Either;
let req_method = req.method().clone();
let f = if self.method.matches(req.method()) {
let fut = self.svc.clone().oneshot(req);
Either::A { inner: fut }
} else {
let fut = self.fallback.clone().oneshot(req);
Either::B { inner: fut }
};
future::OnMethodFuture {
inner: f,
req_method,
}
}
}
/// A [`Service`] adapter that handles errors with a closure.
///
/// Created with
/// [`handler::Layered::handle_error`](crate::handler::Layered::handle_error) or
/// [`routing::Router::handle_error`](crate::routing::Router::handle_error).
/// See those methods for more details.
pub struct HandleError<S, F, B> {
inner: S,
f: F,
_marker: PhantomData<fn() -> B>,
}
impl<S, F, B> Clone for HandleError<S, F, B>
where
S: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self::new(self.inner.clone(), self.f.clone())
}
}
impl<S, F, B> HandleError<S, F, B> {
pub(crate) fn new(inner: S, f: F) -> Self {
Self {
inner,
f,
_marker: PhantomData,
}
}
}
impl<S, F, B> fmt::Debug for HandleError<S, F, B>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HandleError")
.field("inner", &self.inner)
.field("f", &format_args!("{}", std::any::type_name::<F>()))
.finish()
}
}
impl<S, F, ReqBody, ResBody, Res, E> Service<Request<ReqBody>> for HandleError<S, F, ReqBody>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone,
F: FnOnce(S::Error) -> Result<Res, E> + Clone,
Res: IntoResponse,
ResBody: http_body::Body<Data = Bytes> + Send + Sync + 'static,
ResBody::Error: Into<BoxError> + Send + Sync + 'static,
{
type Response = Response<BoxBody>;
type Error = E;
type Future = future::HandleErrorFuture<Oneshot<S, Request<ReqBody>>, F>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
future::HandleErrorFuture {
f: Some(self.f.clone()),
inner: self.inner.clone().oneshot(req),
}
}
}
#[test]
fn traits() {
use crate::tests::*;
assert_send::<OnMethod<(), (), NotSendSync>>();
assert_sync::<OnMethod<(), (), NotSendSync>>();
assert_send::<HandleError<(), (), NotSendSync>>();
assert_sync::<HandleError<(), (), NotSendSync>>();
}
<file_sep>//! Example showing how to convert errors into responses and how one might do
//! dependency injection using trait objects.
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-error-handling-and-dependency-injection
//! ```
use axum::{
async_trait,
body::{Bytes, Full},
extract::{Extension, Path},
handler::{get, post},
http::{Response, StatusCode},
response::IntoResponse,
AddExtensionLayer, Json, Router,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{convert::Infallible, net::SocketAddr, sync::Arc};
use uuid::Uuid;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var(
"RUST_LOG",
"example_error_handling_and_dependency_injection=debug",
)
}
tracing_subscriber::fmt::init();
// Inject a `UserRepo` into our handlers via a trait object. This could be
// the live implementation or just a mock for testing.
let user_repo = Arc::new(ExampleUserRepo) as DynUserRepo;
// Build our application with some routes
let app = Router::new()
.route("/users/:id", get(users_show))
.route("/users", post(users_create))
// Add our `user_repo` to all request's extensions so handlers can access
// it.
.layer(AddExtensionLayer::new(user_repo));
// Run our application
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
/// Handler for `GET /users/:id`.
///
/// Extracts the user repo from request extensions and calls it. `UserRepoError`s
/// are automatically converted into `AppError` which implements `IntoResponse`
/// so it can be returned from handlers directly.
async fn users_show(
Path(user_id): Path<Uuid>,
Extension(user_repo): Extension<DynUserRepo>,
) -> Result<Json<User>, AppError> {
let user = user_repo.find(user_id).await?;
Ok(user.into())
}
/// Handler for `POST /users`.
async fn users_create(
Json(params): Json<CreateUser>,
Extension(user_repo): Extension<DynUserRepo>,
) -> Result<Json<User>, AppError> {
let user = user_repo.create(params).await?;
Ok(user.into())
}
/// Our app's top level error type.
enum AppError {
/// Something went wrong when calling the user repo.
UserRepo(UserRepoError),
}
/// This makes it possible to use `?` to automatically convert a `UserRepoError`
/// into an `AppError`.
impl From<UserRepoError> for AppError {
fn from(inner: UserRepoError) -> Self {
AppError::UserRepo(inner)
}
}
impl IntoResponse for AppError {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
let (status, error_message) = match self {
AppError::UserRepo(UserRepoError::NotFound) => {
(StatusCode::NOT_FOUND, "User not found")
}
AppError::UserRepo(UserRepoError::InvalidUsername) => {
(StatusCode::UNPROCESSABLE_ENTITY, "Invalid username")
}
};
let body = Json(json!({
"error": error_message,
}));
(status, body).into_response()
}
}
/// Example implementation of `UserRepo`.
struct ExampleUserRepo;
#[async_trait]
impl UserRepo for ExampleUserRepo {
async fn find(&self, _user_id: Uuid) -> Result<User, UserRepoError> {
unimplemented!()
}
async fn create(&self, _params: CreateUser) -> Result<User, UserRepoError> {
unimplemented!()
}
}
/// Type alias that makes it easier to extract `UserRepo` trait objects.
type DynUserRepo = Arc<dyn UserRepo + Send + Sync>;
/// A trait that defines things a user repo might support.
#[async_trait]
trait UserRepo {
/// Loop up a user by their id.
async fn find(&self, user_id: Uuid) -> Result<User, UserRepoError>;
/// Create a new user.
async fn create(&self, params: CreateUser) -> Result<User, UserRepoError>;
}
#[derive(Debug, Serialize)]
struct User {
id: Uuid,
username: String,
}
#[derive(Debug, Deserialize)]
struct CreateUser {
username: String,
}
/// Errors that can happen when using the user repo.
#[derive(Debug)]
enum UserRepoError {
#[allow(dead_code)]
NotFound,
#[allow(dead_code)]
InvalidUsername,
}
<file_sep>//! Extractor that parses `multipart/form-data` requests commonly used with file uploads.
//!
//! See [`Multipart`] for more details.
use super::{rejection::*, BodyStream, FromRequest, RequestParts};
use crate::BoxError;
use async_trait::async_trait;
use bytes::Bytes;
use futures_util::stream::Stream;
use http::header::{HeaderMap, CONTENT_TYPE};
use mime::Mime;
use std::{
fmt,
pin::Pin,
task::{Context, Poll},
};
/// Extractor that parses `multipart/form-data` requests commonly used with file uploads.
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// extract::Multipart,
/// handler::post,
/// Router,
/// };
/// use futures::stream::StreamExt;
///
/// async fn upload(mut multipart: Multipart) {
/// while let Some(mut field) = multipart.next_field().await.unwrap() {
/// let name = field.name().unwrap().to_string();
/// let data = field.bytes().await.unwrap();
///
/// println!("Length of `{}` is {} bytes", name, data.len());
/// }
/// }
///
/// let app = Router::new().route("/upload", post(upload));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// For security reasons its recommended to combine this with
/// [`ContentLengthLimit`](super::ContentLengthLimit) to limit the size of the request payload.
#[derive(Debug)]
pub struct Multipart {
inner: multer::Multipart<'static>,
}
#[async_trait]
impl<B> FromRequest<B> for Multipart
where
B: http_body::Body<Data = Bytes> + Default + Unpin + Send + 'static,
B::Error: Into<BoxError> + 'static,
{
type Rejection = MultipartRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let stream = BodyStream::from_request(req).await?;
let headers = req.headers().ok_or(HeadersAlreadyExtracted)?;
let boundary = parse_boundary(headers).ok_or(InvalidBoundary)?;
let multipart = multer::Multipart::new(stream, boundary);
Ok(Self { inner: multipart })
}
}
impl Multipart {
/// Yields the next [`Field`] if available.
pub async fn next_field(&mut self) -> Result<Option<Field<'_>>, MultipartError> {
let field = self
.inner
.next_field()
.await
.map_err(MultipartError::from_multer)?;
if let Some(field) = field {
Ok(Some(Field {
inner: field,
_multipart: self,
}))
} else {
Ok(None)
}
}
}
/// A single field in a multipart stream.
#[derive(Debug)]
pub struct Field<'a> {
inner: multer::Field<'static>,
// multer requires there to only be one live `multer::Field` at any point. This enforces that
// statically, which multer does not do, it returns an error instead.
_multipart: &'a mut Multipart,
}
impl<'a> Stream for Field<'a> {
type Item = Result<Bytes, MultipartError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.inner)
.poll_next(cx)
.map_err(MultipartError::from_multer)
}
}
impl<'a> Field<'a> {
/// The field name found in the
/// [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
/// header.
pub fn name(&self) -> Option<&str> {
self.inner.name()
}
/// The file name found in the
/// [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
/// header.
pub fn file_name(&self) -> Option<&str> {
self.inner.file_name()
}
/// Get the content type of the field.
pub fn content_type(&self) -> Option<&Mime> {
self.inner.content_type()
}
/// Get a map of headers as [`HeaderMap`].
pub fn headers(&self) -> &HeaderMap {
self.inner.headers()
}
/// Get the full data of the field as [`Bytes`].
pub async fn bytes(self) -> Result<Bytes, MultipartError> {
self.inner
.bytes()
.await
.map_err(MultipartError::from_multer)
}
/// Get the full field data as text.
pub async fn text(self) -> Result<String, MultipartError> {
self.inner.text().await.map_err(MultipartError::from_multer)
}
}
/// Errors associated with parsing `multipart/form-data` requests.
#[derive(Debug)]
pub struct MultipartError {
source: multer::Error,
}
impl MultipartError {
fn from_multer(multer: multer::Error) -> Self {
Self { source: multer }
}
}
impl fmt::Display for MultipartError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Error parsing `multipart/form-data` request")
}
}
impl std::error::Error for MultipartError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
fn parse_boundary(headers: &HeaderMap) -> Option<String> {
let content_type = headers.get(CONTENT_TYPE)?.to_str().ok()?;
multer::parse_boundary(content_type).ok()
}
composite_rejection! {
/// Rejection used for [`Multipart`].
///
/// Contains one variant for each way the [`Multipart`] extractor can fail.
pub enum MultipartRejection {
BodyAlreadyExtracted,
InvalidBoundary,
HeadersAlreadyExtracted,
}
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Invalid `boundary` for `multipart/form-data` request"]
/// Rejection type used if the `boundary` in a `multipart/form-data` is
/// missing or invalid.
pub struct InvalidBoundary;
}
<file_sep>use futures_util::ready;
use pin_project_lite::pin_project;
use std::{
future::Future,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use tokio::sync::{mpsc, oneshot, OwnedSemaphorePermit, Semaphore};
use tokio_util::sync::PollSemaphore;
use tower::ServiceExt;
use tower_service::Service;
/// A version of [`tower::buffer::Buffer`] which panicks on channel related errors, thus keeping
/// the error type of the service.
pub(crate) struct MpscBuffer<S, R>
where
S: Service<R>,
{
tx: mpsc::UnboundedSender<Msg<S, R>>,
semaphore: PollSemaphore,
permit: Option<OwnedSemaphorePermit>,
}
impl<S, R> Clone for MpscBuffer<S, R>
where
S: Service<R>,
{
fn clone(&self) -> Self {
Self {
tx: self.tx.clone(),
semaphore: self.semaphore.clone(),
permit: None,
}
}
}
impl<S, R> MpscBuffer<S, R>
where
S: Service<R>,
{
pub(crate) fn new(svc: S) -> Self
where
S: Send + 'static,
R: Send + 'static,
S::Error: Send + 'static,
S::Future: Send + 'static,
{
let (tx, rx) = mpsc::unbounded_channel::<Msg<S, R>>();
let semaphore = PollSemaphore::new(Arc::new(Semaphore::new(1024)));
tokio::spawn(run_worker(svc, rx));
Self {
tx,
semaphore,
permit: None,
}
}
}
async fn run_worker<S, R>(mut svc: S, mut rx: mpsc::UnboundedReceiver<Msg<S, R>>)
where
S: Service<R>,
{
while let Some((req, reply_tx)) = rx.recv().await {
match svc.ready().await {
Ok(svc) => {
let future = svc.call(req);
let _ = reply_tx.send(WorkerReply::Future(future));
}
Err(err) => {
let _ = reply_tx.send(WorkerReply::Error(err));
}
}
}
}
type Msg<S, R> = (
R,
oneshot::Sender<WorkerReply<<S as Service<R>>::Future, <S as Service<R>>::Error>>,
);
enum WorkerReply<F, E> {
Future(F),
Error(E),
}
impl<S, R> Service<R> for MpscBuffer<S, R>
where
S: Service<R>,
{
type Response = S::Response;
type Error = S::Error;
type Future = ResponseFuture<S::Future, S::Error>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.permit.is_some() {
return Poll::Ready(Ok(()));
}
let permit = ready!(self.semaphore.poll_acquire(cx))
.expect("buffer semaphore closed. This is a bug in axum and should never happen. Please file an issue");
self.permit = Some(permit);
Poll::Ready(Ok(()))
}
fn call(&mut self, req: R) -> Self::Future {
let permit = self
.permit
.take()
.expect("semaphore permit missing. Did you forget to call `poll_ready`?");
let (reply_tx, reply_rx) = oneshot::channel::<WorkerReply<S::Future, S::Error>>();
self.tx.send((req, reply_tx)).unwrap_or_else(|_| {
panic!("buffer worker not running. This is a bug in axum and should never happen. Please file an issue")
});
ResponseFuture {
state: State::Channel { reply_rx },
permit,
}
}
}
pin_project! {
pub(crate) struct ResponseFuture<F, E> {
#[pin]
state: State<F, E>,
permit: OwnedSemaphorePermit,
}
}
pin_project! {
#[project = StateProj]
enum State<F, E> {
Channel { reply_rx: oneshot::Receiver<WorkerReply<F, E>> },
Future { #[pin] future: F },
}
}
impl<F, E, T> Future for ResponseFuture<F, E>
where
F: Future<Output = Result<T, E>>,
{
type Output = Result<T, E>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let mut this = self.as_mut().project();
let new_state = match this.state.as_mut().project() {
StateProj::Channel { reply_rx } => {
let msg = ready!(Pin::new(reply_rx).poll(cx))
.expect("buffer worker not running. This is a bug in axum and should never happen. Please file an issue");
match msg {
WorkerReply::Future(future) => State::Future { future },
WorkerReply::Error(err) => return Poll::Ready(Err(err)),
}
}
StateProj::Future { future } => {
return future.poll(cx);
}
};
this.state.set(new_state);
}
}
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
use tower::ServiceExt;
#[tokio::test]
async fn test_buffer() {
let mut svc = MpscBuffer::new(tower::service_fn(handle));
let res = svc.ready().await.unwrap().call(42).await.unwrap();
assert_eq!(res, "foo");
}
async fn handle(req: i32) -> Result<&'static str, std::convert::Infallible> {
assert_eq!(req, 42);
Ok("foo")
}
}
<file_sep>[package]
name = "example-oauth"
version = "0.1.0"
edition = "2018"
publish = false
[dependencies]
axum = { path = "../..", features = ["headers"] }
tokio = { version = "1.0", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.2"
oauth2 = "4.1"
async-session = "3.0.0"
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json"] }
headers = "0.3"
<file_sep>//! Rejection response types.
use super::IntoResponse;
use crate::BoxError;
use crate::{
body::{box_body, BoxBody},
Error,
};
use bytes::Bytes;
use http_body::Full;
use std::convert::Infallible;
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "Extensions taken by other extractor"]
/// Rejection used if the request extension has been taken by another
/// extractor.
pub struct ExtensionsAlreadyExtracted;
}
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "Headers taken by other extractor"]
/// Rejection used if the headers has been taken by another extractor.
pub struct HeadersAlreadyExtracted;
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Failed to parse the request body as JSON"]
/// Rejection type for [`Json`](super::Json).
pub struct InvalidJsonBody(Error);
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Expected request with `Content-Type: application/json`"]
/// Rejection type for [`Json`](super::Json) used if the `Content-Type`
/// header is missing.
pub struct MissingJsonContentType;
}
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "Missing request extension"]
/// Rejection type for [`Extension`](super::Extension) if an expected
/// request extension was not found.
pub struct MissingExtension(Error);
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Failed to buffer the request body"]
/// Rejection type for extractors that buffer the request body. Used if the
/// request body cannot be buffered due to an error.
pub struct FailedToBufferBody(Error);
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Request body didn't contain valid UTF-8"]
/// Rejection type used when buffering the request into a [`String`] if the
/// body doesn't contain valid UTF-8.
pub struct InvalidUtf8(Error);
}
define_rejection! {
#[status = PAYLOAD_TOO_LARGE]
#[body = "Request payload is too large"]
/// Rejection type for [`ContentLengthLimit`](super::ContentLengthLimit) if
/// the request body is too large.
pub struct PayloadTooLarge;
}
define_rejection! {
#[status = LENGTH_REQUIRED]
#[body = "Content length header is required"]
/// Rejection type for [`ContentLengthLimit`](super::ContentLengthLimit) if
/// the request is missing the `Content-Length` header or it is invalid.
pub struct LengthRequired;
}
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "No url params found for matched route. This is a bug in axum. Please open an issue"]
/// Rejection type used if you try and extract the URL params more than once.
pub struct MissingRouteParams;
}
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "Cannot have two request body extractors for a single handler"]
/// Rejection type used if you try and extract the request body more than
/// once.
pub struct BodyAlreadyExtracted;
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Form requests must have `Content-Type: x-www-form-urlencoded`"]
/// Rejection type used if you try and extract the request more than once.
pub struct InvalidFormContentType;
}
/// Rejection type for [`Path`](super::Path) if the capture route
/// param didn't have the expected type.
#[derive(Debug)]
pub struct InvalidPathParam(String);
impl InvalidPathParam {
pub(super) fn new(err: impl Into<String>) -> Self {
InvalidPathParam(err.into())
}
}
impl IntoResponse for InvalidPathParam {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> http::Response<Self::Body> {
let mut res = http::Response::new(Full::from(self.to_string()));
*res.status_mut() = http::StatusCode::BAD_REQUEST;
res
}
}
impl std::fmt::Display for InvalidPathParam {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Invalid URL param. {}", self.0)
}
}
impl std::error::Error for InvalidPathParam {}
/// Rejection type for extractors that deserialize query strings if the input
/// couldn't be deserialized into the target type.
#[derive(Debug)]
pub struct FailedToDeserializeQueryString {
error: Error,
type_name: &'static str,
}
impl FailedToDeserializeQueryString {
pub(super) fn new<T, E>(error: E) -> Self
where
E: Into<BoxError>,
{
FailedToDeserializeQueryString {
error: Error::new(error),
type_name: std::any::type_name::<T>(),
}
}
}
impl IntoResponse for FailedToDeserializeQueryString {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> http::Response<Self::Body> {
let mut res = http::Response::new(Full::from(self.to_string()));
*res.status_mut() = http::StatusCode::BAD_REQUEST;
res
}
}
impl std::fmt::Display for FailedToDeserializeQueryString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Failed to deserialize query string. Expected something of type `{}`. Error: {}",
self.type_name, self.error,
)
}
}
impl std::error::Error for FailedToDeserializeQueryString {}
composite_rejection! {
/// Rejection used for [`Query`](super::Query).
///
/// Contains one variant for each way the [`Query`](super::Query) extractor
/// can fail.
pub enum QueryRejection {
FailedToDeserializeQueryString,
}
}
composite_rejection! {
/// Rejection used for [`Form`](super::Form).
///
/// Contains one variant for each way the [`Form`](super::Form) extractor
/// can fail.
pub enum FormRejection {
InvalidFormContentType,
FailedToDeserializeQueryString,
FailedToBufferBody,
BodyAlreadyExtracted,
HeadersAlreadyExtracted,
}
}
composite_rejection! {
/// Rejection used for [`Json`](super::Json).
///
/// Contains one variant for each way the [`Json`](super::Json) extractor
/// can fail.
pub enum JsonRejection {
InvalidJsonBody,
MissingJsonContentType,
BodyAlreadyExtracted,
HeadersAlreadyExtracted,
}
}
composite_rejection! {
/// Rejection used for [`Extension`](super::Extension).
///
/// Contains one variant for each way the [`Extension`](super::Extension) extractor
/// can fail.
pub enum ExtensionRejection {
MissingExtension,
ExtensionsAlreadyExtracted,
}
}
composite_rejection! {
/// Rejection used for [`Path`](super::Path).
///
/// Contains one variant for each way the [`Path`](super::Path) extractor
/// can fail.
pub enum PathParamsRejection {
InvalidPathParam,
MissingRouteParams,
}
}
composite_rejection! {
/// Rejection used for [`Bytes`](bytes::Bytes).
///
/// Contains one variant for each way the [`Bytes`](bytes::Bytes) extractor
/// can fail.
pub enum BytesRejection {
BodyAlreadyExtracted,
FailedToBufferBody,
}
}
composite_rejection! {
/// Rejection used for [`String`].
///
/// Contains one variant for each way the [`String`] extractor can fail.
pub enum StringRejection {
BodyAlreadyExtracted,
FailedToBufferBody,
InvalidUtf8,
}
}
composite_rejection! {
/// Rejection used for [`Request<_>`].
///
/// Contains one variant for each way the [`Request<_>`] extractor can fail.
///
/// [`Request<_>`]: http::Request
pub enum RequestAlreadyExtracted {
BodyAlreadyExtracted,
HeadersAlreadyExtracted,
ExtensionsAlreadyExtracted,
}
}
/// Rejection used for [`ContentLengthLimit`](super::ContentLengthLimit).
///
/// Contains one variant for each way the
/// [`ContentLengthLimit`](super::ContentLengthLimit) extractor can fail.
#[derive(Debug)]
#[non_exhaustive]
pub enum ContentLengthLimitRejection<T> {
#[allow(missing_docs)]
PayloadTooLarge(PayloadTooLarge),
#[allow(missing_docs)]
LengthRequired(LengthRequired),
#[allow(missing_docs)]
HeadersAlreadyExtracted(HeadersAlreadyExtracted),
#[allow(missing_docs)]
Inner(T),
}
impl<T> IntoResponse for ContentLengthLimitRejection<T>
where
T: IntoResponse,
{
type Body = BoxBody;
type BodyError = Error;
fn into_response(self) -> http::Response<Self::Body> {
match self {
Self::PayloadTooLarge(inner) => inner.into_response().map(box_body),
Self::LengthRequired(inner) => inner.into_response().map(box_body),
Self::HeadersAlreadyExtracted(inner) => inner.into_response().map(box_body),
Self::Inner(inner) => inner.into_response().map(box_body),
}
}
}
impl<T> std::fmt::Display for ContentLengthLimitRejection<T>
where
T: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::PayloadTooLarge(inner) => inner.fmt(f),
Self::LengthRequired(inner) => inner.fmt(f),
Self::HeadersAlreadyExtracted(inner) => inner.fmt(f),
Self::Inner(inner) => inner.fmt(f),
}
}
}
impl<T> std::error::Error for ContentLengthLimitRejection<T>
where
T: std::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::PayloadTooLarge(inner) => Some(inner),
Self::LengthRequired(inner) => Some(inner),
Self::HeadersAlreadyExtracted(inner) => Some(inner),
Self::Inner(inner) => Some(inner),
}
}
}
#[cfg(feature = "headers")]
#[cfg_attr(docsrs, doc(cfg(feature = "headers")))]
pub use super::typed_header::TypedHeaderRejection;
<file_sep># Examples
This folder contains numerous example showing how to use axum. Each example is
setup as its own crate so its dependencies are clear.
## Community showcase
- [Houseflow](https://github.com/gbaranski/houseflow): House automation platform written in Rust.
- [Datafuse](https://github.com/datafuselabs/datafuse): Cloud native data warehouse written in Rust.
- [JWT Auth](https://github.com/Z4RX/axum_jwt_example): JWT auth service for educational purposes.
<file_sep>use super::*;
use std::future::{pending, ready};
use tower::{timeout::TimeoutLayer, MakeService};
async fn unit() {}
async fn forever() {
pending().await
}
fn timeout() -> TimeoutLayer {
TimeoutLayer::new(Duration::from_millis(10))
}
#[derive(Clone)]
struct Svc;
impl<R> Service<R> for Svc {
type Response = Response<Body>;
type Error = hyper::Error;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _req: R) -> Self::Future {
ready(Ok(Response::new(Body::empty())))
}
}
fn check_make_svc<M, R, T, E>(_make_svc: M)
where
M: MakeService<(), R, Response = T, Error = E>,
{
}
fn handle_error<E>(_: E) -> Result<StatusCode, Infallible> {
Ok(StatusCode::INTERNAL_SERVER_ERROR)
}
#[tokio::test]
async fn handler() {
let app = Router::new().route(
"/",
get(forever
.layer(timeout())
.handle_error(|_: BoxError| Ok::<_, Infallible>(StatusCode::REQUEST_TIMEOUT))),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
}
#[tokio::test]
async fn handler_multiple_methods_first() {
let app = Router::new().route(
"/",
get(forever
.layer(timeout())
.handle_error(|_: BoxError| Ok::<_, Infallible>(StatusCode::REQUEST_TIMEOUT)))
.post(unit),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
}
#[tokio::test]
async fn handler_multiple_methods_middle() {
let app = Router::new().route(
"/",
delete(unit)
.get(
forever
.layer(timeout())
.handle_error(|_: BoxError| Ok::<_, Infallible>(StatusCode::REQUEST_TIMEOUT)),
)
.post(unit),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
}
#[tokio::test]
async fn handler_multiple_methods_last() {
let app = Router::new().route(
"/",
delete(unit).get(
forever
.layer(timeout())
.handle_error(|_: BoxError| Ok::<_, Infallible>(StatusCode::REQUEST_TIMEOUT)),
),
);
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/", addr))
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
}
#[test]
fn service_propagates_errors() {
let app = Router::new().route("/echo", service::post::<_, Body>(Svc));
check_make_svc::<_, _, _, hyper::Error>(app.into_make_service());
}
#[test]
fn service_nested_propagates_errors() {
let app = Router::new().route(
"/echo",
Router::new().nest("/foo", service::post::<_, Body>(Svc)),
);
check_make_svc::<_, _, _, hyper::Error>(app.into_make_service());
}
#[test]
fn service_handle_on_method() {
let app = Router::new().route(
"/echo",
service::get::<_, Body>(Svc).handle_error(handle_error::<hyper::Error>),
);
check_make_svc::<_, _, _, Infallible>(app.into_make_service());
}
#[test]
fn service_handle_on_method_multiple() {
let app = Router::new().route(
"/echo",
service::get::<_, Body>(Svc)
.post(Svc)
.handle_error(handle_error::<hyper::Error>),
);
check_make_svc::<_, _, _, Infallible>(app.into_make_service());
}
#[test]
fn service_handle_on_router() {
let app = Router::new()
.route("/echo", service::get::<_, Body>(Svc))
.handle_error(handle_error::<hyper::Error>);
check_make_svc::<_, _, _, Infallible>(app.into_make_service());
}
#[test]
fn service_handle_on_router_still_impls_routing_dsl() {
let app = Router::new()
.route("/echo", service::get::<_, Body>(Svc))
.handle_error(handle_error::<hyper::Error>)
.route("/", get(unit));
check_make_svc::<_, _, _, Infallible>(app.into_make_service());
}
#[test]
fn layered() {
let app = Router::new()
.route("/echo", get::<_, Body, _>(unit))
.layer(timeout())
.handle_error(handle_error::<BoxError>);
check_make_svc::<_, _, _, Infallible>(app.into_make_service());
}
#[tokio::test] // async because of `.boxed()`
async fn layered_boxed() {
let app = Router::new()
.route("/echo", get::<_, Body, _>(unit))
.layer(timeout())
.boxed()
.handle_error(handle_error::<BoxError>);
check_make_svc::<_, _, _, Infallible>(app.into_make_service());
}
<file_sep>use super::{rejection::*, take_body, Extension, FromRequest, RequestParts};
use crate::{body::Body, BoxError, Error};
use async_trait::async_trait;
use bytes::Bytes;
use futures_util::stream::Stream;
use http::{Extensions, HeaderMap, Method, Request, Uri, Version};
use http_body::Body as HttpBody;
use std::{
convert::Infallible,
fmt,
pin::Pin,
task::{Context, Poll},
};
use sync_wrapper::SyncWrapper;
#[async_trait]
impl<B> FromRequest<B> for Request<B>
where
B: Send,
{
type Rejection = RequestAlreadyExtracted;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let req = std::mem::replace(
req,
RequestParts {
method: req.method.clone(),
version: req.version,
uri: req.uri.clone(),
headers: None,
extensions: None,
body: None,
},
);
let err = match req.try_into_request() {
Ok(req) => return Ok(req),
Err(err) => err,
};
match err.downcast::<RequestAlreadyExtracted>() {
Ok(err) => return Err(err),
Err(err) => unreachable!(
"Unexpected error type from `try_into_request`: `{:?}`. This is a bug in axum, please file an issue",
err,
),
}
}
}
#[async_trait]
impl<B> FromRequest<B> for RawBody<B>
where
B: Send,
{
type Rejection = BodyAlreadyExtracted;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let body = take_body(req)?;
Ok(Self(body))
}
}
#[async_trait]
impl<B> FromRequest<B> for Method
where
B: Send,
{
type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
Ok(req.method().clone())
}
}
#[async_trait]
impl<B> FromRequest<B> for Uri
where
B: Send,
{
type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
Ok(req.uri().clone())
}
}
/// Extractor that gets the original request URI regardless of nesting.
///
/// This is necessary since [`Uri`](http::Uri), when used as an extractor, will
/// have the prefix stripped if used in a nested service.
///
/// # Example
///
/// ```
/// use axum::{
/// handler::get,
/// Router,
/// extract::OriginalUri,
/// http::Uri
/// };
///
/// let api_routes = Router::new()
/// .route(
/// "/users",
/// get(|uri: Uri, OriginalUri(original_uri): OriginalUri| async {
/// // `uri` is `/users`
/// // `original_uri` is `/api/users`
/// }),
/// );
///
/// let app = Router::new().nest("/api", api_routes);
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
#[derive(Debug, Clone)]
pub struct OriginalUri(pub Uri);
#[async_trait]
impl<B> FromRequest<B> for OriginalUri
where
B: Send,
{
type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let uri = Extension::<Self>::from_request(req)
.await
.unwrap_or_else(|_| Extension(OriginalUri(req.uri().clone())))
.0;
Ok(uri)
}
}
#[async_trait]
impl<B> FromRequest<B> for Version
where
B: Send,
{
type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
Ok(req.version())
}
}
#[async_trait]
impl<B> FromRequest<B> for HeaderMap
where
B: Send,
{
type Rejection = HeadersAlreadyExtracted;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
req.take_headers().ok_or(HeadersAlreadyExtracted)
}
}
#[async_trait]
impl<B> FromRequest<B> for Extensions
where
B: Send,
{
type Rejection = ExtensionsAlreadyExtracted;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
req.take_extensions().ok_or(ExtensionsAlreadyExtracted)
}
}
/// Extractor that extracts the request body as a [`Stream`].
///
/// Note if your request body is [`body::Body`] you can extract that directly
/// and since it already implements [`Stream`] you don't need this type. The
/// purpose of this type is to extract other types of request bodies as a
/// [`Stream`].
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// extract::BodyStream,
/// handler::get,
/// Router,
/// };
/// use futures::StreamExt;
///
/// async fn handler(mut stream: BodyStream) {
/// while let Some(chunk) = stream.next().await {
/// // ...
/// }
/// }
///
/// let app = Router::new().route("/users", get(handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// [`Stream`]: https://docs.rs/futures/latest/futures/stream/trait.Stream.html
/// [`body::Body`]: crate::body::Body
pub struct BodyStream(
SyncWrapper<Pin<Box<dyn http_body::Body<Data = Bytes, Error = Error> + Send + 'static>>>,
);
impl Stream for BodyStream {
type Item = Result<Bytes, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(self.0.get_mut()).poll_data(cx)
}
}
#[async_trait]
impl<B> FromRequest<B> for BodyStream
where
B: HttpBody + Send + 'static,
B::Data: Into<Bytes>,
B::Error: Into<BoxError>,
{
type Rejection = BodyAlreadyExtracted;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let body = take_body(req)?
.map_data(Into::into)
.map_err(|err| Error::new(err.into()));
let stream = BodyStream(SyncWrapper::new(Box::pin(body)));
Ok(stream)
}
}
impl fmt::Debug for BodyStream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("BodyStream").finish()
}
}
#[test]
fn body_stream_traits() {
crate::tests::assert_send::<BodyStream>();
crate::tests::assert_sync::<BodyStream>();
}
/// Extractor that extracts the raw request body.
///
/// Note that [`body::Body`] can be extracted directly. This purpose of this
/// type is to extract other types of request bodies.
///
/// # Example
///
/// ```rust,no_run
/// use axum::{
/// extract::RawBody,
/// handler::get,
/// Router,
/// };
/// use futures::StreamExt;
///
/// async fn handler(RawBody(body): RawBody) {
/// // ...
/// }
///
/// let app = Router::new().route("/users", get(handler));
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// [`body::Body`]: crate::body::Body
#[derive(Debug, Default, Clone)]
pub struct RawBody<B = Body>(pub B);
#[async_trait]
impl<B> FromRequest<B> for Bytes
where
B: http_body::Body + Send,
B::Data: Send,
B::Error: Into<BoxError>,
{
type Rejection = BytesRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let body = take_body(req)?;
let bytes = hyper::body::to_bytes(body)
.await
.map_err(FailedToBufferBody::from_err)?;
Ok(bytes)
}
}
#[async_trait]
impl FromRequest<Body> for Body {
type Rejection = BodyAlreadyExtracted;
async fn from_request(req: &mut RequestParts<Body>) -> Result<Self, Self::Rejection> {
req.take_body().ok_or(BodyAlreadyExtracted)
}
}
#[async_trait]
impl<B> FromRequest<B> for String
where
B: http_body::Body + Send,
B::Data: Send,
B::Error: Into<BoxError>,
{
type Rejection = StringRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let body = take_body(req)?;
let bytes = hyper::body::to_bytes(body)
.await
.map_err(FailedToBufferBody::from_err)?
.to_vec();
let string = String::from_utf8(bytes).map_err(InvalidUtf8::from_err)?;
Ok(string)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{body::Body, handler::post, tests::*, Router};
use http::StatusCode;
#[tokio::test]
async fn multiple_request_extractors() {
async fn handler(_: Request<Body>, _: Request<Body>) {}
let app = Router::new().route("/", post(handler));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.post(format!("http://{}", addr))
.body("hi there")
.send()
.await
.unwrap();
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(
res.text().await.unwrap(),
"Cannot have two request body extractors for a single handler"
);
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-unix-domain-socket
//! ```
use axum::{
body::Body,
extract::connect_info::{self, ConnectInfo},
handler::get,
http::{Method, Request, StatusCode, Uri},
Router,
};
use futures::ready;
use hyper::{
client::connect::{Connected, Connection},
server::accept::Accept,
};
use std::{
io,
path::PathBuf,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use tokio::net::{unix::UCred, UnixListener};
use tokio::{
io::{AsyncRead, AsyncWrite},
net::UnixStream,
};
use tower::BoxError;
#[cfg(not(unix))]
fn main() {
println!("This example requires unix")
}
#[cfg(unix)]
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "debug")
}
tracing_subscriber::fmt::init();
let path = PathBuf::from("/tmp/axum/helloworld");
let _ = tokio::fs::remove_file(&path).await;
tokio::fs::create_dir_all(path.parent().unwrap())
.await
.unwrap();
let uds = UnixListener::bind(path.clone()).unwrap();
tokio::spawn(async {
let app = Router::new().route("/", get(handler));
axum::Server::builder(ServerAccept { uds })
.serve(app.into_make_service_with_connect_info::<UdsConnectInfo, _>())
.await
.unwrap();
});
let connector = tower::service_fn(move |_: Uri| {
let path = path.clone();
Box::pin(async move {
let stream = UnixStream::connect(path).await?;
Ok::<_, io::Error>(ClientConnection { stream })
})
});
let client = hyper::Client::builder().build(connector);
let request = Request::builder()
.method(Method::GET)
.uri("http://uri-doesnt-matter.com")
.body(Body::empty())
.unwrap();
let response = client.request(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
let body = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body, "Hello, World!");
}
async fn handler(ConnectInfo(info): ConnectInfo<UdsConnectInfo>) -> &'static str {
println!("new connection from `{:?}`", info);
"Hello, World!"
}
struct ServerAccept {
uds: UnixListener,
}
impl Accept for ServerAccept {
type Conn = UnixStream;
type Error = BoxError;
fn poll_accept(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
let (stream, _addr) = ready!(self.uds.poll_accept(cx))?;
Poll::Ready(Some(Ok(stream)))
}
}
struct ClientConnection {
stream: UnixStream,
}
impl AsyncWrite for ClientConnection {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
Pin::new(&mut self.stream).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
Pin::new(&mut self.stream).poll_flush(cx)
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), io::Error>> {
Pin::new(&mut self.stream).poll_shutdown(cx)
}
}
impl AsyncRead for ClientConnection {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> Poll<io::Result<()>> {
Pin::new(&mut self.stream).poll_read(cx, buf)
}
}
impl Connection for ClientConnection {
fn connected(&self) -> Connected {
Connected::new()
}
}
#[derive(Clone, Debug)]
struct UdsConnectInfo {
peer_addr: Arc<tokio::net::unix::SocketAddr>,
peer_cred: UCred,
}
impl connect_info::Connected<&UnixStream> for UdsConnectInfo {
type ConnectInfo = Self;
fn connect_info(target: &UnixStream) -> Self::ConnectInfo {
let peer_addr = target.peer_addr().unwrap();
let peer_cred = target.peer_cred().unwrap();
Self {
peer_addr: Arc::new(peer_addr),
peer_cred,
}
}
}
<file_sep>use super::StarWars;
use async_graphql::connection::{query, Connection, Edge, EmptyFields};
use async_graphql::{Context, Enum, FieldResult, Interface, Object};
/// One of the films in the Star Wars Trilogy
#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub enum Episode {
/// Released in 1977.
NewHope,
/// Released in 1980.
Empire,
/// Released in 1983.
Jedi,
}
pub struct Human(usize);
/// A humanoid creature in the Star Wars universe.
#[Object]
impl Human {
/// The id of the human.
async fn id(&self, ctx: &Context<'_>) -> &str {
ctx.data_unchecked::<StarWars>().chars[self.0].id
}
/// The name of the human.
async fn name(&self, ctx: &Context<'_>) -> &str {
ctx.data_unchecked::<StarWars>().chars[self.0].name
}
/// The friends of the human, or an empty list if they have none.
async fn friends(&self, ctx: &Context<'_>) -> Vec<Character> {
ctx.data_unchecked::<StarWars>().chars[self.0]
.friends
.iter()
.map(|id| Human(*id).into())
.collect()
}
/// Which movies they appear in.
async fn appears_in<'a>(&self, ctx: &'a Context<'_>) -> &'a [Episode] {
&ctx.data_unchecked::<StarWars>().chars[self.0].appears_in
}
/// The home planet of the human, or null if unknown.
async fn home_planet<'a>(&self, ctx: &'a Context<'_>) -> &'a Option<&'a str> {
&ctx.data_unchecked::<StarWars>().chars[self.0].home_planet
}
}
pub struct Droid(usize);
/// A mechanical creature in the Star Wars universe.
#[Object]
impl Droid {
/// The id of the droid.
async fn id(&self, ctx: &Context<'_>) -> &str {
ctx.data_unchecked::<StarWars>().chars[self.0].id
}
/// The name of the droid.
async fn name(&self, ctx: &Context<'_>) -> &str {
ctx.data_unchecked::<StarWars>().chars[self.0].name
}
/// The friends of the droid, or an empty list if they have none.
async fn friends(&self, ctx: &Context<'_>) -> Vec<Character> {
ctx.data_unchecked::<StarWars>().chars[self.0]
.friends
.iter()
.map(|id| Droid(*id).into())
.collect()
}
/// Which movies they appear in.
async fn appears_in<'a>(&self, ctx: &'a Context<'_>) -> &'a [Episode] {
&ctx.data_unchecked::<StarWars>().chars[self.0].appears_in
}
/// The primary function of the droid.
async fn primary_function<'a>(&self, ctx: &'a Context<'_>) -> &'a Option<&'a str> {
&ctx.data_unchecked::<StarWars>().chars[self.0].primary_function
}
}
pub struct QueryRoot;
#[Object]
impl QueryRoot {
async fn hero(
&self,
ctx: &Context<'_>,
#[graphql(
desc = "If omitted, returns the hero of the whole saga. If provided, returns the hero of that particular episode."
)]
episode: Episode,
) -> Character {
if episode == Episode::Empire {
Human(ctx.data_unchecked::<StarWars>().luke).into()
} else {
Droid(ctx.data_unchecked::<StarWars>().artoo).into()
}
}
async fn human(
&self,
ctx: &Context<'_>,
#[graphql(desc = "id of the human")] id: String,
) -> Option<Human> {
ctx.data_unchecked::<StarWars>().human(&id).map(Human)
}
async fn humans(
&self,
ctx: &Context<'_>,
after: Option<String>,
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
) -> FieldResult<Connection<usize, Human, EmptyFields, EmptyFields>> {
let humans = ctx
.data_unchecked::<StarWars>()
.humans()
.iter()
.copied()
.collect::<Vec<_>>();
query_characters(after, before, first, last, &humans)
.await
.map(|conn| conn.map_node(Human))
}
async fn droid(
&self,
ctx: &Context<'_>,
#[graphql(desc = "id of the droid")] id: String,
) -> Option<Droid> {
ctx.data_unchecked::<StarWars>().droid(&id).map(Droid)
}
async fn droids(
&self,
ctx: &Context<'_>,
after: Option<String>,
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
) -> FieldResult<Connection<usize, Droid, EmptyFields, EmptyFields>> {
let droids = ctx
.data_unchecked::<StarWars>()
.droids()
.iter()
.copied()
.collect::<Vec<_>>();
query_characters(after, before, first, last, &droids)
.await
.map(|conn| conn.map_node(Droid))
}
}
#[derive(Interface)]
#[graphql(
field(name = "id", type = "&str"),
field(name = "name", type = "&str"),
field(name = "friends", type = "Vec<Character>"),
field(name = "appears_in", type = "&'ctx [Episode]")
)]
pub enum Character {
Human(Human),
Droid(Droid),
}
async fn query_characters(
after: Option<String>,
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
characters: &[usize],
) -> FieldResult<Connection<usize, usize, EmptyFields, EmptyFields>> {
query(
after,
before,
first,
last,
|after, before, first, last| async move {
let mut start = 0usize;
let mut end = characters.len();
if let Some(after) = after {
if after >= characters.len() {
return Ok(Connection::new(false, false));
}
start = after + 1;
}
if let Some(before) = before {
if before == 0 {
return Ok(Connection::new(false, false));
}
end = before;
}
let mut slice = &characters[start..end];
if let Some(first) = first {
slice = &slice[..first.min(slice.len())];
end -= first.min(slice.len());
} else if let Some(last) = last {
slice = &slice[slice.len() - last.min(slice.len())..];
start = end - last.min(slice.len());
}
let mut connection = Connection::new(start > 0, end < characters.len());
connection.append(
slice
.iter()
.enumerate()
.map(|(idx, item)| Edge::new(start + idx, *item)),
);
Ok(connection)
},
)
.await
}
<file_sep>//! Handle WebSocket connections.
//!
//! # Example
//!
//! ```
//! use axum::{
//! extract::ws::{WebSocketUpgrade, WebSocket},
//! handler::get,
//! response::IntoResponse,
//! Router,
//! };
//!
//! let app = Router::new().route("/ws", get(handler));
//!
//! async fn handler(ws: WebSocketUpgrade) -> impl IntoResponse {
//! ws.on_upgrade(handle_socket)
//! }
//!
//! async fn handle_socket(mut socket: WebSocket) {
//! while let Some(msg) = socket.recv().await {
//! let msg = if let Ok(msg) = msg {
//! msg
//! } else {
//! // client disconnected
//! return;
//! };
//!
//! if socket.send(msg).await.is_err() {
//! // client disconnected
//! return;
//! }
//! }
//! }
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! # Read and write concurrently
//!
//! If you need to read and write concurrently from a [`WebSocket`] you can use
//! [`StreamExt::split`]:
//!
//! ```
//! use axum::{Error, extract::ws::{WebSocket, Message}};
//! use futures::{sink::SinkExt, stream::{StreamExt, SplitSink, SplitStream}};
//!
//! async fn handle_socket(mut socket: WebSocket) {
//! let (mut sender, mut receiver) = socket.split();
//!
//! tokio::spawn(write(sender));
//! tokio::spawn(read(receiver));
//! }
//!
//! async fn read(receiver: SplitStream<WebSocket>) {
//! // ...
//! }
//!
//! async fn write(sender: SplitSink<WebSocket, Message>) {
//! // ...
//! }
//! ```
//!
//! [`StreamExt::split`]: https://docs.rs/futures/0.3.17/futures/stream/trait.StreamExt.html#method.split
use self::rejection::*;
use super::{rejection::*, FromRequest, RequestParts};
use crate::{response::IntoResponse, Error};
use async_trait::async_trait;
use bytes::Bytes;
use futures_util::{
sink::{Sink, SinkExt},
stream::{Stream, StreamExt},
};
use http::{
header::{self, HeaderName, HeaderValue},
Method, Response, StatusCode,
};
use http_body::Full;
use hyper::upgrade::{OnUpgrade, Upgraded};
use sha1::{Digest, Sha1};
use std::{
borrow::Cow,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tokio_tungstenite::{
tungstenite::{
self,
protocol::{self, WebSocketConfig},
},
WebSocketStream,
};
/// Extractor for establishing WebSocket connections.
///
/// Note: This extractor requires the request method to be `GET` so it should
/// always be used with [`get`](crate::handler::get). Requests with other methods will be
/// rejected.
///
/// See the [module docs](self) for an example.
#[derive(Debug)]
pub struct WebSocketUpgrade {
config: WebSocketConfig,
protocols: Option<Box<[Cow<'static, str>]>>,
sec_websocket_key: HeaderValue,
on_upgrade: OnUpgrade,
sec_websocket_protocol: Option<HeaderValue>,
}
impl WebSocketUpgrade {
/// Set the size of the internal message send queue.
pub fn max_send_queue(mut self, max: usize) -> Self {
self.config.max_send_queue = Some(max);
self
}
/// Set the maximum message size (defaults to 64 megabytes)
pub fn max_message_size(mut self, max: usize) -> Self {
self.config.max_message_size = Some(max);
self
}
/// Set the maximum frame size (defaults to 16 megabytes)
pub fn max_frame_size(mut self, max: usize) -> Self {
self.config.max_frame_size = Some(max);
self
}
/// Set the known protocols.
///
/// If the protocol name specified by `Sec-WebSocket-Protocol` header
/// to match any of them, the upgrade response will include `Sec-WebSocket-Protocol` header and return the protocol name.
///
/// # Examples
///
/// ```
/// use axum::{
/// extract::ws::{WebSocketUpgrade, WebSocket},
/// handler::get,
/// response::IntoResponse,
/// Router,
/// };
///
/// let app = Router::new().route("/ws", get(handler));
///
/// async fn handler(ws: WebSocketUpgrade) -> impl IntoResponse {
/// ws.protocols(["graphql-ws", "graphql-transport-ws"])
/// .on_upgrade(|socket| async {
/// // ...
/// })
/// }
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
pub fn protocols<I>(mut self, protocols: I) -> Self
where
I: IntoIterator,
I::Item: Into<Cow<'static, str>>,
{
self.protocols = Some(
protocols
.into_iter()
.map(Into::into)
.collect::<Vec<_>>()
.into(),
);
self
}
/// Finalize upgrading the connection and call the provided callback with
/// the stream.
///
/// When using `WebSocketUpgrade`, the response produced by this method
/// should be returned from the handler. See the [module docs](self) for an
/// example.
pub fn on_upgrade<F, Fut>(self, callback: F) -> impl IntoResponse
where
F: FnOnce(WebSocket) -> Fut + Send + 'static,
Fut: Future + Send + 'static,
{
WebSocketUpgradeResponse {
extractor: self,
callback,
}
}
}
#[async_trait]
impl<B> FromRequest<B> for WebSocketUpgrade
where
B: Send,
{
type Rejection = WebSocketUpgradeRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
if req.method() != Method::GET {
return Err(MethodNotGet.into());
}
if !header_contains(req, header::CONNECTION, "upgrade")? {
return Err(InvalidConnectionHeader.into());
}
if !header_eq(req, header::UPGRADE, "websocket")? {
return Err(InvalidUpgradeHeader.into());
}
if !header_eq(req, header::SEC_WEBSOCKET_VERSION, "13")? {
return Err(InvalidWebsocketVersionHeader.into());
}
let sec_websocket_key = if let Some(key) = req
.headers_mut()
.ok_or(HeadersAlreadyExtracted)?
.remove(header::SEC_WEBSOCKET_KEY)
{
key
} else {
return Err(WebsocketKeyHeaderMissing.into());
};
let on_upgrade = req
.extensions_mut()
.ok_or(ExtensionsAlreadyExtracted)?
.remove::<OnUpgrade>()
.unwrap();
let sec_websocket_protocol = req
.headers()
.ok_or(HeadersAlreadyExtracted)?
.get(header::SEC_WEBSOCKET_PROTOCOL)
.cloned();
Ok(Self {
config: Default::default(),
protocols: None,
sec_websocket_key,
on_upgrade,
sec_websocket_protocol,
})
}
}
fn header_eq<B>(
req: &RequestParts<B>,
key: HeaderName,
value: &'static str,
) -> Result<bool, HeadersAlreadyExtracted> {
if let Some(header) = req.headers().ok_or(HeadersAlreadyExtracted)?.get(&key) {
Ok(header.as_bytes().eq_ignore_ascii_case(value.as_bytes()))
} else {
Ok(false)
}
}
fn header_contains<B>(
req: &RequestParts<B>,
key: HeaderName,
value: &'static str,
) -> Result<bool, HeadersAlreadyExtracted> {
let header = if let Some(header) = req.headers().ok_or(HeadersAlreadyExtracted)?.get(&key) {
header
} else {
return Ok(false);
};
if let Ok(header) = std::str::from_utf8(header.as_bytes()) {
Ok(header.to_ascii_lowercase().contains(value))
} else {
Ok(false)
}
}
struct WebSocketUpgradeResponse<F> {
extractor: WebSocketUpgrade,
callback: F,
}
impl<F, Fut> IntoResponse for WebSocketUpgradeResponse<F>
where
F: FnOnce(WebSocket) -> Fut + Send + 'static,
Fut: Future + Send + 'static,
{
type Body = Full<Bytes>;
type BodyError = <Self::Body as http_body::Body>::Error;
fn into_response(self) -> Response<Self::Body> {
// check requested protocols
let protocol = self
.extractor
.sec_websocket_protocol
.as_ref()
.and_then(|req_protocols| {
let req_protocols = req_protocols.to_str().ok()?;
let protocols = self.extractor.protocols.as_ref()?;
req_protocols
.split(',')
.map(|req_p| req_p.trim())
.find(|req_p| protocols.iter().any(|p| p == req_p))
});
let protocol = match protocol {
Some(protocol) => {
if let Ok(protocol) = HeaderValue::from_str(protocol) {
Some(protocol)
} else {
return (
StatusCode::BAD_REQUEST,
"`Sec-Websocket-Protocol` header is invalid",
)
.into_response();
}
}
None => None,
};
let callback = self.callback;
let on_upgrade = self.extractor.on_upgrade;
let config = self.extractor.config;
tokio::spawn(async move {
let upgraded = on_upgrade.await.expect("connection upgrade failed");
let socket =
WebSocketStream::from_raw_socket(upgraded, protocol::Role::Server, Some(config))
.await;
let socket = WebSocket { inner: socket };
callback(socket).await;
});
let mut builder = Response::builder()
.status(StatusCode::SWITCHING_PROTOCOLS)
.header(
header::CONNECTION,
HeaderValue::from_str("upgrade").unwrap(),
)
.header(header::UPGRADE, HeaderValue::from_str("websocket").unwrap())
.header(
header::SEC_WEBSOCKET_ACCEPT,
sign(self.extractor.sec_websocket_key.as_bytes()),
);
if let Some(protocol) = protocol {
builder = builder.header(header::SEC_WEBSOCKET_PROTOCOL, protocol);
}
builder.body(Full::default()).unwrap()
}
}
/// A stream of WebSocket messages.
#[derive(Debug)]
pub struct WebSocket {
inner: WebSocketStream<Upgraded>,
}
impl WebSocket {
/// Receive another message.
///
/// Returns `None` if the stream stream has closed.
pub async fn recv(&mut self) -> Option<Result<Message, Error>> {
self.next().await
}
/// Send a message.
pub async fn send(&mut self, msg: Message) -> Result<(), Error> {
self.inner
.send(msg.into_tungstenite())
.await
.map_err(Error::new)
}
/// Gracefully close this WebSocket.
pub async fn close(mut self) -> Result<(), Error> {
self.inner.close(None).await.map_err(Error::new)
}
}
impl Stream for WebSocket {
type Item = Result<Message, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.inner.poll_next_unpin(cx).map(|option_msg| {
option_msg.map(|result_msg| {
result_msg
.map_err(Error::new)
.map(Message::from_tungstenite)
})
})
}
}
impl Sink<Message> for WebSocket {
type Error = Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.inner).poll_ready(cx).map_err(Error::new)
}
fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
Pin::new(&mut self.inner)
.start_send(item.into_tungstenite())
.map_err(Error::new)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.inner).poll_flush(cx).map_err(Error::new)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.inner).poll_close(cx).map_err(Error::new)
}
}
/// Status code used to indicate why an endpoint is closing the WebSocket connection.
pub type CloseCode = u16;
/// A struct representing the close command.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct CloseFrame<'t> {
/// The reason as a code.
pub code: CloseCode,
/// The reason as text string.
pub reason: Cow<'t, str>,
}
/// A WebSocket message.
//
// This code comes from https://github.com/snapview/tungstenite-rs/blob/master/src/protocol/message.rs and is under following license:
// Copyright (c) 2017 <NAME>
// Copyright (c) 2016 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum Message {
/// A text WebSocket message
Text(String),
/// A binary WebSocket message
Binary(Vec<u8>),
/// A ping message with the specified payload
///
/// The payload here must have a length less than 125 bytes
Ping(Vec<u8>),
/// A pong message with the specified payload
///
/// The payload here must have a length less than 125 bytes
Pong(Vec<u8>),
/// A close message with the optional close frame.
Close(Option<CloseFrame<'static>>),
}
impl Message {
fn into_tungstenite(self) -> tungstenite::Message {
// TODO: maybe some shorter way to do that?
match self {
Self::Text(text) => tungstenite::Message::Text(text),
Self::Binary(binary) => tungstenite::Message::Binary(binary),
Self::Ping(ping) => tungstenite::Message::Ping(ping),
Self::Pong(pong) => tungstenite::Message::Pong(pong),
Self::Close(Some(close)) => {
tungstenite::Message::Close(Some(tungstenite::protocol::CloseFrame {
code: tungstenite::protocol::frame::coding::CloseCode::from(close.code),
reason: close.reason,
}))
}
Self::Close(None) => tungstenite::Message::Close(None),
}
}
fn from_tungstenite(message: tungstenite::Message) -> Self {
// TODO: maybe some shorter way to do that?
match message {
tungstenite::Message::Text(text) => Self::Text(text),
tungstenite::Message::Binary(binary) => Self::Binary(binary),
tungstenite::Message::Ping(ping) => Self::Ping(ping),
tungstenite::Message::Pong(pong) => Self::Pong(pong),
tungstenite::Message::Close(Some(close)) => Self::Close(Some(CloseFrame {
code: close.code.into(),
reason: close.reason,
})),
tungstenite::Message::Close(None) => Self::Close(None),
}
}
/// Consume the WebSocket and return it as binary data.
pub fn into_data(self) -> Vec<u8> {
match self {
Self::Text(string) => string.into_bytes(),
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => data,
Self::Close(None) => Vec::new(),
Self::Close(Some(frame)) => frame.reason.into_owned().into_bytes(),
}
}
/// Attempt to consume the WebSocket message and convert it to a String.
pub fn into_text(self) -> Result<String, Error> {
match self {
Self::Text(string) => Ok(string),
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => Ok(String::from_utf8(data)
.map_err(|err| err.utf8_error())
.map_err(Error::new)?),
Self::Close(None) => Ok(String::new()),
Self::Close(Some(frame)) => Ok(frame.reason.into_owned()),
}
}
/// Attempt to get a &str from the WebSocket message,
/// this will try to convert binary data to utf8.
pub fn to_text(&self) -> Result<&str, Error> {
match *self {
Self::Text(ref string) => Ok(string),
Self::Binary(ref data) | Self::Ping(ref data) | Self::Pong(ref data) => {
Ok(std::str::from_utf8(data).map_err(Error::new)?)
}
Self::Close(None) => Ok(""),
Self::Close(Some(ref frame)) => Ok(&frame.reason),
}
}
}
impl From<Message> for Vec<u8> {
fn from(msg: Message) -> Self {
msg.into_data()
}
}
fn sign(key: &[u8]) -> HeaderValue {
let mut sha1 = Sha1::default();
sha1.update(key);
sha1.update(&b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"[..]);
let b64 = Bytes::from(base64::encode(&sha1.finalize()));
HeaderValue::from_maybe_shared(b64).expect("base64 is a valid value")
}
pub mod rejection {
//! WebSocket specific rejections.
use crate::extract::rejection::*;
define_rejection! {
#[status = METHOD_NOT_ALLOWED]
#[body = "Request method must be `GET`"]
/// Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).
pub struct MethodNotGet;
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "Connection header did not include 'upgrade'"]
/// Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).
pub struct InvalidConnectionHeader;
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "`Upgrade` header did not include 'websocket'"]
/// Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).
pub struct InvalidUpgradeHeader;
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "`Sec-Websocket-Version` header did not include '13'"]
/// Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).
pub struct InvalidWebsocketVersionHeader;
}
define_rejection! {
#[status = BAD_REQUEST]
#[body = "`Sec-Websocket-Key` header missing"]
/// Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade).
pub struct WebsocketKeyHeaderMissing;
}
composite_rejection! {
/// Rejection used for [`WebSocketUpgrade`](super::WebSocketUpgrade).
///
/// Contains one variant for each way the [`WebSocketUpgrade`](super::WebSocketUpgrade)
/// extractor can fail.
pub enum WebSocketUpgradeRejection {
MethodNotGet,
InvalidConnectionHeader,
InvalidUpgradeHeader,
InvalidWebsocketVersionHeader,
WebsocketKeyHeaderMissing,
HeadersAlreadyExtracted,
ExtensionsAlreadyExtracted,
}
}
}
<file_sep>//! Run with
//!
//! ```not_rust
//! cargo run -p example-sse
//! ```
use axum::{
extract::TypedHeader,
handler::get,
http::StatusCode,
response::sse::{Event, Sse},
Router,
};
use futures::stream::{self, Stream};
use std::{convert::Infallible, net::SocketAddr, time::Duration};
use tokio_stream::StreamExt as _;
use tower_http::{services::ServeDir, trace::TraceLayer};
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "example_sse=debug,tower_http=debug")
}
tracing_subscriber::fmt::init();
let static_files_service = axum::service::get(
ServeDir::new("examples/sse/assets").append_index_html_on_directories(true),
)
.handle_error(|error: std::io::Error| {
Ok::<_, std::convert::Infallible>((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
))
});
// build our application with a route
let app = Router::new()
.nest("/", static_files_service)
.route("/sse", get(sse_handler))
.layer(TraceLayer::new_for_http());
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn sse_handler(
TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
println!("`{}` connected", user_agent.as_str());
// A `Stream` that repeats an event every second
let stream = stream::repeat_with(|| Event::default().data("hi!"))
.map(Ok)
.throttle(Duration::from_secs(1));
Sse::new(stream)
}
<file_sep>//! HTTP body utilities.
use crate::BoxError;
use crate::Error;
mod stream_body;
pub use self::stream_body::StreamBody;
#[doc(no_inline)]
pub use http_body::{Body as HttpBody, Empty, Full};
#[doc(no_inline)]
pub use hyper::body::Body;
#[doc(no_inline)]
pub use bytes::Bytes;
/// A boxed [`Body`] trait object.
///
/// This is used in axum as the response body type for applications. Its
/// necessary to unify multiple response bodies types into one.
pub type BoxBody = http_body::combinators::BoxBody<Bytes, Error>;
/// Convert a [`http_body::Body`] into a [`BoxBody`].
pub fn box_body<B>(body: B) -> BoxBody
where
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError>,
{
body.map_err(Error::new).boxed()
}
pub(crate) fn empty() -> BoxBody {
box_body(http_body::Empty::new())
}
<file_sep>//! axum is a web application framework that focuses on ergonomics and modularity.
//!
//! # Table of contents
//!
//! - [High level features](#high-level-features)
//! - [Compatibility](#compatibility)
//! - [Handlers](#handlers)
//! - [Routing](#routing)
//! - [Precedence](#precedence)
//! - [Matching multiple methods](#matching-multiple-methods)
//! - [Routing to any `Service`](#routing-to-any-service)
//! - [Routing to fallible services](#routing-to-fallible-services)
//! - [Nesting routes](#nesting-routes)
//! - [Extractors](#extractors)
//! - [Building responses](#building-responses)
//! - [Applying middleware](#applying-middleware)
//! - [To individual handlers](#to-individual-handlers)
//! - [To groups of routes](#to-groups-of-routes)
//! - [Error handling](#error-handling)
//! - [Applying multiple middleware](#applying-multiple-middleware)
//! - [Commonly used middleware](#commonly-used-middleware)
//! - [Writing your own middleware](#writing-your-own-middleware)
//! - [Sharing state with handlers](#sharing-state-with-handlers)
//! - [Required dependencies](#required-dependencies)
//! - [Examples](#examples)
//! - [Feature flags](#feature-flags)
//!
//! # High level features
//!
//! - Route requests to handlers with a macro free API.
//! - Declaratively parse requests using extractors.
//! - Simple and predictable error handling model.
//! - Generate responses with minimal boilerplate.
//! - Take full advantage of the [`tower`] and [`tower-http`] ecosystem of
//! middleware, services, and utilities.
//!
//! In particular the last point is what sets `axum` apart from other frameworks.
//! `axum` doesn't have its own middleware system but instead uses
//! [`tower::Service`]. This means `axum` gets timeouts, tracing, compression,
//! authorization, and more, for free. It also enables you to share middleware with
//! applications written using [`hyper`] or [`tonic`].
//!
//! # Compatibility
//!
//! axum is designed to work with [tokio] and [hyper]. Runtime and
//! transport layer independence is not a goal, at least for the time being.
//!
//! # Example
//!
//! The "Hello, World!" of axum is:
//!
//! ```rust,no_run
//! use axum::{
//! handler::get,
//! Router,
//! };
//!
//! #[tokio::main]
//! async fn main() {
//! // build our application with a single route
//! let app = Router::new().route("/", get(|| async { "Hello, World!" }));
//!
//! // run it with hyper on localhost:3000
//! axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
//! .serve(app.into_make_service())
//! .await
//! .unwrap();
//! }
//! ```
//!
//! # Handlers
//!
//! In axum a "handler" is an async function that accepts zero or more
//! ["extractors"](#extractors) as arguments and returns something that
//! can be converted [into a response](#building-responses).
//!
//! Handlers is where your custom domain logic lives and axum applications are
//! built by routing between handlers.
//!
//! Some examples of handlers:
//!
//! ```rust
//! use bytes::Bytes;
//! use http::StatusCode;
//!
//! // Handler that immediately returns an empty `200 OK` response.
//! async fn unit_handler() {}
//!
//! // Handler that immediately returns an empty `200 OK` response with a plain
//! // text body.
//! async fn string_handler() -> String {
//! "Hello, World!".to_string()
//! }
//!
//! // Handler that buffers the request body and returns it.
//! async fn echo(body: Bytes) -> Result<String, StatusCode> {
//! if let Ok(string) = String::from_utf8(body.to_vec()) {
//! Ok(string)
//! } else {
//! Err(StatusCode::BAD_REQUEST)
//! }
//! }
//! ```
//!
//! # Routing
//!
//! Routing between handlers looks like this:
//!
//! ```rust,no_run
//! use axum::{
//! handler::get,
//! Router,
//! };
//!
//! let app = Router::new()
//! .route("/", get(get_slash).post(post_slash))
//! .route("/foo", get(get_foo));
//!
//! async fn get_slash() {
//! // `GET /` called
//! }
//!
//! async fn post_slash() {
//! // `POST /` called
//! }
//!
//! async fn get_foo() {
//! // `GET /foo` called
//! }
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! Routes can also be dynamic like `/users/:id`. See [extractors](#extractors)
//! for more details.
//!
//! You can also define routes separately and merge them with [`Router::or`].
//!
//! ## Precedence
//!
//! Note that routes are matched _bottom to top_ so routes that should have
//! higher precedence should be added _after_ routes with lower precedence:
//!
//! ```rust
//! use axum::{
//! body::{Body, BoxBody},
//! handler::get,
//! http::Request,
//! Router,
//! };
//! use tower::{Service, ServiceExt};
//! use http::{Method, Response, StatusCode};
//! use std::convert::Infallible;
//!
//! # #[tokio::main]
//! # async fn main() {
//! // `/foo` also matches `/:key` so adding the routes in this order means `/foo`
//! // will be inaccessible.
//! let mut app = Router::new()
//! .route("/foo", get(|| async { "/foo called" }))
//! .route("/:key", get(|| async { "/:key called" }));
//!
//! // Even though we use `/foo` as the request URI, `/:key` takes precedence
//! // since its defined last.
//! let (status, body) = call_service(&mut app, Method::GET, "/foo").await;
//! assert_eq!(status, StatusCode::OK);
//! assert_eq!(body, "/:key called");
//!
//! // We have to add `/foo` after `/:key` since routes are matched bottom to
//! // top.
//! let mut new_app = Router::new()
//! .route("/:key", get(|| async { "/:key called" }))
//! .route("/foo", get(|| async { "/foo called" }));
//!
//! // Now it works
//! let (status, body) = call_service(&mut new_app, Method::GET, "/foo").await;
//! assert_eq!(status, StatusCode::OK);
//! assert_eq!(body, "/foo called");
//!
//! // And the other route works as well
//! let (status, body) = call_service(&mut new_app, Method::GET, "/bar").await;
//! assert_eq!(status, StatusCode::OK);
//! assert_eq!(body, "/:key called");
//!
//! // Little helper function to make calling a service easier. Just for
//! // demonstration purposes.
//! async fn call_service<S>(
//! svc: &mut S,
//! method: Method,
//! uri: &str,
//! ) -> (StatusCode, String)
//! where
//! S: Service<Request<Body>, Response = Response<BoxBody>, Error = Infallible>
//! {
//! let req = Request::builder().method(method).uri(uri).body(Body::empty()).unwrap();
//! let res = svc.ready().await.unwrap().call(req).await.unwrap();
//!
//! let status = res.status();
//!
//! let body = res.into_body();
//! let body = hyper::body::to_bytes(body).await.unwrap();
//! let body = String::from_utf8(body.to_vec()).unwrap();
//!
//! (status, body)
//! }
//! # }
//! ```
//!
//! ## Routing to any [`Service`]
//!
//! axum also supports routing to general [`Service`]s:
//!
//! ```rust,no_run
//! use axum::{
//! body::Body,
//! http::Request,
//! Router,
//! service
//! };
//! use tower_http::services::ServeFile;
//! use http::Response;
//! use std::convert::Infallible;
//! use tower::service_fn;
//!
//! let app = Router::new()
//! .route(
//! // Any request to `/` goes to a service
//! "/",
//! // Services who's response body is not `axum::body::BoxBody`
//! // can be wrapped in `axum::service::any` (or one of the other routing filters)
//! // to have the response body mapped
//! service::any(service_fn(|_: Request<Body>| async {
//! let res = Response::new(Body::from("Hi from `GET /`"));
//! Ok(res)
//! }))
//! )
//! .route(
//! "/foo",
//! // This service's response body is `axum::body::BoxBody` so
//! // it can be routed to directly.
//! service_fn(|req: Request<Body>| async move {
//! let body = Body::from(format!("Hi from `{} /foo`", req.method()));
//! let body = axum::body::box_body(body);
//! let res = Response::new(body);
//! Ok(res)
//! })
//! )
//! .route(
//! // GET `/static/Cargo.toml` goes to a service from tower-http
//! "/static/Cargo.toml",
//! service::get(ServeFile::new("Cargo.toml"))
//! );
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! Routing to arbitrary services in this way has complications for backpressure
//! ([`Service::poll_ready`]). See the [`service`] module for more details.
//!
//! ### Routing to fallible services
//!
//! Note that routing to general services has a small gotcha when it comes to
//! errors. axum currently does not support mixing routes to fallible services
//! with infallible handlers. For example this does _not_ compile:
//!
//! ```compile_fail
//! use axum::{
//! Router,
//! service,
//! handler::get,
//! http::{Request, Response},
//! body::Body,
//! };
//! use std::io;
//! use tower::service_fn;
//!
//! let app = Router::new()
//! // this route cannot fail
//! .route("/foo", get(|| async {}))
//! // this route can fail with io::Error
//! .route(
//! "/",
//! service::get(service_fn(|_req: Request<Body>| async {
//! let contents = tokio::fs::read_to_string("some_file").await?;
//! Ok::<_, io::Error>(Response::new(Body::from(contents)))
//! })),
//! );
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! The solution is to use [`handle_error`] and handle the error from the
//! service:
//!
//! ```
//! use axum::{
//! Router,
//! service,
//! handler::get,
//! http::{Request, Response},
//! response::IntoResponse,
//! body::Body,
//! };
//! use std::{io, convert::Infallible};
//! use tower::service_fn;
//!
//! let app = Router::new()
//! // this route cannot fail
//! .route("/foo", get(|| async {}))
//! // this route can fail with io::Error
//! .route(
//! "/",
//! service::get(service_fn(|_req: Request<Body>| async {
//! let contents = tokio::fs::read_to_string("some_file").await?;
//! Ok::<_, io::Error>(Response::new(Body::from(contents)))
//! }))
//! .handle_error(handle_io_error),
//! );
//!
//! fn handle_io_error(error: io::Error) -> Result<impl IntoResponse, Infallible> {
//! # Ok(())
//! // ...
//! }
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! In this particular case you can also handle the error directly in
//! `service_fn` but that is not possible, if you're routing to a service which
//! you don't control.
//!
//! See ["Error handling"](#error-handling) for more details on [`handle_error`]
//! and error handling in general.
//!
//! ## Nesting routes
//!
//! Routes can be nested by calling [`Router::nest`](routing::Router::nest):
//!
//! ```rust,no_run
//! use axum::{
//! body::{Body, BoxBody},
//! http::Request,
//! handler::get,
//! Router,
//! routing::BoxRoute
//! };
//! use tower_http::services::ServeFile;
//! use http::Response;
//!
//! fn api_routes() -> Router<BoxRoute> {
//! Router::new()
//! .route("/users", get(|_: Request<Body>| async { /* ... */ }))
//! .boxed()
//! }
//!
//! let app = Router::new()
//! .route("/", get(|_: Request<Body>| async { /* ... */ }))
//! .nest("/api", api_routes());
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! Note that nested routes will not see the orignal request URI but instead
//! have the matched prefix stripped. This is necessary for services like static
//! file serving to work. Use [`OriginalUri`] if you need the original request
//! URI.
//!
//! # Extractors
//!
//! An extractor is a type that implements [`FromRequest`]. Extractors is how
//! you pick apart the incoming request to get the parts your handler needs.
//!
//! For example, [`extract::Json`] is an extractor that consumes the request
//! body and deserializes it as JSON into some target type:
//!
//! ```rust,no_run
//! use axum::{
//! extract,
//! handler::post,
//! Router,
//! };
//! use serde::Deserialize;
//!
//! let app = Router::new().route("/users", post(create_user));
//!
//! #[derive(Deserialize)]
//! struct CreateUser {
//! email: String,
//! password: String,
//! }
//!
//! async fn create_user(payload: extract::Json<CreateUser>) {
//! let payload: CreateUser = payload.0;
//!
//! // ...
//! }
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! [`extract::Path`] can be used to extract params from a dynamic URL. It
//! is compatible with any type that implements [`serde::Deserialize`], such as
//! [`Uuid`]:
//!
//! ```rust,no_run
//! use axum::{
//! extract,
//! handler::post,
//! Router,
//! };
//! use uuid::Uuid;
//!
//! let app = Router::new().route("/users/:id", post(create_user));
//!
//! async fn create_user(extract::Path(user_id): extract::Path<Uuid>) {
//! // ...
//! }
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! You can also apply multiple extractors:
//!
//! ```rust,no_run
//! use axum::{
//! extract,
//! handler::get,
//! Router,
//! };
//! use uuid::Uuid;
//! use serde::Deserialize;
//!
//! let app = Router::new().route("/users/:id/things", get(get_user_things));
//!
//! #[derive(Deserialize)]
//! struct Pagination {
//! page: usize,
//! per_page: usize,
//! }
//!
//! impl Default for Pagination {
//! fn default() -> Self {
//! Self { page: 1, per_page: 30 }
//! }
//! }
//!
//! async fn get_user_things(
//! extract::Path(user_id): extract::Path<Uuid>,
//! pagination: Option<extract::Query<Pagination>>,
//! ) {
//! let pagination: Pagination = pagination.unwrap_or_default().0;
//!
//! // ...
//! }
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! Additionally `Request<Body>` is itself an extractor:
//!
//! ```rust,no_run
//! use axum::{
//! body::Body,
//! handler::post,
//! http::Request,
//! Router,
//! };
//!
//! let app = Router::new().route("/users/:id", post(handler));
//!
//! async fn handler(req: Request<Body>) {
//! // ...
//! }
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! However it cannot be combined with other extractors since it consumes the
//! entire request.
//!
//! See the [`extract`] module for more details.
//!
//! [`Uuid`]: https://docs.rs/uuid/latest/uuid/
//! [`FromRequest`]: crate::extract::FromRequest
//!
//! # Building responses
//!
//! Anything that implements [`IntoResponse`](response::IntoResponse) can be
//! returned from a handler:
//!
//! ```rust,no_run
//! use axum::{
//! body::Body,
//! handler::{get, Handler},
//! http::{Request, header::{HeaderMap, HeaderName, HeaderValue}},
//! response::{IntoResponse, Html, Json, Headers},
//! Router,
//! };
//! use http::{StatusCode, Response, Uri};
//! use serde_json::{Value, json};
//!
//! // We've already seen returning &'static str
//! async fn plain_text() -> &'static str {
//! "foo"
//! }
//!
//! // String works too and will get a `text/plain` content-type
//! async fn plain_text_string(uri: Uri) -> String {
//! format!("Hi from {}", uri.path())
//! }
//!
//! // Bytes will get a `application/octet-stream` content-type
//! async fn bytes() -> Vec<u8> {
//! vec![1, 2, 3, 4]
//! }
//!
//! // `()` gives an empty response
//! async fn empty() {}
//!
//! // `StatusCode` gives an empty response with that status code
//! async fn empty_with_status() -> StatusCode {
//! StatusCode::NOT_FOUND
//! }
//!
//! // A tuple of `StatusCode` and something that implements `IntoResponse` can
//! // be used to override the status code
//! async fn with_status() -> (StatusCode, &'static str) {
//! (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong")
//! }
//!
//! // A tuple of `HeaderMap` and something that implements `IntoResponse` can
//! // be used to override the headers
//! async fn with_headers() -> (HeaderMap, &'static str) {
//! let mut headers = HeaderMap::new();
//! headers.insert(
//! HeaderName::from_static("x-foo"),
//! HeaderValue::from_static("foo"),
//! );
//! (headers, "foo")
//! }
//!
//! // You can also override both status and headers at the same time
//! async fn with_headers_and_status() -> (StatusCode, HeaderMap, &'static str) {
//! let mut headers = HeaderMap::new();
//! headers.insert(
//! HeaderName::from_static("x-foo"),
//! HeaderValue::from_static("foo"),
//! );
//! (StatusCode::INTERNAL_SERVER_ERROR, headers, "foo")
//! }
//!
//! // `Headers` makes building the header map easier and `impl Trait` is easier
//! // so you don't have to write the whole type
//! async fn with_easy_headers() -> impl IntoResponse {
//! Headers(vec![("x-foo", "foo")])
//! }
//!
//! // `Html` gives a content-type of `text/html`
//! async fn html() -> Html<&'static str> {
//! Html("<h1>Hello, World!</h1>")
//! }
//!
//! // `Json` gives a content-type of `application/json` and works with any type
//! // that implements `serde::Serialize`
//! async fn json() -> Json<Value> {
//! Json(json!({ "data": 42 }))
//! }
//!
//! // `Result<T, E>` where `T` and `E` implement `IntoResponse` is useful for
//! // returning errors
//! async fn result() -> Result<&'static str, StatusCode> {
//! Ok("all good")
//! }
//!
//! // `Response` gives full control
//! async fn response() -> Response<Body> {
//! Response::builder().body(Body::empty()).unwrap()
//! }
//!
//! let app = Router::new()
//! .route("/plain_text", get(plain_text))
//! .route("/plain_text_string", get(plain_text_string))
//! .route("/bytes", get(bytes))
//! .route("/empty", get(empty))
//! .route("/empty_with_status", get(empty_with_status))
//! .route("/with_status", get(with_status))
//! .route("/with_headers", get(with_headers))
//! .route("/with_headers_and_status", get(with_headers_and_status))
//! .route("/with_easy_headers", get(with_easy_headers))
//! .route("/html", get(html))
//! .route("/json", get(json))
//! .route("/result", get(result))
//! .route("/response", get(response));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! # Applying middleware
//!
//! axum is designed to take full advantage of the tower and tower-http
//! ecosystem of middleware.
//!
//! If you're new to tower we recommend you read its [guides][tower-guides] for
//! a general introduction to tower and its concepts.
//!
//! ## To individual handlers
//!
//! A middleware can be applied to a single handler like so:
//!
//! ```rust,no_run
//! use axum::{
//! handler::{get, Handler},
//! Router,
//! };
//! use tower::limit::ConcurrencyLimitLayer;
//!
//! let app = Router::new()
//! .route(
//! "/",
//! get(handler.layer(ConcurrencyLimitLayer::new(100))),
//! );
//!
//! async fn handler() {}
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! ## To groups of routes
//!
//! Middleware can also be applied to a group of routes like so:
//!
//! ```rust,no_run
//! use axum::{
//! handler::{get, post},
//! Router,
//! };
//! use tower::limit::ConcurrencyLimitLayer;
//!
//! async fn handler() {}
//!
//! let app = Router::new()
//! .route("/", get(handler))
//! .route("/foo", post(handler))
//! .layer(ConcurrencyLimitLayer::new(100));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! Note that [`Router::layer`] applies the middleware to all previously added
//! routes, of that particular `Router`. If you need multiple groups of routes
//! with different middleware build them separately and combine them with
//! [`Router::or`]:
//!
//! ```rust,no_run
//! use axum::{
//! handler::{get, post},
//! Router,
//! };
//! use tower::limit::ConcurrencyLimitLayer;
//! # type MyAuthLayer = tower::layer::util::Identity;
//!
//! async fn handler() {}
//!
//! let foo = Router::new()
//! .route("/", get(handler))
//! .route("/foo", post(handler))
//! .layer(ConcurrencyLimitLayer::new(100));
//!
//! let bar = Router::new()
//! .route("/requires-auth", get(handler))
//! .layer(MyAuthLayer::new());
//!
//! let app = foo.or(bar);
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! ## Error handling
//!
//! Handlers created from async functions must always produce a response, even
//! when returning a `Result<T, E>` the error type must implement
//! [`IntoResponse`]. In practice this makes error handling very predictable and
//! easier to reason about.
//!
//! However when applying middleware, or embedding other tower services, errors
//! might happen. For example [`Timeout`] will return an error if the timeout
//! elapses. By default these errors will be propagated all the way up to hyper
//! where the connection will be closed. If that isn't desirable you can call
//! [`handle_error`](handler::Layered::handle_error) to handle errors from
//! adding a middleware to a handler:
//!
//! ```rust,no_run
//! use axum::{
//! handler::{get, Handler},
//! Router,
//! };
//! use tower::{
//! BoxError, timeout::{TimeoutLayer, error::Elapsed},
//! };
//! use std::{borrow::Cow, time::Duration, convert::Infallible};
//! use http::StatusCode;
//!
//! let app = Router::new()
//! .route(
//! "/",
//! get(handle
//! .layer(TimeoutLayer::new(Duration::from_secs(30)))
//! // `Timeout` uses `BoxError` as the error type
//! .handle_error(|error: BoxError| {
//! // Check if the actual error type is `Elapsed` which
//! // `Timeout` returns
//! if error.is::<Elapsed>() {
//! return Ok::<_, Infallible>((
//! StatusCode::REQUEST_TIMEOUT,
//! "Request took too long".into(),
//! ));
//! }
//!
//! // If we encounter some error we don't handle return a generic
//! // error
//! return Ok::<_, Infallible>((
//! StatusCode::INTERNAL_SERVER_ERROR,
//! // `Cow` lets us return either `&str` or `String`
//! Cow::from(format!("Unhandled internal error: {}", error)),
//! ));
//! })),
//! );
//!
//! async fn handle() {}
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! The closure passed to [`handle_error`](handler::Layered::handle_error) must
//! return `Result<T, E>` where `T` implements
//! [`IntoResponse`](response::IntoResponse).
//!
//! See [`routing::Router::handle_error`] for more details.
//!
//! ## Applying multiple middleware
//!
//! [`tower::ServiceBuilder`] can be used to combine multiple middleware:
//!
//! ```rust,no_run
//! use axum::{
//! body::Body,
//! handler::get,
//! http::Request,
//! Router,
//! };
//! use tower::ServiceBuilder;
//! use tower_http::compression::CompressionLayer;
//! use std::{borrow::Cow, time::Duration};
//!
//! let middleware_stack = ServiceBuilder::new()
//! // Return an error after 30 seconds
//! .timeout(Duration::from_secs(30))
//! // Shed load if we're receiving too many requests
//! .load_shed()
//! // Process at most 100 requests concurrently
//! .concurrency_limit(100)
//! // Compress response bodies
//! .layer(CompressionLayer::new())
//! .into_inner();
//!
//! let app = Router::new()
//! .route("/", get(|_: Request<Body>| async { /* ... */ }))
//! .layer(middleware_stack);
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! ## Commonly used middleware
//!
//! [`tower::util`] and [`tower_http`] have a large collection of middleware that are compatible
//! with axum. Some commonly used are:
//!
//! ```rust,no_run
//! use axum::{
//! body::{Body, BoxBody},
//! handler::get,
//! http::{Request, Response},
//! Router,
//! };
//! use tower::{
//! filter::AsyncFilterLayer,
//! util::AndThenLayer,
//! ServiceBuilder,
//! };
//! use std::convert::Infallible;
//! use tower_http::trace::TraceLayer;
//!
//! let middleware_stack = ServiceBuilder::new()
//! // `TraceLayer` adds high level tracing and logging
//! .layer(TraceLayer::new_for_http())
//! // `AsyncFilterLayer` lets you asynchronously transform the request
//! .layer(AsyncFilterLayer::new(map_request))
//! // `AndThenLayer` lets you asynchronously transform the response
//! .layer(AndThenLayer::new(map_response))
//! .into_inner();
//!
//! async fn map_request(req: Request<Body>) -> Result<Request<Body>, Infallible> {
//! Ok(req)
//! }
//!
//! async fn map_response(res: Response<BoxBody>) -> Result<Response<BoxBody>, Infallible> {
//! Ok(res)
//! }
//!
//! let app = Router::new()
//! .route("/", get(|| async { /* ... */ }))
//! .layer(middleware_stack);
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! Additionally axum provides [`extract::extractor_middleware()`] for converting any extractor into
//! a middleware. Among other things, this can be useful for doing authorization. See
//! [`extract::extractor_middleware()`] for more details.
//!
//! ## Writing your own middleware
//!
//! You can also write you own middleware by implementing [`tower::Service`]:
//!
//! ```
//! use axum::{
//! body::{Body, BoxBody},
//! handler::get,
//! http::{Request, Response},
//! Router,
//! };
//! use futures::future::BoxFuture;
//! use tower::{Service, layer::layer_fn};
//! use std::task::{Context, Poll};
//!
//! #[derive(Clone)]
//! struct MyMiddleware<S> {
//! inner: S,
//! }
//!
//! impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for MyMiddleware<S>
//! where
//! S: Service<Request<ReqBody>, Response = Response<ResBody>> + Clone + Send + 'static,
//! S::Future: Send + 'static,
//! ReqBody: Send + 'static,
//! ResBody: Send + 'static,
//! {
//! type Response = S::Response;
//! type Error = S::Error;
//! type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
//!
//! fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
//! self.inner.poll_ready(cx)
//! }
//!
//! fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
//! println!("`MyMiddleware` called!");
//!
//! // best practice is to clone the inner service like this
//! // see https://github.com/tower-rs/tower/issues/547 for details
//! let clone = self.inner.clone();
//! let mut inner = std::mem::replace(&mut self.inner, clone);
//!
//! Box::pin(async move {
//! let res: Response<ResBody> = inner.call(req).await?;
//!
//! println!("`MyMiddleware` received the response");
//!
//! Ok(res)
//! })
//! }
//! }
//!
//! let app = Router::new()
//! .route("/", get(|| async { /* ... */ }))
//! .layer(layer_fn(|inner| MyMiddleware { inner }));
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! # Sharing state with handlers
//!
//! It is common to share some state between handlers for example to share a
//! pool of database connections or clients to other services. That can be done
//! using the [`AddExtension`] middleware (applied with [`AddExtensionLayer`])
//! and the [`extract::Extension`] extractor:
//!
//! ```rust,no_run
//! use axum::{
//! AddExtensionLayer,
//! extract,
//! handler::get,
//! Router,
//! };
//! use std::sync::Arc;
//!
//! struct State {
//! // ...
//! }
//!
//! let shared_state = Arc::new(State { /* ... */ });
//!
//! let app = Router::new()
//! .route("/", get(handler))
//! .layer(AddExtensionLayer::new(shared_state));
//!
//! async fn handler(
//! state: extract::Extension<Arc<State>>,
//! ) {
//! let state: Arc<State> = state.0;
//!
//! // ...
//! }
//! # async {
//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
//! # };
//! ```
//!
//! # Required dependencies
//!
//! To use axum there are a few dependencies you have pull in as well:
//!
//! ```toml
//! [dependencies]
//! axum = "<latest-version>"
//! hyper = { version = "<latest-version>", features = ["full"] }
//! tokio = { version = "<latest-version>", features = ["full"] }
//! tower = "<latest-version>"
//! ```
//!
//! The `"full"` feature for hyper and tokio isn't strictly necessary but its
//! the easiest way to get started.
//!
//! Note that [`axum::Server`] is re-exported by axum so if thats all you need
//! then you don't have to explicitly depend on hyper.
//!
//! Tower isn't strictly necessary either but helpful for testing. See the
//! testing example in the repo to learn more about testing axum apps.
//!
//! # Examples
//!
//! The axum repo contains [a number of examples][examples] that show how to put all the
//! pieces together.
//!
//! # Feature flags
//!
//! axum uses a set of [feature flags] to reduce the amount of compiled and
//! optional dependencies.
//!
//! The following optional features are available:
//!
//! - `headers`: Enables extracting typed headers via [`extract::TypedHeader`].
//! - `http2`: Enables hyper's `http2` feature.
//! - `multipart`: Enables parsing `multipart/form-data` requests with [`extract::Multipart`].
//! - `tower-log`: Enables `tower`'s `log` feature. Enabled by default.
//! - `ws`: Enables WebSockets support via [`extract::ws`].
//!
//! [`tower`]: https://crates.io/crates/tower
//! [`tower-http`]: https://crates.io/crates/tower-http
//! [`tokio`]: http://crates.io/crates/tokio
//! [`hyper`]: http://crates.io/crates/hyper
//! [`tonic`]: http://crates.io/crates/tonic
//! [feature flags]: https://doc.rust-lang.org/cargo/reference/features.html#the-features-section
//! [`IntoResponse`]: crate::response::IntoResponse
//! [`Timeout`]: tower::timeout::Timeout
//! [examples]: https://github.com/tokio-rs/axum/tree/main/examples
//! [`Router::or`]: crate::routing::Router::or
//! [`axum::Server`]: hyper::server::Server
//! [`OriginalUri`]: crate::extract::OriginalUri
//! [`Service`]: tower::Service
//! [`Service::poll_ready`]: tower::Service::poll_ready
//! [`tower::Service`]: tower::Service
//! [`handle_error`]: routing::Router::handle_error
//! [tower-guides]: https://github.com/tower-rs/tower/tree/master/guides
#![warn(
clippy::all,
clippy::dbg_macro,
clippy::todo,
clippy::empty_enum,
clippy::enum_glob_use,
clippy::mem_forget,
clippy::unused_self,
clippy::filter_map_next,
clippy::needless_continue,
clippy::needless_borrow,
clippy::match_wildcard_for_single_variants,
clippy::if_let_mutex,
clippy::mismatched_target_os,
clippy::await_holding_lock,
clippy::match_on_vec_items,
clippy::imprecise_flops,
clippy::suboptimal_flops,
clippy::lossy_float_literal,
clippy::rest_pat_in_fully_bound_structs,
clippy::fn_params_excessive_bools,
clippy::exit,
clippy::inefficient_to_string,
clippy::linkedlist,
clippy::macro_use_imports,
clippy::option_option,
clippy::verbose_file_reads,
clippy::unnested_or_patterns,
rust_2018_idioms,
future_incompatible,
nonstandard_style,
missing_debug_implementations,
missing_docs
)]
#![deny(unreachable_pub, private_in_public)]
#![allow(elided_lifetimes_in_paths, clippy::type_complexity)]
#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(test, allow(clippy::float_cmp))]
#[macro_use]
pub(crate) mod macros;
mod buffer;
mod error;
mod json;
mod util;
pub mod body;
pub mod extract;
pub mod handler;
pub mod response;
pub mod routing;
pub mod service;
#[cfg(test)]
mod tests;
#[doc(no_inline)]
pub use async_trait::async_trait;
#[doc(no_inline)]
pub use http;
#[doc(no_inline)]
pub use hyper::Server;
#[doc(no_inline)]
pub use tower_http::add_extension::{AddExtension, AddExtensionLayer};
#[doc(inline)]
pub use self::{error::Error, json::Json, routing::Router};
/// Alias for a type-erased error type.
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
| 3fc657cb484164d28f503f94d5e4ef7910e55841 | [
"Markdown",
"Rust",
"TOML"
] | 69 | Rust | heliumbrain/axum | f5f6fa08f3691ab35b05128d848eb8e166d84c2b | d94221d786b24057d24d459f1694dd5444059372 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
from itertools import permutations
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import * # Imports all data Types
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
from pyspark.sql.functions import udf
conf = SparkConf().setMaster("local").setAppName("Aggregate Module")
sc = SparkContext(conf = conf) # Initalising or Configuring "Spark Context"
sqlContext = SQLContext(sc)
#############################################################################################################################################
#Text :- Tokenize Extract ngrams Stop word remover
# Columns :- OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName
#############################################################################################################################################
#1. Tokenize
# Data Type Exceptiion
def Tokenize(df,col,val):
Tok = udf(lambda s: s.split(val), StringType())
return df.select(Tok(df[col]).alias('StringTokenizer')).show()
#2. Extract ngrams
# Data Type Exceptiion
'''
>>> ["".join(perm) for perm in itertools.permutations("abc")]
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
'''
def ExtractAnagrams(df,col):
Ana = udf(lambda s: ["".join(perm) for perm in permutations(s)], StringType())
return df.select(Ana(df[col]).alias('StringAnaGrams')).show()
#3. Stop word remover
'''
'''
################################################################################################################################################
def convert(date_string):
date_new = date_string.split(" ")[0]
date_object = date(*map(int,(date_string.split(" ")[0].split("-"))))
return date_object
def dataFrame_Maker(*args):
File = args[0]
OrdersFile = sc.textFile(File)
header = OrdersFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
fields = [StructField(field_name, StringType(), False) for field_name in schemaString.split(',')]
fields[0].dataType = LongType()
fields[2].dataType = IntegerType()
fields[3].dataType = DateType()
fields[4].dataType = DateType()
fields[5].dataType = DateType()
fields[6].dataType = IntegerType()
fields[7].dataType = FloatType()
schema = StructType(fields)
OrdersHeader = OrdersFile.filter(lambda l: "OrderID" in l)
OrdersNoHeader = OrdersFile.subtract(OrdersHeader)
Orders_temp = OrdersNoHeader.map(lambda k: k.split(",")).map(lambda p:(int(p[0]),str(p[1].encode("utf-8")),int(p[2]),convert(p[3]),convert(p[4]),convert(p[5]),int(p[6]),float(p[7]),str(p[8].encode("utf-8"))))
Orders_df = sqlContext.createDataFrame(Orders_temp, schema)
return Orders_df
if __name__ == "__main__":
inputer = sys.argv[1]
df0 = dataFrame_Maker(inputer)
print "\n\n"
#print Tokenize(df0,8,' ')
print "\n\n"
print ExtractAnagrams(df0,1)
print "\n\n"
<file_sep>def up(df,i):
try:
int(df[i])
x=''
except ValueError:
x=df[i].upper()
return x
def upper(df,*args):
df1=df.fillna('')
df1=df1.fillna(0)
df1=df1.rdd
for arg in args:
df1=df1.map(lambda x:up(x,arg))
return df1<file_sep>def sortt(df,*args):
df1=df.na.fill(0)
df1=df1.na.fill('')
for arg in args:
df1=df1.select(arg).collect()
df1=sorted(df1)
return df1<file_sep>def isNull(df,*args):
count=0
for arg in args:
df=df.select(arg).collect()
for k in df:
if k[arg]==None:
count+=1
return count<file_sep>from pyspark import SparkContext
from pyspark import AccumulatorParam
import random
#creating spark context
sc=SparkContext()
#custom accumulator class
class VectorAccumulatorParam(AccumulatorParam):
def zero(self, value):
dict1={}
for i in range(0,len(value)):
dict1[i]=0
return dict1
def addInPlace(self, val1, val2):
for i in val1.keys():
val1[i] += val2[i]
return val1
#creating zero vector for addition
c={}
rand=[]
for i in range(0,100):
c[i]=0
#creating 10 vectors each with dimension 100 and randomly initialized
rand=[]
for j in range(0,10):
dict1={}
for i in range(0,100):
dict1[i]=random.random()
rand.append(dict1)
#creating rdd from 10 vectors
rdd1=sc.parallelize(rand)
#creating accumulator
va = sc.accumulator(c, VectorAccumulatorParam())
#action to be executed on rdd in order to sumup vectors
def sum(x):
global va
va += x
rdd1.foreach(sum)
#print the value of accumulator
print va.value
<file_sep>def funcat(df,i,j):
try:
int(df[i])
x1=''
except ValueError:
x1=str(df[i])
try:
int(df[j])
x2=''
except ValueError:
x2=str(df[j])
x=x1+x2
return x
def concat(df,arg1,arg2):
df1=df.fillna(0)
df1=df1.fillna('')
df1=df1.rdd
df1=df1.map(lambda x:funcat(x,arg1,arg2))
return df1<file_sep>def group(df,arg):
df1=df.groupBy(df.name).avg().collect()
return df1<file_sep>def fundiv(df,i,j):
try:
x1=int(df[i])
except ValueError:
x1=1
try:
x2=int(df[j])
except ValueError:
x2=1
x=x1/x2
return x
def div(df,arg1,arg2):
df1=df.fillna(0)
df1=df1.fillna('')
df1=df1.rdd
df1=df1.map(lambda x:fundiv(x,arg1,arg2))
return df<file_sep>def NulltoZero(df,*args):
a=list(args)
df=df.fillna(0,subset=a)
return df<file_sep># -*- coding: utf-8 -*-
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import HiveContext
from pyspark.sql import GroupedData
from pyspark.sql import DataFrameNaFunctions
from pyspark.sql import DataFrameStatFunctions
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql import Window
from pyspark.sql import SparkSession
conf = SparkConf().setMaster("local").setAppName("My App")
sc = SparkContext(conf = conf) #Initalising or Configuring "Spark Context"
sqlContext = SQLContext(sc)
################################################ End of Working with products.csv ###################################################
print("\n\n************************************* Working with products.csv ********************************************\n\n")
'''
ProductID ProductName SupplierID CategoryID QuantityPerUnit UnitPrice UnitsInStock UnitsOnOrder ReorderLevel Discontinued
'''
from pyspark.sql.types import *
ProductsFile = sc.textFile("/home/akhil/Desktop/3 Day Task/data/products.csv")
header = ProductsFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
#print(schemaString)
fields = [StructField(field_name, StringType(), True) for field_name in schemaString.split(',')]
#print(fields)
#print(len(fields) ) # how many elements in the header?
fields[0].dataType = IntegerType()
fields[2].dataType = IntegerType()
fields[3].dataType = IntegerType()
fields[5].dataType = FloatType()
fields[6].dataType = IntegerType()
fields[7].dataType = IntegerType()
fields[8].dataType = IntegerType()
fields[9].dataType = IntegerType()
#print("\n\n")
#print(fields)
#print("\n\n")
# We can get rid of any annoying leading underscores or change name of field by
# Eg: fields[0].name = 'id'
schema = StructType(fields)
#print(schema)
#print("\n\n")
ProductsHeader = ProductsFile.filter(lambda l: "ProductID" in l)
#print(ProductsHeader.collect())
#print("\n\n")
'''
Substract is used to remove Row from Table
'''
ProductsNoHeader = ProductsFile.subtract(ProductsHeader)
#print(ProductsNoHeader.count())
#print("\n\n")
Products_temp = ProductsNoHeader.map(lambda k: k.split(",")).map(lambda p: (int(p[0]),str(p[1].encode("utf-8")),int(p[2]),int(p[3]),str(p[4].encode("utf-8")),float(p[5]),int(p[6]),int(p[7]), int(p[8]),int(p[9])))
#print(Products_temp.top(2))
#print("\n\n")
Products_df = sqlContext.createDataFrame(Products_temp, schema)
#print(Products_df.head(8)) # look at the first 8 rows
#print("\n\n")
Products_df = ProductsNoHeader.map(lambda k: k.split(",")).map(lambda p: (int(p[0]),(p[1].strip('"')),int(p[2]),int(p[3]),(p[4].strip('"')),float(p[5]),int(p[6]),int(p[7]), int(p[8]),int(p[9]))).toDF(schema)
#print(Products_df.head(10))
#print("\n\n")
Q = Products_df.groupBy("SupplierID").count().show()
#print(Q)
print("\n\n")
#If we have missing values in the Discontinued. But how many are they?
Na = Products_df.filter(Products_df.Discontinued == '').count()
#print("\nMissing values in the Discontinued Field : ",Na)
#print("\n\n")
'''
dtypes and printSchema() methods can be used to get information about the schema, which can be useful further down in the data processing pipeline
'''
#print("\n Dtypes : ",Products_df.dtypes)
print("\n\n")
#print("\nSchema: ",Products_df.printSchema())
print("\n\n")
#Registering Table
Products_df.registerTempTable("Products")
#SQL Query
Q1 = sqlContext.sql("SELECT SupplierID, COUNT(*) AS COUNT FROM Products GROUP BY SupplierID ").show()
#print(Q1)
print("\n\n")
''' UnicodeEncodeError: 'ascii' codec can't encode character u'\xf4' in position 847: ordinal not in range(128)
sqlContext.sql("SELECT (*) FROM Products").show()
print("\n\n")
'''
'''
Imagine that at this point we want to change some column names: say, we want to shorten ProductID to ID, and similarly for the other 3 columns with lat/long information; we certainly do not want to run all the above procedure from the beginning – or even we might not have access to the initial CSV data, but only to the dataframe. We can do that using the dataframe method withColumnRenamed, chained as many times as required.
'''
Products_df = Products_df.withColumnRenamed('ProductID', 'ID').withColumnRenamed('SupplierID', 'SupID')
#print(Products_df.dtypes)
print("\n\n")
#Apply Filter On DF
X = Products_df.filter(Products_df.CategoryID == 2).count()
#print(X)
print("\n\n")
sqlContext.registerDataFrameAsTable(Products_df, "ProductsTable")
result = sqlContext.sql("SELECT * from ProductsTable")
#print(result)
print("\n\n")
################################################ End of Working with products.csv ######################################################
##
##
##################################################### Working with employees.csv ########################################################
print("\n\n****************************************** Working with employees.csv **************************************************\n\n")
'''
EmployeeID LastName FirstName Title TitleOfCourtesy BirthDate HireDate Address City Region PostalCode Country HomePhone Extension Photo Notes ReportsTo PhotoPath
'''
# Create a SparkSession
spark = SparkSession \
.builder \
.appName("My Bap") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
def mapper(line):
fields = line.split(',')
return Row(EmployeeID = (fields[0]), LastName = str(fields[1].encode("utf-8")),FirstName = str(fields[2].encode("utf-8")), Title = str(fields[3].encode("utf-8")), HireDate = str(fields[6].encode("utf-8")), Region = str(fields[9].encode("utf-8")))
lines = spark.sparkContext.textFile("/home/akhil/Desktop/3 Day Task/data/employees.csv")
header = lines.first()
lines = lines.filter(lambda line:line != header)
df = lines.map(mapper)
'''
SparkSession.createDataFrame(data, schema=None, samplingRatio=None, verifySchema=True)
Creates a DataFrame from an RDD, a list or a pandas.DataFrame.
When schema is a list of column names, the type of each column will be inferred from data.
When schema is None, it will try to infer the schema (column names and types) from data, which should be an RDD of Row, or namedtuple, or dict.
When schema is pyspark.sql.types.DataType or a datatype string, it must match the real data, or an exception will be thrown at runtime. If the given schema is not pyspark.sql.types.StructType, it will be wrapped into a pyspark.sql.types.StructType as its only field, and the field name will be “value”, each record will also be wrapped into a tuple, which can be converted to row later.
If schema inference is needed, samplingRatio is used to determined the ratio of rows used for schema inference. The first row will be used if samplingRatio is None.
Parameters:
data – an RDD of any kind of SQL data representation(e.g. row, tuple, int, boolean, etc.), or list, or pandas.DataFrame.
schema – a pyspark.sql.types.DataType or a datatype string or a list of column names, default is None. The data type string format equals to pyspark.sql.types.DataType.simpleString, except that top level struct type can omit the struct<> and atomic types use typeName() as their format, e.g. use byte instead of tinyint for pyspark.sql.types.ByteType. We can also use int as a short name for IntegerType.
samplingRatio – the sample ratio of rows used for inferring
verifySchema – verify data types of every row against schema.
Returns:
DataFrame
'''
'''
createDataFrame(data, schema=None, samplingRatio=None, verifySchema=True)
Creates a DataFrame from an RDD, a list or a pandas.DataFrame.
When schema is a list of column names, the type of each column will be inferred from data.
When schema is None, it will try to infer the schema (column names and types) from data, which should be an RDD of Row, or namedtuple, or dict.
When schema is pyspark.sql.types.DataType or a datatype string it must match the real data, or an exception will be thrown at runtime. If the given schema is not pyspark.sql.types.StructType, it will be wrapped into a pyspark.sql.types.StructType as its only field, and the field name will be “value”, each record will also be wrapped into a tuple, which can be converted to row later.
If schema inference is needed, samplingRatio is used to determined the ratio of rows used for schema inference. The first row will be used if samplingRatio is None.
Parameters:
data – an RDD of any kind of SQL data representation(e.g. Row, tuple, int, boolean, etc.), or list, or pandas.DataFrame.
schema – a pyspark.sql.types.DataType or a datatype string or a list of column names, default is None. The data type string format equals to pyspark.sql.types.DataType.simpleString, except that top level struct type can omit the struct<> and atomic types use typeName() as their format, e.g. use byte instead of tinyint for pyspark.sql.types.ByteType. We can also use int as a short name for pyspark.sql.types.IntegerType.
samplingRatio – the sample ratio of rows used for inferring
verifySchema – verify data types of every row against schema.
Returns:
DataFrame
'''
# Infer the schema, and register the DataFrame as a table.
EmployeesDf = spark.createDataFrame(df).cache()
EmployeesDf.createOrReplaceTempView("Employees")
print(EmployeesDf.select('EmployeeID').show(5))
EmployeesDf2 = spark.sql("SELECT EmployeeID AS ID,FirstName as Name from Employees").show()
print(EmployeesDf2)
print("\n\n")
#Use show() result as Schema but returns None Type obeject..Cannot use collect()
Q3 = sqlContext.sql("SELECT EmployeeID AS ID,FirstName as Name from Employees").show()
print(Q3)
print("\n\n")
from pyspark.sql.types import IntegerType
'''
registerFunction(name, f, returnType=StringType)
Registers a python function (including lambda function) as a UDF so it can be used in SQL statements.
In addition to a name and the function itself, the return type can be optionally specified. When the return type is not given it default to a string and conversion will automatically be done. For any other return type, the produced object must match the specified type.
Parameters:
name – name of the UDF
f – python function
returnType – a pyspark.sql.types.DataType object
'''
sqlContext.registerFunction("stringLengthInt", lambda x: len(x), IntegerType())
x = sqlContext.sql("SELECT stringLengthInt(Region) AS RegionLength From Employees").show()
print(x)
print("\n\n")
'''
sqlContext.sql() returns DataFrame
sql(sqlQuery)
Returns a DataFrame representing the result of the given query.
Returns: DataFrame
'''
sqlContext.registerDataFrameAsTable(EmployeesDf, "EmpTable")
'''
registerDataFrameAsTable(df, tableName)
Registers the given DataFrame as a temporary table in the catalog.
Temporary tables exist only during the lifetime of this instance of SQLContext.
dropTempTable(tableName)
Remove the temp table from catalog.
>>> sqlContext.registerDataFrameAsTable(df, "table1")
>>> sqlContext.dropTempTable("table1")
'''
df2 = sqlContext.table("EmpTable")
print(sorted(df.collect()) == sorted(df2.collect()))
print("\n\n")
sqlContext.sql("SELECT * FROM EmpTable").show()
print("\n\n")
############ Applying RRD Transforms on Data Frames
#people.filter(people.age > 30).join(department, people.deptId == department.id) \
# .groupBy(department.name, "gender").agg({"salary": "avg", "age": "max"})
'''
class pyspark.sql.DataFrame(jdf, sql_ctx)
A distributed collection of data grouped into named columns.
A DataFrame is equivalent to a relational table in Spark SQL, and can be created using various functions in SQLContext:
people = sqlContext.read.parquet("...")
Once created, it can be manipulated using the various domain-specific-language (DSL) functions defined in: DataFrame, Column.
To select a column from the data frame, use the apply method:
ageCol = people.age
A more concrete example:
# To create DataFrame using SQLContext
people = sqlContext.read.parquet("...")
department = sqlContext.read.parquet("...")
people.filter(people.age > 30).join(department, people.deptId == department.id) \
.groupBy(department.name, "gender").agg({"salary": "avg", "age": "max"})
'''
O = df2.agg({"EmployeeID": "max"}).collect()
print(O)
from pyspark.sql import functions as F
U = df2.agg(F.min(df2.EmployeeID)).collect()
print(U)
'''
agg(*exprs)
Aggregate on the entire DataFrame without groups (shorthand for df.groupBy.agg()).
'''
'''
alias(alias)
Returns a new DataFrame with an alias set.
'''
from pyspark.sql.functions import *
df_as1 = df2.alias("df_as1")
df_as2 = df2.alias("df_as2")
joined_df = df_as1.join(df_as2, col("df_as1.EmployeeID") == col("df_as2.EmployeeID"), 'inner')
Al = joined_df.select("df_as1.EmployeeID", "df_as2.EmployeeID", "df_as2.HireDate").collect()
print(Al)
#cache()
'''
cache()
Persists the DataFrame with the default storage level (MEMORY_AND_DISK).
Note The default storage level has changed to MEMORY_AND_DISK to match Scala in 2.0.
'''
#checkpoint(eager=True)
'''
checkpoint(eager=True)
Returns a checkpointed version of this Dataset. Checkpointing can be used to truncate the logical plan of this DataFrame, which is especially useful in iterative algorithms where the plan may grow exponentially. It will be saved to files inside the checkpoint directory set with SparkContext.setCheckpointDir().
Parameters: eager – Whether to checkpoint this DataFrame immediately
'''
#coalesce(numPartitions)
'''
coalesce(numPartitions)
Returns a new DataFrame that has exactly numPartitions partitions.
Similar to coalesce defined on an RDD, this operation results in a narrow dependency, e.g. if you go from 1000 partitions to 100 partitions, there will not be a shuffle, instead each of the 100 new partitions will claim 10 of the current partitions.
>>> df.coalesce(1).rdd.getNumPartitions()
1
'''
#collect()
'''
collect()
Returns all the records as a list of Row.
>>> df.collect()
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
'''
#columns
'''
columns
Returns all column names as a list.
>>> df.columns
['age', 'name']
'''
###############################################################################################################################################
# Statistics Functions on DF
#corr(col1, col2, method=None)
#cov(col1, col2)
'''
corr(col1, col2, method=None)
Calculates the correlation of two columns of a DataFrame as a double value. Currently only supports the Pearson Correlation Coefficient. DataFrame.corr() and DataFrameStatFunctions.corr() are aliases of each other.
Parameters:
col1 – The name of the first column
col2 – The name of the second column
method – The correlation method. Currently only supports “pearson”
cov(col1, col2)
Calculate the sample covariance for the given columns, specified by their names, as a double value. DataFrame.cov() and DataFrameStatFunctions.cov() are aliases.
Parameters:
col1 – The name of the first column
col2 – The name of the second column
'''
# Describe or Summary
'''
describe(*cols)
Computes statistics for numeric and string columns.
This include count, mean, stddev, min, and max. If no columns are given, this function computes statistics for all numerical or string columns.
Note This function is meant for exploratory data analysis, as we make no guarantee about the backward compatibility of the schema of the resulting DataFrame.
>>> df.describe(['age']).show()
+-------+------------------+
|summary| age|
+-------+------------------+
| count| 2|
| mean| 3.5|
| stddev|2.1213203435596424|
| min| 2|
| max| 5|
+-------+------------------+
>>> df.describe().show()
+-------+------------------+-----+
|summary| age| name|
+-------+------------------+-----+
| count| 2| 2|
| mean| 3.5| null|
| stddev|2.1213203435596424| null|
| min| 2|Alice|
| max| 5| Bob|
+-------+------------------+-----+
'''
#toPandas()
'''
toPandas()
Returns the contents of this DataFrame as Pandas pandas.DataFrame.
This is only available if Pandas is installed and available.
Note This method should only be used if the resulting Pandas’s DataFrame is expected to be small, as all the data is loaded into the driver’s memory.
>>> df.toPandas()
age name
0 2 Alice
1 5 Bob
'''
###############################################################################################################################################
#count()
'''
count()
Returns the number of rows in this DataFrame.
>>> df.count()
2
'''
#Views on Tables
'''
createGlobalTempView(name)
Creates a global temporary view with this DataFrame.
The lifetime of this temporary view is tied to this Spark application. throws TempTableAlreadyExistsException, if the view name already exists in the catalog.
>>> df.createGlobalTempView("people")
>>> df2 = spark.sql("select * from global_temp.people")
>>> sorted(df.collect()) == sorted(df2.collect())
True
>>> df.createGlobalTempView("people")
Traceback (most recent call last):
...
AnalysisException: u"Temporary table 'people' already exists;"
>>> spark.catalog.dropGlobalTempView("people")
--------------------------------------------------------------------------
createOrReplaceTempView(name)
Creates or replaces a local temporary view with this DataFrame.
The lifetime of this temporary table is tied to the SparkSession that was used to create this DataFrame.
>>> df.createOrReplaceTempView("people")
>>> df2 = df.filter(df.age > 3)
>>> df2.createOrReplaceTempView("people")
>>> df3 = spark.sql("select * from people")
>>> sorted(df3.collect()) == sorted(df2.collect())
True
>>> spark.catalog.dropTempView("people")
New in version 2.0.
createTempView(name)
Creates a local temporary view with this DataFrame.
The lifetime of this temporary table is tied to the SparkSession that was used to create this DataFrame. throws TempTableAlreadyExistsException, if the view name already exists in the catalog.
>>> df.createTempView("people")
>>> df2 = spark.sql("select * from people")
>>> sorted(df.collect()) == sorted(df2.collect())
True
>>> df.createTempView("people")
Traceback (most recent call last):
...
AnalysisException: u"Temporary table 'people' already exists;"
>>> spark.catalog.dropTempView("people")
'''
#### CUBES ON DF's
'''
cube(*cols)
Create a multi-dimensional cube for the current DataFrame using the specified columns, so we can run aggregation on them.
>>> df.cube("name", df.age).count().orderBy("name", "age").show()
+-----+----+-----+
| name| age|count|
+-----+----+-----+
| null|null| 2|
| null| 2| 1|
| null| 5| 1|
|Alice|null| 1|
|Alice| 2| 1|
| Bob|null| 1|
| Bob| 5| 1|
+-----+----+-----+
'''
#distinct()
'''
distinct()
Returns a new DataFrame containing the distinct rows in this DataFrame.
>>> df.distinct().count()
2
'''
#drop(*cols)
'''
drop(*cols)
Returns a new DataFrame that drops the specified column. This is a no-op if schema doesn’t contain the given column name(s).
Parameters: cols – a string name of the column to drop, or a Column to drop, or a list of string name of the columns to drop.
>>> df.drop('age').collect()
[Row(name=u'Alice'), Row(name=u'Bob')]
>>> df.drop(df.age).collect()
[Row(name=u'Alice'), Row(name=u'Bob')]
>>> df.join(df2, df.name == df2.name, 'inner').drop(df.name).collect()
[Row(age=5, height=85, name=u'Bob')]
>>> df.join(df2, df.name == df2.name, 'inner').drop(df2.name).collect()
[Row(age=5, name=u'Bob', height=85)]
>>> df.join(df2, 'name', 'inner').drop('age', 'height').collect()
[Row(name=u'Bob')]
'''
#dropDuplicates(subset=None)
'''
dropDuplicates(subset=None)
Return a new DataFrame with duplicate rows removed, optionally only considering certain columns.
drop_duplicates() is an alias for dropDuplicates().
>>> from pyspark.sql import Row
>>> df = sc.parallelize([ \
... Row(name='Alice', age=5, height=80), \
... Row(name='Alice', age=5, height=80), \
... Row(name='Alice', age=10, height=80)]).toDF()
>>> df.dropDuplicates().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 5| 80|Alice|
| 10| 80|Alice|
+---+------+-----+
>>> df.dropDuplicates(['name', 'height']).show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 5| 80|Alice|
+---+------+-----+
'''
#dropna(how='any', thresh=None, subset=None)
'''
dropna(how='any', thresh=None, subset=None)
Returns a new DataFrame omitting rows with null values. DataFrame.dropna() and DataFrameNaFunctions.drop() are aliases of each other.
Parameters:
how – ‘any’ or ‘all’. If ‘any’, drop a row if it contains any nulls. If ‘all’, drop a row only if all its values are null.
thresh – int, default None If specified, drop rows that have less than thresh non-null values. This overwrites the how parameter.
subset – optional list of column names to consider.
>>> df4.na.drop().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 10| 80|Alice|
+---+------+-----+
'''
#dtypes
'''
dtypes
Returns all column names and their data types as a list.
>>> df.dtypes
[('age', 'int'), ('name', 'string')]
'''
#explain(extended=False)
'''
explain(extended=False)
Prints the (logical and physical) plans to the console for debugging purpose.
Parameters: extended – boolean, default False. If False, prints only the physical plan.
>>> df.explain()
== Physical Plan ==
Scan ExistingRDD[age#0,name#1]
'''
#fillna(value, subset=None)
'''
fillna(value, subset=None)
Replace null values, alias for na.fill(). DataFrame.fillna() and DataFrameNaFunctions.fill() are aliases of each other.
Parameters:
value – int, long, float, string, or dict. Value to replace null values with. If the value is a dict, then subset is ignored and value must be a mapping from column name (string) to replacement value. The replacement value must be an int, long, float, or string.
subset – optional list of column names to consider. Columns specified in subset that do not have matching data type are ignored. For example, if value is a string, and subset contains a non-string column, then the non-string column is simply ignored.
>>> df4.na.fill(50).show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 10| 80|Alice|
| 5| 50| Bob|
| 50| 50| Tom|
| 50| 50| null|
+---+------+-----+
>>> df4.na.fill({'age': 50, 'name': 'unknown'}).show()
+---+------+-------+
|age|height| name|
+---+------+-------+
| 10| 80| Alice|
| 5| null| Bob|
| 50| null| Tom|
| 50| null|unknown|
+---+------+-------+
'''
#filter(condition)
'''
filter(condition)
Filters rows using the given condition.
where() is an alias for filter().
Parameters: condition – a Column of types.BooleanType or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
'''
#first()
'''
first()
Returns the first row as a Row.
>>> df.first()
Row(age=2, name=u'Alice')
'''
#foreach(f)
'''
foreach(f)
Applies the f function to all Row of this DataFrame.
This is a shorthand for df.rdd.foreach().
>>> def f(person):
... print(person.name)
>>> df.foreach(f)
'''
#foreachPartition(f)
'''
foreachPartition(f)
Applies the f function to each partition of this DataFrame.
This a shorthand for df.rdd.foreachPartition().
>>> def f(people):
... for person in people:
... print(person.name)
>>> df.foreachPartition(f)
'''
#groupBy(*cols)
'''
groupBy(*cols)
Groups the DataFrame using the specified columns, so we can run aggregation on them. See GroupedData for all the available aggregate functions.
groupby() is an alias for groupBy().
Parameters: cols – list of columns to group by. Each element should be a column name (string) or an expression (Column).
>>> df.groupBy().avg().collect()
[Row(avg(age)=3.5)]
>>> sorted(df.groupBy('name').agg({'age': 'mean'}).collect())
[Row(name=u'Alice', avg(age)=2.0), Row(name=u'Bob', avg(age)=5.0)]
>>> sorted(df.groupBy(df.name).avg().collect())
[Row(name=u'Alice', avg(age)=2.0), Row(name=u'Bob', avg(age)=5.0)]
>>> sorted(df.groupBy(['name', df.age]).count().collect())
[Row(name=u'Alice', age=2, count=1), Row(name=u'Bob', age=5, count=1)]
'''
#intersect(other)
'''
intersect(other)
Return a new DataFrame containing rows only in both this frame and another frame.
This is equivalent to INTERSECT in SQL.
'''
#orderBy(*cols, **kwargs)
'''
orderBy(*cols, **kwargs)
Returns a new DataFrame sorted by the specified column(s).
Parameters:
cols – list of Column or column names to sort by.
ascending – boolean or list of boolean (default True). Sort ascending vs. descending. Specify list for multiple sort orders. If a list is specified, length of the list must equal length of the cols.
>>> df.sort(df.age.desc()).collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
>>> df.sort("age", ascending=False).collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
>>> df.orderBy(df.age.desc()).collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
>>> from pyspark.sql.functions import *
>>> df.sort(asc("age")).collect()
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
>>> df.orderBy(desc("age"), "name").collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
>>> df.orderBy(["age", "name"], ascending=[0, 1]).collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
'''
#printSchema()
'''
printSchema()
Prints out the schema in the tree format.
>>> df.printSchema()
root
|-- age: integer (nullable = true)
|-- name: string (nullable = true)
'''
#replace(to_replace, value, subset=None)
'''
replace(to_replace, value, subset=None)
Returns a new DataFrame replacing a value with another value. DataFrame.replace() and DataFrameNaFunctions.replace() are aliases of each other.
Parameters:
to_replace – int, long, float, string, or list. Value to be replaced. If the value is a dict, then value is ignored and to_replace must be a mapping from column name (string) to replacement value. The value to be replaced must be an int, long, float, or string.
value – int, long, float, string, or list. Value to use to replace holes. The replacement value must be an int, long, float, or string. If value is a list or tuple, value should be of the same length with to_replace.
subset – optional list of column names to consider. Columns specified in subset that do not have matching data type are ignored. For example, if value is a string, and subset contains a non-string column, then the non-string column is simply ignored.
>>> df4.na.replace(10, 20).show()
+----+------+-----+
| age|height| name|
+----+------+-----+
| 20| 80|Alice|
| 5| null| Bob|
|null| null| Tom|
|null| null| null|
+----+------+-----+
>>> df4.na.replace(['Alice', 'Bob'], ['A', 'B'], 'name').show()
+----+------+----+
| age|height|name|
+----+------+----+
| 10| 80| A|
| 5| null| B|
|null| null| Tom|
|null| null|null|
+----+------+----+
'''
#schema
'''
schema
Returns the schema of this DataFrame as a pyspark.sql.types.StructType.
>>> df.schema
StructType(List(StructField(age,IntegerType,true),StructField(name,StringType,true)))
'''
#select(*cols)
'''
select(*cols)
Projects a set of expressions and returns a new DataFrame.
Parameters: cols – list of column names (string) or expressions (Column). If one of the column names is ‘*’, that column is expanded to include all columns in the current DataFrame.
>>> df.select('*').collect()
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
>>> df.select('name', 'age').collect()
[Row(name=u'Alice', age=2), Row(name=u'Bob', age=5)]
>>> df.select(df.name, (df.age + 10).alias('age')).collect()
[Row(name=u'Alice', age=12), Row(name=u'Bob', age=15)]
'''
#show(n=20, truncate=True)
'''
show(n=20, truncate=True)
Prints the first n rows to the console.
Parameters:
n – Number of rows to show.
truncate – If set to True, truncate strings longer than 20 chars by default. If set to a number greater than one, truncates long strings to length truncate and align cells right.
>>> df
DataFrame[age: int, name: string]
>>> df.show()
+---+-----+
|age| name|
+---+-----+
| 2|Alice|
| 5| Bob|
+---+-----+
>>> df.show(truncate=3)
+---+----+
|age|name|
+---+----+
| 2| Ali|
| 5| Bob|
+---+----+
'''
######### Sort
'''
sort(*cols, **kwargs)
Returns a new DataFrame sorted by the specified column(s).
Parameters:
cols – list of Column or column names to sort by.
ascending – boolean or list of boolean (default True). Sort ascending vs. descending. Specify list for multiple sort orders. If a list is specified, length of the list must equal length of the cols.
>>> df.sort(df.age.desc()).collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
>>> df.sort("age", ascending=False).collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
>>> df.orderBy(df.age.desc()).collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
>>> from pyspark.sql.functions import *
>>> df.sort(asc("age")).collect()
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
>>> df.orderBy(desc("age"), "name").collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
>>> df.orderBy(["age", "name"], ascending=[0, 1]).collect()
[Row(age=5, name=u'Bob'), Row(age=2, name=u'Alice')]
sortWithinPartitions(*cols, **kwargs)
Returns a new DataFrame with each partition sorted by the specified column(s).
Parameters:
cols – list of Column or column names to sort by.
ascending – boolean or list of boolean (default True). Sort ascending vs. descending. Specify list for multiple sort orders. If a list is specified, length of the list must equal length of the cols.
>>> df.sortWithinPartitions("age", ascending=False).show()
+---+-----+
|age| name|
+---+-----+
| 2|Alice|
| 5| Bob|
+---+-----+
'''
#EXCEPT -> SQL
#subtract(other)
'''
subtract(other)
Return a new DataFrame containing rows in this frame but not in another frame.
This is equivalent to EXCEPT in SQL.
'''
#toDF(*cols)
'''
toDF(*cols)
Returns a new class:DataFrame that with new specified column names
Parameters: cols – list of new column names (string)
>>> df.toDF('f1', 'f2').collect()
[Row(f1=2, f2=u'Alice'), Row(f1=5, f2=u'Bob')]
'''
#toJSON(use_unicode=True)
'''
toJSON(use_unicode=True)
Converts a DataFrame into a RDD of string.
Each row is turned into a JSON document as one element in the returned RDD.
>>> df.toJSON().first()
u'{"age":2,"name":"Alice"}'
'''
#toLocalIterator()
'''
toLocalIterator()
Returns an iterator that contains all of the rows in this DataFrame. The iterator will consume as much memory as the largest partition in this DataFrame.
>>> list(df.toLocalIterator())
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
'''
#UNION ALL -> SQL
#union(other)
'''
union(other)
Return a new DataFrame containing union of rows in this frame and another frame.
This is equivalent to UNION ALL in SQL. To do a SQL-style set union (that does deduplication of elements), use this function followed by a distinct.
unionAll(other)
Return a new DataFrame containing union of rows in this frame and another frame.
'''
#where // filter() -> SQL
#where(condition)
'''
where(condition)
where() is an alias for filter().
'''
#withColumn(colName, col)
'''
withColumn(colName, col)
Returns a new DataFrame by adding a column or replacing the existing column that has the same name.
Parameters:
colName – string, name of the new column.
col – a Column expression for the new column.
>>> df.withColumn('age2', df.age + 2).collect()
[Row(age=2, name=u'Alice', age2=4), Row(age=5, name=u'Bob', age2=7)]
'''
############################ A set of methods for aggregations on a DataFrame, created by DataFrame.groupBy(). #################################
'''
agg(*exprs)
Compute aggregates and returns the result as a DataFrame.
The available aggregate functions are avg, max, min, sum, count.
If exprs is a single dict mapping from string to string, then the key is the column to perform aggregation on, and the value is the aggregate function.
Alternatively, exprs can also be a list of aggregate Column expressions.
Parameters: exprs – a dict mapping from column name (string) to aggregate functions (string), or a list of Column.
>>> gdf = df.groupBy(df.name)
>>> sorted(gdf.agg({"*": "count"}).collect())
[Row(name=u'Alice', count(1)=1), Row(name=u'Bob', count(1)=1)]
>>> from pyspark.sql import functions as F
>>> sorted(gdf.agg(F.min(df.age)).collect())
[Row(name=u'Alice', min(age)=2), Row(name=u'Bob', min(age)=5)]
avg(*cols)
Computes average values for each numeric columns for each group.
mean() is an alias for avg().
Parameters: cols – list of column names (string). Non-numeric columns are ignored.
>>> df.groupBy().avg('age').collect()
[Row(avg(age)=3.5)]
>>> df3.groupBy().avg('age', 'height').collect()
[Row(avg(age)=3.5, avg(height)=82.5)]
max(*cols)
Computes the max value for each numeric columns for each group.
>>> df.groupBy().max('age').collect()
[Row(max(age)=5)]
>>> df3.groupBy().max('age', 'height').collect()
[Row(max(age)=5, max(height)=85)]
mean(*cols)
Computes average values for each numeric columns for each group.
mean() is an alias for avg().
Parameters: cols – list of column names (string). Non-numeric columns are ignored.
>>> df.groupBy().mean('age').collect()
[Row(avg(age)=3.5)]
>>> df3.groupBy().mean('age', 'height').collect()
[Row(avg(age)=3.5, avg(height)=82.5)]
'''
################################################################################################################################################
#################################################### class pyspark.sql.Column(jc) A column in a DataFrame. ####################################
'''
between(lowerBound, upperBound)
A boolean expression that is evaluated to true if the value of this expression is between the given columns.
>>> df.select(df.name, df.age.between(2, 4)).show()
+-----+---------------------------+
| name|((age >= 2) AND (age <= 4))|
+-----+---------------------------+
|Alice| true|
| Bob| false|
+-----+---------------------------+
cast(dataType)
Convert the column into type dataType.
>>> df.select(df.age.cast("string").alias('ages')).collect()
[Row(ages=u'2'), Row(ages=u'5')]
>>> df.select(df.age.cast(StringType()).alias('ages')).collect()
[Row(ages=u'2'), Row(ages=u'5')]
getItem(key)
An expression that gets an item at position ordinal out of a list, or gets an item by key out of a dict.
>>> df = sc.parallelize([([1, 2], {"key": "value"})]).toDF(["l", "d"])
>>> df.select(df.l.getItem(0), df.d.getItem("key")).show()
+----+------+
|l[0]|d[key]|
+----+------+
| 1| value|
+----+------+
>>> df.select(df.l[0], df.d["key"]).show()
+----+------+
|l[0]|d[key]|
+----+------+
| 1| value|
+----+------+
substr(startPos, length)
Return a Column which is a substring of the column.
Parameters:
startPos – start position (int or Column)
length – length of the substring (int or Column)
>>> df.select(df.name.substr(1, 3).alias("col")).collect()
[Row(col=u'Ali'), Row(col=u'Bob')]
when(condition, value)
Evaluates a list of conditions and returns one of multiple possible result expressions. If Column.otherwise() is not invoked, None is returned for unmatched conditions.
See pyspark.sql.functions.when() for example usage.
Parameters:
condition – a boolean Column expression.
value – a literal value, or a Column expression.
>>> from pyspark.sql import functions as F
>>> df.select(df.name, F.when(df.age > 4, 1).when(df.age < 3, -1).otherwise(0)).show()
+-----+------------------------------------------------------------+
| name|CASE WHEN (age > 4) THEN 1 WHEN (age < 3) THEN -1 ELSE 0 END|
+-----+------------------------------------------------------------+
|Alice| -1|
| Bob| 1|
+-----+------------------------------------------------------------+
'''
################################################################################################################################################
##################################################### ROW ####################################################################################
'''
Row
A row in DataFrame. The fields in it can be accessed:
like attributes (row.key)
like dictionary values (row[key])
key in row will search through row keys.
Row can be used to create a row object by using named arguments, the fields will be sorted by names.
>>> row = Row(name="Alice", age=11)
>>> row
Row(age=11, name='Alice')
>>> row['name'], row['age']
('Alice', 11)
>>> row.name, row.age
('Alice', 11)
>>> 'name' in row
True
>>> 'wrong_key' in row
False
'''
##################################################### Writing Back ##########################################################
'''
write
Interface for saving the content of the non-streaming DataFrame out into external storage.
Returns: DataFrameWriter
writeStream
Interface for saving the content of the streaming DataFrame out into external storage.
'''
##################################################### JOINS ON DF's ######################################################
#join(other, on=None, how=None)
'''
join(other, on=None, how=None)
Joins with another DataFrame, using the given join expression.
Parameters:
other – Right side of the join
on – a string for the join column name, a list of column names, a join expression (Column), or a list of Columns. If on is a string or a list of strings indicating the name of the join column(s), the column(s) must exist on both sides, and this performs an equi-join.
how – str, default ‘inner’. One of inner, outer, left_outer, right_outer, leftsemi.
The following performs a full outer join between df1 and df2.
>>> df.join(df2, df.name == df2.name, 'outer').select(df.name, df2.height).collect()
[Row(name=None, height=80), Row(name=u'Bob', height=85), Row(name=u'Alice', height=None)]
>>> df.join(df2, 'name', 'outer').select('name', 'height').collect()
[Row(name=u'Tom', height=80), Row(name=u'Bob', height=85), Row(name=u'Alice', height=None)]
>>> cond = [df.name == df3.name, df.age == df3.age]
>>> df.join(df3, cond, 'outer').select(df.name, df3.age).collect()
[Row(name=u'Alice', age=2), Row(name=u'Bob', age=5)]
>>> df.join(df2, 'name').select(df.name, df2.height).collect()
[Row(name=u'Bob', height=85)]
>>> df.join(df4, ['name', 'age']).select(df.name, df.age).collect()
[Row(name=u'Bob', age=5)]
'''
#crossJoin(other)
'''
crossJoin(other)
Returns the cartesian product with another DataFrame.
Parameters: other – Right side of the cartesian product.
>>> df.select("age", "name").collect()
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
>>> df2.select("name", "height").collect()
[Row(name=u'Tom', height=80), Row(name=u'Bob', height=85)]
>>> df.crossJoin(df2.select("height")).select("age", "name", "height").collect()
[Row(age=2, name=u'Alice', height=80), Row(age=2, name=u'Alice', height=85),
Row(age=5, name=u'Bob', height=80), Row(age=5, name=u'Bob', height=85)]
'''
##################################################### Working with suppliers.csv ########################################################
print("\n\n****************************************** Working with suppliers.csv **************************************************\n\n")
from pyspark.sql.types import *
SuppliersFile = sc.textFile("/home/akhil/Desktop/3 Day Task/data/suppliers.csv")
header = SuppliersFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
fields = [StructField(field_name, StringType(), True) for field_name in schemaString.split(',')]
#print(fields)
#print(len(fields) ) # how many elements in the header?
'''
SupplierID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax HomePage
'''
fields[0].dataType = IntegerType()
#fields[7].dataType = IntegerType()
#print("\n\n")
print(fields)
print("\n\n")
# We can get rid of any annoying leading underscores or change name of field by
# Eg: fields[0].name = 'id'
schema = StructType(fields)
print(schema)
print("\n\n")
SuppliersHeader = SuppliersFile.filter(lambda l: "SupplierID" in l)
#print(SuppliersHeader.collect())
#print("\n\n")
SuppliersNoHeader = SuppliersFile.subtract(SuppliersHeader)
#print(SuppliersNoHeader.count())
#print("\n\n")
#Remove Nullable = "False" Here
Suppliers_temp = SuppliersNoHeader.map(lambda k: k.split(",")).map(lambda p:(int(p[0]),str(p[1].encode("utf-8")),p[2],p[3],p[4],p[5],p[6],p[7], p[8],p[9],p[10],p[11]))
#str(fields[1].encode("utf-8"))
print(Suppliers_temp.top(2))
print("\n\n")
Suppliers_df = sqlContext.createDataFrame(Suppliers_temp, schema)
print("\n Dtypes : ",Suppliers_df.dtypes)
print("\n\n")
print("\nSchema: ",Suppliers_df.printSchema())
print("\n\n")
#Registering Table
Suppliers_df.registerTempTable("Suppliers")
##################################################### Working with categories.csv ########################################################
print("\n\n****************************************** Working with categories.csv **************************************************\n\n")
'''
CategoryID CategoryName Description Picture
'''
from pyspark.sql.types import *
CategoriesFile = sc.textFile("/home/akhil/Desktop/3 Day Task/data/categories.csv")
header = CategoriesFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
#print(schemaString)
fields = [StructField(field_name, StringType(), True) for field_name in schemaString.split(',')]
#print(fields)
#print(len(fields) ) # how many elements in the header?
fields[0].dataType = IntegerType()
#print("\n\n")
#print(fields)
#print("\n\n")
# We can get rid of any annoying leading underscores or change name of field by
# Eg: fields[0].name = 'id'
schema = StructType(fields)
print(schema)
print("\n\n")
CategoriesHeader = CategoriesFile.filter(lambda l: "CategoryID" in l)
#print(CategoriesHeader.collect())
#print("\n\n")
CategoriesNoHeader = CategoriesFile.subtract(CategoriesHeader)
#print(CategoriesNoHeader.count())
#print("\n\n")
Categories_temp = CategoriesNoHeader.map(lambda k: k.split(",")).map(lambda p: (int(p[0]),p[1],p[2],p[3]))
#print(Categories_temp.top(2))
#print("\n\n")
Categories_df = sqlContext.createDataFrame(Categories_temp, schema)
print("\n Dtypes : ",Categories_df.dtypes)
print("\n\n")
print("\nSchema: ",Categories_df.printSchema())
print("\n\n")
#Registering Table
Categories_df.registerTempTable("Categories")
print("\n\n")
##################################################### Working with customers.csv #####################################################
print("\n\n****************************************** Working with customers.csv ***********************************************\n\n")
'''
CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax
'''
# Create a SparkSession
spark = SparkSession \
.builder \
.appName("My Cap") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
def mapper(line):
fields = line.split(',')
return Row(CustomerID = (fields[0]), CompanyName = str(fields[1].encode("utf-8")),ContactName = str(fields[2].encode("utf-8")), ContactTitle = str(fields[3].encode("utf-8")),Address = str(fields[4].encode("utf-8")),City = str(fields[5].encode("utf-8")),Region = str(fields[6].encode("utf-8")),PostalCode = str(fields[7].encode("utf-8")),Country = str(fields[8].encode("utf-8")), Phone = str(fields[9].encode("utf-8")),Fax = fields[10] )
lines = spark.sparkContext.textFile("/home/akhil/Desktop/3 Day Task/data/customers.csv")
header = lines.first()
lines = lines.filter(lambda line:line != header)
dfi = lines.map(mapper)
# Infer the schema, and register the DataFrame as a table.
CustomersDf = spark.createDataFrame(dfi).cache()
CustomersDf.createOrReplaceTempView("Customers")
print(CustomersDf.select('CustomerID').show(5))
#CustomersDf2 = spark.sql("SELECT CustomerID AS ID,FirstName as Name from Customers").show()
#print(CustomersDf2)
#print("\n\n")
#Use show() result as Schema but returns None Type obeject..Cannot use collect()
#Q3 = sqlContext.sql("SELECT CustomerID AS ID,FirstName as Name from Customers").show()
#print(Q3)
#print("\n\n")
sqlContext.registerDataFrameAsTable(CustomersDf, "CusTable")
'''
df2 = sqlContext.table("CusTable")
print(sorted(df.collect()) == sorted(df2.collect()))
print("\n\n")
'''
##################################################### Working with orders.csv #####################################################
print("\n\n****************************************** Working with orders.csv ***********************************************\n\n")
'''
OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName ShipAddress ShipCity ShipRegion ShipPostalCode ShipCountry
'''
# Create a SparkSession
spark = SparkSession \
.builder \
.appName("My Dap") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
def mapper(line):
fields = line.split(',')
return Row(OrderID = (fields[0]),CustomerID = str(fields[1].encode("utf-8")),EmployeeID = (fields[2]), OrderDate = str(fields[3].encode("utf-8")),RequiredDate = str(fields[4].encode("utf-8")), ShippedDate = str(fields[5].encode("utf-8")),ShipVia = fields[6] ,Freight = float(fields[7]),ShipName = str(fields[8].encode("utf-8")),ShipAddress = str(fields[9].encode("utf-8")), ShipCity = str(fields[10].encode("utf-8")),ShipRegion = str(fields[11].encode("utf-8")),ShipPostalCode = fields[12],ShipCountry = str(fields[13].encode("utf-8")))
lines = spark.sparkContext.textFile("/home/akhil/Desktop/3 Day Task/data/orders.csv")
header = lines.first()
lines = lines.filter(lambda line:line != header)
dfo = lines.map(mapper)
# Infer the schema, and register the DataFrame as a table.
OrdersDf = spark.createDataFrame(dfo).cache()
OrdersDf.createOrReplaceTempView("Orders")
print(OrdersDf.select('OrderID').show(5))
sqlContext.registerDataFrameAsTable(OrdersDf, "OrdTable")
##################################################### Working with order-details.csv ####################################################
print("\n\n****************************************** Working with order-details.csv **********************************************\n\n")
'''
OrderID ProductID UnitPrice Quantity Discount
'''
# Create a SparkSession
spark = SparkSession \
.builder \
.appName("My Eap") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
def mapper(line):
fields = line.split(',')
return Row(OrderID = (fields[0]),ProductID = (fields[1]), UnitPrice = str(fields[2].encode("utf-8")),Quantity = str(fields[3].encode("utf-8")), Discount = fields[4] )
lines = spark.sparkContext.textFile("/home/akhil/Desktop/3 Day Task/data/order-details.csv")
header = lines.first()
lines = lines.filter(lambda line:line != header)
dfm = lines.map(mapper)
# Infer the schema, and register the DataFrame as a table.
OrderDetailsDf = spark.createDataFrame(dfm).cache()
OrderDetailsDf.createOrReplaceTempView("OrderDetails")
print(OrderDetailsDf.select('OrderID').show(5))
sqlContext.registerDataFrameAsTable(OrderDetailsDf, "OrdDetTable")
################################################################################################################################################
# #
# Working on Data Frames for Constructing Components of Resultant Star Schema # #
################################################################################################################################################
####################################################### Product Table ###########################################################
'''
ProductID ProductName SupplierID CategoryID QuantityPerUnit UnitPrice UnitsInStock UnitsOnOrder ReorderLevel Discontinued
'''
sqlContext.sql("SELECT ID ,SupID,CategoryID,Discontinued FROM ProductsTable").show()
print("\n\n")
'''
SupplierID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax HomePage
'''
sqlContext.sql("SELECT SupplierID FROM Suppliers").show()
print("\n\n")
'''
CategoryID CategoryName Description Picture
'''
sqlContext.sql("SELECT * FROM Categories").show()
print("\n\n")
#NO SQL
#ProductsDF.select('ID' ,'SupID','CategoryID','Discontinued').dropDuplicates().show()
#INNER JOIN ON 3 Tables
'''
SELECT column_Name1,column_name2,......
From tbl_name1,tbl_name2,tbl_name3
where tbl_name1.column_name = tbl_name2.column_name
and tbl_name2.column_name = tbl_name3.column_name
'''
sqlContext.sql("SELECT p.ProductID, p.SupplierID, p.CategoryID, c.CategoryName,c.Description,p.Discontinued FROM Products p INNER JOIN Suppliers s on p.SupplierID = s.SupplierID INNER JOIN Categories c on p.CategoryID = c.CategoryID").show()
print("\n\n")
''' Exact Solution
sqlContext.sql("SELECT p.ProductID,p.ProductName,p.SupplierID,s.CompanyName,p.CategoryID,c.CategoryName,c.Description,p.Discontinued FROM Products p INNER JOIN Suppliers s on p.SupplierID = s.SupplierID INNER JOIN Categories c on p.CategoryID = c.CategoryID").show()
print("\n\n")
'''
#NON SQL
Products_df.join(Suppliers_df, Products_df.SupplierID == Suppliers_df.SupplierID).select(Products_df.ProductID,Products_df.SupplierID,Products_df.CategoryID,Products_df.Discontinued).join(Categories_df, Products_df.CategoryID == Categories_df.CategoryID).select(Products_df.ProductID,Products_df.SupplierID,Products_df.CategoryID,Products_df.Discontinued,Categories_df.CategoryName,Categories_df.Description).show()
####################################################### Employee Table ###########################################################
'''
EmployeeID LastName FirstName Title TitleOfCourtesy BirthDate HireDate Address City Region PostalCode Country HomePhone Extension Photo Notes ReportsTo PhotoPath
'''
sqlContext.sql("SELECT * FROM EmpTable").show()
print("\n\n")
sqlContext.sql("SELECT EmployeeID,LastName,FirstName,Title,HireDate,Region FROM EmpTable").show()
print("\n\n")
#NON SQL
EmployeesDf.select('EmployeeID','LastName','FirstName','Title','HireDate','Region').show()
##################################################### Customer Table #####################################################
'''
CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax
'''
'''
Error:
sqlContext.sql("SELECT * FROM CusTable").show()
print("\n\n")
'''
''' Exact Solution
sqlContext.sql("SELECT CustomerID,CompanyName,City,Region,PostalCode,Country FROM CusTable").show()
print("\n\n")
'''
sqlContext.sql("SELECT CustomerID,Region,PostalCode,Country FROM CusTable").show()
print("\n\n")
CustomersDF.select('CustomerID','Region','PostalCode','Country').show()
##################################################### Time Table #####################################################
#OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate
'''
OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName ShipAddress ShipCity ShipRegion ShipPostalCode ShipCountry
'''
sqlContext.sql("SELECT OrderID FROM OrdTable").show()
print("\n\n")
'''
UnicodeEncodeError: 'ascii' codec can't encode characters in position 959-960: ordinal not in range(128)
sqlContext.sql("SELECT * FROM OrdTable").show()
print("\n\n")
'''
sqlContext.sql("SELECT OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate FROM OrdTable").show()
print("\n\n")
####### Creating New SparkSession to Extract Data
# Create a SparkSession
spark = SparkSession \
.builder \
.appName("My Map") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
def mapper(line):
fields = line.split(',')
return Row(OrderID = (fields[0]),CustomerID = str(fields[1].encode("utf-8")),EmployeeID = (fields[2]), OrderDate = (fields[3].encode("utf-8")),RequiredDate = str(fields[4].encode("utf-8")), ShippedDate = str(fields[5].encode("utf-8")))
lines = spark.sparkContext.textFile("/home/akhil/Desktop/3 Day Task/data/orders.csv")
header = lines.first()
lines = lines.filter(lambda line:line != header)
dfo_2 = lines.map(mapper)
# Infer the schema, and register the DataFrame as a table.
OrdersDf_2 = spark.createDataFrame(dfo_2).cache()
OrdersDf_2.createOrReplaceTempView("Orders2")
print(OrdersDf_2.select('OrderID').show(5))
sqlContext.registerDataFrameAsTable(OrdersDf_2, "OrdsNTable")
from pyspark.sql.types import IntegerType
'''
registerFunction(name, f, returnType=StringType)
Registers a python function (including lambda function) as a UDF so it can be used in SQL statements.
In addition to a name and the function itself, the return type can be optionally specified. When the return type is not given it default to a string and conversion will automatically be done. For any other return type, the produced object must match the specified type.
Parameters:
name – name of the UDF
f – python function
returnType – a pyspark.sql.types.DataType object
'''
q = {'01' : 'Q1' , '02' : 'Q1' ,'03' : 'Q1' ,'04' : 'Q2', '05' : 'Q2', '06' : 'Q2', '07' : 'Q3', '08' : 'Q3', '09' : 'Q3', '10' : 'Q4', '11' : 'Q4', '12' : 'Q4'}
d = {'01' : 'Jan' , '02' : 'Feb' ,'03' : 'Mar' ,'04' : 'Apr', '05' : 'May', '06' : 'Jun', '07' : 'July', '08' : 'Aug', '09' : 'Sep', '10' : 'Oct', '11' : 'Nov', '12' : 'Dec'}
w = {'01' : 'Week 1' , '02' : 'Week 1' ,'03' : 'Week 1' ,'04' : 'Week 1', '05' : 'Week 1', '06' : 'Week 1', '07' : 'Week 1', '08' : 'Week 2', '09' : 'Week 2', '10' : 'Week 2', '11' : 'Week 2', '12' : 'Week 2', '13' : 'Week 2', '14' : 'Week 2','15' : 'Week 3', '16' : 'Week 3', '17' : 'Week 3', '18' : 'Week 3', '19' : 'Week 3', '20' : 'Week 3', '21' : 'Week 3', '22' : 'Week 4', '23' : 'Week 4', '24' : 'Week 4','25' : 'Week 4', '26' : 'Week 4', '27' : 'Week 4', '28' : 'Week 4', '29' : 'Week 4', '30' : 'Week 4', '31' : 'Week 4'}
# 1996-07-04 00:00:00.000
sqlContext.registerFunction("Date", lambda x: x.split(' ')[0], StringType())
sqlContext.registerFunction("Year", lambda x: x.split(' ')[0].split('-')[0], StringType())
sqlContext.registerFunction("Month", lambda x: d[x.split(' ')[0].split('-')[1]], StringType())
sqlContext.registerFunction("Quarter", lambda x: q[x.split(' ')[0].split('-')[1]], StringType())
sqlContext.registerFunction("Week", lambda x: w[x.split(' ')[0].split('-')[2]], StringType())
sqlContext.sql("SELECT Date(OrderDate) As Date, Week(OrderDate) As WeekBy, Month(OrderDate) As Month , Quarter(OrderDate) As Quarter , Year(OrderDate) AS Year From OrdsNTable").show()
#print(x)
print("\n\n")
<file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import * # Imports all data Types
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
from pyspark.sql.functions import udf
conf = SparkConf().setMaster("local").setAppName("Aggregate Module")
sc = SparkContext(conf = conf) # Initalising or Configuring "Spark Context"
sqlContext = SQLContext(sc)
#############################################################################################################################################
#Other :- Currency Temperature Timezone Weight Length GeoIP
# Columns :- OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName
#############################################################################################################################################
#1. Currency
def Currency(df,col,conv1,conv2):
r = conv1/conv2
cur = udf(lambda s: (s*r), FloatType())
return df.select(cur(df[col]).alias('CurrencyConversion')).show()
#2. Temperature
def TemperatureDeg(df,col):
deg = udf(lambda s: ((s-32)*0.556), FloatType())
return df.select(deg(df[col]).alias('CelsiusTemperature')).show()
def TemperatureFrh(df,col):
frh = udf(lambda s: ((s*1.5)+32), FloatType())
return df.select(frh(df[col]).alias('FahrenheitTemperature')).show()
#3. Timezone
def TimeConverterGMT(df,col,val):
Conv = {'GMT':0 , 'EDT':-4 , 'EST' : -5 ,'CDT' : -5 , 'CST' : -6 ,'MDT' : -6 ,'MST' : -7,'PDT' : -7 , 'PST' : -8 ,'IST' : 5.5 ,'Sydney': 10 ,'UTC' : 0 }
conv = udf(lambda s: (s+Conv[val]), FloatType())
return df.select(conv(df[col]).alias('GMTConverter')).show()
#4. Weight
def WeightConverter_Gr_Kg(df,col):
wtconv = udf(lambda s: (s/1000), FloatType())
return df.select(wtconv(df[col]).alias('GramToKgConverter')).show()
def WeightConverter_Kg_Gr(df,col):
wtconv = udf(lambda s: (s*1000), IntegerType())
return df.select(wtconv(df[col]).alias('KgToGramConverter')).show()
#5. Length
def LengthConverter_Mtr_Km(df,col):
Lnconv = udf(lambda s: (s/1000), IntegerType())
return df.select(Lnconv(df[col]).alias('MtrToKmConverter')).show()
def LengthConverter_Km_Mtr(df,col):
Lnconv = udf(lambda s: (s*1000), IntegerType())
#return df.select(Lnconv(df[col]).alias('KmToMtrConverter')).show()
dfn = df.select(df[0],Lnconv(df[col]).alias('KmToMtrConverter'))
#return dfn.show()
#return df.join(dfn,dfn[0]==df[0]).show()
return df.join(dfn,["OrderID"]).show()
#6. GeoIP
'''
Not A Good Transform
But Can be solved by using Dictionary
'''
################################################################################################################################################
def convert(date_string):
date_new = date_string.split(" ")[0]
date_object = date(*map(int,(date_string.split(" ")[0].split("-"))))
return date_object
def dataFrame_Maker(*args):
File = args[0]
OrdersFile = sc.textFile(File)
header = OrdersFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
fields = [StructField(field_name, StringType(), False) for field_name in schemaString.split(',')]
fields[0].dataType = LongType()
fields[2].dataType = IntegerType()
fields[3].dataType = DateType()
fields[4].dataType = DateType()
fields[5].dataType = DateType()
fields[6].dataType = IntegerType()
fields[7].dataType = FloatType()
schema = StructType(fields)
OrdersHeader = OrdersFile.filter(lambda l: "OrderID" in l)
OrdersNoHeader = OrdersFile.subtract(OrdersHeader)
Orders_temp = OrdersNoHeader.map(lambda k: k.split(",")).map(lambda p:(int(p[0]),str(p[1].encode("utf-8")),int(p[2]),convert(p[3]),convert(p[4]),convert(p[5]),int(p[6]),float(p[7]),str(p[8].encode("utf-8"))))
Orders_df = sqlContext.createDataFrame(Orders_temp, schema)
return Orders_df
if __name__ == "__main__":
inputer = sys.argv[1]
df0 = dataFrame_Maker(inputer)
print "\n\n"
#print TemperatureFrh(df0,2)
print "\n\n"
print ("Please Select TimeZones for Conversion:",'GMT', 'EDT', 'EST','CDT', 'CST','MDT','MST','PDT', 'PST','IST','Sydney','UTC')
#print TimeConverterGMT(df0,2,'IST')
print "\n\n"
print LengthConverter_Km_Mtr(df0,2)
print "\n\n"
<file_sep>def last(df,arg):
df=df.select(arg).collect() #return type will be list
df=df[-1]
return df
<file_sep>def product(df,arg):
df1=df.fillna(1,subset=arg)
df=df1.select(arg).collect()
m=1
for k in df:
try:
x1=int(k[arg])
except ValueError:
x1=1
m=m*x1
return m
<file_sep>def low(df,i):
try:
int(df[i])
x=''
except ValueError:
x=df[i].lower()
return x
def lower(df,*args):
df1=df.fillna('')
df1=df1.fillna(0)
df1=df1.rdd
for arg in args:
df1=df1.map(lambda x:low(x,arg))
return df1<file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import DataFrameStatFunctions
from pyspark.sql import types
from pyspark.sql.types import * # Imports all data Types
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
#import pyspark.sql.DataFrameStatFunctions as statfunc
conf = SparkConf().setMaster("local").setAppName("Aggregate Module")
sc = SparkContext(conf = conf) # Initalising or Configuring "Spark Context"
sqlContext = SQLContext(sc)
# Columns :- OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName
# Statistical :- Mean ; Median ; Mode ; Standard Deviation ; Variance ; Correlation ; Covariance ; Standardize ; Normalize
################################################################################################################################################
#1. Mean
# Data Type Exceptiion
def Mean_col(df,col):
#return(df.agg(func.mean(df[col]))) # DataFrame[avg(EmployeeID): double]
return(df.agg(func.mean(df[col])).collect()[0][0])
#2. Median
# Data Type Exceptiion
def Median(df,col):
df_sorted = df.sort(df[col].desc()).collect()
#return df_sorted
length = df.count()
if not length % 2:
return((df_sorted[length / 2][col] + df_sorted[(length / 2) - 1][col]) / 2.0)
else:
return(df_sorted[length / 2][col])
'''
length = len(sorts)
if not length % 2:
return (sorts[length / 2] + sorts[length / 2 - 1]) / 2.0
return sorts[length / 2]
'''
#3. Mode
# Data Type Exceptiion
def Mode_Col(df,col):
#return(df.groupby(df[col]).count().distinct().groupby(df[col]).max('count').collect())
#return(df.groupby(df[col]).max(str(df[col])).collect())
dfi = df.groupby(df[col]).count().distinct()
#return(dfi.show())
#return(dfi.agg(func.max(dfi[1])).show())
#return dfi.orderBy(func.desc("count")).first()
return dfi.orderBy(func.desc("count")).collect()[0][0]
#return dfi.sort(dfi.count.desc()).show()
#4. Standard Deviation
# Data Type Exceptiion
def StandardDev(df,col): # returns the unbiased sample standard deviation of the expression in a group.
return(df.agg(func.stddev(df[col])).collect()[0][0])
def StandardDev_pop(df,col): # returns population standard deviation of the expression in a group.
return(df.agg(func.stddev_pop(df[col])).collect()[0][0])
def StandardDev_sample(df,col): # returns the unbiased sample standard deviation of the expression in a group.Almost same as StandardDev.
return(df.agg(func.stddev_samp(df[col])).collect()[0][0])
#5. Variance
# Data Type Exceptiion
def Variance(df,col):
return(df.agg(func.variance(df[col])).collect()[0][0])
def VariancePop(df,col):
return((df.agg(func.var_pop(df[col])).collect()[0][0]))
def VarianceSamp(df,col):
return((df.agg(func.var_samp(df[col])).collect()[0][0]))
#6. Correlation
# Data Type Exceptiion
def Correlation(df,col1,col2,method=None): # Calculates the correlation of two columns of a DataFrame as a double value. Currently only supports the Pearson Correlation Coefficient.So method is specified as "None".
return((df.agg(func.corr(df[col1],df[col2])).collect()[0][0]))
#7. Covariance
# Data Type Exceptiion
#Explore Later
def Covariance(df,col1,col2): # Calculate the sample covariance for the given columns, specified by their names, as a double value.
#return((df.stat.cov(str(df[col1]),str(df[col2])).collect()[0][0]))
#return((df.agg(DataFrameStatFunctions.cov(df[col1],df[col2])).collect()[0][0]))
return(df.cov(col1,col2))
#8. Standardize
# Data Type Exceptiion
#Broad Cast mean,stddev in sc
'''
broadcast = sc.broadcast([mean,stddev])
mean= broadcast.value[0]
stddev = broadcast.value[1]
'''
from pyspark.sql.types import StringType
from pyspark.sql.types import FloatType
from pyspark.sql.functions import udf
def Standardize(df,col,colnum):
mean = Mean_col(df,colnum)
stddev = StandardDev(df,colnum)
print mean,stddev
std = udf(lambda s: ((s-mean)/stddev), FloatType())
#return df.select(std(df[colnum]).alias(col+'Standardize')).collect()
return df.select(std(df[colnum]).alias(col+'Standardize')).show()
#newDF = df.rdd.map(lambda x: ((x[colnum]-mean)/stddev) ).toDF([col+' Standardize'])
#newDF = df.rdd.map(lambda line: (line[colnum])).toDF()
#x = df.rdd.map(lambda line: Row(col =((x[colnum]-mean)/stddev))).toDF()
#return (x.show())
# To be decided correct DataType or Use map to select [:7] places
#9. Normalize
#Data Type Exceptiion
#Broad Cast mini,maxi in sc
'''
broadcast = sc.broadcast([mini,maxi])
mini = broadcast.value[0]
maxi = broadcast.value[1]
'''
'''
Xnew = (X - Xmin)/(Xmax - Xmin)
'''
def Normalize(df,col,colnum):
maxi = df.agg(func.max(df[col])).collect()[0][0]
mini = df.agg(func.min(df[col])).collect()[0][0]
print maxi,mini
rg = maxi - mini
nor = udf(lambda s: ((s-mini)/rg), IntegerType()) # DoubleType FloatType IntegerType
return df.select(nor(df[colnum]).alias(col+'Normalize')).show()
################################################################################################################################################
def test(*args):
x = args[0]
#y = args[1]
print "\n\n"
print x
print "\n\n"
#print y
#print "\n\n"
def convert(date_string):
date_new = date_string.split(" ")[0]
date_object = date(*map(int,(date_string.split(" ")[0].split("-"))))
return date_object
def dataFrame_Maker(*args):
File = args[0]
OrdersFile = sc.textFile(File)
header = OrdersFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
#By Default We Set as StringType()
fields = [StructField(field_name, StringType(), False) for field_name in schemaString.split(',')]
#print(fields)
#print("\n\n")
#print(len(fields) ) # how many elements in the header?
#print "\n\n"
fields[0].dataType = LongType()
fields[2].dataType = IntegerType()
fields[3].dataType = DateType()
fields[4].dataType = DateType()
fields[5].dataType = DateType()
fields[6].dataType = IntegerType()
fields[7].dataType = FloatType()
#print("\n\n")
#print(fields)
#print("\n\n")
schema = StructType(fields)
#print(schema)
#print("\n\n")
OrdersHeader = OrdersFile.filter(lambda l: "OrderID" in l)
#print(OrdersHeader.collect())
#print("\n\n")
OrdersNoHeader = OrdersFile.subtract(OrdersHeader)
#print(OrdersNoHeader.count())
#print("\n\n")
#print(OrdersNoHeader.collect())
#print("\n\n")
Orders_temp = OrdersNoHeader.map(lambda k: k.split(",")).map(lambda p:(int(p[0]),str(p[1].encode("utf-8")),int(p[2]),convert(p[3]),convert(p[4]),convert(p[5]),int(p[6]),float(p[7]),str(p[8].encode("utf-8"))))
#print(Orders_temp.top(2))
#print("\n\n")
Orders_df = sqlContext.createDataFrame(Orders_temp, schema)
#print("Dtypes : ",Orders_df.dtypes)
#print("\n\n")
#print("Schema: ",Orders_df.printSchema())
#print("\n\n")
return Orders_df
if __name__ == "__main__":
inputer = sys.argv[1]
#test(inputer)
df0 = dataFrame_Maker(inputer)
print "\n\n"
print Mode_Col(df0,2)
print "\n\n"
#print Mean_col(df0,2)
print "\n\n"
#print StandardDev(df0,2)
print "\n\n"
#print StandardDev_pop(df0,2)
print "\n\n"
#print StandardDev_sample(df0,2)
print "\n\n"
#print Variance(df0,2)
print "\n\n"
#print VariancePop(df0,2)
print "\n\n"
#print VarianceSamp(df0,2)
print "\n\n"
#print Correlation(df0,0,2)
print "\n\n"
#print Correlation(df0,3,4)
#print "\n\n"
"""
Exception:
pyspark.sql.utils.AnalysisException: u"cannot resolve 'corr(`OrderDate`, `RequiredDate`)' due to data type mismatch: argument 1 requires double type, however, '`OrderDate`' is of date type. argument 2 requires double type, however, '`RequiredDate`' is of date type.;"
"""
#print Covariance(df0,'OrderID','EmployeeID')
print "\n\n"
#print Standardize(df0,'EmployeeID',2)
print "\n\n"
#print Median(df0,2)
print "\n\n"
print Normalize(df0,'EmployeeID',2)
print "\n\n"
<file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import * # Imports all data Types
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
from pyspark.sql.functions import udf
conf = SparkConf().setMaster("local").setAppName("Aggregate Module")
sc = SparkContext(conf = conf) # Initalising or Configuring "Spark Context"
sqlContext = SQLContext(sc)
#Mathematical :- Abs Log Exponential Inverse Factorial Ceiling Floor Mod Power Radians Round Square Cube Square Root Cube Root Sine Cosine
# Columns :- OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName
################################################################################################################################################
#1. Abs
# Data Type Exceptiion
def Absolute(df,col):
#return(df.groupby(df[col]).agg(func.abs(df[col])).show())
#return(df.select(func.abs(df[col]).alias('Abs')).collect())
#return(df.select(func.abs(df[col]).alias('Abs')).map(lambda l: str(l.Abs)).collect())
return(df.select(func.abs(df[col]).alias('Abs')).show())
#2. Log
# Data Type Exceptiion
def Log(df,logval,col): # Returns the first argument-based logarithm of the second argument.If there is only one argument, then this takes the natural logarithm of the argument.
#return(df.groupby(df[col]).agg(func.log(logval,df[col])).show())
#df.select(log(logval, df[col]).alias('ten')).map(lambda l: str(l.ten)).collect()
#return(df.select(func.log(logval,df[col]).alias('Log')).show())
#df.select(func.log(10.0, df.EmployeeID).alias('Ten')).map(lambda l: str(l.ten)[:7]).collect()
#return(df.select(func.log(logval, df[col]).alias('ten')).collect())
return(df.select(func.log(logval, df[col]).alias('Log'+str(logval))).show())
def Log10(df,col): # Computes the logarithm of the given value in Base 10.
return(df.select(func.log10(df[col]).alias('Log10')).show())
def LogNat(df,col): # Computes the natural logarithm of the given value plus one.
return(df.select(func.log1p(df[col]).alias('LogNat+1')).show())
def Log2(df,col): # Returns the base-2 logarithm of the argument.
return(df.select(func.log2(df[col]).alias('Log2')).show())
#3. Exponential
# Data Type Exceptiion
def Exponential(df,col): # Computes the exponential of the given value.
return(df.select(func.exp(df[col]).alias('Exponential')).show())
def ExponentialNeg1(df,col): # Computes the exponential of the given value minus one.
#return(df.select(func.expm1(df[col]).alias('Exponential-1'))) # DataFrame[Exponential-1: double]
return(df.select(func.expm1(df[col]).alias('Exponential-1')).show())
#4. Inverse
# Data Type Exceptiion
'''
'''
#5. Factorial
# Data Type Exceptiion
def Factorial(df,col): # Computes the factorial of the given value.
#return(df.select(factorial(df[col]).alias('Factorial')).collect())
return(df.select(func.factorial(df[col]).alias('Factorial')).show())
#6. Ceiling
# Data Type Exceptiion
def Ceiling(df,col): # Computes the ceiling of the given value.
#return(df.select(func.ceil(df[col]).alias('Ceiling')).collect())
return(df.select(func.ceil(df[col]).alias('Ceiling')).show())
#7. Floor
# Data Type Exceptiion
def Floor(df,col): # Computes the floor of the given value.
#return(df.select(func.floor(df[col]).alias('Floor')).collect())
return(df.select(func.floor(df[col]).alias('Floor')).show())
#8. Mod
# Data Type Exceptiion
'''
'''
#9. Power
# Data Type Exceptiion
def PowerCols(df,col1,col2):
#return(df.select(func.pow(df[col1],df[col2]).alias('Power')).collect())
return(df.select(func.pow(df[col1],df[col2]).alias('Power')).show())
def PowerVal(df,col,val):
#return(df.select(func.pow(df[col],val).alias('Power'+str(val))).collect())
return(df.select(func.pow(df[col],val).alias('Power'+str(val))).show())
#10. Radians
# Data Type Exceptiion
def Radians(df,col): # Converts an angle measured in degrees to an approximately equivalent angle measured in radians.
return(df.select(func.toRadians(df[col]).alias('Radians')).show())
def Degrees(df,col): # Converts an angle measured in radians to an approximately equivalent angle measured in degrees.
return(df.select(func.toDegrees(df[col]).alias('Degrees')).show())
#11. Round
# Data Type Exceptiion
def RoundUP(df,col,scale=0): # Round the given value to scale decimal places using HALF_UP rounding mode if scale >= 0 or at integral part when scale < 0.
return(df.select(func.round(df[col],scale).alias('RoundUP')).show())
def RoundEVEN(df,col,scale=0): # Round the given value to scale decimal places using HALF_UP rounding mode if scale >= 0 or at integral part when scale < 0.
return(df.select(func.bround(df[col],scale).alias('RoundEVEN')).show())
#12. Square
# Data Type Exceptiion
def Square(df,col):
sqr = udf(lambda s: (s*s), IntegerType())
#return(df.rdd.map(lambda line: (line[col]*line[col])))#.toDF(['SquaredCol']))
return df.select(sqr(df[col]).alias('SquaredCol')).show()
#13. Cube
# Data Type Exceptiion
def Cube(df,col):
cub = udf(lambda s: (s*s*s), IntegerType())
#return(df.rdd.map(lambda line: (line[col]*line[col])))#.toDF(['SquaredCol']))
return df.select(cub(df[col]).alias('CubedCol')).show()
#14. Square Root
# Data Type Exceptiion
def SquareRoot(df,col): # Computes the square root of the specified float value.
return(df.select(func.sqrt(df[col]).alias('SquareRoot')).show())
#15. Cube Root
# Data Type Exceptiion
def CubeRoot(df,col): # Computes the cube-root of the given value.
return(df.select(func.cbrt(df[col]).alias('CubeRoot')).show())
#16. Sine
# Data Type Exceptiion
def Sin(df,col): # Computes the sine of the given value.
return(df.select(func.sin(df[col]).alias('Sin')).show())
def Sinh(df,col): # Computes the hyperbolic sine of the given value.
return(df.select(func.sinh(df[col]).alias('Hyperbolic Sine')).show())
def aSin(df,col): # Computes the sine inverse of the given value; the returned angle is in the range-pi/2 through pi/2.
return(df.select(func.asin(df[col]).alias('Sine Inverse')).show())
#17. Cosine
# Data Type Exceptiion
def Cos(df,col): # Computes the cosine of the given value.
return(df.select(func.cos(df[col]).alias('Cos')).show())
def Cosh(df,col): # Computes the hyperbolic cosine of the given value.
return(df.select(func.cosh(df[col]).alias('Hyperbolic Cosine')).show())
def aCos(df,col): # Computes the cosine inverse of the given value; the returned angle is in the range0.0 through pi.
return(df.select(func.acos(df[col]).alias('Cosine Inverse')).show())
################################################################################################################################################
def test(*args):
x = args[0]
#y = args[1]
print "\n\n"
print x
print "\n\n"
#print y
#print "\n\n"
def convert(date_string):
date_new = date_string.split(" ")[0]
date_object = date(*map(int,(date_string.split(" ")[0].split("-"))))
return date_object
def dataFrame_Maker(*args):
File = args[0]
OrdersFile = sc.textFile(File)
header = OrdersFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
#By Default We Set as StringType()
fields = [StructField(field_name, StringType(), False) for field_name in schemaString.split(',')]
#print(fields)
#print("\n\n")
#print(len(fields) ) # how many elements in the header?
#print "\n\n"
fields[0].dataType = LongType()
fields[2].dataType = IntegerType()
fields[3].dataType = DateType()
fields[4].dataType = DateType()
fields[5].dataType = DateType()
fields[6].dataType = IntegerType()
fields[7].dataType = FloatType()
#print("\n\n")
#print(fields)
#print("\n\n")
schema = StructType(fields)
#print(schema)
#print("\n\n")
OrdersHeader = OrdersFile.filter(lambda l: "OrderID" in l)
#print(OrdersHeader.collect())
#print("\n\n")
OrdersNoHeader = OrdersFile.subtract(OrdersHeader)
#print(OrdersNoHeader.count())
#print("\n\n")
#print(OrdersNoHeader.collect())
#print("\n\n")
Orders_temp = OrdersNoHeader.map(lambda k: k.split(",")).map(lambda p:(int(p[0]),str(p[1].encode("utf-8")),int(p[2]),convert(p[3]),convert(p[4]),convert(p[5]),int(p[6]),float(p[7]),str(p[8].encode("utf-8"))))
#print(Orders_temp.top(2))
#print("\n\n")
Orders_df = sqlContext.createDataFrame(Orders_temp, schema)
#print("Dtypes : ",Orders_df.dtypes)
#print("\n\n")
#print("Schema: ",Orders_df.printSchema())
#print("\n\n")
return Orders_df
if __name__ == "__main__":
inputer = sys.argv[1]
#test(inputer)
df0 = dataFrame_Maker(inputer)
#print Absolute(df0,2)
print "\n\n"
#print Log(df0,10.0,2)
print "\n\n"
#print Log2(df0,2)
print "\n\n"
#print ExponentialNeg1(df0,2)
print "\n\n"
#print Factorial(df0,2)
print "\n\n"
#print PowerCols(df0,2,2)
print "\n\n"
#print PowerVal(df0,2,0)
print "\n\n"
#print Degrees(df0,2)
print "\n\n"
#print RoundEVEN(df0,2,1)
print "\n\n"
#print SquareRoot(df0,2)
print "\n\n"
#print aSin(df0,2)
print "\n\n"
#print Cosh(df0,2)
print "\n\n"
print Square(df0,2)
print "\n\n"
<file_sep>def sp(df,i,ke):
try:
int(df[i])
x=''
except ValueError:
x=df[i].split(ke)
return x
def splt(df,arg,val):
df1=df.na.fill('')
df1=df1.na.fill(0)
df1=df1.map(lambda x:sp(x,arg,val))
return df1
<file_sep>def first(df,arg):
return df.select(df[arg]).first()<file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import * # Imports all data Types
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
from pyspark.sql.functions import udf
conf = SparkConf().setMaster("local").setAppName("Aggregate Module")
sc = SparkContext(conf = conf) # Initalising or Configuring "Spark Context"
sqlContext = SQLContext(sc)
#############################################################################################################################################
# Columns :- OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName
#############################################################################################################################################
#1. Rank
'''
pyspark.sql.functions.dense_rank()
Window function: returns the rank of rows within a window partition, without any gaps.
The difference between rank and denseRank is that denseRank leaves no gaps in ranking sequence when there are ties. That is, if you were ranking a competition using denseRank and had three people tie for second place, you would say that all three were in second place and that the next person came in third.
pyspark.sql.functions.percent_rank()
Window function: returns the relative rank (i.e. percentile) of rows within a window partition.
pyspark.sql.functions.rank()
Window function: returns the rank of rows within a window partition.
The difference between rank and denseRank is that denseRank leaves no gaps in ranking sequence when there are ties. That is, if you were ranking a competition using denseRank and had three people tie for second place, you would say that all three were in second place and that the next person came in third.
This is equivalent to the RANK function in SQL.
'''
#def Rank(df,col):
#return(df.select(df[col].func.rank()).alias('Rank').show())
# return df.select(df[col]).alias("Rank").withColumn("Rank", func.rank()).collect()
def Rank(df,colnme):
lookup = df.select(colnme).distinct().orderBy(colnme).rdd.zipWithIndex().map(lambda x: x[0] + (x[1], )).toDF([colnme, "Rank"])
return df.join(lookup, [colnme]).withColumn("Rank", Column("Rank"))
#2. Percentile
'''
pyspark.sql.functions.percent_rank()
Window function: returns the relative rank (i.e. percentile) of rows within a window partition.
'''
#3. Quartile
'''
def quartiles(dataPoints):
# check the input is not empty
if not dataPoints:
raise StatsError('no data points passed')
# 1. order the data set
sortedPoints = sorted(dataPoints)
# 2. divide the data set in two halves
mid = len(sortedPoints) / 2
if (len(sortedPoints) % 2 == 0):
# even
lowerQ = median(sortedPoints[:mid])
upperQ = median(sortedPoints[mid:])
else:
# odd
lowerQ = median(sortedPoints[:mid]) # same as even
upperQ = median(sortedPoints[mid+1:])
return (lowerQ, upperQ)
'''
#4. Decile
'''
'''
################################################################################################################################################
def convert(date_string):
date_new = date_string.split(" ")[0]
date_object = date(*map(int,(date_string.split(" ")[0].split("-"))))
return date_object
def dataFrame_Maker(*args):
File = args[0]
OrdersFile = sc.textFile(File)
header = OrdersFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
fields = [StructField(field_name, StringType(), False) for field_name in schemaString.split(',')]
fields[0].dataType = LongType()
fields[2].dataType = IntegerType()
fields[3].dataType = DateType()
fields[4].dataType = DateType()
fields[5].dataType = DateType()
fields[6].dataType = IntegerType()
fields[7].dataType = FloatType()
schema = StructType(fields)
OrdersHeader = OrdersFile.filter(lambda l: "OrderID" in l)
OrdersNoHeader = OrdersFile.subtract(OrdersHeader)
Orders_temp = OrdersNoHeader.map(lambda k: k.split(",")).map(lambda p:(int(p[0]),str(p[1].encode("utf-8")),int(p[2]),convert(p[3]),convert(p[4]),convert(p[5]),int(p[6]),float(p[7]),str(p[8].encode("utf-8"))))
Orders_df = sqlContext.createDataFrame(Orders_temp, schema)
return Orders_df
if __name__ == "__main__":
inputer = sys.argv[1]
df0 = dataFrame_Maker(inputer)
print "\n\n"
print Rank(df0,'EmployeeID')
print "\n\n"
<file_sep>
#This is just used to collect sample of csv i.e first 2 columns
df1 = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/orders.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1]))
#print(df1.collect()[0])
print("\n\n")
#This is full list of orders csv
df1 = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/orders.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1],line[2],line[3],line[4],line[5],line[6],line[7],line[8],line[9]))
#print(df1.collect()[1:5])
print("\n\n")
#This is full list of products csv
df2 = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/products.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1],line[2],line[3],line[4],line[5],line[6],line[7],line[8],line[9]))
#print(df2.collect()[1:5])
print("\n\n ##This is order-details: ")
#This is full list of order-details csv
df3 = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/order-details.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1],line[2],line[3],line[4]))
#print(df3.collect()[1:5])
print("\n\n")
#Product Dimension Table
print("''''''''''''''''''''''''''''''''''''''''''''''' Products Dimension Table ''''''''''''''''''''''''''''''''''''''''''''''''''")
ProductDimenRDD = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/products.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1],line[3]))
#print(ProductDimenRDD.collect()[1:5])
print("\n\n")
#Employee Dimension Table
print("''''''''''''''''''''''''''''''''''''''''''''''' Employee Dimension Table ''''''''''''''''''''''''''''''''''''''''''''''''''")
ProductDimenDf = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/employees.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1)
def customFunc3(row):
x = row[1]+row[2]
return(x , row[3])
samy = ProductDimenDf.map(customFunc3)
print(samy.collect()[1:5])
print("\n\n")
#df_EmpDimen = samy.toDF(['column', 'value'])
#newDF = SQLContext.createDataFrame(samy, ["Name", "Profession"]) #### TypeError: unbound method createDataFrame() must be called with SQLContext instance as first argument (got PipelinedRDD instance instead)
'''
RDD_of_Rows = samy.map(lambda x : Row(**x))
print(RDD_of_Rows)
df = SQLContext.createDataFrame(RDD_of_Rows)
#df.printschema()
'''
# Even with above, I am facing same error.
print("\n\n")
header = samy.first()
print(header)
rddy = samy.filter(lambda line:line != header)
#Location Dimension Table
print(rddy.take(2))
print('\n\n Checking toDF() \n\n ')
print(hasattr(rddy, "toDF"))
print('\n\n')
print('\n\n Checking toDF() Again \n\n')
sqlContext = SQLContext(sc) # or HiveContext
print(hasattr(rddy, "toDF"))
print('\n\n Now Finally ---------------- KKKKKKKKKKKKKKKKKKKK: \n\n')
df = rddy.map(lambda line: Row(Name = line[0], Profession = line[1])).toDF()
print(df.take(5))
print("\n\n")
print(df)
print("\n\n")
print(df.select('Name').show(5))
print("\n\n")
print("''''''''''''''''''''''''''''''''''''''''''''''' Location Dimension Table ''''''''''''''''''''''''''''''''''''''''''''''''''")
LocationDimenRDD = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/customers.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1)
#.map(lambda line: (line[5],line[8]))
count = 1000
def customFunction(row):
return (count + 1, row[5] ,row[8])
sample = LocationDimenRDD.map(customFunction)
#sample3 = LocationDimenRDD.withColumn('LocationCode', LocationDimenDf.CustomerID + 2)
#print(sample.collect()[1:5])
print("\n\n")
#Period Dimension Table
print("''''''''''''''''''''''''''''''''''''''''''''''' Period Dimension Table ''''''''''''''''''''''''''''''''''''''''''''''''''")
PeriodDimenRDD = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/orders.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1)
#d = { '1' : 'Q1' , '2' : 'Q1' , '3' : 'Q1' , '4' : 'Q2' , '5' : 'Q2' , '6' : 'Q2' , '7' : 'Q3', '8' : 'Q3' , '9' : 'Q3' , '10' : 'Q4' , '11' : 'Q4' , '12' : 'Q4' ,' ' : ' '}
d = { '01' : 'Q1' , '02' : 'Q1' , '03' : 'Q1' , '04' : 'Q2' , '05' : 'Q2' , '06' : 'Q2' , '07' : 'Q3', '08' : 'Q3' , '09' : 'Q3' , '10' : 'Q4' , '11' : 'Q4' , '12' : 'Q4' ,' ' : ' '}
def customfunction2(row):
x = row[3].split(" ")
y = x[0].split("-")
yr = y[1]
#q = str(y[0][1])
#qr = d[q]
#prc = yr + qr
#return(prc , yr , qr)
return(yr,y)
sam1 = PeriodDimenRDD.map(customfunction2)
#print(sam1.collect())
print("\n\n")
'''
df3n = df3.map(lambda x: (x[1],x[0],x[2],x[3],x[4]))
print(df3n.collect()[1:5])
print("\n\n")
df4 = df2.join(df3n)
print(df4.collect()[1:5])
print('\n\n')
a = df4.groupByKey()
#print(a.collect())
val = a.collect()[1:3]
print(val)
print('\n\n')
print([(j[0],[i for i in j[1]]) for j in val)
'''
#print([(j[0],[i for i in j[1]]) for j in a.collect()])
'''
print('\n\n')
'''
<file_sep>def ZerotoNull(df,*args):
a=list(args)
df=df.na.replace(0,'',subset=a)
return df<file_sep>
'''
Notes:
Managing Spark Partitions with Coalesce and Repartition
Spark splits data into partitions and executes computations on the partitions in parallel. We should understand how data is partitioned and when you need to manually adjust the partitioning to keep your Spark computations running efficiently.
'''
# -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
conf = SparkConf().setMaster("local").setAppName("Task 1")
sc = SparkContext(conf = conf)
sqlContext = SQLContext(sc)
################################################ D1_AutoInsurance.csv ###################################################
print("\n\n************************************* D1_AutoInsurance.csv ********************************************\n\n")
'''
Customer State Customer Lifetime Value Response Coverage Education Effective To Date EmploymentStatus Gender Income Location Code Marital Status Monthly Premium Auto Months Since Last Claim Months Since Policy Inception Number of Open Complaints Number of Policies Policy Type Policy Renew Offer Type Sales Channel Total Claim Amount Vehicle Class Vehicle Size
'''
filey = "/root/Desktop/D1_AutoInsurance.csv"
spark = SparkSession.builder.master("local").appName("Task 3 App").config("spark.some.config.option", "some-value").getOrCreate()
df = spark.read.csv(filey,header=True,inferSchema=True)
#(schema=None, sep=None, encoding=None, quote=None, escape=None, comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None, ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None, negativeInf=None, dateFormat=None, maxColumns=None, maxCharsPerColumn=None, maxMalformedLogPerPartition=None, mode=None)
df.show()
#print(df.schema)
print df.printSchema()
df.rdd.repartition(3)
print df.rdd.getNumPartitions()
print "\n\n"
#df.write.csv("/root/Desktop/spark_output")
#Depending on the number of Partitions, The data is separated on the different partitions.
#coalesce
#The coalesce method reduces the number of partitions in a DataFrame.
df.coalesce(2)
print df.rdd.getNumPartitions()
# As I am working on standalone local System,partition will always be 1.
'''
The coalesce algorithm moved the data from Partition B to Partition A and moved the data from Partition D to Partition C. The data in Partition A and Partition C does not move with the coalesce algorithm. This algorithm is fast in certain situations because it minimizes data movement.
'''
#The coalesce algorithm changes the number of nodes by moving data from some partitions to existing partitions. This algorithm obviously cannot increate the number of partitions.
#Repartition
#The repartition method can be used to either increase or decrease the number of partitions in a DataFrame.
df.repartition(2)
print df.rdd.getNumPartitions()
'''
Repartition ==> 2 For,
Partition ABC: 1, 3, 5, 6, 8, 10
Partition XYZ: 2, 4, 7, 9
Partition ABC contains data from Partition A, Partition B, Partition C, and Partition D. Partition XYZ also contains data from each original partition. The repartition algorithm does a full data shuffle and equally distributes the data among the partitions. It does not attempt to minimize data movement like the coalesce algorithm.
'''
df.repartition(6)
print df.rdd.getNumPartitions()
'''
Partition 00000: 5, 7
Partition 00001: 1
Partition 00002: 2
Partition 00003: 8
Partition 00004: 3, 9
Partition 00005: 4, 6, 10
The repartition method does a full shuffle of the data, so the number of partitions can be increased.
'''
'''
Differences between coalesce and repartition
The repartition algorithm does a full shuffle of the data and creates equal sized partitions of data. coalesce combines existing partitions to avoid a full shuffle.
'''
#repartition by column:
Statedf = df.repartition(df.State)
Statedf.show() # PARTITION Occured by STATE Name.
''''
When partitioning by a column, Spark will create a minimum of 200 partitions by default. This example will have two partitions with data and 198 empty partitions.
The statef contains different partitions for each state and is optimized for extracts by state. Partitioning by a column is similar to indexing a column in a relational database.
'''
'''
In general, you can determine the number of partitions by multiplying the number of CPUs in the cluster by 4 (source).
number_of_partitions = number_of_cpus * 4
'''
#If you're writing the data out to a file system, you can choose a partition size that will create reasonable sized files (100MB). Spark will optimize the number of partitions based on the number of clusters when the data is read.
#Why did we use the repartition method instead of coalesce?
#A full data shuffle is an expensive operation for large data sets, but our data puddle is only 2,000 rows. The repartition method returns equal sized text files, which are more efficient for downstream consumers.
#Actual performance improvement
#It took 241 seconds to count the rows in the data puddle when the data wasn't repartitioned on a 5 node cluster. But 2 sec after Partition.
'''
You probably need to think about partitions
The partitioning of DataFrames seems like a low level implementation detail that should be managed by the framework, but it's not. When filtering large DataFrames into smaller ones, you should almost always repartition the data.
You'll probably be filtering large DataFrames into smaller ones frequently, so get used to repartitioning.
'''
#######################################
#One additional point to note here is that, as the basic principle of Spark RDD is immutability. The repartition or coalesce will create new RDD. The base RDD will continue to have existence with its original number of partitions. In case the use case demands to persist RDD in cache, then the same has to be done for the newly created RDD.
######################################
KeysVal = df.rdd.map(lambda x: (x[1],[x[0],x[2]])).toDF(["Key","Value"])
print KeysVal.show()
print "\n\n"
A = df.rdd.countByKey()
#B = df.rdd.collectAsMap()
C = df.rdd.lookup("Arizona")
print A
print "\n\n"
#print B
print "\n\n"
print C
print "\n\n"
'''
#joins and cogroup in Spark :
There are indications that joins in Spark are implemented with / based on the cogroup function/primitive/transform. So let me focus first on cogroup - it returns a result which is RDD consisting of essentially ALL elements of the cogrouped RDDs. Said in another way - for every key in each of the cogrouped RDDs there is at least one element from at least one of the cogrouped RDDs.
That would mean that when smaller, moreover streaming e.g. JavaPairDstreamRDDs keep getting joined with much larger, batch RDD that would result in RAM allocated for multiple instances of the result (cogrouped) RDD a.k.a essentially the large batch RDD and some more ... Obviously the RAM will get returned when the DStream RDDs get discard and they do on a regular basis, but still that seems as unnecessary spike in the RAM consumption
We have two questions:
Is there anyway to control the cogroup process more "precisely" e.g. tell it to include I the cogrouped RDD only elements where there are at least one element from EACH of the cogrouped RDDs per given key. Based on the current cogroup API this is not possible
If the cogroup is really such a sledgehammer and secondly the joins are based on cogroup then even though they can present a prettier picture in terms of the end result visible to the end user does that mean that under the hood there is still the same atrocious RAM consumption going on
Solution:
It is not that bad. It largelly depends on the granularity of your partitioning. Cogroup will first shuffle by key, in disk, to distinct executor nodes. For each key, yes, the entire set of all elements with that key, for both RDDs, will be loaded in RAM and given to you. But not all keys need to be in RAM at any given time, so unless your data is really skewed you will not suffer for it much.
'''
x = df.rdd.map(lambda l:(str(l[0]), 1))
y = df.rdd.map(lambda l:(str(l[0]), 2))
CGXY = x.cogroup(y).collect()[:10]
print SXY
JXY = x.join(y).collect()[:10]
print JXY
#groupByKey and reduceByKey
#groupByKey([numTasks])
KeysGroupBy = KeysVal.groupByKey()
#print KeysGroupBy.collect()[:10]
print "\n\n"
KeysMap = KeysGroupBy.map(lambda x : {x[0]: list(x[1])}).collect()
#print KeysMap[:10]
print "\n\n"
#print rdd.collect()[:10]
ReduceKeyRDD = df.rdd.map(lambda n: (str(n[1]), float(n[2]))).reduceByKey(lambda v1,v2: v1 + v2).collect()
#print ReduceKeyRDD
print "\n\n"
<file_sep># -*- coding: utf-8 -*-
import numpy
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
conf = SparkConf().setMaster("local").setAppName("Task 1")
sc = SparkContext(conf = conf)
sqlContext = SQLContext(sc)
################################################ D1_AutoInsurance.csv ###################################################
print("\n\n************************************* D1_AutoInsurance.csv ********************************************\n\n")
'''
Customer State Customer Lifetime Value Response Coverage Education Effective To Date EmploymentStatus Gender Income Location Code Marital Status Monthly Premium Auto Months Since Last Claim Months Since Policy Inception Number of Open Complaints Number of Policies Policy Type Policy Renew Offer Type Sales Channel Total Claim Amount Vehicle Class Vehicle Size
'''
#RDD
'''
filey = sc.textFile("/root/Desktop/D1_AutoInsurance.csv")
rdd = filey.map(lambda line: line.split(","))
print rdd.count()
header = rdd.first() #extract header
rddN = rdd.filter(lambda row : row != header) #filter out header
Map_rdd = rddN.map(lambda x: [x[0],x[1],x[2]])
print Map_rdd.collect()[:10]
print "\n\n"
KeyValueRDD = rddN.map(lambda n: (str(n[1]), float(n[2])))
'''
#DF
filey = "/root/Desktop/D1_AutoInsurance.csv"
spark = SparkSession.builder.master("local").appName("Task 4 App").config("spark.some.config.option", "some-value").getOrCreate()
df = spark.read.csv(filey,header=True,inferSchema=True)
df.show()
print df.printSchema()
dfN = df.select(df[6])
dfN.show()
from datetime import date, datetime
def convert(date_string):
x = date_string.split("/")
print x
print "\n\n"
date_object = date(*map(int,([x[2],x[0],x[1]])))
return date_object
DF = df.rdd.map(lambda p:convert(p[6]))
print DF.collect()[:10]
#add_months(start, months)
#Returns the date that is months months after start
#dfn = DF.select(func.add_months(DF[6], 1).alias('AddedMonth'))
#print dfn.collect()[:10]
################################
OrdersFile = sc.textFile("/root/Desktop/example.csv")
header = OrdersFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
#By Default We Set as StringType()
fields = [StructField(field_name, StringType(), False) for field_name in schemaString.split(',')]
print(fields)
print("\n\n")
print(len(fields) ) # how many elements in the header?
print "\n\n"
fields[2].dataType = FloatType()
fields[6].dataType = DateType()
print("\n\n")
print(fields)
print("\n\n")
schema = StructType(fields)
print(schema)
print("\n\n")
OrdersHeader = OrdersFile.filter(lambda l: "Customer" in l)
print(OrdersHeader.collect())
print("\n\n")
OrdersNoHeader = OrdersFile.subtract(OrdersHeader)
print(OrdersNoHeader.count())
print("\n\n")
print(OrdersNoHeader.collect())
print("\n\n")
from datetime import date, datetime
def convert(date_string):
x = date_string.split("/")
print x
print "\n\n"
date_object = date(*map(int,([x[2],x[0],x[1]])))
return date_object
#(int(p[0]),str(p[1].encode("utf-8")),int(p[2]),convert(p[3]),convert(p[4]),convert(p[5]),int(p[6]),float(p[7]),str(p[8].encode("utf-8"))
Orders_temp = OrdersNoHeader.map(lambda k: k.split(",")).map(lambda p:(str(p[0].encode("utf-8")),str(p[1].encode("utf-8")),float(p[2]),str(p[3].encode("utf-8")),str(p[4].encode("utf-8")),str(p[5].encode("utf-8")),convert(p[6])))
print(Orders_temp.top(2))
print("\n\n")
Orders_df = sqlContext.createDataFrame(Orders_temp, schema)
print("Dtypes : ",Orders_df.dtypes)
print("\n\n")
print("Schema: ",Orders_df.printSchema())
print("\n\n")
#add_months(start, months)
#Returns the date that is months months after start
dfn = Orders_df.select(func.add_months(Orders_df[6], 1).alias('AddedMonth'))
print "OOOOOOOOOOOOOOOOOOOOOOOOOMMMMMMMMMMMMMMMMMMMMMMMMMMMMGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG"
print "\n\n"
print dfn.collect()[:10]
dfn.show()
dfn2 = Orders_df.select(func.date_add(Orders_df[6], 1).alias('AddedDate'))
#dfn2.show()
#date_format(date, format)
dfn3 = Orders_df.select(func.date_format(Orders_df[6], 'MM/dd/yyy').alias('date'))
#dfn3.show()
#date_sub(start, days)
dfn4 = Orders_df.select(func.date_sub(Orders_df[6], 3).alias('date_sub'))
#dfn4.show()
#datediff(end, start)
dfn5 = Orders_df.select(func.datediff(Orders_df[6],Orders_df[6]).alias('datediff'))
#dfn5.show()
#dayofmonth(col)
dfn6 = Orders_df.select(func.dayofmonth(Orders_df[6]).alias('dayofmonth'))
#dfn6.show()
#dayofyear(col)
dfn7 = Orders_df.select(func.dayofyear(Orders_df[6]).alias('dayofyear'))
#dfn7.show()
#functions.last_day(date)
dfn8 = Orders_df.select(func.last_day(Orders_df[6]).alias('last_day'))
#dfn8.show()
#functions.month
dfn9 = Orders_df.select(func.month(Orders_df[6]).alias('month'))
dfn9.show()
#functions.months_between(date1, date2)
dfn10 = Orders_df.select(func.months_between(Orders_df[6],Orders_df[6]).alias('months_between'))
#dfn10.show()
#functions.next_day(date, dayOfWeek)
dfn11 = Orders_df.select(func.next_day(Orders_df[6],'Sun').alias('next_day'))
#dfn11.show()
#functions.to_date(col)
dfn12 = Orders_df.select(func.to_date(Orders_df[6]).alias('to_date'))
#dfn12.show()
#functions.weekofyear(col)
dfn13 = Orders_df.select(func.weekofyear(Orders_df[6]).alias('weekofyear'))
#dfn13.show()
#functions.year(col)
dfn14 = Orders_df.select(func.year(Orders_df[6]).alias('year'))
#dfn14.show()
#Quarter(col)
def Quarter(x):
#d = { '01' : 'Q1' , '02' : 'Q1' , '03' : 'Q1' , '04' : 'Q2' , '05' : 'Q2' , '06' : 'Q2' , '07' : 'Q3', '08' : 'Q3' , '09' : 'Q3' , '10' : 'Q4' , '11' : 'Q4' , '12' : 'Q4' }
d = { '1' : 'Q1' , '2' : 'Q1' , '3' : 'Q1' , '4' : 'Q2' , '5' : 'Q2' , '6' : 'Q2' , '7' : 'Q3', '8' : 'Q3' , '9' : 'Q3' , '10' : 'Q4' , '11' : 'Q4' , '12' : 'Q4' ,' ' : ' '}
print "OOOOOOOK"
print x
return(d[str(x.month)])
dfn15 = Orders_df.rdd.map(lambda l: Row(Quarter = Quarter(l[6]))).toDF()
#dfn15 = dfi.map(lambda line: Row(Quarter = line[0])).toDF()
#dfn15 = Orders_df.select(Quarter(Orders_df[6]))
#print dfn15.collect()
dfn15.show()
#functions.quarter(col)
dfn16 = Orders_df.select(func.quarter(Orders_df[6]).alias('quarter'))
dfn16.show()
#FiscalWeek || FiscalYear
#Month Start Date
#date_list = [my_dt_ob.year, my_dt_ob.month, my_dt_ob.day, my_dt_ob.hour, my_dt_ob.minute, my_dt_ob.second]
def Month_Start_Date(x):
x = x.replace(day=1)
print x.day
return x
dfn17 = Orders_df.rdd.map(lambda l: Row(Month_Start_Date = Month_Start_Date(l[6]))).toDF()
dfn17.show()
<file_sep>from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import HiveContext
from pyspark.sql import GroupedData
from pyspark.sql import DataFrameNaFunctions
from pyspark.sql import DataFrameStatFunctions
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql import Window
#Normal Spark Code
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local").setAppName("My App")
sc = SparkContext(conf = conf) #Initalising or Configuring "Spark Context"
'''
#************************************************************************************************************************************************#
#Working ON Text files
#************************************************************************************************************************************************#
lines = sc.textFile('/home/akhil/Desktop/SampleTextFile.txt')
#print(lines.collect()) // It gives full set of lines
#print(lines.take(10)) // It gives out top ten elements of LIST
print(lines.first()) # It gives sample part of file
lines_nonempty = lines.filter( lambda x: len(x) > 0 ) # We are using "filter" to use len() to remove all nonempty lines
print(lines_nonempty) # It prints a RDD
print(lines_nonempty.count()) # It prints "count" of value
words = lines_nonempty.flatMap(lambda x: x.split()) #flatmap will return only all words in lines
print(words.take(10))
wordc1 = words.map(lambda x: (x, 1)) # Initalise each word with "1" and "word" as KEY
wordc2 = wordc1.reduceByKey(lambda x,y:x+y) # Now collect all values of "KEYS" by adding counts
print(wordc2.take(5))
'''
'''
[(u'semper,', 12), (u'semper.', 19), (u'ipsum.', 54), (u'ipsum,', 37), (u'mollis.', 12)]
'''
'''
wordc3 = wordc2.map(lambda x:(x[1],x[0])) # Changing oritation of Key by "map"
print(wordc3.take(5))
'''
'''
[(12, u'semper,'), (19, u'semper.'), (54, u'ipsum.'), (37, u'ipsum,'), (12, u'mollis.')]
'''
'''
wordcounts = wordc3.sortByKey(False) # False means Decreasing order
print(wordcounts.take(10))
'''
'''
[(473, u'et'), (416, u'sit'), (352, u'at'), (350, u'ac'), (327, u'in'), (326, u'quis'), (315, u'vitae'), (314, u'non'), (310, u'a'), (304, u'vel')]
'''
'''
wordcounts2 = wordc3.sortByKey() # True means Increasing or leave as default
print(wordcounts2.take(10))
'''
'''
[(3, u'imperdiet,'), (3, u'purus,'), (3, u'vehicula,'), (3, u'maximus.'), (3, u'laoreet,'), (3, u'feugiat,'), (3, u'dignissim,'), (3, u'iaculis,'), (3, u'vulputate,'), (3, u'sodales,')]
'''
'''
#Transformation in a single invocation, with a few changes to deal with some punctuation characters and convert #the text to lower case.
#We use lower() to convert from Uppper to lower Case
wordcountsrev = sc.textFile('/home/akhil/Desktop/SampleTextFile.txt') \
.map( lambda x: x.replace(',',' ').replace('.',' ').replace('-',' ').lower()) \
.flatMap(lambda x: x.split()) \
.map(lambda x: (x, 1)) \
.reduceByKey(lambda x,y:x+y) \
.map(lambda x:(x[1],x[0])) \
.sortByKey(False)
print(wordcountsrev.take(10))
#Finding frequent word bigrams (Two words comeing as a Pair)
#Work on sentences
sent1 = sc.textFile('/home/akhil/Desktop/SampleTextFile.txt').glom() #glom() helps to get uniform list of set of lists like [[]]
print(sent1.take(10))
sent2 = sent1.map(lambda x: " ".join(x))
print(sent2.take(3))
sentences = sent2.flatMap(lambda x: x.split("."))
print(sentences.take(5))
'''
'''
[u'Lorem ipsum dolor sit amet, consectetur adipiscing elit', u' Vivamus condimentum sagittis lacus, laoreet luctus ligula laoreet ut', u' Vestibulum ullamcorper accumsan velit vel vehicula', u' Proin tempor lacus arcu', u' Nunc at elit condimentum, semper nisi et, condimentum mi']
'''
'''
bigrams = sentences.map(lambda x:x.split()).flatMap(lambda x: [((x[i],x[i+1]),1) for i in range(0,len(x)-1)])
print(bigrams.take(10))
#new RDD contains tuples containing the word bigram (itself a tuple containing the first and second word) as the first value and the number #1 as the second value.
'''
'''
[((u'Lorem', u'ipsum'), 1), ((u'ipsum', u'dolor'), 1), ((u'dolor', u'sit'), 1), ((u'sit', u'amet,'), 1), ((u'amet,', u'consectetur'), 1), ((u'consectetur', u'adipiscing'), 1), ((u'adipiscing', u'elit'), 1), ((u'Vivamus', u'condimentum'), 1), ((u'condimentum', u'sagittis'), 1), ((u'sagittis', u'lacus,'), 1)]
'''
'''
freq_bigrams = bigrams.reduceByKey(lambda x,y:x+y).map(lambda x:(x[1],x[0])).sortByKey(False)
print(freq_bigrams.take(10))
'''
'''
The map and reduceByKey RDD transformations will be immediately recognizable to aficionados of the MapReduce paradigm. Spark supports the efficient parallel application of map and reduce operations by dividing data up into multiple partitions. In the example above, each file will by default generate one partition. What Spark adds to existing frameworks like Hadoop are the ability to add multiple map and reduce tasks to a single workflow.
'''
'''
#This Step is used to look at :
# The distribution of objects in each partition in our rdd
lines = sc.textFile('/home/akhil/Desktop/SampleTextFile.txt')
def countPartitions(id,iterator):
c = 0
for _ in iterator:
c += 1
yield (id,c)
x = lines.mapPartitionsWithSplit(countPartitions).collectAsMap()
print(x)
'''
'''
* Each partition within an RDD is replicated across multiple workers running on different nodes in a cluster so that failure of a single worker should not cause the RDD to become unavailable.
* Many operations including map and flatMap operations can be applied independently to each partition, running as concurrent jobs based on the number of available cores. Typically these operations will preserve the number of partitions.
* When processing reduceByKey, Spark will create a number of output partitions based on the default paralellism based on the numbers of nodes and cores available to Spark. Data is effectively reshuffled so that input data from different input partitions with the same key value is passed to the same output partition and combined there using the specified reduce function. sortByKey is another operation which transforms N input partitions to M output partitions.
'''
'''
print(sc.defaultParallelism)
wordcounters = sc.textFile('/home/akhil/Desktop/SampleTextFile.txt') \
.map( lambda x: x.replace(',',' ').replace('.',' ').replace('-',' ').lower()) \
.flatMap(lambda x: x.split()) \
.map(lambda x: (x, 1)) \
.reduceByKey(lambda x,y:x+y)
print(wordcounters.mapPartitionsWithSplit(countPartitions).collectAsMap())
#Same thing with control on partitions @ numPartitions = 2
wordcountering = sc.textFile('/home/akhil/Desktop/SampleTextFile.txt') \
.map( lambda x: x.replace(',',' ').replace('.',' ').replace('-',' ').lower()) \
.flatMap(lambda x: x.split()) \
.map(lambda x: (x, 1)) \
.reduceByKey(lambda x,y:x+y,numPartitions=2)
print(wordcountering.mapPartitionsWithSplit(countPartitions).collectAsMap())
'''
#************************************************************************************************************************************************#
#Working ON CSV files (northwind Data Base)
#************************************************************************************************************************************************#
#This is just used to collect sample of csv i.e first 2 columns
df1 = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/orders.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1]))
#print(df1.collect()[0])
print("\n\n")
#This is full list of orders csv
df1 = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/orders.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1],line[2],line[3],line[4],line[5],line[6],line[7],line[8],line[9]))
#print(df1.collect()[1:5])
print("\n\n")
#This is full list of products csv
df2 = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/products.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1],line[2],line[3],line[4],line[5],line[6],line[7],line[8],line[9]))
#print(df2.collect()[1:5])
print("\n\n ##This is order-details: ")
#This is full list of order-details csv
df3 = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/order-details.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1],line[2],line[3],line[4]))
#print(df3.collect()[1:5])
print("\n\n")
#Product Dimension Table
print("''''''''''''''''''''''''''''''''''''''''''''''' Products Dimension Table ''''''''''''''''''''''''''''''''''''''''''''''''''")
ProductDimenRDD = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/products.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line: (line[0],line[1],line[3]))
#print(ProductDimenRDD.collect()[1:5])
print("\n\n")
#Employee Dimension Table
print("''''''''''''''''''''''''''''''''''''''''''''''' Employee Dimension Table ''''''''''''''''''''''''''''''''''''''''''''''''''")
ProductDimenDf = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/employees.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1)
def customFunc3(row):
x = row[1]+row[2]
return(x , row[3])
samy = ProductDimenDf.map(customFunc3)
print(samy.collect()[1:5])
print("\n\n")
#df_EmpDimen = samy.toDF(['column', 'value'])
#newDF = SQLContext.createDataFrame(samy, ["Name", "Profession"]) #### TypeError: unbound method createDataFrame() must be called with SQLContext instance as first argument (got PipelinedRDD instance instead)
'''
RDD_of_Rows = samy.map(lambda x : Row(**x))
print(RDD_of_Rows)
df = SQLContext.createDataFrame(RDD_of_Rows)
#df.printschema()
'''
# Even with above, I am facing same error.
print("\n\n")
header = samy.first()
print(header)
rddy = samy.filter(lambda line:line != header)
#Location Dimension Table
print(rddy.take(2))
print('\n\n Checking toDF() \n\n ')
print(hasattr(rddy, "toDF"))
print('\n\n')
print('\n\n Checking toDF() Again \n\n')
sqlContext = SQLContext(sc) # or HiveContext
print(hasattr(rddy, "toDF"))
print('\n\n Now Finally ---------------- KKKKKKKKKKKKKKKKKKKK: \n\n')
df = rddy.map(lambda line: Row(Name = line[0], Profession = line[1])).toDF()
print(df.take(5))
print("\n\n")
print(df)
print("\n\n")
print(df.select('Name').show(5))
print("\n\n")
print("''''''''''''''''''''''''''''''''''''''''''''''' Location Dimension Table ''''''''''''''''''''''''''''''''''''''''''''''''''")
LocationDimenRDD = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/customers.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1)
#.map(lambda line: (line[5],line[8]))
count = 1000
def customFunction(row):
return (count + 1, row[5] ,row[8])
sample = LocationDimenRDD.map(customFunction)
#sample3 = LocationDimenRDD.withColumn('LocationCode', LocationDimenDf.CustomerID + 2)
#print(sample.collect()[1:5])
print("\n\n")
#Period Dimension Table
print("''''''''''''''''''''''''''''''''''''''''''''''' Period Dimension Table ''''''''''''''''''''''''''''''''''''''''''''''''''")
PeriodDimenRDD = sc.textFile("/home/akhil/Desktop/Ass@SparkSQL/northwind-mongo-master/orders.csv").map(lambda line: line.split(",")).filter(lambda line: len(line)>1)
#d = { '1' : 'Q1' , '2' : 'Q1' , '3' : 'Q1' , '4' : 'Q2' , '5' : 'Q2' , '6' : 'Q2' , '7' : 'Q3', '8' : 'Q3' , '9' : 'Q3' , '10' : 'Q4' , '11' : 'Q4' , '12' : 'Q4' ,' ' : ' '}
d = { '01' : 'Q1' , '02' : 'Q1' , '03' : 'Q1' , '04' : 'Q2' , '05' : 'Q2' , '06' : 'Q2' , '07' : 'Q3', '08' : 'Q3' , '09' : 'Q3' , '10' : 'Q4' , '11' : 'Q4' , '12' : 'Q4' ,' ' : ' '}
def customfunction2(row):
x = row[3].split(" ")
y = x[0].split("-")
yr = y[1]
#q = str(y[0][1])
#qr = d[q]
#prc = yr + qr
#return(prc , yr , qr)
return(yr,y)
sam1 = PeriodDimenRDD.map(customfunction2)
#print(sam1.collect())
print("\n\n")
'''
df3n = df3.map(lambda x: (x[1],x[0],x[2],x[3],x[4]))
print(df3n.collect()[1:5])
print("\n\n")
df4 = df2.join(df3n)
print(df4.collect()[1:5])
print('\n\n')
a = df4.groupByKey()
#print(a.collect())
val = a.collect()[1:3]
print(val)
print('\n\n')
print([(j[0],[i for i in j[1]]) for j in val)
'''
#print([(j[0],[i for i in j[1]]) for j in a.collect()])
'''
print('\n\n')
'''
<file_sep>def funmul(df,i,j):
try:
x1=int(df[i])
except ValueError:
x1=1
try:
x2=int(df[j])
except ValueError:
x2=1
x=x1*x2
return x
def mul(df,arg1,arg2):
df1=df.fillna(1)
df1=df1.rdd
df1=df1.map(lambda x:funmul(x,arg1,arg2))
return df1<file_sep>def dele(df,arg,val):
df1=df.fillna(0)
df1=df.select(arg).collect()
a=[]
for k in df1:
if k[arg]!=val:
a.append(k)
return a<file_sep>def fl(df,i):
func = lambda s: s[:1].lower() + s[1:] if s else ''
x=func(df[i])
return x
def flower(df,*args):
df1=NulltoZero(df)
df1=df1.rdd
for arg in args:
df1=df1.map(lambda x:fl(x,arg))
return df1<file_sep>def funadd(df,i,j):
try:
x1=int(df[i])
except ValueError:
x1=0
try:
x2=int(df[j])
except ValueError:
x2=0
x=x1+x2
return x
def add(df,arg1,arg2):
df1=df.fillna(0)
df1=df1.rdd
df1=df1.map(lambda x:funadd(x,arg1,arg2))
return df1<file_sep>def uni(df1,df2):
df3=df1.union(df2).distinct()
return df3<file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
conf = SparkConf().setMaster("local").setAppName("Task 1")
sc = SparkContext(conf = conf)
sqlContext = SQLContext(sc)
################################################ D1_AutoInsurance.csv ###################################################
print("\n\n************************************* D1_AutoInsurance.csv ********************************************\n\n")
'''
Customer State Customer Lifetime Value Response Coverage Education Effective To Date EmploymentStatus Gender Income Location Code Marital Status Monthly Premium Auto Months Since Last Claim Months Since Policy Inception Number of Open Complaints Number of Policies Policy Type Policy Renew Offer Type Sales Channel Total Claim Amount Vehicle Class Vehicle Size
'''
#RDD
#combineByKey()
filey = sc.textFile("/root/Desktop/D1_AutoInsurance.csv")
rdd = filey.map(lambda line: line.split(","))
print rdd.count()
header = rdd.first() #extract header
rddN = rdd.filter(lambda row : row != header) #filter out header
Map_rdd = rddN.map(lambda x: [x[0],x[1],x[2]])
print Map_rdd.collect()[:10]
print "\n\n"
KeyValueRDD = rddN.map(lambda n: (str(n[1]), float(n[2])))
def add(a, b):
return a + int(b)
print sorted(KeyValueRDD.combineByKey(int, add, add).collect())
#DF
'''
filey = "/root/Desktop/D1_AutoInsurance.csv"
spark = SparkSession.builder.master("local").appName("Task 4 App").config("spark.some.config.option", "some-value").getOrCreate()
df = spark.read.csv(filey,header=True,inferSchema=True)
df.show()
#print df.printSchema()
'''
<file_sep>def sel(df,arg):
df1=df.select(arg)
return df1<file_sep>def dis(df,arg):
df1=df.select(arg).distinct()
return df1<file_sep>def fil(df,arg,op,val):
df1=df.na.fill(0)
df1=df1.na.fill('')
df1=df1.filter(df1[arg])
return df1<file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
conf = SparkConf().setMaster("local").setAppName("Task 1")
sc = SparkContext(conf = conf)
sqlContext = SQLContext(sc)
################################################ D1_AutoInsurance.csv ###################################################
print("\n\n************************************* D1_AutoInsurance.csv ********************************************\n\n")
'''
Customer State Customer Lifetime Value Response Coverage Education Effective To Date EmploymentStatus Gender Income Location Code Marital Status Monthly Premium Auto Months Since Last Claim Months Since Policy Inception Number of Open Complaints Number of Policies Policy Type Policy Renew Offer Type Sales Channel Total Claim Amount Vehicle Class Vehicle Size
'''
#RDD
'''
filey = sc.textFile("/root/Desktop/D1_AutoInsurance.csv")
rdd = filey.map(lambda line: line.split(","))
print rdd.count()
header = rdd.first() #extract header
rddN = rdd.filter(lambda row : row != header) #filter out header
Map_rdd = rddN.map(lambda x: [x[0],x[1],x[2]])
print Map_rdd.collect()[:10]
print "\n\n"
KeyValueRDD = rddN.map(lambda n: (str(n[1]), float(n[2])))
'''
#DF
filey = "/root/Desktop/D1_AutoInsurance.csv"
spark = SparkSession.builder.master("local").appName("Task 4 App").config("spark.some.config.option", "some-value").getOrCreate()
df = spark.read.csv(filey,header=True,inferSchema=True)
df.show()
print df.printSchema()
c = 0
flag1 = 0
def abc(l): # BroadCast c
#global c
if broadcastedflag.value[0] == 0:
c = broadcasted.value[0]
c+=1
broadcastedflag.value[0]+=1
else:
broadcasted.value[0]+=1
c = broadcasted.value[0]
#broadcasted = sc.broadcast([c,d]) # WE CANNOT DO BROADCAST ON DRIVERS
return(c,l)
flag2 = 0
d = 0
def abc2(l): # BroadCast d
#global d
if broadcastedflag.value[1] == 0:
d = broadcasted.value[1]
d+=1
broadcastedflag.value[1]+=1
else:
broadcasted.value[1]+=1
d=broadcasted.value[1]
return(l,d)
broadcasted = sc.broadcast([c,d])
broadcastedflag = sc.broadcast([flag1,flag2])
CusDF = df.rdd.map(lambda l: abc(l[0])).toDF(["Key","Value"])
PrmDF = df.rdd.map(lambda l: abc2(l[12])).toDF(["Key","Value"])
#CusDF.limit(100).show()
#PrmDF.limit(100).show()
#JDF = CusDF.join(PrmDF,CusDF.Key == PrmDF.Key)
#JDF.show()
#print "OOOOOOOOOOOOOOOOMMMMMMMMMMMMMMMMMMMMMGGGGGGGGGGGGGGGGGGGGG"
'''
broadcastedPrmDF = sc.broadcast(PrmDF.rdd.collectAsMap())
rowFunc = lambda x: (x[0], x[1], broadcastedPrmDF.value.get(x[1], -1))
def mapFunc(partition):
for row in partition:
yield rowFunc(row)
JoinCusDFPrmDF = CusDF.rdd.mapPartitions(mapFunc,preservesPartitioning=True)
print JoinCusDFPrmDF.take(5)
'''
'''
foreach(func) Run a function func on each element of the dataset. This is usually done for side effects such as updating an Accumulator or interacting with external storage systems.
Note: modifying variables other than Accumulators outside of the foreach() may result in undefined behavior. See Understanding closures for more details.
'''
a = sc.accumulator(1)
def f(x):
global a
a += float(x["Customer Lifetime Value"])
print(x["Customer Lifetime Value"])
df.rdd.foreach(f)
print a.value
b = sc.accumulator(0)
def g(x):
b.add(x["Customer Lifetime Value"])
df.rdd.foreach(g)
print b.value
'''
>>> from pyspark.accumulators import AccumulatorParam
>>> class VectorAccumulatorParam(AccumulatorParam):
... def zero(self, value):
... return [0.0] * len(value)
... def addInPlace(self, val1, val2):
... for i in xrange(len(val1)):
... val1[i] += val2[i]
... return val1
>>> va = sc.accumulator([1.0, 2.0, 3.0], VectorAccumulatorParam())
>>> va.value
[1.0, 2.0, 3.0]
>>> def g(x):
... global va
... va += [x] * 3
>>> rdd.foreach(g)
>>> va.value
[7.0, 8.0, 9.0]
>>> rdd.map(lambda x: a.value).collect() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Py4JJavaError:...
>>> def h(x):
... global a
... a.value = 7
>>> rdd.foreach(h) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Py4JJavaError:...
>>> sc.accumulator([1.0, 2.0, 3.0]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Exception:...
'''
<file_sep>def lkup(df,arg,ke):
df1=df.select(arg).collect()
for k in df1:
if k[arg]==ke:
return True
else:
return False<file_sep>def funsub(df,i,j):
try:
x1=int(df[i])
except ValueError:
x1=0
try:
x2=int(df[j])
except ValueError:
x2=0
if x2>x1:
x2,x1=x1,x2
x=x1-x2
return x
def sub(df,arg1,arg2):
df1=df.fillna(0)
df1=df1.fillna('')
df1=df1.rdd
df1=df1.map(lambda x:funsub(x,arg1,arg2))
return df1<file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import * # Imports all data Types
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
from pyspark.sql.functions import udf
from pyspark.sql import Window
conf = SparkConf().setMaster("local").setAppName("Aggregate Module")
sc = SparkContext(conf = conf) # Initalising or Configuring "Spark Context"
sqlContext = SQLContext(sc)
#############################################################################################################################################
# Columns :- OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName
#############################################################################################################################################
################################################################################################################################################
def convert(date_string):
date_new = date_string.split(" ")[0]
date_object = date(*map(int,(date_string.split(" ")[0].split("-"))))
return date_object
def dataFrame_Maker(*args):
File = args[0]
OrdersFile = sc.textFile(File)
header = OrdersFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
fields = [StructField(field_name, StringType(), False) for field_name in schemaString.split(',')]
fields[0].dataType = LongType()
fields[2].dataType = IntegerType()
fields[3].dataType = DateType()
fields[4].dataType = DateType()
fields[5].dataType = DateType()
fields[6].dataType = IntegerType()
fields[7].dataType = FloatType()
schema = StructType(fields)
OrdersHeader = OrdersFile.filter(lambda l: "OrderID" in l)
OrdersNoHeader = OrdersFile.subtract(OrdersHeader)
Orders_temp = OrdersNoHeader.map(lambda k: k.split(",")).map(lambda p:(int(p[0]),str(p[1].encode("utf-8")),int(p[2]),convert(p[3]),convert(p[4]),convert(p[5]),int(p[6]),float(p[7]),str(p[8].encode("utf-8"))))
Orders_df = sqlContext.createDataFrame(Orders_temp, schema)
return Orders_df
if __name__ == "__main__":
inputer = sys.argv[1]
spark = SparkSession.builder.master("local").appName("Aki-Karthi App").config("spark.some.config.option", "some-value").getOrCreate()
df = spark.read.csv(inputer,header=True,inferSchema=True)
#(schema=None, sep=None, encoding=None, quote=None, escape=None, comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None, ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None, negativeInf=None, dateFormat=None, maxColumns=None, maxCharsPerColumn=None, maxMalformedLogPerPartition=None, mode=None)
df.show()
#print(df.schema)
print df.printSchema()
#df0 = dataFrame_Maker(inputer)
'''
print "\n\n"
customers = sc.parallelize([("Alice", "2016-05-01", 50.00),("Alice", "2016-05-03", 45.00),("Alice", "2016-05-04", 55.00),("Bob", "2016-05-01", 25.00),("Bob", "2016-05-04", 29.00),("Bob", "2016-05-06", 27.00)]).toDF(["Name", "Date", "AmountSpent"])
print customers.show()
print "\n\n"
#wSpec1 = Window.partitionBy("Name").orderBy("Date").rowsBetween(-1, 1)
# customers.withColumn("MovingAvg",func.avg(customers("AmountSpent")).over(wSpec1)).show()
#customers.withColumn("MovingAvg",customers.filter(customers("AmountSpent") > 30)).show()
#customers.filter("AmountSpent > 30").show()
a = "AmountSpent"
b = '>'
c = str(30)
x = a+b+c
#customers.filter("AmountSpent > 30").show()
print a
customers.filter(x).show()
'''
<file_sep>def currentdt():
import datetime
now=datetime.datetime.now()
return now<file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
conf = SparkConf().setMaster("local").setAppName("Task 1")
sc = SparkContext(conf = conf)
sqlContext = SQLContext(sc)
################################################ D1_AutoInsurance.csv ###################################################
print("\n\n************************************* D1_AutoInsurance.csv ********************************************\n\n")
'''
Customer State Customer Lifetime Value Response Coverage Education Effective To Date EmploymentStatus Gender Income Location Code Marital Status Monthly Premium Auto Months Since Last Claim Months Since Policy Inception Number of Open Complaints Number of Policies Policy Type Policy Renew Offer Type Sales Channel Total Claim Amount Vehicle Class Vehicle Size
'''
filey = sc.textFile("/root/Desktop/D1_AutoInsurance.csv")
rdd = filey.map(lambda line: line.split(","))
print rdd.count()
for row in rdd.take(rdd.count()): print(row[1])
#Map(func)
Map_rdd = rdd.map(lambda x: [x[0],x[1],x[2]])
#print Map_rdd.collect()[:10]
print "\n\n"
#Filter(func)
print "Filter :"
print "\n\n"
Filter_rdd = rdd.filter(lambda x: [x[12] > 85])
#print Filter_rdd.collect()[:10]
print "\n\n"
#flatMap(func)
flatMap_rdd = rdd.flatMap(lambda x: [x[0],x[1],x[2]])
#print flatMap_rdd.collect()[:10]
print "\n\n"
#sample(withReplacement, fraction, seed)
sampleRdd = rdd.sample(True,0.5,3)
#print sampleRdd.collect()[:10]
print "\n\n"
#union(otherDataset)
A = rdd.map(lambda x: [x[0],x[1],x[2]])
B = rdd.map(lambda x: [x[3],x[4],x[5]])
AUB = A.union(B)
#print AUB.take(10)
#print AUB.collect()
print "\n\n"
#Intersection(otherDataset)
C = rdd.map(lambda x: [x[0],x[1],x[2]])
D = rdd.map(lambda x: [x[0],x[1],x[2]])
CVD = C.intersection(D)
print CVD
print "\n\n"
#Distinct([numTasks]))
CountRDD = rdd.count()
#print CountRDD
print "\n\n"
DistinctRDD = rdd.distinct()
#print DistinctRDD
print "\n\n"
Keys = rdd.map(lambda x: (x[0],[x[1],x[2]]))
#print Keys.collect()
print "\n\n"
KeysVal = rdd.map(lambda x: (x[1],[x[0],x[2]]))
#print KeysVal.collect()
print "\n\n"
#groupByKey([numTasks])
KeysGroupBy = KeysVal.groupByKey()
#print KeysGroupBy.collect()[:10]
print "\n\n"
KeysMap = KeysGroupBy.map(lambda x : {x[0]: list(x[1])}).collect()
#print KeysMap[:10]
print "\n\n"
header = rdd.first() #extract header
rddN = rdd.filter(lambda row : row != header) #filter out header
#print rdd.collect()[:10]
ReduceKeyRDD = rddN.map(lambda n: (str(n[1]), float(n[2]))).reduceByKey(lambda v1,v2: v1 + v2).collect()
#print ReduceKeyRDD
print "\n\n"
sortByKeyRDD = rddN.map(lambda n: (str(n[1]), float(n[2]))).sortByKey(False).collect()
#print sortByKeyRDD
print "\n\n"
names1 = rddN.map(lambda a: (a[0], 1))
names2 = rddN.map(lambda a: (a[1], 1))
JoinRDD = names1.join(names2).collect()
#print JoinRDD
print "\n\n"
LeftJoin = names1.leftOuterJoin(names2).collect()
#print LeftJoin
print "\n\n"
#pipeRDD = rdd.pipe(rddN)
#print pipeRDD.collect()
print "\n\n"
print "#########################################################################"
print "\n\n"
x = rddN.map(lambda l:(str(l[0]), 1))
y = rddN.map(lambda l:(str(l[0]), 2))
SXY = sorted(x.cogroup(y).collect())
#print SXY
CountNames = names1.countByKey()
#print CountNames
print "\n\n"
Ex = names1.repartition(3)
#print Ex.getNumPartitions()
####################################################################################
#aggregateByKey(zeroValue)(seqOp, combOp, [numTasks])
#AggregateRDD = rddN.aggregateByKey([],\
(lambda x, y: (x[0]+y[0],x[1]+1)),\
(lambda rdd1, rdd2: (rdd1[0]+rdd2[0], rdd1[1]+rdd2[1])))
#print AggregateRDD.collect()
#print "\n\n"
###################################################################################
<file_sep>def datediff(df,arg):
from time import gmtime, strftime
strftime("%Y-%m-%d", gmtime())
df=df.select(arg)
<file_sep>def uniall(df1,df2):
df3=df1.union(df2)
return df3<file_sep># -*- coding: utf-8 -*-
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
conf = SparkConf().setMaster("local").setAppName("Task 1")
sc = SparkContext(conf = conf)
sqlContext = SQLContext(sc)
################################################ D1_AutoInsurance.csv ###################################################
print("\n\n************************************* D1_AutoInsurance.csv ********************************************\n\n")
'''
Customer State Customer Lifetime Value Response Coverage Education Effective To Date EmploymentStatus Gender Income Location Code Marital Status Monthly Premium Auto Months Since Last Claim Months Since Policy Inception Number of Open Complaints Number of Policies Policy Type Policy Renew Offer Type Sales Channel Total Claim Amount Vehicle Class Vehicle Size
'''
filey = sc.textFile("/root/Desktop/D1_AutoInsurance.csv")
rdd = filey.map(lambda line: line.split(","))
print rdd.count()
header = rdd.first() #extract header
rddN = rdd.filter(lambda row : row != header) #filter out header
Map_rdd = rdd.map(lambda x: [x[0],x[1],x[2]])
print Map_rdd.collect()[:10]
print "\n\n"
c = 0
def abc(l): # BroadCast c
global c
c+=1
return(c,l)
DfMap = Map_rdd.map(lambda l: abc(l))
print DfMap.collect()[:10]
print "\n\n"
DfEnuMap = Map_rdd.map(lambda l: list(enumerate(l)))
print DfEnuMap.collect()
print "\n\n"
Map_rddN = rdd.map(lambda x: [[x[0],x[1],x[2]]])
#DfEnuMapL = Map_rddN.map(lambda l: enumerate(l))
#print DfEnuMapL.collect()
#print "\n\n"
#PrintDfEnuMap = DfEnuMap.map(lambda l : l[0]).collect()
#print PrintDfEnuMap
'''
DfEnuMapP = Map_rdd.map(lambda l: print(l))
print DfEnuMapP
print "\n\n"
'''
<file_sep>def substring(df,sub,*args):
df1=df.na.fill(0)
df1=df1.na.fill('')
count=0
for arg in args:
df1=df1.select(arg).collect()
for k in df1:
x=str(k[arg]).find(sub)
if x>-1:
count+=1
return count<file_sep># -*- coding: utf-8 -*-
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import HiveContext
from pyspark.sql import GroupedData
from pyspark.sql import DataFrameNaFunctions
from pyspark.sql import DataFrameStatFunctions
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql import Window
from pyspark.sql import SparkSession
conf = SparkConf().setMaster("local").setAppName("My App")
sc = SparkContext(conf = conf) #Initalising or Configuring "Spark Context"
sqlContext = SQLContext(sc)
##################################################### RDD Transformations on Data Sets #########################################################
'''
Data Set looks like This:
Year First Name County Sex Count
2012 DOMINIC CAYUGA M 6
2012 ADDISON ONONDAGA F 14
2012 ADDISON ONONDAGA F 14
2012 JULIA ONONDAGA F 15
'''
# 1.MAP()
baby_names = sc.textFile("/home/akhil/Desktop/baby_names.csv")
rows = baby_names.map(lambda line: line.split(","))
#Prints Names
for row in rows.take(rows.count()):
print(row[1])
# 2.flatMap(func)
'''
#“Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).”
#flatMap is helpful with nested datasets. It may be beneficial to think of the RDD source as hierarchical JSON (which may have been converted to #case classes or nested collections). This is unlike CSV which has no hierarchical structural.
Eg:
Spark flatMap Example Using Python
# Bazic map example in python
x = sc.parallelize(["spark rdd example", "sample example"], 2)
# map operation will return Array of Arrays in following case (check the result)
y = x.map(lambda x: x.split(' '))
y.collect()
[['spark', 'rdd', 'example'], ['sample', 'example']]
# flatMap operation will return Array of words in following case (check the result)
y = x.flatMap(lambda x: x.split(' '))
y.collect()
['spark', 'rdd', 'example', 'sample', 'example']
sc.parallelize([2, 3, 4]).flatMap(lambda x: [x,x,x]).collect()
[2, 2, 2, 3, 3, 3, 4, 4, 4]
sc.parallelize([1,2,3]).map(lambda x: [x,x,x]).collect()
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
'''
# 3.filter() ==> SELECT Names from Table where Table['Names'] == "MICHAEL"
a = rows.filter(lambda line: "MICHAEL" in line).collect()
print a
# 4.mapPartitions(func, preservesPartitioning=False)
'''
Consider mapPartitions a tool for performance optimization if you have the resources available. It won’t do much when running examples on your laptop. It’s the same as “map”, but works with Spark RDD partitions which are distributed. Remember the first D in RDD – Resilient Distributed Datasets.
In examples below that when using parallelize, elements of the collection are copied to form a distributed dataset that can be operated on in parallel.
A distributed dataset can be operated on in parallel.
One important parameter for parallel collections is the number of partitions to cut the dataset into. Spark will run one task for each partition of the cluster.
'''
'''
one_through_9 = range(1,10)
parallel = sc.parallelize(one_through_9, 3)
def f(iterator): yield sum(iterator)
parallel.mapPartitions(f).collect()
[6, 15, 24]
parallel = sc.parallelize(one_through_9)
parallel.mapPartitions(f).collect()
[1, 2, 3, 4, 5, 6, 7, 17]
Results [6,15,24] are created because mapPartitions loops through 3 partitions which is the second argument to the sc.parallelize call.
Partion 1: 1+2+3 = 6
Partition 2: 4+5+6 = 15
Partition 3: 7+8+9 = 24
The second example produces [1,2,3,4,5,6,7,17] which I’m guessing means the default number of partitions on my laptop is 8.
Partion 1 = 1
Partition 2= 2
Partion 3 = 3
Partition 4 = 4
Partion 5 = 5
Partition 6 = 6
Partion 7 = 7
Partition 8: 8+9 = 17
Typically you want 2-4 partitions for each CPU core in your cluster. Normally, Spark tries to set the number of partitions automatically based on your cluster or hardware based on standalone environment.
To find the default number of partitions and confirm the guess of 8 above:
print sc.defaultParallelism
'''
# 5.mapPartitionsWithIndex(func)
parallel = sc.parallelize(one_through_nine,3)
def show(index, iterator):
yield 'index: '+str(index)+" values: "+ str(list(iterator))
parallel.mapPartitionsWithIndex(show).collect()
'''
['index: 0 values: [1, 2, 3]',
'index: 1 values: [4, 5, 6]',
'index: 2 values: [7, 8, 9]']
'''
'''
When learning these APIs on an individual laptop or desktop, it might be helpful to show differences in capabilities and outputs. For example, if we change the above example to use a parallelize’d list with 3 slices, our output changes significantly As Above.
'''
# 6.distinct([numTasks])
#Another simple one. Return a new RDD with distinct elements within a source RDD
parallel = sc.parallelize(range(1,9))
par2 = sc.parallelize(range(5,15))
parallel.union(par2).distinct().collect()
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
######################################################## The Keys ##############################################################################
#The group of transformation functions (groupByKey, reduceByKey, aggregateByKey, sortByKey, join) all act on key,value pair RDDs.
baby_names = sc.textFile("baby_names.csv")
rows = baby_names.map(lambda line: line.split(","))
# 7.groupByKey([numTasks]) ===> GROUPBY in SQL
#“When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable<V>) pairs. ”
#The following groups all names to counties in which they appear over the years.
rows = baby_names.map(lambda line: line.split(","))
namesToCounties = rows.map(lambda n: (str(n[1]),str(n[2]) )).groupByKey()
namesToCounties.map(lambda x : {x[0]: list(x[1])}).collect()
'''
[{'GRIFFIN': ['ERIE',
'ONONDAGA',
'NEW YORK',
'ERIE',
'SUFFOLK',
'MONROE',
'NEW YORK',
...
'''
#8. reduceByKey(func, [numTasks]) ==> GroupBY AND SUM()
Operates on key, value pairs again, but the func must be of type (V,V) => V
Let’s sum the yearly name counts over the years in the CSV. Notice we need to filter out the header row. Also notice we are going to use the “Count” column value (n[4])
filtered_rows = baby_names.filter(lambda line: "Count" not in line).map(lambda line: line.split(","))
filtered_rows.map(lambda n: (str(n[1]), int(n[4]) ) ).reduceByKey(lambda v1,v2: v1 + v2).collect()
'''
[('GRIFFIN', 268),
('KALEB', 172),
('JOHNNY', 219),
('SAGE', 5),
('MIKE', 40),
('NAYELI', 44),
....
'''
reduceByKey(func: (V, V) ⇒ V): RDD[(K, V)]
#9. aggregateByKey(zeroValue)(seqOp, combOp, [numTasks])
Ok, I admit, this one drives me a bit nuts. Why wouldn’t we just use reduceByKey? I don’t feel smart enough to know when to use aggregateByKey over reduceByKey. For example, the same results may be produced as reduceByKey:
filtered_rows = baby_names.filter(lambda line: "Count" not in line).map(lambda line: line.split(","))
filtered_rows.map(lambda n: (str(n[1]), int(n[4]) ) ).aggregateByKey(0, lambda k,v: int(v)+k, lambda v,k: k+v).collect()
'''
[('GRIFFIN', 268),
('KALEB', 172),
('JOHNNY', 219),
('SAGE', 5),
...
'''
#10. sortByKey(ascending=True, numPartitions=None, keyfunc=<function <lambda>>) ==> GROUPBY AND ORDERBY INC/DEC
This simply sorts the (K,V) pair by K.
filtered_rows.map (lambda n: (str(n[1]), int(n[4]) ) ).sortByKey().collect()
'''
[('AADEN', 18),
('AADEN', 11),
('AADEN', 10),
('AALIYAH', 50),
('AALIYAH', 44),
...
'''
#opposite
filtered_rows.map (lambda n: (str(n[1]), int(n[4]) ) ).sortByKey(False).collect()
'''
[('ZOIE', 5),
('ZOEY', 37),
('ZOEY', 32),
('ZOEY', 30),
'''
############################################################### JOIN ###########################################################################
join(otherDataset, [numTasks])
If you have relational database experience, this will be easy. It’s joining of two datasets. Other joins are available as well such as leftOuterJoin and rightOuterJoin.
names1 = sc.parallelize(("abe", "abby", "apple")).map(lambda a: (a, 1))
names2 = sc.parallelize(("apple", "beatty", "beatrice")).map(lambda a: (a, 1))
names1.join(names2).collect()
[('apple', (1, 1))]
names1.leftOuterJoin(names2).collect()
[('abe', (1, None)), ('apple', (1, 1)), ('abby', (1, None))]
names1.rightOuterJoin(names2).collect()
[('apple', (1, 1)), ('beatrice', (None, 1)), ('beatty', (None, 1))]
#$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$#
#Source link: https://www.supergloo.com/fieldnotes/apache-spark-transformations-python-examples/
#https://github.com/tmcgrath/spark-with-python-course/blob/master/Spark-Transformers-With-Spark.ipynb
#$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$#
##################################################### Testing TimeStamp DataType() #####################################################
##################################################### Working with orders.csv #####################################################
print("\n\n****************************************** Working with orders.csv ***********************************************\n\n")
'''
#OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName ShipAddress #ShipCity ShipRegion ShipPostalCode ShipCountry
'''
# Imports all data Types
from pyspark.sql.types import *
OrdersFile = sc.textFile("/home/akhil/Desktop/3 Day Task/data/orders.csv")
header = OrdersFile.first()
schemaString = header.replace('"','') # get rid of the double-quotes
#By Default We Set as StringType()
fields = [StructField(field_name, StringType(), False) for field_name in schemaString.split(',')]
print(fields)
print(len(fields) ) # how many elements in the header?
fields[0].dataType = LongType()
fields[2].dataType = IntegerType()
fields[3].dataType = DateType()
fields[4].dataType = DateType()
fields[6].dataType = IntegerType()
fields[7].dataType = FloatType()
print("\n\n")
print(fields)
print("\n\n")
# We can get rid of any annoying leading underscores or change name of field by
# Eg: fields[0].name = 'id'
schema = StructType(fields)
print(schema)
print("\n\n")
OrdersHeader = OrdersFile.filter(lambda l: "OrderID" in l)
print(OrdersHeader.collect())
print("\n\n")
OrdersNoHeader = OrdersFile.subtract(OrdersHeader)
print(OrdersNoHeader.count())
print("\n\n")
from datetime import date, datetime
def convert(date_string):
date_new = date_string.split(" ")[0]
date_object = date(*map(int,(date_string.split(" ")[0].split("-"))))
#assert date_object == datetime.strptime(date_new, "%Y/%m/%d").date()
return date_object
#Remove Nullable = "False" Here
Orders_temp = OrdersNoHeader.map(lambda k: k.split(",")).map(lambda p:(int(p[0]),str(p[1].encode("utf-8")),int(p[2]),convert(p[3]),convert(p[4]),p[5],int(p[6]),float(p[7]), p[8],p[9],p[10],p[11],p[12],p[13]))
print(Orders_temp.top(2))
print("\n\n")
Orders_df = sqlContext.createDataFrame(Orders_temp, schema)
print("\n Dtypes : ",Orders_df.dtypes)
print("\n\n")
print("\n Schema: ",Orders_df.printSchema())
print("\n\n")
print("\n\n ******************************************** OK WELL ************************************* \n\n")
from pyspark.sql.types import *
from pyspark.sql.functions import *
cached = Orders_df.persist()
# OR USE cacheTable() from SparkContext
#............. Issue or Error Here. .....!!
#x = cached.count()
print "\n\n"
col = cached.columns
print("\n\n ******************************************** OK WELL NOW ************************************* \n\n")
print col
print "\n\n"
print cached.printSchema()
#Registering Table
Orders_df.registerTempTable("Orders")
####################################################### Manually create DataFrames (Fact Table) ################################################
print("\n\n****************************************** Working with Fact Table ***********************************************\n\n")
FactSchema = StructType([
StructField('ProductID',IntegerType(),nullable=False),StructField('EmployeeID',LongType(),nullable=False),StructField('CustomerID',StringType(),nullable=False),StructField('OrderDate',StringType(),nullable=False),StructField('ShipDate',StringType(),nullable=False),StructField('UnitPrice',FloatType(),nullable=False),StructField('Quantity',StringType(),nullable=False),StructField('Discount',FloatType(),nullable=False),StructField('ExtendedPrice',DoubleType(),nullable=False)])
FactData = sc.parallelize([
Row(1,1080,'ASDEF','1996-07-04 00:00:00.000','1996-07-04 00:00:00.000',34.56,'13 Books',3.56,89.56) ])
FactDF = sqlContext.createDataFrame(FactData,FactSchema)
print FactDF.printSchema()
################################################################# withColumn() #################################################################
'''
DataFrame provides a convenient method of form DataFrame.withColumn([string] columnName, [udf] userDefinedFunction) to append column to an existing DataFrame. Here the userDefinedFunction is of type pyspark.sql.functions.udf which is of the form udf(userMethod, returnType). The userMethod is the actual python method the user application implements and the returnType has to be one of the types defined in pyspark.sql.types, the user method can return. Here is an example python notebook that creates a DataFrame of rectangles.
'''
import pyspark
from pyspark import SparkConf
from pyspark import SparkContext
from pyspark.sql import HiveContext
from pyspark.sql.types import *
from pyspark.sql.functions import udf
sparkContext = SparkContext(conf = SparkConf())
hiveContext = HiveContext(sparkContext)
rectangleList = [('RectangleA',10,20,30),('RectangleB',40,50,60),('RectangleC',70,80,90)]
rectangleDataFrame = hiveContext.createDataFrame(rectangleList,['RectangleName','Height','Width','DegreeofRotation'])
'''
Let us suppose that the application needs to add the length of the diagonals of the rectangle as a new column in the DataFrame. Since the length of the diagonal can be represented as a float DataFrame.withColumn can be used with returnType as FloatType.
'''
#User defined function for calculating Diagnaol
from math import *
def calculateDiag(ht,wdt):
return sqrt(ht*ht + wdt*wdt)
#Define UDF for calculating the length of the diagonal
diagonalCalculator = udf(calculateDiag,FloatType())
#Append th length of the diagonal as a new column to the original data frame
rectangleDataFrame = rectangleDataFrame.withColumn("Diagonal",diagonalCalculator(rectangleDataFrame['Height'],rectangleDataFrame['Width']))
print rectangleDataFrame.take(1)
#Advanced Way : https://blogs.msdn.microsoft.com/azuredatalake/2016/02/10/pyspark-appending-columns-to-dataframe-when-dataframe-withcolumn-cannot-be-used/
#################################################################################################################################################
############################################## SQL To Equavalent Transforms on DF #####################################################
##################################################### Quaring DataFrames ##########################################################
'''
#OrderID CustomerID EmployeeID OrderDate RequiredDate ShippedDate ShipVia Freight ShipName ShipAddress #ShipCity ShipRegion ShipPostalCode ShipCountry
# Use Orders_df DataFrame
'''
print("\n\n ******************************************************* SQL - SELECT ******************************************************** \n\n")
#1 . SQL - SELECT
#select (only one column)
xyz = Orders_df.select('OrderID').take(2)
print xyz
#first
frst = Orders_df.first()
print frst
#selecting multiple columns
selected = Orders_df.select('OrderID','CustomerID','OrderDate')
selected.show()
#2 . SQL - SELECT BY NAME AND GROUPBY
#############################
#filter - WHERE Equavelent
#############################
#shipnames = Orders_df.filter(functions.col('OrderID') == 3) # Returns None
#shipnames = Orders_df.filter(functions.col('EmployeeID') == '5')
#UnicodeEncodeError: 'ascii' codec can't encode character u'\xfa' in position 906: ordinal not in range(128)
#shipnames.show()
#Alias
Orders_df.select(functions.col('OrderDate').alias('Date')).show()
#######################
#grouping/counting
#######################
#val = Orders_df.filter(functions.col('OrderDate') == 1997-07-07).groupBy('CustomerID').count() #
#val = Orders_df.filter(functions.col('OrderDate') == datetime.date(1996, 7, 9)).groupBy('CustomerID').count()
#TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
#print val
######################
#where
######################
#ex_df = parquet.where(functions.col('CustomerID') > 4 ).toPandas()
#print ex_df
############## User Defined Functions with DataFrames ###########
# We use UDF() from functions.udf()
#Use link : http://blog.brakmic.com/data-science-for-losers-part-5-spark-dataframes/
#UDFs are not unique to SparkSQL. You can also define them as named functions and insert them into a chain of operators without using SQL. The contrived example below shows how we would define and use a UDF directly in the code.
#Eg:
'''
from pyspark.sql.types import StringType
from pyspark.sql.functions import udf
# Define the UDF
def uppercase(string):
return string.upper()
udf_uppercase = udf(uppercase, StringType())
# Convert a whole column to uppercase with a UDF.
newDF = oldDF.withColumn("name_upper", udf_uppercase("name"))
'''
################################################################################################################################################
The eBay online auction dataset has the following data fields:
@ auctionid - unique identifier of an auction
@ bid - the proxy bid placed by a bidder
@ bidtime - the time (in days) that the bid was placed, from the start of the auction
@ bidder - eBay username of the bidder
@ bidderrate - eBay feedback rating of the bidder
@ openbid - the opening bid set by the seller
@ price - the closing price that the item sold for (equivalent to the second highest bid + an increment)
Using Spark DataFrames we will explore the data with questions like:
> How many auctions were held?
> How many bids were made per item?
> What's the minimum, maximum, and average number of bids per item?
> Show the bids with price > 100
Using Spark DataFrames, we will explore the SFPD data with questions like:
> What are the top 10 Resolutions?
> How many Categories are there?
> What are the top 10 incident Categories?
#How many auctions were held?
auction.select("auctionid").distinct.count
#Long = 627
#How many bids per item?
auction.groupBy("auctionid", "item").count.show
#**********************************************************************************************************************************************#
auctionid item count
3016429446 palm 10
8211851222 xbox 28
3014480955 palm 12
8214279576 xbox 4
3014844871 palm 18
3014012355 palm 35
1641457876 cartier 2
#**********************************************************************************************************************************************#
#What's the min number of bids per item? what's the average? what's the max?
auction.groupBy("item", "auctionid").count.agg(min("count"), avg("count"),max("count")).show
# MIN(count) AVG(count) MAX(count)
# 1 16.992025518341308 75
# Get the auctions with closing price > 100
highprice= auction.filter("price > 100")
highprice: org.apache.spark.sql.DataFrame = [auctionid: string, bid: float, bidtime: float, bidder: // string, bidderrate: int, openbid: float, price: float, item: string, daystolive: int]
#display dataframe in a tabular format
highprice.show()
# auctionid bid bidtime bidder bidderrate openbid price item daystolive
# 8213034705 95.0 2.927373 jake7870 0 95.0 117.5 xbox 3
# 8213034705 115.0 2.943484 davidbresler2 1 95.0 117.5 xbox 3
#************************************************************************************************************************************************
#DataFrame DF :
'''
word tag count
0 a S 30
1 the S 20
2 a T 60
3 an T 5
4 the T 10
'''
#We want to find, for every "word", the "tag" that has the most "count". So the return would be something like
'''
Out:
word tag count
1 the S 20
2 a T 60
3 an T 5
'''
# 1 ( Not Working)
# DF.groupby(['word']).agg(lambda x: x['tag'][ x['count'].argmax() ] )
# agg is the same as aggregate. It's callable is passed the columns (Series objects) of the DataFrame, one at a time.
# 2 (Real Solution)
def f(x):
print type(x)
print x
df.groupby('word').apply(f)
'''
OUT :-
<class 'pandas.core.frame.DataFrame'>
word tag count
0 a S 30
2 a T 60
<class 'pandas.core.frame.DataFrame'>
word tag count
0 a S 30
2 a T 60
<class 'pandas.core.frame.DataFrame'>
word tag count
3 an T 5
<class 'pandas.core.frame.DataFrame'>
word tag count
1 the S 20
4 the T 10
'''
'''
your function just operates (in this case) on a sub-section of the frame with the grouped variable all having the same value (in this case 'word'), if you are passing a function, then you have to deal with the aggregation of potentially non-string columns; standard functions, like 'sum' do this for you.
Automatically does NOT aggregate on the string columns
'''
df.groupby('word').sum()
'''
word count
a 90
an 5
the 30
'''
#You ARE aggregating on all columns
df.groupby('word').apply(lambda x: x.sum())
'''
word tag count
word
a aa ST 90
an an T 5
the thethe ST 30
'''
# You can do pretty much anything within the function
df.groupby('word').apply(lambda x: x['count'].sum())
'''
word
a 90
an 5
the 30
'''
################################################################################################################################################
#Spark DataFrame groupBy and sort in the descending order (pyspark)
from pyspark.sql.functions import col
(group_by_dataframe
.count()
.filter("`count` >= 10")
.sort(col("count").desc()))
#How could I order by sum, within a DataFrame in PySpark?
order_items.groupBy("order_item_order_id").sum("order_item_subtotal").orderBy(desc("SUM(order_item_subtotal#429)")).show()
<file_sep>def isnotNull(df,*args):
for arg in args:
df=df.drop(arg)
return df<file_sep>def colrename(df,*args):
a=list(args)
for k in range(int(len(a)/2)):
r=int(len(a)/2)+k
df=df.withColumnRenamed(a[k], a[r])
return df<file_sep># -*- coding: utf-8 -*-
import numpy
#Python Imports
from operator import add
import sys
from datetime import date, datetime
from ast import literal_eval
#Spark Imports
from pyspark import SparkConf, SparkContext, sql
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from pyspark.sql import Column
from pyspark.sql import Row
from pyspark.sql import functions
from pyspark.sql import types
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import pyspark.sql.functions as func
conf = SparkConf().setMaster("local").setAppName("Task 1")
sc = SparkContext(conf = conf)
sqlContext = SQLContext(sc)
################################################ D1_AutoInsurance.csv ###################################################
print("\n\n************************************* D1_AutoInsurance.csv ********************************************\n\n")
'''
Customer State Customer Lifetime Value Response Coverage Education Effective To Date EmploymentStatus Gender Income Location Code Marital Status Monthly Premium Auto Months Since Last Claim Months Since Policy Inception Number of Open Complaints Number of Policies Policy Type Policy Renew Offer Type Sales Channel Total Claim Amount Vehicle Class Vehicle Size
'''
#RDD
'''
filey = sc.textFile("/root/Desktop/D1_AutoInsurance.csv")
rdd = filey.map(lambda line: line.split(","))
print rdd.count()
header = rdd.first() #extract header
rddN = rdd.filter(lambda row : row != header) #filter out header
Map_rdd = rddN.map(lambda x: [x[0],x[1],x[2]])
print Map_rdd.collect()[:10]
print "\n\n"
KeyValueRDD = rddN.map(lambda n: (str(n[1]), float(n[2])))
'''
#DF
filey = "/root/Desktop/D1_AutoInsurance.csv"
spark = SparkSession.builder.master("local").appName("Task 4 App").config("spark.some.config.option", "some-value").getOrCreate()
df = spark.read.csv(filey,header=True,inferSchema=True)
df.show()
print df.printSchema()
dfN = df.select(df[12])
dfN.show()
#dfN = dfN.collect()
from pyspark.mllib.feature import Normalizer
from pyspark.mllib.linalg import Vectors
print dfN
print"\n\n"
col = dfN.rdd.map(lambda l : l[0]).collect()
col = col[:-1]
v = Vectors.dense(col)
nor = Normalizer(1)
print nor.transform(v)
#spark-convert-data-frame-column-to-vectors-dense
from pyspark.sql.functions import col, stddev_samp
df.withColumn("scaled",
col("Customer Lifetime Value") / df.agg(stddev_samp("Customer Lifetime Value")).first()[0])
#df.show()
| 74521d1cd42a233694634ebd368d09715b2384c6 | [
"Python"
] | 47 | Python | AkhilReddy/MySparkWork | 556089f7ecb23febd67348a7ccc6f1abd018ccc9 | c82f587cce81e6814de324c01f4d9c5a5fc087ce |
refs/heads/master | <file_sep>import SeacrhIcon from "@material-ui/icons/Search";
import DescriptionIcon from "@material-ui/icons/Description";
import PlayCircleFilledIcon from "@material-ui/icons/PlayCircleFilled";
import ThumbsUpDownIcon from "@material-ui/icons/ThumbsUpDown";
import SettingsIcon from "@material-ui/icons/Settings";
import CheckCircleIcon from "@material-ui/icons/CheckCircle";
import CardorListViews from "../../assets/images/GetStarted/BrowsingTheMarketplace/CardorListViews.png";
import ChangeFilterOptions from "../../assets/images/GetStarted/BrowsingTheMarketplace/ChangeFilterOptions.png";
import SortOptions from "../../assets/images/GetStarted/BrowsingTheMarketplace/SortOptions.png";
import RatingandRanking from "../../assets/images/GetStarted/BrowsingTheMarketplace/RatingandRanking.png";
import Search from "../../assets/images/GetStarted/BrowsingTheMarketplace/Search.png";
import AboutDetails from "../../assets/images/GetStarted/ChooseingYourAi/AboutDetails.png";
import Pricing from "../../assets/images/GetStarted/ChooseingYourAi/Pricing.png";
import DemoTrial from "../../assets/images/GetStarted/ChooseingYourAi/DemoTrial.png";
import InstallRun from "../../assets/images/GetStarted/ChooseingYourAi/Install&Run.png";
import Tutorials from "../../assets/images/GetStarted/ChooseingYourAi/Tutorials.png";
import AccessingtheDemo from "../../assets/images/GetStarted/DemoAiServices/AccessingtheDemo.png";
import ConfigureAIParameters from "../../assets/images/GetStarted/DemoAiServices/ConfigureAIParameters.png";
import Metamask from "../../assets/images/GetStarted/DemoAiServices/Metamask.png";
import Seeoutputresults from "../../assets/images/GetStarted/DemoAiServices/Seeoutputresults.png";
import RatingAIServices from "../../assets/images/GetStarted/RateReviewImprove/RatingAIServices.png";
import AccessingSortingrReviews from "../../assets/images/GetStarted/RateReviewImprove/AccessingSortingrReviews.png";
import WritingReview from "../../assets/images/GetStarted/RateReviewImprove/WritingReview.png";
import Install from "../../assets/images/GetStarted/MakeItYourAI/Install.png";
import Run from "../../assets/images/GetStarted/MakeItYourAI/Run.png";
import MultipleChannels from "../../assets/images/GetStarted/MakeItYourAI/MultipleChannels.png";
import Documentation from "../../assets/images/GetStarted/MakeItYourAI/Documentation.png";
import ManagingyourAGItokens from "../../assets/images/GetStarted/UsingAgi/ManagingyourAGItokens.png";
import Metamaskwalletsupport from "../../assets/images/GetStarted/UsingAgi/Metamaskwalletsupport.png";
import Usingchannelbalances from "../../assets/images/GetStarted/UsingAgi/Usingchannelbalances.png";
export const GetStartedCategoriesData = [
{
categoryIcon: SeacrhIcon,
categoryTitle: "Browsing the marketplace",
categoryDescription:
"Exploring AI - The SingularityNET AI Marketplace hosts a wide variety of AI services that range from Text generation to Face detection. You can view all of them by default in “List view” as shown here but also search by category, rating, most recent and favourites.",
categoryTabs: [
{ title: "Card or List Views ", media: { type: "img", content: CardorListViews } },
{ title: "Change Filter Options", media: { type: "img", content: ChangeFilterOptions } },
{ title: "Sort Options", media: { type: "img", content: SortOptions } },
{ title: "Rating and Rankings", media: { type: "img", content: RatingandRanking } },
{ title: "Search", media: { type: "img", content: Search } },
],
},
{
categoryIcon: DescriptionIcon,
categoryTitle: "Choosing your AI",
categoryDescription:
"AI Services - Each AI service on this platform is unique. Click on any service you would like to use to find out more about its required input, expected output, cost, usage, developer’s note and much more!",
categoryTabs: [
{ title: "About Details", media: { type: "img", content: AboutDetails } },
{ title: "Pricing", media: { type: "img", content: Pricing } },
{ title: "Demo Trial", media: { type: "img", content: DemoTrial } },
{ title: "Install & Run", media: { type: "img", content: InstallRun } },
{ title: "Tutorials", media: { type: "img", content: Tutorials } },
],
},
{
categoryIcon: PlayCircleFilledIcon,
categoryTitle: "Demo AI Services",
categoryDescription:
"Try it out yourself! – Majority of services have free demo calls that you can try right away. Input your parameters and data and let AI process your request instantly. After your trial demo calls used up, you can still run the demos using MetaMask via AGI tokens. ",
categoryTabs: [
{ title: "Accessing the demo", media: { type: "img", content: AccessingtheDemo } },
{ title: "Configure AI parameters", media: { type: "gif", content: ConfigureAIParameters } },
{ title: "See output results", media: { type: "gif", content: Seeoutputresults } },
{ title: "Metamask (coming soon)", media: { type: "gif", content: Metamask } },
],
},
{
categoryIcon: ThumbsUpDownIcon,
categoryTitle: "Rate, Review, Improve",
categoryDescription:
"Feedback - Democratizing AI requires collaboration, and not just between developers. Ratings and reviews help developers improve their algorithms as well as the design of their AI service. It’s also an opportunity for new teams to be born. ",
categoryTabs: [
{ title: "Rating AI Services", media: { type: "img", content: RatingAIServices } },
{ title: "Accessing & sorting reviews", media: { type: "img", content: AccessingSortingrReviews } },
{ title: "Writing review ", media: { type: "img", content: WritingReview } },
],
},
{
categoryIcon: SettingsIcon,
categoryTitle: "Make it your AI",
categoryDescription:
"Install & run it - It has never been easier to find and integrate AI algorithms. Regardless of your internal tech capabilities, you can now seamlessly integrate a service to your website, app or other product via the SingularityNET AI Marketplace. ",
categoryTabs: [
{ title: "Install", media: { type: "img", content: Install } },
{ title: "Run", media: { type: "img", content: Run } },
{ title: "Multiple languages", media: { type: "img", content: MultipleChannels } },
{ title: "documentation", media: { type: "img", content: Documentation } },
],
},
{
categoryIcon: SettingsIcon,
categoryTitle: "Using AGI",
categoryDescription:
"Own your funds - Whether you want to use services, delete your account or use your funds outside of the platform, you are the sole controller of your funds. Your wallet, your cryptographic key, your AGI. ",
categoryTabs: [
{ title: "Managing your AGI tokens", media: { type: "img", content: ManagingyourAGItokens } },
{ title: "Metamask wallet support", media: { type: "img", content: Metamaskwalletsupport } },
{ title: "Using channel balances", media: { type: "img", content: Usingchannelbalances } },
],
},
];
export const GetStartedFeaturesData = [
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "Access to the RFAI portal to request for a new AI service and incentivize development.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "Access to the RFAI portal to request for a new AI service and incentivize development.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "Access to the RFAI portal to request for a new AI service and incentivize development.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "Access to the RFAI portal to request for a new AI service and incentivize development.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "AI services dashboard.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "AI services dashboard.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "AI services dashboard.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "AI services dashboard.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "Transfer AGI Tokens from multiple wallet anytime.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "Transfer AGI Tokens from multiple wallet anytime.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "Transfer AGI Tokens from multiple wallet anytime.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Feature Name",
featureDescription: "Transfer AGI Tokens from multiple wallet anytime.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Integrate with any language",
featureDescription: "Integrate AI services using your preferred language such as Python, Java, C++, and many more.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Integrate with any language",
featureDescription: "Integrate AI services using your preferred language such as Python, Java, C++, and many more.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Integrate with any language",
featureDescription: "Integrate AI services using your preferred language such as Python, Java, C++, and many more.",
},
{
featureIcon: CheckCircleIcon,
featureName: "Integrate with any language",
featureDescription: "Integrate AI services using your preferred language such as Python, Java, C++, and many more.",
},
];
<file_sep>export const useStyles = theme => ({
GetStartedMainContaienr: {
padding: "30px 60px 60px",
backgroundColor: theme.palette.text.offWhiteColor,
flexDirection: "column",
},
TopSection: {
maxWidth: 800,
margin: "0 auto 30px",
textAlign: "center",
},
SignUpFree: {
maxWidth: "47%",
margin: "0 auto ",
textAlign: "center",
},
FeaturesMainContainer: { marginTop: 60 },
FreeTrialSignUp: {
marginTop: 16,
textAlign: "center",
"& > span": {
marginBottom: 16,
display: "block",
color: theme.palette.text.darkShadedGray,
fontSize: 14,
fontStyle: "italic",
lineHeight: "19px",
},
"& button": { padding: "13px 16% 11px" },
},
});
<file_sep>import React from "react";
import { withStyles } from "@material-ui/styles";
import Slider from "@material-ui/core/Slider";
import Grid from "@material-ui/core/Grid";
import OutlinedInput from "@material-ui/core/OutlinedInput";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";
import TextField from "@material-ui/core/TextField";
import InfoIcon from "@material-ui/icons/Info";
import Avatar from "@material-ui/core/Avatar";
import StyledButton from "../../../../components/common/StyledButton";
import BarackObama from "../../../images/ThirdPartyServices/snet/text_generation/BarackObama.jpg";
import BarackObamaAvatar from "../../../images/ThirdPartyServices/snet/text_generation/BarackObama_avatar.jpg";
import BernieSanders from "../../../images/ThirdPartyServices/snet/text_generation/BernieSanders.jpg";
import BernieSandersAvatar from "../../../images/ThirdPartyServices/snet/text_generation/BernieSanders_avatar.jpg";
import BethanyBrookshire from "../../../images/ThirdPartyServices/snet/text_generation/BethanyBrookshire.jpg";
import BethanyBrookshireAvatar from "../../../images/ThirdPartyServices/snet/text_generation/BethanyBrookshire_avatar.jpg";
import BillGates from "../../../images/ThirdPartyServices/snet/text_generation/BillGates.jpg";
import BillGatesAvatar from "../../../images/ThirdPartyServices/snet/text_generation/BillGates_avatar.jpg";
import BrianSwitek from "../../../images/ThirdPartyServices/snet/text_generation/BrianSwitek.jpg";
import BrianSwitekAvatar from "../../../images/ThirdPartyServices/snet/text_generation/BrianSwitek_avatar.jpg";
import ConanOBrien from "../../../images/ThirdPartyServices/snet/text_generation/ConanOBrien.jpg";
import ConanOBrienAvatar from "../../../images/ThirdPartyServices/snet/text_generation/ConanOBrien_avatar.jpg";
import DeborahBlum from "../../../images/ThirdPartyServices/snet/text_generation/DeborahBlum.jpg";
import DeborahBlumAvatar from "../../../images/ThirdPartyServices/snet/text_generation/DeborahBlum_avatar.jpg";
import DeepakChopra from "../../../images/ThirdPartyServices/snet/text_generation/DeepakChopra.jpg";
import DeepakChopraAvatar from "../../../images/ThirdPartyServices/snet/text_generation/DeepakChopra_avatar.jpg";
import DonaldTrump from "../../../images/ThirdPartyServices/snet/text_generation/DonaldTrump.jpg";
import DonaldTrumpAvatar from "../../../images/ThirdPartyServices/snet/text_generation/DonaldTrump_avatar.jpg";
import DwayneJohnson from "../../../images/ThirdPartyServices/snet/text_generation/DwayneJohnson.jpg";
import DwayneJohnsonAvatar from "../../../images/ThirdPartyServices/snet/text_generation/DwayneJohnson_avatar.jpg";
import EllenDeGeneres from "../../../images/ThirdPartyServices/snet/text_generation/EllenDeGeneres.jpg";
import EllenDeGeneresAvatar from "../../../images/ThirdPartyServices/snet/text_generation/EllenDeGeneres_avatar.jpg";
import ElonMusk from "../../../images/ThirdPartyServices/snet/text_generation/ElonMusk.jpg";
import ElonMuskAvatar from "../../../images/ThirdPartyServices/snet/text_generation/ElonMusk_avatar.jpg";
import EricWeinstein from "../../../images/ThirdPartyServices/snet/text_generation/EricWeinstein.png";
import EricWeinsteinAvatar from "../../../images/ThirdPartyServices/snet/text_generation/EricWeinstein_avatar.png";
import god from "../../../images/ThirdPartyServices/snet/text_generation/god.jpg";
import godAvatar from "../../../images/ThirdPartyServices/snet/text_generation/god_avatar.jpg";
import HillaryClinton from "../../../images/ThirdPartyServices/snet/text_generation/HillaryClinton.jpg";
import HillaryClintonAvatar from "../../../images/ThirdPartyServices/snet/text_generation/HillaryClinton_avatar.jpg";
import JimmyFallon from "../../../images/ThirdPartyServices/snet/text_generation/JimmyFallon.jpg";
import JimmyFallonAvatar from "../../../images/ThirdPartyServices/snet/text_generation/JimmyFallon_avatar.jpg";
import JoeBiden from "../../../images/ThirdPartyServices/snet/text_generation/JoeBiden.jpg";
import JoeBidenAvatar from "../../../images/ThirdPartyServices/snet/text_generation/JoeBiden_avatar.jpg";
import JoeRogan from "../../../images/ThirdPartyServices/snet/text_generation/JoeRogan.png";
import JoeRoganAvatar from "../../../images/ThirdPartyServices/snet/text_generation/JoeRogan_avatar.png";
import JordanPeterson from "../../../images/ThirdPartyServices/snet/text_generation/JordanPeterson.jpg";
import JordanPetersonAvatar from "../../../images/ThirdPartyServices/snet/text_generation/JordanPeterson_avatar.jpg";
import JustinBieber from "../../../images/ThirdPartyServices/snet/text_generation/JustinBieber.jpg";
import JustinBieberAvatar from "../../../images/ThirdPartyServices/snet/text_generation/JustinBieber_avatar.jpg";
import KatyPerry from "../../../images/ThirdPartyServices/snet/text_generation/KatyPerry.jpg";
import KatyPerryAvatar from "../../../images/ThirdPartyServices/snet/text_generation/KatyPerry_avatar.jpg";
import KevinHart from "../../../images/ThirdPartyServices/snet/text_generation/KevinHart.jpg";
import KevinHartAvatar from "../../../images/ThirdPartyServices/snet/text_generation/KevinHart_avatar.jpg";
import KimKardashian from "../../../images/ThirdPartyServices/snet/text_generation/KimKardashian.png";
import KimKardashianAvatar from "../../../images/ThirdPartyServices/snet/text_generation/KimKardashian_avatar.png";
import LadyGaga from "../../../images/ThirdPartyServices/snet/text_generation/LadyGaga.jpg";
import LadyGagaAvatar from "../../../images/ThirdPartyServices/snet/text_generation/LadyGaga_avatar.jpg";
import NeildeGrasseTyson from "../../../images/ThirdPartyServices/snet/text_generation/NeildeGrasseTyson.jpg";
import NeildeGrasseTysonAvatar from "../../../images/ThirdPartyServices/snet/text_generation/NeildeGrasseTyson_avatar.jpg";
import PhilipPlait from "../../../images/ThirdPartyServices/snet/text_generation/PhilipPlait.jpg";
import PhilipPlaitAvatar from "../../../images/ThirdPartyServices/snet/text_generation/PhilipPlait_avatar.jpg";
import RebeccaSkloot from "../../../images/ThirdPartyServices/snet/text_generation/RebeccaSkloot.jpg";
import RebeccaSklootAvatar from "../../../images/ThirdPartyServices/snet/text_generation/RebeccaSkloot_avatar.jpg";
import RichardDawkins from "../../../images/ThirdPartyServices/snet/text_generation/RichardDawkins.jpg";
import RichardDawkinsAvatar from "../../../images/ThirdPartyServices/snet/text_generation/RichardDawkins_avatar.jpg";
import RickyGervais from "../../../images/ThirdPartyServices/snet/text_generation/RickyGervais.jpg";
import RickyGervaisAvatar from "../../../images/ThirdPartyServices/snet/text_generation/RickyGervais_avatar.jpg";
import SamHarris from "../../../images/ThirdPartyServices/snet/text_generation/SamHarris.jpg";
import SamHarrisAvatar from "../../../images/ThirdPartyServices/snet/text_generation/SamHarris_avatar.jpg";
import TerenceMcKenna from "../../../images/ThirdPartyServices/snet/text_generation/TerenceMcKenna.jpg";
import TerenceMcKennaAvatar from "../../../images/ThirdPartyServices/snet/text_generation/TerenceMcKenna_avatar.jpg";
import { GENGPT2 } from "./ntg_pb_service";
import { useStyles } from "./styles";
import AnchorLink from "../../../../components/common/AnchorLink";
const initialUserInput = {
start_text: "",
run_name: "trump",
temperature: 0.8,
top_k: 20,
length: 256,
};
const runNames = [
{ key: "badastronomer", value: "<NAME>", image: PhilipPlait, avatar: PhilipPlaitAvatar },
{ key: "barackobama", value: "<NAME>", image: BarackObama, avatar: BarackObamaAvatar },
{ key: "beebrookshire", value: "<NAME>", image: BethanyBrookshire, avatar: BethanyBrookshireAvatar },
{ key: "berniesanders", value: "<NAME>", image: BernieSanders, avatar: BernieSandersAvatar },
{ key: "billgates", value: "<NAME>", image: BillGates, avatar: BillGatesAvatar },
{ key: "conanobrien", value: "<NAME>", image: ConanOBrien, avatar: ConanOBrienAvatar },
{ key: "deborahblum", value: "<NAME>", image: DeborahBlum, image: DeborahBlumAvatar },
{ key: "deepakchopra", value: "<NAME>", image: DeepakChopra, avatar: DeepakChopraAvatar },
{ key: "elonmusk", value: "<NAME>", image: ElonMusk, avatar: ElonMuskAvatar },
{ key: "ericrweinstein", value: "<NAME>", image: EricWeinstein, avatar: EricWeinsteinAvatar },
{ key: "hillaryclinton", value: "<NAME>", image: HillaryClinton, avatar: HillaryClintonAvatar },
{ key: "jimmyfallon", value: "jimmyfallon", image: JimmyFallon, avatar: JimmyFallonAvatar },
{ key: "joebiden", value: "<NAME>", image: JoeBiden, avatar: JoeBidenAvatar },
{ key: "joerogan", value: "<NAME>", image: JoeRogan, avatar: JoeRoganAvatar },
{ key: "jordanbpeterson", value: "Dr <NAME>", image: JordanPeterson, avatar: JordanPetersonAvatar },
{ key: "justinbieber", value: "<NAME>", image: JustinBieber, avatar: JustinBieberAvatar },
{ key: "katyperry", value: "<NAME>", image: KatyPerry, avatar: KatyPerryAvatar },
{ key: "kevinhart4real", value: "<NAME>", image: KevinHart, avatar: KevinHartAvatar },
{ key: "kimkardashian", value: "<NAME>", image: KimKardashian, avatar: KimKardashianAvatar },
{ key: "ladygaga", value: "<NAME>", image: LadyGaga, avatar: LadyGagaAvatar },
{ key: "laelaps", value: "<NAME>", image: BrianSwitek, avatar: BrianSwitekAvatar },
{ key: "neiltyson", value: "<NAME>", image: NeildeGrasseTyson, avatar: NeildeGrasseTysonAvatar },
{ key: "trump", value: "<NAME>", image: DonaldTrump, avatar: DonaldTrumpAvatar },
{ key: "rebeccaskloot", value: "<NAME>", image: RebeccaSkloot, avatar: RebeccaSklootAvatar },
{ key: "richarddawkins", value: "<NAME>", image: RichardDawkins, avatar: RichardDawkinsAvatar },
{ key: "rickygervais", value: "<NAME>", image: RickyGervais, avatar: RickyGervaisAvatar },
{ key: "samharrisorg", value: "<NAME>", image: SamHarris, avatar: SamHarrisAvatar },
{ key: "terencemckenna_", value: "<NAME>", image: TerenceMcKenna, avatar: TerenceMcKennaAvatar },
{ key: "theellenshow", value: "<NAME>", image: EllenDeGeneres, avatar: EllenDeGeneresAvatar },
{ key: "therock", value: "<NAME>", image: DwayneJohnson, avatar: DwayneJohnsonAvatar },
{ key: "thetweetofgod", value: "God", image: god, avatar: godAvatar },
{ key: "ticbot", value: "TicBot" },
];
class TextGenerationService extends React.Component {
constructor(props) {
super(props);
this.submitAction = this.submitAction.bind(this);
this.handleFormUpdate = this.handleFormUpdate.bind(this);
this.changeSlider = this.changeSlider.bind(this);
this.users_guide = "https://github.com/iktina/neural-text-generation";
this.state = {
...initialUserInput,
serviceName: "GENGPT2",
methodName: "gen_gpt_2",
response: undefined,
};
this.isComplete = false;
this.serviceMethods = [];
this.allServices = [];
this.methodsForAllServices = [];
}
changeSlider(elementName, value) {
// Event Target Name and Value are getting Blank
this.setState({
[elementName]: value,
});
}
handleFormUpdate(event) {
this.setState({
[event.target.name]: event.target.value,
});
}
onKeyPressvalidator(event) {
// console.log(event.target.value);
}
submitAction() {
const { methodName, start_text, temperature, top_k, run_name, length } = this.state;
const methodDescriptor = GENGPT2[methodName];
const request = new methodDescriptor.requestType();
request.setStartText(start_text);
request.setTemperature(temperature);
request.setTopK(top_k);
request.setRunName(run_name);
request.setLength(length);
const props = {
request,
onEnd: response => {
const { message, status, statusMessage } = response;
if (status !== 0) {
throw new Error(statusMessage);
}
const selectedRunName = runNames.find(el => el.key === this.state.run_name);
const image = selectedRunName && selectedRunName.image;
this.setState({
...initialUserInput,
response: { status: "success", answer: message.getAnswer(), image, start_text },
});
},
};
this.props.serviceClient.unary(methodDescriptor, props);
}
parseAvatarSrc = () => {
const selectedRunName = runNames.find(el => el.key === this.state.run_name);
return selectedRunName && selectedRunName.avatar;
};
renderForm() {
const { run_name, start_text, length: maxResponseLength, top_k, temperature } = this.state;
const { classes } = this.props;
return (
<React.Fragment>
<Grid container spacing={24} className={classes.textGenConfigDetails}>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.description}>
<p>
For this demo you will be asked to input a text content and the persona you would like the tweet to come from.
</p>
<p>
Check out the
<AnchorLink
newTab
href="https://github.com/iktina/neural-text-generation#how-does-it-work"
label="Guide"
className={classes.guideLink}
/>
for detailed steps.
</p>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.header}>
<h4>Parameters</h4>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.dropdownAndAvatar}>
<Grid item xs={12} sm={12} md={7} lg={7} className={classes.dropdown}>
<InfoIcon className={classes.infoIcon} />
<FormControl variant="outlined" className={classes.formControl}>
<InputLabel htmlFor="outlined-age-simple">Persona Model</InputLabel>
<Select
value={run_name}
onChange={this.handleFormUpdate}
name="run_name"
input={<OutlinedInput labelWidth={320} name="age" id="outlined-age-simple" />}
>
{runNames.map(item => (
<MenuItem className={classes.menuItem} key={item.key} value={item.key}>
{item.value}
</MenuItem>
))}
</Select>
</FormControl>
</Grid>
<Grid item xs={12} sm={12} md={5} lg={5}>
<Avatar alt="Singularity" src={this.parseAvatarSrc()} className={classes.avatar} />
</Grid>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.textArea}>
<InfoIcon className={classes.infoIcon} />
<TextField
name="start_text"
label="Tweet Context or Question"
multiline
rows="7"
variant="outlined"
value={start_text}
onChange={this.handleFormUpdate}
onKeyPress={e => this.onKeyPressvalidator(e)}
/>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.progressBarContainer}>
<Grid item xs={12} sm={12} md={3} lg={3}>
<InfoIcon className={classes.infoIcon} />
<span className={classes.title}>Max Length</span>
</Grid>
<Grid item xs={12} sm={12} md={9} lg={9} className={classes.sliderContainer}>
<span className={classes.startEndNumber}>0</span>
<Slider
name="length"
value={maxResponseLength}
max={1024}
min={1}
aria-labelledby="discrete-slider-always"
step={10}
valueLabelDisplay="on"
onChange={(e, val) => this.changeSlider("length", val)}
/>
<span className={classes.startEndNumber}>1024</span>
</Grid>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.progressBarContainer}>
<Grid item xs={12} sm={12} md={3} lg={3}>
<InfoIcon className={classes.infoIcon} />
<span className={classes.title}>Top K</span>
</Grid>
<Grid item xs={12} sm={12} md={9} lg={9} className={classes.sliderContainer}>
<span className={classes.startEndNumber}>0</span>
<Slider
name="top_k"
value={top_k}
aria-labelledby="discrete-slider-always"
min={0}
max={20}
step={1}
valueLabelDisplay="on"
onChange={(e, val) => this.changeSlider("top_k", val)}
/>
<span className={classes.startEndNumber}>20</span>
</Grid>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.progressBarContainer}>
<Grid item xs={12} sm={12} md={3} lg={3}>
<InfoIcon className={classes.infoIcon} />
<span className={classes.title}>Temperature</span>
</Grid>
<Grid item xs={12} sm={12} md={9} lg={9} className={classes.sliderContainer}>
<span className={classes.startEndNumber}>0</span>
<Slider
name="temperature"
value={temperature}
step={0.1}
min={0.2}
max={1.5}
aria-labelledby="discrete-slider-always"
valueLabelDisplay="on"
onChange={(e, val) => this.changeSlider("temperature", val)}
/>
<span className={classes.startEndNumber}>1.5</span>
</Grid>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.btnContainer}>
<StyledButton type="blue" btnText="Invoke" onClick={this.submitAction} />
</Grid>
</Grid>
</React.Fragment>
);
}
renderComplete() {
const { response } = this.state;
const { classes } = this.props;
return (
<Grid container spacing={24} className={classes.textGenRunDetails}>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.runTabDescription}>
<p>Your request has been completed. You can now vote for the agent below.</p>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.resultsHeader}>
<h4>Results</h4>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.resultsContent}>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.imgContainer}>
<img src={response.image} />
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.resultDetails}>
<Grid item xs={12} sm={12} md={5} lg={5}>
<InfoIcon className={classes.infoIcon} />
<span className="resultTitle">Status</span>
</Grid>
<Grid item xs={12} sm={12} md={7} lg={7}>
<span className={classes.resultValue}>success</span>
</Grid>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.resultDetails}>
<Grid item xs={12} sm={12} md={5} lg={5}>
<InfoIcon className={classes.infoIcon} />
<span className="resultTitle">Input text</span>
</Grid>
<Grid item xs={12} sm={12} md={7} lg={7}>
<span className={classes.resultValue}>{response.start_text}</span>
</Grid>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.resultDetails}>
<Grid item xs={12} sm={12} md={5} lg={5}>
<InfoIcon className={classes.infoIcon} />
<span className="resultTitle">Response output</span>
</Grid>
<Grid item xs={12} sm={12} md={7} lg={7}>
<span className={classes.resultValue}>{response.answer.replace("[END BY LENGTH]", "")}</span>
</Grid>
</Grid>
</Grid>
</Grid>
);
}
render() {
if (this.props.isComplete) return <div>{this.renderComplete()}</div>;
else {
return <div>{this.renderForm()}</div>;
}
}
}
export default withStyles(useStyles)(TextGenerationService);
| 450cc2d4758cca0a39674f1720b9a43ae1bdd643 | [
"JavaScript"
] | 3 | JavaScript | sujithvarma/refactored-dapp | 91b30ed63d89b1cfddde05c33fd67fc253a14827 | b1a646f888070b3d092d7db5787e2769a4863fa7 |
refs/heads/master | <repo_name>alex6673/MVVMDemo<file_sep>/MVVMDemo/Base/Base+Extensions.swift
//
// Extensions.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/12.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
protocol Reusable: class {
static var reuseIdentifier: String { get }
}
extension Reusable {
static var reuseIdentifier: String {
return String(describing: self)
}
}
extension UITableViewCell: Reusable {}
extension UITableViewHeaderFooterView: Reusable {}
extension UITableView {
final func register<T: UITableViewCell>(cellType: T.Type) {
register(cellType.self, forCellReuseIdentifier: cellType.reuseIdentifier)
}
final func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T {
guard let cell = self.dequeueReusableCell(withIdentifier: cellType.reuseIdentifier, for: indexPath) as? T else {
fatalError(
"Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). "
+ "Check that the reuseIdentifier is set properly in your XIB/Storyboard "
+ "and that you registered the cell beforehand"
)
}
return cell
}
final func register<T: UITableViewHeaderFooterView>(headerFooterViewType: T.Type) {
register(headerFooterViewType.self, forHeaderFooterViewReuseIdentifier: headerFooterViewType.reuseIdentifier)
}
final func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(_ viewType: T.Type = T.self) -> T? {
guard let view = self.dequeueReusableHeaderFooterView(withIdentifier: viewType.reuseIdentifier) as? T? else {
fatalError(
"Failed to dequeue a header/footer with identifier \(viewType.reuseIdentifier) "
+ "matching type \(viewType.self). "
+ "Check that the reuseIdentifier is set properly in your XIB/Storyboard "
+ "and that you registered the header/footer beforehand"
)
}
return view
}
}
extension ObservableType where E == Bool {
func not() -> Observable<Bool> {
return map(!)
}
}
extension SharedSequenceConvertibleType {
func mapToVoid() -> SharedSequence<SharingStrategy, Void> {
return map { _ in }
}
}
extension ObservableType {
func catchErrorJustNever() -> Observable<E> {
return catchError { _ in
return Observable.never()
}
}
func catchErrorJustComplete() -> Observable<E> {
return catchError { _ in
return Observable.empty()
}
}
func asDriverOnErrorJustNever() -> Driver<E> {
return asDriver(onErrorDriveWith: .never())
}
func asDriverOnErrorJustComplete() -> Driver<E> {
return asDriver(onErrorDriveWith: .empty())
}
func mapToVoid() -> Observable<Void> {
return map { _ in }
}
}
extension PrimitiveSequence {
func asDriverOnErrorJustNever() -> Driver<E> {
return asDriver(onErrorDriveWith: .never())
}
func asDriverOnErrorJustComplete() -> Driver<E> {
return asDriver(onErrorDriveWith: .empty())
}
}
<file_sep>/MVVMDemo/ViewController/UserTableViewController.swift
//
// UserTableViewController.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/12.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import RxSwift
import RxDataSources
import RxCocoa
final class UserTableViewController: UIViewController {
// MARK: - Properties
var disposeBag = DisposeBag()
private var page: BehaviorRelay<String?> = .init(value: "0")
private var per_page: BehaviorRelay<String?> = .init(value: "20")
private var viewModel: UserTableViewModel
private var refreshControlFecting: Binder<Bool> {
return Binder(refreshControl) { (refreshControl, value) in
value ? refreshControl.beginRefreshing() : refreshControl.endRefreshing()
}
}
private var tableViewDeselect: Binder<IndexPath> {
return Binder(tableView) { (tableView, value) in
tableView.deselectRow(at: value, animated: true)
}
}
// MARK: - UI Components
private let tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.backgroundColor = .white
tableView.estimatedRowHeight = 64
tableView.rowHeight = UITableView.automaticDimension
tableView.register(cellType: UserTableViewCell.self)
return tableView
}()
private let refreshControl: UIRefreshControl = .init()
// MARK: - Con(De)structor
init() {
self.viewModel = UserTableViewModel()
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Overridden: BaseViewController
override func viewDidLoad() {
super.viewDidLoad()
bindViewModel()
setProperties()
view.addSubview(tableView)
layout()
self.per_page = .init(value: "20")
}
// MARK: - Binding
private func bindViewModel() {
// Input
let viewWillAppear = rx.sentMessage(#selector(UIViewController.viewWillAppear))
.take(1)
.mapToVoid()
let pullToRefresh = refreshControl.rx.controlEvent(.valueChanged).asObservable()
let trigger = Observable.merge(viewWillAppear, pullToRefresh)
let param = Observable.combineLatest(page, per_page) { ($0, $1) }
let request: Observable<(String?, String?)> = Observable.combineLatest(trigger, param) { (trigger, param) in
print(param)
return (param.0, param.1)
}
let input = type(of: viewModel).Input(
request: request.asDriverOnErrorJustNever())
// Output
let output = viewModel.transform(input: input)
output.fetching
.drive(refreshControlFecting)
.disposed(by: disposeBag)
output.users
.drive(tableView.rx.items(
cellIdentifier: UserTableViewCell.reuseIdentifier,
cellType: UserTableViewCell.self)) { index, model, cell in
cell.configure(with: model, index: index)
print(index)
}
.disposed(by: disposeBag)
}
// MARK: - Private methods
private func setProperties() {
view.backgroundColor = .white
tableView.separatorStyle = .none
tableView.refreshControl = refreshControl
tableView.rx
.setDelegate(self)
.disposed(by: disposeBag)
}
}
// MARK: - Layout
extension UserTableViewController {
private func layout() {
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
// MARK: - UITableViewDelegate
extension UserTableViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 128
}
}
<file_sep>/MVVMDemo/Base/ViewModelType.swift
//
// ViewModelType.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/12.
// Copyright © 2020 <NAME>. All rights reserved.
//
protocol ViewModelType {
associatedtype Input
associatedtype Output
func transform(input: Input) -> Output
}
<file_sep>/MVVMDemo/API/APIRequest.swift
//
// APIProvider.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/12.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import Moya
import RxCocoa
import RxSwift
final class APIRequest {
static let shared = APIRequest()
private let provider = APIProvider<APIService>()
// MARK: - Properties
var disposeBag = DisposeBag()
func getUsers(page: String?, per_page: String?, fetching: PublishRelay<Bool>) -> Driver<[GithubUser]> {
print("getUsers");
return provider.request([GithubUser].self, token: .users(page: page, per_page: per_page))
.do(onSuccess: { (_) in
fetching.accept(false)
}, onError: { (_) in
fetching.accept(false)
}, onSubscribe: {
fetching.accept(true)
})
.asDriver(onErrorJustReturn: [])
}
}
<file_sep>/MVVMDemo/Base/MoyaLib.swift
//
// MoyaLib.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/13.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Moya
protocol MoyaCacheable {
typealias MoyaCacheablePolicy = URLRequest.CachePolicy
var cachePolicy: MoyaCacheablePolicy { get }
}
final class MoyaCacheablePlugin: PluginType {
func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
if let moyaCachableProtocol = target as? MoyaCacheable {
var cachableRequest = request
cachableRequest.cachePolicy = moyaCachableProtocol.cachePolicy
return cachableRequest
}
return request
}
}
<file_sep>/MVVMDemo/API/APIProvider.swift
//
// APIProvider.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/13.
// Copyright © 2020 <NAME>. All rights reserved.
//
import RxSwift
import Moya
class APIProvider<Target: TargetType>: MoyaProvider<Target> {
// MARK: - Properties
let disposeBag = DisposeBag()
// MARK: - Con(De)structor
init(plugins: [PluginType]? = nil) {
var finalPlugins = plugins ?? [PluginType]()
finalPlugins.append(MoyaCacheablePlugin())
super.init(plugins: finalPlugins)
}
// MARK: - Internal methods
func request<T>(_ modelType: T.Type, token: Target, callbackQueue: DispatchQueue? = nil) -> Single<T> where T: Decodable {
return self.rx.request(token, callbackQueue: callbackQueue).map(modelType)
}
// MARK: - Private methods
private func parse<T>(_ modelType: T.Type, data: Data) throws -> T where T: Decodable {
return try JSONDecoder().decode(modelType, from: data)
}
}
<file_sep>/Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'MVVMDemo' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
platform :ios, '11.0'
use_frameworks!
inhibit_all_warnings!
# Pods for MVVMDemo
pod 'RxSwift'
pod 'RxDataSources'
pod 'Moya/RxSwift'
pod 'Kingfisher'
pod 'FluidHighlighter'
end
<file_sep>/MVVMDemo/ViewModel/UserTableViewModel.swift
//
// UserTableViewModel.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/12.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
final class UserTableViewModel {
private var disposeBag = DisposeBag()
}
// MARK: - ViewModelType
extension UserTableViewModel: ViewModelType {
struct Input {
let request: Driver<(String?, String?)>
}
struct Output {
let fetching: Driver<Bool>
let users: Driver<[GithubUser]>
}
func transform(input: Input) -> Output {
let fetching: PublishRelay<Bool> = .init()
let users: Driver<[GithubUser]> = input.request
.flatMapLatest { [weak self] in
guard let _ = self else {return .empty()}
return APIRequest.shared.getUsers(page: $0.0, per_page: $0.1, fetching: fetching)
}
return Output(
fetching: fetching.asDriverOnErrorJustNever(),
users: users
);
}
}
<file_sep>/MVVMDemo/ViewController.swift
//
// ViewController.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/13.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import UIKit
final class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
let vc = UserTableViewController()
vc.view.translatesAutoresizingMaskIntoConstraints = false
vc.modalPresentationStyle = .popover
self.definesPresentationContext = true
self.present(vc, animated: true)
}
}
<file_sep>/MVVMDemo/TableViewCell/UserTableViewCell.swift
//
// UserTableViewCell.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/12.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import FluidHighlighter
import Kingfisher
import RxSwift
final class UserTableViewCell: UITableViewCell {
// MARK: - UI Components
private let avatarImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.cornerRadius = 32.0;
imageView.layer.masksToBounds = true;
return imageView
}()
private let usernameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.preferredFont(forTextStyle: .title3)
return label
}()
private let siteadminLabel: UIButton = {
let label = UIButton()
label.translatesAutoresizingMaskIntoConstraints = false
label.tintColor = .white
label.backgroundColor = .purple
label.layer.cornerRadius = 8
label.layer.masksToBounds = true
label.contentEdgeInsets = UIEdgeInsets(top: 0, left: 4, bottom: 0, right: 4)
label.isUserInteractionEnabled = false
label.isUserInteractionEnabled = false
return label
}()
private let lineView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .gray
return view
}()
private let hstackView: UIStackView = {
let view = UIStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.distribution = .fill
view.alignment = .top
view.spacing = 6
view.axis = .horizontal
return view
}()
private let vstackView: UIStackView = {
let view = UIStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.distribution = .fill
view.alignment = .top
view.spacing = 6
view.axis = .vertical
return view
}()
// MARK: - Con(De)structor
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setProperties()
vstackView.addArrangedSubview(usernameLabel)
vstackView.addArrangedSubview(siteadminLabel)
hstackView.addArrangedSubview(avatarImageView)
hstackView.addArrangedSubview(vstackView)
contentView.addSubview(hstackView)
contentView.addSubview(lineView)
layout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Overridden: UITableViewCell
override func prepareForReuse() {
super.prepareForReuse()
usernameLabel.text = nil
avatarImageView.image = nil
}
// MARK: - Internal methods
func configure(with model: GithubUser, index: Int) {
fh.enable(normalColor: .white, highlightedColor: .green)
usernameLabel.text = model.login
usernameLabel.textColor = .black
if let sa = model.site_admin, !sa {
siteadminLabel.setTitle("STAFF", for: .normal)
} else {
siteadminLabel.removeFromSuperview()
}
avatarImageView.kf.setImage(with: URL(string: model.avatar_url!)!)
}
// MARK: - Private methods
private func setProperties() {
backgroundColor = .gray
selectionStyle = .none
}
}
// MARK: - Layout
extension UserTableViewCell {
private func layout() {
hstackView.widthAnchor.constraint(equalTo: contentView.widthAnchor).isActive = true
hstackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4).isActive = true
hstackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -6).isActive = true
avatarImageView.widthAnchor.constraint(equalToConstant: 64).isActive = true
avatarImageView.heightAnchor.constraint(equalToConstant: 64).isActive = true
siteadminLabel.widthAnchor.constraint(equalToConstant: 64).isActive = true
vstackView.centerYAnchor.constraint(equalTo: hstackView.centerYAnchor).isActive = true
lineView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
lineView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
lineView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
lineView.heightAnchor.constraint(equalToConstant: 2.0).isActive = true
}
}
<file_sep>/MVVMDemo/Model/GithubUser.swift
//
// GithubUser.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/12.
// Copyright © 2020 <NAME>. All rights reserved.
//
struct GithubUser: Decodable {
var login: String?
var id: Int64?
var node_id: String?
var avatar_url: String?
var gravatar_id: String?
var url: String?
var type: String?
var site_admin: Bool?
}
<file_sep>/MVVMDemo/API/APIService.swift
//
// APIService.swift
// MVVMDemo
//
// Created by <NAME> on 2020/9/12.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Moya
enum APIService {
case users(page: String?, per_page: String?)
case user(login: String)
}
// MARK: - TargetType
extension APIService: TargetType {
var baseURL: URL {
return URL(string: "https://api.github.com")!
}
var path: String {
switch self {
case .users:
return "/users"
case .user(let login):
return "/users/" + login
}
}
var method: Method {
return .get
}
var sampleData: Data {
return "".data(using: .utf8)!
}
var task: Task {
switch self {
case .users(let page, let per_page):
var parameters = [String: Any]()
parameters["page"] = 0
parameters["per_page"] = 20
if let page = page {
parameters["page"] = page
}
if let per_page = per_page {
parameters["per_page"] = per_page
}
return .requestParameters(parameters: parameters, encoding: URLEncoding.default)
case .user(_):
return .requestPlain
}
}
var headers: [String: String]? {
return ["Accept": "application/vnd.github.v3+json"]
}
}
| c3899c1db7ecf12b3ee30003605720ad7c350392 | [
"Swift",
"Ruby"
] | 12 | Swift | alex6673/MVVMDemo | 7f18a8f185a3aefd8054efa69018a623bfd9b6c6 | cff4b53c8b5316fd96a0ac46a61a69c165396fbd |
refs/heads/master | <file_sep>// RADIUS
export const borderRadius = 3;
// SPACING
export const small = 10;
export const medium = 15;
export const large = 25;
<file_sep># Environment Config
### List of env variables
"set-dev": "shx echo \"export default 'dev';\"> active.env.js",
"set-stage": "shx echo \"export default 'staging';\"> active.env.js",
"set-qa": "shx echo \"export default 'qa';\"> active.env.js",
"set-release": "shx echo \"export default 'release';\"> active.env.js"
### Change environment example
```bash
npm run set-dev
```
## Usage
```javascript
//To use te environment variables import the env file in your component
import API from "../../config/env";
//and reference it
console.log(API.admin)
```
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
## License
[MIT](https://choosealicense.com/licenses/mit/)<file_sep>export const primary: string = "#600080";
export const secondary: string = "#233e97";
export const white: string = "#FFFFFF";
export const black: string = "#0A0A0A";
// ACTIONS
export const success: string = "#3adb76";
export const warning: string = "#ffae00";
export const alert: string = "#cc4b37";
// GRAYSCALE
export const light: string = "#e6e6e6";
export const medium: string = "#cacaca";
export const dark: string = "#8a8a8a";
//EMG COLORS
// export const EMG_PRIMARY: string = "#600080";
// export const EMG_secondary: string = "#233e97";
// export const EMG_ALERT: string = "#d0112b";
// export const EMG_SUCCESS: string = "#009943";
// export const EMG_WARNING: string = "#E7B421";
// export default {
// PRIMARY: "#600080",
// SECONDARY: "#233e97",
// BLACK: "#000",
// WHITE: "#fff",
// MEDIUM: "#6e6969",
// LIGHT: "#f8f4f4",
// DARK: "#0c0c0c",
// SUCCESS: "#3adb76",
// WARNING: "#ffae00",
// ALERT: "#cc4b37",
// };
<file_sep>export default 'qa';
<file_sep>import { Platform } from "react-native";
import { scaleFont } from "./mixins";
// FONT FAMILY
// export const FONT_FAMILY_REGULAR = 'Nunito-Regular';
// export const FONT_FAMILY_BOLD = 'Nunito-Bold';
export const FONT_FAMILY_REGULAR = Platform.OS === "android" ? "Nunito-Regular" : "Avenir";
export const FONT_FAMILY_BOLD = Platform.OS === "android" ? "Nunito-Bold" : "Avenir Black";
// FONT WEIGHT
export const FONT_WEIGHT_REGULAR = '400';
export const FONT_WEIGHT_BOLD = '700';
// FONT SIZE
export const FONT_SIZE_20 = scaleFont(20);
export const FONT_SIZE_18 = scaleFont(18);
export const FONT_SIZE_16 = scaleFont(16);
export const FONT_SIZE_14 = scaleFont(14);
export const FONT_SIZE_12 = scaleFont(12);
// LINE HEIGHT
export const LINE_HEIGHT_24 = scaleFont(24);
export const LINE_HEIGHT_20 = scaleFont(20);
export const LINE_HEIGHT_16 = scaleFont(16);
// TEXT TRANSFORM
export const UPPERCASE = 'uppercase';
// FONT STYLE
export const FONT_REGULAR = {
fontFamily: FONT_FAMILY_REGULAR,
fontWeight: FONT_WEIGHT_REGULAR,
};
export const FONT_BOLD = {
fontFamily: FONT_FAMILY_BOLD,
fontWeight: FONT_WEIGHT_BOLD,
};
// export default {
// FONT_REGULAR: FONT_REGULAR,
// FONT_BOLD: FONT_BOLD,
// FONT_FAMILY_REGULAR: FONT_FAMILY_REGULAR,
// FONT_FAMILY_BOLD: FONT_FAMILY_BOLD,
// FONT_WEIGHT_REGULAR: FONT_WEIGHT_REGULAR,
// FONT_WEIGHT_BOLD: FONT_WEIGHT_BOLD,
// FONT_SIZE_16: FONT_SIZE_16,
// FONT_SIZE_14: FONT_SIZE_14,
// FONT_SIZE_12: FONT_SIZE_12,
// LINE_HEIGHT_24: LINE_HEIGHT_24,
// LINE_HEIGHT_20: LINE_HEIGHT_20,
// LINE_HEIGHT_16: LINE_HEIGHT_16,
// };
<file_sep>// Set environment variable listed in config/env.js
// dev | qa | staging | release
// To use te environment variables import the env file in your component
// import API from "../../config/env";
// and reference it
// console.log(API.admin)
import active from "../active.env"
const envs = {
dev: {
imagePath: "http://d27x8bwqafmno1.cloudfront.net/",
admin: "http://localhost:23064/",
login: "http://localhost:47540/auth/",
lms: "http://localhost:52821/",
events: "http://localhost:2605/",
translations: "http://emergenetics-qa-i18n.itlabs.com.mk/",
culture: "https://s3.amazonaws.com/emgadminqa/translations/",
imageResizer: "http://emergenetics-gi-qa-images.devweb.office.it-labs.com/",
notify: "http://localhost:9441/",
roles: "/roles.json",
defaultState: "dashboard"
// SOUNDS: Platform.OS === "android" || false,
},
qa: {
imagePath: "https://d1qae0wzormm1r.cloudfront.net/",
admin: "https://qa-admin.emergenetics.com/",
login: "https://qa-sso.emergenetics.com/auth/",
lms: "https://qa-lms.emergenetics.com/",
events: "https://qa-ems.emergenetics.com",
translations: "https://qa-i18n.emergenetics.com/",
culture: "https://d5u4v8r8pm121.cloudfront.net/translations/",
imageResizer: "https://qa-ir.emergenetics.com/",
notify: "https://qa-notify.emergenetics.com/",
roles: "./roles.json",
defaultState: "dashboard",
payment: false
},
staging: {
imagePath: "https://d1833mb8844gxk.cloudfront.net/",
admin: "https://uat-admin.emergenetics.com/",
login: "https://uat-sso.emergenetics.com/auth/",
lms: "https://uat-lms.emergenetics.com/",
events: "https://uat-ems.emergenetics.com",
translations: "https://uat-i18n.emergenetics.com/",
culture: "https://uat-admin-emergenetics.s3.amazonaws.com/translations/",
imageResizer: "https://uat-ir.emergenetics.com/",
notify: "https://uat-notify.emergenetics.com/",
roles: "./roles.json",
defaultState: "dashboard",
payment: true
},
release: {
imagePath: "https://d663bcqlxq0rb.cloudfront.net/",
admin: "https://admin.emergenetics.com/",
login: "https://sso.emergenetics.com/auth/",
lms: "https://lms.emergenetics.com/",
events: "https://ems.emergenetics.com",
translations: "https://i18n.emergenetics.com/",
culture: "https://d14xxhx5bu4knc.cloudfront.net/translations/",
imageResizer: "https://ir.emergenetics.com/",
notify: "https://notify.emergenetics.com/",
roles: "./roles.json",
defaultState: "dashboard",
payment: true
}
}
export default envs[active] | a017d1327760cec34e1d02e2174cc4e499baca4a | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | Marko-D/sixth-app | 15d3067c001d0dd002ed6e792d49625b0a707e40 | 4168a999e6a66e38ab42c2cae007c12c74529063 |
refs/heads/master | <file_sep># DynamoDB Viewer
This is for DynamoDB viewer. You can see DynamoDB contents.
# Preparation
You can arrange ```application.yml``` file for your own URL. Default value is below(us-east-1).
```application.yml
amazon:
dynamodb:
endpoint: https://dynamodb.us-east-1.amazonaws.com
```
As precondition, this applicaiton will work on a machine which has AWS configuration of AWS CLI.
# Build
Firstly to get a jar file type mvn command.
```
$ mvn clean package
```
# Execution
Type below command after creating jar file with maven command at project root folder.
```
$ java -jar target/dynamodb-view-0.0.1-SNAPSHOT.jar
```
If you want to access to DynamoDB with not default host and port, you can type below.
```
$ java -jar target/dynamodb-view-0.0.1-SNAPSHOT.jar --amazon.dynamodb.endpoint=<NEW URL>
```
For host targeting, if you don't put any setting in command line parameter, this program access to localhost that means all resources(e.g. js files) will be referred from local contents.
If you want to change the situation, you can put ```server.host``` and ```server.port``` parameters like below.
```
$ java -jar target/dynamodb-view-0.0.1-SNAPSHOT.jar --server.host=<HOST NAME> --server.port=<PORT NUMBER>
e.g.
$ java -jar target/dynamodb-view-0.0.1-SNAPSHOT.jar --server.host=ec2-XXX-XXX-XXX-XXX.compute-1.amazonaws.com --server.port=8080
```
<file_sep>package jp.gr.java_conf.kojiisd.dynamodb_local.service;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.model.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* Viewer service for DynamoDB.
*
* @author kojiisd
*/
@Service
public class DynamoDbViewerService {
/**
* DynamoDB value separator
*/
private static final String VALUE_SEPARATOR = ",";
/**
* DynamoDB client
*/
@Autowired
private AmazonDynamoDB dynamoDB;
/**
* Get all table names as list.
*
* @return table name list
*/
public List<String> getAllTables() {
ListTablesResult listResult = this.dynamoDB.listTables();
List<String> tableNameList = new ArrayList<String>();
for (String tableName : listResult.getTableNames()) {
tableNameList.add(tableName);
}
return tableNameList;
}
/**
* Scan target table.
*
* @param tableName table name
* @return scan result
*/
public List<Map<String, String>> scanTableByTableName(String tableName) {
List<Map<String, String>> resultMapList = new ArrayList<Map<String, String>>();
ScanResult scanResult = this.dynamoDB.scan(new ScanRequest(tableName));
// For display easily, format will be List<Map<String, String>>
// To view screen without layout broken, once put all columns in Map.
for (Map<String, AttributeValue> valueMap : scanResult.getItems()) {
Map<String, String> columnMap = createEmptyColumnMap(scanResult);
for (Map.Entry<String, AttributeValue> valueMapEntry : valueMap.entrySet()) {
columnMap.put(valueMapEntry.getKey(), extractColumnValue(valueMapEntry.getValue()));
}
resultMapList.add(columnMap);
}
return resultMapList;
}
/**
* Get describe information for table.
*
* @param tableName table name
* @return table description
*/
public TableDescription inquiryTableByTableName(String tableName) {
DescribeTableRequest request = new DescribeTableRequest().withTableName(tableName);
DescribeTableResult describeResult = this.dynamoDB.describeTable(request);
return describeResult.getTable();
}
/**
* Delete table.
*
* @param tableName table name
*/
public void deleteTableByTableName(String tableName) throws InterruptedException {
DescribeTableRequest describeRequest = new DescribeTableRequest().withTableName(tableName);
DescribeTableResult describeResult = this.dynamoDB.describeTable(describeRequest);
CreateTableRequest createRequest = new CreateTableRequest().withTableName(tableName)
.withAttributeDefinitions(describeResult.getTable().getAttributeDefinitions())
.withKeySchema(describeResult.getTable().getKeySchema())
.withProvisionedThroughput(new ProvisionedThroughput()
.withReadCapacityUnits(describeResult.getTable().getProvisionedThroughput().getReadCapacityUnits())
.withWriteCapacityUnits(describeResult.getTable().getProvisionedThroughput().getWriteCapacityUnits()));
DynamoDB db = new DynamoDB(this.dynamoDB);
Table table = db.getTable(tableName);
table.delete();
table.waitForDelete();
table = db.createTable(createRequest);
table.waitForActive();
}
/**
* Drop table.
*
* @param tableName table name
*/
public void dropTableByTableName(String tableName) {
this.dynamoDB.deleteTable(tableName);
}
/**
* Create Empty column map for display all columns in screen.
*
* @param scanResult scan result
* @return Map value
*/
private Map<String, String> createEmptyColumnMap(ScanResult scanResult) {
Map<String, String> columnMap = new LinkedHashMap<String, String>();
for (Map<String, AttributeValue> valueMap : scanResult.getItems()) {
for (Map.Entry<String, AttributeValue> valueMapEntry : valueMap.entrySet()) {
columnMap.put(valueMapEntry.getKey(), StringUtils.EMPTY);
}
}
return columnMap;
}
/**
* Extract column value from DynamoDB with following types.
* - bOOL, b, n, s -> String type extract
* - sS, nS, bS, m -> String with "," combine
*
* @param value AttributeValue
* @return result of extract
*/
private String extractColumnValue(AttributeValue value) {
String result = StringUtils.EMPTY;
if (value == null) {
return result;
}
if (value.getBOOL() != null) {
result = value.getBOOL().toString();
} else if (value.getB() != null) {
result = value.getB().toString();
} else if (value.getN() != null) {
result = value.getN();
} else if (value.getS() != null) {
result = value.getS();
} else if (value.getM() != null) {
ObjectMapper mapper = new ObjectMapper();
try {
result = mapper.writeValueAsString(value.getM());
} catch (JsonProcessingException ex) {
// TODO Exception handling
ex.printStackTrace();
result = StringUtils.EMPTY;
}
} else if (value.getSS() != null) {
result = String.join(VALUE_SEPARATOR, value.getSS().toArray(new String[0]));
} else if (value.getNS() != null) {
result = String.join(VALUE_SEPARATOR, value.getNS().toArray(new String[0]));
} else if (value.getBS() != null) {
result = String.join(VALUE_SEPARATOR, value.getBS().toArray(new String[0]));
}
return result;
}
}
<file_sep>var dynamoDbViewer = angular.module('DynamoDbViewer', ['ngTable', 'angular-loading-bar', 'ui.bootstrap']);
dynamoDbViewer.controller("listTables",
function listTables($scope, $uibModal, $window, $http, ngTableParams, cfpLoadingBar) {
var tmpHost;
var tmpPort;
$scope.init = function(host, port) {
$scope.tableParams = new ngTableParams(
{ page: 1,
count: 10 },
{ counts: [],
total: 1,
dataset: $scope.tables });
tmpHost = (host == "" || host == null || host == "null") ? "localhost" : host;
tmpPort = (port == "" || port == null) ? "8080" : port;
var url = "http://" + tmpHost + ":" + tmpPort + "/api/list-tables"
cfpLoadingBar.start();
$http.get(url)
.then(function(response) {
//First function handles success
$scope.tables = response.data;
cfpLoadingBar.complete();
}, function(response) {
cfpLoadingBar.complete();
//Second function handles error
alert("Can not connect to DynamoDB. Please check connection and try again.");
});
};
$scope.inquiry = function(tableName) {
var url = "http://" + tmpHost + ":" + tmpPort + "/api/inquiry/" + tableName
var inquiryData;
$http.get(url)
.then(function(response) {
inquiryData = response.data;
$scope.inquiryData = JSON.stringify(inquiryData, null, " ");
$uibModal.open({
templateUrl: "inquiry.html",
scope: $scope
});
}, function(response) {
alert("Can not connect to DynamoDB Local. Please check connection and try again.");
});
};
$scope.deleteTable = function(tableName) {
$scope.targetTableName = tableName;
$scope.operation = "Clear Data";
var url = "http://" + tmpHost + ":" + tmpPort + "/api/delete/" + tableName
var inquiryData;
var modalInstance = $uibModal.open({
templateUrl: "confirm.html",
scope: $scope
});
modalInstance.result.then(function() {
$http.get(url)
.then(function(response) {
alert("Table clear finished.")
}, function(response) {
alert("Error happened while deleting. Please check connection and try again.");
});
}, function() {});
};
$scope.dropTable = function(tableName) {
$scope.targetTableName = tableName;
$scope.operation = "Drop";
var url = "http://" + tmpHost + ":" + tmpPort + "/api/drop/" + tableName
var inquiryData;
var modalInstance = $uibModal.open({
templateUrl: "confirm.html",
scope: $scope
});
modalInstance.result.then(function() {
$http.get(url)
.then(function(response) {
alert("Table drop finished.")
$window.location.reload();
}, function(response) {
alert("Error happened while dropping. Please check connection and try again.");
});
}, function() {});
};
});
dynamoDbViewer.controller("inquiryTable",
function inquiryTable($scope, $http, ngTableParams, cfpLoadingBar){
$scope.init = function(tableName, host, port) {
$scope.tableName = tableName;
$scope.sortType = '';
$scope.preSortType = '';
$scope.setSortType = function(sortType) {
$scope.sortType = sortType;
}
$scope.sortReverse = false;
$scope.setSortReverse = function(sortReverse) {
// TODO to put icon for sort order
// if ($scope.preSortType != $scope.sortType) {
// $scope.sortReverse = false;
// } else {
// $scope.sortReverse = !sortReverse;
// }
// $scope.preSortType = $scope.sortType;
$scope.sortReverse = !sortReverse;
}
$scope.searchWord = '';
$scope.setSearchWord = function(searchWord) {
$scope.searchWord = searchWord;
}
$scope.tableParams = new ngTableParams(
{ page: 1,
count: 10 },
{ counts: [],
total: 1,
dataset: $scope.tables });
var tmpHost = (host == "" || host == null || host == "null") ? "localhost" : host;
var tmpPort = (port == "" || port == null) ? "8080" : port;
var url = "http://" + tmpHost + ":" + tmpPort + "/api/scan/"
cfpLoadingBar.start();
$http.get(url + $scope.tableName)
.then(function(response) {
//First function handles success
$scope.datas = response.data;
cfpLoadingBar.complete();
}, function(response) {
//Second function handles error
alert("Can not connect to DynamoDB. Please check connection and try again.");
cfpLoadingBar.complete();
});
};
});
dynamoDbViewer.controller("queryTable",
function inquiryTable($scope, $http, ngTableParams, cfpLoadingBar){
$scope.init = function(tableName, host, port) {
$scope.tableName = tableName;
$scope.sortType = '';
$scope.setSortType = function(sortType) {
$scope.sortType = sortType;
}
$scope.sortReverse = false;
$scope.setSortReverse = function(sortReverse) {
$scope.sortReverse = !sortReverse;
}
$scope.searchWord = '';
$scope.setSearchWord = function(searchWord) {
$scope.searchWord = searchWord;
}
$scope.tableParams = new ngTableParams(
{ page: 1,
count: 10 },
{ counts: [],
total: 1,
dataset: $scope.tables });
var tmpHost = (host == "" || host == null || host == "null") ? "localhost" : host;
var tmpPort = (port == "" || port == null) ? "8080" : port;
var url = "http://" + tmpHost + ":" + tmpPort + "/api/query/"
cfpLoadingBar.start();
$http.get(url + $scope.tableName)
.then(function(response) {
//First function handles success
$scope.datas = response.data;
cfpLoadingBar.complete();
}, function(response) {
//Second function handles error
alert("Can not connect to DynamoDB. Please check connection and try again.");
cfpLoadingBar.complete();
});
};
});
| b46bf870585e5737969622968edfee6a1ccd3e80 | [
"Markdown",
"Java",
"JavaScript"
] | 3 | Markdown | kojiisd/dynamodb-viewer-java | 402b50f0bdeb68c1001e9d5d0281df96415b4d65 | 534d7a44a856f6ed04d68005922dec2e827ef3a3 |
refs/heads/master | <repo_name>Semty/SocialBannersApp<file_sep>/SocialBannersApp/SocialBannersApp/Extensions.swift
//
// Extensions.swift
// SocialBannersApp
//
// Created by <NAME> on 21.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import Cocoa
extension NSView {
func createGradientLayer(withFirstColor firstGradientColor: CGColor,
secondColor secondDradientColor: CGColor,
andFrame frame: CGRect) -> CAGradientLayer {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = frame
gradientLayer.colors = [secondDradientColor, firstGradientColor]
return gradientLayer
}
func image() -> NSImage {
let imageRepresentation = bitmapImageRepForCachingDisplay(in: bounds)!
cacheDisplay(in: bounds, to: imageRepresentation)
return NSImage(cgImage: imageRepresentation.cgImage!, size: bounds.size)
}
public static func setShadowFor(view: NSView) {
let xTranslationFactor: CGFloat = 0
let yTranslationFactor: CGFloat = 0.08
var widthRelativeFactor: CGFloat = 0.8
let heightRelativeFactor: CGFloat = 0.78
let blurRadiusFactor: CGFloat = 0.1
let shadowOpacity: CGFloat = 0.1
if view.frame.width < 120 {
widthRelativeFactor = widthRelativeFactor * 0.8
}
var shadowWidth = view.frame.width * widthRelativeFactor
if (view.frame.width - shadowWidth) / 2 > 35 {
shadowWidth = view.frame.width - 70
widthRelativeFactor = shadowWidth / view.frame.width
}
let shadowHeight = view.frame.height * heightRelativeFactor
let xTranslation = (view.frame.width - shadowWidth) / 2 + (view.frame.width * xTranslationFactor)
var yTranslation = (view.frame.height - shadowHeight) / 2 + (view.frame.height * yTranslationFactor)
let minBottomSpace: CGFloat = 6
if (yTranslation + shadowHeight - view.frame.height) < minBottomSpace {
yTranslation = view.frame.height + minBottomSpace - shadowHeight
}
let maxBottomSpace: CGFloat = 12
if (yTranslation + shadowHeight - view.frame.height) > maxBottomSpace {
yTranslation = view.frame.height + maxBottomSpace - shadowHeight
}
let minSideSize = view.bounds.width > view.bounds.height ? view.bounds.height : view.bounds.width
let blurRadius = minSideSize * blurRadiusFactor
if blurRadius > 10 || blurRadius < 7 {
view.layer?.shadowRadius = blurRadius
}
view.setShadow(
xTranslation: xTranslation,
yTranslation: yTranslation,
widthRelativeFactor: widthRelativeFactor,
heightRelativeFactor: heightRelativeFactor,
blurRadius: blurRadius,
shadowOpacity: shadowOpacity,
cornerRadius: 4.0
)
}
func setShadow(
xTranslation: CGFloat,
yTranslation: CGFloat,
widthRelativeFactor: CGFloat,
heightRelativeFactor: CGFloat,
blurRadius: CGFloat,
shadowOpacity: CGFloat,
cornerRadius: CGFloat = 0
) {
let shadowWidth = self.frame.width * widthRelativeFactor
let shadowHeight = self.frame.height * heightRelativeFactor
let shadowPath = CGPath(roundedRect: CGRect.init(x: xTranslation, y: yTranslation,
width: shadowWidth, height: shadowHeight),
cornerWidth: cornerRadius, cornerHeight: cornerRadius, transform: nil)
self.layer?.shadowColor = NSColor.black.cgColor
self.layer?.shadowOffset = CGSize.zero
self.layer?.shadowOpacity = Float(shadowOpacity)
self.layer?.shadowRadius = blurRadius
self.layer?.masksToBounds = false
self.layer?.shadowPath = shadowPath
}
}
extension NSColor {
public class func hexColor(rgbValue: Int, alpha: CGFloat = 1.0) -> NSColor {
return NSColor(red: ((CGFloat)((rgbValue & 0xFF0000) >> 16))/255.0,
green:((CGFloat)((rgbValue & 0xFF00) >> 8))/255.0,
blue:((CGFloat)(rgbValue & 0xFF))/255.0,
alpha:alpha)
}
}
extension NSBitmapImageRep {
var png: Data? {
return representation(using: .PNG, properties: [:])
}
}
extension Data {
var bitmap: NSBitmapImageRep? {
return NSBitmapImageRep(data: self)
}
}
extension NSImage {
var png: Data? {
return tiffRepresentation?.bitmap?.png
}
func savePNG(to url: URL) -> Bool {
do {
try png?.write(to: url)
return true
} catch {
print(error)
return false
}
}
}
extension NSObject {
func calculateFont(toFit textField: NSTextField, withString string: NSString, minSize min: Int, maxSize max: Int) -> NSFont {
for i in min...max {
var attr: [String: Any] = [:] as Dictionary
attr[NSFontSizeAttribute] = NSFont(name: textField.font!.fontName, size: CGFloat(i))!
let strSize = string.size(withAttributes: [NSFontAttributeName: NSFont.init(name: textField.font!.fontName, size: CGFloat(i))!])
let linesNumber = Int(textField.bounds.height/strSize.height)
if strSize.width/CGFloat(linesNumber) > textField.bounds.width {
return (i == min ? NSFont(name: "\(textField.font!.fontName)", size: CGFloat(min)) : NSFont(name: "\(textField.font!.fontName)", size: CGFloat(i-1)))!
}
}
return NSFont(name: "\(textField.font!.fontName)", size: CGFloat(Double(max)-0.5))!
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/AppContents.swift
//
// AppContents.swift
// SocialBannersApp
//
// Created by <NAME> on 18.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class AppContents: NSObject {
static func getFontsModel() -> [FontModel] {
return [
FontModel(type: .avenirNextDemiBold),
FontModel(type: .avenitNextBold),
FontModel(type: .avenirNextMedium),
FontModel(type: .avenirNexRegular),
FontModel(type: .avenirNextCondensedMedium),
FontModel(type: .avenirNextCondensedBold),
FontModel(type: .timesNewRoman),
FontModel(type: .georgia),
FontModel(type: .georgiaBold),
FontModel(type: .gillSans),
FontModel(type: .gillSansBold)
]
}
static func getContentColor() -> [ColorModel] {
return [
ColorModel(name: "Sky",
fillColor: NSColor.hexColor(rgbValue: 0x14ABFB)),
ColorModel(name: "White",
fillColor: .white),
ColorModel(name: "Gray",
fillColor: NSColor.hexColor(rgbValue: 0x5F6F7D)),
ColorModel(name: "Night",
fillColor: NSColor.hexColor(rgbValue: 0x415C8E)),
ColorModel(name: "Black",
fillColor: .black),
ColorModel(name: "Orange",
fillColor: NSColor.hexColor(rgbValue: 0xF6A623)),
ColorModel(name: "Red",
fillColor: NSColor.hexColor(rgbValue: 0xD0011B)),
ColorModel(name: "Green",
fillColor: NSColor.hexColor(rgbValue: 0x7ED321)),
ColorModel(name: "Pink",
fillColor: NSColor.hexColor(rgbValue: 0xBD0FE1)),
ColorModel(name: "Purple",
fillColor: NSColor.hexColor(rgbValue: 0x9012FE)),
ColorModel(name: "Cian",
fillColor: NSColor.hexColor(rgbValue: 0x02CBE4)),
ColorModel(name: "Light Blue",
fillColor: NSColor.hexColor(rgbValue: 0xA8C4F0))
]
}
static func getBackgroundColors() -> [ColorModel] {
return [
ColorModel(name: "White",
fillColor: .white),
ColorModel(name: "Gray",
fillColor: NSColor.hexColor(rgbValue: 0x5F6F7D)),
ColorModel(name: "Sky",
fillColor: NSColor.hexColor(rgbValue: 0x14ABFB)),
ColorModel(name: "Water",
fillColor: NSColor.hexColor(rgbValue: 0x9CE2FF)),
ColorModel(name: "Night",
fillColor: NSColor.hexColor(rgbValue: 0x415C8E)),
ColorModel(name: "Black",
fillColor: .black),
ColorModel(name: "Sea Water",
firstGradientColor: NSColor.hexColor(rgbValue: 0x1AD6FD),
secondGradientColor: NSColor.hexColor(rgbValue: 0x1D62F0)),
ColorModel(name: "Salt",
firstGradientColor: NSColor.hexColor(rgbValue: 0x7AFFE0),
secondGradientColor: NSColor.hexColor(rgbValue: 0x2991F3)),
ColorModel(name: "Pastel",
firstGradientColor: NSColor.hexColor(rgbValue: 0x01DBFC),
secondGradientColor: NSColor.hexColor(rgbValue: 0x0985CD)),
ColorModel(name: "Fantasy",
firstGradientColor: NSColor.hexColor(rgbValue: 0x9155E1),
secondGradientColor: NSColor.hexColor(rgbValue: 0x67ECFF)),
ColorModel(name: "Hot",
firstGradientColor: NSColor.hexColor(rgbValue: 0xFBDA61),
secondGradientColor: NSColor.hexColor(rgbValue: 0xF76B1C)),
ColorModel(name: "<NAME>",
firstGradientColor: NSColor.hexColor(rgbValue: 0xFC6E51),
secondGradientColor: NSColor.hexColor(rgbValue: 0xDB391E)),
ColorModel(name: "Red",
firstGradientColor: NSColor.hexColor(rgbValue: 0xF5515F),
secondGradientColor: NSColor.hexColor(rgbValue: 0x9F031B)),
ColorModel(name: "Nature",
firstGradientColor: NSColor.hexColor(rgbValue: 0x81D86D),
secondGradientColor: NSColor.hexColor(rgbValue: 0x23AE87)),
ColorModel(name: "Linier",
firstGradientColor: NSColor.hexColor(rgbValue: 0x48CFAD),
secondGradientColor: NSColor.hexColor(rgbValue: 0x19A784)),
ColorModel(name: "Pink",
firstGradientColor: NSColor.hexColor(rgbValue: 0xEC87C0),
secondGradientColor: NSColor.hexColor(rgbValue: 0xBF4C90)),
ColorModel(name: "<NAME>",
firstGradientColor: NSColor.hexColor(rgbValue: 0xEDF1F7),
secondGradientColor: NSColor.hexColor(rgbValue: 0xC9D7E9)),
ColorModel(name: "Business",
firstGradientColor: NSColor.hexColor(rgbValue: 0xCCD1D9),
secondGradientColor: NSColor.hexColor(rgbValue: 0x8F9AA8))
]
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/CreateNewBannerViewController.swift
//
// CreateNewBannerViewController.swift
// SocialBannersApp
//
// Created by <NAME> on 29.05.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class CreateNewBannerViewController: NSViewController, NSCollectionViewDataSource, NSCollectionViewDelegate, NSTextFieldDelegate {
// MARK: - IBOutlet's
@IBOutlet weak var scrollView: NSScrollView!
@IBOutlet weak var createBannerView: NSView!
@IBOutlet weak var substrateHeaderView: SubstrateHeaderView!
@IBOutlet weak var newBannerView: NewBannerView!
@IBOutlet weak var roundedHeaderView: WhiteRoundedView!
@IBOutlet weak var backToBannersButton: BackToBannersButton!
@IBOutlet weak var imageCollectionScrollView: ImagesBannerScrollView!
@IBOutlet weak var imagesCollectionView: NSCollectionView!
@IBOutlet weak var enterTitleField: NSTextField!
@IBOutlet weak var enterSubtitleField: NSTextField!
@IBOutlet weak var bgColorLabel: NSTextField!
@IBOutlet weak var bgColorView: BGColorView!
@IBOutlet weak var changeNBBackgroundColorButton: ChangeButton!
@IBOutlet weak var contentColorLabel: NSTextField!
@IBOutlet weak var contentColorView: ContentColorView!
@IBOutlet weak var changeNBContentColorButton: ChangeButton!
@IBOutlet weak var changeNBContentFontLabel: NSTextField!
@IBOutlet weak var changeNBContentFontButton: ChangeButton!
@IBOutlet weak var saveNewBannerButton: SaveButton!
// MARK: - New Banner Elements
@IBOutlet weak var titleForNewBanner: TitleTextField!
@IBOutlet weak var subtitleForNewBanner: SubtitleTextField!
@IBOutlet weak var imageForNewBannerView: BackgroundImageView!
// MARK: - Final New Banner Elements For Saving in Full HD
@IBOutlet weak var finalNewBanner: NewBannerView!
@IBOutlet weak var finalBackgroundImage: BackgroundImageView!
@IBOutlet weak var finalTitleLabel: TitleTextField!
@IBOutlet weak var finalSubtitleLabel: SubtitleTextField!
// MARK: - Private variables
private var topScrollPoint = CGPoint.zero // default (it's not top!)
private var headerStartOrigin = CGPoint.zero // default
private var substrateStartFrame = CGRect.zero // default
private var newBannerStartFrame = CGRect.zero // default
// MARK: - Public variables
let imageBannerModel = IconsCollectionModel()
var newBannerModel = BannerModel()
// MARK: - View Did Load
override func viewDidLoad() {
super.viewDidLoad()
self.titleForNewBanner.stringValue = "Title"
self.enterTitleField.stringValue = "Title"
newBannerView.translatesAutoresizingMaskIntoConstraints = true
roundedHeaderView.translatesAutoresizingMaskIntoConstraints = true
headerStartOrigin = roundedHeaderView.frame.origin
substrateStartFrame = substrateHeaderView.frame
newBannerStartFrame = newBannerView.frame
changeNBBackgroundColorButton.draw(changeNBBackgroundColorButton.frame)
changeNBContentColorButton.draw(changeNBContentColorButton.frame)
changeNBContentFontButton.draw(changeNBContentFontButton.frame)
saveNewBannerButton.draw(saveNewBannerButton.frame)
imagesCollectionView.frame = imageCollectionScrollView.bounds
self.topScrollPoint = CGPoint(x: 0,
y: createBannerView.bounds.height - scrollView.bounds.height)
self.view.wantsLayer = true
self.scrollView.contentView.scrollToVisible(CGRect(x: 0,
y: createBannerView.bounds.height-self.view.bounds.height,
width: self.view.bounds.width,
height: self.view.bounds.height))
// Set notification for tracking scroll position
self.scrollView.contentView.postsBoundsChangedNotifications = true
NotificationCenter.default.addObserver(self,
selector: #selector(boundsDidChangeNotification(_:)),
name: .NSViewBoundsDidChange,
object: scrollView.contentView)
// Configure Collection View
configureCollectionView()
imagesCollectionView.selectItems(at: [IndexPath.init(item: newBannerModel.iconImage.rawValue,
section: 0)],
scrollPosition: NSCollectionViewScrollPosition.centeredHorizontally)
if newBannerModel.iconImage != .empty {
imageForNewBannerView.setBackgroundImage(withIndex: newBannerModel.iconImage.rawValue,
andColor: newBannerModel.contentColor)
} else {
imageForNewBannerView.isHidden = true
}
newBannerView.layout()
}
// MARK: - View Will Appear
override func viewWillAppear() {
super.viewWillAppear()
self.view.window?.styleMask.remove(.resizable)
self.newBannerView.setBackgroundColor(withColors: newBannerModel.backgroundColor)
self.updateNBFont(withType: newBannerModel.fontType)
self.updateNBContentColor(withContentColor: newBannerModel.contentColor)
self.titleForNewBanner.stringValue = newBannerModel.titleText
self.subtitleForNewBanner.stringValue = newBannerModel.subtitleText
self.enterTitleField.stringValue = newBannerModel.titleText
self.enterSubtitleField.stringValue = newBannerModel.subtitleText
self.bgColorLabel.stringValue = newBannerModel.bgColorName
self.bgColorView.setBackgroundColor(withColors: newBannerModel.backgroundColor)
self.contentColorLabel.stringValue = newBannerModel.contentColorName
self.contentColorView.layer?.backgroundColor = newBannerModel.contentColor.cgColor
if subtitleForNewBanner.stringValue.characters.count == 0 {
subtitleForNewBanner.isHidden = true
newBannerView.layout()
}
}
// MARK: - NSCollectionViewDataSource
public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return imageBannerModel.numberOfItems
}
public func numberOfSections(in collectionView: NSCollectionView) -> Int {
return imageBannerModel.numberOfSections
}
public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: "ImageBannerCollectionItem",
for: indexPath)
guard let collectionViewItem = item as? ImageBannerCollectionItem else {
return item
}
(collectionViewItem.view as! BackgroundImageView).setBackgroundImage(withIndex: indexPath.item, andColor: .white)
let isItemSelected = collectionView.selectionIndexPaths.contains(indexPath)
collectionViewItem.setHighlight(isItemSelected, atIndex: indexPath.item)
return item
}
// MARK: - NSCollectionViewDelegate
public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
for indexPath in indexPaths {
guard let item = collectionView.item(at: indexPath) else {continue}
(item as! ImageBannerCollectionItem).setHighlight(true, atIndex: indexPath.item)
if indexPath.item != 0 {
imageForNewBannerView.isHidden = false
imageForNewBannerView.setBackgroundImage(withIndex: indexPath.item,
andColor: newBannerModel.contentColor)
} else {
imageForNewBannerView.isHidden = true
}
imageForNewBannerView.layer?.setNeedsDisplay()
newBannerView.layout()
newBannerModel.iconImage = ImageIndex(rawValue: indexPath.item)!
}
}
public func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
for indexPath in indexPaths {
guard let item = collectionView.item(at: indexPath) else {continue}
(item as! ImageBannerCollectionItem).setHighlight(false, atIndex: indexPath.item)
}
}
// MARK: - Actions
@IBAction func backToBannersAction(_ sender: NSButton) {
let bannersVC = self.presenting as! ViewController
bannersVC.bannersCollection.deselectAll(nil)
self.dismiss(sender)
bannersVC.resizeWindow(withCreateBannerSize: bannersVC.view.bounds)
}
@IBAction func saveNewBanner(_ sender: Any) {
prepareForSaveFinalNewBanner()
allowFolderForSaving()
}
override func controlTextDidChange(_ obj: Notification) {
let enterTextField = obj.object as! NSTextField
if enterTextField == enterTitleField {
if enterTitleField.stringValue.characters.count <= 20 {
self.titleForNewBanner.stringValue = enterTextField.stringValue
self.titleForNewBanner.font =
self.calculateFont(toFit: self.titleForNewBanner,
withString: self.titleForNewBanner.stringValue as NSString,
minSize: 1,
maxSize: 15)
}
} else if enterTextField == enterSubtitleField {
if enterTextField.stringValue.characters.count > 0 {
subtitleForNewBanner.isHidden = false
} else {
subtitleForNewBanner.isHidden = true
}
newBannerView.layout()
if enterSubtitleField.stringValue.characters.count <= 30 {
self.subtitleForNewBanner.stringValue = enterTextField.stringValue
self.subtitleForNewBanner.font =
self.calculateFont(toFit: self.subtitleForNewBanner,
withString: self.subtitleForNewBanner.stringValue as NSString,
minSize: 1,
maxSize: 11)
}
}
}
// MARK: - Transitions
@IBAction func changeNBBackgroundColorAction(_ sender: Any) {
let changeNBVC = self.storyboard?.instantiateController(withIdentifier: "SelectBackgroundColorController") as! SelectBackgroundColorController
self.presentViewControllerAsSheet(changeNBVC)
}
@IBAction func changeNBContentColorAction(_ sender: Any) {
let changeNBVC = self.storyboard?.instantiateController(withIdentifier: "SelectContentColorController") as! SelectContentColorController
self.presentViewControllerAsSheet(changeNBVC)
}
@IBAction func changeNBContentFontAction(_ sender: Any) {
let changeNBVC = self.storyboard?.instantiateController(withIdentifier: "SelectFontNameController") as! SelectFontNameController
self.presentViewControllerAsSheet(changeNBVC)
}
// MARK: - Tracking of the scroll position
func boundsDidChangeNotification(_ notification: NSNotification) {
let visibleRect = scrollView.contentView.documentVisibleRect
let currentScrollPosition = visibleRect.origin
let scrollYOffset = currentScrollPosition.y - topScrollPoint.y
//print("scrollYOffset = \(scrollYOffset)")
// Pull Up Header
if currentScrollPosition.y <= topScrollPoint.y {
scrollToDown(withScrollYOffset: scrollYOffset)
} else {
scrollToUp(withScrollYOffset: scrollYOffset)
}
}
// MARK: - Scrolling Functions
func scrollToDown(withScrollYOffset scrollYOffset: CGFloat) {
let substrateYOffset: CGFloat = (scrollYOffset <= 0 && scrollYOffset >= -20) ? scrollYOffset : -20
let newOriginForHeader = CGPoint(x: headerStartOrigin.x,
y: headerStartOrigin.y + scrollYOffset - substrateYOffset)
let offsetPercent = (scrollYOffset <= 0 && scrollYOffset >= -20) ? scrollYOffset/(-20) : 1.0
let newOriginForNewBanner =
CGPoint(x: newBannerStartFrame.origin.x + 15*offsetPercent,
y: newBannerStartFrame.origin.y + scrollYOffset + 40*offsetPercent)
roundedHeaderView.setFrameOrigin(newOriginForHeader)
newBannerView.setFrameOrigin(newOriginForNewBanner)
let xyScaleOffset = (scrollYOffset <= 0 && scrollYOffset >= -20) ? scrollYOffset/160 : -20/160
let newBannerScale = 1.0 + xyScaleOffset
newBannerView.layer?.setAffineTransform(CGAffineTransform.init(scaleX: newBannerScale,
y: newBannerScale))
}
func scrollToUp(withScrollYOffset scrollYOffset: CGFloat) {
substrateHeaderView.setFrameSize(NSSize.init(width: substrateHeaderView.bounds.width,
height: substrateStartFrame.size.height + scrollYOffset))
substrateHeaderView.setFrameOrigin(NSPoint.init(x: substrateStartFrame.origin.x,
y: substrateStartFrame.origin.y - scrollYOffset))
}
// MARK: - Configure CollectionView
fileprivate func configureCollectionView() {
let flowLayout = NSCollectionViewFlowLayout()
flowLayout.itemSize = NSSize(width: 40.0, height: 40.0)
flowLayout.sectionInset = EdgeInsets(top: 5.0, left: 159.0, bottom: 5.0, right: 159.0)
//flowLayout.minimumInteritemSpacing = 10.0
flowLayout.minimumLineSpacing = 20.0
flowLayout.scrollDirection = .horizontal
imagesCollectionView.collectionViewLayout = flowLayout
(imagesCollectionView.superview?.superview as! ImagesBannerScrollView).draw(imagesCollectionView.bounds)
view.wantsLayer = true
}
// MARK: - New Banner Updating Functions
public func updateNBFont(withType font: FontModel) {
self.titleForNewBanner.font = NSFont(name: font.type.rawValue,
size: 15.0)
self.subtitleForNewBanner.font = NSFont(name: font.type.rawValue,
size: 14.0)
self.titleForNewBanner.font =
self.calculateFont(toFit: self.titleForNewBanner,
withString: self.titleForNewBanner.stringValue as NSString,
minSize: 1,
maxSize: 15)
self.subtitleForNewBanner.font =
self.calculateFont(toFit: self.subtitleForNewBanner,
withString: self.subtitleForNewBanner.stringValue as NSString,
minSize: 1,
maxSize: 10)
self.changeNBContentFontLabel.stringValue = font.type.rawValue
}
public func updateNBContentColor(withContentColor color: NSColor) {
self.titleForNewBanner.textColor = color
self.subtitleForNewBanner.textColor = color
self.imageForNewBannerView.setBackgroundImage(withIndex: newBannerModel.iconImage.rawValue,
andColor: color)
}
// MARK: - Saving Final New Banner
func prepareForSaveFinalNewBanner() {
if newBannerModel.iconImage == .empty {
finalBackgroundImage.isHidden = true
} else {
finalBackgroundImage.isHidden = false
finalBackgroundImage.setBackgroundImage(withIndex: newBannerModel.iconImage.rawValue,
andColor: newBannerModel.contentColor)
}
self.newBannerModel.titleText = self.titleForNewBanner.stringValue
if subtitleForNewBanner.stringValue.characters.count == 0 {
finalSubtitleLabel.isHidden = true
} else {
self.newBannerModel.subtitleText = self.subtitleForNewBanner.stringValue
finalSubtitleLabel.isHidden = false
}
finalNewBanner.layout()
finalTitleLabel.stringValue = titleForNewBanner.stringValue
finalSubtitleLabel.stringValue = subtitleForNewBanner.stringValue
finalTitleLabel.font = NSFont(name: newBannerModel.fontType.type.rawValue,
size: 100)
finalSubtitleLabel.font = NSFont(name: newBannerModel.fontType.type.rawValue,
size: 100)
finalTitleLabel.font =
self.calculateFont(toFit: self.finalTitleLabel,
withString: self.finalTitleLabel.stringValue as NSString,
minSize: 1,
maxSize: 60)
finalSubtitleLabel.font =
self.calculateFont(toFit: self.finalSubtitleLabel,
withString: self.finalSubtitleLabel.stringValue as NSString,
minSize: 1,
maxSize: 40)
finalTitleLabel.textColor = newBannerModel.contentColor
finalSubtitleLabel.textColor = newBannerModel.contentColor
finalNewBanner.setBackgroundColor(withColors: newBannerModel.backgroundColor)
finalNewBanner.layout()
finalNewBanner.layer?.setNeedsDisplay()
}
func saveFinalNewBanner(withURL fileUrl: URL) {
finalNewBanner.isHidden = false
let image = finalNewBanner.image()
finalNewBanner.removeFromSuperview()
// write to it
if image.savePNG(to: fileUrl) {
saveModelBanner()
}
let bannersVC = self.presenting as! ViewController
bannersVC.bannersCollection.reloadData()
self.dismiss(nil)
bannersVC.resizeWindow(withCreateBannerSize: bannersVC.view.bounds)
}
func saveModelBanner() {
BannersDefaults.save(banner: newBannerModel,
forKey: .banners)
}
func allowFolderForSaving()
{
let savePanel = NSSavePanel()
savePanel.canCreateDirectories = true
savePanel.allowedFileTypes = ["png"]
savePanel.beginSheetModal(for: self.view.window!) { (result) in
if result == NSFileHandlingPanelOKButton
{
let fileUrl = savePanel.url
if let rightURL = fileUrl {
self.saveFinalNewBanner(withURL: rightURL)
}
}
}
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/IconsCollectionModel.swift
//
// IconsCollectionModel.swift
// SocialBannersApp
//
// Created by <NAME> on 13.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class IconsCollectionModel: NSObject {
fileprivate(set) var numberOfSections = 1
fileprivate(set) var numberOfItems = 25 // Default
}
<file_sep>/SocialBannersApp/SocialBannersApp/SelectContentColorController.swift
//
// SelectContentColorController.swift
// SocialBannersApp
//
// Created by <NAME> on 20.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class SelectContentColorController: NSViewController, NSCollectionViewDataSource, NSCollectionViewDelegate {
// MARK: - IBOutlet's
@IBOutlet weak var colorScrollView: NSScrollView!
@IBOutlet weak var colorCollection: NSCollectionView!
// MARK: - Private Variables
let backgroundColors = AppContents.getContentColor()
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
colorCollection.frame = colorScrollView.bounds
// Do view setup here.
}
override func viewWillAppear() {
super.viewWillAppear()
self.view.window?.styleMask.remove(.resizable)
}
// MARK: - NSCollectionViewDataSource
public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
public func numberOfSections(in collectionView: NSCollectionView) -> Int {
return backgroundColors.count / 3
}
public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: "ContentColorBannerCollectionItem",
for: indexPath)
guard let collectionViewItem = item as? ContentColorBannerCollectionItem else {
return item
}
let colorModel = backgroundColors[indexPath.item+indexPath.section*3]
collectionViewItem.view.layer?.backgroundColor = colorModel.fillColor?.cgColor
return item
}
// MARK: - NSCollectionViewDelegate
public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
for indexPath in indexPaths {
let colorModel = backgroundColors[indexPath.item+indexPath.section*3]
let addNewBannerVC = self.presenting as! CreateNewBannerViewController
addNewBannerVC.newBannerModel.contentColorName = colorModel.name
addNewBannerVC.contentColorLabel.stringValue = colorModel.name
addNewBannerVC.newBannerModel.contentColor = colorModel.fillColor!
addNewBannerVC.contentColorView.layer?.backgroundColor = colorModel.fillColor?.cgColor
addNewBannerVC.updateNBContentColor(withContentColor: colorModel.fillColor!)
addNewBannerVC.imageForNewBannerView.layer?.setNeedsDisplay()
self.dismiss(nil)
}
}
// MARK: - Actions
@IBAction func backToCreateBunnerAction(_ sender: Any) {
self.dismiss(sender)
}
// MARK: - Configure CollectionView
fileprivate func configureCollectionView() {
let flowLayout = NSCollectionViewFlowLayout()
flowLayout.itemSize = NSSize(width: 60.0, height: 60.0)
flowLayout.sectionInset = EdgeInsets(top: 0, left: 78.5, bottom: 10.0, right: 78.5)
flowLayout.minimumInteritemSpacing = 10.0
flowLayout.minimumLineSpacing = 25.0
flowLayout.scrollDirection = .vertical
colorCollection.collectionViewLayout = flowLayout
view.wantsLayer = true
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/TypeTitleForNewBannerView.swift
//
// TypeTitleForNewBannerView.swift
// SocialBannersApp
//
// Created by <NAME> on 14.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class TypeTitleForNewBannerView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
self.layer?.cornerRadius = 4
self.layer?.backgroundColor = NSColor.white.cgColor
self.layer?.opacity = 0.3
// Drawing code here.
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/SelectBackgroundColorController.swift
//
// SelectBackgroundColorController.swift
// SocialBannersApp
//
// Created by <NAME> on 18.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class SelectBackgroundColorController: NSViewController, NSCollectionViewDataSource, NSCollectionViewDelegate {
// MARK: - IBOutlet's
@IBOutlet weak var colorCollection: NSCollectionView!
@IBOutlet weak var colorScrollView: NSScrollView!
// MARK: - Private Variables
let backgroundColors = AppContents.getBackgroundColors()
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
colorCollection.frame = colorScrollView.bounds
// Do view setup here.
}
override func viewWillAppear() {
super.viewWillAppear()
self.view.window?.styleMask.remove(.resizable)
}
// MARK: - NSCollectionViewDataSource
public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
public func numberOfSections(in collectionView: NSCollectionView) -> Int {
return backgroundColors.count / 3
}
public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: "BgColorBannerCollectionItem",
for: indexPath)
guard let collectionViewItem = item as? BgColorBannerCollectionItem else {
return item
}
let bgColorView = collectionViewItem.view as! BGColorView
let gradientModel = backgroundColors[indexPath.item+indexPath.section*3]
if let bgColor = gradientModel.fillColor {
bgColorView.setBackgroundColor(withColors: [bgColor.cgColor, bgColor.cgColor])
} else {
bgColorView.setBackgroundColor(withColors: [gradientModel.firstGradientColor!.cgColor, gradientModel.secondGradientColor!.cgColor])
}
return item
}
// MARK: - NSCollectionViewDelegate
public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
for indexPath in indexPaths {
guard let item = collectionView.item(at: indexPath) else {continue}
let gradientModel = backgroundColors[indexPath.item+indexPath.section*3]
let gradientColor = (item.view as! BGColorView).backgroundColors
let addNewBannerVC = self.presenting as! CreateNewBannerViewController
addNewBannerVC.newBannerModel.backgroundColor = gradientColor
addNewBannerVC.newBannerView.setBackgroundColor(withColors: gradientColor)
addNewBannerVC.newBannerModel.bgColorName = gradientModel.name
addNewBannerVC.bgColorLabel.stringValue = gradientModel.name
addNewBannerVC.bgColorView.setBackgroundColor(withColors: gradientColor)
self.dismiss(nil)
}
}
// MARK: - Actions
@IBAction func backToAddNewBannerAction(_ sender: Any) {
//let addNewBannerVC = self.presenting as! CreateNewBannerViewController
self.dismiss(sender)
}
// MARK: - Configure CollectionView
fileprivate func configureCollectionView() {
let flowLayout = NSCollectionViewFlowLayout()
flowLayout.itemSize = NSSize(width: 60.0, height: 60.0)
flowLayout.sectionInset = EdgeInsets(top: 0, left: 78.5, bottom: 10.0, right: 78.5)
flowLayout.minimumInteritemSpacing = 10.0
flowLayout.minimumLineSpacing = 25.0
flowLayout.scrollDirection = .vertical
colorCollection.collectionViewLayout = flowLayout
view.wantsLayer = true
}
}
<file_sep>/README.md
# Social Banners: Design of Posts (macOS)
Developer: <NAME> (https://github.com/Semty)
Designer: <NAME> (https://github.com/IvanVorobei)
<img src="http://telegra.ph/file/ab4589c3caa1a76e5cc7a.png" width="45%"></img> <img src="http://telegra.ph/file/845a6bfd37d1937cb2014.png" width="45%"></img> <img src="http://telegra.ph/file/9910270408620e6e924c3.png" width="45%"></img> <img src="http://telegra.ph/file/37ca9b02ef0f4f5dce225.png" width="45%"></img>
The application allows you to make posts on social platforms more visible and unique!
It's no secret that a monotonous text is often scrolled through the feed, without even being read.
There is an easy way to draw attention to a publication on VK/Twitter or Facebook – attach a banner with a catchy title and vivid colors!
With our application you will have a lot of colors available, along with a large custom field and a huge number of combinations of visual features. Such banner will definitely stand out!
Enhance the loyalty of your subscribers with the help of our application!
App Store: https://itunes.apple.com/ru/app/social-banners-design-of-posts/id1252245526?l=en&mt=12.
<file_sep>/SocialBannersApp/SocialBannersApp/ChangeButton.swift
//
// ChangeButton.swift
// SocialBannersApp
//
// Created by <NAME> on 17.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class ChangeButton: NSButton {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
self.layer?.cornerRadius = 4
self.layer?.backgroundColor = .white
let titleColor =
NSColor(red: 0.10980392,
green: 0.55686275,
blue: 0.8745098,
alpha: 1.0)
let pstyle = NSMutableParagraphStyle()
pstyle.alignment = .center
let titleFont = NSFont(name: "Avenir Next Medium",
size: 12)
self.attributedTitle = NSAttributedString(string: Translation.changeString,
attributes: [NSFontAttributeName: titleFont!,NSForegroundColorAttributeName: titleColor, NSParagraphStyleAttributeName: pstyle])
NSView.setShadowFor(view: self)
// Drawing code here.
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/AddBannerButton.swift
//
// AddBannerButton.swift
// SocialBannersApp
//
// Created by <NAME> on 28.05.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class AddBannerButton: NSButton {
var gradientLayer = CAGradientLayer()
var verLinePlusLayer = CAShapeLayer()
var horLinePlusLayer = CAShapeLayer()
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if gradientLayer.superlayer == nil {
setBackgroundLayer()
self.layer?.cornerRadius = dirtyRect.size.height / 2
self.gradientLayer.cornerRadius = dirtyRect.size.height / 2
}
NSView.setShadowFor(view: self)
// Drawing code here.
}
func setBackgroundLayer() {
// Creation Background Color (Gradient)
let firstGradientColor = CGColor.init(red: 0.10196078,
green: 0.83921569,
blue: 0.99215686,
alpha: 1.0)
let secondDradientColor = CGColor.init(red: 0.11372549,
green: 0.38431373,
blue: 0.94117647,
alpha: 1)
gradientLayer = createGradientLayer(withFirstColor: secondDradientColor,
secondColor: firstGradientColor,
andFrame: self.bounds)
self.layer?.addSublayer(gradientLayer)
// Creation Plus on the Button
let width: CGFloat = 1.35
verLinePlusLayer.path =
CGPath(roundedRect: CGRect.init(x: self.bounds.size.width / 2 - width/2,
y: self.bounds.size.height / 4,
width: width,
height: self.bounds.size.height / 2),
cornerWidth: 0.2,
cornerHeight: 0.2,
transform: nil)
horLinePlusLayer.path =
CGPath(roundedRect: CGRect.init(x: self.bounds.size.height / 4,
y: self.bounds.size.width / 2 - width/2,
width: self.bounds.size.height / 2,
height: width),
cornerWidth: 0.2,
cornerHeight: 0.2,
transform: nil)
verLinePlusLayer.strokeColor = .white
verLinePlusLayer.fillColor = .white
horLinePlusLayer.strokeColor = .white
horLinePlusLayer.fillColor = .white
self.layer?.addSublayer(verLinePlusLayer)
self.layer?.addSublayer(horLinePlusLayer)
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/BannersIconsBezierPaths.swift
//
// BannersIconsBezierPaths.swift
// SocialBanners
//
// Created by IvanVorobei on 6/17/17.
// Copyright © 2017 IvanVorobei. All rights reserved.
//
// Generated by PaintCode
// http://www.paintcodeapp.com
//
import Cocoa
public class BannersIconsBezierPaths : NSObject {
//// Cache
private struct Cache {
static let baseColor: NSColor = NSColor(red: 0.078, green: 0.671, blue: 0.984, alpha: 1)
}
//// Colors
public dynamic class var baseColor: NSColor { return Cache.baseColor }
//// Drawing Methods
public dynamic class func drawDoc(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 66.88, y: 49.74))
bezierPath.line(to: NSPoint(x: 34.12, y: 49.74))
bezierPath.curve(to: NSPoint(x: 31.38, y: 47.01), controlPoint1: NSPoint(x: 32.61, y: 49.74), controlPoint2: NSPoint(x: 31.38, y: 48.52))
bezierPath.curve(to: NSPoint(x: 34.12, y: 44.27), controlPoint1: NSPoint(x: 31.38, y: 45.49), controlPoint2: NSPoint(x: 32.61, y: 44.27))
bezierPath.line(to: NSPoint(x: 66.88, y: 44.27))
bezierPath.curve(to: NSPoint(x: 69.62, y: 47.01), controlPoint1: NSPoint(x: 68.39, y: 44.27), controlPoint2: NSPoint(x: 69.62, y: 45.49))
bezierPath.curve(to: NSPoint(x: 66.88, y: 49.74), controlPoint1: NSPoint(x: 69.62, y: 48.52), controlPoint2: NSPoint(x: 68.39, y: 49.74))
bezierPath.line(to: NSPoint(x: 66.88, y: 49.74))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 66.88, y: 33.34))
bezierPath.line(to: NSPoint(x: 34.12, y: 33.34))
bezierPath.curve(to: NSPoint(x: 31.38, y: 30.6), controlPoint1: NSPoint(x: 32.61, y: 33.34), controlPoint2: NSPoint(x: 31.38, y: 32.11))
bezierPath.curve(to: NSPoint(x: 34.12, y: 27.87), controlPoint1: NSPoint(x: 31.38, y: 29.09), controlPoint2: NSPoint(x: 32.61, y: 27.87))
bezierPath.line(to: NSPoint(x: 66.88, y: 27.87))
bezierPath.curve(to: NSPoint(x: 69.62, y: 30.6), controlPoint1: NSPoint(x: 68.39, y: 27.87), controlPoint2: NSPoint(x: 69.62, y: 29.09))
bezierPath.curve(to: NSPoint(x: 66.88, y: 33.34), controlPoint1: NSPoint(x: 69.62, y: 32.11), controlPoint2: NSPoint(x: 68.39, y: 33.34))
bezierPath.line(to: NSPoint(x: 66.88, y: 33.34))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 69.62, y: 71.61))
bezierPath.curve(to: NSPoint(x: 64.15, y: 77.08), controlPoint1: NSPoint(x: 66.6, y: 71.61), controlPoint2: NSPoint(x: 64.15, y: 74.06))
bezierPath.line(to: NSPoint(x: 64.15, y: 88.02))
bezierPath.line(to: NSPoint(x: 80.54, y: 71.61))
bezierPath.line(to: NSPoint(x: 69.62, y: 71.61))
bezierPath.line(to: NSPoint(x: 69.62, y: 71.61))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 80.54, y: 16.93))
bezierPath.curve(to: NSPoint(x: 75.08, y: 11.46), controlPoint1: NSPoint(x: 80.54, y: 13.91), controlPoint2: NSPoint(x: 78.09, y: 11.46))
bezierPath.line(to: NSPoint(x: 25.92, y: 11.46))
bezierPath.curve(to: NSPoint(x: 20.46, y: 16.93), controlPoint1: NSPoint(x: 22.91, y: 11.46), controlPoint2: NSPoint(x: 20.46, y: 13.91))
bezierPath.line(to: NSPoint(x: 20.46, y: 82.55))
bezierPath.curve(to: NSPoint(x: 25.92, y: 88.02), controlPoint1: NSPoint(x: 20.46, y: 85.57), controlPoint2: NSPoint(x: 22.91, y: 88.02))
bezierPath.line(to: NSPoint(x: 58.62, y: 88.02))
bezierPath.curve(to: NSPoint(x: 58.69, y: 77.08), controlPoint1: NSPoint(x: 58.57, y: 81.47), controlPoint2: NSPoint(x: 58.69, y: 77.08))
bezierPath.curve(to: NSPoint(x: 69.62, y: 66.14), controlPoint1: NSPoint(x: 58.69, y: 71.04), controlPoint2: NSPoint(x: 63.58, y: 66.14))
bezierPath.line(to: NSPoint(x: 80.54, y: 66.14))
bezierPath.line(to: NSPoint(x: 80.54, y: 16.93))
bezierPath.line(to: NSPoint(x: 80.54, y: 16.93))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 64.15, y: 93.49))
bezierPath.line(to: NSPoint(x: 64.15, y: 93.41))
bezierPath.curve(to: NSPoint(x: 58.69, y: 93.49), controlPoint1: NSPoint(x: 63.8, y: 93.41), controlPoint2: NSPoint(x: 62.35, y: 93.54))
bezierPath.line(to: NSPoint(x: 25.92, y: 93.49))
bezierPath.curve(to: NSPoint(x: 15, y: 82.55), controlPoint1: NSPoint(x: 19.89, y: 93.49), controlPoint2: NSPoint(x: 15, y: 88.59))
bezierPath.line(to: NSPoint(x: 15, y: 16.93))
bezierPath.curve(to: NSPoint(x: 25.92, y: 5.99), controlPoint1: NSPoint(x: 15, y: 10.89), controlPoint2: NSPoint(x: 19.89, y: 5.99))
bezierPath.line(to: NSPoint(x: 75.08, y: 5.99))
bezierPath.curve(to: NSPoint(x: 86, y: 16.93), controlPoint1: NSPoint(x: 81.11, y: 5.99), controlPoint2: NSPoint(x: 86, y: 10.89))
bezierPath.line(to: NSPoint(x: 86, y: 71.61))
bezierPath.line(to: NSPoint(x: 64.15, y: 93.49))
bezierPath.line(to: NSPoint(x: 64.15, y: 93.49))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawPainter(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 92.23, y: 84.08))
bezierPath.curve(to: NSPoint(x: 92.41, y: 83.94), controlPoint1: NSPoint(x: 92.26, y: 84), controlPoint2: NSPoint(x: 92.33, y: 83.95))
bezierPath.curve(to: NSPoint(x: 92.63, y: 84.03), controlPoint1: NSPoint(x: 92.5, y: 83.93), controlPoint2: NSPoint(x: 92.58, y: 83.96))
bezierPath.curve(to: NSPoint(x: 85.71, y: 79.6), controlPoint1: NSPoint(x: 91.03, y: 81.8), controlPoint2: NSPoint(x: 89.5, y: 80.95))
bezierPath.curve(to: NSPoint(x: 79.83, y: 76.78), controlPoint1: NSPoint(x: 82.82, y: 78.58), controlPoint2: NSPoint(x: 81.53, y: 78))
bezierPath.curve(to: NSPoint(x: 76.57, y: 70.18), controlPoint1: NSPoint(x: 77.17, y: 74.88), controlPoint2: NSPoint(x: 76.02, y: 72.42))
bezierPath.line(to: NSPoint(x: 76.74, y: 69.47))
bezierPath.line(to: NSPoint(x: 76.3, y: 68.89))
bezierPath.line(to: NSPoint(x: 76.22, y: 68.8))
bezierPath.line(to: NSPoint(x: 74.96, y: 67.17))
bezierPath.line(to: NSPoint(x: 73.79, y: 68.86))
bezierPath.curve(to: NSPoint(x: 69.71, y: 73.88), controlPoint1: NSPoint(x: 72.53, y: 70.69), controlPoint2: NSPoint(x: 71.16, y: 72.37))
bezierPath.curve(to: NSPoint(x: 43.81, y: 85.46), controlPoint1: NSPoint(x: 62.95, y: 80.9), controlPoint2: NSPoint(x: 53.51, y: 85.13))
bezierPath.curve(to: NSPoint(x: 42.51, y: 85.49), controlPoint1: NSPoint(x: 43.37, y: 85.48), controlPoint2: NSPoint(x: 42.94, y: 85.49))
bezierPath.curve(to: NSPoint(x: 14.06, y: 72.24), controlPoint1: NSPoint(x: 31.69, y: 85.49), controlPoint2: NSPoint(x: 21.32, y: 80.66))
bezierPath.curve(to: NSPoint(x: 5.29, y: 42.35), controlPoint1: NSPoint(x: 6.85, y: 63.86), controlPoint2: NSPoint(x: 3.65, y: 52.97))
bezierPath.curve(to: NSPoint(x: 5.8, y: 39.68), controlPoint1: NSPoint(x: 5.43, y: 41.46), controlPoint2: NSPoint(x: 5.6, y: 40.56))
bezierPath.curve(to: NSPoint(x: 24.33, y: 15.37), controlPoint1: NSPoint(x: 8.47, y: 27.98), controlPoint2: NSPoint(x: 15.24, y: 19.14))
bezierPath.curve(to: NSPoint(x: 30.82, y: 14.01), controlPoint1: NSPoint(x: 26.51, y: 14.47), controlPoint2: NSPoint(x: 28.69, y: 14.01))
bezierPath.curve(to: NSPoint(x: 43.4, y: 21.72), controlPoint1: NSPoint(x: 36.07, y: 14.01), controlPoint2: NSPoint(x: 40.63, y: 16.8))
bezierPath.curve(to: NSPoint(x: 45.44, y: 27.5), controlPoint1: NSPoint(x: 44.47, y: 23.61), controlPoint2: NSPoint(x: 45.15, y: 25.56))
bezierPath.curve(to: NSPoint(x: 45.37, y: 30.82), controlPoint1: NSPoint(x: 45.56, y: 28.38), controlPoint2: NSPoint(x: 45.54, y: 29.15))
bezierPath.curve(to: NSPoint(x: 45.36, y: 30.87), controlPoint1: NSPoint(x: 45.37, y: 30.84), controlPoint2: NSPoint(x: 45.37, y: 30.84))
bezierPath.curve(to: NSPoint(x: 45.25, y: 34.39), controlPoint1: NSPoint(x: 45.19, y: 32.61), controlPoint2: NSPoint(x: 45.15, y: 33.37))
bezierPath.curve(to: NSPoint(x: 45.32, y: 34.89), controlPoint1: NSPoint(x: 45.27, y: 34.55), controlPoint2: NSPoint(x: 45.29, y: 34.72))
bezierPath.curve(to: NSPoint(x: 51.94, y: 40.52), controlPoint1: NSPoint(x: 45.87, y: 38.35), controlPoint2: NSPoint(x: 48.42, y: 40.52))
bezierPath.curve(to: NSPoint(x: 54.8, y: 40.07), controlPoint1: NSPoint(x: 52.89, y: 40.52), controlPoint2: NSPoint(x: 53.85, y: 40.37))
bezierPath.line(to: NSPoint(x: 56.54, y: 39.51))
bezierPath.line(to: NSPoint(x: 55.66, y: 37.91))
bezierPath.curve(to: NSPoint(x: 53.14, y: 33.07), controlPoint1: NSPoint(x: 54.74, y: 36.22), controlPoint2: NSPoint(x: 53.89, y: 34.59))
bezierPath.curve(to: NSPoint(x: 49.99, y: 25.38), controlPoint1: NSPoint(x: 51.59, y: 29.92), controlPoint2: NSPoint(x: 50.53, y: 27.32))
bezierPath.curve(to: NSPoint(x: 49.81, y: 24.71), controlPoint1: NSPoint(x: 49.91, y: 25.07), controlPoint2: NSPoint(x: 49.86, y: 24.92))
bezierPath.curve(to: NSPoint(x: 49.56, y: 22.59), controlPoint1: NSPoint(x: 49.62, y: 23.92), controlPoint2: NSPoint(x: 49.53, y: 23.21))
bezierPath.curve(to: NSPoint(x: 50.39, y: 20.82), controlPoint1: NSPoint(x: 49.61, y: 21.75), controlPoint2: NSPoint(x: 49.87, y: 21.19))
bezierPath.curve(to: NSPoint(x: 51.86, y: 20.56), controlPoint1: NSPoint(x: 50.78, y: 20.55), controlPoint2: NSPoint(x: 51.29, y: 20.46))
bezierPath.curve(to: NSPoint(x: 54.27, y: 21.75), controlPoint1: NSPoint(x: 52.52, y: 20.68), controlPoint2: NSPoint(x: 53.09, y: 20.92))
bezierPath.curve(to: NSPoint(x: 61.96, y: 29.19), controlPoint1: NSPoint(x: 56.17, y: 23.1), controlPoint2: NSPoint(x: 58.7, y: 25.49))
bezierPath.curve(to: NSPoint(x: 68.32, y: 36.94), controlPoint1: NSPoint(x: 63.95, y: 31.45), controlPoint2: NSPoint(x: 66.09, y: 34.05))
bezierPath.line(to: NSPoint(x: 68.6, y: 37.3))
bezierPath.line(to: NSPoint(x: 69.04, y: 37.44))
bezierPath.curve(to: NSPoint(x: 79.54, y: 48.67), controlPoint1: NSPoint(x: 74.34, y: 39.22), controlPoint2: NSPoint(x: 78.46, y: 43.65))
bezierPath.curve(to: NSPoint(x: 79.88, y: 52.73), controlPoint1: NSPoint(x: 79.81, y: 49.94), controlPoint2: NSPoint(x: 79.92, y: 51.3))
bezierPath.line(to: NSPoint(x: 79.86, y: 53.2))
bezierPath.line(to: NSPoint(x: 80.12, y: 53.6))
bezierPath.curve(to: NSPoint(x: 86.06, y: 63.33), controlPoint1: NSPoint(x: 82.27, y: 56.92), controlPoint2: NSPoint(x: 84.16, y: 60.01))
bezierPath.curve(to: NSPoint(x: 86.13, y: 63.46), controlPoint1: NSPoint(x: 86.08, y: 63.37), controlPoint2: NSPoint(x: 86.1, y: 63.41))
bezierPath.line(to: NSPoint(x: 86.43, y: 64.07))
bezierPath.line(to: NSPoint(x: 87.08, y: 64.25))
bezierPath.curve(to: NSPoint(x: 92.69, y: 69.35), controlPoint1: NSPoint(x: 89.41, y: 64.88), controlPoint2: NSPoint(x: 91.46, y: 66.73))
bezierPath.curve(to: NSPoint(x: 92.23, y: 84.08), controlPoint1: NSPoint(x: 94.55, y: 73.35), controlPoint2: NSPoint(x: 94.41, y: 78.58))
bezierPath.line(to: NSPoint(x: 92.23, y: 84.08))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 95.03, y: 85.19))
bezierPath.curve(to: NSPoint(x: 95.42, y: 68.08), controlPoint1: NSPoint(x: 97.5, y: 78.96), controlPoint2: NSPoint(x: 97.66, y: 72.89))
bezierPath.curve(to: NSPoint(x: 87.87, y: 61.34), controlPoint1: NSPoint(x: 93.84, y: 64.68), controlPoint2: NSPoint(x: 91.1, y: 62.22))
bezierPath.line(to: NSPoint(x: 87.48, y: 62.79))
bezierPath.line(to: NSPoint(x: 88.83, y: 62.12))
bezierPath.curve(to: NSPoint(x: 88.68, y: 61.84), controlPoint1: NSPoint(x: 88.78, y: 62.02), controlPoint2: NSPoint(x: 88.73, y: 61.93))
bezierPath.curve(to: NSPoint(x: 82.65, y: 51.96), controlPoint1: NSPoint(x: 86.75, y: 58.47), controlPoint2: NSPoint(x: 84.83, y: 55.33))
bezierPath.line(to: NSPoint(x: 82.89, y: 52.83))
bezierPath.curve(to: NSPoint(x: 82.49, y: 48.04), controlPoint1: NSPoint(x: 82.95, y: 51.17), controlPoint2: NSPoint(x: 82.81, y: 49.55))
bezierPath.curve(to: NSPoint(x: 70, y: 34.59), controlPoint1: NSPoint(x: 81.18, y: 41.95), controlPoint2: NSPoint(x: 76.29, y: 36.7))
bezierPath.line(to: NSPoint(x: 70.71, y: 35.09))
bezierPath.curve(to: NSPoint(x: 64.23, y: 27.2), controlPoint1: NSPoint(x: 68.44, y: 32.16), controlPoint2: NSPoint(x: 66.26, y: 29.51))
bezierPath.curve(to: NSPoint(x: 56.01, y: 19.29), controlPoint1: NSPoint(x: 60.82, y: 23.33), controlPoint2: NSPoint(x: 58.13, y: 20.79))
bezierPath.curve(to: NSPoint(x: 52.41, y: 17.6), controlPoint1: NSPoint(x: 54.47, y: 18.21), controlPoint2: NSPoint(x: 53.49, y: 17.8))
bezierPath.curve(to: NSPoint(x: 48.67, y: 18.35), controlPoint1: NSPoint(x: 51.07, y: 17.35), controlPoint2: NSPoint(x: 49.74, y: 17.61))
bezierPath.curve(to: NSPoint(x: 46.55, y: 22.42), controlPoint1: NSPoint(x: 47.3, y: 19.3), controlPoint2: NSPoint(x: 46.64, y: 20.73))
bezierPath.curve(to: NSPoint(x: 46.88, y: 25.42), controlPoint1: NSPoint(x: 46.5, y: 23.4), controlPoint2: NSPoint(x: 46.63, y: 24.37))
bezierPath.curve(to: NSPoint(x: 47.09, y: 26.19), controlPoint1: NSPoint(x: 46.94, y: 25.67), controlPoint2: NSPoint(x: 46.99, y: 25.85))
bezierPath.curve(to: NSPoint(x: 50.44, y: 34.4), controlPoint1: NSPoint(x: 47.69, y: 28.33), controlPoint2: NSPoint(x: 48.81, y: 31.09))
bezierPath.curve(to: NSPoint(x: 53.02, y: 39.35), controlPoint1: NSPoint(x: 51.2, y: 35.96), controlPoint2: NSPoint(x: 52.07, y: 37.62))
bezierPath.line(to: NSPoint(x: 54.34, y: 38.63))
bezierPath.line(to: NSPoint(x: 53.88, y: 37.19))
bezierPath.curve(to: NSPoint(x: 51.94, y: 37.51), controlPoint1: NSPoint(x: 53.22, y: 37.4), controlPoint2: NSPoint(x: 52.57, y: 37.51))
bezierPath.curve(to: NSPoint(x: 48.3, y: 34.41), controlPoint1: NSPoint(x: 49.9, y: 37.51), controlPoint2: NSPoint(x: 48.62, y: 36.41))
bezierPath.curve(to: NSPoint(x: 48.25, y: 34.08), controlPoint1: NSPoint(x: 48.28, y: 34.3), controlPoint2: NSPoint(x: 48.27, y: 34.19))
bezierPath.curve(to: NSPoint(x: 48.36, y: 31.17), controlPoint1: NSPoint(x: 48.18, y: 33.33), controlPoint2: NSPoint(x: 48.21, y: 32.71))
bezierPath.curve(to: NSPoint(x: 48.37, y: 31.12), controlPoint1: NSPoint(x: 48.37, y: 31.14), controlPoint2: NSPoint(x: 48.37, y: 31.14))
bezierPath.curve(to: NSPoint(x: 48.42, y: 27.07), controlPoint1: NSPoint(x: 48.56, y: 29.2), controlPoint2: NSPoint(x: 48.59, y: 28.26))
bezierPath.curve(to: NSPoint(x: 46.03, y: 20.25), controlPoint1: NSPoint(x: 48.08, y: 24.75), controlPoint2: NSPoint(x: 47.27, y: 22.45))
bezierPath.curve(to: NSPoint(x: 30.82, y: 11), controlPoint1: NSPoint(x: 42.74, y: 14.39), controlPoint2: NSPoint(x: 37.18, y: 11))
bezierPath.curve(to: NSPoint(x: 23.17, y: 12.59), controlPoint1: NSPoint(x: 28.29, y: 11), controlPoint2: NSPoint(x: 25.71, y: 11.54))
bezierPath.curve(to: NSPoint(x: 2.86, y: 39.01), controlPoint1: NSPoint(x: 13.12, y: 16.75), controlPoint2: NSPoint(x: 5.73, y: 26.41))
bezierPath.curve(to: NSPoint(x: 2.31, y: 41.9), controlPoint1: NSPoint(x: 2.64, y: 39.96), controlPoint2: NSPoint(x: 2.46, y: 40.93))
bezierPath.curve(to: NSPoint(x: 11.78, y: 74.2), controlPoint1: NSPoint(x: 0.54, y: 53.39), controlPoint2: NSPoint(x: 3.99, y: 65.17))
bezierPath.curve(to: NSPoint(x: 42.51, y: 88.5), controlPoint1: NSPoint(x: 19.6, y: 83.29), controlPoint2: NSPoint(x: 30.8, y: 88.5))
bezierPath.curve(to: NSPoint(x: 43.91, y: 88.48), controlPoint1: NSPoint(x: 42.98, y: 88.5), controlPoint2: NSPoint(x: 43.45, y: 88.49))
bezierPath.curve(to: NSPoint(x: 71.88, y: 75.97), controlPoint1: NSPoint(x: 54.4, y: 88.11), controlPoint2: NSPoint(x: 64.59, y: 83.55))
bezierPath.curve(to: NSPoint(x: 76.27, y: 70.58), controlPoint1: NSPoint(x: 73.44, y: 74.34), controlPoint2: NSPoint(x: 74.92, y: 72.53))
bezierPath.line(to: NSPoint(x: 75.03, y: 69.72))
bezierPath.line(to: NSPoint(x: 73.84, y: 70.65))
bezierPath.line(to: NSPoint(x: 73.92, y: 70.74))
bezierPath.line(to: NSPoint(x: 75.11, y: 69.82))
bezierPath.line(to: NSPoint(x: 73.64, y: 69.46))
bezierPath.curve(to: NSPoint(x: 78.08, y: 79.23), controlPoint1: NSPoint(x: 72.77, y: 73.01), controlPoint2: NSPoint(x: 74.48, y: 76.66))
bezierPath.curve(to: NSPoint(x: 84.7, y: 82.44), controlPoint1: NSPoint(x: 80.06, y: 80.65), controlPoint2: NSPoint(x: 81.56, y: 81.33))
bezierPath.curve(to: NSPoint(x: 90.17, y: 85.78), controlPoint1: NSPoint(x: 87.94, y: 83.59), controlPoint2: NSPoint(x: 89.04, y: 84.21))
bezierPath.curve(to: NSPoint(x: 92.78, y: 86.93), controlPoint1: NSPoint(x: 90.76, y: 86.61), controlPoint2: NSPoint(x: 91.76, y: 87.05))
bezierPath.curve(to: NSPoint(x: 95.03, y: 85.19), controlPoint1: NSPoint(x: 93.79, y: 86.8), controlPoint2: NSPoint(x: 94.66, y: 86.13))
bezierPath.line(to: NSPoint(x: 95.03, y: 85.19))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 63.58, y: 63))
bezierPath.curve(to: NSPoint(x: 57.68, y: 59.76), controlPoint1: NSPoint(x: 62.3, y: 60.98), controlPoint2: NSPoint(x: 60.09, y: 59.76))
bezierPath.curve(to: NSPoint(x: 53.98, y: 60.83), controlPoint1: NSPoint(x: 56.37, y: 59.76), controlPoint2: NSPoint(x: 55.09, y: 60.13))
bezierPath.curve(to: NSPoint(x: 50.9, y: 65.17), controlPoint1: NSPoint(x: 52.41, y: 61.82), controlPoint2: NSPoint(x: 51.31, y: 63.36))
bezierPath.curve(to: NSPoint(x: 51.8, y: 70.41), controlPoint1: NSPoint(x: 50.49, y: 66.97), controlPoint2: NSPoint(x: 50.81, y: 68.84))
bezierPath.curve(to: NSPoint(x: 57.69, y: 73.65), controlPoint1: NSPoint(x: 53.08, y: 72.43), controlPoint2: NSPoint(x: 55.29, y: 73.65))
bezierPath.curve(to: NSPoint(x: 61.4, y: 72.58), controlPoint1: NSPoint(x: 59.01, y: 73.65), controlPoint2: NSPoint(x: 60.29, y: 73.28))
bezierPath.curve(to: NSPoint(x: 64.48, y: 68.24), controlPoint1: NSPoint(x: 62.97, y: 71.59), controlPoint2: NSPoint(x: 64.07, y: 70.05))
bezierPath.curve(to: NSPoint(x: 63.58, y: 63), controlPoint1: NSPoint(x: 64.89, y: 66.44), controlPoint2: NSPoint(x: 64.57, y: 64.57))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 61.03, y: 64.61))
bezierPath.curve(to: NSPoint(x: 61.54, y: 67.58), controlPoint1: NSPoint(x: 61.59, y: 65.5), controlPoint2: NSPoint(x: 61.77, y: 66.55))
bezierPath.curve(to: NSPoint(x: 59.8, y: 70.03), controlPoint1: NSPoint(x: 61.31, y: 68.6), controlPoint2: NSPoint(x: 60.69, y: 69.47))
bezierPath.curve(to: NSPoint(x: 57.69, y: 70.64), controlPoint1: NSPoint(x: 59.16, y: 70.43), controlPoint2: NSPoint(x: 58.44, y: 70.64))
bezierPath.curve(to: NSPoint(x: 54.35, y: 68.8), controlPoint1: NSPoint(x: 56.32, y: 70.64), controlPoint2: NSPoint(x: 55.08, y: 69.95))
bezierPath.curve(to: NSPoint(x: 53.84, y: 65.84), controlPoint1: NSPoint(x: 53.79, y: 67.91), controlPoint2: NSPoint(x: 53.61, y: 66.86))
bezierPath.curve(to: NSPoint(x: 55.59, y: 63.38), controlPoint1: NSPoint(x: 54.07, y: 64.81), controlPoint2: NSPoint(x: 54.69, y: 63.94))
bezierPath.curve(to: NSPoint(x: 57.68, y: 62.77), controlPoint1: NSPoint(x: 56.22, y: 62.98), controlPoint2: NSPoint(x: 56.94, y: 62.77))
bezierPath.curve(to: NSPoint(x: 61.03, y: 64.61), controlPoint1: NSPoint(x: 59.06, y: 62.77), controlPoint2: NSPoint(x: 60.3, y: 63.46))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 68.14, y: 54.81))
bezierPath.curve(to: NSPoint(x: 76.64, y: 66.53), controlPoint1: NSPoint(x: 70.91, y: 58.87), controlPoint2: NSPoint(x: 73.85, y: 62.92))
bezierPath.line(to: NSPoint(x: 77.63, y: 67.82))
bezierPath.line(to: NSPoint(x: 78.84, y: 66.73))
bezierPath.curve(to: NSPoint(x: 80.19, y: 65.68), controlPoint1: NSPoint(x: 79.25, y: 66.37), controlPoint2: NSPoint(x: 79.7, y: 66.02))
bezierPath.curve(to: NSPoint(x: 82.63, y: 64.43), controlPoint1: NSPoint(x: 80.98, y: 65.13), controlPoint2: NSPoint(x: 81.8, y: 64.71))
bezierPath.line(to: NSPoint(x: 84.37, y: 63.83))
bezierPath.line(to: NSPoint(x: 83.44, y: 62.24))
bezierPath.curve(to: NSPoint(x: 75.48, y: 49.75), controlPoint1: NSPoint(x: 81.09, y: 58.23), controlPoint2: NSPoint(x: 78.55, y: 54.26))
bezierPath.curve(to: NSPoint(x: 60.72, y: 30.39), controlPoint1: NSPoint(x: 70.45, y: 42.36), controlPoint2: NSPoint(x: 65.21, y: 35.49))
bezierPath.curve(to: NSPoint(x: 54.21, y: 23.87), controlPoint1: NSPoint(x: 58.19, y: 27.52), controlPoint2: NSPoint(x: 55.96, y: 25.28))
bezierPath.line(to: NSPoint(x: 50.33, y: 20.75))
bezierPath.line(to: NSPoint(x: 51.82, y: 25.49))
bezierPath.curve(to: NSPoint(x: 55.52, y: 33.97), controlPoint1: NSPoint(x: 52.5, y: 27.65), controlPoint2: NSPoint(x: 53.76, y: 30.55))
bezierPath.curve(to: NSPoint(x: 68.14, y: 54.81), controlPoint1: NSPoint(x: 58.62, y: 40.01), controlPoint2: NSPoint(x: 63.1, y: 47.4))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 70.64, y: 53.11))
bezierPath.curve(to: NSPoint(x: 58.2, y: 32.59), controlPoint1: NSPoint(x: 65.66, y: 45.81), controlPoint2: NSPoint(x: 61.24, y: 38.51))
bezierPath.curve(to: NSPoint(x: 54.7, y: 24.59), controlPoint1: NSPoint(x: 56.52, y: 29.31), controlPoint2: NSPoint(x: 55.32, y: 26.56))
bezierPath.line(to: NSPoint(x: 52.31, y: 26.22))
bezierPath.curve(to: NSPoint(x: 58.45, y: 32.38), controlPoint1: NSPoint(x: 53.91, y: 27.5), controlPoint2: NSPoint(x: 56.03, y: 29.63))
bezierPath.curve(to: NSPoint(x: 72.99, y: 51.45), controlPoint1: NSPoint(x: 62.86, y: 37.38), controlPoint2: NSPoint(x: 68.02, y: 44.15))
bezierPath.curve(to: NSPoint(x: 80.84, y: 63.77), controlPoint1: NSPoint(x: 76.02, y: 55.9), controlPoint2: NSPoint(x: 78.52, y: 59.82))
bezierPath.line(to: NSPoint(x: 82.14, y: 63))
bezierPath.line(to: NSPoint(x: 81.65, y: 61.58))
bezierPath.curve(to: NSPoint(x: 78.47, y: 63.2), controlPoint1: NSPoint(x: 80.55, y: 61.96), controlPoint2: NSPoint(x: 79.48, y: 62.5))
bezierPath.curve(to: NSPoint(x: 76.83, y: 64.49), controlPoint1: NSPoint(x: 77.88, y: 63.61), controlPoint2: NSPoint(x: 77.33, y: 64.04))
bezierPath.line(to: NSPoint(x: 77.83, y: 65.61))
bezierPath.line(to: NSPoint(x: 79.03, y: 64.69))
bezierPath.curve(to: NSPoint(x: 70.64, y: 53.11), controlPoint1: NSPoint(x: 76.27, y: 61.13), controlPoint2: NSPoint(x: 73.37, y: 57.13))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 20.96, y: 52.49))
bezierPath.curve(to: NSPoint(x: 17.25, y: 53.56), controlPoint1: NSPoint(x: 19.65, y: 52.49), controlPoint2: NSPoint(x: 18.37, y: 52.86))
bezierPath.curve(to: NSPoint(x: 14.17, y: 57.89), controlPoint1: NSPoint(x: 15.68, y: 54.54), controlPoint2: NSPoint(x: 14.58, y: 56.09))
bezierPath.curve(to: NSPoint(x: 15.07, y: 63.13), controlPoint1: NSPoint(x: 13.76, y: 59.7), controlPoint2: NSPoint(x: 14.08, y: 61.56))
bezierPath.curve(to: NSPoint(x: 20.97, y: 66.37), controlPoint1: NSPoint(x: 16.35, y: 65.16), controlPoint2: NSPoint(x: 18.56, y: 66.37))
bezierPath.curve(to: NSPoint(x: 24.67, y: 65.31), controlPoint1: NSPoint(x: 22.28, y: 66.37), controlPoint2: NSPoint(x: 23.56, y: 66))
bezierPath.curve(to: NSPoint(x: 26.86, y: 55.73), controlPoint1: NSPoint(x: 27.92, y: 63.27), controlPoint2: NSPoint(x: 28.9, y: 58.97))
bezierPath.curve(to: NSPoint(x: 20.96, y: 52.49), controlPoint1: NSPoint(x: 25.57, y: 53.7), controlPoint2: NSPoint(x: 23.36, y: 52.49))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 20.96, y: 55.5))
bezierPath.curve(to: NSPoint(x: 24.31, y: 57.34), controlPoint1: NSPoint(x: 22.33, y: 55.5), controlPoint2: NSPoint(x: 23.58, y: 56.19))
bezierPath.curve(to: NSPoint(x: 23.07, y: 62.76), controlPoint1: NSPoint(x: 25.46, y: 59.17), controlPoint2: NSPoint(x: 24.91, y: 61.6))
bezierPath.curve(to: NSPoint(x: 20.97, y: 63.36), controlPoint1: NSPoint(x: 22.44, y: 63.15), controlPoint2: NSPoint(x: 21.71, y: 63.36))
bezierPath.curve(to: NSPoint(x: 17.62, y: 61.52), controlPoint1: NSPoint(x: 19.6, y: 63.36), controlPoint2: NSPoint(x: 18.35, y: 62.68))
bezierPath.curve(to: NSPoint(x: 17.11, y: 58.56), controlPoint1: NSPoint(x: 17.06, y: 60.63), controlPoint2: NSPoint(x: 16.88, y: 59.59))
bezierPath.curve(to: NSPoint(x: 18.86, y: 56.11), controlPoint1: NSPoint(x: 17.35, y: 57.53), controlPoint2: NSPoint(x: 17.96, y: 56.67))
bezierPath.curve(to: NSPoint(x: 20.96, y: 55.5), controlPoint1: NSPoint(x: 19.49, y: 55.71), controlPoint2: NSPoint(x: 20.22, y: 55.5))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 13.96, y: 42.83))
bezierPath.curve(to: NSPoint(x: 19.86, y: 46.07), controlPoint1: NSPoint(x: 15.24, y: 44.86), controlPoint2: NSPoint(x: 17.45, y: 46.07))
bezierPath.curve(to: NSPoint(x: 23.57, y: 45), controlPoint1: NSPoint(x: 21.17, y: 46.07), controlPoint2: NSPoint(x: 22.45, y: 45.7))
bezierPath.curve(to: NSPoint(x: 26.65, y: 40.67), controlPoint1: NSPoint(x: 25.14, y: 44.02), controlPoint2: NSPoint(x: 26.23, y: 42.47))
bezierPath.curve(to: NSPoint(x: 25.75, y: 35.43), controlPoint1: NSPoint(x: 27.06, y: 38.86), controlPoint2: NSPoint(x: 26.74, y: 36.99))
bezierPath.curve(to: NSPoint(x: 19.85, y: 32.18), controlPoint1: NSPoint(x: 24.47, y: 33.4), controlPoint2: NSPoint(x: 22.26, y: 32.18))
bezierPath.curve(to: NSPoint(x: 16.14, y: 33.25), controlPoint1: NSPoint(x: 18.54, y: 32.18), controlPoint2: NSPoint(x: 17.26, y: 32.55))
bezierPath.curve(to: NSPoint(x: 13.06, y: 37.59), controlPoint1: NSPoint(x: 14.57, y: 34.24), controlPoint2: NSPoint(x: 13.48, y: 35.78))
bezierPath.curve(to: NSPoint(x: 13.96, y: 42.83), controlPoint1: NSPoint(x: 12.65, y: 39.39), controlPoint2: NSPoint(x: 12.97, y: 41.26))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 16.51, y: 41.22))
bezierPath.curve(to: NSPoint(x: 16.01, y: 38.26), controlPoint1: NSPoint(x: 15.95, y: 40.33), controlPoint2: NSPoint(x: 15.77, y: 39.28))
bezierPath.curve(to: NSPoint(x: 17.75, y: 35.8), controlPoint1: NSPoint(x: 16.24, y: 37.23), controlPoint2: NSPoint(x: 16.86, y: 36.36))
bezierPath.curve(to: NSPoint(x: 19.85, y: 35.2), controlPoint1: NSPoint(x: 18.38, y: 35.41), controlPoint2: NSPoint(x: 19.11, y: 35.2))
bezierPath.curve(to: NSPoint(x: 23.2, y: 37.03), controlPoint1: NSPoint(x: 21.22, y: 35.2), controlPoint2: NSPoint(x: 22.47, y: 35.88))
bezierPath.curve(to: NSPoint(x: 23.71, y: 40), controlPoint1: NSPoint(x: 23.76, y: 37.92), controlPoint2: NSPoint(x: 23.94, y: 38.97))
bezierPath.curve(to: NSPoint(x: 21.96, y: 42.45), controlPoint1: NSPoint(x: 23.47, y: 41.02), controlPoint2: NSPoint(x: 22.85, y: 41.89))
bezierPath.curve(to: NSPoint(x: 19.86, y: 43.06), controlPoint1: NSPoint(x: 21.33, y: 42.85), controlPoint2: NSPoint(x: 20.6, y: 43.06))
bezierPath.curve(to: NSPoint(x: 16.51, y: 41.22), controlPoint1: NSPoint(x: 18.49, y: 43.06), controlPoint2: NSPoint(x: 17.24, y: 42.37))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 31.44, y: 75.11))
bezierPath.curve(to: NSPoint(x: 37.33, y: 78.36), controlPoint1: NSPoint(x: 32.72, y: 77.14), controlPoint2: NSPoint(x: 34.93, y: 78.36))
bezierPath.curve(to: NSPoint(x: 41.04, y: 77.29), controlPoint1: NSPoint(x: 38.65, y: 78.36), controlPoint2: NSPoint(x: 39.93, y: 77.99))
bezierPath.curve(to: NSPoint(x: 43.22, y: 67.71), controlPoint1: NSPoint(x: 44.29, y: 75.25), controlPoint2: NSPoint(x: 45.27, y: 70.95))
bezierPath.curve(to: NSPoint(x: 37.32, y: 64.47), controlPoint1: NSPoint(x: 41.94, y: 65.68), controlPoint2: NSPoint(x: 39.73, y: 64.47))
bezierPath.curve(to: NSPoint(x: 33.62, y: 65.54), controlPoint1: NSPoint(x: 36.01, y: 64.47), controlPoint2: NSPoint(x: 34.73, y: 64.84))
bezierPath.curve(to: NSPoint(x: 30.54, y: 69.87), controlPoint1: NSPoint(x: 32.05, y: 66.52), controlPoint2: NSPoint(x: 30.95, y: 68.07))
bezierPath.curve(to: NSPoint(x: 31.44, y: 75.11), controlPoint1: NSPoint(x: 30.13, y: 71.68), controlPoint2: NSPoint(x: 30.45, y: 73.55))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 33.99, y: 73.51))
bezierPath.curve(to: NSPoint(x: 33.48, y: 70.54), controlPoint1: NSPoint(x: 33.43, y: 72.62), controlPoint2: NSPoint(x: 33.25, y: 71.57))
bezierPath.curve(to: NSPoint(x: 35.22, y: 68.09), controlPoint1: NSPoint(x: 33.71, y: 69.52), controlPoint2: NSPoint(x: 34.33, y: 68.65))
bezierPath.curve(to: NSPoint(x: 37.32, y: 67.48), controlPoint1: NSPoint(x: 35.86, y: 67.69), controlPoint2: NSPoint(x: 36.58, y: 67.48))
bezierPath.curve(to: NSPoint(x: 40.67, y: 69.32), controlPoint1: NSPoint(x: 38.7, y: 67.48), controlPoint2: NSPoint(x: 39.94, y: 68.17))
bezierPath.curve(to: NSPoint(x: 39.43, y: 74.74), controlPoint1: NSPoint(x: 41.83, y: 71.15), controlPoint2: NSPoint(x: 41.27, y: 73.58))
bezierPath.curve(to: NSPoint(x: 37.33, y: 75.34), controlPoint1: NSPoint(x: 38.8, y: 75.13), controlPoint2: NSPoint(x: 38.08, y: 75.34))
bezierPath.curve(to: NSPoint(x: 33.99, y: 73.51), controlPoint1: NSPoint(x: 35.96, y: 75.34), controlPoint2: NSPoint(x: 34.72, y: 74.66))
bezierPath.close()
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawPicture(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 29.5, y: 64.38))
bezierPath.curve(to: NSPoint(x: 24.38, y: 69.5), controlPoint1: NSPoint(x: 26.67, y: 64.38), controlPoint2: NSPoint(x: 24.38, y: 66.67))
bezierPath.curve(to: NSPoint(x: 29.5, y: 74.62), controlPoint1: NSPoint(x: 24.38, y: 72.33), controlPoint2: NSPoint(x: 26.67, y: 74.62))
bezierPath.curve(to: NSPoint(x: 34.62, y: 69.5), controlPoint1: NSPoint(x: 32.33, y: 74.62), controlPoint2: NSPoint(x: 34.62, y: 72.33))
bezierPath.curve(to: NSPoint(x: 29.5, y: 64.38), controlPoint1: NSPoint(x: 34.62, y: 66.67), controlPoint2: NSPoint(x: 32.33, y: 64.38))
bezierPath.line(to: NSPoint(x: 29.5, y: 64.38))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 29.5, y: 79.75))
bezierPath.curve(to: NSPoint(x: 19.25, y: 69.5), controlPoint1: NSPoint(x: 23.84, y: 79.75), controlPoint2: NSPoint(x: 19.25, y: 75.16))
bezierPath.curve(to: NSPoint(x: 29.5, y: 59.25), controlPoint1: NSPoint(x: 19.25, y: 63.84), controlPoint2: NSPoint(x: 23.84, y: 59.25))
bezierPath.curve(to: NSPoint(x: 39.75, y: 69.5), controlPoint1: NSPoint(x: 35.16, y: 59.25), controlPoint2: NSPoint(x: 39.75, y: 63.84))
bezierPath.curve(to: NSPoint(x: 29.5, y: 79.75), controlPoint1: NSPoint(x: 39.75, y: 75.16), controlPoint2: NSPoint(x: 35.16, y: 79.75))
bezierPath.line(to: NSPoint(x: 29.5, y: 79.75))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 85.88, y: 46.11))
bezierPath.line(to: NSPoint(x: 70.5, y: 61.81))
bezierPath.line(to: NSPoint(x: 45.03, y: 35.9))
bezierPath.line(to: NSPoint(x: 34.62, y: 46.44))
bezierPath.line(to: NSPoint(x: 14.12, y: 27.64))
bezierPath.line(to: NSPoint(x: 14.12, y: 79.75))
bezierPath.curve(to: NSPoint(x: 19.25, y: 84.88), controlPoint1: NSPoint(x: 14.12, y: 82.58), controlPoint2: NSPoint(x: 16.42, y: 84.88))
bezierPath.line(to: NSPoint(x: 80.75, y: 84.88))
bezierPath.curve(to: NSPoint(x: 85.88, y: 79.75), controlPoint1: NSPoint(x: 83.58, y: 84.88), controlPoint2: NSPoint(x: 85.88, y: 82.58))
bezierPath.line(to: NSPoint(x: 85.88, y: 46.11))
bezierPath.line(to: NSPoint(x: 85.88, y: 46.11))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 85.88, y: 18.25))
bezierPath.curve(to: NSPoint(x: 80.75, y: 13.12), controlPoint1: NSPoint(x: 85.88, y: 15.42), controlPoint2: NSPoint(x: 83.58, y: 13.12))
bezierPath.line(to: NSPoint(x: 67.51, y: 13.12))
bezierPath.line(to: NSPoint(x: 48.63, y: 32.25))
bezierPath.line(to: NSPoint(x: 70.5, y: 54.13))
bezierPath.line(to: NSPoint(x: 85.88, y: 38.75))
bezierPath.line(to: NSPoint(x: 85.88, y: 18.25))
bezierPath.line(to: NSPoint(x: 85.88, y: 18.25))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 19.25, y: 13.12))
bezierPath.curve(to: NSPoint(x: 14.12, y: 18.25), controlPoint1: NSPoint(x: 16.42, y: 13.12), controlPoint2: NSPoint(x: 14.12, y: 15.42))
bezierPath.line(to: NSPoint(x: 14.12, y: 20.66))
bezierPath.line(to: NSPoint(x: 34.48, y: 38.89))
bezierPath.line(to: NSPoint(x: 60.25, y: 13.12))
bezierPath.line(to: NSPoint(x: 19.25, y: 13.12))
bezierPath.line(to: NSPoint(x: 19.25, y: 13.12))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 80.75, y: 90))
bezierPath.line(to: NSPoint(x: 19.25, y: 90))
bezierPath.curve(to: NSPoint(x: 9, y: 79.75), controlPoint1: NSPoint(x: 13.59, y: 90), controlPoint2: NSPoint(x: 9, y: 85.41))
bezierPath.line(to: NSPoint(x: 9, y: 18.25))
bezierPath.curve(to: NSPoint(x: 19.25, y: 8), controlPoint1: NSPoint(x: 9, y: 12.59), controlPoint2: NSPoint(x: 13.59, y: 8))
bezierPath.line(to: NSPoint(x: 80.75, y: 8))
bezierPath.curve(to: NSPoint(x: 91, y: 18.25), controlPoint1: NSPoint(x: 86.41, y: 8), controlPoint2: NSPoint(x: 91, y: 12.59))
bezierPath.line(to: NSPoint(x: 91, y: 79.75))
bezierPath.curve(to: NSPoint(x: 80.75, y: 90), controlPoint1: NSPoint(x: 91, y: 85.41), controlPoint2: NSPoint(x: 86.41, y: 90))
bezierPath.line(to: NSPoint(x: 80.75, y: 90))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawDiagram(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 85.64, y: 33.7))
bezierPath.line(to: NSPoint(x: 46.89, y: 46.89))
bezierPath.line(to: NSPoint(x: 46.89, y: 89.78))
bezierPath.curve(to: NSPoint(x: 89.46, y: 48.12), controlPoint1: NSPoint(x: 69.13, y: 89.89), controlPoint2: NSPoint(x: 89.46, y: 70.67))
bezierPath.curve(to: NSPoint(x: 85.64, y: 33.7), controlPoint1: NSPoint(x: 89.46, y: 42.23), controlPoint2: NSPoint(x: 87.93, y: 37.77))
bezierPath.line(to: NSPoint(x: 85.64, y: 33.7))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 45.46, y: 9.72))
bezierPath.curve(to: NSPoint(x: 9.72, y: 45.46), controlPoint1: NSPoint(x: 25.72, y: 9.72), controlPoint2: NSPoint(x: 9.72, y: 25.72))
bezierPath.curve(to: NSPoint(x: 41.17, y: 81.2), controlPoint1: NSPoint(x: 9.72, y: 63.45), controlPoint2: NSPoint(x: 23.78, y: 78.69))
bezierPath.line(to: NSPoint(x: 41.17, y: 42.8))
bezierPath.line(to: NSPoint(x: 77.51, y: 30.15))
bezierPath.curve(to: NSPoint(x: 45.46, y: 9.72), controlPoint1: NSPoint(x: 72.68, y: 17.93), controlPoint2: NSPoint(x: 58.79, y: 9.72))
bezierPath.line(to: NSPoint(x: 45.46, y: 9.72))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 46.89, y: 95.5))
bezierPath.line(to: NSPoint(x: 41.17, y: 95.5))
bezierPath.line(to: NSPoint(x: 41.17, y: 86.92))
bezierPath.curve(to: NSPoint(x: 4, y: 45.46), controlPoint1: NSPoint(x: 20.36, y: 84.67), controlPoint2: NSPoint(x: 4, y: 66.83))
bezierPath.curve(to: NSPoint(x: 45.46, y: 4), controlPoint1: NSPoint(x: 4, y: 22.56), controlPoint2: NSPoint(x: 22.56, y: 4))
bezierPath.curve(to: NSPoint(x: 83.31, y: 28.6), controlPoint1: NSPoint(x: 62.35, y: 4), controlPoint2: NSPoint(x: 76.85, y: 14.11))
bezierPath.line(to: NSPoint(x: 89.78, y: 26.88))
bezierPath.curve(to: NSPoint(x: 95.5, y: 48.12), controlPoint1: NSPoint(x: 92.91, y: 32.01), controlPoint2: NSPoint(x: 95.5, y: 39.29))
bezierPath.curve(to: NSPoint(x: 46.89, y: 95.5), controlPoint1: NSPoint(x: 95.5, y: 74.29), controlPoint2: NSPoint(x: 72.64, y: 95.5))
bezierPath.line(to: NSPoint(x: 46.89, y: 95.5))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawBrush(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 84.52, y: 76.45))
bezierPath.line(to: NSPoint(x: 51.02, y: 43.37))
bezierPath.line(to: NSPoint(x: 47.33, y: 47.01))
bezierPath.line(to: NSPoint(x: 80.83, y: 80.1))
bezierPath.curve(to: NSPoint(x: 84.52, y: 80.1), controlPoint1: NSPoint(x: 81.85, y: 81.1), controlPoint2: NSPoint(x: 83.5, y: 81.1))
bezierPath.curve(to: NSPoint(x: 84.52, y: 76.45), controlPoint1: NSPoint(x: 85.54, y: 79.09), controlPoint2: NSPoint(x: 85.54, y: 77.46))
bezierPath.line(to: NSPoint(x: 84.52, y: 76.45))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 41.8, y: 34.26))
bezierPath.curve(to: NSPoint(x: 38.11, y: 37.9), controlPoint1: NSPoint(x: 41.46, y: 34.6), controlPoint2: NSPoint(x: 38.11, y: 37.9))
bezierPath.line(to: NSPoint(x: 43.64, y: 43.37))
bezierPath.line(to: NSPoint(x: 47.33, y: 39.72))
bezierPath.line(to: NSPoint(x: 41.8, y: 34.26))
bezierPath.line(to: NSPoint(x: 41.8, y: 34.26))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 36.26, y: 21.52))
bezierPath.curve(to: NSPoint(x: 15.22, y: 18.94), controlPoint1: NSPoint(x: 33.67, y: 19.1), controlPoint2: NSPoint(x: 22.06, y: 13.73))
bezierPath.curve(to: NSPoint(x: 19.4, y: 24.52), controlPoint1: NSPoint(x: 15.22, y: 18.94), controlPoint2: NSPoint(x: 17.6, y: 20.8))
bezierPath.curve(to: NSPoint(x: 34.42, y: 34.26), controlPoint1: NSPoint(x: 23.7, y: 35.95), controlPoint2: NSPoint(x: 34.42, y: 34.26))
bezierPath.line(to: NSPoint(x: 38.11, y: 30.62))
bezierPath.curve(to: NSPoint(x: 36.26, y: 21.52), controlPoint1: NSPoint(x: 38.14, y: 30.58), controlPoint2: NSPoint(x: 40.86, y: 25.78))
bezierPath.line(to: NSPoint(x: 36.26, y: 21.52))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 88.21, y: 83.74))
bezierPath.curve(to: NSPoint(x: 77.14, y: 83.74), controlPoint1: NSPoint(x: 85.15, y: 86.75), controlPoint2: NSPoint(x: 80.2, y: 86.75))
bezierPath.line(to: NSPoint(x: 31.78, y: 38.94))
bezierPath.curve(to: NSPoint(x: 15.22, y: 26.22), controlPoint1: NSPoint(x: 26.23, y: 39.07), controlPoint2: NSPoint(x: 18.54, y: 37.1))
bezierPath.curve(to: NSPoint(x: 6, y: 20.76), controlPoint1: NSPoint(x: 12.68, y: 20.47), controlPoint2: NSPoint(x: 6, y: 20.76))
bezierPath.curve(to: NSPoint(x: 39.95, y: 17.87), controlPoint1: NSPoint(x: 19.87, y: 5.37), controlPoint2: NSPoint(x: 36.22, y: 14.09))
bezierPath.curve(to: NSPoint(x: 43.35, y: 28.52), controlPoint1: NSPoint(x: 43.23, y: 21.2), controlPoint2: NSPoint(x: 43.71, y: 25.26))
bezierPath.line(to: NSPoint(x: 88.21, y: 72.81))
bezierPath.curve(to: NSPoint(x: 88.21, y: 83.74), controlPoint1: NSPoint(x: 91.26, y: 75.83), controlPoint2: NSPoint(x: 91.26, y: 80.72))
bezierPath.line(to: NSPoint(x: 88.21, y: 83.74))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawSocial(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 9.9, y: 62.54))
bezierPath.curve(to: NSPoint(x: 42.37, y: 90.59), controlPoint1: NSPoint(x: 9.9, y: 78.03), controlPoint2: NSPoint(x: 23.93, y: 90.59))
bezierPath.curve(to: NSPoint(x: 71.89, y: 62.54), controlPoint1: NSPoint(x: 57.05, y: 90.59), controlPoint2: NSPoint(x: 71.89, y: 78.03))
bezierPath.curve(to: NSPoint(x: 42.37, y: 34.48), controlPoint1: NSPoint(x: 71.89, y: 47.04), controlPoint2: NSPoint(x: 60.3, y: 34.48))
bezierPath.curve(to: NSPoint(x: 31.78, y: 35.3), controlPoint1: NSPoint(x: 39.74, y: 34.48), controlPoint2: NSPoint(x: 34.24, y: 34.79))
bezierPath.line(to: NSPoint(x: 21.71, y: 28.58))
bezierPath.line(to: NSPoint(x: 21.71, y: 39.04))
bezierPath.curve(to: NSPoint(x: 9.9, y: 62.54), controlPoint1: NSPoint(x: 14.51, y: 44.89), controlPoint2: NSPoint(x: 9.9, y: 52.69))
bezierPath.line(to: NSPoint(x: 9.9, y: 62.54))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 32.44, y: 29.36))
bezierPath.curve(to: NSPoint(x: 42.37, y: 28.58), controlPoint1: NSPoint(x: 34.74, y: 28.98), controlPoint2: NSPoint(x: 39.95, y: 28.58))
bezierPath.curve(to: NSPoint(x: 77.79, y: 62.91), controlPoint1: NSPoint(x: 63.56, y: 28.58), controlPoint2: NSPoint(x: 77.79, y: 44.36))
bezierPath.curve(to: NSPoint(x: 42.37, y: 96.5), controlPoint1: NSPoint(x: 77.79, y: 81.46), controlPoint2: NSPoint(x: 60.01, y: 96.5))
bezierPath.curve(to: NSPoint(x: 4, y: 62.91), controlPoint1: NSPoint(x: 21.15, y: 96.5), controlPoint2: NSPoint(x: 4, y: 81.46))
bezierPath.curve(to: NSPoint(x: 15.81, y: 36.47), controlPoint1: NSPoint(x: 4, y: 52.16), controlPoint2: NSPoint(x: 8.09, y: 43.04))
bezierPath.line(to: NSPoint(x: 15.81, y: 19.72))
bezierPath.line(to: NSPoint(x: 32.44, y: 29.36))
bezierPath.line(to: NSPoint(x: 32.44, y: 29.36))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 83.54, y: 69.51))
bezierPath.curve(to: NSPoint(x: 83.69, y: 66.97), controlPoint1: NSPoint(x: 83.6, y: 68.67), controlPoint2: NSPoint(x: 83.69, y: 67.83))
bezierPath.curve(to: NSPoint(x: 83.25, y: 61.43), controlPoint1: NSPoint(x: 83.69, y: 65.09), controlPoint2: NSPoint(x: 83.51, y: 63.25))
bezierPath.curve(to: NSPoint(x: 89.6, y: 44.82), controlPoint1: NSPoint(x: 87.22, y: 56.78), controlPoint2: NSPoint(x: 89.6, y: 51.05))
bezierPath.curve(to: NSPoint(x: 74.84, y: 21.33), controlPoint1: NSPoint(x: 89.6, y: 34.97), controlPoint2: NSPoint(x: 83.72, y: 26.33))
bezierPath.line(to: NSPoint(x: 74.84, y: 10.86))
bezierPath.line(to: NSPoint(x: 64.76, y: 17.58))
bezierPath.curve(to: NSPoint(x: 57.13, y: 16.77), controlPoint1: NSPoint(x: 62.31, y: 17.07), controlPoint2: NSPoint(x: 59.76, y: 16.77))
bezierPath.curve(to: NSPoint(x: 39.87, y: 22.88), controlPoint1: NSPoint(x: 49.48, y: 16.77), controlPoint2: NSPoint(x: 45.42, y: 19.06))
bezierPath.curve(to: NSPoint(x: 34.99, y: 22.67), controlPoint1: NSPoint(x: 38.27, y: 22.75), controlPoint2: NSPoint(x: 36.64, y: 22.67))
bezierPath.curve(to: NSPoint(x: 31.51, y: 22.82), controlPoint1: NSPoint(x: 33.82, y: 22.67), controlPoint2: NSPoint(x: 32.67, y: 22.75))
bezierPath.curve(to: NSPoint(x: 57.13, y: 11.6), controlPoint1: NSPoint(x: 38.54, y: 15.95), controlPoint2: NSPoint(x: 45.76, y: 11.6))
bezierPath.curve(to: NSPoint(x: 64.2, y: 12.19), controlPoint1: NSPoint(x: 59.55, y: 11.6), controlPoint2: NSPoint(x: 61.9, y: 11.82))
bezierPath.line(to: NSPoint(x: 80.74, y: 2))
bezierPath.line(to: NSPoint(x: 80.74, y: 18.75))
bezierPath.curve(to: NSPoint(x: 95.5, y: 45.19), controlPoint1: NSPoint(x: 89.71, y: 24.9), controlPoint2: NSPoint(x: 95.5, y: 34.44))
bezierPath.curve(to: NSPoint(x: 83.54, y: 69.51), controlPoint1: NSPoint(x: 95.5, y: 54.77), controlPoint2: NSPoint(x: 90.89, y: 63.39))
bezierPath.line(to: NSPoint(x: 83.54, y: 69.51))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 58.6, y: 58.11))
bezierPath.curve(to: NSPoint(x: 63.03, y: 62.54), controlPoint1: NSPoint(x: 61.05, y: 58.11), controlPoint2: NSPoint(x: 63.03, y: 60.09))
bezierPath.curve(to: NSPoint(x: 58.6, y: 66.97), controlPoint1: NSPoint(x: 63.03, y: 64.98), controlPoint2: NSPoint(x: 61.05, y: 66.97))
bezierPath.curve(to: NSPoint(x: 54.18, y: 62.54), controlPoint1: NSPoint(x: 56.16, y: 66.97), controlPoint2: NSPoint(x: 54.18, y: 64.98))
bezierPath.curve(to: NSPoint(x: 58.6, y: 58.11), controlPoint1: NSPoint(x: 54.18, y: 60.09), controlPoint2: NSPoint(x: 56.16, y: 58.11))
bezierPath.line(to: NSPoint(x: 58.6, y: 58.11))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 23.19, y: 58.11))
bezierPath.curve(to: NSPoint(x: 27.61, y: 62.54), controlPoint1: NSPoint(x: 25.63, y: 58.11), controlPoint2: NSPoint(x: 27.61, y: 60.09))
bezierPath.curve(to: NSPoint(x: 23.19, y: 66.97), controlPoint1: NSPoint(x: 27.61, y: 64.98), controlPoint2: NSPoint(x: 25.63, y: 66.97))
bezierPath.curve(to: NSPoint(x: 18.76, y: 62.54), controlPoint1: NSPoint(x: 20.74, y: 66.97), controlPoint2: NSPoint(x: 18.76, y: 64.98))
bezierPath.curve(to: NSPoint(x: 23.19, y: 58.11), controlPoint1: NSPoint(x: 18.76, y: 60.09), controlPoint2: NSPoint(x: 20.74, y: 58.11))
bezierPath.line(to: NSPoint(x: 23.19, y: 58.11))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 40.9, y: 58.11))
bezierPath.curve(to: NSPoint(x: 45.32, y: 62.54), controlPoint1: NSPoint(x: 43.34, y: 58.11), controlPoint2: NSPoint(x: 45.32, y: 60.09))
bezierPath.curve(to: NSPoint(x: 40.9, y: 66.97), controlPoint1: NSPoint(x: 45.32, y: 64.98), controlPoint2: NSPoint(x: 43.34, y: 66.97))
bezierPath.curve(to: NSPoint(x: 36.47, y: 62.54), controlPoint1: NSPoint(x: 38.45, y: 66.97), controlPoint2: NSPoint(x: 36.47, y: 64.98))
bezierPath.curve(to: NSPoint(x: 40.9, y: 58.11), controlPoint1: NSPoint(x: 36.47, y: 60.09), controlPoint2: NSPoint(x: 38.45, y: 58.11))
bezierPath.line(to: NSPoint(x: 40.9, y: 58.11))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawFlyer(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 87.57, y: 82.03))
bezierPath.line(to: NSPoint(x: 66.96, y: 61.34))
bezierPath.line(to: NSPoint(x: 79.42, y: 27.05))
bezierPath.curve(to: NSPoint(x: 78.86, y: 21.86), controlPoint1: NSPoint(x: 80.04, y: 25.09), controlPoint2: NSPoint(x: 79.65, y: 22.65))
bezierPath.curve(to: NSPoint(x: 74.14, y: 21.62), controlPoint1: NSPoint(x: 76.61, y: 19.6), controlPoint2: NSPoint(x: 75, y: 20.68))
bezierPath.line(to: NSPoint(x: 54.21, y: 48.55))
bezierPath.line(to: NSPoint(x: 32.15, y: 26.41))
bezierPath.line(to: NSPoint(x: 36.12, y: 11.66))
bezierPath.curve(to: NSPoint(x: 25.18, y: 25.71), controlPoint1: NSPoint(x: 34.55, y: 13.23), controlPoint2: NSPoint(x: 25.4, y: 25.49))
bezierPath.curve(to: NSPoint(x: 11.7, y: 36.14), controlPoint1: NSPoint(x: 25.03, y: 25.86), controlPoint2: NSPoint(x: 12.99, y: 34.83))
bezierPath.line(to: NSPoint(x: 25.84, y: 32.32))
bezierPath.line(to: NSPoint(x: 48.32, y: 54.4))
bezierPath.line(to: NSPoint(x: 21.58, y: 74.18))
bezierPath.curve(to: NSPoint(x: 21.87, y: 78.96), controlPoint1: NSPoint(x: 20.81, y: 74.87), controlPoint2: NSPoint(x: 19.81, y: 76.89))
bezierPath.curve(to: NSPoint(x: 27.03, y: 79.38), controlPoint1: NSPoint(x: 22.67, y: 79.76), controlPoint2: NSPoint(x: 25.07, y: 80))
bezierPath.line(to: NSPoint(x: 61.17, y: 67.01))
bezierPath.line(to: NSPoint(x: 82.07, y: 87.53))
bezierPath.curve(to: NSPoint(x: 87.67, y: 87.56), controlPoint1: NSPoint(x: 83.53, y: 88.99), controlPoint2: NSPoint(x: 86.39, y: 88.84))
bezierPath.curve(to: NSPoint(x: 87.57, y: 82.03), controlPoint1: NSPoint(x: 88.94, y: 86.28), controlPoint2: NSPoint(x: 89.03, y: 83.49))
bezierPath.line(to: NSPoint(x: 87.57, y: 82.03))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 91.32, y: 91.28))
bezierPath.curve(to: NSPoint(x: 78.34, y: 90.45), controlPoint1: NSPoint(x: 87.87, y: 94.74), controlPoint2: NSPoint(x: 81.81, y: 93.93))
bezierPath.line(to: NSPoint(x: 60.7, y: 72.85))
bezierPath.line(to: NSPoint(x: 27.98, y: 85.08))
bezierPath.curve(to: NSPoint(x: 17.8, y: 83.04), controlPoint1: NSPoint(x: 24.85, y: 85.89), controlPoint2: NSPoint(x: 21.69, y: 86.94))
bezierPath.curve(to: NSPoint(x: 17.8, y: 70.8), controlPoint1: NSPoint(x: 15.82, y: 81.05), controlPoint2: NSPoint(x: 11.7, y: 76.92))
bezierPath.line(to: NSPoint(x: 40.24, y: 52.44))
bezierPath.line(to: NSPoint(x: 25.64, y: 37.87))
bezierPath.line(to: NSPoint(x: 12.02, y: 41.27))
bezierPath.curve(to: NSPoint(x: 7.6, y: 40.24), controlPoint1: NSPoint(x: 10, y: 41.79), controlPoint2: NSPoint(x: 8.64, y: 41.39))
bezierPath.curve(to: NSPoint(x: 5.93, y: 34.13), controlPoint1: NSPoint(x: 7.08, y: 39.59), controlPoint2: NSPoint(x: 3.28, y: 36.78))
bezierPath.line(to: NSPoint(x: 21.77, y: 21.81))
bezierPath.line(to: NSPoint(x: 34.09, y: 5.97))
bezierPath.curve(to: NSPoint(x: 40.21, y: 7.56), controlPoint1: NSPoint(x: 36, y: 4.05), controlPoint2: NSPoint(x: 37.78, y: 5.25))
bezierPath.curve(to: NSPoint(x: 40.96, y: 12.14), controlPoint1: NSPoint(x: 41.75, y: 9.1), controlPoint2: NSPoint(x: 41.42, y: 9.89))
bezierPath.line(to: NSPoint(x: 37.88, y: 25.67))
bezierPath.line(to: NSPoint(x: 52.38, y: 40.22))
bezierPath.line(to: NSPoint(x: 70.72, y: 17.78))
bezierPath.curve(to: NSPoint(x: 82.93, y: 17.78), controlPoint1: NSPoint(x: 76.82, y: 11.66), controlPoint2: NSPoint(x: 80.95, y: 15.8))
bezierPath.curve(to: NSPoint(x: 84.97, y: 27.98), controlPoint1: NSPoint(x: 86.82, y: 21.68), controlPoint2: NSPoint(x: 85.78, y: 24.84))
bezierPath.line(to: NSPoint(x: 72.84, y: 60.75))
bezierPath.line(to: NSPoint(x: 90.41, y: 78.38))
bezierPath.curve(to: NSPoint(x: 91.32, y: 91.28), controlPoint1: NSPoint(x: 93.88, y: 81.86), controlPoint2: NSPoint(x: 94.77, y: 87.82))
bezierPath.line(to: NSPoint(x: 91.32, y: 91.28))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawSpeaker(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 89.78, y: 24.2))
bezierPath.line(to: NSPoint(x: 69.77, y: 38.53))
bezierPath.line(to: NSPoint(x: 69.77, y: 72.93))
bezierPath.line(to: NSPoint(x: 89.78, y: 87.27))
bezierPath.line(to: NSPoint(x: 89.78, y: 24.2))
bezierPath.line(to: NSPoint(x: 89.78, y: 24.2))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 64.05, y: 41.4))
bezierPath.line(to: NSPoint(x: 55.47, y: 41.4))
bezierPath.line(to: NSPoint(x: 55.47, y: 70.07))
bezierPath.line(to: NSPoint(x: 64.05, y: 70.07))
bezierPath.line(to: NSPoint(x: 64.05, y: 41.4))
bezierPath.line(to: NSPoint(x: 64.05, y: 41.4))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 49.75, y: 41.4))
bezierPath.line(to: NSPoint(x: 26.88, y: 41.4))
bezierPath.curve(to: NSPoint(x: 9.72, y: 55.73), controlPoint1: NSPoint(x: 21.19, y: 41.4), controlPoint2: NSPoint(x: 9.72, y: 43.07))
bezierPath.curve(to: NSPoint(x: 26.88, y: 70.07), controlPoint1: NSPoint(x: 9.72, y: 68.4), controlPoint2: NSPoint(x: 21, y: 70.25))
bezierPath.line(to: NSPoint(x: 49.75, y: 70.07))
bezierPath.line(to: NSPoint(x: 49.75, y: 41.4))
bezierPath.line(to: NSPoint(x: 49.75, y: 41.4))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 35.45, y: 15.6))
bezierPath.curve(to: NSPoint(x: 32.59, y: 12.73), controlPoint1: NSPoint(x: 35.45, y: 14.01), controlPoint2: NSPoint(x: 34.17, y: 12.73))
bezierPath.line(to: NSPoint(x: 29.73, y: 12.73))
bezierPath.curve(to: NSPoint(x: 26.88, y: 15.6), controlPoint1: NSPoint(x: 28.16, y: 12.73), controlPoint2: NSPoint(x: 26.88, y: 14.01))
bezierPath.line(to: NSPoint(x: 26.88, y: 35.67))
bezierPath.line(to: NSPoint(x: 35.45, y: 35.67))
bezierPath.line(to: NSPoint(x: 35.45, y: 15.6))
bezierPath.line(to: NSPoint(x: 35.45, y: 15.6))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 89.78, y: 93))
bezierPath.line(to: NSPoint(x: 64.05, y: 75.8))
bezierPath.line(to: NSPoint(x: 26.88, y: 75.8))
bezierPath.curve(to: NSPoint(x: 4, y: 55.73), controlPoint1: NSPoint(x: 14.24, y: 75.8), controlPoint2: NSPoint(x: 4, y: 68.4))
bezierPath.curve(to: NSPoint(x: 21.16, y: 35.67), controlPoint1: NSPoint(x: 4, y: 45.03), controlPoint2: NSPoint(x: 11.27, y: 37.56))
bezierPath.curve(to: NSPoint(x: 21.16, y: 12.73), controlPoint1: NSPoint(x: 21.28, y: 34.89), controlPoint2: NSPoint(x: 21.16, y: 12.73))
bezierPath.curve(to: NSPoint(x: 26.88, y: 7), controlPoint1: NSPoint(x: 21.16, y: 9.57), controlPoint2: NSPoint(x: 23.72, y: 7))
bezierPath.line(to: NSPoint(x: 35.45, y: 7))
bezierPath.curve(to: NSPoint(x: 41.17, y: 12.73), controlPoint1: NSPoint(x: 38.61, y: 7), controlPoint2: NSPoint(x: 41.17, y: 9.57))
bezierPath.line(to: NSPoint(x: 41.17, y: 35.67))
bezierPath.line(to: NSPoint(x: 64.05, y: 35.67))
bezierPath.line(to: NSPoint(x: 89.78, y: 18.47))
bezierPath.curve(to: NSPoint(x: 95.5, y: 24.2), controlPoint1: NSPoint(x: 92.94, y: 18.47), controlPoint2: NSPoint(x: 95.5, y: 21.04))
bezierPath.line(to: NSPoint(x: 95.5, y: 87.27))
bezierPath.curve(to: NSPoint(x: 89.78, y: 93), controlPoint1: NSPoint(x: 95.5, y: 90.43), controlPoint2: NSPoint(x: 92.94, y: 93))
bezierPath.line(to: NSPoint(x: 89.78, y: 93))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawTime(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 76.88, y: 47.31))
bezierPath.line(to: NSPoint(x: 82.25, y: 47.31))
bezierPath.line(to: NSPoint(x: 82.25, y: 52.69))
bezierPath.line(to: NSPoint(x: 76.88, y: 52.69))
bezierPath.line(to: NSPoint(x: 76.88, y: 47.31))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 50, y: 12.38))
bezierPath.curve(to: NSPoint(x: 12.38, y: 50), controlPoint1: NSPoint(x: 29.22, y: 12.38), controlPoint2: NSPoint(x: 12.38, y: 29.22))
bezierPath.curve(to: NSPoint(x: 50, y: 87.62), controlPoint1: NSPoint(x: 12.38, y: 70.78), controlPoint2: NSPoint(x: 29.22, y: 87.62))
bezierPath.curve(to: NSPoint(x: 87.62, y: 50), controlPoint1: NSPoint(x: 70.78, y: 87.62), controlPoint2: NSPoint(x: 87.62, y: 70.78))
bezierPath.curve(to: NSPoint(x: 50, y: 12.38), controlPoint1: NSPoint(x: 87.62, y: 29.22), controlPoint2: NSPoint(x: 70.78, y: 12.38))
bezierPath.line(to: NSPoint(x: 50, y: 12.38))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 50, y: 93))
bezierPath.curve(to: NSPoint(x: 7, y: 50), controlPoint1: NSPoint(x: 26.25, y: 93), controlPoint2: NSPoint(x: 7, y: 73.75))
bezierPath.curve(to: NSPoint(x: 50, y: 7), controlPoint1: NSPoint(x: 7, y: 26.25), controlPoint2: NSPoint(x: 26.25, y: 7))
bezierPath.curve(to: NSPoint(x: 93, y: 50), controlPoint1: NSPoint(x: 73.75, y: 7), controlPoint2: NSPoint(x: 93, y: 26.25))
bezierPath.curve(to: NSPoint(x: 50, y: 93), controlPoint1: NSPoint(x: 93, y: 73.75), controlPoint2: NSPoint(x: 73.75, y: 93))
bezierPath.line(to: NSPoint(x: 50, y: 93))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 66.33, y: 70.77))
bezierPath.line(to: NSPoint(x: 70.05, y: 67.04))
bezierPath.line(to: NSPoint(x: 73.77, y: 70.77))
bezierPath.line(to: NSPoint(x: 70.05, y: 74.49))
bezierPath.line(to: NSPoint(x: 66.33, y: 70.77))
bezierPath.line(to: NSPoint(x: 66.33, y: 70.77))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 65.54, y: 31.78))
bezierPath.line(to: NSPoint(x: 69.34, y: 27.98))
bezierPath.line(to: NSPoint(x: 73.14, y: 31.78))
bezierPath.line(to: NSPoint(x: 69.34, y: 35.58))
bezierPath.line(to: NSPoint(x: 65.54, y: 31.78))
bezierPath.line(to: NSPoint(x: 65.54, y: 31.78))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 50, y: 82.25))
bezierPath.curve(to: NSPoint(x: 47.31, y: 79.56), controlPoint1: NSPoint(x: 48.52, y: 82.25), controlPoint2: NSPoint(x: 47.31, y: 81.05))
bezierPath.line(to: NSPoint(x: 47.31, y: 52.63))
bezierPath.line(to: NSPoint(x: 25.81, y: 52.63))
bezierPath.curve(to: NSPoint(x: 23.12, y: 49.94), controlPoint1: NSPoint(x: 24.33, y: 52.63), controlPoint2: NSPoint(x: 23.12, y: 51.42))
bezierPath.curve(to: NSPoint(x: 25.81, y: 47.25), controlPoint1: NSPoint(x: 23.12, y: 48.45), controlPoint2: NSPoint(x: 24.33, y: 47.25))
bezierPath.line(to: NSPoint(x: 50, y: 47.25))
bezierPath.curve(to: NSPoint(x: 52.69, y: 49.94), controlPoint1: NSPoint(x: 51.49, y: 47.25), controlPoint2: NSPoint(x: 52.69, y: 48.45))
bezierPath.line(to: NSPoint(x: 52.69, y: 79.56))
bezierPath.curve(to: NSPoint(x: 50, y: 82.25), controlPoint1: NSPoint(x: 52.69, y: 81.05), controlPoint2: NSPoint(x: 51.49, y: 82.25))
bezierPath.line(to: NSPoint(x: 50, y: 82.25))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 33.05, y: 70.63))
bezierPath.line(to: NSPoint(x: 29.25, y: 74.43))
bezierPath.line(to: NSPoint(x: 25.45, y: 70.63))
bezierPath.line(to: NSPoint(x: 29.25, y: 66.83))
bezierPath.line(to: NSPoint(x: 33.05, y: 70.63))
bezierPath.line(to: NSPoint(x: 33.05, y: 70.63))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 25.09, y: 31.64))
bezierPath.line(to: NSPoint(x: 28.81, y: 27.91))
bezierPath.line(to: NSPoint(x: 32.53, y: 31.64))
bezierPath.line(to: NSPoint(x: 28.81, y: 35.37))
bezierPath.line(to: NSPoint(x: 25.09, y: 31.64))
bezierPath.line(to: NSPoint(x: 25.09, y: 31.64))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 47.31, y: 17.75))
bezierPath.line(to: NSPoint(x: 52.69, y: 17.75))
bezierPath.line(to: NSPoint(x: 52.69, y: 23.12))
bezierPath.line(to: NSPoint(x: 47.31, y: 23.12))
bezierPath.line(to: NSPoint(x: 47.31, y: 17.75))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawHot(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 50.94, y: 8.78))
bezierPath.curve(to: NSPoint(x: 17.77, y: 41.66), controlPoint1: NSPoint(x: 32.62, y: 8.78), controlPoint2: NSPoint(x: 17.77, y: 24.27))
bezierPath.curve(to: NSPoint(x: 20.65, y: 52.14), controlPoint1: NSPoint(x: 17.77, y: 45.7), controlPoint2: NSPoint(x: 17.86, y: 48.98))
bezierPath.curve(to: NSPoint(x: 38.84, y: 35.46), controlPoint1: NSPoint(x: 20.35, y: 50.31), controlPoint2: NSPoint(x: 24.68, y: 34.64))
bezierPath.curve(to: NSPoint(x: 49.94, y: 86.62), controlPoint1: NSPoint(x: 38.23, y: 47.37), controlPoint2: NSPoint(x: 35.01, y: 76.53))
bezierPath.curve(to: NSPoint(x: 69.78, y: 46.36), controlPoint1: NSPoint(x: 48.62, y: 70.76), controlPoint2: NSPoint(x: 52.49, y: 49.47))
bezierPath.curve(to: NSPoint(x: 73.35, y: 65.24), controlPoint1: NSPoint(x: 68.79, y: 52.72), controlPoint2: NSPoint(x: 68.9, y: 63.29))
bezierPath.curve(to: NSPoint(x: 81.01, y: 40.14), controlPoint1: NSPoint(x: 73.83, y: 55.51), controlPoint2: NSPoint(x: 81.01, y: 49.5))
bezierPath.curve(to: NSPoint(x: 50.94, y: 8.78), controlPoint1: NSPoint(x: 81.01, y: 23.19), controlPoint2: NSPoint(x: 64.65, y: 8.78))
bezierPath.line(to: NSPoint(x: 50.94, y: 8.78))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 78.07, y: 75.4))
bezierPath.curve(to: NSPoint(x: 63.92, y: 55.03), controlPoint1: NSPoint(x: 65.42, y: 71.79), controlPoint2: NSPoint(x: 63.11, y: 61.54))
bezierPath.curve(to: NSPoint(x: 55.27, y: 95.5), controlPoint1: NSPoint(x: 54.9, y: 65.66), controlPoint2: NSPoint(x: 55.27, y: 77.89))
bezierPath.curve(to: NSPoint(x: 32.19, y: 43.47), controlPoint1: NSPoint(x: 26.33, y: 84.56), controlPoint2: NSPoint(x: 33.06, y: 53.04))
bezierPath.curve(to: NSPoint(x: 23.54, y: 63.7), controlPoint1: NSPoint(x: 24.91, y: 49.44), controlPoint2: NSPoint(x: 23.54, y: 63.7))
bezierPath.curve(to: NSPoint(x: 12, y: 40.58), controlPoint1: NSPoint(x: 15.85, y: 59.74), controlPoint2: NSPoint(x: 12, y: 49.16))
bezierPath.curve(to: NSPoint(x: 49.5, y: 3), controlPoint1: NSPoint(x: 12, y: 19.82), controlPoint2: NSPoint(x: 28.79, y: 3))
bezierPath.curve(to: NSPoint(x: 87, y: 40.58), controlPoint1: NSPoint(x: 70.21, y: 3), controlPoint2: NSPoint(x: 87, y: 19.82))
bezierPath.curve(to: NSPoint(x: 78.07, y: 75.4), controlPoint1: NSPoint(x: 87, y: 52.91), controlPoint2: NSPoint(x: 77.96, y: 58.6))
bezierPath.line(to: NSPoint(x: 78.07, y: 75.4))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawMusic(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 90.66, y: 26.38))
bezierPath.curve(to: NSPoint(x: 84.81, y: 20.53), controlPoint1: NSPoint(x: 90.66, y: 23.15), controlPoint2: NSPoint(x: 88.04, y: 20.53))
bezierPath.line(to: NSPoint(x: 82.05, y: 20.53))
bezierPath.curve(to: NSPoint(x: 84.81, y: 36.6), controlPoint1: NSPoint(x: 83.79, y: 25.39), controlPoint2: NSPoint(x: 84.81, y: 30.81))
bezierPath.curve(to: NSPoint(x: 82.98, y: 49.75), controlPoint1: NSPoint(x: 84.81, y: 41.26), controlPoint2: NSPoint(x: 84.13, y: 45.67))
bezierPath.line(to: NSPoint(x: 84.81, y: 49.75))
bezierPath.curve(to: NSPoint(x: 90.66, y: 43.91), controlPoint1: NSPoint(x: 88.04, y: 49.75), controlPoint2: NSPoint(x: 90.66, y: 47.13))
bezierPath.line(to: NSPoint(x: 90.66, y: 26.38))
bezierPath.line(to: NSPoint(x: 90.66, y: 26.38))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 75.68, y: 20.53))
bezierPath.line(to: NSPoint(x: 73.12, y: 20.53))
bezierPath.curve(to: NSPoint(x: 67.28, y: 26.38), controlPoint1: NSPoint(x: 69.9, y: 20.53), controlPoint2: NSPoint(x: 67.28, y: 23.15))
bezierPath.line(to: NSPoint(x: 67.28, y: 43.91))
bezierPath.curve(to: NSPoint(x: 73.12, y: 49.75), controlPoint1: NSPoint(x: 67.28, y: 47.13), controlPoint2: NSPoint(x: 69.9, y: 49.75))
bezierPath.line(to: NSPoint(x: 76.8, y: 49.75))
bezierPath.curve(to: NSPoint(x: 78.97, y: 36.6), controlPoint1: NSPoint(x: 78.16, y: 45.7), controlPoint2: NSPoint(x: 78.97, y: 41.29))
bezierPath.curve(to: NSPoint(x: 75.68, y: 20.53), controlPoint1: NSPoint(x: 78.97, y: 30.76), controlPoint2: NSPoint(x: 77.74, y: 25.31))
bezierPath.line(to: NSPoint(x: 75.68, y: 20.53))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 16.53, y: 49.75))
bezierPath.curve(to: NSPoint(x: 14.69, y: 36.6), controlPoint1: NSPoint(x: 15.37, y: 45.67), controlPoint2: NSPoint(x: 14.69, y: 41.26))
bezierPath.curve(to: NSPoint(x: 17.45, y: 20.53), controlPoint1: NSPoint(x: 14.69, y: 30.81), controlPoint2: NSPoint(x: 15.72, y: 25.39))
bezierPath.line(to: NSPoint(x: 14.69, y: 20.53))
bezierPath.curve(to: NSPoint(x: 8.84, y: 26.38), controlPoint1: NSPoint(x: 11.46, y: 20.53), controlPoint2: NSPoint(x: 8.84, y: 23.15))
bezierPath.line(to: NSPoint(x: 8.84, y: 43.91))
bezierPath.curve(to: NSPoint(x: 14.69, y: 49.75), controlPoint1: NSPoint(x: 8.84, y: 47.13), controlPoint2: NSPoint(x: 11.46, y: 49.75))
bezierPath.line(to: NSPoint(x: 16.53, y: 49.75))
bezierPath.line(to: NSPoint(x: 16.53, y: 49.75))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 22.7, y: 49.75))
bezierPath.line(to: NSPoint(x: 26.38, y: 49.75))
bezierPath.curve(to: NSPoint(x: 32.22, y: 43.91), controlPoint1: NSPoint(x: 29.6, y: 49.75), controlPoint2: NSPoint(x: 32.22, y: 47.13))
bezierPath.line(to: NSPoint(x: 32.22, y: 26.38))
bezierPath.curve(to: NSPoint(x: 26.38, y: 20.53), controlPoint1: NSPoint(x: 32.22, y: 23.15), controlPoint2: NSPoint(x: 29.6, y: 20.53))
bezierPath.line(to: NSPoint(x: 23.82, y: 20.53))
bezierPath.curve(to: NSPoint(x: 20.53, y: 36.6), controlPoint1: NSPoint(x: 21.76, y: 25.31), controlPoint2: NSPoint(x: 20.53, y: 30.76))
bezierPath.curve(to: NSPoint(x: 22.7, y: 49.75), controlPoint1: NSPoint(x: 20.53, y: 41.29), controlPoint2: NSPoint(x: 21.34, y: 45.7))
bezierPath.line(to: NSPoint(x: 22.7, y: 49.75))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 90.48, y: 54.07))
bezierPath.curve(to: NSPoint(x: 90.66, y: 57.05), controlPoint1: NSPoint(x: 90.56, y: 55.06), controlPoint2: NSPoint(x: 90.66, y: 56.04))
bezierPath.curve(to: NSPoint(x: 49.75, y: 96.5), controlPoint1: NSPoint(x: 90.66, y: 78.84), controlPoint2: NSPoint(x: 72.34, y: 96.5))
bezierPath.curve(to: NSPoint(x: 8.84, y: 57.05), controlPoint1: NSPoint(x: 27.16, y: 96.5), controlPoint2: NSPoint(x: 8.84, y: 78.84))
bezierPath.curve(to: NSPoint(x: 9.03, y: 54.07), controlPoint1: NSPoint(x: 8.84, y: 56.04), controlPoint2: NSPoint(x: 8.94, y: 55.06))
bezierPath.curve(to: NSPoint(x: 3, y: 43.91), controlPoint1: NSPoint(x: 5.45, y: 52.07), controlPoint2: NSPoint(x: 3, y: 48.29))
bezierPath.line(to: NSPoint(x: 3, y: 26.38))
bezierPath.curve(to: NSPoint(x: 14.69, y: 14.69), controlPoint1: NSPoint(x: 3, y: 19.92), controlPoint2: NSPoint(x: 8.23, y: 14.69))
bezierPath.curve(to: NSPoint(x: 26.38, y: 14.69), controlPoint1: NSPoint(x: 14.69, y: 14.69), controlPoint2: NSPoint(x: 26.39, y: 14.67))
bezierPath.curve(to: NSPoint(x: 38.06, y: 26.38), controlPoint1: NSPoint(x: 32.58, y: 14.97), controlPoint2: NSPoint(x: 38.06, y: 20.1))
bezierPath.line(to: NSPoint(x: 38.06, y: 43.91))
bezierPath.curve(to: NSPoint(x: 26.38, y: 55.59), controlPoint1: NSPoint(x: 38.06, y: 50.36), controlPoint2: NSPoint(x: 32.83, y: 55.59))
bezierPath.line(to: NSPoint(x: 14.69, y: 55.59))
bezierPath.curve(to: NSPoint(x: 49.75, y: 90.66), controlPoint1: NSPoint(x: 14.69, y: 75.06), controlPoint2: NSPoint(x: 30.39, y: 90.66))
bezierPath.curve(to: NSPoint(x: 84.81, y: 55.59), controlPoint1: NSPoint(x: 69.12, y: 90.66), controlPoint2: NSPoint(x: 84.81, y: 76.44))
bezierPath.line(to: NSPoint(x: 73.12, y: 55.59))
bezierPath.curve(to: NSPoint(x: 61.44, y: 43.91), controlPoint1: NSPoint(x: 66.67, y: 55.59), controlPoint2: NSPoint(x: 61.44, y: 50.36))
bezierPath.line(to: NSPoint(x: 61.44, y: 26.38))
bezierPath.curve(to: NSPoint(x: 73.12, y: 14.69), controlPoint1: NSPoint(x: 61.44, y: 20.1), controlPoint2: NSPoint(x: 66.92, y: 14.97))
bezierPath.curve(to: NSPoint(x: 78.97, y: 14.69), controlPoint1: NSPoint(x: 73.11, y: 14.67), controlPoint2: NSPoint(x: 78.97, y: 14.69))
bezierPath.line(to: NSPoint(x: 78.97, y: 5.92))
bezierPath.curve(to: NSPoint(x: 81.89, y: 3), controlPoint1: NSPoint(x: 78.97, y: 4.31), controlPoint2: NSPoint(x: 80.27, y: 3))
bezierPath.curve(to: NSPoint(x: 84.81, y: 5.92), controlPoint1: NSPoint(x: 83.51, y: 3), controlPoint2: NSPoint(x: 84.81, y: 4.31))
bezierPath.line(to: NSPoint(x: 84.81, y: 14.69))
bezierPath.curve(to: NSPoint(x: 96.5, y: 26.38), controlPoint1: NSPoint(x: 91.27, y: 14.69), controlPoint2: NSPoint(x: 96.5, y: 19.92))
bezierPath.line(to: NSPoint(x: 96.5, y: 43.91))
bezierPath.curve(to: NSPoint(x: 90.48, y: 54.07), controlPoint1: NSPoint(x: 96.5, y: 48.29), controlPoint2: NSPoint(x: 94.05, y: 52.07))
bezierPath.line(to: NSPoint(x: 90.48, y: 54.07))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawWorld(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 82.04, y: 27.11))
bezierPath.curve(to: NSPoint(x: 64.68, y: 31.13), controlPoint1: NSPoint(x: 76.63, y: 28.91), controlPoint2: NSPoint(x: 70.81, y: 30.26))
bezierPath.curve(to: NSPoint(x: 66.1, y: 46.42), controlPoint1: NSPoint(x: 65.51, y: 36.03), controlPoint2: NSPoint(x: 65.96, y: 41.16))
bezierPath.line(to: NSPoint(x: 88.74, y: 46.42))
bezierPath.curve(to: NSPoint(x: 82.04, y: 27.11), controlPoint1: NSPoint(x: 88.23, y: 39.29), controlPoint2: NSPoint(x: 85.83, y: 32.69))
bezierPath.line(to: NSPoint(x: 82.04, y: 27.11))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 58.96, y: 10.9))
bezierPath.curve(to: NSPoint(x: 63.57, y: 25.55), controlPoint1: NSPoint(x: 60.85, y: 15.45), controlPoint2: NSPoint(x: 62.39, y: 20.37))
bezierPath.curve(to: NSPoint(x: 78.15, y: 22.23), controlPoint1: NSPoint(x: 68.66, y: 24.8), controlPoint2: NSPoint(x: 73.53, y: 23.69))
bezierPath.curve(to: NSPoint(x: 58.96, y: 10.9), controlPoint1: NSPoint(x: 73.05, y: 16.79), controlPoint2: NSPoint(x: 66.43, y: 12.79))
bezierPath.line(to: NSPoint(x: 58.96, y: 10.9))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 52, y: 9.79))
bezierPath.curve(to: NSPoint(x: 49.25, y: 9.66), controlPoint1: NSPoint(x: 51.09, y: 9.73), controlPoint2: NSPoint(x: 50.18, y: 9.66))
bezierPath.curve(to: NSPoint(x: 46.5, y: 9.79), controlPoint1: NSPoint(x: 48.32, y: 9.66), controlPoint2: NSPoint(x: 47.42, y: 9.73))
bezierPath.curve(to: NSPoint(x: 40.71, y: 26.3), controlPoint1: NSPoint(x: 44.1, y: 14.81), controlPoint2: NSPoint(x: 42.15, y: 20.38))
bezierPath.curve(to: NSPoint(x: 49.25, y: 26.69), controlPoint1: NSPoint(x: 43.52, y: 26.55), controlPoint2: NSPoint(x: 46.37, y: 26.69))
bezierPath.curve(to: NSPoint(x: 57.8, y: 26.3), controlPoint1: NSPoint(x: 52.13, y: 26.69), controlPoint2: NSPoint(x: 54.98, y: 26.55))
bezierPath.curve(to: NSPoint(x: 52, y: 9.79), controlPoint1: NSPoint(x: 56.35, y: 20.38), controlPoint2: NSPoint(x: 54.4, y: 14.81))
bezierPath.line(to: NSPoint(x: 52, y: 9.79))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 20.35, y: 22.23))
bezierPath.curve(to: NSPoint(x: 34.93, y: 25.55), controlPoint1: NSPoint(x: 24.97, y: 23.69), controlPoint2: NSPoint(x: 29.84, y: 24.8))
bezierPath.curve(to: NSPoint(x: 39.54, y: 10.9), controlPoint1: NSPoint(x: 36.11, y: 20.37), controlPoint2: NSPoint(x: 37.65, y: 15.45))
bezierPath.curve(to: NSPoint(x: 20.35, y: 22.23), controlPoint1: NSPoint(x: 32.07, y: 12.79), controlPoint2: NSPoint(x: 25.45, y: 16.79))
bezierPath.line(to: NSPoint(x: 20.35, y: 22.23))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 16.46, y: 27.11))
bezierPath.curve(to: NSPoint(x: 9.76, y: 46.42), controlPoint1: NSPoint(x: 12.67, y: 32.69), controlPoint2: NSPoint(x: 10.27, y: 39.29))
bezierPath.line(to: NSPoint(x: 32.4, y: 46.42))
bezierPath.curve(to: NSPoint(x: 33.82, y: 31.13), controlPoint1: NSPoint(x: 32.54, y: 41.16), controlPoint2: NSPoint(x: 32.99, y: 36.03))
bezierPath.curve(to: NSPoint(x: 16.46, y: 27.11), controlPoint1: NSPoint(x: 27.69, y: 30.26), controlPoint2: NSPoint(x: 21.87, y: 28.91))
bezierPath.line(to: NSPoint(x: 16.46, y: 27.11))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 16.46, y: 71.39))
bezierPath.curve(to: NSPoint(x: 33.82, y: 67.37), controlPoint1: NSPoint(x: 21.87, y: 69.59), controlPoint2: NSPoint(x: 27.69, y: 68.24))
bezierPath.curve(to: NSPoint(x: 32.4, y: 52.08), controlPoint1: NSPoint(x: 32.99, y: 62.47), controlPoint2: NSPoint(x: 32.54, y: 57.34))
bezierPath.line(to: NSPoint(x: 9.76, y: 52.08))
bezierPath.curve(to: NSPoint(x: 16.46, y: 71.39), controlPoint1: NSPoint(x: 10.27, y: 59.21), controlPoint2: NSPoint(x: 12.67, y: 65.81))
bezierPath.line(to: NSPoint(x: 16.46, y: 71.39))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 39.54, y: 87.6))
bezierPath.curve(to: NSPoint(x: 34.93, y: 72.95), controlPoint1: NSPoint(x: 37.65, y: 83.05), controlPoint2: NSPoint(x: 36.11, y: 78.13))
bezierPath.curve(to: NSPoint(x: 20.35, y: 76.27), controlPoint1: NSPoint(x: 29.84, y: 73.7), controlPoint2: NSPoint(x: 24.97, y: 74.81))
bezierPath.curve(to: NSPoint(x: 39.54, y: 87.6), controlPoint1: NSPoint(x: 25.45, y: 81.71), controlPoint2: NSPoint(x: 32.07, y: 85.71))
bezierPath.line(to: NSPoint(x: 39.54, y: 87.6))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 46.5, y: 88.71))
bezierPath.curve(to: NSPoint(x: 49.25, y: 88.84), controlPoint1: NSPoint(x: 47.42, y: 88.77), controlPoint2: NSPoint(x: 48.32, y: 88.84))
bezierPath.curve(to: NSPoint(x: 52, y: 88.71), controlPoint1: NSPoint(x: 50.18, y: 88.84), controlPoint2: NSPoint(x: 51.09, y: 88.77))
bezierPath.curve(to: NSPoint(x: 57.8, y: 72.2), controlPoint1: NSPoint(x: 54.4, y: 83.69), controlPoint2: NSPoint(x: 56.35, y: 78.11))
bezierPath.curve(to: NSPoint(x: 49.25, y: 71.81), controlPoint1: NSPoint(x: 54.98, y: 71.95), controlPoint2: NSPoint(x: 52.13, y: 71.81))
bezierPath.curve(to: NSPoint(x: 40.71, y: 72.2), controlPoint1: NSPoint(x: 46.37, y: 71.81), controlPoint2: NSPoint(x: 43.52, y: 71.95))
bezierPath.curve(to: NSPoint(x: 46.5, y: 88.71), controlPoint1: NSPoint(x: 42.15, y: 78.11), controlPoint2: NSPoint(x: 44.1, y: 83.69))
bezierPath.line(to: NSPoint(x: 46.5, y: 88.71))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 60.43, y: 46.42))
bezierPath.curve(to: NSPoint(x: 58.98, y: 31.84), controlPoint1: NSPoint(x: 60.28, y: 41.44), controlPoint2: NSPoint(x: 59.83, y: 36.54))
bezierPath.curve(to: NSPoint(x: 49.25, y: 32.28), controlPoint1: NSPoint(x: 55.79, y: 32.12), controlPoint2: NSPoint(x: 52.55, y: 32.28))
bezierPath.curve(to: NSPoint(x: 39.53, y: 31.84), controlPoint1: NSPoint(x: 45.95, y: 32.28), controlPoint2: NSPoint(x: 42.71, y: 32.12))
bezierPath.curve(to: NSPoint(x: 38.07, y: 46.42), controlPoint1: NSPoint(x: 38.67, y: 36.54), controlPoint2: NSPoint(x: 38.22, y: 41.44))
bezierPath.line(to: NSPoint(x: 60.43, y: 46.42))
bezierPath.line(to: NSPoint(x: 60.43, y: 46.42))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 38.07, y: 52.08))
bezierPath.curve(to: NSPoint(x: 39.53, y: 66.66), controlPoint1: NSPoint(x: 38.22, y: 57.06), controlPoint2: NSPoint(x: 38.67, y: 61.96))
bezierPath.curve(to: NSPoint(x: 49.25, y: 66.22), controlPoint1: NSPoint(x: 42.71, y: 66.38), controlPoint2: NSPoint(x: 45.95, y: 66.22))
bezierPath.curve(to: NSPoint(x: 58.97, y: 66.66), controlPoint1: NSPoint(x: 52.55, y: 66.22), controlPoint2: NSPoint(x: 55.79, y: 66.38))
bezierPath.curve(to: NSPoint(x: 60.43, y: 52.08), controlPoint1: NSPoint(x: 59.83, y: 61.96), controlPoint2: NSPoint(x: 60.28, y: 57.06))
bezierPath.line(to: NSPoint(x: 38.07, y: 52.08))
bezierPath.line(to: NSPoint(x: 38.07, y: 52.08))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 78.15, y: 76.27))
bezierPath.curve(to: NSPoint(x: 63.57, y: 72.95), controlPoint1: NSPoint(x: 73.53, y: 74.81), controlPoint2: NSPoint(x: 68.66, y: 73.7))
bezierPath.curve(to: NSPoint(x: 58.96, y: 87.6), controlPoint1: NSPoint(x: 62.39, y: 78.13), controlPoint2: NSPoint(x: 60.85, y: 83.05))
bezierPath.curve(to: NSPoint(x: 78.15, y: 76.27), controlPoint1: NSPoint(x: 66.43, y: 85.71), controlPoint2: NSPoint(x: 73.05, y: 81.71))
bezierPath.line(to: NSPoint(x: 78.15, y: 76.27))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 82.04, y: 71.39))
bezierPath.curve(to: NSPoint(x: 88.74, y: 52.08), controlPoint1: NSPoint(x: 85.83, y: 65.81), controlPoint2: NSPoint(x: 88.23, y: 59.21))
bezierPath.line(to: NSPoint(x: 66.1, y: 52.08))
bezierPath.curve(to: NSPoint(x: 64.68, y: 67.37), controlPoint1: NSPoint(x: 65.96, y: 57.34), controlPoint2: NSPoint(x: 65.51, y: 62.47))
bezierPath.curve(to: NSPoint(x: 82.04, y: 71.39), controlPoint1: NSPoint(x: 70.81, y: 68.24), controlPoint2: NSPoint(x: 76.63, y: 69.59))
bezierPath.line(to: NSPoint(x: 82.04, y: 71.39))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 49.25, y: 94.5))
bezierPath.curve(to: NSPoint(x: 4, y: 49.25), controlPoint1: NSPoint(x: 24.26, y: 94.5), controlPoint2: NSPoint(x: 4, y: 74.24))
bezierPath.curve(to: NSPoint(x: 49.25, y: 4), controlPoint1: NSPoint(x: 4, y: 24.26), controlPoint2: NSPoint(x: 24.26, y: 4))
bezierPath.curve(to: NSPoint(x: 94.5, y: 49.25), controlPoint1: NSPoint(x: 74.24, y: 4), controlPoint2: NSPoint(x: 94.5, y: 24.26))
bezierPath.curve(to: NSPoint(x: 49.25, y: 94.5), controlPoint1: NSPoint(x: 94.5, y: 74.24), controlPoint2: NSPoint(x: 74.24, y: 94.5))
bezierPath.line(to: NSPoint(x: 49.25, y: 94.5))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawRain(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 67.25, y: 32.75))
bezierPath.line(to: NSPoint(x: 29.88, y: 32.75))
bezierPath.curve(to: NSPoint(x: 9.75, y: 50), controlPoint1: NSPoint(x: 15.47, y: 32.92), controlPoint2: NSPoint(x: 9.75, y: 43.93))
bezierPath.curve(to: NSPoint(x: 27, y: 67.25), controlPoint1: NSPoint(x: 9.75, y: 57.84), controlPoint2: NSPoint(x: 16.72, y: 66.65))
bezierPath.curve(to: NSPoint(x: 47.12, y: 90.25), controlPoint1: NSPoint(x: 26.91, y: 78.93), controlPoint2: NSPoint(x: 34.14, y: 90.25))
bezierPath.curve(to: NSPoint(x: 65.86, y: 75.84), controlPoint1: NSPoint(x: 56.98, y: 90.25), controlPoint2: NSPoint(x: 63.51, y: 84.21))
bezierPath.curve(to: NSPoint(x: 90.25, y: 55.75), controlPoint1: NSPoint(x: 79.16, y: 76.45), controlPoint2: NSPoint(x: 90.25, y: 67.09))
bezierPath.curve(to: NSPoint(x: 67.25, y: 32.75), controlPoint1: NSPoint(x: 90.25, y: 43.68), controlPoint2: NSPoint(x: 81.56, y: 32.75))
bezierPath.line(to: NSPoint(x: 67.25, y: 32.75))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 70.32, y: 81.54))
bezierPath.curve(to: NSPoint(x: 47.12, y: 96), controlPoint1: NSPoint(x: 66.1, y: 90.1), controlPoint2: NSPoint(x: 57.31, y: 96))
bezierPath.curve(to: NSPoint(x: 21.34, y: 72.01), controlPoint1: NSPoint(x: 33.47, y: 96), controlPoint2: NSPoint(x: 22.31, y: 85.41))
bezierPath.curve(to: NSPoint(x: 4, y: 50), controlPoint1: NSPoint(x: 11.31, y: 69.14), controlPoint2: NSPoint(x: 4, y: 60.38))
bezierPath.curve(to: NSPoint(x: 27, y: 27), controlPoint1: NSPoint(x: 4, y: 37.75), controlPoint2: NSPoint(x: 14.18, y: 27.7))
bezierPath.line(to: NSPoint(x: 70.12, y: 27))
bezierPath.curve(to: NSPoint(x: 96, y: 54.31), controlPoint1: NSPoint(x: 84.22, y: 27), controlPoint2: NSPoint(x: 96, y: 39.23))
bezierPath.curve(to: NSPoint(x: 70.32, y: 81.54), controlPoint1: NSPoint(x: 96, y: 70.1), controlPoint2: NSPoint(x: 84.64, y: 80.69))
bezierPath.line(to: NSPoint(x: 70.32, y: 81.54))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 70.12, y: 21.25))
bezierPath.curve(to: NSPoint(x: 67.25, y: 18.38), controlPoint1: NSPoint(x: 68.54, y: 21.25), controlPoint2: NSPoint(x: 67.25, y: 19.96))
bezierPath.curve(to: NSPoint(x: 70.12, y: 15.5), controlPoint1: NSPoint(x: 67.25, y: 16.79), controlPoint2: NSPoint(x: 68.54, y: 15.5))
bezierPath.curve(to: NSPoint(x: 73, y: 18.38), controlPoint1: NSPoint(x: 71.71, y: 15.5), controlPoint2: NSPoint(x: 73, y: 16.79))
bezierPath.curve(to: NSPoint(x: 70.12, y: 21.25), controlPoint1: NSPoint(x: 73, y: 19.96), controlPoint2: NSPoint(x: 71.71, y: 21.25))
bezierPath.line(to: NSPoint(x: 70.12, y: 21.25))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 58.62, y: 9.75))
bezierPath.curve(to: NSPoint(x: 55.75, y: 6.88), controlPoint1: NSPoint(x: 57.04, y: 9.75), controlPoint2: NSPoint(x: 55.75, y: 8.46))
bezierPath.curve(to: NSPoint(x: 58.62, y: 4), controlPoint1: NSPoint(x: 55.75, y: 5.29), controlPoint2: NSPoint(x: 57.04, y: 4))
bezierPath.curve(to: NSPoint(x: 61.5, y: 6.88), controlPoint1: NSPoint(x: 60.21, y: 4), controlPoint2: NSPoint(x: 61.5, y: 5.29))
bezierPath.curve(to: NSPoint(x: 58.62, y: 9.75), controlPoint1: NSPoint(x: 61.5, y: 8.46), controlPoint2: NSPoint(x: 60.21, y: 9.75))
bezierPath.line(to: NSPoint(x: 58.62, y: 9.75))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 41.38, y: 9.75))
bezierPath.curve(to: NSPoint(x: 38.5, y: 6.88), controlPoint1: NSPoint(x: 39.79, y: 9.75), controlPoint2: NSPoint(x: 38.5, y: 8.46))
bezierPath.curve(to: NSPoint(x: 41.38, y: 4), controlPoint1: NSPoint(x: 38.5, y: 5.29), controlPoint2: NSPoint(x: 39.79, y: 4))
bezierPath.curve(to: NSPoint(x: 44.25, y: 6.88), controlPoint1: NSPoint(x: 42.96, y: 4), controlPoint2: NSPoint(x: 44.25, y: 5.29))
bezierPath.curve(to: NSPoint(x: 41.38, y: 9.75), controlPoint1: NSPoint(x: 44.25, y: 8.46), controlPoint2: NSPoint(x: 42.96, y: 9.75))
bezierPath.line(to: NSPoint(x: 41.38, y: 9.75))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 35.62, y: 21.25))
bezierPath.curve(to: NSPoint(x: 32.75, y: 18.38), controlPoint1: NSPoint(x: 34.04, y: 21.25), controlPoint2: NSPoint(x: 32.75, y: 19.96))
bezierPath.curve(to: NSPoint(x: 35.62, y: 15.5), controlPoint1: NSPoint(x: 32.75, y: 16.79), controlPoint2: NSPoint(x: 34.04, y: 15.5))
bezierPath.curve(to: NSPoint(x: 38.5, y: 18.38), controlPoint1: NSPoint(x: 37.21, y: 15.5), controlPoint2: NSPoint(x: 38.5, y: 16.79))
bezierPath.curve(to: NSPoint(x: 35.62, y: 21.25), controlPoint1: NSPoint(x: 38.5, y: 19.96), controlPoint2: NSPoint(x: 37.21, y: 21.25))
bezierPath.line(to: NSPoint(x: 35.62, y: 21.25))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 52.88, y: 21.25))
bezierPath.curve(to: NSPoint(x: 50, y: 18.38), controlPoint1: NSPoint(x: 51.29, y: 21.25), controlPoint2: NSPoint(x: 50, y: 19.96))
bezierPath.curve(to: NSPoint(x: 52.88, y: 15.5), controlPoint1: NSPoint(x: 50, y: 16.79), controlPoint2: NSPoint(x: 51.29, y: 15.5))
bezierPath.curve(to: NSPoint(x: 55.75, y: 18.38), controlPoint1: NSPoint(x: 54.46, y: 15.5), controlPoint2: NSPoint(x: 55.75, y: 16.79))
bezierPath.curve(to: NSPoint(x: 52.88, y: 21.25), controlPoint1: NSPoint(x: 55.75, y: 19.96), controlPoint2: NSPoint(x: 54.46, y: 21.25))
bezierPath.line(to: NSPoint(x: 52.88, y: 21.25))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawSun(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 89.33, y: 25.43))
bezierPath.line(to: NSPoint(x: 9.17, y: 25.43))
bezierPath.curve(to: NSPoint(x: 6.08, y: 22.36), controlPoint1: NSPoint(x: 7.46, y: 25.43), controlPoint2: NSPoint(x: 6.08, y: 24.05))
bezierPath.curve(to: NSPoint(x: 9.17, y: 19.29), controlPoint1: NSPoint(x: 6.08, y: 20.66), controlPoint2: NSPoint(x: 7.46, y: 19.29))
bezierPath.line(to: NSPoint(x: 89.33, y: 19.29))
bezierPath.curve(to: NSPoint(x: 92.42, y: 22.36), controlPoint1: NSPoint(x: 91.04, y: 19.29), controlPoint2: NSPoint(x: 92.42, y: 20.66))
bezierPath.curve(to: NSPoint(x: 89.33, y: 25.43), controlPoint1: NSPoint(x: 92.42, y: 24.05), controlPoint2: NSPoint(x: 91.04, y: 25.43))
bezierPath.line(to: NSPoint(x: 89.33, y: 25.43))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 12.25, y: 67.16))
bezierPath.curve(to: NSPoint(x: 16.61, y: 67.16), controlPoint1: NSPoint(x: 13.46, y: 65.96), controlPoint2: NSPoint(x: 15.41, y: 65.96))
bezierPath.curve(to: NSPoint(x: 16.61, y: 71.5), controlPoint1: NSPoint(x: 17.82, y: 68.36), controlPoint2: NSPoint(x: 17.82, y: 70.3))
bezierPath.line(to: NSPoint(x: 12.25, y: 75.84))
bezierPath.curve(to: NSPoint(x: 7.89, y: 75.84), controlPoint1: NSPoint(x: 11.04, y: 77.04), controlPoint2: NSPoint(x: 9.1, y: 77.04))
bezierPath.curve(to: NSPoint(x: 7.89, y: 71.5), controlPoint1: NSPoint(x: 6.68, y: 74.64), controlPoint2: NSPoint(x: 6.68, y: 72.7))
bezierPath.line(to: NSPoint(x: 12.25, y: 67.16))
bezierPath.line(to: NSPoint(x: 12.25, y: 67.16))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 92.42, y: 37.71))
bezierPath.line(to: NSPoint(x: 6.08, y: 37.71))
bezierPath.curve(to: NSPoint(x: 3, y: 34.64), controlPoint1: NSPoint(x: 4.38, y: 37.71), controlPoint2: NSPoint(x: 3, y: 36.34))
bezierPath.curve(to: NSPoint(x: 6.08, y: 31.57), controlPoint1: NSPoint(x: 3, y: 32.94), controlPoint2: NSPoint(x: 4.38, y: 31.57))
bezierPath.line(to: NSPoint(x: 92.42, y: 31.57))
bezierPath.curve(to: NSPoint(x: 95.5, y: 34.64), controlPoint1: NSPoint(x: 94.12, y: 31.57), controlPoint2: NSPoint(x: 95.5, y: 32.94))
bezierPath.curve(to: NSPoint(x: 92.42, y: 37.71), controlPoint1: NSPoint(x: 95.5, y: 36.34), controlPoint2: NSPoint(x: 94.12, y: 37.71))
bezierPath.line(to: NSPoint(x: 92.42, y: 37.71))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 80.08, y: 13.14))
bezierPath.line(to: NSPoint(x: 18.42, y: 13.14))
bezierPath.curve(to: NSPoint(x: 15.33, y: 10.07), controlPoint1: NSPoint(x: 16.71, y: 13.14), controlPoint2: NSPoint(x: 15.33, y: 11.77))
bezierPath.curve(to: NSPoint(x: 18.42, y: 7), controlPoint1: NSPoint(x: 15.33, y: 8.37), controlPoint2: NSPoint(x: 16.71, y: 7))
bezierPath.line(to: NSPoint(x: 80.08, y: 7))
bezierPath.curve(to: NSPoint(x: 83.17, y: 10.07), controlPoint1: NSPoint(x: 81.79, y: 7), controlPoint2: NSPoint(x: 83.17, y: 8.37))
bezierPath.curve(to: NSPoint(x: 80.08, y: 13.14), controlPoint1: NSPoint(x: 83.17, y: 11.77), controlPoint2: NSPoint(x: 81.79, y: 13.14))
bezierPath.line(to: NSPoint(x: 80.08, y: 13.14))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 49.25, y: 80.71))
bezierPath.curve(to: NSPoint(x: 52.33, y: 83.79), controlPoint1: NSPoint(x: 50.95, y: 80.71), controlPoint2: NSPoint(x: 52.33, y: 82.09))
bezierPath.line(to: NSPoint(x: 52.33, y: 89.93))
bezierPath.curve(to: NSPoint(x: 49.25, y: 93), controlPoint1: NSPoint(x: 52.33, y: 91.63), controlPoint2: NSPoint(x: 50.95, y: 93))
bezierPath.curve(to: NSPoint(x: 46.17, y: 89.93), controlPoint1: NSPoint(x: 47.55, y: 93), controlPoint2: NSPoint(x: 46.17, y: 91.63))
bezierPath.line(to: NSPoint(x: 46.17, y: 83.79))
bezierPath.curve(to: NSPoint(x: 49.25, y: 80.71), controlPoint1: NSPoint(x: 46.17, y: 82.09), controlPoint2: NSPoint(x: 47.55, y: 80.71))
bezierPath.line(to: NSPoint(x: 49.25, y: 80.71))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 86.25, y: 67.16))
bezierPath.line(to: NSPoint(x: 90.61, y: 71.5))
bezierPath.curve(to: NSPoint(x: 90.61, y: 75.84), controlPoint1: NSPoint(x: 91.82, y: 72.7), controlPoint2: NSPoint(x: 91.82, y: 74.64))
bezierPath.curve(to: NSPoint(x: 86.25, y: 75.84), controlPoint1: NSPoint(x: 89.41, y: 77.04), controlPoint2: NSPoint(x: 87.46, y: 77.04))
bezierPath.line(to: NSPoint(x: 81.89, y: 71.5))
bezierPath.curve(to: NSPoint(x: 81.89, y: 67.16), controlPoint1: NSPoint(x: 80.68, y: 70.3), controlPoint2: NSPoint(x: 80.68, y: 68.36))
bezierPath.curve(to: NSPoint(x: 86.25, y: 67.16), controlPoint1: NSPoint(x: 83.1, y: 65.96), controlPoint2: NSPoint(x: 85.04, y: 65.96))
bezierPath.line(to: NSPoint(x: 86.25, y: 67.16))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 19.09, y: 43.86))
bezierPath.curve(to: NSPoint(x: 49.25, y: 68.43), controlPoint1: NSPoint(x: 21.95, y: 57.87), controlPoint2: NSPoint(x: 34.33, y: 68.43))
bezierPath.curve(to: NSPoint(x: 79.41, y: 43.86), controlPoint1: NSPoint(x: 64.17, y: 68.43), controlPoint2: NSPoint(x: 76.55, y: 57.87))
bezierPath.line(to: NSPoint(x: 85.9, y: 43.86))
bezierPath.curve(to: NSPoint(x: 49.25, y: 74.57), controlPoint1: NSPoint(x: 83.53, y: 61.18), controlPoint2: NSPoint(x: 68.05, y: 74.57))
bezierPath.curve(to: NSPoint(x: 12.6, y: 43.86), controlPoint1: NSPoint(x: 30.45, y: 74.57), controlPoint2: NSPoint(x: 14.97, y: 61.18))
bezierPath.line(to: NSPoint(x: 19.09, y: 43.86))
bezierPath.line(to: NSPoint(x: 19.09, y: 43.86))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawMoon(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 26.38, y: 36.17))
bezierPath.curve(to: NSPoint(x: 23.75, y: 47.35), controlPoint1: NSPoint(x: 24.5, y: 40.35), controlPoint2: NSPoint(x: 23.75, y: 43.46))
bezierPath.curve(to: NSPoint(x: 44.75, y: 80.65), controlPoint1: NSPoint(x: 23.75, y: 68.63), controlPoint2: NSPoint(x: 35.22, y: 75.29))
bezierPath.curve(to: NSPoint(x: 65.75, y: 83.27), controlPoint1: NSPoint(x: 51.72, y: 83.92), controlPoint2: NSPoint(x: 60.25, y: 84.63))
bezierPath.curve(to: NSPoint(x: 44.58, y: 44.87), controlPoint1: NSPoint(x: 54.99, y: 78.23), controlPoint2: NSPoint(x: 44.58, y: 61.96))
bezierPath.curve(to: NSPoint(x: 45.33, y: 36.17), controlPoint1: NSPoint(x: 44.58, y: 41.86), controlPoint2: NSPoint(x: 44.88, y: 38.97))
bezierPath.line(to: NSPoint(x: 26.38, y: 36.17))
bezierPath.line(to: NSPoint(x: 26.38, y: 36.17))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 89.38, y: 36.17))
bezierPath.line(to: NSPoint(x: 51.14, y: 36.17))
bezierPath.curve(to: NSPoint(x: 50, y: 45.33), controlPoint1: NSPoint(x: 50.45, y: 39.12), controlPoint2: NSPoint(x: 50, y: 42.16))
bezierPath.curve(to: NSPoint(x: 78.05, y: 83.86), controlPoint1: NSPoint(x: 50, y: 63.32), controlPoint2: NSPoint(x: 61.77, y: 78.56))
bezierPath.curve(to: NSPoint(x: 59.19, y: 88.5), controlPoint1: NSPoint(x: 72.4, y: 86.81), controlPoint2: NSPoint(x: 66, y: 88.5))
bezierPath.curve(to: NSPoint(x: 18.5, y: 47.94), controlPoint1: NSPoint(x: 36.71, y: 88.5), controlPoint2: NSPoint(x: 18.5, y: 70.34))
bezierPath.curve(to: NSPoint(x: 20.26, y: 36.17), controlPoint1: NSPoint(x: 18.5, y: 43.85), controlPoint2: NSPoint(x: 19.12, y: 39.9))
bezierPath.line(to: NSPoint(x: 10.62, y: 36.17))
bezierPath.curve(to: NSPoint(x: 8, y: 33.55), controlPoint1: NSPoint(x: 9.17, y: 36.17), controlPoint2: NSPoint(x: 8, y: 34.99))
bezierPath.curve(to: NSPoint(x: 10.62, y: 30.93), controlPoint1: NSPoint(x: 8, y: 32.1), controlPoint2: NSPoint(x: 9.17, y: 30.93))
bezierPath.line(to: NSPoint(x: 89.38, y: 30.93))
bezierPath.curve(to: NSPoint(x: 92, y: 33.55), controlPoint1: NSPoint(x: 90.83, y: 30.93), controlPoint2: NSPoint(x: 92, y: 32.1))
bezierPath.curve(to: NSPoint(x: 89.38, y: 36.17), controlPoint1: NSPoint(x: 92, y: 34.99), controlPoint2: NSPoint(x: 90.83, y: 36.17))
bezierPath.line(to: NSPoint(x: 89.38, y: 36.17))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 57.88, y: 25.7))
bezierPath.line(to: NSPoint(x: 21.12, y: 25.7))
bezierPath.curve(to: NSPoint(x: 18.5, y: 23.08), controlPoint1: NSPoint(x: 19.67, y: 25.7), controlPoint2: NSPoint(x: 18.5, y: 24.53))
bezierPath.curve(to: NSPoint(x: 21.12, y: 20.47), controlPoint1: NSPoint(x: 18.5, y: 21.64), controlPoint2: NSPoint(x: 19.67, y: 20.47))
bezierPath.line(to: NSPoint(x: 57.88, y: 20.47))
bezierPath.curve(to: NSPoint(x: 60.5, y: 23.08), controlPoint1: NSPoint(x: 59.33, y: 20.47), controlPoint2: NSPoint(x: 60.5, y: 21.64))
bezierPath.curve(to: NSPoint(x: 57.88, y: 25.7), controlPoint1: NSPoint(x: 60.5, y: 24.53), controlPoint2: NSPoint(x: 59.33, y: 25.7))
bezierPath.line(to: NSPoint(x: 57.88, y: 25.7))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 52.62, y: 15.23))
bezierPath.line(to: NSPoint(x: 26.38, y: 15.23))
bezierPath.curve(to: NSPoint(x: 23.75, y: 12.62), controlPoint1: NSPoint(x: 24.92, y: 15.23), controlPoint2: NSPoint(x: 23.75, y: 14.06))
bezierPath.curve(to: NSPoint(x: 26.38, y: 10), controlPoint1: NSPoint(x: 23.75, y: 11.17), controlPoint2: NSPoint(x: 24.92, y: 10))
bezierPath.line(to: NSPoint(x: 52.62, y: 10))
bezierPath.curve(to: NSPoint(x: 55.25, y: 12.62), controlPoint1: NSPoint(x: 54.08, y: 10), controlPoint2: NSPoint(x: 55.25, y: 11.17))
bezierPath.curve(to: NSPoint(x: 52.62, y: 15.23), controlPoint1: NSPoint(x: 55.25, y: 14.06), controlPoint2: NSPoint(x: 54.08, y: 15.23))
bezierPath.line(to: NSPoint(x: 52.62, y: 15.23))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawOK(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 87.87, y: 70.73))
bezierPath.curve(to: NSPoint(x: 37.77, y: 19.76), controlPoint1: NSPoint(x: 87.87, y: 70.73), controlPoint2: NSPoint(x: 38.55, y: 20.57))
bezierPath.curve(to: NSPoint(x: 29.42, y: 19.76), controlPoint1: NSPoint(x: 35.46, y: 17.42), controlPoint2: NSPoint(x: 31.73, y: 17.42))
bezierPath.curve(to: NSPoint(x: 10.46, y: 39.06), controlPoint1: NSPoint(x: 29.42, y: 19.76), controlPoint2: NSPoint(x: 10.52, y: 39))
bezierPath.curve(to: NSPoint(x: 10.63, y: 47.39), controlPoint1: NSPoint(x: 8.33, y: 41.42), controlPoint2: NSPoint(x: 8.39, y: 45.08))
bezierPath.curve(to: NSPoint(x: 18.98, y: 47.39), controlPoint1: NSPoint(x: 12.94, y: 49.73), controlPoint2: NSPoint(x: 16.68, y: 49.73))
bezierPath.line(to: NSPoint(x: 33.59, y: 32.51))
bezierPath.line(to: NSPoint(x: 79.52, y: 79.23))
bezierPath.curve(to: NSPoint(x: 87.87, y: 79.23), controlPoint1: NSPoint(x: 81.82, y: 81.57), controlPoint2: NSPoint(x: 85.56, y: 81.57))
bezierPath.curve(to: NSPoint(x: 87.87, y: 70.73), controlPoint1: NSPoint(x: 90.17, y: 76.9), controlPoint2: NSPoint(x: 90.17, y: 73.09))
bezierPath.line(to: NSPoint(x: 87.87, y: 70.73))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 92.04, y: 83.47))
bezierPath.curve(to: NSPoint(x: 75.34, y: 83.47), controlPoint1: NSPoint(x: 87.43, y: 88.18), controlPoint2: NSPoint(x: 79.95, y: 88.18))
bezierPath.line(to: NSPoint(x: 33.59, y: 41.02))
bezierPath.line(to: NSPoint(x: 23.16, y: 51.63))
bezierPath.curve(to: NSPoint(x: 6.46, y: 51.63), controlPoint1: NSPoint(x: 18.55, y: 56.3), controlPoint2: NSPoint(x: 11.07, y: 56.3))
bezierPath.curve(to: NSPoint(x: 6.46, y: 34.64), controlPoint1: NSPoint(x: 1.85, y: 46.93), controlPoint2: NSPoint(x: 1.85, y: 39.32))
bezierPath.line(to: NSPoint(x: 25.24, y: 15.52))
bezierPath.curve(to: NSPoint(x: 41.94, y: 15.52), controlPoint1: NSPoint(x: 29.86, y: 10.82), controlPoint2: NSPoint(x: 37.33, y: 10.82))
bezierPath.line(to: NSPoint(x: 92.04, y: 66.49))
bezierPath.curve(to: NSPoint(x: 92.04, y: 83.47), controlPoint1: NSPoint(x: 96.65, y: 71.19), controlPoint2: NSPoint(x: 96.65, y: 78.8))
bezierPath.line(to: NSPoint(x: 92.04, y: 83.47))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawSearch(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 42.87, y: 25.22))
bezierPath.curve(to: NSPoint(x: 10.83, y: 56.73), controlPoint1: NSPoint(x: 25.17, y: 25.22), controlPoint2: NSPoint(x: 10.83, y: 39.31))
bezierPath.curve(to: NSPoint(x: 42.87, y: 88.26), controlPoint1: NSPoint(x: 10.83, y: 74.14), controlPoint2: NSPoint(x: 25.17, y: 88.26))
bezierPath.curve(to: NSPoint(x: 74.91, y: 56.73), controlPoint1: NSPoint(x: 60.56, y: 88.26), controlPoint2: NSPoint(x: 74.91, y: 74.14))
bezierPath.curve(to: NSPoint(x: 42.87, y: 25.22), controlPoint1: NSPoint(x: 74.91, y: 39.31), controlPoint2: NSPoint(x: 60.56, y: 25.22))
bezierPath.line(to: NSPoint(x: 42.87, y: 25.22))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 94.15, y: 8.9))
bezierPath.line(to: NSPoint(x: 70.91, y: 31.77))
bezierPath.curve(to: NSPoint(x: 80.73, y: 56.73), controlPoint1: NSPoint(x: 76.99, y: 38.39), controlPoint2: NSPoint(x: 80.73, y: 47.11))
bezierPath.curve(to: NSPoint(x: 42.87, y: 94), controlPoint1: NSPoint(x: 80.73, y: 77.32), controlPoint2: NSPoint(x: 63.78, y: 94))
bezierPath.curve(to: NSPoint(x: 5, y: 56.73), controlPoint1: NSPoint(x: 21.95, y: 94), controlPoint2: NSPoint(x: 5, y: 77.32))
bezierPath.curve(to: NSPoint(x: 42.87, y: 19.48), controlPoint1: NSPoint(x: 5, y: 36.16), controlPoint2: NSPoint(x: 21.95, y: 19.48))
bezierPath.curve(to: NSPoint(x: 66.7, y: 27.81), controlPoint1: NSPoint(x: 51.9, y: 19.48), controlPoint2: NSPoint(x: 60.19, y: 22.6))
bezierPath.line(to: NSPoint(x: 90.03, y: 4.85))
bezierPath.curve(to: NSPoint(x: 94.15, y: 4.85), controlPoint1: NSPoint(x: 91.17, y: 3.73), controlPoint2: NSPoint(x: 93.01, y: 3.73))
bezierPath.curve(to: NSPoint(x: 94.15, y: 8.9), controlPoint1: NSPoint(x: 95.28, y: 5.95), controlPoint2: NSPoint(x: 95.28, y: 7.78))
bezierPath.line(to: NSPoint(x: 94.15, y: 8.9))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawEmpty(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 84.06, y: 95.5))
bezierPath.line(to: NSPoint(x: 61.19, y: 95.5))
bezierPath.line(to: NSPoint(x: 61.19, y: 89.78))
bezierPath.line(to: NSPoint(x: 84.06, y: 89.78))
bezierPath.curve(to: NSPoint(x: 89.78, y: 84.06), controlPoint1: NSPoint(x: 87.22, y: 89.78), controlPoint2: NSPoint(x: 89.78, y: 87.22))
bezierPath.line(to: NSPoint(x: 89.78, y: 61.19))
bezierPath.line(to: NSPoint(x: 95.5, y: 61.19))
bezierPath.line(to: NSPoint(x: 95.5, y: 84.06))
bezierPath.curve(to: NSPoint(x: 84.06, y: 95.5), controlPoint1: NSPoint(x: 95.5, y: 90.38), controlPoint2: NSPoint(x: 90.38, y: 95.5))
bezierPath.line(to: NSPoint(x: 84.06, y: 95.5))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 89.78, y: 15.44))
bezierPath.curve(to: NSPoint(x: 84.06, y: 9.72), controlPoint1: NSPoint(x: 89.78, y: 12.28), controlPoint2: NSPoint(x: 87.22, y: 9.72))
bezierPath.line(to: NSPoint(x: 61.19, y: 9.72))
bezierPath.line(to: NSPoint(x: 61.19, y: 4))
bezierPath.line(to: NSPoint(x: 84.06, y: 4))
bezierPath.curve(to: NSPoint(x: 95.5, y: 15.44), controlPoint1: NSPoint(x: 90.38, y: 4), controlPoint2: NSPoint(x: 95.5, y: 9.12))
bezierPath.line(to: NSPoint(x: 95.5, y: 38.31))
bezierPath.line(to: NSPoint(x: 89.78, y: 38.31))
bezierPath.line(to: NSPoint(x: 89.78, y: 15.44))
bezierPath.line(to: NSPoint(x: 89.78, y: 15.44))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 9.72, y: 15.44))
bezierPath.line(to: NSPoint(x: 9.72, y: 38.31))
bezierPath.line(to: NSPoint(x: 4, y: 38.31))
bezierPath.line(to: NSPoint(x: 4, y: 15.44))
bezierPath.curve(to: NSPoint(x: 15.44, y: 4), controlPoint1: NSPoint(x: 4, y: 9.12), controlPoint2: NSPoint(x: 9.12, y: 4))
bezierPath.line(to: NSPoint(x: 38.31, y: 4))
bezierPath.line(to: NSPoint(x: 38.31, y: 9.72))
bezierPath.line(to: NSPoint(x: 15.44, y: 9.72))
bezierPath.curve(to: NSPoint(x: 9.72, y: 15.44), controlPoint1: NSPoint(x: 12.28, y: 9.72), controlPoint2: NSPoint(x: 9.72, y: 12.28))
bezierPath.line(to: NSPoint(x: 9.72, y: 15.44))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 4, y: 84.06))
bezierPath.line(to: NSPoint(x: 4, y: 61.19))
bezierPath.line(to: NSPoint(x: 9.72, y: 61.19))
bezierPath.line(to: NSPoint(x: 9.72, y: 84.06))
bezierPath.curve(to: NSPoint(x: 15.44, y: 89.78), controlPoint1: NSPoint(x: 9.72, y: 87.22), controlPoint2: NSPoint(x: 12.28, y: 89.78))
bezierPath.line(to: NSPoint(x: 38.31, y: 89.78))
bezierPath.line(to: NSPoint(x: 38.31, y: 95.5))
bezierPath.line(to: NSPoint(x: 15.44, y: 95.5))
bezierPath.curve(to: NSPoint(x: 4, y: 84.06), controlPoint1: NSPoint(x: 9.12, y: 95.5), controlPoint2: NSPoint(x: 4, y: 90.38))
bezierPath.line(to: NSPoint(x: 4, y: 84.06))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawRepair(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 79.87, y: 51.24))
bezierPath.curve(to: NSPoint(x: 56.01, y: 47.83), controlPoint1: NSPoint(x: 73.4, y: 44.78), controlPoint2: NSPoint(x: 63.67, y: 43.7))
bezierPath.line(to: NSPoint(x: 22.65, y: 14.49))
bezierPath.curve(to: NSPoint(x: 14.47, y: 14.49), controlPoint1: NSPoint(x: 20.39, y: 12.24), controlPoint2: NSPoint(x: 16.73, y: 12.24))
bezierPath.curve(to: NSPoint(x: 14.47, y: 22.66), controlPoint1: NSPoint(x: 12.22, y: 16.75), controlPoint2: NSPoint(x: 12.22, y: 20.4))
bezierPath.line(to: NSPoint(x: 47.83, y: 55.99))
bezierPath.curve(to: NSPoint(x: 51.26, y: 79.83), controlPoint1: NSPoint(x: 43.71, y: 63.65), controlPoint2: NSPoint(x: 44.79, y: 73.36))
bezierPath.curve(to: NSPoint(x: 65.28, y: 85.61), controlPoint1: NSPoint(x: 55.14, y: 83.7), controlPoint2: NSPoint(x: 60.2, y: 85.55))
bezierPath.curve(to: NSPoint(x: 65.57, y: 65.53), controlPoint1: NSPoint(x: 59.96, y: 79.95), controlPoint2: NSPoint(x: 60.03, y: 71.06))
bezierPath.curve(to: NSPoint(x: 85.65, y: 65.25), controlPoint1: NSPoint(x: 71.1, y: 60), controlPoint2: NSPoint(x: 79.99, y: 59.93))
bezierPath.curve(to: NSPoint(x: 79.87, y: 51.24), controlPoint1: NSPoint(x: 85.59, y: 60.18), controlPoint2: NSPoint(x: 83.75, y: 55.12))
bezierPath.line(to: NSPoint(x: 79.87, y: 51.24))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 89.09, y: 76.36))
bezierPath.curve(to: NSPoint(x: 81.91, y: 69.62), controlPoint1: NSPoint(x: 87.67, y: 74.76), controlPoint2: NSPoint(x: 85.3, y: 72.72))
bezierPath.curve(to: NSPoint(x: 69.65, y: 69.62), controlPoint1: NSPoint(x: 78.32, y: 66.03), controlPoint2: NSPoint(x: 73.24, y: 66.03))
bezierPath.curve(to: NSPoint(x: 69.65, y: 81.87), controlPoint1: NSPoint(x: 66.06, y: 73.21), controlPoint2: NSPoint(x: 66.06, y: 78.28))
bezierPath.curve(to: NSPoint(x: 76.46, y: 89.1), controlPoint1: NSPoint(x: 72.96, y: 85.17), controlPoint2: NSPoint(x: 76.52, y: 89.09))
bezierPath.curve(to: NSPoint(x: 47.17, y: 83.91), controlPoint1: NSPoint(x: 66.85, y: 93.54), controlPoint2: NSPoint(x: 55.09, y: 91.82))
bezierPath.curve(to: NSPoint(x: 40.93, y: 57.26), controlPoint1: NSPoint(x: 39.95, y: 76.7), controlPoint2: NSPoint(x: 37.89, y: 66.31))
bezierPath.line(to: NSPoint(x: 10.39, y: 26.74))
bezierPath.curve(to: NSPoint(x: 10.39, y: 10.41), controlPoint1: NSPoint(x: 5.87, y: 22.23), controlPoint2: NSPoint(x: 5.87, y: 14.92))
bezierPath.curve(to: NSPoint(x: 26.74, y: 10.41), controlPoint1: NSPoint(x: 14.9, y: 5.9), controlPoint2: NSPoint(x: 22.22, y: 5.9))
bezierPath.line(to: NSPoint(x: 57.28, y: 40.93))
bezierPath.curve(to: NSPoint(x: 83.96, y: 47.16), controlPoint1: NSPoint(x: 66.34, y: 37.89), controlPoint2: NSPoint(x: 76.74, y: 39.95))
bezierPath.curve(to: NSPoint(x: 89.09, y: 76.36), controlPoint1: NSPoint(x: 91.87, y: 55.07), controlPoint2: NSPoint(x: 93.51, y: 66.76))
bezierPath.line(to: NSPoint(x: 89.09, y: 76.36))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawAlarm(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 76.81, y: 89))
bezierPath.line(to: NSPoint(x: 71.94, y: 89))
bezierPath.line(to: NSPoint(x: 71.94, y: 84.12))
bezierPath.line(to: NSPoint(x: 76.81, y: 84.12))
bezierPath.curve(to: NSPoint(x: 84.12, y: 76.81), controlPoint1: NSPoint(x: 80.85, y: 84.12), controlPoint2: NSPoint(x: 84.12, y: 80.85))
bezierPath.line(to: NSPoint(x: 84.12, y: 71.94))
bezierPath.line(to: NSPoint(x: 89, y: 71.94))
bezierPath.line(to: NSPoint(x: 89, y: 76.81))
bezierPath.curve(to: NSPoint(x: 76.81, y: 89), controlPoint1: NSPoint(x: 89, y: 83.54), controlPoint2: NSPoint(x: 83.54, y: 89))
bezierPath.line(to: NSPoint(x: 76.81, y: 89))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 50, y: 20.75))
bezierPath.curve(to: NSPoint(x: 20.75, y: 50), controlPoint1: NSPoint(x: 33.85, y: 20.75), controlPoint2: NSPoint(x: 20.75, y: 33.84))
bezierPath.curve(to: NSPoint(x: 50, y: 79.25), controlPoint1: NSPoint(x: 20.75, y: 66.15), controlPoint2: NSPoint(x: 33.85, y: 79.25))
bezierPath.curve(to: NSPoint(x: 79.25, y: 50), controlPoint1: NSPoint(x: 66.15, y: 79.25), controlPoint2: NSPoint(x: 79.25, y: 66.15))
bezierPath.curve(to: NSPoint(x: 50, y: 20.75), controlPoint1: NSPoint(x: 79.25, y: 33.84), controlPoint2: NSPoint(x: 66.15, y: 20.75))
bezierPath.line(to: NSPoint(x: 50, y: 20.75))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 84.12, y: 50))
bezierPath.curve(to: NSPoint(x: 50, y: 84.12), controlPoint1: NSPoint(x: 84.12, y: 68.84), controlPoint2: NSPoint(x: 68.85, y: 84.12))
bezierPath.curve(to: NSPoint(x: 15.88, y: 50), controlPoint1: NSPoint(x: 31.15, y: 84.12), controlPoint2: NSPoint(x: 15.88, y: 68.84))
bezierPath.curve(to: NSPoint(x: 33.66, y: 20.04), controlPoint1: NSPoint(x: 15.88, y: 37.07), controlPoint2: NSPoint(x: 23.06, y: 25.83))
bezierPath.line(to: NSPoint(x: 25.62, y: 11))
bezierPath.line(to: NSPoint(x: 32.94, y: 11))
bezierPath.line(to: NSPoint(x: 39.48, y: 17.54))
bezierPath.curve(to: NSPoint(x: 50, y: 15.88), controlPoint1: NSPoint(x: 42.8, y: 16.47), controlPoint2: NSPoint(x: 46.33, y: 15.88))
bezierPath.curve(to: NSPoint(x: 60.52, y: 17.54), controlPoint1: NSPoint(x: 53.67, y: 15.88), controlPoint2: NSPoint(x: 57.2, y: 16.47))
bezierPath.line(to: NSPoint(x: 67.06, y: 11))
bezierPath.line(to: NSPoint(x: 74.38, y: 11))
bezierPath.line(to: NSPoint(x: 66.34, y: 20.04))
bezierPath.curve(to: NSPoint(x: 84.12, y: 50), controlPoint1: NSPoint(x: 76.94, y: 25.83), controlPoint2: NSPoint(x: 84.12, y: 37.07))
bezierPath.line(to: NSPoint(x: 84.12, y: 50))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 67.06, y: 52.44))
bezierPath.line(to: NSPoint(x: 52.44, y: 52.44))
bezierPath.line(to: NSPoint(x: 52.44, y: 69.5))
bezierPath.curve(to: NSPoint(x: 50, y: 71.94), controlPoint1: NSPoint(x: 52.44, y: 70.85), controlPoint2: NSPoint(x: 51.35, y: 71.94))
bezierPath.curve(to: NSPoint(x: 47.56, y: 69.5), controlPoint1: NSPoint(x: 48.65, y: 71.94), controlPoint2: NSPoint(x: 47.56, y: 70.85))
bezierPath.line(to: NSPoint(x: 47.56, y: 50))
bezierPath.curve(to: NSPoint(x: 50, y: 47.56), controlPoint1: NSPoint(x: 47.56, y: 48.65), controlPoint2: NSPoint(x: 48.65, y: 47.56))
bezierPath.line(to: NSPoint(x: 67.06, y: 47.56))
bezierPath.curve(to: NSPoint(x: 69.5, y: 50), controlPoint1: NSPoint(x: 68.41, y: 47.56), controlPoint2: NSPoint(x: 69.5, y: 48.65))
bezierPath.curve(to: NSPoint(x: 67.06, y: 52.44), controlPoint1: NSPoint(x: 69.5, y: 51.35), controlPoint2: NSPoint(x: 68.41, y: 52.44))
bezierPath.line(to: NSPoint(x: 67.06, y: 52.44))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 15.88, y: 76.81))
bezierPath.curve(to: NSPoint(x: 23.19, y: 84.12), controlPoint1: NSPoint(x: 15.88, y: 80.85), controlPoint2: NSPoint(x: 19.15, y: 84.12))
bezierPath.line(to: NSPoint(x: 28.06, y: 84.12))
bezierPath.line(to: NSPoint(x: 28.06, y: 89))
bezierPath.line(to: NSPoint(x: 23.19, y: 89))
bezierPath.curve(to: NSPoint(x: 11, y: 76.81), controlPoint1: NSPoint(x: 16.46, y: 89), controlPoint2: NSPoint(x: 11, y: 83.54))
bezierPath.line(to: NSPoint(x: 11, y: 71.94))
bezierPath.line(to: NSPoint(x: 15.88, y: 71.94))
bezierPath.line(to: NSPoint(x: 15.88, y: 76.81))
bezierPath.line(to: NSPoint(x: 15.88, y: 76.81))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawMap(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 70.25, y: 46.91))
bezierPath.curve(to: NSPoint(x: 72.84, y: 44.31), controlPoint1: NSPoint(x: 70.25, y: 45.47), controlPoint2: NSPoint(x: 71.41, y: 44.31))
bezierPath.curve(to: NSPoint(x: 75.44, y: 46.91), controlPoint1: NSPoint(x: 74.28, y: 44.31), controlPoint2: NSPoint(x: 75.44, y: 45.47))
bezierPath.line(to: NSPoint(x: 75.44, y: 67.66))
bezierPath.curve(to: NSPoint(x: 72.84, y: 70.25), controlPoint1: NSPoint(x: 75.44, y: 69.09), controlPoint2: NSPoint(x: 74.28, y: 70.25))
bezierPath.curve(to: NSPoint(x: 70.25, y: 67.66), controlPoint1: NSPoint(x: 71.41, y: 70.25), controlPoint2: NSPoint(x: 70.25, y: 69.09))
bezierPath.line(to: NSPoint(x: 70.25, y: 46.91))
bezierPath.line(to: NSPoint(x: 70.25, y: 46.91))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 85.81, y: 22.27))
bezierPath.line(to: NSPoint(x: 70.25, y: 33.94))
bezierPath.line(to: NSPoint(x: 49.5, y: 18.38))
bezierPath.line(to: NSPoint(x: 28.75, y: 26.16))
bezierPath.line(to: NSPoint(x: 13.19, y: 16.43))
bezierPath.line(to: NSPoint(x: 13.19, y: 68.3))
bezierPath.line(to: NSPoint(x: 28.75, y: 78.03))
bezierPath.line(to: NSPoint(x: 49.5, y: 70.25))
bezierPath.line(to: NSPoint(x: 70.25, y: 85.81))
bezierPath.line(to: NSPoint(x: 85.81, y: 74.14))
bezierPath.line(to: NSPoint(x: 85.81, y: 22.27))
bezierPath.line(to: NSPoint(x: 85.81, y: 22.27))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 70.25, y: 91))
bezierPath.line(to: NSPoint(x: 49.5, y: 75.44))
bezierPath.line(to: NSPoint(x: 28.75, y: 83.22))
bezierPath.line(to: NSPoint(x: 8, y: 70.25))
bezierPath.line(to: NSPoint(x: 8, y: 8))
bezierPath.line(to: NSPoint(x: 28.75, y: 20.97))
bezierPath.line(to: NSPoint(x: 49.5, y: 13.19))
bezierPath.line(to: NSPoint(x: 70.25, y: 28.75))
bezierPath.line(to: NSPoint(x: 91, y: 13.19))
bezierPath.line(to: NSPoint(x: 91, y: 75.44))
bezierPath.line(to: NSPoint(x: 70.25, y: 91))
bezierPath.line(to: NSPoint(x: 70.25, y: 91))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 52.09, y: 57.28))
bezierPath.curve(to: NSPoint(x: 49.5, y: 54.69), controlPoint1: NSPoint(x: 50.66, y: 57.28), controlPoint2: NSPoint(x: 49.5, y: 56.12))
bezierPath.line(to: NSPoint(x: 49.5, y: 39.12))
bezierPath.curve(to: NSPoint(x: 52.09, y: 36.53), controlPoint1: NSPoint(x: 49.5, y: 37.69), controlPoint2: NSPoint(x: 50.66, y: 36.53))
bezierPath.curve(to: NSPoint(x: 54.69, y: 39.12), controlPoint1: NSPoint(x: 53.53, y: 36.53), controlPoint2: NSPoint(x: 54.69, y: 37.69))
bezierPath.line(to: NSPoint(x: 54.69, y: 54.69))
bezierPath.curve(to: NSPoint(x: 52.09, y: 57.28), controlPoint1: NSPoint(x: 54.69, y: 56.12), controlPoint2: NSPoint(x: 53.53, y: 57.28))
bezierPath.line(to: NSPoint(x: 52.09, y: 57.28))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 31.34, y: 65.06))
bezierPath.curve(to: NSPoint(x: 28.75, y: 62.47), controlPoint1: NSPoint(x: 29.91, y: 65.06), controlPoint2: NSPoint(x: 28.75, y: 63.9))
bezierPath.line(to: NSPoint(x: 28.75, y: 36.53))
bezierPath.curve(to: NSPoint(x: 31.34, y: 33.94), controlPoint1: NSPoint(x: 28.75, y: 35.1), controlPoint2: NSPoint(x: 29.91, y: 33.94))
bezierPath.curve(to: NSPoint(x: 33.94, y: 36.53), controlPoint1: NSPoint(x: 32.78, y: 33.94), controlPoint2: NSPoint(x: 33.94, y: 35.1))
bezierPath.line(to: NSPoint(x: 33.94, y: 62.47))
bezierPath.curve(to: NSPoint(x: 31.34, y: 65.06), controlPoint1: NSPoint(x: 33.94, y: 63.9), controlPoint2: NSPoint(x: 32.78, y: 65.06))
bezierPath.line(to: NSPoint(x: 31.34, y: 65.06))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawLocation(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 49.5, y: 47.28))
bezierPath.curve(to: NSPoint(x: 41.12, y: 55.63), controlPoint1: NSPoint(x: 44.87, y: 47.28), controlPoint2: NSPoint(x: 41.12, y: 51.02))
bezierPath.curve(to: NSPoint(x: 49.5, y: 63.97), controlPoint1: NSPoint(x: 41.12, y: 60.23), controlPoint2: NSPoint(x: 44.87, y: 63.97))
bezierPath.curve(to: NSPoint(x: 57.88, y: 55.63), controlPoint1: NSPoint(x: 54.13, y: 63.97), controlPoint2: NSPoint(x: 57.88, y: 60.23))
bezierPath.curve(to: NSPoint(x: 49.5, y: 47.28), controlPoint1: NSPoint(x: 57.88, y: 51.02), controlPoint2: NSPoint(x: 54.13, y: 47.28))
bezierPath.line(to: NSPoint(x: 49.5, y: 47.28))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 49.5, y: 69.53))
bezierPath.curve(to: NSPoint(x: 35.54, y: 55.63), controlPoint1: NSPoint(x: 41.79, y: 69.53), controlPoint2: NSPoint(x: 35.54, y: 63.31))
bezierPath.curve(to: NSPoint(x: 49.5, y: 41.72), controlPoint1: NSPoint(x: 35.54, y: 47.94), controlPoint2: NSPoint(x: 41.79, y: 41.72))
bezierPath.curve(to: NSPoint(x: 63.46, y: 55.63), controlPoint1: NSPoint(x: 57.21, y: 41.72), controlPoint2: NSPoint(x: 63.46, y: 47.94))
bezierPath.curve(to: NSPoint(x: 49.5, y: 69.53), controlPoint1: NSPoint(x: 63.46, y: 63.31), controlPoint2: NSPoint(x: 57.21, y: 69.53))
bezierPath.line(to: NSPoint(x: 49.5, y: 69.53))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 49.5, y: 8.34))
bezierPath.curve(to: NSPoint(x: 21.58, y: 55.63), controlPoint1: NSPoint(x: 44.86, y: 8.32), controlPoint2: NSPoint(x: 21.58, y: 44))
bezierPath.curve(to: NSPoint(x: 49.5, y: 83.44), controlPoint1: NSPoint(x: 21.58, y: 70.98), controlPoint2: NSPoint(x: 34.08, y: 83.44))
bezierPath.curve(to: NSPoint(x: 77.42, y: 55.63), controlPoint1: NSPoint(x: 64.92, y: 83.44), controlPoint2: NSPoint(x: 77.42, y: 70.98))
bezierPath.curve(to: NSPoint(x: 49.5, y: 8.34), controlPoint1: NSPoint(x: 77.42, y: 44.15), controlPoint2: NSPoint(x: 54.07, y: 8.32))
bezierPath.line(to: NSPoint(x: 49.5, y: 8.34))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 49.5, y: 89))
bezierPath.curve(to: NSPoint(x: 16, y: 55.63), controlPoint1: NSPoint(x: 31, y: 89), controlPoint2: NSPoint(x: 16, y: 74.06))
bezierPath.curve(to: NSPoint(x: 49.5, y: 0), controlPoint1: NSPoint(x: 16, y: 41.67), controlPoint2: NSPoint(x: 43.93, y: -0.03))
bezierPath.curve(to: NSPoint(x: 83, y: 55.63), controlPoint1: NSPoint(x: 54.98, y: -0.03), controlPoint2: NSPoint(x: 83, y: 41.86))
bezierPath.curve(to: NSPoint(x: 49.5, y: 89), controlPoint1: NSPoint(x: 83, y: 74.06), controlPoint2: NSPoint(x: 68, y: 89))
bezierPath.line(to: NSPoint(x: 49.5, y: 89))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawGamePad(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 70.83, y: 63.67))
bezierPath.curve(to: NSPoint(x: 66.56, y: 59.42), controlPoint1: NSPoint(x: 68.47, y: 63.67), controlPoint2: NSPoint(x: 66.56, y: 61.76))
bezierPath.curve(to: NSPoint(x: 70.83, y: 55.17), controlPoint1: NSPoint(x: 66.56, y: 57.07), controlPoint2: NSPoint(x: 68.47, y: 55.17))
bezierPath.curve(to: NSPoint(x: 75.09, y: 59.42), controlPoint1: NSPoint(x: 73.18, y: 55.17), controlPoint2: NSPoint(x: 75.09, y: 57.07))
bezierPath.curve(to: NSPoint(x: 70.83, y: 63.67), controlPoint1: NSPoint(x: 75.09, y: 61.76), controlPoint2: NSPoint(x: 73.18, y: 63.67))
bezierPath.line(to: NSPoint(x: 70.83, y: 63.67))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 79.36, y: 52.33))
bezierPath.curve(to: NSPoint(x: 75.09, y: 48.08), controlPoint1: NSPoint(x: 77, y: 52.33), controlPoint2: NSPoint(x: 75.09, y: 50.43))
bezierPath.curve(to: NSPoint(x: 79.36, y: 43.83), controlPoint1: NSPoint(x: 75.09, y: 45.74), controlPoint2: NSPoint(x: 77, y: 43.83))
bezierPath.curve(to: NSPoint(x: 83.62, y: 48.08), controlPoint1: NSPoint(x: 81.71, y: 43.83), controlPoint2: NSPoint(x: 83.62, y: 45.74))
bezierPath.curve(to: NSPoint(x: 79.36, y: 52.33), controlPoint1: NSPoint(x: 83.62, y: 50.43), controlPoint2: NSPoint(x: 81.71, y: 52.33))
bezierPath.line(to: NSPoint(x: 79.36, y: 52.33))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 89.31, y: 41))
bezierPath.curve(to: NSPoint(x: 77.94, y: 29.67), controlPoint1: NSPoint(x: 89.31, y: 34.74), controlPoint2: NSPoint(x: 84.22, y: 29.67))
bezierPath.line(to: NSPoint(x: 21.06, y: 29.67))
bezierPath.curve(to: NSPoint(x: 9.69, y: 41), controlPoint1: NSPoint(x: 14.78, y: 29.67), controlPoint2: NSPoint(x: 9.69, y: 34.74))
bezierPath.line(to: NSPoint(x: 9.69, y: 58))
bezierPath.curve(to: NSPoint(x: 21.06, y: 69.33), controlPoint1: NSPoint(x: 9.69, y: 64.26), controlPoint2: NSPoint(x: 14.78, y: 69.33))
bezierPath.line(to: NSPoint(x: 77.94, y: 69.33))
bezierPath.curve(to: NSPoint(x: 89.31, y: 58), controlPoint1: NSPoint(x: 84.22, y: 69.33), controlPoint2: NSPoint(x: 89.31, y: 64.26))
bezierPath.line(to: NSPoint(x: 89.31, y: 41))
bezierPath.line(to: NSPoint(x: 89.31, y: 41))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 77.94, y: 75))
bezierPath.line(to: NSPoint(x: 21.06, y: 75))
bezierPath.curve(to: NSPoint(x: 4, y: 58), controlPoint1: NSPoint(x: 11.64, y: 75), controlPoint2: NSPoint(x: 4, y: 67.39))
bezierPath.line(to: NSPoint(x: 4, y: 41))
bezierPath.curve(to: NSPoint(x: 21.06, y: 24), controlPoint1: NSPoint(x: 4, y: 31.61), controlPoint2: NSPoint(x: 11.64, y: 24))
bezierPath.line(to: NSPoint(x: 77.94, y: 24))
bezierPath.curve(to: NSPoint(x: 95, y: 41), controlPoint1: NSPoint(x: 87.36, y: 24), controlPoint2: NSPoint(x: 95, y: 31.61))
bezierPath.line(to: NSPoint(x: 95, y: 58))
bezierPath.curve(to: NSPoint(x: 77.94, y: 75), controlPoint1: NSPoint(x: 95, y: 67.39), controlPoint2: NSPoint(x: 87.36, y: 75))
bezierPath.line(to: NSPoint(x: 77.94, y: 75))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 67.98, y: 43.83))
bezierPath.curve(to: NSPoint(x: 63.72, y: 39.58), controlPoint1: NSPoint(x: 65.63, y: 43.83), controlPoint2: NSPoint(x: 63.72, y: 41.93))
bezierPath.curve(to: NSPoint(x: 67.98, y: 35.33), controlPoint1: NSPoint(x: 63.72, y: 37.24), controlPoint2: NSPoint(x: 65.63, y: 35.33))
bezierPath.curve(to: NSPoint(x: 72.25, y: 39.58), controlPoint1: NSPoint(x: 70.34, y: 35.33), controlPoint2: NSPoint(x: 72.25, y: 37.24))
bezierPath.curve(to: NSPoint(x: 67.98, y: 43.83), controlPoint1: NSPoint(x: 72.25, y: 41.93), controlPoint2: NSPoint(x: 70.34, y: 43.83))
bezierPath.line(to: NSPoint(x: 67.98, y: 43.83))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 40.97, y: 52.33))
bezierPath.line(to: NSPoint(x: 32.44, y: 52.33))
bezierPath.line(to: NSPoint(x: 32.44, y: 60.83))
bezierPath.curve(to: NSPoint(x: 29.59, y: 63.67), controlPoint1: NSPoint(x: 32.44, y: 62.4), controlPoint2: NSPoint(x: 31.17, y: 63.67))
bezierPath.curve(to: NSPoint(x: 26.75, y: 60.83), controlPoint1: NSPoint(x: 28.02, y: 63.67), controlPoint2: NSPoint(x: 26.75, y: 62.4))
bezierPath.line(to: NSPoint(x: 26.75, y: 52.33))
bezierPath.line(to: NSPoint(x: 18.22, y: 52.33))
bezierPath.curve(to: NSPoint(x: 15.38, y: 49.5), controlPoint1: NSPoint(x: 16.65, y: 52.33), controlPoint2: NSPoint(x: 15.38, y: 51.06))
bezierPath.curve(to: NSPoint(x: 18.22, y: 46.67), controlPoint1: NSPoint(x: 15.38, y: 47.93), controlPoint2: NSPoint(x: 16.65, y: 46.67))
bezierPath.line(to: NSPoint(x: 26.75, y: 46.67))
bezierPath.line(to: NSPoint(x: 26.75, y: 38.17))
bezierPath.curve(to: NSPoint(x: 29.59, y: 35.33), controlPoint1: NSPoint(x: 26.75, y: 36.6), controlPoint2: NSPoint(x: 28.02, y: 35.33))
bezierPath.curve(to: NSPoint(x: 32.44, y: 38.17), controlPoint1: NSPoint(x: 31.17, y: 35.33), controlPoint2: NSPoint(x: 32.44, y: 36.6))
bezierPath.line(to: NSPoint(x: 32.44, y: 46.67))
bezierPath.line(to: NSPoint(x: 40.97, y: 46.67))
bezierPath.curve(to: NSPoint(x: 43.81, y: 49.5), controlPoint1: NSPoint(x: 42.54, y: 46.67), controlPoint2: NSPoint(x: 43.81, y: 47.93))
bezierPath.curve(to: NSPoint(x: 40.97, y: 52.33), controlPoint1: NSPoint(x: 43.81, y: 51.06), controlPoint2: NSPoint(x: 42.54, y: 52.33))
bezierPath.line(to: NSPoint(x: 40.97, y: 52.33))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 59.45, y: 55.17))
bezierPath.curve(to: NSPoint(x: 55.19, y: 50.92), controlPoint1: NSPoint(x: 57.1, y: 55.17), controlPoint2: NSPoint(x: 55.19, y: 53.26))
bezierPath.curve(to: NSPoint(x: 59.45, y: 46.67), controlPoint1: NSPoint(x: 55.19, y: 48.57), controlPoint2: NSPoint(x: 57.1, y: 46.67))
bezierPath.curve(to: NSPoint(x: 63.72, y: 50.92), controlPoint1: NSPoint(x: 61.81, y: 46.67), controlPoint2: NSPoint(x: 63.72, y: 48.57))
bezierPath.curve(to: NSPoint(x: 59.45, y: 55.17), controlPoint1: NSPoint(x: 63.72, y: 53.26), controlPoint2: NSPoint(x: 61.81, y: 55.17))
bezierPath.line(to: NSPoint(x: 59.45, y: 55.17))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawCharts(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 77.85, y: 15.78))
bezierPath.curve(to: NSPoint(x: 75.27, y: 13.19), controlPoint1: NSPoint(x: 77.85, y: 14.35), controlPoint2: NSPoint(x: 76.69, y: 13.19))
bezierPath.curve(to: NSPoint(x: 72.69, y: 15.78), controlPoint1: NSPoint(x: 73.84, y: 13.19), controlPoint2: NSPoint(x: 72.69, y: 14.35))
bezierPath.line(to: NSPoint(x: 72.69, y: 41.72))
bezierPath.curve(to: NSPoint(x: 75.27, y: 44.31), controlPoint1: NSPoint(x: 72.69, y: 43.15), controlPoint2: NSPoint(x: 73.84, y: 44.31))
bezierPath.curve(to: NSPoint(x: 77.85, y: 41.72), controlPoint1: NSPoint(x: 76.69, y: 44.31), controlPoint2: NSPoint(x: 77.85, y: 43.15))
bezierPath.line(to: NSPoint(x: 77.85, y: 15.78))
bezierPath.line(to: NSPoint(x: 77.85, y: 15.78))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 77.85, y: 49.5))
bezierPath.line(to: NSPoint(x: 72.69, y: 49.5))
bezierPath.curve(to: NSPoint(x: 67.54, y: 44.31), controlPoint1: NSPoint(x: 69.85, y: 49.5), controlPoint2: NSPoint(x: 67.54, y: 47.18))
bezierPath.line(to: NSPoint(x: 67.54, y: 13.19))
bezierPath.curve(to: NSPoint(x: 72.69, y: 8), controlPoint1: NSPoint(x: 67.54, y: 10.32), controlPoint2: NSPoint(x: 69.85, y: 8))
bezierPath.line(to: NSPoint(x: 77.85, y: 8))
bezierPath.curve(to: NSPoint(x: 83, y: 13.19), controlPoint1: NSPoint(x: 80.69, y: 8), controlPoint2: NSPoint(x: 83, y: 10.32))
bezierPath.line(to: NSPoint(x: 83, y: 44.31))
bezierPath.curve(to: NSPoint(x: 77.85, y: 49.5), controlPoint1: NSPoint(x: 83, y: 47.18), controlPoint2: NSPoint(x: 80.69, y: 49.5))
bezierPath.line(to: NSPoint(x: 77.85, y: 49.5))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 26.31, y: 15.78))
bezierPath.curve(to: NSPoint(x: 23.73, y: 13.19), controlPoint1: NSPoint(x: 26.31, y: 14.35), controlPoint2: NSPoint(x: 25.16, y: 13.19))
bezierPath.curve(to: NSPoint(x: 21.15, y: 15.78), controlPoint1: NSPoint(x: 22.31, y: 13.19), controlPoint2: NSPoint(x: 21.15, y: 14.35))
bezierPath.line(to: NSPoint(x: 21.15, y: 59.88))
bezierPath.curve(to: NSPoint(x: 23.73, y: 62.47), controlPoint1: NSPoint(x: 21.15, y: 61.31), controlPoint2: NSPoint(x: 22.31, y: 62.47))
bezierPath.curve(to: NSPoint(x: 26.31, y: 59.88), controlPoint1: NSPoint(x: 25.16, y: 62.47), controlPoint2: NSPoint(x: 26.31, y: 61.31))
bezierPath.line(to: NSPoint(x: 26.31, y: 15.78))
bezierPath.line(to: NSPoint(x: 26.31, y: 15.78))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 26.31, y: 67.66))
bezierPath.line(to: NSPoint(x: 21.15, y: 67.66))
bezierPath.curve(to: NSPoint(x: 16, y: 62.47), controlPoint1: NSPoint(x: 18.31, y: 67.66), controlPoint2: NSPoint(x: 16, y: 65.33))
bezierPath.line(to: NSPoint(x: 16, y: 13.19))
bezierPath.curve(to: NSPoint(x: 21.15, y: 8), controlPoint1: NSPoint(x: 16, y: 10.32), controlPoint2: NSPoint(x: 18.31, y: 8))
bezierPath.line(to: NSPoint(x: 26.31, y: 8))
bezierPath.curve(to: NSPoint(x: 31.46, y: 13.19), controlPoint1: NSPoint(x: 29.15, y: 8), controlPoint2: NSPoint(x: 31.46, y: 10.32))
bezierPath.line(to: NSPoint(x: 31.46, y: 62.47))
bezierPath.curve(to: NSPoint(x: 26.31, y: 67.66), controlPoint1: NSPoint(x: 31.46, y: 65.33), controlPoint2: NSPoint(x: 29.15, y: 67.66))
bezierPath.line(to: NSPoint(x: 26.31, y: 67.66))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 52.08, y: 15.78))
bezierPath.curve(to: NSPoint(x: 49.5, y: 13.19), controlPoint1: NSPoint(x: 52.08, y: 14.35), controlPoint2: NSPoint(x: 50.93, y: 13.19))
bezierPath.curve(to: NSPoint(x: 46.92, y: 15.78), controlPoint1: NSPoint(x: 48.07, y: 13.19), controlPoint2: NSPoint(x: 46.92, y: 14.35))
bezierPath.line(to: NSPoint(x: 46.92, y: 83.22))
bezierPath.curve(to: NSPoint(x: 49.5, y: 85.81), controlPoint1: NSPoint(x: 46.92, y: 84.65), controlPoint2: NSPoint(x: 48.07, y: 85.81))
bezierPath.curve(to: NSPoint(x: 52.08, y: 83.22), controlPoint1: NSPoint(x: 50.93, y: 85.81), controlPoint2: NSPoint(x: 52.08, y: 84.65))
bezierPath.line(to: NSPoint(x: 52.08, y: 15.78))
bezierPath.line(to: NSPoint(x: 52.08, y: 15.78))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 52.08, y: 91))
bezierPath.line(to: NSPoint(x: 46.92, y: 91))
bezierPath.curve(to: NSPoint(x: 41.77, y: 85.81), controlPoint1: NSPoint(x: 44.08, y: 91), controlPoint2: NSPoint(x: 41.77, y: 88.68))
bezierPath.line(to: NSPoint(x: 41.77, y: 13.19))
bezierPath.curve(to: NSPoint(x: 46.92, y: 8), controlPoint1: NSPoint(x: 41.77, y: 10.32), controlPoint2: NSPoint(x: 44.08, y: 8))
bezierPath.line(to: NSPoint(x: 52.08, y: 8))
bezierPath.curve(to: NSPoint(x: 57.23, y: 13.19), controlPoint1: NSPoint(x: 54.92, y: 8), controlPoint2: NSPoint(x: 57.23, y: 10.32))
bezierPath.line(to: NSPoint(x: 57.23, y: 85.81))
bezierPath.curve(to: NSPoint(x: 52.08, y: 91), controlPoint1: NSPoint(x: 57.23, y: 88.68), controlPoint2: NSPoint(x: 54.92, y: 91))
bezierPath.line(to: NSPoint(x: 52.08, y: 91))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawEat(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, iconColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 11.44, y: 30.38))
bezierPath.curve(to: NSPoint(x: 49.5, y: 68.62), controlPoint1: NSPoint(x: 11.44, y: 51.5), controlPoint2: NSPoint(x: 28.48, y: 68.62))
bezierPath.curve(to: NSPoint(x: 87.56, y: 30.38), controlPoint1: NSPoint(x: 70.52, y: 68.62), controlPoint2: NSPoint(x: 87.56, y: 51.5))
bezierPath.line(to: NSPoint(x: 11.44, y: 30.38))
bezierPath.line(to: NSPoint(x: 11.44, y: 30.38))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 52.22, y: 74.08))
bezierPath.line(to: NSPoint(x: 52.22, y: 79.54))
bezierPath.line(to: NSPoint(x: 57.66, y: 79.54))
bezierPath.curve(to: NSPoint(x: 60.38, y: 82.27), controlPoint1: NSPoint(x: 59.16, y: 79.54), controlPoint2: NSPoint(x: 60.38, y: 80.76))
bezierPath.curve(to: NSPoint(x: 57.66, y: 85), controlPoint1: NSPoint(x: 60.38, y: 83.78), controlPoint2: NSPoint(x: 59.16, y: 85))
bezierPath.line(to: NSPoint(x: 41.34, y: 85))
bezierPath.curve(to: NSPoint(x: 38.62, y: 82.27), controlPoint1: NSPoint(x: 39.84, y: 85), controlPoint2: NSPoint(x: 38.62, y: 83.78))
bezierPath.curve(to: NSPoint(x: 41.34, y: 79.54), controlPoint1: NSPoint(x: 38.62, y: 80.76), controlPoint2: NSPoint(x: 39.84, y: 79.54))
bezierPath.line(to: NSPoint(x: 46.78, y: 79.54))
bezierPath.curve(to: NSPoint(x: 46.78, y: 74.08), controlPoint1: NSPoint(x: 46.78, y: 79.54), controlPoint2: NSPoint(x: 46.76, y: 73.85))
bezierPath.curve(to: NSPoint(x: 6, y: 30.38), controlPoint1: NSPoint(x: 24.03, y: 72.66), controlPoint2: NSPoint(x: 6, y: 53.59))
bezierPath.line(to: NSPoint(x: 6, y: 27.65))
bezierPath.curve(to: NSPoint(x: 8.72, y: 24.92), controlPoint1: NSPoint(x: 6, y: 26.14), controlPoint2: NSPoint(x: 7.22, y: 24.92))
bezierPath.line(to: NSPoint(x: 90.28, y: 24.92))
bezierPath.curve(to: NSPoint(x: 93, y: 27.65), controlPoint1: NSPoint(x: 91.78, y: 24.92), controlPoint2: NSPoint(x: 93, y: 26.14))
bezierPath.line(to: NSPoint(x: 93, y: 30.38))
bezierPath.curve(to: NSPoint(x: 52.22, y: 74.08), controlPoint1: NSPoint(x: 93, y: 53.59), controlPoint2: NSPoint(x: 74.97, y: 72.66))
bezierPath.line(to: NSPoint(x: 52.22, y: 74.08))
bezierPath.close()
bezierPath.move(to: NSPoint(x: 90.28, y: 19.46))
bezierPath.line(to: NSPoint(x: 8.72, y: 19.46))
bezierPath.curve(to: NSPoint(x: 6, y: 16.73), controlPoint1: NSPoint(x: 7.22, y: 19.46), controlPoint2: NSPoint(x: 6, y: 18.24))
bezierPath.curve(to: NSPoint(x: 8.72, y: 14), controlPoint1: NSPoint(x: 6, y: 15.22), controlPoint2: NSPoint(x: 7.22, y: 14))
bezierPath.line(to: NSPoint(x: 90.28, y: 14))
bezierPath.curve(to: NSPoint(x: 93, y: 16.73), controlPoint1: NSPoint(x: 91.78, y: 14), controlPoint2: NSPoint(x: 93, y: 15.22))
bezierPath.curve(to: NSPoint(x: 90.28, y: 19.46), controlPoint1: NSPoint(x: 93, y: 18.24), controlPoint2: NSPoint(x: 91.78, y: 19.46))
bezierPath.line(to: NSPoint(x: 90.28, y: 19.46))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
iconColor.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
@objc(BannersIconsBezierPathsResizingBehavior)
public enum ResizingBehavior: Int {
case aspectFit /// The content is proportionally resized to fit into the target rectangle.
case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
case stretch /// The content is stretched to match the entire target rectangle.
case center /// The content is centered in the target rectangle, but it is NOT resized.
public func apply(rect: NSRect, target: NSRect) -> NSRect {
if rect == target || target == NSRect.zero {
return rect
}
var scales = NSSize.zero
scales.width = abs(target.width / rect.width)
scales.height = abs(target.height / rect.height)
switch self {
case .aspectFit:
scales.width = min(scales.width, scales.height)
scales.height = scales.width
case .aspectFill:
scales.width = max(scales.width, scales.height)
scales.height = scales.width
case .stretch:
break
case .center:
scales.width = 1
scales.height = 1
}
var result = rect.standardized
result.size.width *= scales.width
result.size.height *= scales.height
result.origin.x = target.minX + (target.width - result.width) / 2
result.origin.y = target.minY + (target.height - result.height) / 2
return result
}
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/GradientView.swift
//
// GradientView.swift
// SocialBannersApp
//
// Created by <NAME> on 02.06.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class GradientView: NSView {
var gradientLayer = CAGradientLayer()
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
setBackgroundLayer()
// Drawing code here.
}
func setBackgroundLayer() {
let firstGradientColor = CGColor.init(red: 0.10196078,
green: 0.83921569,
blue: 0.99215686,
alpha: 1.0)
let secondDradientColor = CGColor.init(red: 0.11372549,
green: 0.38431373,
blue: 0.94117647,
alpha: 1)
gradientLayer = createGradientLayer(withFirstColor: firstGradientColor,
secondColor: secondDradientColor,
andFrame: self.bounds)
self.layer?.addSublayer(gradientLayer)
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/FontModel.swift
//
// FontModel.swift
// SocialBannersApp
//
// Created by <NAME> on 20.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class FontModel: NSObject{
var type: FontString
init(type: FontString) {
self.type = type
}
}
enum FontString: String {
case avenirNextDemiBold = "Avenir Next Demi Bold"
case avenitNextBold = "Avenir Next Bold"
case avenirNextMedium = "Avenir Next Medium"
case avenirNexRegular = "Avenir Next Regular"
case avenirNextCondensedMedium = "Avenir Next Condensed Medium"
case avenirNextCondensedBold = "Avenir Next Condensed Bold"
case timesNewRoman = "Times New Roman"
case georgia = "Georgia"
case georgiaBold = "Georgia Bold"
case gillSans = "Gill Sans"
case gillSansBold = "Gill Sans Bold"
}
<file_sep>/SocialBannersApp/SocialBannersApp/SelectFontNameController.swift
//
// SelectFontNameController.swift
// SocialBannersApp
//
// Created by <NAME> on 20.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class SelectFontNameController: NSViewController, NSCollectionViewDataSource, NSCollectionViewDelegate {
// MARK: - IBOutlet's
@IBOutlet weak var fontNameScrollView: NSScrollView!
@IBOutlet weak var fontNameCollection: NSCollectionView!
// MARK: - Private Variables
let allFonts = AppContents.getFontsModel()
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
fontNameCollection.frame = fontNameScrollView.bounds
// Do view setup here.
}
override func viewWillAppear() {
super.viewWillAppear()
self.view.window?.styleMask.remove(.resizable)
}
// MARK: - NSCollectionViewDataSource
public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
public func numberOfSections(in collectionView: NSCollectionView) -> Int {
return allFonts.count
}
public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: "FontNameCollectionItem",
for: indexPath)
guard let collectionViewItem = item as? FontNameCollectionItem else {
return item
}
let fontModel = allFonts[indexPath.section]
collectionViewItem.setFont(withType: fontModel)
return item
}
// MARK: - NSCollectionViewDelegate
public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
for indexPath in indexPaths {
let fontModel = allFonts[indexPath.section]
let addNewBannerVC = self.presenting as! CreateNewBannerViewController
addNewBannerVC.newBannerModel.fontType = fontModel
addNewBannerVC.updateNBFont(withType: fontModel)
self.dismiss(nil)
}
}
// MARK: - Actions
@IBAction func backToCreateBannerAction(_ sender: Any) {
self.dismiss(nil)
}
// MARK: - Configure CollectionView
fileprivate func configureCollectionView() {
let flowLayout = NSCollectionViewFlowLayout()
flowLayout.itemSize = NSSize(width: view.bounds.width, height: 39.0)
flowLayout.sectionInset = EdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
flowLayout.scrollDirection = .vertical
fontNameCollection.collectionViewLayout = flowLayout
view.wantsLayer = true
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/BannerModel.swift
//
// BannerModel.swift
// SocialBannersApp
//
// Created by <NAME> on 18.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class BannerModel: NSObject, NSCoding {
var iconImage: ImageIndex = .empty // default
var contentColor = NSColor.hexColor(rgbValue: 0x14ABFB) // default
var backgroundColor = [NSColor.white.cgColor, NSColor.white.cgColor] // default
var bgColorName = "White"
var contentColorName = "Sky"
var titleText = ""
var subtitleText = ""
var fontType = FontModel(type: .avenirNextMedium)
var saveNumber = 0
override init() {
//super.init()
}
init(withIconImage iconImage: ImageIndex, contentColor: NSColor, backgroundColor: [CGColor], bgColorName: String, contentColorName: String, titleText: String, subtitleText: String, fontType: FontModel, saveNumber: Int) {
self.iconImage = iconImage
self.contentColor = contentColor
self.backgroundColor = backgroundColor
self.bgColorName = bgColorName
self.contentColorName = contentColorName
self.titleText = titleText
self.subtitleText = subtitleText
self.fontType = fontType
self.saveNumber = saveNumber
}
required convenience init(coder aDecoder: NSCoder) {
let iconInt = aDecoder.decodeInteger(forKey: "iconImage")
let iconImage = ImageIndex(rawValue: iconInt)
let contentColor = aDecoder.decodeObject(forKey: "contentColor") as! NSColor
let backgroundColorWithNSColor = aDecoder.decodeObject(forKey: "backgroundColor") as! [NSColor]
let backgroundColor = [backgroundColorWithNSColor[0].cgColor, backgroundColorWithNSColor[1].cgColor]
let bgColorName = aDecoder.decodeObject(forKey: "bgColorName") as! String
let contentColorName = aDecoder.decodeObject(forKey: "contentColorName") as! String
let titleText = aDecoder.decodeObject(forKey: "titleText") as! String
let subtitleText = aDecoder.decodeObject(forKey: "subtitleText") as! String
let fontTypeString = aDecoder.decodeObject(forKey: "fontType") as! String
let fontType = FontModel(type: FontString(rawValue: fontTypeString)!)
let saveNumber = aDecoder.decodeInteger(forKey: "saveNumber")
self.init(withIconImage: iconImage!,
contentColor: contentColor,
backgroundColor: backgroundColor,
bgColorName: bgColorName,
contentColorName: contentColorName,
titleText: titleText,
subtitleText: subtitleText,
fontType: fontType,
saveNumber: saveNumber)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(iconImage.rawValue, forKey: "iconImage")
aCoder.encode(contentColor, forKey: "contentColor")
let backgroundColorWithNSColor = [NSColor.init(cgColor: backgroundColor[0]), NSColor.init(cgColor: backgroundColor[1])]
aCoder.encode(backgroundColorWithNSColor, forKey: "backgroundColor")
aCoder.encode(bgColorName, forKey: "bgColorName")
aCoder.encode(contentColorName, forKey: "contentColorName")
aCoder.encode(titleText, forKey: "titleText")
aCoder.encode(subtitleText, forKey: "subtitleText")
let fontTypeString = fontType.type.rawValue
aCoder.encode(fontTypeString, forKey: "fontType")
aCoder.encode(saveNumber, forKey: "saveNumber")
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/BGColorView.swift
//
// BGColorView.swift
// SocialBannersApp
//
// Created by <NAME> on 19.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class BGColorView: NSView {
var gradientLayer = CAGradientLayer()
var backgroundColors: [CGColor] = [.white, .white]
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if gradientLayer.superlayer == nil {
setBackgroundColor(withColors: backgroundColors)
}
self.layer?.backgroundColor = .white
self.layer?.cornerRadius = 4.0
// Drawing code here.
}
func setBackgroundColor(withColors colors: [CGColor]) {
backgroundColors = colors
gradientLayer.colors = backgroundColors
gradientLayer.startPoint = CGPoint(x: 0,
y: 1)
gradientLayer.endPoint = CGPoint(x: 1.0,
y: 0.0)
if gradientLayer.superlayer == nil {
self.layer?.addSublayer(gradientLayer)
gradientLayer.cornerRadius = 4.0
gradientLayer.frame = self.bounds
}
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/PreviewBannerCollectionItem.swift
//
// PreviewBannerCollectionItem.swift
// SocialBannersApp
//
// Created by <NAME> on 23/06/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class PreviewBannerCollectionItem: NSCollectionViewItem {
// MARK: - IBOutlet's
@IBOutlet var newBannerView: NewBannerView!
@IBOutlet weak var newBannerImage: BackgroundImageView!
@IBOutlet weak var newBannerTitleLabel: TitleTextField!
@IBOutlet weak var newBannerSubtitleLabel: SubtitleTextField!
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.clear.cgColor
}
func setAllElements(withCurrentModel newBannerModel: BannerModel) {
newBannerImage.removeFromSuperview()
self.newBannerView.addSubview(newBannerImage)
self.newBannerView.layout()
if newBannerModel.iconImage == .empty {
newBannerImage.isHidden = true
} else {
newBannerImage.isHidden = false
newBannerImage.setBackgroundImage(withIndex: newBannerModel.iconImage.rawValue,
andColor: newBannerModel.contentColor)
}
newBannerTitleLabel.stringValue = newBannerModel.titleText
if newBannerModel.subtitleText.characters.count == 0 {
newBannerSubtitleLabel.isHidden = true
} else {
newBannerSubtitleLabel.stringValue = newBannerModel.subtitleText
newBannerSubtitleLabel.isHidden = false
}
newBannerView.layout()
newBannerTitleLabel.font = NSFont(name: newBannerModel.fontType.type.rawValue,
size: 16)
newBannerSubtitleLabel.font = NSFont(name: newBannerModel.fontType.type.rawValue,
size: 15)
newBannerTitleLabel.font =
self.calculateFont(toFit: self.newBannerTitleLabel,
withString: self.newBannerTitleLabel.stringValue as NSString,
minSize: 1,
maxSize: 18)
newBannerSubtitleLabel.font =
self.calculateFont(toFit: self.newBannerSubtitleLabel,
withString: self.newBannerSubtitleLabel.stringValue as NSString,
minSize: 1,
maxSize: 13)
newBannerTitleLabel.textColor = newBannerModel.contentColor
newBannerSubtitleLabel.textColor = newBannerModel.contentColor
newBannerView.setBackgroundColor(withColors: newBannerModel.backgroundColor)
newBannerView.layout()
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/BackgroundImageView.swift
//
// BackgroundImageView.swift
// SocialBannersApp
//
// Created by <NAME> on 18.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class BackgroundImageView: NSView {
var image = ImageIndex.empty {
didSet {
self.draw(self.frame)
}
}
var color = NSColor.white
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if NSGraphicsContext.current() != nil {
switch image {
case .empty:
BannersIconsBezierPaths.drawEmpty(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .doc:
BannersIconsBezierPaths.drawDoc(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .painter:
BannersIconsBezierPaths.drawPainter(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .picture:
BannersIconsBezierPaths.drawPicture(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .diagram:
BannersIconsBezierPaths.drawDiagram(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .brush:
BannersIconsBezierPaths.drawBrush(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .social:
BannersIconsBezierPaths.drawSocial(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .flyer:
BannersIconsBezierPaths.drawFlyer(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .speaker:
BannersIconsBezierPaths.drawSpeaker(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .time:
BannersIconsBezierPaths.drawTime(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .hot:
BannersIconsBezierPaths.drawHot(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .music:
BannersIconsBezierPaths.drawMusic(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .world:
BannersIconsBezierPaths.drawWorld(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .rain:
BannersIconsBezierPaths.drawRain(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .sun:
BannersIconsBezierPaths.drawSun(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .moon:
BannersIconsBezierPaths.drawMoon(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .ok:
BannersIconsBezierPaths.drawOK(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .search:
BannersIconsBezierPaths.drawSearch(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .repair:
BannersIconsBezierPaths.drawRepair(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .alarm:
BannersIconsBezierPaths.drawAlarm(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .map:
BannersIconsBezierPaths.drawMap(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .location:
BannersIconsBezierPaths.drawLocation(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .gamepad:
BannersIconsBezierPaths.drawGamePad(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .charts:
BannersIconsBezierPaths.drawCharts(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
case .eat:
BannersIconsBezierPaths.drawEat(frame: dirtyRect,
resizing: .stretch,
iconColor: color)
}
}
// Drawing code here.
}
func setBackgroundImage(withIndex index: Int, andColor color: NSColor) {
self.color = color
image = ImageIndex(rawValue: index)!
}
}
enum ImageIndex: Int {
case empty = 0
case doc = 16
case painter = 10
case picture = 12
case diagram = 14
case brush = 11
case social = 3
case flyer = 17
case speaker = 1
case time = 2
case hot = 5
case music = 13
case world = 24
case rain = 8
case sun = 7
case moon = 9
case ok = 6
case search = 4
case repair = 18
case alarm = 21
case map = 23
case location = 22
case gamepad = 19
case charts = 15
case eat = 20
}
<file_sep>/SocialBannersApp/SocialBannersApp/BackToBannersButton.swift
//
// BackToBannersButton.swift
// SocialBannersApp
//
// Created by <NAME> on 02.06.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class BackToBannersButton: NSButton {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
BaseElementsBezierPaths.drawBackArrow()
// Drawing code here.
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/BannersDefaults.swift
//
// BannersDefaults.swift
// SocialBannersApp
//
// Created by <NAME> on 23/06/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class BannersDefaults {
static func save(banner bannerObject: BannerModel, forKey key: BannersKey) {
if UserDefaults.standard.array(forKey: key.rawValue) == nil {
let archiveData = NSKeyedArchiver.archivedData(withRootObject: bannerObject)
UserDefaults.standard.setValue([archiveData],
forKey: key.rawValue)
} else {
var banners = UserDefaults.standard.array(forKey: key.rawValue) as! [Data]
bannerObject.saveNumber = (loadBanners(forKey: .banners).first?.saveNumber)! + 1
if banners.count == 18 {
banners.removeLast()
}
let archiveData = NSKeyedArchiver.archivedData(withRootObject: bannerObject)
banners.insert(archiveData, at: 0)
UserDefaults.standard.setValue(banners,
forKey: key.rawValue)
}
}
static func loadBanners(forKey key: BannersKey) -> [BannerModel] {
if let banners = UserDefaults.standard.array(forKey: key.rawValue) {
let inputData = banners as! [Data]
var unarchivedBanners = [BannerModel]()
for data in inputData {
unarchivedBanners.append(NSKeyedUnarchiver.unarchiveObject(with: data) as! BannerModel)
}
return unarchivedBanners
} else {
return []
}
}
}
enum BannersKey: String {
case banners
}
<file_sep>/SocialBannersApp/SocialBannersApp/FontNameCollectionItem.swift
//
// FontNameCollectionItem.swift
// SocialBannersApp
//
// Created by <NAME> on 20.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class FontNameCollectionItem: NSCollectionViewItem {
@IBOutlet weak var fontNameLabel: NSTextFieldCell!
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.clear.cgColor
fontNameLabel.textColor = NSColor.hexColor(rgbValue: 0x14ABFB)
// Do view setup here.
}
func setFont(withType font: FontModel) {
self.fontNameLabel.font = NSFont(name: font.type.rawValue,
size: 18.0)
self.fontNameLabel.stringValue = font.type.rawValue
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/BaseElementsBezierPaths.swift
//
// BaseElementsBezierPaths.swift
// SocialBanners
//
// Created by IvanVorobei on 6/2/17.
// Copyright © 2017 IvanVorobei. All rights reserved.
//
// Generated by PaintCode
// http://www.paintcodeapp.com
//
import Cocoa
public class BaseElementsBezierPaths : NSObject {
//// Cache
private struct Cache {
static let fillColor: NSColor = NSColor(red: 0.078, green: 0.671, blue: 0.984, alpha: 1)
}
//// Colors
public dynamic class var fillColor: NSColor { return Cache.fillColor }
//// Drawing Methods
public dynamic class func drawBackArrow(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 12, height: 20), resizing: ResizingBehavior = .aspectFit) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 12, height: 20), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 12, y: resizedFrame.height / 20)
//// Color Declarations
let strokeColor = NSColor(red: 0.078, green: 0.671, blue: 0.984, alpha: 1)
//// Group 2
//// Bezier 2 Drawing
let bezier2Path = NSBezierPath()
bezier2Path.move(to: NSPoint(x: 10.17, y: 3.07))
bezier2Path.curve(to: NSPoint(x: 9.85, y: 3.2), controlPoint1: NSPoint(x: 10.09, y: 3.15), controlPoint2: NSPoint(x: 9.97, y: 3.2))
bezier2Path.curve(to: NSPoint(x: 9.53, y: 3.07), controlPoint1: NSPoint(x: 9.74, y: 3.2), controlPoint2: NSPoint(x: 9.62, y: 3.15))
bezier2Path.curve(to: NSPoint(x: 9.53, y: 2.45), controlPoint1: NSPoint(x: 9.36, y: 2.9), controlPoint2: NSPoint(x: 9.36, y: 2.62))
bezier2Path.line(to: NSPoint(x: 2.64, y: 9.4))
bezier2Path.line(to: NSPoint(x: 1.94, y: 10.1))
bezier2Path.line(to: NSPoint(x: 2.64, y: 10.8))
bezier2Path.line(to: NSPoint(x: 9.53, y: 17.75))
bezier2Path.curve(to: NSPoint(x: 9.53, y: 17.13), controlPoint1: NSPoint(x: 9.36, y: 17.58), controlPoint2: NSPoint(x: 9.36, y: 17.3))
bezier2Path.curve(to: NSPoint(x: 10.17, y: 17.13), controlPoint1: NSPoint(x: 9.71, y: 16.96), controlPoint2: NSPoint(x: 10, y: 16.96))
bezier2Path.line(to: NSPoint(x: 2.87, y: 9.79))
bezier2Path.curve(to: NSPoint(x: 2.87, y: 10.41), controlPoint1: NSPoint(x: 3.04, y: 9.96), controlPoint2: NSPoint(x: 3.04, y: 10.24))
bezier2Path.line(to: NSPoint(x: 10.17, y: 3.07))
bezier2Path.close()
bezier2Path.move(to: NSPoint(x: 8.75, y: 1.66))
bezier2Path.line(to: NSPoint(x: 1.45, y: 9))
bezier2Path.curve(to: NSPoint(x: 1.45, y: 11.2), controlPoint1: NSPoint(x: 0.85, y: 9.61), controlPoint2: NSPoint(x: 0.85, y: 10.59))
bezier2Path.line(to: NSPoint(x: 8.75, y: 18.54))
bezier2Path.curve(to: NSPoint(x: 10.95, y: 18.54), controlPoint1: NSPoint(x: 9.36, y: 19.15), controlPoint2: NSPoint(x: 10.35, y: 19.15))
bezier2Path.curve(to: NSPoint(x: 10.96, y: 16.34), controlPoint1: NSPoint(x: 11.56, y: 17.93), controlPoint2: NSPoint(x: 11.56, y: 16.95))
bezier2Path.line(to: NSPoint(x: 4.06, y: 9.4))
bezier2Path.line(to: NSPoint(x: 4.06, y: 10.8))
bezier2Path.line(to: NSPoint(x: 10.95, y: 3.86))
bezier2Path.curve(to: NSPoint(x: 10.96, y: 1.66), controlPoint1: NSPoint(x: 11.56, y: 3.25), controlPoint2: NSPoint(x: 11.56, y: 2.27))
bezier2Path.curve(to: NSPoint(x: 9.85, y: 1.2), controlPoint1: NSPoint(x: 10.66, y: 1.36), controlPoint2: NSPoint(x: 10.27, y: 1.2))
bezier2Path.curve(to: NSPoint(x: 8.75, y: 1.66), controlPoint1: NSPoint(x: 9.44, y: 1.2), controlPoint2: NSPoint(x: 9.05, y: 1.36))
bezier2Path.close()
strokeColor.setFill()
bezier2Path.fill()
NSGraphicsContext.restoreGraphicsState()
}
public dynamic class func drawArea(frame targetFrame: NSRect = NSRect(x: 0, y: 0, width: 167, height: 9), resizing: ResizingBehavior = .aspectFit) {
//// General Declarations
let context = NSGraphicsContext.current()!.cgContext
//// Resize to Target Frame
NSGraphicsContext.saveGraphicsState()
let resizedFrame: NSRect = resizing.apply(rect: NSRect(x: 0, y: 0, width: 167, height: 9), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 167, y: resizedFrame.height / 9)
//// Color Declarations
let fillColor2 = NSColor(red: 1, green: 1, blue: 1, alpha: 1)
//// Bezier Drawing
let bezierPath = NSBezierPath()
bezierPath.move(to: NSPoint(x: 0, y: 9))
bezierPath.line(to: NSPoint(x: 167, y: 9))
bezierPath.line(to: NSPoint(x: 167, y: 7.37))
bezierPath.curve(to: NSPoint(x: 83.5, y: 2), controlPoint1: NSPoint(x: 167, y: 7.37), controlPoint2: NSPoint(x: 127.33, y: 2))
bezierPath.curve(to: NSPoint(x: 0, y: 7.37), controlPoint1: NSPoint(x: 39.67, y: 2), controlPoint2: NSPoint(x: 0, y: 7.37))
bezierPath.line(to: NSPoint(x: 0, y: 9))
bezierPath.close()
bezierPath.windingRule = .evenOddWindingRule
fillColor2.setFill()
bezierPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
@objc(BaseElementsBezierPathsResizingBehavior)
public enum ResizingBehavior: Int {
case aspectFit /// The content is proportionally resized to fit into the target rectangle.
case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
case stretch /// The content is stretched to match the entire target rectangle.
case center /// The content is centered in the target rectangle, but it is NOT resized.
public func apply(rect: NSRect, target: NSRect) -> NSRect {
if rect == target || target == NSRect.zero {
return rect
}
var scales = NSSize.zero
scales.width = abs(target.width / rect.width)
scales.height = abs(target.height / rect.height)
switch self {
case .aspectFit:
scales.width = min(scales.width, scales.height)
scales.height = scales.width
case .aspectFill:
scales.width = max(scales.width, scales.height)
scales.height = scales.width
case .stretch:
break
case .center:
scales.width = 1
scales.height = 1
}
var result = rect.standardized
result.size.width *= scales.width
result.size.height *= scales.height
result.origin.x = target.minX + (target.width - result.width) / 2
result.origin.y = target.minY + (target.height - result.height) / 2
return result
}
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/ContentColorView.swift
//
// ContentColorView.swift
// SocialBannersApp
//
// Created by <NAME> on 20.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class ContentColorView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
self.layer?.cornerRadius = 4.0
// Drawing code here.
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/ImageBannerCollectionItem.swift
//
// ImageBannerCollectionItem.swift
// SocialBannersApp
//
// Created by <NAME> on 13.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class ImageBannerCollectionItem: NSCollectionViewItem {
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.clear.cgColor
view.layer?.cornerRadius = 4
}
func setHighlight(_ selected: Bool, atIndex index: Int) {
let selectedColor = NSColor(red: 0.07843137,
green: 0.67058824,
blue: 0.98431373,
alpha: 1.0)
let imageView = self.view as! BackgroundImageView
if selected {
imageView.setBackgroundImage(withIndex: index,
andColor: selectedColor)
imageView.layer?.backgroundColor = .white
} else {
imageView.setBackgroundImage(withIndex: index,
andColor: .white)
imageView.layer?.backgroundColor = .clear
}
imageView.layer?.setNeedsDisplay()
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/NewBannerView.swift
//
// NewBannerView.swift
// SocialBannersApp
//
// Created by <NAME> on 03.06.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class NewBannerView: NSView {
var gradientLayer = CAGradientLayer()
var backgroundColors: [CGColor] = [.white, .white]
var backgroundImageView: BackgroundImageView?
var titleTextField: TitleTextField?
var subtitleTextField: SubtitleTextField?
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if gradientLayer.superlayer == nil {
setBackgroundColor(withColors: backgroundColors)
}
self.layer?.backgroundColor = .clear
self.layer?.cornerRadius = 6.0
let shadow = NSShadow()
shadow.shadowOffset = NSSize(width: 0, height: -2)
shadow.shadowColor = NSColor.black.withAlphaComponent(0.25)
shadow.shadowBlurRadius = 8
self.shadow = shadow
// Drawing code here.
}
func setBackgroundColor(withColors colors: [CGColor]) {
if gradientLayer.superlayer != nil {
let tempLayer = CAGradientLayer()
tempLayer.frame = self.bounds
gradientLayer.removeFromSuperlayer()
gradientLayer = tempLayer
gradientLayer.cornerRadius = self.bounds.height*0.07
self.layer?.insertSublayer(gradientLayer, at: 0)
}
backgroundColors = colors
gradientLayer.colors = backgroundColors
gradientLayer.startPoint = CGPoint(x: 0,
y: 1)
gradientLayer.endPoint = CGPoint(x: 1.0,
y: 0.0)
if gradientLayer.superlayer == nil {
gradientLayer.cornerRadius = 6.0
gradientLayer.frame = self.bounds
self.layer?.insertSublayer(gradientLayer, at: 0)
}
}
override func layout() {
super.layout()
if setAllElements() {
imageHiddenLayout()
subtitleHiddenLayout()
}
}
func subtitleHiddenLayout() {
if (subtitleTextField?.isHidden)! {
let newOriginY = (self.bounds.height/2) - (titleTextField?.bounds.height)!/2
titleTextField?.frame = CGRect(x: (titleTextField?.frame.origin.x)!,
y: newOriginY,
width: (titleTextField?.bounds.width)!,
height: (titleTextField?.bounds.height)!)
} else {
let distanceBetweenFields: CGFloat = 0.0 // 0% from height
let newFrameTitleField =
CGRect(x: (titleTextField?.frame.origin.x)!,
y: (self.bounds.height/2) + ((titleTextField?.bounds.height)!+(subtitleTextField?.bounds.height)!+distanceBetweenFields)/2 - (titleTextField?.bounds.height)!,
width: (titleTextField?.bounds.width)!,
height: (titleTextField?.bounds.height)!)
let newFrameSubtitleField =
CGRect(x: (subtitleTextField?.frame.origin.x)!,
y: (self.bounds.height/2) - ((titleTextField?.bounds.height)!+(subtitleTextField?.bounds.height)!+distanceBetweenFields)/2,
width: (subtitleTextField?.bounds.width)!,
height: (subtitleTextField?.bounds.height)!)
titleTextField?.frame = newFrameTitleField
subtitleTextField?.frame = newFrameSubtitleField
}
}
func imageHiddenLayout() {
let heightTitleLabel = self.bounds.height*0.22
let heightSubtitleLabel = self.bounds.height*0.16
backgroundImageView?.frame =
CGRect(x: 0.08 * self.bounds.width,
y: 0.34 * self.bounds.height,
width: 0.33 * self.bounds.height,
height: 0.33 * self.bounds.height)
if (backgroundImageView?.isHidden)! {
titleTextField?.frame = CGRect(x: self.bounds.origin.x,
y: (titleTextField?.frame.origin.y)!,
width: self.bounds.width,
height: heightTitleLabel)
subtitleTextField?.frame = CGRect(x: self.bounds.origin.x,
y: (subtitleTextField?.frame.origin.y)!,
width: self.bounds.width,
height: heightSubtitleLabel)
} else {
let newOriginX = (backgroundImageView?.frame.origin.x)!+(backgroundImageView?.frame.width)!
titleTextField?.frame = CGRect(x: newOriginX,
y: (titleTextField?.frame.origin.y)!,
width: self.bounds.width-newOriginX,
height: heightTitleLabel)
subtitleTextField?.frame = CGRect(x: newOriginX,
y: (subtitleTextField?.frame.origin.y)!,
width: self.bounds.width-newOriginX,
height: heightSubtitleLabel)
}
}
func setAllElements() -> Bool {
if backgroundImageView == nil || titleTextField == nil || subtitleTextField == nil {
for subview in self.subviews {
if subview is BackgroundImageView && backgroundImageView == nil {
backgroundImageView = subview as? BackgroundImageView
}
if subview is TitleTextField && titleTextField == nil {
titleTextField = subview as? TitleTextField
}
if subview is SubtitleTextField && subtitleTextField == nil {
subtitleTextField = subview as? SubtitleTextField
}
}
if backgroundImageView != nil || titleTextField != nil || subtitleTextField != nil {
return true
} else {
return false
}
} else {
return true
}
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/ColorModel.swift
//
// ColorModel.swift
// SocialBannersApp
//
// Created by <NAME> on 18.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class ColorModel {
var name: String
var fillColor: NSColor?
var firstGradientColor: NSColor?
var secondGradientColor: NSColor?
init(name: String, fillColor: NSColor) {
self.name = name
self.fillColor = fillColor
}
init(name: String, firstGradientColor: NSColor, secondGradientColor: NSColor) {
self.name = name
self.firstGradientColor = firstGradientColor
self.secondGradientColor = secondGradientColor
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/SubstrateHeaderView.swift
//
// SubstrateHeaderView.swift
// SocialBannersApp
//
// Created by <NAME> on 03.06.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class SubstrateHeaderView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
self.layer?.backgroundColor = .white
// Drawing code here.
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/BgColorBannerCollectionItem.swift
//
// BgColorBannerCollectionItem.swift
// SocialBannersApp
//
// Created by <NAME> on 18.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class BgColorBannerCollectionItem: NSCollectionViewItem {
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.clear.cgColor
view.layer?.cornerRadius = 4
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/ViewController.swift
//
// ViewController.swift
// SocialBannersApp
//
// Created by <NAME> on 14.05.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, NSCollectionViewDataSource, NSCollectionViewDelegate {
// MARK: - IBOutlet's
@IBOutlet weak var addBannerButton: AddBannerButton!
@IBOutlet weak var myBannersLabel: NSTextField!
@IBOutlet weak var bannersScrollView: NSScrollView!
@IBOutlet weak var bannersCollection: NSCollectionView!
lazy var window: NSWindow! = self.view.window
// MARK: - Private Variables
private var windowStartedSize = CGRect.zero
private var windowFinishedSize = CGRect.zero
private var windowStartedState = true
override func viewDidLoad() {
super.viewDidLoad()
//UserDefaults.standard.removeObject(forKey: BannersKey.banners.rawValue)
configureCollectionView()
bannersCollection.frame = bannersScrollView.bounds
// Do any additional setup after loading the view.
}
override func viewWillAppear() {
super.viewWillAppear()
self.window.backgroundColor = NSColor(calibratedRed: 0.96470588,
green: 0.96470588,
blue: 0.96470588,
alpha: 1.0)
remove(.resizable)
}
override func viewDidAppear() {
super.viewDidAppear()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
// MARK: - NSCollectionViewDataSource
public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
let bannersModel = BannersDefaults.loadBanners(forKey: .banners)
return bannersModel.count
}
public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: "PreviewBannerCollectionItem",
for: indexPath)
guard let collectionViewItem = item as? PreviewBannerCollectionItem else {
return item
}
let bannersModel = BannersDefaults.loadBanners(forKey: .banners)
if bannersModel.count > 0 {
collectionViewItem.setAllElements(withCurrentModel: bannersModel[indexPath.item])
}
return item
}
// MARK: - NSCollectionViewDelegate
public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
for indexPath in indexPaths {
let createBannerVC = self.storyboard?.instantiateController(withIdentifier: "CreateNewBannerViewController") as! CreateNewBannerViewController
let bannersModel = BannersDefaults.loadBanners(forKey: .banners)
createBannerVC.newBannerModel = bannersModel[indexPath.item]
resizeWindow(withCreateBannerSize: createBannerVC.view.bounds)
self.presentViewControllerAsSheet(createBannerVC)
}
}
// MARK: - Helpful Functions
func remove(_ member: NSWindowStyleMask) {
window.styleMask.remove(member)
}
func resizeWindow(withCreateBannerSize createBannerSize: CGRect) {
if windowStartedState {
hideAllElements(isHidden: true)
self.windowStartedSize = self.window.frame
self.windowFinishedSize = CGRect(x: windowStartedSize.origin.x + (windowStartedSize.width - createBannerSize.width)/2,
y: windowStartedSize.origin.y,
width: createBannerSize.width,
height: windowStartedSize.height)
self.window.setFrame(windowFinishedSize,
display: true,
animate: true)
} else {
hideAllElements(isHidden: false)
self.windowFinishedSize = (self.view.window?.frame)!
self.windowStartedSize = CGRect(x: windowFinishedSize.origin.x - (windowStartedSize.width - createBannerSize.width)/2,
y: windowFinishedSize.origin.y,
width: windowStartedSize.width,
height: windowStartedSize.height)
self.view.window?.setFrame(windowStartedSize,
display: true,
animate: true)
}
windowStartedState = !windowStartedState
}
func hideAllElements(isHidden: Bool) {
let alpha: CGFloat = isHidden ? 0.0 : 1.0
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = isHidden ? 0.3 : 1.0
addBannerButton.animator().alphaValue = alpha
myBannersLabel.animator().alphaValue = alpha
bannersCollection.animator().alphaValue = alpha
}, completionHandler: nil)
}
// MARK: - Actions
@IBAction func addNewBannerAction(_ sender: AddBannerButton) {
let createBannerVC = self.storyboard?.instantiateController(withIdentifier: "CreateNewBannerViewController") as! CreateNewBannerViewController
resizeWindow(withCreateBannerSize: createBannerVC.view.bounds)
self.presentViewControllerAsSheet(createBannerVC)
}
// MARK: - Configure CollectionView
fileprivate func configureCollectionView() {
let flowLayout = NSCollectionViewFlowLayout()
let widthForLayout = 224.0
flowLayout.itemSize = NSSize(width: widthForLayout,
height: widthForLayout * 0.5625)
flowLayout.sectionInset = EdgeInsets(top: 20, left: 20,
bottom: 20, right: 20)
flowLayout.minimumInteritemSpacing = 15
flowLayout.minimumLineSpacing = 40
flowLayout.scrollDirection = .vertical
bannersCollection.collectionViewLayout = flowLayout
bannersCollection.enclosingScrollView?.scrollerStyle = .overlay
bannersCollection.enclosingScrollView?.scrollerKnobStyle = .light
view.wantsLayer = true
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/SubtitleTextField.swift
//
// SubtitleTextField.swift
// SocialBannersApp
//
// Created by <NAME> on 21.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class SubtitleTextField: NSTextField {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
override func becomeFirstResponder() -> Bool {
let success = super.becomeFirstResponder()
if success {
let textfield = (self.currentEditor()) as! NSTextView
if textfield.responds(to: #selector(setter: NSTextView.insertionPointColor)) {
textfield.insertionPointColor = .white
}
}
return success
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/IconLabel.swift
//
// IconLabel.swift
// SocialBannersApp
//
// Created by <NAME> on 11.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class IconLabel: NSTextField {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let shadow = NSShadow()
shadow.shadowOffset = NSSize(width: 0, height: -1)
shadow.shadowColor = NSColor.black.withAlphaComponent(0.25)
self.shadow = shadow
// Drawing code here.
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/Translation.swift
//
// Translation.swift
// SocialBannersApp
//
// Created by <NAME> on 24.06.2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import Cocoa
class Translation {
// MARK: - English Base
static let changeString = NSLocalizedString("changeString",
tableName: "Main",
bundle: Bundle.main,
value: "Change",
comment: "Change String Button")
static let saveString = NSLocalizedString("saveString",
tableName: "Main",
bundle: Bundle.main,
value: "Save",
comment: "Save String Button")
}
<file_sep>/SocialBannersApp/SocialBannersApp/TitleView.swift
//
// TitleView.swift
// SocialBannersApp
//
// Created by <NAME> on 28.05.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
class TitleView: NSView {
var gradientLayer = CAGradientLayer()
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if gradientLayer.superlayer == nil {
setBackgroundLayer()
}
// Drawing code here.
}
func setBackgroundLayer() {
let firstGradientColor = CGColor.init(red: 0.10196078,
green: 0.83921569,
blue: 0.99215686,
alpha: 1.0)
let secondDradientColor = CGColor.init(red: 0.11372549,
green: 0.38431373,
blue: 0.94117647,
alpha: 1)
gradientLayer = createGradientLayer(withFirstColor: firstGradientColor,
secondColor: secondDradientColor,
andFrame: self.bounds)
self.layer?.insertSublayer(gradientLayer,
at: 0)
let shadow = NSShadow()
shadow.shadowOffset = NSSize(width: 0, height: -2)
shadow.shadowColor = NSColor.black.withAlphaComponent(0.25)
shadow.shadowBlurRadius = 4
self.shadow = shadow
}
}
<file_sep>/SocialBannersApp/SocialBannersApp/CrtBnnrBgScrollView.swift
//
// CrtBnnrBgScrollView.swift
// SocialBannersApp
//
// Created by <NAME> on 02.06.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Cocoa
import Darwin
class CrtBnnrBgScrollView: NSScrollView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
self.scrollerStyle = .overlay
self.scrollerKnobStyle = .light
// Drawing code here.
}
override func scrollWheel(with event: NSEvent) {
var shouldForwardScroll = false
if self.usesPredominantAxisScrolling {
if fabs(event.deltaX) > fabs(event.deltaY) {
// horizontal scroll
if !self.hasHorizontalScroller {
shouldForwardScroll = true
}
} else {
/*
// vertical scroll
if !self.hasVerticalScroller {
shouldForwardScroll = true
}*/
}
}
if shouldForwardScroll {
self.nextResponder?.scrollWheel(with: event)
} else {
super.scrollWheel(with: event)
}
}
}
| 15a86f4f75fdedd883efc8da9d09ed973d7d4c9f | [
"Swift",
"Markdown"
] | 34 | Swift | Semty/SocialBannersApp | e598b70c50f363943f6b9de0eb473ccefa0d6706 | 9b74a373eb0df4ca44f35ae339d701a63d12134e |
refs/heads/master | <file_sep>from .models import Details, Experience, Education, Project
from django import forms, template
class ProfileForm(forms.ModelForm):
class Meta:
model = Details
fields = ['first_name', 'last_name', 'birth_date', 'gender', 'contact', 'address', 'facebook', 'github', 'linkedin', 'photo']
class ExperienceForm(forms.ModelForm):
class Meta:
model = Experience
fields = ['company', 'start_date', 'end_date', 'description']
class EducationForm(forms.ModelForm):
class Meta:
model = Education
fields = ['institution_name', 'degree', 'start_year', 'end_year']
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['title', 'description', 'url', 'image_file']
<file_sep>import os
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.utils import timezone
class Details(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
birth_date = models.DateField(null=True, blank=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
contact = models.CharField(max_length=10)
address = models.CharField(max_length=500)
facebook = models.CharField(max_length=100)
github = models.CharField(max_length=100)
linkedin = models.CharField(max_length=100)
created_at = models.DateTimeField(null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
deleted_at = models.DateTimeField(null=True, blank=True)
photo = models.FileField()
class Meta:
verbose_name_plural = 'details'
def __str__(self):
return self.first_name + ' ' + self.last_name
def age(self):
current = timezone.now()
return (current - self.birth_date)
def save(self, *args, **kwargs):
if not self.createdAt:
self.createdAt = timezone.now()
self.updatedAt = timezone.now()
return super(Review, self).save(*args, **kwargs)
class Experience(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
company = models.CharField(max_length=200)
start_date = models.DateField(null=True, blank=True)
end_date = models.DateField(null=True, blank=True)
description = models.TextField(max_length=1000)
class Education(models.Model):
DEGREE_CHOICES = (
('H', 'High School'),
('I', 'Intermediate'),
('G', 'Graduate'),
('P', 'Post Graduate'),
('R', 'Research')
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
institution_name = models.CharField(max_length=100)
degree = models.CharField(max_length=1, choices=DEGREE_CHOICES)
start_year = models.CharField(max_length=4)
end_year = models.CharField(max_length=4)
class Project(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
description = models.TextField(max_length=1000, null=True, blank=True)
url = models.CharField(null=True, blank=True, max_length=500)
image_file = models.FileField(blank=True)
class Meta:
unique_together = ['user', 'title']
<file_sep>from django.conf.urls import url
from . import views
app_name = 'resume'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
# /resume/profile/create
url(r'^profile/create/$', views.ProfileCreate.as_view(), name='profile-create'),
# /resume/profile/update
url(r'^profile/update/$', views.ProfileUpdate.as_view(), name='profile-update'),
# /resume/experience/add
url(r'^experience/add/$', views.ExperienceAdd.as_view(), name='experience-add'),
# /resume/experiences/
url(r'^experiences/$', views.ExperienceList.as_view(), name='experiences'),
# /resume/experience/3/update/
url(r'^experience/(?P<pk>[0-9]+)/update/$', views.ExperienceUpdate.as_view(), name='experience-update'),
# /resume/education/add
url(r'^education/add/$', views.ExperienceAdd.as_view(), name='education-add'),
# /resume/educations/
url(r'^educations/$', views.EducationList.as_view(), name='educations'),
# /resume/education/3/update/
url(r'^education/(?P<pk>[0-9]+)/update/$', views.EducationUpdate.as_view(), name='education-update'),
# /resume/project/add
url(r'^project/add/$', views.ProjectAdd.as_view(), name='project-add'),
# /resume/projects/
url(r'^projects/$', views.ProjectList.as_view(), name='projects'),
# /resume/experience/3/update/
url(r'^project/(?P<pk>[0-9]+)/update/$', views.ProjectUpdate.as_view(), name='project-update'),
]
<file_sep>from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.utils.timezone import utc
from django.views.generic import View
from .models import Details, Education, Experience, Project
from .forms import ProfileForm, ExperienceForm, EducationForm, ProjectForm
class IndexView(generic.ListView):
pass
@method_decorator(login_required, name="dispatch")
class ProfileCreate(CreateView):
form_class = ProfileForm
template_name = 'resume/profile_create.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
profile = form.save(commit = False)
profile.user = request.user
# fname, extension = os.splitext(form.cleaned_data['photo'].name)
profile.save()
else:
return render(request, self.template_name, {'errors': form.errors})
return redirect('resume:index')
class ProfileUpdate(UpdateView):
model = Details
template_name = 'resume/profile_update.html'
fields = ['first_name', 'last_name', 'birth_date', 'gender', 'contact', 'address', 'facebook', 'github', 'linkedin']
class ExperienceAdd(View):
form_class = ExperienceForm
template_name = 'resume/experience_add.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
experience = form.save(commit = False)
experience.user = request.user
experience.save()
else:
return render(request, self.template_name, {'errors': form.errors})
return redirect('resume:experiences')
class ExperienceList(generic.ListView):
template_name = 'resume/experiences.html'
context_object_name = 'all_experiences'
def get_queryset(self):
return Experience.objects.filter(user=request.user)
class ExperienceUpdate(UpdateView):
model = Experience
template_name = 'resume/experience_update.html'
fields = ['company', 'start_date', 'end_date', 'description']
class EducationAdd(View):
form_class = EducationForm
template_name = 'resume/education_add.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
education = form.save(commit = False)
education.user = request.user
education.save()
else:
return render(request, self.template_name, {'errors': form.errors})
return redirect('resume:educations')
class EducationList(generic.ListView):
template_name = 'resume/educations.html'
context_object_name = 'all_education'
def get_queryset(self):
return Education.objects.filter(user=request.user)
class EducationUpdate(UpdateView):
model = Experience
template_name = 'resume/experience_update.html'
fields = ['institution_name', 'degree', 'start_year', 'end_year']
class ProjectAdd(View):
form_class = ProjectForm
template_name = 'resume/project_add.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
project = form.save(commit = False)
project.user = request.user
project.save()
else:
return render(request, self.template_name, {'errors': form.errors})
return redirect('resume:projects')
class ProjectList(generic.ListView):
template_name = 'resume/projects.html'
context_object_name = 'all_projects'
def get_queryset(self):
return Project.objects.filter(user=request.user)
class ProjectUpdate(UpdateView):
model = Project
template_name = 'resume/project_update.html'
fields = ['title', 'description', 'url', 'image_file']
<file_sep>from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='website/index.html'), name='home'),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts/urls')),
url(r'^resume/', include('resume.urls')),
url(r'^website/', include('website.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| 45e8e31e3acbb46d3052da65699d886f0e0e446b | [
"Python"
] | 5 | Python | rajat19/Biografya | 39c01a8527a74497b6cdb799b7cc56fd4c8832a6 | 1594fc9f0196715004f401aceb31c647fc951af5 |
refs/heads/master | <file_sep>const path = require('path');
const paths = {
assets: path.resolve(__dirname, './src/assets'),
styles: path.resolve(__dirname, './src/assets/styles'),
images: path.resolve(__dirname, './src/assets/images'),
fonts: path.resolve(__dirname, './src/assets/fonts'),
components: path.resolve(__dirname, './src/components'),
pages: path.resolve(__dirname, './src/pages'),
public: path.resolve(__dirname, './public'),
root: path.resolve(__dirname, './')
};
module.exports = paths;
<file_sep>import React, { userState, useState } from 'react';
const box = props => {
const [personsState, setPersonsState] = useState({
persons: [
{ name: 'Basketball', power: 77 },
{ name: 'Boxing', power: 92 },
{ name: 'Jim', power: 99 }
]
});
const switchNameHandler = () => {
setPersonsState({
persons: [
{ name: 'Yoga', power: 33 },
{ name: 'Dance', power: 41 },
{ name: 'Walking', power: 19 }
]
});
};
return (
<div className="box">
<ul>
{personsState.persons.map((person, index) => {
return <li key={index}>{++index + ':' + person.name}</li>;
})}
</ul>
<button onClick={switchNameHandler}>click me now</button>
</div>
);
};
export default box;
<file_sep>import React, { Component } from 'react';
import Box from '@components/presentational/Box/Box.jsx';
class App extends Component {
state = {
persons: [
{ name: 'Max', age: 29 },
{ name: 'Jane', age: 21 },
{ name: 'Jack', age: 22 }
]
};
switchNameHandler = () => {
this.setState({
persons: [
{ name: 'Casey', age: 28 },
{ name: 'Janice', age: 21 },
{ name: 'Emily', age: 19 }
]
});
};
render() {
return (
<div>
<h1>Hi from React!</h1>
<ul>
{this.state.persons.map((person, index) => {
return <li key={index}>{++index + ':' + person.name}</li>;
})}
</ul>
<button onClick={this.switchNameHandler}>click</button>
<Box />
</div>
);
}
}
export default App;
| 1522defb550cecfe37b32fd15e670820af709c52 | [
"JavaScript"
] | 3 | JavaScript | nikolalakovic85/react-demo | cff89c3103e301289b9a671a7cef467ab0863523 | 0e01b7985e7f964f9e937066acb95e7bf88961fb |
refs/heads/master | <file_sep>//karim
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RockPaperScissors
{
public partial class frmPlay : Form
{
int x = 0;
int y = 0;
Random rnd = new Random();
public frmPlay(String userName)
{
InitializeComponent();
lblName.Text = userName;
}
private void btnPlay_Click(object sender, EventArgs e)
{
int player2 = rnd.Next(0, 4);
if (picUser.Image == null)
{
MessageBox.Show("Please select Rock, Paper, or Scissors");
}
else
{
switch (player2)
{
case 1:
picPc.Image = Properties.Resources.paper2;
break;
case 2:
picPc.Image = Properties.Resources.rock2;
break;
case 3:
picPc.Image = Properties.Resources.scissor2;
break;
}
if (picUser.Image == picPaper.Image && player2 == 1 || picUser.Image == picRock.Image && player2 == 2 || picUser.Image == picScissor.Image && player2 == 3)
{
lblScoreKeeper.Text = "Tie";
}
if (picUser.Image == picPaper.Image && player2 == 2 || picUser.Image == picScissor.Image && player2 == 1 || picUser.Image == picRock.Image && player2 == 3)
{
++x;
lblUserScore.Text = x.ToString();
lblScoreKeeper.Text = lblName.Text + " Won";
}
if (picUser.Image == picPaper.Image && player2 == 3 || picUser.Image == picRock.Image && player2 == 1 || picUser.Image == picScissor.Image && player2 == 2)
{
++y;
lblPcScore.Text = y.ToString();
lblScoreKeeper.Text = "PC Won";
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void picPaper_Click(object sender, EventArgs e)
{
picUser.Image = picPaper.Image;
}
private void picScissor_Click(object sender, EventArgs e)
{
picUser.Image = picScissor.Image;
}
private void picRock_Click(object sender, EventArgs e)
{
picUser.Image = picRock.Image;
}
private void lblStartOver_Click(object sender, EventArgs e)
{
int userScore, pcScore, winner=0;
string winnerMsg;
int.TryParse(lblUserScore.Text, out userScore);
int.TryParse(lblPcScore.Text, out pcScore);
if(userScore > pcScore)
{
userScore = winner;
winnerMsg = lblName.Text +"\nYou Won, Game is being restarted";
}
else if(userScore < pcScore)
{
pcScore = winner;
winnerMsg = "You Lost, Good luck on your next game\nGame is being restarted";
}
else
{
winnerMsg = "That was a tie,\nGame is being restarted";
}
lblUserScore.Text = "";
lblPcScore.Text = "";
picUser.Image = null;
picPc.Image = null;
lblScoreKeeper.Text = "";
MessageBox.Show(winnerMsg.ToString(), "Start Over");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RockPaperScissors
{
public partial class frmRockPaperScissors : Form
{
public frmRockPaperScissors()
{
InitializeComponent();
}
private void btnSignIn_Click(object sender, EventArgs e)
{
frmPlay frm2 = new frmPlay(txtName.Text);
frmRockPaperScissors frm1 = new frmRockPaperScissors();
if (txtName.Text == "")
{
MessageBox.Show("Please enter your name!!", "Invalid Entry");
}
else
{
this.Hide();
frm2.ShowDialog();
this.Close();
}
}
}
}
| 2be5e5756d5b846aee2c8da7360e861d9ac40e7c | [
"C#"
] | 2 | C# | karimeltabche/RockPaperScissors | 5db400738006e7a042bf1967c9b90c39296fe6e4 | 2b4856f43c998e329d1747a7ef54959880913432 |
refs/heads/master | <repo_name>namseohyeon/herethon-project<file_sep>/hereapp/views.py
from django.shortcuts import render, redirect
from .models import Email, Result
# Create your views here.
def index(request):
return render(request, 'index.html')
def new(request):
return render(request, 'new.html')
def showresults(request):
results = Result.objects.all()
return render(request, 'see-results.html', {'results':results})
def addemail(request):
if request.method == 'POST':
newEmail = Email()
newEmail.name = request.POST['name']
newEmail.email = request.POST['email']
newEmail.save()
return redirect('mypage')
else:
return render(request, 'addemail.html')
def mypage(request):
emails = Email.objects.all()
return render(request, 'mypage.html', {'emails':emails})
<file_sep>/hereapp/urls.py
from django.urls import path
from . import views
from hereapp import views
urlpatterns = [
path('new/', views.new, name='new'),
path('addemail/', views.addemail, name='addemail'),
path('mypage/', views.mypage, name="mypage"),
path('showresults/', views.showresults, name='showreulsts'),
] | bf28ec5bca25ba3dbf44ae9e1c6f88f0e306fa32 | [
"Python"
] | 2 | Python | namseohyeon/herethon-project | 65a2d30ce4f8a832ec9770321054df90570845c5 | cb06ec41c23d285c6d9574557580873947f69cf7 |
refs/heads/master | <file_sep>require 'spec_helper_acceptance'
describe 'pulsar class' do
context 'default parameters' do
# Using puppet_apply as a helper
it 'should work idempotently with no errors' do
pp = <<-EOS
user { 'galaxy':
ensure => present,
}
group { 'galaxy':
ensure => present,
}
class { 'supervisord': }
class { 'pulsar':
manage_gcc => true,
manage_git => true,
}
EOS
# Run it twice and test for idempotency
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :catch_changes => true)
end
describe package('gcc') do
it { should be_installed }
end
describe package('gcc-c++') do
it { should be_installed }
end
describe package('git') do
it { should be_installed }
end
describe package('python') do
it { should be_installed }
end
describe package('python2-pip') do
it { should be_installed }
end
describe package('python-devel') do
it { should be_installed }
end
describe package('python-gunicorn') do
it { should_not be_installed }
end
describe package('python-virtualenv') do
it { should be_installed }
end
describe yumrepo('epel') do
it { should exist }
it { should be_enabled }
end
describe file('/opt/pulsar') do
it { should be_directory }
it { should be_mode 775 }
end
describe file('/opt/pulsar/venv') do
it { should be_directory }
it { should be_mode 775 }
end
describe file('/opt/pulsar/venv/lib/python2.7/site-packages/pulsar') do
it { should be_directory }
end
describe file('/opt/pulsar/requirements.txt') do
it { should be_file }
it { should contain 'pulsar-app' }
end
describe file('/opt/pulsar/app.yml') do
it { should be_file }
it { should be_mode 664 }
it { should contain 'staging_directory: /opt/pulsar/files/staging' }
it { should contain '__default__' }
it { should contain 'persistence_directory: /opt/pulsar/files/persisted_data' }
it { should contain 'tool_dependency_dir: /opt/pulsar/dependencies' }
end
describe file('/opt/pulsar/local_env.sh') do
it { should be_file }
it { should be_mode 664 }
it { should contain '#export DRMAA_LIBRARY_PATH=/path/to/libdrmaa.so' }
end
describe file('/opt/pulsar/run.sh') do
it { should be_file }
it { should be_mode 775 }
it { should contain 'PULSAR_CONFIG_DIR=/opt/pulsar' }
it { should contain 'PULSAR_LOCAL_ENV=/opt/pulsar/local_env.sh' }
it { should contain 'PULSAR_VIRTUALENV=/opt/pulsar/venv' }
end
describe file('/opt/pulsar/server.ini') do
it { should be_file }
it { should be_mode 664 }
it { should contain '# Puppet managed file. Local changes will be overwritten.' }
it { should contain '[server:main]' }
it { should contain 'use = egg:Paste#http' }
end
describe file('/etc/supervisor/conf.d/pulsar.conf') do
it { should be_file }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
it { should be_mode 644 }
it { should contain '[program:pulsar]' }
end
describe process('pulsar') do
it { should be_running }
end
end
end
<file_sep># pulsar
master branch: [](http://travis-ci.org/millerjl1701/millerjl1701-pulsar)
#### Table of Contents
1. [Module Description - What the module does and why it is useful](#module-description)
1. [Setup - The basics of getting started with pulsar](#setup)
* [What pulsar affects](#what-pulsar-affects)
* [Setup requirements](#setup-requirements)
* [Beginning with pulsar](#beginning-with-pulsar)
1. [Usage - Configuration options and additional functionality](#usage)
1. [Reference - An under-the-hood peek at what the module is doing and how](#reference)
1. [Limitations - OS compatibility, etc.](#limitations)
1. [Development - Guide for contributing to the module](#development)
## Module Description
This module installs, configures and manages pulsar, an add-on to Galaxy.
For more information on pulsar and the capabilities it provides, please see [https://pulsar.readthedocs.io/en/latest/](https://pulsar.readthedocs.io/en/latest/).
Galaxy is an open web-based platform for accessible, reproducible, and transparent computational biomedical research.
* [Galaxy Project Web Site](https://galaxyproject.org/)
* [Galaxy Documentation](https://galaxyproject.org/docs/)
* [Galaxy Code Repository](https://github.com/galaxyproject/galaxy)
This module uses Puppet 4 data types as well as providing puppet data in the module. It will not work with puppet versions earlier than 4.7, and is currently written to support CentOS/RHEL 7. Other operating systems will be added as time permits.
This module relies on the [stankevich/python](https://forge.puppet.com/stankevich/python) python module for installation of pip, pulsar-app, and other packages. By default, the management of python is disabled in the pulsar module.
For pulsar to properly install using the git repository as opposed to the pip package, git will need to be managed either with this module (leveraging the puppetlabs/git module) or a different method or module.
For pulsar to properly startup, gcc needs to be present as pulsar installs dependencies into the application directory that require compilation. The gcc installation can be managed with either this module (leveraging the puppetlabs/gcc module) or a different method or module.
By default, the `/etc/supervisor/conf.d/pulsar.conf` file is managed by the pulsar module as it assumes that the millerjl1701/supervisord module is being used. If you are a different module or method for supervisord, the management of this file can be disabled.
## Setup
### What pulsar affects
* Packages (by default)
* pulsar-app (via pip)
* gcc
* git
* python-dev
* python2-pip
* python-virtualenv.
* Files
* /etc/supervisor/conf.d/pulsar.conf
* /opt/pulsar
* /opt/pulsar/app.yml
* /opt/pulsar/local_env.sh
* /opt/pulsar/requirements.txt
* /opt/pulsar/run.sh
* /opt/pulsar/server.ini
* /opt/pulsar/venv
* /var/log/pulsar
* Services
* pulsar (as a supervisord program)
### Setup Requirements
This module depends on the following puppet modules:
* [mmckinst-hash2stuff](https://forge.puppet.com/mmckinst/hash2stuff)
* [puppetlabs-gcc](https://forge.puppet.com/puppetlabs/gcc)
* [puppetlabs-git](https://forge.puppet.com/puppetlabs/git)
* [puppetlabs-stdlib](https://forge.puppet.com/puppetlabs/stdlib)
* [puppetlabs-vcsrepo](https://forge.puppet.com/puppetlabs/vcsrepo)
* [stankevich-python](https://forge.puppet.com/stankevich/python)
The [stahnma-epel](https://forge.puppet.com/stahnma/epel) module is listed in the metadata.json file as a dependency as well, since stankevich-python lists it as a dependency. A parameter for this module is provided to disable the use of epel for package installation should you be using yumrepo resources or Spacewalk package management instead.
The supervisord program is expected to be utlilized for the management of the pulsar service. This module does not manage or configuration of the supervisord service. The acceptance tests rely on the millerjl1701/supervisord puppet module for supervisord installation and configuration. If you are using a different method, the supervisord pulsar.conf file management can be disabled.
### Beginning with pulsar
Assuming that the prerequisites are met (supervisord, python and gcc. potentially git), `include pulsar` is all that is needed to install, configure, and start up a pulsar server listening to port localhost:8913.
## Usage
### Installation of pulsar and all needed dependencies with puppet manifest
```puppet
class { 'pulsar':
manage_gcc => true,
manage_git => true,
manage_python => true,
}
```
### Installation of pulsar and all needed dependencies using hiera
```yaml
---
pulsar::manage_python: true
pulsar::manage_gcc: true
pulsar::manage_git: true
```
## Reference
Generated puppet strings documentation with examples is available from [https://millerjl1701.github.io/millerjl1701-pulsar](https://millerjl1701.github.io/millerjl1701-pulsar).
The puppet strings documentation is also included in the /docs folder.
### Public Classes
* pulsar: Main class which installs and configures the pulsar service. Parameters may be passed via class declaration or hiera.
### Private Classes
* pulsar::config: Class for generating the configuration files for the pulsar server.
* pulsar::gcc: Class for installing gcc for use by pulsar.
* pulsar::git: Class for installing git for use by pulsar.
* pulsar::install: Class for installing the pulsar server.
* pulsar::python: Class for installing and configuring python for use by pulsar.
* pulsar::service: Class for managing the pulsar service.
## Limitations
This module is currently written for CentOS/RHEL 7 only. Other operating systems will be added as time permits (unless someone submits a PR first. :)
No validation of the server.ini file is performed to check what settings have been added. Passing appropriate parameters and values are left as an exercise for the reader.
## Development
Please see the [CONTRIBUTING document](CONTRIBUTING.md) for information on how to get started developing code and submit a pull request for this module. While written in an opinionated fashion at the start, over time this can become less and less the case.
### Contributors
To see who is involved with this module, see the [GitHub list of contributors](https://github.com/millerjl1701/millerjl1701-pulsar/graphs/contributors) or the [CONTRIBUTORS document](CONTRIBUTORS).
## Credits
Since this module is designed primarily for the management of Galaxy processes, the [Galaxy Project Administration Training repository](https://github.com/galaxyproject/dagobah-training/) was used heavily to guide how pulsar is configured and used in complex environments. The GalaxyProject [ansible galaxy runbooks](https://github.com/galaxyproject/ansible-galaxy) and [use galaxy runbooks](https://github.com/galaxyproject/usegalaxy-playbook/) were also referenced in order to grok the needed pieces installed and configured more efficiently. Thank you to all the instructors and contriibutors past and present who have developed and published these materials.
<file_sep>require 'spec_helper'
describe 'pulsar' do
context 'supported operating systems' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts
end
context "pulsar class without any parameters changed from defaults" do
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('pulsar::gcc') }
it { is_expected.to contain_class('pulsar::git') }
it { is_expected.to contain_class('pulsar::python') }
it { is_expected.to contain_class('pulsar::install') }
it { is_expected.to contain_class('pulsar::config') }
it { is_expected.to contain_class('pulsar::service') }
it { is_expected.to contain_class('pulsar::gcc').that_comes_before('Class[pulsar::git]') }
it { is_expected.to contain_class('pulsar::git').that_comes_before('Class[pulsar::python]') }
it { is_expected.to contain_class('pulsar::python').that_comes_before('Class[pulsar::install]') }
it { is_expected.to contain_class('pulsar::install').that_comes_before('Class[pulsar::config]') }
it { is_expected.to contain_class('pulsar::service').that_subscribes_to('Class[pulsar::config]') }
it { is_expected.to contain_class('epel') }
it { is_expected.to contain_yumrepo('epel') }
it { is_expected.to_not contain_package('gcc') }
it { is_expected.to_not contain_package('gcc-c++') }
it { is_expected.to_not contain_package('git') }
it { is_expected.to contain_class('python') }
it { is_expected.to contain_file('/opt/pulsar').with(
'ensure' => 'directory',
'owner' => 'galaxy',
'group' => 'galaxy',
'mode' => '0775',
) }
it { is_expected.to contain_file('/opt/pulsar').with(
'ensure' => 'directory',
'owner' => 'galaxy',
'group' => 'galaxy',
'mode' => '0775',
) }
it { is_expected.to contain_file('/opt/pulsar/app.yml').with(
'ensure' => 'present',
'owner' => 'galaxy',
'group' => 'galaxy',
'mode' => '0664',
) }
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^staging_directory: \/opt\/pulsar\/files\/staging$/) }
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^managers:\n __default__:$/) }
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^#job_directory_mode: 0777$/) }
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^#private_token: <PASSWORD>$/) }
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^persistence_directory: \/opt\/pulsar\/files\/persisted_data$/) }
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^#assign_ids: uuid$/) }
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^tool_dependency_dir: \/opt\/pulsar\/dependencies$/) }
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^#file_cache_dir: cache$/) }
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with(
'ensure' => 'present',
'owner' => 'galaxy',
'group' => 'galaxy',
'mode' => '0664',
) }
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^#export DRMAA_LIBRARY_PATH=\/path\/to\/libdrmaa.so$/) }
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^#export GALAXY_HOME=\/path\/to\/galaxy$/) }
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^#export GALAXY_VIRTUAL_ENV=\/path\/to\/galaxy\/.venv$/) }
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^#export TEST_GALAXY_LIBS=1$/) }
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^# . .venv\/bin\/activate$/) }
it { is_expected.to contain_file('/opt/pulsar/run.sh').with(
'ensure' => 'present',
'owner' => 'galaxy',
'group' => 'galaxy',
'mode' => '0775',
) }
it { is_expected.to contain_file('/opt/pulsar/run.sh').with_content(/^PULSAR_CONFIG_DIR=\/opt\/pulsar$/) }
it { is_expected.to contain_file('/opt/pulsar/run.sh').with_content(/^PULSAR_LOCAL_ENV=\/opt\/pulsar\/local_env.sh$/) }
it { is_expected.to contain_file('/opt/pulsar/run.sh').with_content(/^PULSAR_VIRTUALENV=\/opt\/pulsar\/venv$/) }
it { is_expected.to contain_file('/opt/pulsar/server.ini').with(
'ensure' => 'present',
'owner' => 'galaxy',
'group' => 'galaxy',
'mode' => '0664',
) }
it { is_expected.to contain_file('/opt/pulsar/server.ini').with_content(/^\# Puppet managed file. Local changes will be overwritten.$/) }
it { is_expected.to contain_file('/opt/pulsar/server.ini').with_content(/^\[server\:main\]$/) }
it { is_expected.to contain_file('/opt/pulsar/server.ini').with_content(/^use = egg\:Paste\#http$/) }
it { is_expected.to contain_file('/var/log/pulsar').with(
'ensure' => 'directory',
'owner' => 'galaxy',
'group' => 'galaxy',
'mode' => '0775',
) }
it { is_expected.to contain_python__virtualenv('/opt/pulsar/venv').with(
'ensure' => 'present',
'owner' => 'galaxy',
'group' => 'galaxy',
'mode' => '0775',
'require' => 'File[/opt/pulsar]',
) }
it { is_expected.to contain_file('/opt/pulsar/requirements.txt').with(
'ensure' => 'present',
'owner' => 'galaxy',
'group' => 'galaxy',
'mode' => '0664',
'require' => 'File[/opt/pulsar]',
) }
it { is_expected.to contain_file('/opt/pulsar/requirements.txt').with_content(/^pulsar-app$/) }
it { is_expected.to contain_python__requirements('pulsar_pip_requirements').with(
'requirements' => '/opt/pulsar/requirements.txt',
'virtualenv' => '/opt/pulsar/venv',
'owner' => 'galaxy',
'group' => 'galaxy',
'cwd' => '/opt/pulsar',
'manage_requirements' => 'false',
'fix_requirements_owner' => 'true',
'log_dir' => '/opt/pulsar',
'require' => 'File[/opt/pulsar/requirements.txt]',
) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with(
'ensure' => 'present',
'owner' => 'root',
'group' => 'root',
'mode' => '0644',
) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^\[program:pulsar\]$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^user = galaxy$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^group = galaxy$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^directory = \/opt\/pulsar$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^command = \/opt\/pulsar\/venv\/bin\/pulsar --mode \'paster\' --config \'\/opt\/pulsar\'$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^stdout_logfile = \/var\/log\/pulsar\/pulsar.log$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^stdout_logfile_backups = 10$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^autostart = true$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^autorestart = true$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^environment = VIRTUAL_ENV=\"\/opt\/pulsar\/venv\",PATH=\"\/opt\/pulsar\:\/opt\/pulsar\/venv\/bin\:\%\(ENV_PATH\)s\"$/) }
it { is_expected.to contain_exec('pulsar_supervisord_reread_config').with(
'command' => 'supervisorctl update',
'path' => '/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/puppetlabs/bin:/root/bin',
'refreshonly' => 'true',
'notify' => 'Service[pulsar]',
) }
it { is_expected.to contain_exec('pulsar_supervisord_reread_config').that_subscribes_to('File[/etc/supervisor/conf.d/pulsar.conf]') }
it { is_expected.to contain_service('pulsar').with(
'ensure' => 'running',
'status' => '/bin/ps -C pulsar -o pid=',
'start' => 'supervisorctl start pulsar',
'restart' => 'supervisorctl restart pulsar',
'stop' => 'supervisorctl stop pulsar',
) }
it { is_expected.to contain_service('pulsar').that_subscribes_to('File[/etc/supervisor/conf.d/pulsar.conf]') }
it { is_expected.to contain_service('pulsar').that_subscribes_to('Exec[pulsar_supervisord_reread_config]') }
end
context 'pulsar class with manage_gcc set to true' do
let(:params){
{
:manage_gcc => true,
}
}
it { is_expected.to contain_package('gcc') }
it { is_expected.to contain_package('gcc-c++') }
end
context 'pulsar class with manage_git set to true' do
let(:params){
{
:manage_git => true,
}
}
it { is_expected.to contain_package('git') }
end
context 'pulsar class with manage_python set to true' do
let(:params){
{
:manage_python => true,
}
}
it { is_expected.to contain_class('python').with(
'dev' => 'present',
'manage_gunicorn' => false,
'use_epel' => true,
'virtualenv' => 'present',
) }
end
context 'pulsar class with manage_python_dev set to absent' do
let(:params){
{
:manage_python_dev => 'absent',
}
}
it { is_expected.to contain_class('python').with_dev('absent') }
end
context 'pulsar class with manage_python_use_epel set to false when python is managed' do
let(:params){
{
:manage_python => true,
:manage_python_use_epel => false,
}
}
it { is_expected.to contain_class('python').with_use_epel('false') }
end
context 'pulsar class with manage_python_virtualenv set to absent' do
let(:params){
{
:manage_python_virtualenv => 'absent',
}
}
it { is_expected.to contain_class('python').with_virtualenv('absent') }
end
context 'pulsar class with pulsar_config_dir set to /etc/pulsar' do
let(:params){
{
:pulsar_config_dir => '/etc/pulsar',
}
}
it { is_expected.to contain_file('/etc/pulsar/app.yml') }
it { is_expected.to contain_file('/etc/pulsar/local_env.sh') }
it { is_expected.to contain_file('/etc/pulsar/run.sh') }
it { is_expected.to contain_file('/etc/pulsar/server.ini') }
it { is_expected.to contain_file('/etc/pulsar/run.sh').with_content(/^PULSAR_CONFIG_DIR=\/etc\/pulsar$/) }
it { is_expected.to contain_file('/etc/pulsar/run.sh').with_content(/^PULSAR_LOCAL_ENV=\/etc\/pulsar\/local_env.sh$/) }
end
context 'pulsar class with pulsar_dir set to /opt/foo' do
let(:params){
{
:pulsar_dir => '/opt/foo',
}
}
it { is_expected.to contain_file('/opt/foo').with_ensure('directory') }
it { is_expected.to contain_python__virtualenv('/opt/foo/venv').with(
'ensure' => 'present',
'require' => 'File[/opt/foo]',
) }
it { is_expected.to contain_file('/opt/foo/requirements.txt').with(
'ensure' => 'present',
'require' => 'File[/opt/foo]',
) }
it { is_expected.to contain_python__requirements('pulsar_pip_requirements').with(
'requirements' => '/opt/foo/requirements.txt',
'virtualenv' => '/opt/foo/venv',
'cwd' => '/opt/foo',
'log_dir' => '/opt/foo',
'require' => 'File[/opt/foo/requirements.txt]',
) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^directory = \/opt\/foo$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^command = \/opt\/foo\/venv\/bin\/pulsar --mode \'paster\' --config \'\/opt\/foo\'$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^environment = VIRTUAL_ENV=\"\/opt\/foo\/venv\",PATH=\"\/opt\/foo\:\/opt\/foo\/venv\/bin\:\%\(ENV_PATH\)s\"$/) }
end
context 'pulsar class with pulsar_dirmode set to 0755' do
let(:params){
{
:pulsar_dirmode => '0755',
}
}
it { is_expected.to contain_file('/opt/pulsar').with_mode('0755') }
it { is_expected.to contain_file('/opt/pulsar/run.sh').with_mode('0755') }
it { is_expected.to contain_python__virtualenv('/opt/pulsar/venv').with_mode('0755') }
end
context 'pulsar class with pulsar_drmaa_path set to /opt/drmaa' do
let(:params){
{
:pulsar_drmaa_path => '/opt/drmaa',
}
}
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^export DRMAA_LIBRARY_PATH=\/opt\/drmaa$/) }
end
context 'pulsar class with pulsar_filemode set to 0644' do
let(:params){
{
:pulsar_filemode => '0644',
}
}
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_mode('0644') }
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_mode('0644') }
it { is_expected.to contain_file('/opt/pulsar/requirements.txt').with_mode('0644') }
it { is_expected.to contain_file('/opt/pulsar/server.ini').with_mode('0644') }
end
context 'pulsar class with pulsar_file_cache_dir set to /opt/pulsar/cache' do
let(:params){
{
:pulsar_file_cache_dir => '/opt/pulsar/cache',
}
}
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^file_cache_dir: \/opt\/pulsar\/cache$/) }
end
context 'pulsar class with pulsar_galaxy_path set to /opt/galaxy' do
let(:params){
{
:pulsar_galaxy_path => '/opt/galaxy',
}
}
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^export GALAXY_HOME=\/opt\/galaxy$/) }
end
context 'pulsar class with pulsar_galaxy_venv_path set to /opt/galaxy' do
let(:params){
{
:pulsar_galaxy_venv_path => '/opt/galaxy/venv',
}
}
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^export GALAXY_VIRTUAL_ENV=\/opt\/galaxy\/venv$/) }
end
context 'pulsar class with pulsar_galaxy_verify set to true' do
let(:params){
{
:pulsar_galaxy_verify => true,
}
}
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^export TEST_GALAXY_LIBS=1$/) }
end
context 'pulsar class with pulsar_git_repository set to https://example.com/galaxy/pulsar when pulsar_pip_install is also set to false' do
let(:params){
{
:pulsar_git_repository => 'https://example.com/galaxy/pulsar',
:pulsar_pip_install => false,
}
}
it { is_expected.to contain_vcsrepo('/opt/pulsar').with_source('https://example.com/galaxy/pulsar') }
end
context 'pulsar class with pulsar_git_revision set to devel when pulsar_pip_install is also set to false' do
let(:params){
{
:pulsar_git_revision => 'devel',
:pulsar_pip_install => false,
}
}
it { is_expected.to contain_vcsrepo('/opt/pulsar').with_revision('devel') }
end
context 'pulsar class with pulsar_group set to pulsar' do
let(:params){
{
:pulsar_group => 'pulsar',
}
}
it { is_expected.to contain_file('/opt/pulsar').with_group('pulsar') }
it { is_expected.to contain_file('/opt/pulsar/requirements.txt').with_group('pulsar') }
it { is_expected.to contain_python__requirements('pulsar_pip_requirements').with_group('pulsar') }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^group = pulsar$/) }
end
context 'pulsar class with pulsar_group set to pulsar in addition to pulsar_pip_install set to false' do
let(:params){
{
:pulsar_group => 'pulsar',
:pulsar_pip_install => false,
}
}
it { is_expected.to contain_vcsrepo('/opt/pulsar').with_group('pulsar') }
end
context 'pulsar class with pulsar_job_directory_mode set to 0755' do
let(:params){
{
:pulsar_job_directory_mode => '0755',
}
}
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^job_directory_mode: 0755$/) }
end
context 'pulsar class with pulsar_job_run_as_user set to true' do
let(:params){
{
:pulsar_job_run_as_user => true,
}
}
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^. venv\/bin\/activate$/) }
end
context 'pulsar class with pulsar_job_run_as_user set to true and pulsar_pip_install set to false' do
let(:params){
{
:pulsar_job_run_as_user => true,
:pulsar_pip_install => false,
}
}
it { is_expected.to contain_file('/opt/pulsar/local_env.sh').with_content(/^. .venv\/bin\/activate$/) }
end
context 'pulsar class with pulsar_logdir set to /var/log/foobar' do
let(:params){
{
:pulsar_logdir => '/var/log/foobar',
}
}
it { is_expected.to contain_file('/var/log/foobar').with_ensure('directory') }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^stdout_logfile = \/var\/log\/foobar\/pulsar.log$/) }
end
context 'pulsar class with pulsar_num_backups set to 90' do
let (:params){
{
:pulsar_num_backups => 50,
}
}
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^stdout_logfile_backups = 50$/) }
end
context 'pulsar class with pulsar_named_managers set to hash' do
let(:params){
{
:pulsar_named_managers => { 'foo' => { 'type' => 'bar', 'jobs' => '2', } },
}
}
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^managers:\n foo:\n type: bar\n jobs: 2$/) }
end
context 'pulsar class with pulsar_owner set to pulsar' do
let(:params){
{
:pulsar_owner => 'pulsar',
}
}
it { is_expected.to contain_file('/opt/pulsar').with_owner('pulsar') }
it { is_expected.to contain_file('/opt/pulsar/requirements.txt').with_owner('pulsar') }
it { is_expected.to contain_python__requirements('pulsar_pip_requirements').with_owner('pulsar') }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^user = pulsar$/) }
end
context 'pulsar class with pulsar_owner set to pulsar in addition to pulsar_pip_install set to false' do
let(:params){
{
:pulsar_owner => 'pulsar',
:pulsar_pip_install => false,
}
}
it { is_expected.to contain_vcsrepo('/opt/pulsar').with(
'user' => 'pulsar',
'owner' => 'pulsar',
) }
end
context 'pulsar class with pulsar_persistence_dir set to /opt/pulsar/persist' do
let(:params){
{
:pulsar_persistence_dir => '/opt/pulsar/persist',
}
}
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^persistence_directory: \/opt\/pulsar\/persist$/) }
end
context 'pulsar class with pulsar_pip_install set to false' do
let(:params){
{
:pulsar_pip_install => false,
}
}
it { is_expected.to contain_vcsrepo('/opt/pulsar').with(
'ensure' => 'present',
'provider' => 'git',
'source' => 'https://github.com/galaxyproject/pulsar',
'revision' => 'master',
'user' => 'galaxy',
'owner' => 'galaxy',
'group' => 'galaxy',
) }
it { is_expected.to contain_python__virtualenv('/opt/pulsar/.venv').with(
'ensure' => 'present',
'require' => 'Vcsrepo[/opt/pulsar]',
) }
it { is_expected.to contain_file('/opt/pulsar/requirements.txt').with(
'ensure' => 'present',
'require' => 'Vcsrepo[/opt/pulsar]',
) }
it { is_expected.to contain_python__requirements('pulsar_pip_requirements').with(
'virtualenv' => '/opt/pulsar/.venv',
) }
it { is_expected.to contain_file('/opt/pulsar/run.sh').with_content(/^PULSAR_VIRTUALENV=\/opt\/pulsar\/.venv$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^command = \/opt\/pulsar\/.venv\/bin\/pulsar --mode \'paster\' --config \'\/opt\/pulsar\'$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/pulsar.conf').with_content(/^environment = VIRTUAL_ENV=\"\/opt\/pulsar\/.venv\",PATH=\"\/opt\/pulsar\:\/opt\/pulsar\/.venv\/bin\:\%\(ENV_PATH\)s\"$/) }
end
context 'pulsar class with pulsar_private_token set' do
let(:params){
{
:pulsar_private_token => '<PASSWORD>',
}
}
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^private_token: onewillneverknow$/) }
end
context 'pulsar class with pulsar_requirements to include drmaa' do
let(:params){
{
:pulsar_requirements => [ 'pulsar-app', 'drmaa', ],
}
}
it { is_expected.to contain_file('/opt/pulsar/requirements.txt').with_content(/^pulsar-app$/) }
it { is_expected.to contain_file('/opt/pulsar/requirements.txt').with_content(/^drmaa$/) }
end
context 'pulsar class with pulsar_staging_dir set to /opt/pulsar/staged' do
let(:params){
{
:pulsar_staging_dir => '/opt/pulsar/staged',
}
}
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^staging_directory: \/opt\/pulsar\/staged$/) }
end
context 'pulsar class with pulsar_tool_dependency_dir set to /opt/pulsar/deps' do
let(:params){
{
:pulsar_tool_dependency_dir => '/opt/pulsar/deps',
}
}
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^tool_dependency_dir: \/opt\/pulsar\/deps$/) }
end
context 'pulsar class with pulsar_use_uuids set to true' do
let(:params){
{
:pulsar_use_uuids => true,
}
}
it { is_expected.to contain_file('/opt/pulsar/app.yml').with_content(/^assign_ids: uuid$/) }
end
context 'pulsar class with service_manage_config set to false' do
let(:params){
{
:service_manage_config => false,
}
}
it { is_expected.to_not contain_file('/etc/supervisor/conf.d/pulsar.conf') }
end
context 'pulsar class with service_manage_configdir set to /etc/foo' do
let(:params){
{
:service_manage_configdir => '/etc/foo',
}
}
it { is_expected.to contain_file('/etc/foo/pulsar.conf') }
it { is_expected.to contain_exec('pulsar_supervisord_reread_config').that_subscribes_to('File[/etc/foo/pulsar.conf]') }
it { is_expected.to contain_service('pulsar').that_subscribes_to('File[/etc/foo/pulsar.conf]') }
end
context 'pulsar class with service_name set to foo' do
let(:params){
{
:service_name => 'foo',
}
}
it { is_expected.to contain_file('/etc/supervisor/conf.d/foo.conf').with_content(/^\[program:foo\]$/) }
it { is_expected.to contain_file('/etc/supervisor/conf.d/foo.conf').with_content(/^stdout_logfile = \/var\/log\/pulsar\/foo.log$/) }
it { is_expected.to contain_exec('pulsar_supervisord_reread_config').that_subscribes_to('File[/etc/supervisor/conf.d/foo.conf]') }
it { is_expected.to contain_exec('pulsar_supervisord_reread_config').with_notify('Service[foo]') }
it { is_expected.to contain_service('foo').with(
'start' => 'supervisorctl start foo',
'restart' => 'supervisorctl restart foo',
'stop' => 'supervisorctl stop foo',
) }
it { is_expected.to contain_service('foo').that_subscribes_to('File[/etc/supervisor/conf.d/foo.conf]') }
it { is_expected.to contain_service('foo').that_subscribes_to('Exec[pulsar_supervisord_reread_config]') }
end
end
end
end
context 'unsupported operating system' do
describe 'pulsar class without any parameters on Solaris/Nexenta' do
let(:facts) do
{
:osfamily => 'Solaris',
:operatingsystem => 'Nexenta',
}
end
it { expect { is_expected.to contain_package('pulsar') }.to raise_error(Puppet::Error, /Nexenta not supported/) }
end
end
end
| a272f897b35313672a06088c861dc8feeb4f4ca2 | [
"Markdown",
"Ruby"
] | 3 | Ruby | millerjl1701/millerjl1701-pulsar | bfcaf889fda08fb6fb0810db5fa1c87c13db06c6 | fc7f26912c68faf2934c80fb447907c0e45d8a38 |
refs/heads/master | <file_sep># FuzzyCruiseController
Implementation of Greg Viot’s Fuzzy Cruise Controller using Fuzzy Logic.
## Introduction
Many fuzzy control systems are tasked to keep a certain variable close to a specific value. For instance, the speed of the cruise needs to be kept relatively constant. A fuzzy control system links fuzzy variables using a set of rules. These rules are simply mappings that describe how one or more fuzzy variables relates to another. Using these rules, a system is developed which gives the output corresponding to the set of input values.
## Implementation
The system is implemented in the Python programming language using scikit-fuzzy, which is a fuzzy logic Python package that works with numpy arrays. We create the three fuzzy variables - two inputs, one output (error, delta, output).
<p align="center">
<img src="https://github.com/anushkavirgaonkar/FuzzyCruiseController/blob/master/assets/fig1.png" height="100" width="300">
</p>
We then define the complex set of rules in the fuzzy system.
<p align="center">
<img src="https://github.com/anushkavirgaonkar/FuzzyCruiseController/blob/master/assets/fig2.PNG" height="600" width="500">
</p>
Based on these rules, the fuzzy controller system predicts the output values.
<p align="center">
<img src="https://github.com/anushkavirgaonkar/FuzzyCruiseController/blob/master/assets/fig3.PNG" height="600" width="500">
</p>
With helpful use of Matplotlib and repeated simulations, we can observe what the entire control system surface looks like in three dimensions.
<p align="center">
<img src="https://github.com/anushkavirgaonkar/FuzzyCruiseController/blob/master/assets/fig4.PNG" height="600" width="700">
</p>
<file_sep>import numpy as np
import skfuzzy.control as ctrl
universe = np.linspace(-2, 2, 5)
error = ctrl.Antecedent(universe, 'error')
delta = ctrl.Antecedent(universe, 'delta')
output = ctrl.Consequent(universe, 'output')
names = ['nb', 'ns', 'ze', 'ps', 'pb']
error.automf(names=names)
delta.automf(names=names)
output.automf(names=names)
rule0 = ctrl.Rule(antecedent=((error['nb'] & delta['nb']) |
(error['ns'] & delta['nb']) |
(error['nb'] & delta['ns'])),
consequent=output['nb'], label='rule nb')
rule1 = ctrl.Rule(antecedent=((error['nb'] & delta['ze']) |
(error['nb'] & delta['ps']) |
(error['ns'] & delta['ns']) |
(error['ns'] & delta['ze']) |
(error['ze'] & delta['ns']) |
(error['ze'] & delta['nb']) |
(error['ps'] & delta['nb'])),
consequent=output['ns'], label='rule ns')
rule2 = ctrl.Rule(antecedent=((error['nb'] & delta['pb']) |
(error['ns'] & delta['ps']) |
(error['ze'] & delta['ze']) |
(error['ps'] & delta['ns']) |
(error['pb'] & delta['nb'])),
consequent=output['ze'], label='rule ze')
rule3 = ctrl.Rule(antecedent=((error['ns'] & delta['pb']) |
(error['ze'] & delta['pb']) |
(error['ze'] & delta['ps']) |
(error['ps'] & delta['ps']) |
(error['ps'] & delta['ze']) |
(error['pb'] & delta['ze']) |
(error['pb'] & delta['ns'])),
consequent=output['ps'], label='rule ps')
rule4 = ctrl.Rule(antecedent=((error['ps'] & delta['pb']) |
(error['pb'] & delta['pb']) |
(error['pb'] & delta['ps'])),
consequent=output['pb'], label='rule pb')
system = ctrl.ControlSystem(rules=[rule0, rule1, rule2, rule3, rule4])
sim = ctrl.ControlSystemSimulation(system, flush_after_run=6 * 6 + 1)
upsampled = np.linspace(-2, 2, 6)
x, y = np.meshgrid(upsampled, upsampled)
z = np.zeros_like(x)
print("\tError\t\tDelta\t\tOutput\n")
for i in range(6):
for j in range(6):
sim.input['error'] = x[i, j]
sim.input['delta'] = y[i, j]
sim.compute()
z[i, j] = sim.output['output']
print("\t",'{0:.2f}'.format(x[i,j]),"\t\t",'{0:.2f}'.format(y[i,j]),"\t\t",'{0:.2f}'.format(z[i,j]),"\n")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap='viridis',
linewidth=0.4, antialiased=True)
cset = ax.contourf(x, y, z, zdir='z', offset=-2.5, cmap='viridis', alpha=0.5)
cset = ax.contourf(x, y, z, zdir='x', offset=3, cmap='viridis', alpha=0.5)
cset = ax.contourf(x, y, z, zdir='y', offset=3, cmap='viridis', alpha=0.5)
ax.view_init(30, 200)
plt.show()
| 0f9ed3a47afe665cf3092ab785be1c05ceaa14e7 | [
"Markdown",
"Python"
] | 2 | Markdown | anushkavirgaonkar/FuzzyCruiseController | 9b45f865895a674260e3af96b63f9d48a82630bd | 35ae4f9490604b9c11221d5955ec8bd315f7ed4f |
refs/heads/master | <file_sep>package com.edufabricio.server.route;
import com.edufabricio.server.exception.BadRequestException;
import com.edufabricio.server.exception.ResourceNotFoundException;
import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
import javax.ws.rs.core.Response;
import java.util.Date;
@Component
@Slf4j
public class ApplicationRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
onException(BadRequestException.class).handled(true).process(exchange -> {
Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
Response response = Response.status(400).entity("{\"error\":\"" + caused.getMessage() + "\"}").build();
exchange.getOut().setBody(response);
exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
});
onException(ResourceNotFoundException.class).handled(true).process(exchange -> {
Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
Response r = Response.status(404).entity("{\"error\":\"" + caused.getMessage() + "\"}").build();
exchange.getOut().setBody(r);
exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
});
configureSender();
}
private void configureSender() {
from("cxfrs:bean:sender?bindingStyle=SimpleConsumer")
.recipientList(simple("direct:${header.operationName}"))
.process(exchange -> exchange.getIn()
.removeHeader("Content-Length"));
from("direct:send")
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
String jsonString = (String) exchange.getIn().getBody();
BasicDBObject message = (BasicDBObject) JSON.parse(jsonString);
message.put("dispatchedAt",new Date());
exchange.getIn().setBody(message);
}
})
.to("mongodb3:mongoClientBean?database=eventBus&collection=messages&operation=save");
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.edufabricio</groupId>
<artifactId>camel-mongodb-queue-sender</artifactId>
<version>1.0.RELEASE</version>
<packaging>jar</packaging>
<name>camel-mongodb-queue-sender</name>
<description>Camel MongoDB Queue Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-boot-admin.version>1.5.2</spring-boot-admin.version>
<cxf.version>3.1.12</cxf.version>
<jackson-jaxrs.version>2.8.9</jackson-jaxrs.version>
<hikari-cp.version>2.6.3</hikari-cp.version>
<rest-assured.version>3.0.3</rest-assured.version>
<camel.version>2.19.1</camel.version>
<s4b-service-context>2.0.0.RELEASE</s4b-service-context>
<s4b-security-oauth2.version>1.3.9.RELEASE</s4b-security-oauth2.version>
<s4b-hibernate.version>1.0.3.RELEASE</s4b-hibernate.version>
<lombok.version>1.16.18</lombok.version>
<checkstyle.version>8.0</checkstyle.version>
<checkstyle.plugin.version>2.17</checkstyle.plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-jaxrs.version}</version>
</dependency>
<!-- Spring Boot Admin -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<!-- DB -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${hikari-cp.version}</version>
</dependency>
<!-- CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>${cxf.version}</version>
</dependency>
<!-- Camel -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-mongodb3</artifactId>
<version>${camel.version}</version>
</dependency>
<!-- tests -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>${rest-assured.version}</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- Feign Netflix -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>9.5.0</version>
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-jackson</artifactId>
<version>8.18.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>9.3.1</version>
</dependency>
</dependencies>
</project>
<file_sep>package com.edufabricio.server;
import io.restassured.RestAssured;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc(print = MockMvcPrint.LOG_DEBUG)
@ActiveProfiles({"integration"})
public abstract class BaseIntegrationTest {
@LocalServerPort
private int port;
@Before
public void setup() {
RestAssured.port = port;
}
}
<file_sep>package com.edufabricio.server.jpa;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.*;
import java.util.Date;
import java.util.Set;
/**
* Created by eduardo on 16/07/2017.
*/
@Data
@Entity
@Table(name = "MESSAGE_RECEIVED")
public class MessageReceived {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name = "SEND_AT")
private Date sendAt;
@Column(name = "MESSAGE")
private String message;
}
<file_sep>**Using Camel MongoDB Component**
https://github.com/apache/camel/blob/master/components/camel-mongodb3/src/main/docs/mongodb3-component.adoc
**References**
* https://blog.serverdensity.com/replacing-rabbitmq-with-mongodb/
* https://dzone.com/articles/why-and-how-replace-amazon-sqs
* http://shtylman.com/post/the-tail-of-mongodb/
**Requirements**
Step 1 - Start a mongod on localhost:27017
````
mondod
````
Step 2 - Create a capped collection for events:
````
db.createCollection("messages", { capped : true, size : 5242880, max : 5000 } )
````
**Sender**
Running : on ./sender folder execute:
````
mvn spring-boot:run
````
You can send messages to localhost:38080/sender with body json e.g. {"message":"Text messae for Event"}
It will saved to mongodb messages collection.
**Receiver**
Running : on ./receiver folder execute:
````
mvn spring-boot:run
````
On startup camel will create a taiable cursor for collection message consuming all pending messages and record ir on H2
http://localhost:38081/h2console
````
SELECT * FROM MESSAGE_RECEIVED
````
<file_sep>package com.edufabricio.server.route.utils;
import lombok.experimental.UtilityClass;
import java.util.Iterator;
import java.util.List;
@UtilityClass
public class RouteBuilderUtils {
public static String toString(List<Long> longList) {
StringBuilder sb = new StringBuilder();
Iterator<Long> it = longList.iterator();
while (it.hasNext()) {
sb.append(it.next());
if (it.hasNext()) {
sb.append(",");
}
}
return sb.toString();
}
}
<file_sep>package com.edufabricio.server.exception;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
public BadRequestException(String message, Exception e) {
super(message, e);
}
}
<file_sep>package com.edufabricio.server.service;
import com.edufabricio.server.jpa.MessageReceived;
import com.edufabricio.server.repository.MessageReceivedRepository;
import com.mongodb.BasicDBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class ReceiverService {
@Autowired
private MessageReceivedRepository messageReceivedRepository;
public void receive(BasicDBObject message) {
MessageReceived messageReceived = new MessageReceived();
messageReceived.setMessage(message.getString("message"));
messageReceived.setSendAt(new Date());
messageReceivedRepository.save(messageReceived);
}
}
<file_sep>package com.edufabricio.server.route;
import com.edufabricio.server.exception.BadRequestException;
import com.edufabricio.server.exception.ResourceNotFoundException;
import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
import javax.ws.rs.core.Response;
import java.util.Date;
@Component
@Slf4j
public class ApplicationRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
onException(BadRequestException.class).handled(true).process(exchange -> {
Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
Response response = Response.status(400).entity("{\"error\":\"" + caused.getMessage() + "\"}").build();
exchange.getOut().setBody(response);
exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
});
onException(ResourceNotFoundException.class).handled(true).process(exchange -> {
Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
Response r = Response.status(404).entity("{\"error\":\"" + caused.getMessage() + "\"}").build();
exchange.getOut().setBody(r);
exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
});
configureReceiver();
}
private void configureReceiver() {
from("mongodb3:mongoClientBean?database=eventBus&collection=messages" +
"&tailTrackIncreasingField=dispatchedAt" +
"&persistentId=messagesTracker" +
"&persistentTailTracking=true")
.id("tailableCursorConsumer1")
.autoStartup(true)
.to("bean:receiverService?method=receive");
}
}
<file_sep>package com.edufabricio.config;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MongoClientConfig {
@Bean
public MongoClient mongoClientBean(){
MongoClient mongoClient
= new MongoClient("localhost",27017);
return mongoClient;
}
}
| 71656b2feb0eeb4c3153ffa87a6dfb84eb6778c5 | [
"Markdown",
"Java",
"Maven POM"
] | 10 | Java | dufabricio/camel-mongodb-queue | 2833d5a365aa832e7eb8d348b79c4a5bd410b13e | 0043cb1fcb3a00e4a330af6b9b10d928e3ae81b5 |
refs/heads/master | <repo_name>DamZera/visual_stability<file_sep>/src/sobel.C
#include "tracking.h"
int main(void){
Mat frame,frameOrig, sobel;
namedWindow("MyCam",1);
std::vector<Point> vect;
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
cap.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH); //taille de la fenetre
cap.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT); //au dela de 320*240, image qui lag
while(1){
//frame = imread("../imageTest.jpg", CV_LOAD_IMAGE_COLOR);
if(cap.read(frame)){// get a new frame from camera
frame.copyTo(frameOrig);
cvtColor(frame, frameOrig, CV_BGR2GRAY);
sobel = maskFiltrageSobel(frameOrig);
/*vect = Harris(frame);
for(std::vector<Point>::iterator i = vect.begin(); i != vect.end();++i){
Point &p = *i;
std::cout << p << std::endl;
circle(frame, p, 1, Scalar(0, 255, 0), 1);
}*/
namedWindow( "Display window", WINDOW_AUTOSIZE );
imshow("Display window", sobel);
//imshow("Original",frameOrig);
}
if(waitKey(5) >= 0) break;
}
waitKey(0);
return 0;
}<file_sep>/src/color_calibration.C
#include "color_calibration.h"
void colour_red_detection(Mat& frame,int minX, int minY, int maxX, int maxY, int& xMilieu, int& yMilieu){
double sumR = 0, sumG = 0, sumB = 0, nbpixel = 0;
int minR = 255, minG = 255, minB = 255;
int maxR = 0, maxG = 0, maxB = 0;
xMilieu=0; yMilieu=0;
for (int i=minY;i<maxY;i++){
for (int j=minX;j<maxX;j++){
int b = frame.at<Vec3b>(i,j)[0];
int g = frame.at<Vec3b>(i,j)[1];
int r = frame.at<Vec3b>(i,j)[2];
sumR += r;
sumG += g;
sumB += b;
nbpixel++;
if(r > maxR){
maxR = r;
} else if(r < minR){
minR = r;
}
if(g > maxG){
maxG = g;
} else if(g < minG){
minG = g;
}
if(b > maxB){
maxB = b;
} else if(r < minB){
minB = b;
}
}
}
for (int i=0;i<frame.rows;i++){
for (int j=0;j<frame.cols;j++){
int b = frame.at<Vec3b>(i,j)[0];
int g = frame.at<Vec3b>(i,j)[1];
int r = frame.at<Vec3b>(i,j)[2];
if ( (r > S_RMIN) && (r < S_RMAX) && (g > S_GMIN) && (g < S_GMAX) && (b > S_BMIN) && (b < S_BMAX)){
frame.at<Vec3b>(i,j)[0] = 0;
frame.at<Vec3b>(i,j)[1] = 0;
frame.at<Vec3b>(i,j)[2] = 255;
} else {
frame.at<Vec3b>(i,j)[0] = 0;
frame.at<Vec3b>(i,j)[1] = 0;
frame.at<Vec3b>(i,j)[2] = 0;
}
}
}
std::cout << "R.avg: " << sumR/nbpixel << " G.avg: " << sumG/nbpixel << " B.avg: " << sumB/nbpixel << std::endl;
std::cout << "R.min: " << minR << " R.max: " << maxR << "G.min: " << minG << " G.max: " << maxG << "B.min: " << minB << " B.max: " << maxB << std::endl;
}
int main(int argc, char** argv){
int maxX =0,maxY=0,minX=0,minY=0;
int xMilieu, yMilieu;
int frameMX, frameMY;
int vectX=0, vectY=0;
int yawAngle=Y_D, pitchAngle=P_D;
int taskPeriodValid;
frameMX = WIDTH / 2;
frameMY = HEIGHT / 2;
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat frame,frameOrig;
namedWindow("MyCam",1);
cap.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH); //taille de la fenetre
cap.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT); //au dela de 320*240, image qui lag
while(1){
if(cap.read(frame)){// get a new frame from camera
frame.copyTo(frameOrig);
colour_red_detection(frame,frameMX-20,frameMY-20,frameMX+20,frameMY+20,xMilieu,yMilieu);
rectangle(frame, Point(frameMX-20, frameMY-20), Point(frameMX+20, frameMY+20), Scalar(0, 255, 0));
rectangle(frameOrig, Point(frameMX-20, frameMY-20), Point(frameMX+20, frameMY+20), Scalar(0, 255, 0));
imshow("MyCam", frame);
imshow("Original",frameOrig);
}
if(waitKey(5) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}<file_sep>/src/color_calibration.h
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
#include <sys/time.h>
#define WIDTH 320
#define HEIGHT 240
#define Y_D 90
#define P_D 60
#define TASK_DEADLINE 100000 //100ms
#define TASK_PERIOD 15000 //15ms
#define SEUIL_CENTER 15
#define S_RMIN 75
#define S_RMAX 205
#define S_GMIN 10
#define S_GMAX 50
#define S_BMIN 16
#define S_BMAX 126
#define SEUIL_PIXEL_VIT 50
using namespace cv;
void colour_red_detection(Mat& frame,int minX, int minY, int maxX, int maxY, int& xMilieu, int& yMilieu);<file_sep>/arduino/test_servo/test_servo.ino
#include <Servo.h>
Servo servYaw;
Servo servPitch;
char buff[40];
int yaw = -1;
int pitch = -1;
int i = 0;
char car;
void setup() {
Serial.begin(9600);
//servYaw.attach(3);
//servPitch.attach(5);
}
void readSerialToServos(){
while(Serial.available() > 0){
car = Serial.read();
if(car != '+'){
buff[i] = car;
buff[i+1] = '\0';
i++;
} else{
sscanf(buff, "Y:%d:P:%d", &yaw, &pitch);
//Serial.print("'");
//Serial.print(buff);
//Serial.println("'");
i=0;
}
}
}
void loop() {
readSerialToServos();
if(yaw != -1 || pitch != -1){
Serial.print("Yaw:");
Serial.print(yaw);
Serial.print("Pitch:");
Serial.println(pitch);
servYaw.write(yaw);
servPitch.write(pitch);
}
yaw=-1;pitch=-1;
}
<file_sep>/src/color_tracking.h
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
#include <sys/time.h>
#include "serial.h"
#define WIDTH 320
#define HEIGHT 240
#define Y_D 90
#define P_D 60
#define TASK_DEADLINE 100000 //100ms
#define TASK_PERIOD 15000 //15ms
#define SEUIL_CENTER 15
#define S_RMIN 75
#define S_RMAX 205
#define S_GMIN 10
#define S_GMAX 50
#define S_BMIN 16
#define S_BMAX 126
#define SEUIL_PIXEL_VIT 50
using namespace cv;
struct timeval start, checkpoint;
int taskPeriodCheck();
void processYawPitchAngles(int vectY, int vectX, int& yawAngle, int& pitchAngle);
void colour_red_detection(Mat& frame,int& minX, int& minY, int& maxX, int& maxY, int& xMilieu, int& yMilieu);
<file_sep>/src/tracking.h
#include <opencv2/opencv.hpp>
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <sys/time.h>
#define TASK_DEADLINE 100000 //100ms
#define TASK_PERIOD 15000 //15ms
#define ALPHA 0.1
#define SEUIL 2000
#define WIDTH 320
#define HEIGHT 240
#define PI 3.14159265
using namespace cv;
Mat maskFiltrageSobel(Mat& frame);
Mat Harris (Mat& grey);
bool compare (int i,int j);
int taskPeriodCheck();
struct timeval start, checkpoint;
double harris[HEIGHT][WIDTH];
double gauss[5][5] = {
0.00390625, 0.015625, 0.0234375, 0.015625, 0.00390625,
0.015625, 0.0625, 0.09375, 0.0625, 0.015625,
0.0234375, 0.09375, 0.140625, 0.09375, 0.0234375,
0.015625, 0.0625, 0.09375, 0.0625, 0.015625,
0.00390625, 0.015625, 0.0234375, 0.015625, 0.00390625,
};<file_sep>/src/tSerial.c
#include "serial.h"
int servAngle(serial_com *sp, int angleY, int angleP){
char *buffer = new char[20];
int test;
sprintf(buffer, "Y:%d:P:%d+", angleY, angleP);
test = serial_write(sp, buffer);
#ifdef SERIALPORTDEBUG
printf("Write: %d // %s\n", test, buffer);
#endif
return test;
}
int main(void){
serial_com sp;
char *buffer = new char[80];
int test;
serial_open(&sp, "/dev/cu.usbmodem1411");
printf("Fic : %d\n", sp.fd);
sleep(1);
for(int i=45; i<120; i++){
servAngle(&sp, i, i);
usleep(15000);
}
serial_close(&sp);
}<file_sep>/arduino/Visual_stability/Visual_stability.ino
#include <Servo.h>
Servo servYaw;
Servo servPitch;
char buff[40];
int yaw;
int pitch;
int i = 0;
char car;
void setup() {
Serial.begin(9600);
servYaw.attach(5);
servPitch.attach(3);
pitch=60;yaw=90;
}
void readSerialToServos(){
while(Serial.available() > 0){
car = Serial.read();
if(car != '+'){
buff[i] = car;
buff[i+1] = '\0';
i++;
} else{
sscanf(buff, "Y:%d:P:%d", &yaw, &pitch);
i=0;
}
}
}
void loop() {
readSerialToServos();
servYaw.write(yaw);
servPitch.write(pitch);
}
<file_sep>/src/tCamColor.C
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
using namespace cv;
int main(int, char**){
int maxX =0,maxY=0,minX=0,minY=0;
int xMilieu,yMilieu;
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat frame,frameOrig;
namedWindow("MyCam",1);
cap.set(CV_CAP_PROP_FRAME_WIDTH,320); //taille de la fenetre
cap.set(CV_CAP_PROP_FRAME_HEIGHT,240); //au dela de 320*240, image qui lag
//MatIterator_<Vec3b> it, end;
while(1){
if(cap.read(frame)){// get a new frame from camera
frame.copyTo(frameOrig);
for (int i=0;i<frame.rows;i++){
for (int j=0;j<frame.cols;j++){
int b = frame.at<Vec3b>(i,j)[0];
int g = frame.at<Vec3b>(i,j)[1];
int r = frame.at<Vec3b>(i,j)[2];
if ( (r > 150) && ((g+b) < 150)){
frame.at<Vec3b>(i,j)[0] = 0;
frame.at<Vec3b>(i,j)[1] = 0;
frame.at<Vec3b>(i,j)[2] = 255;
if (i<minX) minX=i;
if (j<minY) minY=j;
if (i>maxX) maxX=i;
if(j>maxY) maxY=j;
} else {
frame.at<Vec3b>(i,j)[0] = 0;
frame.at<Vec3b>(i,j)[1] = 0;
frame.at<Vec3b>(i,j)[2] = 0;
}
}
}
xMilieu=(minX+maxX)/2;
yMilieu=(minY+maxY)/2;
frame.at<Vec3b>(xMilieu,yMilieu)[0] = 255;
//std::cout << xMilieu;
//std::cout << yMilieu;
maxX =0;maxY=0;minX=20000;minY=20000;
imshow("MyCam", frame);
imshow("Original",frameOrig);
}
if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
<file_sep>/src/colour_detection.C
#include "colour_detection.h"
using namespace cv;
void colour_red_detection(Mat& frame,int& minX, int& minY, int& maxX, int& maxY){
for (int i=0;i<frame.rows;i++){
for (int j=0;j<frame.cols;j++){
if ( (r > 150) && ((g+b) < 150)){
frame.at<Vec3b>(i,j)[0] = 0;
frame.at<Vec3b>(i,j)[1] = 0;
frame.at<Vec3b>(i,j)[2] = 255;
if (j<minX) minX=j;
if (i<minY) minY=i;
if (j>maxX) maxX=j;
if(i>maxY) maxY=i;
} else {
frame.at<Vec3b>(i,j)[0] = 0;
frame.at<Vec3b>(i,j)[1] = 0;
frame.at<Vec3b>(i,j)[2] = 0;
}
}
}
}
<file_sep>/src/cap_test.C
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
#include <sys/time.h>
#include "colour_detection.h"
#include "serial.h"
#define WIDTH 320
#define HEIGHT 240
#define Y_D 90
#define P_D 60
using namespace cv;
#define TASK_DEADLINE 100000 //100ms
#define TASK_PERIOD 15000 //10ms
#define SEUIL_CENTER 15
struct timeval start, checkpoint;
int taskPeriodCheck(){
int taskPeriodValid;
long diff;
gettimeofday(&checkpoint, 0);
diff=(checkpoint.tv_sec-start.tv_sec) * 1000000L + (checkpoint.tv_usec-start.tv_usec);
/* calcul de la difference */
if (diff < TASK_PERIOD ) taskPeriodValid = 0;
else {
gettimeofday(&start, 0); // reinitialisation du temps initial
if (diff > TASK_PERIOD + TASK_DEADLINE){
fprintf (stderr,"***echeance manquée %ld \n", diff);
taskPeriodValid = 0;
} else {
taskPeriodValid = 1;
}
}
return taskPeriodValid;
}
int main(int, char**){
int maxX =0,maxY=0,minX=0,minY=0;
int xMilieu,yMilieu;
int frameMX, frameMY;
int vectX=0, vectY=0;
int yawAngle=Y_D, pitchAngle=P_D;
int taskPeriodValid;
serial_com sp;
frameMX = WIDTH / 2;
frameMY = HEIGHT / 2;
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat frame,frameOrig;
namedWindow("MyCam",1);
serial_open(&sp, "/dev/cu.usbmodem1421");
//sleep(1);
cap.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH); //taille de la fenetre
cap.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT); //au dela de 320*240, image qui lag
//MatIterator_<Vec3b> it, end;
gettimeofday(&start, 0);
while(1){
if(cap.read(frame)){// get a new frame from camera
frame.copyTo(frameOrig);
colour_red_detection(frame,minX,minY,maxX,maxY);
if(minX != 20000 | minY != 20000 | maxX != 0 | maxY !=0){
xMilieu=(minX+maxX)/2;
yMilieu=(minY+maxY)/2;
frame.at<Vec3b>(xMilieu,yMilieu)[0] = 255;
circle(frame, Point(xMilieu, yMilieu), 8, Scalar(0, 255, 0), 2);
//rectangle(frame, Point(minX, minY), Point(maxX, maxY), Scalar(0, 255, 0));
vectX = xMilieu-frameMX;
vectY = yMilieu-frameMY;
taskPeriodValid = taskPeriodCheck();
if(taskPeriodValid){
if(vectY<-SEUIL_CENTER && vectX<-SEUIL_CENTER){
yawAngle--;pitchAngle++;
} else if(vectY>SEUIL_CENTER && vectX>SEUIL_CENTER){
yawAngle++;pitchAngle--;
} else if(-SEUIL_CENTER<vectY && vectY<SEUIL_CENTER && vectX<-SEUIL_CENTER){
yawAngle--;
} else if(-SEUIL_CENTER<vectY && vectY<SEUIL_CENTER && vectX>SEUIL_CENTER){
yawAngle++;
} else if(-SEUIL_CENTER<vectX && vectX<SEUIL_CENTER && vectY<-SEUIL_CENTER){
pitchAngle++;
} else if(-SEUIL_CENTER<vectX && vectX<SEUIL_CENTER && vectY>SEUIL_CENTER){
pitchAngle--;
} else if(vectY>SEUIL_CENTER && vectX<-SEUIL_CENTER){
yawAngle--;pitchAngle--;
} else if(vectY<-SEUIL_CENTER && vectX>SEUIL_CENTER){
yawAngle++;pitchAngle++;
}
servAngle(&sp, yawAngle, pitchAngle);
}
std::cout << vectX << " : " << vectY << std::endl;
std::cout << yawAngle << " : " << pitchAngle << std::endl;
}
maxX =0;maxY=0;minX=20000;minY=20000;
imshow("MyCam", frame);
imshow("Original",frameOrig);
}
if(waitKey(5) >= 0) break;
}
serial_close(&sp);
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
<file_sep>/src/Makefile
all: color_tracking color_calibration
color_tracking: color_tracking.o serial.o
g++ color_tracking.o serial.o -o color_tracking -lopencv_core -lopencv_highgui -lopencv_imgproc
color_tracking.o: serial.C color_tracking.C
g++ color_tracking.C serial.C -c
color_calibration: color_calibration.o
g++ color_calibration.o -o color_calibration -lopencv_core -lopencv_highgui -lopencv_imgproc
color_calibration.o: color_calibration.C
g++ color_calibration.C -c
serial.o: serial.C
g++ serial.C -c
clean:
rm *.o
mrproper:
rm color_calibration
rm color_tracking
rm *.o
<file_sep>/src/serial.h
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct serial_com{
char nom_port[100];
int fd;
}serial_com;
int serial_open(serial_com *sp, char *name);
void serial_close(serial_com* sp);
int serial_write(serial_com* sp, char* buff);
int serial_read(serial_com* sp, char* buf, char until, int buf_max, int timeout);
int servAngle(serial_com *sp, int angleY, int angleP);<file_sep>/src/tracking.C
#include "tracking.h"
int taskPeriodCheck(){
int taskPeriodValid;
long diff;
gettimeofday(&checkpoint, 0);
diff=(checkpoint.tv_sec-start.tv_sec) * 1000000L + (checkpoint.tv_usec-start.tv_usec);
/* calcul de la difference */
if (diff < TASK_PERIOD ) taskPeriodValid = 0;
else {
gettimeofday(&start, 0); // reinitialisation du temps initial
if (diff > TASK_PERIOD + TASK_DEADLINE){
fprintf (stderr,"***echeance manquée %ld \n", diff);
taskPeriodValid = 0;
} else {
taskPeriodValid = 1;
}
}
return taskPeriodValid;
}
Mat maskFiltrageSobel(Mat& grey){
long sumY, sumX;
long gradX, gradY, tmp;
Mat greyMat(grey.rows, grey.cols, CV_8UC1);
//cvtColor(frame, grey, CV_BGR2GRAY);
for (int i=1;i<grey.rows-1;i++){
for (int j=1;j<grey.cols-1;j++){
gradX = (-1 * grey.at<uchar>(i-1,j-1)) + grey.at<uchar>(i-1,j+1)
+ (-2 * grey.at<uchar>(i,j-1)) + (2 * grey.at<uchar>(i,j+1))
+ (-1 * grey.at<uchar>(i+1,j-1)) + grey.at<uchar>(i+1,j+1);
gradY = (-1 * grey.at<uchar>(i-1,j-1)) + grey.at<uchar>(i+1,j-1)
+ (-2 * grey.at<uchar>(i-1,j)) + (2 * grey.at<uchar>(i+1,j))
+ (-1 * grey.at<uchar>(i-1,j+1)) + grey.at<uchar>(i+1,j+1);
tmp=sqrt((gradX*gradX) + (gradY*gradY));
greyMat.at<uchar>(i, j)=(fabs(tmp)/1020)*255;
}
}
return greyMat;
}
double distance(double xA, double yA, double xB, double yB){
return sqrt(pow(xB-xA,2)+pow(yB-yA,2));
}
Mat Harris (Mat& grey, Mat& frame, std::vector<Point>& vectBefore, std::vector<Point>& vectAfter){
double sumY, sumX, dX, dY;
double sumIX,sumIY,sumIXIY;
Mat IX(grey.rows, grey.cols, CV_8UC1);
Mat IY(grey.rows, grey.cols, CV_8UC1);
Mat IXIY(grey.rows, grey.cols, CV_8UC1);
Mat test(grey.rows, grey.cols, CV_8UC1);
std::vector<Point3d> vect_harris;
int accu[100][360]={0};
for (int i=0;i<grey.rows-5;i++){
for (int j=0;j<grey.cols-5;j++){
double a = 0;
double b = 0;
double c = 0;
// Calcul de dérivées avec le grandient Sobel
sumX = (-1 * grey.at<uchar>(i-1,j-1)) + grey.at<uchar>(i-1,j+1)
+ (-2 * grey.at<uchar>(i,j-1)) + (2 * grey.at<uchar>(i,j+1))
+ (-1 * grey.at<uchar>(i+1,j-1)) + grey.at<uchar>(i+1,j+1);
dX=(std::abs(sumX)/1020)*255;
sumY = (-1 * grey.at<uchar>(i-1,j-1)) + grey.at<uchar>(i+1,j-1)
+ (-2 * grey.at<uchar>(i-1,j)) + (2 * grey.at<uchar>(i+1,j))
+ (-1 * grey.at<uchar>(i-1,j+1)) + grey.at<uchar>(i+1,j+1);
dY=(std::abs(sumY)/1020)*255;
IX.at<uchar>(i,j) = (uchar)(dX*dX);
IY.at<uchar>(i,j) = (uchar)(dY*dY);
IXIY.at<uchar>(i,j) = (uchar)(dX*dY);
// Convolution avec gaussienne
for (int x = 0; x < 5; x++){
for (int y = 0; y < 5; y++){
a += IX.at<uchar>(i + y, j + x) * gauss[x][y];
b += IY.at<uchar>(i + y, j + x) * gauss[x][y];
c += IXIY.at<uchar>(i + y, j + x) * gauss[x][y];
}
}
//lambda entre 0.04 et 0.06
double responce = (a * b) - c - (ALPHA * (a + b) * (a + b));
//entre 104 et 107
// 1000 tres bon seuil
if(responce > SEUIL){
harris[i][j] = responce;
//vect_harris.push_back(Point3d(i,j,responce));
//circle(frame, Point(j,i), 1, Scalar(0, 255, 0), 1);
}else{
harris[i][j] = 0;
}
}
}
/*std::sort(vect_harris.begin(), vect_harris.end(), [](Point3d const & a, Point3d const & b) { return a.z > b.z; });
int count = 0;
for(std::vector<Point3d>::iterator i = vect_harris.begin(); i != vect_harris.end();++i){
if(count<30)circle(frame, Point((*i).x,(*i).y), 1, Scalar(0, 255, 0), 1);
else break;
count++;
}*/
// Calculer la force de coin pour chaque pixel
for (int i=0;i<grey.rows-14;i+=15){
for (int j=0;j<grey.cols-14;j+=15){
double tmp;
double max=0;
int xM = 0, yM = 0;
for (int x=0;x<15;x++){
for (int y=0;y<15;y++){
tmp = harris[y+i][x+j];
if(tmp>max){
max=tmp;
yM = y+i; xM = x+j;
}
}
}
if(harris[i][j]>0){
//vectAfter.push_back(Point(xM,yM));
circle(frame, Point(xM,yM), 1, Scalar(0, 255, 0), 1);
/*if(!vectBefore.empty()){
double tmp, min=1000000000000000;
int minX, minY;
for(std::vector<Point>::iterator i = vectBefore.begin(); i != vectBefore.end();++i){
tmp = distance(xM,yM,(*i).x, (*i).y);
if(tmp<min){
min = tmp;
minX = (*i).x;
minY = (*i).y;
}
//std::cout << (*i).x << " : " << (*i).y << std::endl;
}
int ang;
if (min==0) ang = 0;
else ang = acos ((minX-xM)/min) * 180.0 / PI;
//std::cout <<min <<":"<< minX <<":"<< xM << ":" << ang << std::endl;
if (min<100) accu[(int)min][ang]++;
//line(frame, Point(xM,yM), Point(minX, minY), Scalar(255, 0, 0));
}*/
}
}
}
/*int best = 0;
int bestDist, bestAng;
for(int i=0; i<100; i++){
for(int j=0; j<360; j++){
int tmp = accu[i][j];
if(tmp>best){
best = tmp;
bestDist = i;
bestAng = j;
}
}
}*/
//line(frame, Point(0, 0), Point(bestDist*cos(bestAng), bestDist*sin(bestAng)), Scalar(255, 0, 0));
//vectBefore.swap(vectAfter);
//vectAfter.clear();
return grey;
}
int main(void){
Mat frame,frameOrig, sobel;
namedWindow("MyCam",1);
std::vector<Point> vectBefore;
std::vector<Point> vectAfter;
VideoCapture cap(0); // open the default camera
int taskPeriodValid;
if(!cap.isOpened()) // check if we succeeded
return -1;
cap.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH); //taille de la fenetre
cap.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT); //au dela de 320*240, image qui lag
gettimeofday(&start, 0);
while(1){
if(cap.read(frame)){// get a new frame from camera
frame.copyTo(frameOrig);
cvtColor(frame, frameOrig, CV_BGR2GRAY);
taskPeriodValid = taskPeriodCheck();
if(taskPeriodValid){
frameOrig = Harris(frameOrig, frame, vectBefore, vectAfter);
imshow("Original",frameOrig);
}
/*for(std::vector<Point>::iterator i = vect.begin(); i != vect.end();++i){
Point &p = *i;
circle(frame, p, 1, Scalar(0, 255, 0), 1);
}*/
namedWindow( "Display window", WINDOW_AUTOSIZE );
imshow("Display window", frame);
//imshow("Original",frameOrig);
}
if(waitKey(0) >= 0) break;
//waitKey(0);
}
return 0;
}<file_sep>/src/color_tracking.C
#include "color_tracking.h"
int taskPeriodCheck(){
int taskPeriodValid;
long diff;
gettimeofday(&checkpoint, 0);
diff=(checkpoint.tv_sec-start.tv_sec) * 1000000L + (checkpoint.tv_usec-start.tv_usec);
/* calcul de la difference */
if (diff < TASK_PERIOD ) taskPeriodValid = 0;
else {
gettimeofday(&start, 0); // reinitialisation du temps initial
if (diff > TASK_PERIOD + TASK_DEADLINE){
fprintf (stderr,"***echeance manquée %ld \n", diff);
taskPeriodValid = 0;
} else {
taskPeriodValid = 1;
}
}
return taskPeriodValid;
}
void processYawPitchAngles(int vectY, int vectX, int& yawAngle, int& pitchAngle){
int valToaddX = 0, valToaddY = 0;
valToaddX = abs(vectX / SEUIL_PIXEL_VIT);
valToaddY = abs(vectY / SEUIL_PIXEL_VIT);
//std::cout << "vx: " << valToaddX << " vy: " << valToaddY << std::endl;
if(vectY<-SEUIL_CENTER && vectX<-SEUIL_CENTER){
yawAngle-=valToaddX;pitchAngle-=valToaddY;
} else if(vectY>SEUIL_CENTER && vectX>SEUIL_CENTER){
yawAngle+=valToaddX;pitchAngle+=valToaddY;
} else if(-SEUIL_CENTER<vectY && vectY<SEUIL_CENTER && vectX<-SEUIL_CENTER){
yawAngle-=valToaddX;
} else if(-SEUIL_CENTER<vectY && vectY<SEUIL_CENTER && vectX>SEUIL_CENTER){
yawAngle+=valToaddX;
} else if(-SEUIL_CENTER<vectX && vectX<SEUIL_CENTER && vectY<-SEUIL_CENTER){
pitchAngle-=valToaddY;
} else if(-SEUIL_CENTER<vectX && vectX<SEUIL_CENTER && vectY>SEUIL_CENTER){
pitchAngle+=valToaddY;
} else if(vectY>SEUIL_CENTER && vectX<-SEUIL_CENTER){
yawAngle-=valToaddX;pitchAngle+=valToaddY;
} else if(vectY<-SEUIL_CENTER && vectX>SEUIL_CENTER){
yawAngle+=valToaddX;pitchAngle-=valToaddY;
}
if(yawAngle>180)
yawAngle = 180;
else if(yawAngle<0)
yawAngle = 0;
if(pitchAngle>180)
pitchAngle = 180;
else if(pitchAngle<0)
pitchAngle = 0;
}
void colour_red_detection(Mat& frame,int& minX, int& minY, int& maxX, int& maxY, int& xMilieu, int& yMilieu){
double sumX = 0, sumY = 0, nbpixel = 0;
xMilieu=0; yMilieu=0;
for (int i=0;i<frame.rows;i++){
for (int j=0;j<frame.cols;j++){
int b = frame.at<Vec3b>(i,j)[0];
int g = frame.at<Vec3b>(i,j)[1];
int r = frame.at<Vec3b>(i,j)[2];
if ( (r > S_RMIN) && (r < S_RMAX) && (g > S_GMIN) && (g < S_GMAX) && (b > S_BMIN) && (b < S_BMAX)){
frame.at<Vec3b>(i,j)[0] = 0;
frame.at<Vec3b>(i,j)[1] = 0;
frame.at<Vec3b>(i,j)[2] = 255;
sumX+=j;
sumY+=i;
nbpixel++;
} else {
frame.at<Vec3b>(i,j)[0] = 0;
frame.at<Vec3b>(i,j)[1] = 0;
frame.at<Vec3b>(i,j)[2] = 0;
}
}
}
if(nbpixel != 0){
xMilieu=round(sumX/nbpixel);
yMilieu=round(sumY/nbpixel);
}
//std::cout << "xM: " << xMilieu << " yM: " << yMilieu << " nb: " << nbpixel << std::endl;
}
int main(int argc, char** argv){
int maxX =0,maxY=0,minX=0,minY=0;
int xMilieu, yMilieu;
int frameMX, frameMY;
int vectX=0, vectY=0;
int yawAngle=Y_D, pitchAngle=P_D;
int taskPeriodValid;
serial_com sp;
frameMX = WIDTH / 2;
frameMY = HEIGHT / 2;
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat frame,frameOrig;
namedWindow("MyCam",1);
serial_open(&sp, argv[1]);
//sleep(1);
cap.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH); //taille de la fenetre
cap.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT); //au dela de 320*240, image qui lag
//MatIterator_<Vec3b> it, end;
gettimeofday(&start, 0);
while(1){
if(cap.read(frame)){// get a new frame from camera
frame.copyTo(frameOrig);
colour_red_detection(frame,minX,minY,maxX,maxY,xMilieu,yMilieu);
//if(minX != 20000 | minY != 20000 | maxX != 0 | maxY !=0){
if(xMilieu != 0 && yMilieu != 0){
/*xMilieu=(minX+maxX)/2;
yMilieu=(minY+maxY)/2;
frame.at<Vec3b>(xMilieu,yMilieu)[0] = 255;*/
circle(frame, Point(xMilieu, yMilieu), 8, Scalar(0, 255, 0), 2);
//rectangle(frame, Point(minX, minY), Point(maxX, maxY), Scalar(0, 255, 0));
vectX = xMilieu-frameMX;
vectY = yMilieu-frameMY;
taskPeriodValid = taskPeriodCheck();
if(taskPeriodValid){
processYawPitchAngles(vectY, vectX, yawAngle, pitchAngle);
servAngle(&sp, yawAngle, pitchAngle);
}
}
maxX =0;maxY=0;minX=20000;minY=20000;
imshow("MyCam", frame);
imshow("Original",frameOrig);
}
if(waitKey(5) >= 0) break;
}
serial_close(&sp);
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}<file_sep>/src/serial.C
#include "serial.h"
//#define SERIALPORTDEBUG
struct termios toptions;
int serial_open(serial_com *sp, char* name){
strcpy(sp->nom_port, name);
//int fd = open(sp->nom_port, O_RDWR | O_NOCTTY | O_NDELAY);
int fd = open(sp->nom_port, O_RDWR | O_NONBLOCK );
sp->fd = fd;
if(fd == -1){
perror("open :: ");
}
usleep(300000);
tcgetattr(sp->fd, &toptions);
/*---- CONFIGURATION 9600 8N1 ----*/
cfsetispeed(&toptions, (speed_t)B9600);
cfsetospeed(&toptions, (speed_t)B9600);
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
toptions.c_cflag &= ~CRTSCTS;
toptions.c_cflag |= CLOCAL | CREAD;
toptions.c_iflag |= IGNPAR | IGNCR;
toptions.c_iflag &= ~(IXON | IXOFF | IXANY);
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
toptions.c_oflag &= ~OPOST;
toptions.c_cc[VMIN] = 0;
toptions.c_cc[VTIME] = 0;
tcsetattr(sp->fd, TCSANOW, &toptions);
if( tcsetattr(sp->fd, TCSAFLUSH, &toptions) <0){
perror("init_serialport: Couldn't set term attribues");
return -1;
}
return fd;
}
void serial_close(serial_com* sp){
close(sp->fd);
}
int serial_write(serial_com* sp, char* buff){
int len = strlen(buff);
int test = write(sp->fd, buff, len);
if(test != len)
printf("serialport_write: couldn't write whole string\n");
return test;
}
int serial_read(serial_com* sp, char* buf, char until, int buf_max, int timeout){
char b[1];
int i=0;
do {
int n = read(sp->fd, b, 1);
if( n==-1) return -1;
if( n==0 ) {
usleep( 1 * 1000 );
timeout--;
if( timeout==0 ) return -2;
continue;
}
#ifdef SERIALPORTDEBUG
printf("serialport_read_until: i=%d, n=%d b='%c'\n",i,n,b[0]);
#endif
buf[i] = b[0];
i++;
} while( b[0] != until && i < buf_max && timeout>0 );
buf[i] = 0;
return 0;
}
int servAngle(serial_com *sp, int angleY, int angleP){
char *buffer = new char[20];
int test;
sprintf(buffer, "Y:%d:P:%d+", angleY, angleP);
test = serial_write(sp, buffer);
#ifdef SERIALPORTDEBUG
printf("Write: %d // %s\n", test, buffer);
#endif
return test;
}
| 62874e61059cb9af4c47f782c7063302d0165985 | [
"C",
"Makefile",
"C++"
] | 16 | C | DamZera/visual_stability | ff54be2b7d32a64ebef2fb85a7fa42849a5a4331 | 62153732323e9471cb04c612a75b38056d9dc5fe |
refs/heads/master | <repo_name>Skowryk/thehangman<file_sep>/src/routes/Home/components/HomeView.js
import React from 'react'
import GuessedWord from './GuessedWord'
import MissedLetters from './MissedLetters'
import Hangman from './Hangman'
import './HomeView.scss'
const WIN = 2
const LOSE = 1
export class HomeView extends React.Component {
constructor () {
super()
this.state = {
gameState: 0,
word: null,
missedLetters: [],
guessedLetters: [],
wordLength: 11
}
this.checkEnteredKey = this.checkEnteredKey.bind(this)
this.startNewGame = this.startNewGame.bind(this)
this.checkWin = this.checkWin.bind(this)
}
componentDidMount () {
this.startNewGame()
}
componentWillUpdate (nextProps, nextState) {
if (nextState.missedLetters.length >= 11 && nextState.gameState === 0) {
this.gameOver(LOSE)
}
if (nextState.word && nextState.word !== this.state.word) {
window.addEventListener('keypress', this.checkEnteredKey, true)
}
}
componentDidUpdate () {
if (!this.state.gameState) {
this.checkWin()
}
}
componentWillUnmount () {
window.removeEventListener('keypress', this.checkEnteredKey, true)
}
render () {
const { word, missedLetters, guessedLetters, wordLength, gameState } = this.state
if (word !== null) {
return (
<div className='wrapper'>
{gameState !== 0 &&
<div className='game-over'>
<div>
<p>{gameState === LOSE ? 'Game over' : 'Congrats! You won!'}</p>
<p><span onClick={this.startNewGame}>New Word</span></p>
</div>
</div>
}
<div className='game'>
<MissedLetters letters={missedLetters} />
<Hangman step={missedLetters.length} />
<GuessedWord guessedLetters={guessedLetters} word={word} maxLength={wordLength} />
</div>
</div>
)
}
return (<div />)
}
startNewGame () {
this.setState({ gameState: 0, guessedLetters: [], missedLetters: [] })
this.fetchWord()
}
checkWin () {
if (this.state.word) {
let win = true
const wordArray = this.state.word.split('')
for (let i = 0; i < wordArray.length; i++) {
if (!this.state.guessedLetters.includes(wordArray[i])) {
win = false
}
}
if (win) {
this.gameOver(WIN)
}
}
}
gameOver (state) {
window.removeEventListener('keypress', this.checkEnteredKey, true)
this.setState({ gameState: state })
}
checkEnteredKey (key) {
if ((key.keyCode >= 97 && key.keyCode <= 122) || key.keyCode === 32 || key.keyCode === 45) {
if (!this.state.word.includes(key.key) && !this.state.missedLetters.includes(key.key)) {
this.setState({ missedLetters: [...this.state.missedLetters, key.key] })
} else if (this.state.word.includes(key.key) && !this.state.guessedLetters.includes(key.key)) {
this.setState({ guessedLetters: [...this.state.guessedLetters, key.key] })
}
}
}
fetchWord () {
const url = 'http://api.wordnik.com:80/v4/words.json/randomWord?hasDictionaryDef=false&minCorpusCount=0&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=5&maxLength=' + this.state.wordLength + '&api_key=<KEY>'
fetch(url)
.then(res => res.json())
.then((resp) => {
this.setState({ word: resp.word })
})
}
}
export default HomeView
| 99fe23066e1c0d503292ce44a3bccaa9e26640d9 | [
"JavaScript"
] | 1 | JavaScript | Skowryk/thehangman | 1c78df5ad2e3b60ab0afdc2f4b70efc2f73bf472 | 90bd4454031cdc9c1638eaf9adf62685f1c32443 |
refs/heads/master | <file_sep>启动项目
### `yarn start`
打包项目
### `yarn build`
# 改项目为四种数据管理
简化stort操作的方法
### 1 stort hooks
## useSelector 获取数据
## useDispatch 修改数据方法
传递的数据比较简单时
### 2 context
## createContext 创建context 并export
## <Context.Provider value={{n, setN}}> 初始化value 中的两个数据为useState 创建
## 引入Context 并 const {n, setN} = useContext(Context) 可直接使用
单页面数据管理
### 3 hooks state
父子组件传地方法
### 4 useReducer
## 父组件 const [reducerState, dispatch] = useReducer(reducer, initialState)
## <Child dispatch={dispatch} /> 传递
## 子组件 props.dispatch()
<file_sep>/* eslint-disable react/prop-types */
import React, {useState,useEffect, useContext, useReducer} from "react";
import { useSelector} from "react-redux";
import "./App.css";
import { Context } from "./App";
import Child from "./Child";
const initialState = {
n: 0
};
const reducer = (state, action) => {
switch(action.type){
case "addOne":
return { n: state.n + 1 };
case "addTwo":
return { n: state.n + 2 };
case "addX":
return { n: state.n + action.x };
default: {
throw new Error("unknown type");
}
}
};
function Detail(props) {
const [reducerState, dispatch] = useReducer(reducer, initialState);
const {n, setN} = useContext(Context);
console.log(n);
let [state, setStste] = useState({num: 0}); // hooks数据管理
useEffect(() => {
console.log("这里是变化以后的弹窗!");
} , [state.num]);
const counter = useSelector(state => state.counter);
return (
<div className="App" >
<div> 这个是stort的值 {counter}</div>
<hr/>
<div>这个是context的值 { n }</div>
<button onClick={() => { setN(1);}}> 修改context值 </button>
<hr />
<div> {state.num} </div>
<button onClick={() => { state.num = 5 ; setStste({...state}); }}> 改变state值 </button>
<hr />
<div> {reducerState.n} </div>
<button onClick={()=>dispatch({type: "addOne"})}> 改变useReducer值 </button>
<hr />
<Child dispatch={dispatch} />
<hr />
<button onClick={() => { props.history.push("/"); }}> 回去 </button>
</div>
);
}
export default Detail;
<file_sep>import React, { useState, createContext } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Home from "./Home";
import Detail from "./Detail";
import "./App.css";
export const Context = createContext(null); // context 全局数据管理
function App() {
const [n, setN] = useState(0);
return <BrowserRouter>
<Context.Provider value={{n, setN}}>
<React.Suspense fallback={"正在加载中..."}>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/home" component={Home} />
<Route exact path="/detail" component={Detail} />
</Switch>
</React.Suspense>
</Context.Provider>
</BrowserRouter>;
}
export default App;
<file_sep>/* eslint-disable react/prop-types */
import React, {useContext} from "react";
import { useSelector, useDispatch } from "react-redux";
import "./App.css";
import { Context } from "./App";
function Home(props) {
const {n, setN} = useContext(Context);
const dispatch = useDispatch(); //stort hooks最新数据管理
const counter = useSelector(state => state.counter);
return (
<div className="App">
<div>这个是stort的值 {counter}</div>
<button onClick={() => { dispatch({ type: "INCREMENT" }); }}> 修改stort值 </button>
<hr />
<div>这个是context的值 { n }</div>
<button onClick={() => { setN(10);}}> 修改context值 </button>
<hr />
<button onClick={() => { props.history.push("/detail"); }}> 跳转 </button>
</div>
);
}
export default Home;
<file_sep>/* eslint-disable react/prop-types */
import React from "react";
import "./App.css";
function Child(props) {
return (
<div className="App">
<h2> 这就是子元素 </h2>
<button onClick={()=>props.dispatch({type: "addTwo"})}> 子元素变useReducer值 </button>
</div>
);
}
export default Child;
| b4393df0d42d6b758190fa3f9d1af02a823ca050 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | Ray1314/react-hooks | ed4fa3cb43d1017d9b9f93b8e65eeef4bb2d87be | ca01709e23ad968f5f2474bc8e68db2e48a7dc18 |
refs/heads/master | <file_sep>'use babel';
export default {
config: {
terraformExecutablePath: {
title: 'Terraform Executable Path',
type: 'string',
description: 'Path to Terraform executable (e.g. /usr/local/bin/terraform) if not in shell env path.',
default: 'terraform',
order: 1,
},
blacklist: {
title: 'Exclude Regexp for .tf',
type: 'string',
description: 'Regular expression for Terraform filenames to ignore (e.g. foo|[bB]ar would ignore afoo.tf and theBar.tf).',
default: '',
},
timeout: {
title: 'Linting Timeout',
type: 'number',
description: 'Number of seconds to wait on lint attempt before timing out.',
default: 10,
},
format: {
title: 'Auto Formatting',
type: 'object',
properties: {
enabled: {
title: 'Use Terraform Fmt',
description: 'Use \'terraform fmt\' to rewrite all Terraform files in the directory of the current file to a canonical format (occurs before linting).',
type: 'boolean',
default: false,
},
currentFile: {
title: 'Format Current File',
description: 'Only format the currently opened file instead of all files in the directory. Functional only if auto-formatting is also enabled.',
type: 'boolean',
default: false,
},
recursive: {
title: 'Recursive Format',
description: 'Recursively format all Terraform files from the directory of the current file. Functional only if auto-formatting is also enabled.',
type: 'boolean',
default: false,
},
},
},
},
// activate linter
activate() {
const helpers = require('atom-linter');
// error on terraform < 0.12
helpers.exec(atom.config.get('linter-terraform-syntax.terraformExecutablePath'), ['validate', '--help']).then(output => {
if (!(/-json/.exec(output))) {
atom.notifications.addError(
'The terraform executable installed in your path is unsupported.',
{
detail: 'Please upgrade your version of Terraform to >= 0.12 (>= 0.13 preferred), or downgrade this package to 1.4.1.'
}
);
}
});
},
deactivate() {
this.idleCallbacks.forEach((callbackID) => window.cancelIdleCallback(callbackID));
this.idleCallbacks.clear();
this.subscriptions.dispose();
},
provideLinter() {
return {
name: 'Terraform',
grammarScopes: ['source.terraform'],
scope: 'project',
lintsOnChange: false,
lint: async (textEditor) => {
// establish const vars
const helpers = require('atom-linter');
const editorFile = process.platform === 'win32' ? textEditor.getPath().replace(/\\/g, '/') : textEditor.getPath();
// try to get file path and handle errors appropriately
let dir = '';
try {
// const is block scoped in js for some reason
dir = require('path').dirname(editorFile);
} catch (error) {
// notify on stdin error
if (/\.dirname/.exec(error.message) != null) {
atom.notifications.addError(
'Terraform cannot lint on stdin due to nonexistent pathing on directories. Please save this config to your filesystem.',
{ detail: 'Save this config.' }
);
} else {
// notify on other errors
atom.notifications.addError(
'An error occurred with linter-terraform-syntax.',
{ detail: error.message }
);
}
}
// bail out if this is on the blacklist
if (atom.config.get('linter-terraform-syntax.blacklist') !== '') {
const blacklist = new RegExp(atom.config.get('linter-terraform-syntax.blacklist'));
if (blacklist.exec(editorFile)) return [];
}
// auto-formatting
if (atom.config.get('linter-terraform-syntax.useTerraformFormat') || atom.config.get('linter-terraform-syntax.format.enabled')) {
const fmtArgs = ['fmt', '-list=false'];
// recursive format if selected
if (atom.config.get('linter-terraform-syntax.recursiveFormat') || atom.config.get('linter-terraform-syntax.format.recursive'))
fmtArgs.push('-recursive');
// select the target for the auto-formatting
if (atom.config.get('linter-terraform-syntax.formatCurrentFile') || atom.config.get('linter-terraform-syntax.format.currentFile'))
fmtArgs.push(editorFile);
// auto-format the target
helpers.exec(atom.config.get('linter-terraform-syntax.terraformExecutablePath'), fmtArgs, { cwd: dir });
}
// execute the linting
return helpers.exec(atom.config.get('linter-terraform-syntax.terraformExecutablePath'), ['validate', '-no-color', '-json'], { cwd: dir, ignoreExitCode: true, timeout: atom.config.get('linter-terraform-syntax.timeout') * 1000 }).then(output => {
const toReturn = [];
// parse json output
const info = JSON.parse(output);
// assign formatVersion for future use
const formatVersion = info.format_version;
// command is reporting an issue
if (info.valid === false) {
info.diagnostics.forEach((issue) => {
// if no range information given then we have to improvise
let file = dir;
let lineStart = 0;
let lineEnd = 0;
let colStart = 0;
let colEnd = 1;
// we have range information so use it
if (issue.range != null) {
file = dir + require('path').sep + issue.range.filename;
lineStart = issue.range.start.line - 1;
lineEnd = issue.range.end.line - 1;
colStart = issue.range.start.column - 1;
colEnd = issue.range.end.column;
// otherwise check if we need to fix dir display
// add empty char to file path to circumvent unwanted relativization causing empty path display
} else if (atom.project.relativizePath(file)[0] === dir) file += ' ';
toReturn.push({
severity: issue.severity,
excerpt: issue.detail === '' ? issue.summary : issue.detail,
location: {
file,
position: [[lineStart, colStart], [lineEnd, colEnd]],
},
});
});
}
return toReturn;
});
}
};
}
};
<file_sep>### (Next)
- update fixtures to provider-less where possible
### 1.6.2
- Refactor auto formatting config options.
- Support deprecation for Terraform 0.12.
- Fix missing detail conditional from `null` to empty string.
### 1.6.1
- Update displayed information for File to be platform independent.
- Updates to Linter API usage.
- Fix inaccurate location position regression.
### 1.6.0
- Add config option for recursive auto-formatting.
- Drop support for `plan`.
### 1.5.1
- Remove description and replace summary in excerpt with details.
- Backup to validate summary if detail is null.
- Modify auto-formatting to execute from current file's directory.
### 1.5.0
- Add config setting to only auto-format the currently opened file.
- Minimum supported version now 0.12.
### 1.4.1
- Add `timeout` option to config settings.
- Circumvent atom-linter displaying only a file in the issue path for Terraform 0.12.
### 1.4.0
- Update linter scope to project level.
- Full 0.12 support and auto-detection.
### 1.3.1
- Add Beta support for Terraform >= 0.12.
### 1.3.0
- Remove specific check for `terraform init` prerequisite.
- Establish 0.11 as minimum version of Terraform.
- Fix check on linting nonexistent files.
- Improve required variable check disable.
### 1.2.6
- Added option to set global var files for all projects.
- Added option to set local var files for each project.
- Added option to ignore 'required variable not set' error.
- Improve ability to recognize necessary `terraform init`.
- Circumvent atom-linter displaying a blank file path when the linted file is in the root directory of the Atom project.
### 1.2.5
- Added option to exclude `.tf` filenames that match a regexp from linting.
- Updated `atom-linter` dependency.
- Catch linting on nonexistent files.
### 1.2.4
- Removing deprecation warning parsing since it does not seem to actually exist.
- Slight output parsing optimization.
- Adding proper capturing for new syntax error format.
- Notify when `terraform init` is necessary for solving issues in the directory.
### 1.2.3
- Added proper capturing for syntax errors in alternate format.
### 1.2.2
- Updated format captures and directory execution for 0.10 compatibility issues.
### 1.2.1
- Prevent displaying useless block info line for directory errors in Terraform >= 0.9.
- Added `terraform fmt` config option.
- Fixed path issue with Windows `\` versus expected `/` in Terraform.
### 1.2.0
- Switched to using Linter v2 API.
- Removed `atom-package-deps` dependency and functionality.
### 1.1.2
- Syntax errors for other files in the directory are now displayed within those files.
- Non-syntax directory error message no longer has superfluous current file.
- Removed color codes from displayed messages where applicable.
- Experimental support for capturing deprecation warnings.
### 1.1.1
- Capture error messages for all kinds of formatted `validate` and `plan` non-syntax errors in directory.
- Notify syntax errors for other Terraform files in directory.
- Removed range 1 where unnecessary.
### 1.1.0
- Added severity key.
- Show syntax errors for only active file and not all files in active directory.
- Add `terraform plan` option.
### 1.0.0
- Initial version ready for wide usage.
<file_sep>
### Linter-Terraform-Syntax
[](https://travis-ci.com/mschuchard/linter-terraform-syntax)
Linter-Terraform-Syntax aims to provide functional and robust `terraform validate` linting and `fmt` formatting functionality within Atom/Pulsar.
### APM (Atom) and PPM (Pulsar) Support
`apm` was discontinued prior to the sunset by the Atom Editor team. `ppm` for Pulsar does not yet support package publishing. Therefore, the installation instructions are now as follows if you want the latest version in Atom, Atom Beta, or Atom Dev:
- Locate the Atom or Pulsar packages directory on your filesystem (normally at `<home>/.{atom,pulsar}/packages`)
- Retrieve the code from this repository either via `git` or the Code-->Download ZIP option in Github.
- Place the directory containing the repository's code in the Atom or Pulsar packages directory.
- Execute `npm install` in the package directory (requires NPM).
- Repeat for any missing or outdated dependencies.
and Pulsar:
- Install the old version of the package as usual with either PPM or the GUI installer in the editor.
- Locate the Atom or Pulsar packages directory on your filesystem (normally at `<home>/.{atom,pulsar}/packages`)
- Replace the `lib/main.js` file in the package directory with the file located in this remote Github repository.
Additionally: this package is now in maintenance mode. All feature requests and bug reports in the Github repository issue tracker will receive a response, and possibly also be implemented (especially bug fixes). However, active development on this package has ceased.
Note that at this current time the package unit tests (outside of CI which will be Atom Beta `1.61.0` for the time being) and acceptance testing are performed with the latest stable version of Pulsar.
### Installation
Terraform >= 0.12 is required to be installed (five most recent minor versions are officially supported; check CI matrix) before using this (downgrade to 1.4.1 for 0.11 support). The Linter and Language-Terraform Atom packages are also required.
### Usage
- To quickly and easily access issues in other files, you will need to change the settings inside Linter-UI-Default. For `Panel Represents` and/or `Statusbar Represents`, you will need to change their options to `Entire Project`. This will allow you to use either display to quickly access issues in other files by clicking on the displayed information. Note this will not work on directory issues since a directory cannot be opened in a pane.
- Support for linting with `plan` was removed in version 1.6.0. Please downgrade to 1.5.1 if you wish to continue linting with `plan`.
| 523c1bb3ac8e7ea8310bb9f6723bfe4accb2628c | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | mschuchard/linter-terraform-syntax | cd15e6b8f233c07cacfb70cfc9e5fd41b60e73b6 | ac70f8bc8e73c8e04cb5ed71af6b5967d49a6177 |
refs/heads/main | <file_sep>from django.urls import reverse_lazy
from django.views import generic
from .forms import Predioform
from .models import Predio
class Predioview(generic.ListView):
model = Predio
template_name = 'listpredio.html'
context_object_name = 'predio'
class Predioinsertar(generic.CreateView):
model = Predio
context_object_name = 'predio'
template_name = 'formpredio.html'
form_class = Predioform
success_url = reverse_lazy("Predio:predios")
class Predioeditar(generic.UpdateView):
model = Predio
context_object_name = 'predio'
template_name = 'formpredio.html'
form_class = Predioform
success_url = reverse_lazy("Predio:predios")
class Predioeliminar(generic.DeleteView):
model = Predio
context_object_name = 'predio'
template_name = 'deletepredio.html'
form_class = Predioform
success_url = reverse_lazy("Predio:predios")
<file_sep>
$(document).ready(function(){
anime({
targets: '.modal',
translateY: 50
});
//startanimate();
$('#elminarModal').modal({backdrop: 'static', keyboard: false});
$('#elminarModal').modal('show')
$('#mdllogout').modal('show')
$( "#fondop" ).load("/Persona/loadPersona");
$( "#fondor" ).load("/Rol/loadrol");
$( "#fondou" ).load("/Usuario/loadusuario");
$( "#fondotc" ).load("/Tiposcasos/tiposcaso");
$( "#fondoc" ).load("/Caso/loadcaso");
$('#id_Caso').hide()
$('#id_usuario').hide()
document.getElementById('id_usuario').value =sessionStorage['idusuario'];
document.getElementById('id_Caso').value =sessionStorage['idcaso'];
$("label[for='id_usuario']").hide()
$("label[for='id_Caso']").hide()
$(function () {
$('[data-toggle="popover"]').popover()
})
//finshanimate();
});
function Animation(runM){
anime({
targets: '.modal',
translateY: runM
});
}
function startanimate(){
anime({
targets: '.container-fluid',
translateX: 100,
direction: 'reverse',
});
}
(function($) {
"use strict";
// Add active state to sidbar nav links
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$("#layoutSidenav_nav .sb-sidenav a.nav-link").each(function() {
if (this.href === path) {
$(this).addClass("active");
}
});
// Toggle the side navigation
$("#sidebarToggle").on("click", function(e) {
e.preventDefault();
$("body").toggleClass("sb-sidenav-toggled");
});
})(jQuery);
<file_sep>from django.db import models
class TipoGeografia(models.Model):
nombre = models.CharField(max_length=200)
def __str__(self):
return '{}'.format(self.nombre)
class Meta:
verbose_name_plural='TipoGeografias'
<file_sep>
import requests
from django.urls import reverse_lazy
from django.views import generic
from Propietario.models import Propietario
from Cliente.models import Cliente
from django.db.models import Q
#ilter(Cliente__numeroIdentificacion__icontains=query)
class search(generic.ListView):
template_name = 'listconsulta.html'
context_object_name = 'Propietario'
def get_queryset(self):
query = self.request.GET.get('name')
if not query :
query = ""
return Propietario.objects.all().select_related('Cliente','Predio').filter(Q(Cliente__NombreCliente__startswith=query) | Q(Cliente__numeroIdentificacion__startswith=query) | Q(Predio__TipoGeografia__nombre__startswith=query))<file_sep>
from django.db import models
from TipoGeografia.models import TipoGeografia
class Predio(models.Model):
Ubicacion = models.CharField(max_length=200)
TipoGeografia = models.ForeignKey(TipoGeografia, on_delete=models.CASCADE)
def __str__(self):
return '{}'.format(self.Ubicacion)
class Meta:
verbose_name_plural='Predios'
<file_sep>from django.urls import path
from .views import Propietarioview,Propietarioinsertar,Propietarioeditar,Propietarioeliminar
urlpatterns = [
path('', Propietarioview.as_view(), name='propietarios'),
path('propietario/new/', Propietarioinsertar.as_view(), name='Insertar'),
path('propietario/Editar/<int:pk>', Propietarioeditar.as_view(), name='Editar'),
path('propietario/eliminar/<int:pk>', Propietarioeliminar.as_view(), name='Eliminar'),
]
<file_sep>from django.db import models
# Create your models here.
class TipoCliente(models.Model):
nombre = models.CharField(max_length=200)
def __str__(self):
return '{}'.format(self.nombre)
class Meta:
verbose_name_plural='TipoClientes'
<file_sep>from django.urls import reverse_lazy
from django.views import generic
from .forms import Propietarioform
from .models import Propietario
class Propietarioview(generic.ListView):
model = Propietario
template_name = 'listpropietario.html'
context_object_name = 'propietario'
class Propietarioinsertar(generic.CreateView):
model = Propietario
context_object_name = 'propietario'
template_name = 'formpropietario.html'
form_class = Propietarioform
success_url = reverse_lazy("Propietario:propietarios")
class Propietarioeditar(generic.UpdateView):
model = Propietario
context_object_name = 'propietario'
template_name = 'formpropietario.html'
form_class = Propietarioform
success_url = reverse_lazy("Propietario:propietarios")
class Propietarioeliminar(generic.DeleteView):
model = Propietario
context_object_name = 'propietario'
template_name = 'deletepropietario.html'
form_class = Propietarioform
success_url = reverse_lazy("Propietario:propietarios")
<file_sep>
from django.urls import path
from .views import search
urlpatterns = [
path('', search.as_view(), name='buscador'),
]<file_sep>from django import forms
from .models import Cliente
class Clienteform(forms.ModelForm):
class Meta:
model = Cliente
fields = ['TipoIdentificacion','TipoCliente', 'NombreCliente','numeroIdentificacion']
labels = {'TipoIdentificacion': 'Seleccione tipo de identificacion ',
'TipoCliente': 'Seleccione tipo de cliente ',
'NombreCliente': 'Nombre del cliente ',
'numeroIdentificacion':'numero de identificacion'
}
widget = {'TipoIdentificacion': forms.TextInput(),
'TipoCliente': forms.TextInput(),
'NombreCliente': forms.TextInput(),
'numeroIdentificacion': forms.TextInput(),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'})
<file_sep># Generated by Django 3.1.7 on 2021-09-17 20:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Cliente', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='cliente',
name='NombreCliente',
field=models.CharField(max_length=200, unique=True),
),
]
<file_sep>from django.apps import AppConfig
class TipoclienteConfig(AppConfig):
name = 'TipoCliente'
<file_sep>from django.db import models
from TipoCliente.models import TipoCliente
from TipoIdentificacion.models import TipoIdentificacion
# Create your models here.
class Cliente(models.Model):
TipoIdentificacion = models.ForeignKey(TipoIdentificacion, on_delete=models.CASCADE)
TipoCliente = models.ForeignKey(TipoCliente, on_delete=models.CASCADE)
NombreCliente = models.CharField(max_length=200)
numeroIdentificacion = models.CharField(max_length=200, unique=True)
def __str__(self):
return '{}'.format(self.NombreCliente)
class Meta:
verbose_name_plural='Clientes'
<file_sep># arcerojas
Entrevista de trabajo
Solucion del problema
la solucion del problema conto con una base datos relacional, con una capa backend ralizado desde el framework de django y una capa frontend realizado en los templates de django.
no se vio la necesidad de implementar una capa Rest y si se pidiera esta se realizaria con djago rest framework (DRF) y una capa de libreria o framework frontend como lo es Angula,Reactjs,Vue.
Pasos para instalar el sistema
- docker-compose build
- compose-compose up(talvez pueda repetir este paso dos veces dependiendo de las configuraciones de su entorno)
Entrar al contenedor para realizar las migraciones
- docker exec -ti ddb /bin/bash
Insertar las siguientes consultas en pgAdmin o en el IDE de gestor de BD que prefiera
- Consultas sql
- INSERT INTO public."TipoCliente_tipocliente"(nombre)VALUES ('Empresa');
- INSERT INTO public."TipoCliente_tipocliente"(nombre)VALUES ('Persona');
- INSERT INTO public."TipoGeografia_tipogeografia"(nombre)VALUES ('Rural');
- INSERT INTO public."TipoGeografia_tipogeografia"(nombre)VALUES ('Urbano');
- INSERT INTO public."TipoIdentificacion_tipoidentificacion"(nombre)VALUES('CC');
- INSERT INTO public."TipoIdentificacion_tipoidentificacion"(nombre)VALUES('NIT');
Muchas gracias y agradecimientos
<file_sep>from django.db import models
from Cliente.models import Cliente
# Create your models here.
class DetalleClientePersona(models.Model):
edad = models.CharField(max_length=200)
apellido = models.CharField(max_length=200)
Cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE)
def __str__(self):
return '{}'.format(self.apellido)
class Meta:
verbose_name_plural='TipoClientes'
<file_sep># Generated by Django 3.1.7 on 2021-09-17 20:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Cliente', '0002_auto_20210917_2037'),
]
operations = [
migrations.AlterField(
model_name='cliente',
name='NombreCliente',
field=models.CharField(max_length=200),
),
migrations.AlterField(
model_name='cliente',
name='numeroIdentificacion',
field=models.CharField(max_length=200, unique=True),
),
]
<file_sep>from django.apps import AppConfig
class DetalleclientepersonaConfig(AppConfig):
name = 'DetalleClientePersona'
<file_sep>from django.apps import AppConfig
class TipoidentificacionConfig(AppConfig):
name = 'TipoIdentificacion'
<file_sep>from django.shortcuts import render
from django.views import generic
class inicio(generic.TemplateView):
template_name = "inicio.html"
<file_sep>Django==3.1.7
django_environ == 0.4.5
psycopg2-binary>=2.8.3
djangorestframework==3.12.2
django-cors-headers==3.7.0
requests==1.1.0<file_sep>
from django.urls import path
from .views import Clienteview,Clienteinsertar,Clienteeditar,Clienteeliminar
urlpatterns = [
path('', Clienteview.as_view(), name='clientes'),
path('cliente/new/', Clienteinsertar.as_view(), name='Insertar'),
path('cliente/Editar/<int:pk>', Clienteeditar.as_view(), name='Editar'),
path('cliente/eliminar/<int:pk>', Clienteeliminar.as_view(), name='Eliminar'),
]
<file_sep>from django.urls import path
from .views import Predioview,Predioinsertar,Predioeditar,Predioeliminar
urlpatterns = [
path('', Predioview.as_view(), name='predios'),
path('predio/new/', Predioinsertar.as_view(), name='Insertar'),
path('Predio/Editar/<int:pk>', Predioeditar.as_view(), name='Editar'),
path('predio/eliminar/<int:pk>', Predioeliminar.as_view(), name='Eliminar'),
]
<file_sep>from django.apps import AppConfig
class PredioConfig(AppConfig):
name = 'Predio'
<file_sep>from django.db import models
# Create your models here.
from Cliente.models import Cliente
from Predio.models import Predio
class Propietario(models.Model):
Cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE)
Predio = models.ForeignKey(Predio, on_delete=models.CASCADE)
def __str__(self):
return '{}'.format(self.Cliente)
class Meta:
verbose_name_plural='Predios'
<file_sep>from django.contrib import admin
from django.urls import include, path
from inicio.views import inicio
urlpatterns = [
path('', inicio.as_view(), name='inicio'),
]
<file_sep>
from django.urls import reverse_lazy
from django.views import generic
from .forms import Clienteform
from .models import Cliente
class Clienteview(generic.ListView):
model = Cliente
template_name = 'listcliente.html'
context_object_name = 'cliente'
class Clienteinsertar(generic.CreateView):
model = Cliente
context_object_name = 'cliente'
template_name = 'formcliente.html'
form_class = Clienteform
success_url = reverse_lazy("Cliente:clientes")
class Clienteeditar(generic.UpdateView):
model = Cliente
context_object_name = 'cliente'
template_name = 'formcliente.html'
form_class = Clienteform
success_url = reverse_lazy("Cliente:clientes")
class Clienteeliminar(generic.DeleteView):
model = Cliente
context_object_name = 'cliente'
template_name = 'deletecliente.html'
form_class = Clienteform
success_url = reverse_lazy("Cliente:clientes")
<file_sep>from django import forms
from .models import Predio
class Predioform(forms.ModelForm):
class Meta:
model = Predio
fields = ['Ubicacion','TipoGeografia']
labels = {'Ubicacion': 'Digite la ubicacion ',
'TipoGeografia': 'Seleccione el tipo de geografia'
}
widget = {'Ubicacion': forms.TextInput(),
'TipoGeografia': forms.TextInput(),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'})
<file_sep># Generated by Django 3.1.7 on 2021-09-16 23:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('TipoCliente', '0001_initial'),
('TipoIdentificacion', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Cliente',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('NombreCliente', models.CharField(max_length=200)),
('numeroIdentificacion', models.CharField(max_length=200)),
('TipoCliente', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='TipoCliente.tipocliente')),
('TipoIdentificacion', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='TipoIdentificacion.tipoidentificacion')),
],
),
]
<file_sep>"""arcerojas URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(('inicio.urls', 'inicio'), namespace='inicio')),
path('Cliente/', include(('Cliente.urls', 'Cliente'), namespace='Persona')),
path('Predio/', include(('Predio.urls', 'Predio'), namespace='Predio')),
path('Propietario/', include(('Propietario.urls', 'Propietario'), namespace='Propietario')),
path('Busqueda/', include(('consulta.urls', 'Consulta'), namespace='Consulta')),
]
| 214e67e48b5f9c24bd64d9c04c94db86ee0c85e0 | [
"JavaScript",
"Python",
"Text",
"Markdown"
] | 29 | Python | efnaranjo6/arcerojas | ace90508d2a95f837c255f9245af3d1bff0d8f02 | 238542f11a91958cf5d3221781c8425c23a8a1c1 |
refs/heads/develop | <repo_name>maikforte/project-mango<file_sep>/frontend/src/app/hris/shared/sidebar/modules.ts
import { ParentModule } from '../../../model/parent-module.model';
import { ChildModule } from '../../../model/child-module.model';
export function initModules(): Array<ParentModule> {
let modules: Array<ParentModule>;
modules = new Array<ParentModule>();
const adminChildModules: Array<ChildModule> = [
new ChildModule('User Maintenance', 'User Maintenance', '/user-maintenance'),
new ChildModule('Test Maintenance', 'Test Maintenance', '/test-maintenance')
];
const userChildModules: Array<ChildModule> = [
new ChildModule('Leave', 'leave', '/leave-form'),
new ChildModule('Productivity Tool Loan', 'Prod Tool', '/productivity-tool-loan')
];
const adminModules: ParentModule = new ParentModule('Administration', 'Admin modules', 'fa-home', adminChildModules);
const userModules: ParentModule = new ParentModule('Forms', 'Forms', 'fa-home', userChildModules);
modules.push(adminModules);
modules.push(userModules);
return modules;
}
<file_sep>/frontend/src/app/model/child-module.model.ts
export class ChildModule {
public label: string;
public description: string;
public route: string;
constructor()
constructor(label: string, description: string, route: string)
constructor (label?: string, description?: string, route?: string) {
this.label = label;
this.description = description;
this.route = route;
}
}
<file_sep>/frontend/src/app/hris/hris.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HrisComponent } from './hris.component';
import { SharedModule } from './shared/shared.module';
import { UserMaintenanceModule } from './user-maintenance/user-maintenance.module';
import { AppRoutingModule } from '../app-routing.module';
@NgModule({
imports: [
CommonModule,
AppRoutingModule,
SharedModule,
UserMaintenanceModule
],
declarations: [HrisComponent]
})
export class HrisModule { }
<file_sep>/frontend/src/app/model/parent-module.model.ts
import { ChildModule } from './child-module.model';
export class ParentModule {
public label: string;
public description: string;
public icon: string;
public childModules: Array<ChildModule>;
constructor()
constructor(label: string, description: string, icon: string, childModules: Array<ChildModule>)
constructor(label?: string, description?: string, icon?: string, childModules?: Array<ChildModule>) {
this.label = label;
this.description = description;
this.icon = icon;
this.childModules = childModules;
}
}
<file_sep>/frontend/src/app/hris/shared/sidebar/sidebar.component.ts
import { Component, OnInit } from '@angular/core';
import { ParentModule } from '../../../model/parent-module.model';
import { initModules } from './modules';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {
public parentModules: Array<ParentModule>;
public isToggled: boolean;
constructor() { }
ngOnInit() {
this.isToggled = false;
this.initParentModules();
}
private initParentModules(): void {
this.parentModules = initModules();
}
public toggle(): void {
if (window.innerWidth <= 900) {
this.isToggled = !this.isToggled;
}
}
}
| 44a16d88b9ae0c8867602a4e84e0b9e99bf96720 | [
"TypeScript"
] | 5 | TypeScript | maikforte/project-mango | d61ecaa17e14b396a51977c9e5f2ce356ddf3493 | 86f934cc63fda4b69e6441f7f51f4405f942c605 |
refs/heads/master | <file_sep>/* eslint no-restricted-globals: 'off' */
// Turn duration of the movies from hours to minutes
function turnHoursToMinutes(moviesArray) {
return moviesArray.map(function (elem) {
var hours = 0;
var minutes = 0;
if (elem.duration.indexOf('h') !== -1) {
hours = parseInt(elem.duration[0], 10) * 60;
}
if (elem.duration.indexOf('min') !== -1) {
minutes = parseInt(elem.duration.substring(elem.duration.length - 5, elem.duration.length - 3), 10);
}
return Object.assign({}, elem, { duration: hours + minutes });
});
}
turnHoursToMinutes(movies);
// Get the average of all rates with 2 decimals
function ratesAverage (moviesArray){
var rate = moviesArray.reduce(function(accum, current){
return accum + parseInt(current.rate);
}, 0);
return rate/moviesArray.length;
//Math.round(original*100)/100
}
ratesAverage(movies)
// Get the average of Drama Movies
function dramaMoviesRate(moviesArray) {
var dramaList = moviesArray.filter(function(movie){
for (i = 0; i<movie.genre.length;i++){
return movie.genre[i] == "Drama";
}
});
return ratesAverage(dramaList);
}
// Order by time duration, in growing order
// How many movies did STEVEN SPIELBERG
// Order by title and print the first 20 titles
// Best yearly rate average
| 68152b18d2a2852ab140f90e093026c25e223ecc | [
"JavaScript"
] | 1 | JavaScript | esthvega/lab-javascript-all-times-movies | 64d18364aa2d2e37bc9aebc7961a796767413a6b | 6a1321a8b731f63ba2cce3a0ed8d0f711b956b1d |
refs/heads/master | <file_sep>from django.db import models
class Item(models.Model):
# items
TYPE_CHOICES = (
('01', 'ARM CHAIR'),
('02', 'COUCH'),
('03', 'COFFEE TABLE'),
('04', 'DESK'),
('05', 'BED'),
('06', 'DINING TABLE'),
('07', 'DINING CHAIR'),
('08', 'SHELVING')
)
store_name = models.ForeignKey('Store', to_field='store_name')
item_type = models.CharField(max_length=20, choices=TYPE_CHOICES)
item_name = models.CharField(max_length=50)
price_multipler = models.IntegerField()
item_link = models.URLField()
description = models.TextField()
subjective_input = models.TextField(blank=True, null=True)
def __unicode__(self): # string representation for debugging
return self.item_name
class Store(models.Model):
# stores
TYPE_CHOICES = (
('01', 'IKEA'),
('02', 'CB2'),
('03', 'EQ3'),
('04', 'GAUTIER'),
('05', 'THE BAY'),
('06', 'WEST ELM'),
('07', 'BO CONCEPT')
)
store_name = models.CharField(max_length=20, choices=TYPE_CHOICES, unique=True)
store_website = models.URLField()
store_address = models.CharField(max_length=150)
city = models.CharField(max_length=30)
province = models.CharField(max_length=5)
postal_code = models.CharField(max_length=10)
phone_number = models.CharField(max_length=20)
def __unicode__(self): # string representation for debugging
return self.store_name<file_sep>from django.http import HttpResponse, Http404
from django.template import RequestContext, loader
from django.shortcuts import render
from alternativ.models import Item, Store
# VIEWS: return an HttpResponse... or raise Http404 if invalid request.
# Globals
TYPES = {'ARM CHAIR': '01',
'COUCH': '02',
'COFFEE TABLE': '03',
'DESK': '04',
'BED': '05',
'DINING TABLE': '06',
'DINING CHAIR': '07',
'SHELVING': '08'
}
STORES = {'CB2': '01',
'EQ3': '02',
'GAUTIER': '03',
'THE BAY': '04',
'WEST ELM': '05',
'WESTELM': '05', # kinda hacky, it's OK for now
'BO CONCEPT': '06', # in the interest of deadlines :/
'BOCONCEPT': '06'
}
def invalid_url(item, cat=False):
'''Invalid url handler helper function. Cat is a flag meaning
the input url to be checked is an item, not a category.'''
# should be convertable to int
try:
num = int(item)
except ValueError:
raise Http404
# should only be two characters long
if len(item) != 2:
# that one edge case
if cat and num == 9:
return '09'
else:
raise Http404
# there are only 8 categories
if not cat and num not in range(1,9):
raise Http404
# there are only 54 items (yes, this should be changed...)
if cat and num not in range(9, 55):
raise Http404
return item
def about(request):
template = loader.get_template('about.html')
context = RequestContext(request, {})
return HttpResponse(template.render(context))
def index(request):
template = loader.get_template('index.html')
context = RequestContext(request, {
'types': TYPES})
return HttpResponse(template.render(context))
def detail(request, item):
'''Views handler for the category page - ie. "Couch". '''
# handle invalid urls
invalid_url(item)
template = loader.get_template('type.html')
# get ikea item
ikea_item = Item.objects.filter(store_name="IKEA", item_type__iexact="%s" % Item.TYPE_CHOICES[int(item) - 1][1])[0]
# get all the alternative items
alt = Item.objects.exclude(store_name="IKEA").filter(item_type__iexact="%s" % Item.TYPE_CHOICES[int(item) - 1][1])
# create mapping between store name and code
item_list = {}
for i in alt:
item_list[i] = STORES[str(i.store_name.store_name).upper()]
# pass in the context
context = RequestContext(request, {
'item_type': Item.TYPE_CHOICES[int(item) - 1][1],
'ikea_item': ikea_item.description,
'subj': ikea_item.subjective_input,
'alt_items': item_list,
'code': item
})
return HttpResponse(template.render(context))
def options(request, item_type, item):
# handle invalid urls
invalid_url(item_type)
item = invalid_url(item, True)
# item_type can be used for a back button if desired
template = loader.get_template('option.html')
# get the item
item = Item.objects.get(id=item)
store = Store.objects.get(store_name=item.store_name)
# get the corresponding ikea item
ikea_name = Item.objects.get(id=item_type).item_name.upper()
# sanity check URL
correct_type = Item.TYPE_CHOICES[int(item_type) - 1][1].title()
if item.item_type != correct_type:
raise Http404
# get full address for Google Maps display
full_address = store.store_address + " " + store.city + " " + store.province + " " + store.postal_code
context = RequestContext(request, {
# item specific
'item_code': item,
'type_code': item_type,
'item_name': item.item_name,
'item_desc': item.description,
'subj': item.subjective_input,
'price': item.price_multipler,
'store_name': item.store_name,
'item_link': item.item_link,
# ikea item
'ikea_name': ikea_name,
# store specific
'store_code': STORES[str(item.store_name).upper()],
'store_address': store.store_address,
'store_website': store.store_website,
'city': store.city,
'province': store.province,
'postal_code': store.postal_code,
'phone': store.phone_number,
'full_address': full_address
})
return HttpResponse(template.render(context))<file_sep>"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
""" Tests that 1 + 1 always equals 2. """
self.assertEqual(1 + 1, 2)
class LinksTestCase(TestCase):
def test_index(self):
""" Tests that index page loads correctly and receives a list of furniture types. """
resp = self.client.get('/')
self.assertEqual(resp.status_code, 200)
self.assertTrue('types' in resp.context)
self.assertEqual(resp.templates[0].name, 'index.html')
def test_about(self):
'''Test correct linkage of about page.'''
resp = self.client.get('/about')
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.templates[0].name, 'about.html')
def test_cat_correct(self):
'''Test correct linkage of a category page.'''
resp = self.client.get('/08')
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.templates[0].name, 'type.html')
def test_cat_correct_2(self):
'''Test correct linkage of a category page.'''
resp = self.client.get('/01')
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.templates[0].name, 'type.html')
def test_cat_fail(self):
'''Test failing linkage of a category page.'''
resp = self.client.get('/09')
self.assertEqual(resp.status_code, 404)<file_sep>Django==1.5.5
PyRSS2Gen==1.0.0
altgraph==0.10.1
bdist-mpkg==0.4.4
dj-database-url==0.2.2
dj-static==0.0.5
django-toolbelt==0.0.1
gunicorn==18.0
psycopg2==2.5.1
py2app==0.7.1
pyOpenSSL==0.13
pystache==0.5.3
python-dateutil==1.5
pytz==2012d
static==1.0.2
virtualenv==1.10.1
wsgiref==0.1.2
xattr==0.6.4
zope.interface==3.8.0
geopy==0.98.3
django-easy-maps==0.9<file_sep>from django.contrib import admin
from alternativ.models import Item
admin.site.register(Item)<file_sep>ikealternative
==============
A web service for suggesting furniture stores in Toronto when you decide to say good-bye to IKEA. Developed as a part of Myplanet Fellowship 2014.
Check out the ongoing work @ <a href="http://alternativ.herokuapp.com">alternativ.herokuapp.com</a>
| 453abe251b7646e18af75e1980267e155e1d1c1c | [
"Markdown",
"Python",
"Text"
] | 6 | Python | fromtheothershore/ikealternative | 63bf5bdd396879865b2c95cc9ab59f08113bc152 | 13bbc95aaf708cc39eb2be509813074dcb85a5a8 |
refs/heads/master | <repo_name>Raydextert/Arcengine<file_sep>/GisDemo/Command/AddJunctionFlagTool.cs
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.NetworkAnalysis;
using System.Collections.Generic;
using ESRI.ArcGIS.Geodatabase;
using GisDemo.Command;
namespace GisDemo.Command
{
public sealed class AddJunctionFlagTool:BaseTool
{
private IHookHelper m_hookHelper = null;
private IGeometricNetwork geomretyNetwork;
private List<IJunctionFlag> listJunctionFlags;
public List<IJunctionFlag> ListJunctionFlags
{
set
{
listJunctionFlags = value;
}
}
//接口数组都是引用类型
public IGeometricNetwork GeometryNetwork
{
set
{
geomretyNetwork = value;
}
}
public AddJunctionFlagTool()
{
this.m_caption = "添加交汇点";
this.m_category = "几何网络分析";
this.m_message = "在地图上点击管点,将其添加为网络分析的点要素";
this.m_toolTip = "添加分析管点";
string path = Application.StartupPath;
string filepath = path.Substring(0, path.LastIndexOf("\\"));
this.m_cursor = new System.Windows.Forms.Cursor(filepath + "\\" + "Icon\\Cursors\\UtilityNetworkJunctionAdd16.cur");
}
public override void OnCreate(object hook)
{
if(hook == null) return;
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
}
public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
base.OnMouseDown(Button, Shift, X, Y);
if (Button != 1) return;
//获取坐标点
IPoint inPoint = new PointClass();
inPoint = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
IMap map = m_hookHelper.FocusMap;
//查询与坐标点最近的管点
IPointToEID pointToEID = new PointToEIDClass();
//
if (geomretyNetwork == null) return;
pointToEID.GeometricNetwork = geomretyNetwork;
pointToEID.SourceMap = map;
pointToEID.SnapTolerance = 10;
IPoint outPoint=new PointClass ();
int nearestJunctionEID = -1;
pointToEID.GetNearestJunction(inPoint,out nearestJunctionEID ,out outPoint);
if (outPoint == null || outPoint.IsEmpty) return;
//获取管点标识并加入列表
INetElements netElemnts = geomretyNetwork.Network as INetElements;
int UserClassID = 0;
int UserID = 0;
int UserSubID = 0;
netElemnts.QueryIDs(nearestJunctionEID, esriElementType.esriETJunction, out UserClassID, out UserID, out UserSubID);
//设置并添加管点标识
INetFlag netFlag = new JunctionFlagClass() as INetFlag;
netFlag.UserClassID = UserClassID;
netFlag.UserID = UserID;
netFlag.UserSubID = UserSubID;
//
listJunctionFlags.Add(netFlag as IJunctionFlag);
//绘制点要素
DrawElement(outPoint);
}
public override void OnMouseMove(int Button, int Shift, int X, int Y)
{
//TODO: Add ToolAddJunctionFlag. OnMouseMove implementation
}
#region 私有方法
private void DrawElement(IPoint point)
{
if (point == null || point.IsEmpty) return;
ISimpleMarkerSymbol MarkerSymbol = new SimpleMarkerSymbolClass();
MarkerSymbol.Size = 8;
MarkerSymbol.Color = ExportMap.Getcolor(85, 255, 0);
MarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSSquare;
IElement element = new MarkerElementClass();
element.Geometry = point;
((IMarkerElement)element).Symbol = MarkerSymbol;
//设置添加要素点名称
((IElementProperties)element).Name = "Flag";
this.m_hookHelper.ActiveView.GraphicsContainer.AddElement(element, 0);
this.m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, this.m_hookHelper.ActiveView.Extent );
}
#endregion
}
}
<file_sep>/GisDemo/Command/AddEdgeTool.cs
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.NetworkAnalysis;
using System.Collections.Generic;
using ESRI.ArcGIS.Geodatabase;
using GisDemo.Command;
namespace GisDemo.Command
{
//该类不可再继承
public sealed class AddEdgeTool:BaseTool
{
private IHookHelper m_hookHelper = null;
private IGeometricNetwork geometricNetwork;
public IGeometricNetwork GeometricNetwork
{
set
{
geometricNetwork = value;
}
}
private List<IEdgeFlag > listEdgeFlag;
public List<IEdgeFlag> ListEdgeFlag
{
set
{
listEdgeFlag = value;
}
}
public AddEdgeTool()
{
this.m_caption = "添加交汇边";
this.m_category = "几何网络分析";
this.m_message = "在地图上点击管线,将其添加为网络分析的线要素";
this.m_toolTip = "添加分析管线";
string path = Application.StartupPath;
string filepath = path.Substring(0, path.LastIndexOf("\\"));
this.m_cursor = new System.Windows.Forms.Cursor(filepath + "\\" + "Icon\\Cursors\\UtilityNetworkJunctionAdd16.cur");
}
public override void OnCreate(object hook)
{
if (hook == null) return;
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
}
public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
if (Button != 1) return;
IPoint inPoint = new PointClass();
inPoint = this.m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
IMap map = this.m_hookHelper.FocusMap;
//查询与点最近的EID
IPointToEID pointToEID = new PointToEIDClass();
pointToEID.GeometricNetwork = geometricNetwork;
pointToEID.SourceMap = map;
pointToEID.SnapTolerance = 10;
IPoint outPoint = new PointClass();
int nearestEdgeID = -1;
double percent = -1;
pointToEID.GetNearestEdge(inPoint, out nearestEdgeID, out outPoint,out percent);
if (outPoint == null || outPoint.IsEmpty) return;
//获取与点最邻近的边
INetElements netElments = geometricNetwork.Network as INetElements;
int userClSSID = 0;
int userID = 0;
int userSubID = 0;
netElments.QueryIDs(nearestEdgeID , esriElementType.esriETEdge, out userClSSID, out userID, out userSubID);
INetFlag netFlag = new EdgeFlagClass() as INetFlag;
netFlag.UserClassID = userClSSID;
netFlag.UserID = userID;
netFlag.UserSubID = userSubID;
//添加管线标识
listEdgeFlag.Add(netFlag as IEdgeFlag);
//绘制点所在的边
DrawElement(outPoint);
}
private void DrawElement(IPoint point)
{
if (point == null || point.IsEmpty) return;
ISimpleMarkerSymbol MarkerSymbol = new SimpleMarkerSymbolClass();
MarkerSymbol.Size = 8;
MarkerSymbol.Color = ExportMap.Getcolor(85, 255, 0);
MarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSSquare;
IElement element = new MarkerElementClass();
element.Geometry = point;
((IMarkerElement)element).Symbol = MarkerSymbol;
//设置添加要素点名称
((IElementProperties)element).Name = "Flag";
this.m_hookHelper.ActiveView.GraphicsContainer.AddElement(element, 0);
this.m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, this.m_hookHelper.ActiveView.Extent);
}
}
}
<file_sep>/GisDemo/forms/AttrQueryFrm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF.BaseClasses;
/*===============================================
*
*
* 属性查询窗体
*
* 作者:zrc 日期:2019/11/18
*================================================
*/
namespace GisDemo.forms
{
public partial class AttrQueryFrm : Form
{
public AttrQueryFrm()
{
InitializeComponent();
}
private IMapControlDefault mapcontrol = null;
public IMapControlDefault Mapcontrol
{
set { mapcontrol = value; }
get { return mapcontrol; }
}
IFeatureLayer fteLyr = null;
private IFeatureClass fteClss=null;
esriFieldType fieldType;
private void AttrQueryFrm_Load(object sender, EventArgs e)
{
loadLyrs();
}
#region 私有方法
private void loadLyrs()
{
if (Mapcontrol == null) return;
for (int i = 0; i < Mapcontrol.LayerCount; i++)
{
object lyrname = this.Mapcontrol.get_Layer(i).Name;
this.LyrCmbx.Items.Add(lyrname);
}
if (this.LyrCmbx.Items.Count == 0) return;
this.LyrCmbx.Text = this.LyrCmbx.Items[0].ToString();
}
private void loadFields(string lyrname)
{
if (string.IsNullOrEmpty(lyrname)) return;
this.fieldslistBox.Items.Clear();
fteLyr = null;
for (int i = 0; i < this.Mapcontrol.LayerCount; i++)
{
if (this.Mapcontrol.get_Layer(i).Name == lyrname)
{
fteLyr = this.Mapcontrol.get_Layer(i) as IFeatureLayer;
break;
}
}
//加载字段
if (fteLyr == null) return;
fteClss = fteLyr.FeatureClass;
for (int j = 0; j < fteLyr.FeatureClass.Fields.FieldCount; j++)
{
this.fieldslistBox.Items.Add(fteLyr.FeatureClass.Fields.get_Field(j).Name);
}
}
private void GetUniqueVal()
{
if (fteClss == null) return;
this.ValueList.Items.Clear();
int fieldIndex = -1;
string fieldSel = this.fieldslistBox.SelectedItem.ToString();
for (int i = 0; i < fteClss.Fields.FieldCount; i++)
{
if (fteClss.Fields.get_Field(i).Name ==fieldSel &&!string .IsNullOrEmpty (fieldSel))
{
fieldIndex = i;
break;
}
}
if (fieldIndex == -1) return;
fieldType = fteClss.Fields.get_Field(fieldIndex).Type;
IFeatureCursor pCursor = fteClss.Search(null, false);
IFeature pFeature = pCursor .NextFeature ();
while (pFeature != null)
{
this.ValueList.Items.Add(pFeature.get_Value(fieldIndex));
pFeature = pCursor.NextFeature();
}
}
private void ExpandMap(IFeatureCursor Cursor)
{
if (Cursor == null) return;
IFeature pFeature = Cursor.NextFeature();
IEnvelope pEnve = new EnvelopeClass();
while (pFeature != null)
{
//先缩放再高亮
pEnve.Union(pFeature.Extent);
pFeature = Cursor.NextFeature();
}
this.Mapcontrol.ActiveView.Extent = pEnve;
this.Mapcontrol.Refresh();
//即时调用更新窗体方法,进而首先进行缩放
this.Mapcontrol.ActiveView.ScreenDisplay.UpdateWindow();
}
private void FlashFeature(IFeatureCursor Cursor)
{
//高亮显示要素
this.Mapcontrol.Map.ClearSelection();
this.Mapcontrol.Refresh();
if (Cursor == null) return;
IFeature pFeature = Cursor.NextFeature();
while (pFeature != null)
{
//先缩放再高亮
this.Mapcontrol.Map.SelectFeature(fteLyr, pFeature);
this.Mapcontrol.Refresh(esriViewDrawPhase.esriViewGeoSelection, null, null);
this.Mapcontrol.Refresh();
pFeature = Cursor.NextFeature();
}
}
#endregion
private void fieldslistBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void LyrCmbx_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.LyrCmbx.Items.Count == 0) return;
string Lyrname = this.LyrCmbx.SelectedItem.ToString();
loadFields(Lyrname);
}
private void uniquevalueBtn_Click(object sender, EventArgs e)
{
GetUniqueVal();
}
private void equalbtn_Click(object sender, EventArgs e)
{
try
{
this.exptxtBox.Text += "=";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void fieldslistBox_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.exptxtBox.Text += this .fieldslistBox .SelectedItem .ToString ();
//获取字段类型
}
private void ValueList_MouseDoubleClick(object sender, MouseEventArgs e)
{
switch (fieldType)
{
case esriFieldType.esriFieldTypeInteger:
case esriFieldType.esriFieldTypeSmallInteger:
case esriFieldType.esriFieldTypeSingle:
case esriFieldType.esriFieldTypeDouble:
case esriFieldType.esriFieldTypeOID:
case esriFieldType.esriFieldTypeGUID:
this.exptxtBox.Text += this.ValueList.SelectedItem.ToString();
break;
default :
this.exptxtBox.Text += "\'"+this.ValueList.SelectedItem.ToString()+"\'";
break;
}
}
private void greaterbtn_Click(object sender, EventArgs e)
{
this.exptxtBox.Text += ">";
}
private void smallerbtn_Click(object sender, EventArgs e)
{
this.exptxtBox.Text += "<";
}
private void Clearbtn_Click(object sender, EventArgs e)
{
this.exptxtBox.Text = "";
}
private void likebtn_Click(object sender, EventArgs e)
{
this.exptxtBox.Text += "Like";
}
private void andbtn_Click(object sender, EventArgs e)
{
this.exptxtBox.Text += "AND";
}
private void orbtn_Click(object sender, EventArgs e)
{
this.exptxtBox.Text += "OR";
}
private void surebtn_Click(object sender, EventArgs e)
{
try
{
if (this.exptxtBox.Text == "") return;
IQueryFilter filter = new QueryFilterClass();
filter.WhereClause = this.exptxtBox.Text;
IFeatureCursor pCursor = fteClss.Search(filter, false);
if (pCursor == null) return;
//ExpandMap(pCursor);
FlashFeature(pCursor);
this.Close();
this.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("表达式错误"+"\n"+ex.Message);
return;
}
}
private void ApplyBtn_Click(object sender, EventArgs e)
{
try
{
if (this.exptxtBox.Text == "") return;
IQueryFilter filter = new QueryFilterClass();
filter.WhereClause = this.exptxtBox.Text;
IFeatureCursor pCursor = fteClss.Search(filter, false);
if (pCursor == null) return;
//ExpandMap(pCursor);
FlashFeature(pCursor);
}
catch (Exception ex)
{
MessageBox.Show("表达式错误" + "\n" + ex.Message);
return;
}
}
private void CancleBtn_Click(object sender, EventArgs e)
{
this.Close();
this.Dispose();
}
}
}
<file_sep>/GisDemo/Command/ExportMap.cs
using System;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Output;
/*============================================================
*
* 本类功能概述:要素转图片
*
*
*
*
*============================================================
*/
namespace GisDemo.Command
{
public class ExportMap
{
//使用静态方法提高代码的复用性
public static void ExportView(IActiveView ActiveView,int _resolution,IGeometry pGeo,int Width,int Height,string pathtxt,bool bRegion)
{
IExport pExort = null;
tagRECT pRect = new tagRECT ();
IEnvelope pEnvelope=pGeo .Envelope ;
string outputType = System.IO.Path.GetExtension(pathtxt).ToLower ();
switch (outputType)
{
case ".jpg":
pExort = new ExportJPEGClass();
break;
case ".bmp":
pExort = new ExportBMPClass();
break;
case ".gif":
pExort = new ExportGIFClass();
break;
case ".tif":
pExort = new ExportTIFFClass();
break;
case ".png":
pExort = new ExportPNGClass();
break;
case ".pdf":
pExort = new ExportPDFClass();
break;
default :
MessageBox.Show("未设置输出格式,默认为jpg格式", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
pExort = new ExportJPEGClass();
break;
}
pExort.ExportFileName = pathtxt;
pRect.left = 0; pRect.top = 0;
pRect.right = Width; pRect.bottom = Height;
//
if (bRegion)
{
ActiveView.GraphicsContainer.DeleteAllElements();
ActiveView.Refresh();
}
//获取输出影像范围的矩形大小
IEnvelope envelope = new EnvelopeClass();
envelope.PutCoords((double)pRect.left, (double)pRect.top, (double)pRect.right, (double)pRect.bottom);
pExort.PixelBounds = envelope;
ActiveView.Output(pExort.StartExporting(), _resolution, ref pRect, pEnvelope, null);
pExort.FinishExporting();
pExort.Cleanup();
}
public static IElement CreateElement(IGeometry pGeometry, IRgbColor linecolor, IRgbColor fillcolor)
{
if (pGeometry == null || linecolor == null || fillcolor == null)
{
return null;
}
IElement pEle = null;
if (pGeometry == null) return null;
//限制只能创建面要素
pEle = new PolygonElementClass();
pEle.Geometry = pGeometry;
IFillShapeElement pFillEle = pEle as IFillShapeElement;
ISimpleFillSymbol symbol = new SimpleFillSymbolClass();
symbol.Color = fillcolor;
symbol.Outline.Color = linecolor;
symbol.Style = esriSimpleFillStyle.esriSFSBackwardDiagonal;
if (symbol == null)
{
return null;
}
pFillEle.Symbol = symbol;
return pEle;
}
public static IRgbColor Getcolor(int red, int blue, int green)
{
IRgbColor color =new RgbColorClass ();
if (red > 255) red = 255;
if (red < 0) red = 0;
if (blue > 255) red = 255;
if (blue < 0) red = 0;
if (green > 255) red = 255;
if (green < 0) red = 0;
color.Red = red;
color.Blue = blue;
color.Green = green;
return color;
}
public static void AddElement(IGeometry pGeo,IActiveView m_ActiveView)
{
if (pGeo == null || m_ActiveView == null) return;
//非静态方法要求对象引用
IRgbColor fillColor = Getcolor(255, 0, 0);
IRgbColor lineColor = Getcolor(255, 255, 255);
IElement pElement = CreateElement(pGeo, lineColor, fillColor);
m_ActiveView.GraphicsContainer.AddElement(pElement, 0);
m_ActiveView.Refresh();
}
}
}
<file_sep>/GisDemo/MainFrm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.Geoprocessor;
using GisDemo.forms;
using GisDemo.Command;
namespace GisDemo
{
//定义委托调用其他窗体控件
public delegate void showResult(double []a,string mapunits,string mouseOperate);
public partial class MainFrm : Form
{
#region 字段变量
ExportMapFrm exportmapFrm = null;//地图导出窗体
frmMeasureResult frmMeasureResult = null;//量测窗体
string pMouseOperate = null;
private string sMapunits = "未知单位";
private double TotalLength;//总长度
private double SegmentLength;//部分長度
IPoint Dwnpoint = null;
IPoint movepnt = null;
INewLineFeedback m_newline = null;
INewPolygonFeedback m_newpolygon = null;
IPointCollection Area_Pocoll = null;
private object missing = Type.Missing;
private IFeatureLayer featureLyr = null;
private AttrbuteFrm attrFrm = null;
private AttrQueryFrm attrqueryFrm = null;
//网络分析窗体
private NetAnalysisFrm netAnalysisFrm = null;
#endregion
public MainFrm()
{
InitializeComponent();
this.axTOOControl.SetBuddyControl(this.axMapcontrol);
this.axToolbarControl.SetBuddyControl(this.axMapcontrol);
}
//事件
private event showResult ShowResultEvent;
private void LoadMxdItem_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.RestoreDirectory = true;
dlg.Filter = "地图文档(*.mxd)|*.mxd";
dlg.Multiselect = false;
if (dlg.ShowDialog() == DialogResult.OK)
{
string filefullpath = dlg.FileName; ;
if (string.IsNullOrEmpty(filefullpath))
return;
//检查地图有效性
if (this.axMapcontrol.CheckMxFile(filefullpath))
{
this.axMapcontrol.LoadMxFile(filefullpath);
}
else
{
MessageBox.Show("打开失败,无效的地图文档", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void DataAddItem_Click(object sender, EventArgs e)
{
try
{
ControlsAddDataCommand addData = new ControlsAddDataCommandClass();
addData.OnCreate(this.axMapcontrol.GetOcx());
addData.OnClick();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void SaveItem_Click(object sender, EventArgs e)
{
try
{
string mxdpath = this.axMapcontrol.DocumentFilename;
IMapDocument mapDoc = new MapDocumentClass();
if (!string.IsNullOrEmpty(mxdpath) && this.axMapcontrol.CheckMxFile(mxdpath))
{
if (mapDoc.get_IsReadOnly(mxdpath))
{
MessageBox.Show("该文档为只读不能保存");
return;
}
}
else
{
//当没有默认路径时
SaveFileDialog dlg = new SaveFileDialog();
dlg.AddExtension = true;
dlg.Filter = "地图文档(*.mxd)|*.mxd";
dlg.RestoreDirectory = true;
dlg.OverwritePrompt = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
mxdpath = dlg.FileName;
}
else
{
return;
}
}
mapDoc.New(mxdpath);
mapDoc.ReplaceContents(this.axMapcontrol.Map as IMxdContents);
mapDoc.Save(mapDoc.UsesRelativePaths, true);
mapDoc.Close();
MessageBox.Show("保存地图文档成功");
}
catch (Exception ex)
{
MessageBox.Show("保存失败"+ex.Message);
}
}
private void SaveAsItem_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.RestoreDirectory = true;
dlg.Filter = "地图文档(*.mxd)|*.mxd";
dlg.AddExtension = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
string mxdpath = dlg.FileName;
if (string.IsNullOrEmpty(mxdpath)) return;
IMapDocument mapDoc = new MapDocumentClass();
mapDoc.New(mxdpath);
mapDoc.ReplaceContents(this.axMapcontrol.Map as IMxdContents);
mapDoc.Save(true, true);
mapDoc.Close();
MessageBox.Show("保存成功");
}
}
catch (Exception ex)
{
MessageBox.Show("保存失败" + ex.Message);
}
}
private void ExportMapItem_Click(object sender, EventArgs e)
{
try
{
}
catch (Exception ex)
{
MessageBox.Show("导出失败" + ex.Message);
}
}
/// <summary>
/// 区域导出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RegionExportItem_Click(object sender, EventArgs e)
{
try
{
this.axMapcontrol.CurrentTool = null;
this.axMapcontrol.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
pMouseOperate = "区域导出";
}
catch (Exception ex)
{
MessageBox.Show("导出地图失败"+ex.Message);
}
}
private void ExportToMapItem_Click(object sender, EventArgs e)
{
try
{
if (exportmapFrm == null || exportmapFrm.IsDisposed)
{
exportmapFrm = new ExportMapFrm(this.axMapcontrol);
}
exportmapFrm.GetGeometry = this.axMapcontrol.ActiveView.Extent;
exportmapFrm.IsRgion = false;
exportmapFrm.Show();
//激活窗体并赋予它焦点
exportmapFrm.Activate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
///鼠标点击操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void axMapcontrol_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
{
Dwnpoint = new PointClass();
Dwnpoint = this.axMapcontrol.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
if (e.button != 1) return;
#region 地图操作
switch (pMouseOperate)
{
case "区域导出":
//删除绘制的图片
this.axMapcontrol.ActiveView.GraphicsContainer.DeleteAllElements();
this.axMapcontrol.ActiveView.Refresh();
IPolygon polygon = DrawPolygon(this.axMapcontrol);
if (polygon == null) return;
ExportMap.AddElement(polygon, this.axMapcontrol.ActiveView);
if (polygon == null) return;
if (exportmapFrm == null || exportmapFrm.IsDisposed)
{
exportmapFrm = new ExportMapFrm(this .axMapcontrol );
exportmapFrm.IsRgion = true;
exportmapFrm.GetGeometry = polygon as IGeometry;
exportmapFrm.Show();
}
exportmapFrm.GetGeometry = polygon;
exportmapFrm.IsRgion = true;
//获取当前控件焦点
exportmapFrm.Activate();
break;
case "MeasureLength":
if (m_newline == null)
{
m_newline = new NewLineFeedbackClass();
m_newline.Display = this.axMapcontrol.ActiveView.ScreenDisplay;
m_newline.Start(Dwnpoint);
TotalLength = 0;
}
else
{
TotalLength += SegmentLength;
m_newline.AddPoint(Dwnpoint);
}
break;
case "MeasureArea":
if (m_newpolygon == null||Area_Pocoll==null )
{
m_newpolygon = new NewPolygonFeedbackClass();
Area_Pocoll = new PolygonClass();
m_newpolygon.Display = this.axMapcontrol.ActiveView.ScreenDisplay;
m_newpolygon.Start(Dwnpoint);
Area_Pocoll.AddPoint(Dwnpoint);
TotalLength = 0;
}
else
{
m_newpolygon.AddPoint(Dwnpoint);
Area_Pocoll.AddPoint(Dwnpoint);
TotalLength += SegmentLength;
}
break;
}
#endregion
}
private IPolygon DrawPolygon(AxMapControl mapcontrol)
{
if (mapcontrol == null) return null;
IGeometry pGeometry = null;
//实例图形绘制对象
IRubberBand rub = new RubberPolygonClass();
pGeometry = rub.TrackNew(mapcontrol.ActiveView.ScreenDisplay, null);
return pGeometry as IPolygon;
}
private void axMapcontrol_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
{
sMapunits = GetMapunits(this.axMapcontrol.Map.MapUnits);
this.barCoortxt.Text = string.Format("当前坐标:X={0:#.###} Y={1:#.###} {2}", e.mapX, e.mapY,sMapunits);
movepnt=new PointClass ();
movepnt .PutCoords (e.mapX ,e .mapY );
switch (pMouseOperate)
{
case "MeasureLength":
if (m_newline != null&&movepnt !=null)
{
m_newline.MoveTo(movepnt);
//计算两点距离
double deltaX = 0;
double deltaY = 0;
deltaX = movepnt.X - Dwnpoint.X;
deltaY = movepnt.Y - Dwnpoint.Y;
SegmentLength = Math.Round(Math.Sqrt(deltaX * deltaX + deltaY * deltaY));
TotalLength = TotalLength + SegmentLength;
if (frmMeasureResult != null)
{
//绑定事件
ShowResultEvent += new showResult(frmMeasureResult.showResult);
ShowResultEvent(new double[] { SegmentLength, TotalLength }, sMapunits,pMouseOperate);
TotalLength = TotalLength - SegmentLength;//鼠标移动到新点重新开始算
}
}
break;
case "MeasureArea":
if (m_newpolygon != null && Area_Pocoll != null)
{
m_newpolygon.MoveTo(movepnt);
IPointCollection pocoll = new PolygonClass();
IGeometry pGeo = null;
IPolygon polygon = null;
ITopologicalOperator topo = null;
for (int i = 0; i < Area_Pocoll.PointCount; i++)
{
pocoll.AddPoint(Area_Pocoll.get_Point(i),missing,missing );
}
if (movepnt == null || movepnt.IsEmpty) return;
pocoll.AddPoint(movepnt, missing, missing);
if (pocoll.PointCount < 3) return;
polygon = pocoll as IPolygon;
if (polygon == null) return;
//多边形闭合
polygon.Close();
pGeo = polygon as IGeometry;
topo = pGeo as ITopologicalOperator;
//使几何图形的拓扑正确
topo.Simplify();
pGeo.Project(this.axMapcontrol.SpatialReference);
IArea area = pGeo as IArea;
if (frmMeasureResult != null && !frmMeasureResult.IsDisposed)
{
ShowResultEvent += new showResult(frmMeasureResult.showResult);
ShowResultEvent(new double[] { area.Area, polygon.Length }, sMapunits, pMouseOperate);
}
}
break;
}
}
#region 私有方法
private string GetMapunits(esriUnits _Mapunit)
{
string sMapunit = string.Empty;
switch (_Mapunit)
{
case esriUnits.esriCentimeters :
sMapunits = "厘米";
break;
case esriUnits.esriDecimalDegrees:
sMapunit = "十进制";
break ;
case esriUnits.esriDecimeters:
sMapunit="分米";
break ;
case esriUnits.esriFeet:
sMapunit ="尺";
break ;
case esriUnits.esriInches:
sMapunit ="英寸";
break ;
case esriUnits.esriKilometers:
sMapunit ="千米";
break ;
case esriUnits.esriMeters:
sMapunit ="米";
break ;
case esriUnits.esriMiles:
sMapunit ="英里";
break ;
case esriUnits.esriMillimeters:
sMapunit ="毫米";
break ;
case esriUnits.esriNauticalMiles:
sMapunit ="海里";
break ;
case esriUnits.esriPoints:
sMapunit="点";
break ;
case esriUnits.esriUnitsLast:
sMapunit="UnitsLast";
break ;
case esriUnits.esriUnknownUnits:
sMapunit ="未知单位";
break ;
case esriUnits.esriYards:
sMapunit ="码";
break ;
default :
break ;
}
return sMapunit;
}
private void DrawElement(IGeometry pGeo)
{
if (pGeo == null) return;
//线
if (pGeo is IPolyline)
{
ISimpleLineSymbol linesymbol = new SimpleLineSymbolClass();
linesymbol.Color = ExportMap.Getcolor(255, 255, 255);
linesymbol.Width = 1;
ILineElement m_LineElement = new LineElementClass();
m_LineElement.Symbol = linesymbol;
//
IElement pEle = m_LineElement as IElement;
pEle.Geometry = pGeo;
this.axMapcontrol.ActiveView.GraphicsContainer.AddElement(pEle, 0);
this.axMapcontrol.ActiveView.Refresh();
}
}
#endregion
private void Calculatebtn_Click(object sender, EventArgs e)
{
this.axMapcontrol.CurrentTool = null;
pMouseOperate = "MeasureLength";
if (frmMeasureResult == null || frmMeasureResult.IsDisposed)
{
frmMeasureResult = new frmMeasureResult();
}
frmMeasureResult.Show();
frmMeasureResult.Activate();
}
private void axMapcontrol_OnDoubleClick(object sender, IMapControlEvents2_OnDoubleClickEvent e)
{
IPoint dblpnt = new PointClass();
dblpnt.PutCoords(e.mapX, e.mapY);
switch (pMouseOperate)
{
case "MeasureLength":
if (m_newline != null)
{
if(dblpnt.IsEmpty ||dblpnt ==null )return ;
IPolyline polyline = m_newline.Stop();
//绘制路径
DrawElement(polyline as IGeometry);
m_newline = null;
//显示长度
if (frmMeasureResult != null &&!frmMeasureResult.IsDisposed)
{
//double deltaX = dblpnt.X - Dwnpoint.X;
//double deltaY = dblpnt.Y - Dwnpoint.Y;
//SegmentLength = Math.Round(Math.Sqrt(deltaX * deltaX + deltaY * deltaY));
ShowResultEvent(new double[] { SegmentLength, TotalLength }, sMapunits,pMouseOperate);
//清除绘制要素
this.axMapcontrol.ActiveView.GraphicsContainer.DeleteAllElements();
}
}
break;
case "MeasureArea":
if (m_newpolygon != null)
{
Area_Pocoll.AddPoint(dblpnt, missing, missing);
IPolygon polygon = m_newpolygon.Stop() as IPolygon;
if (Area_Pocoll.PointCount < 3||polygon.IsEmpty ) return;
polygon.Close();
IGeometry pGeo = polygon as IGeometry;
ITopologicalOperator topo = pGeo as ITopologicalOperator;
topo.Simplify();
pGeo.Project(this.axMapcontrol.SpatialReference);
IArea area = pGeo as IArea;
if (frmMeasureResult != null && !frmMeasureResult.IsDisposed)
{
ShowResultEvent(new double[] { area.Area, polygon.Length }, sMapunits, pMouseOperate);
}
}
break;
}
}
private void AreaCalbtn_Click(object sender, EventArgs e)
{
this.axMapcontrol.CurrentTool = null;
pMouseOperate = "MeasureArea";
if (frmMeasureResult == null || frmMeasureResult.IsDisposed)
{
frmMeasureResult = new frmMeasureResult();
}
frmMeasureResult.Show();
frmMeasureResult.Activate();
}
private void ZoomInTool_Click(object sender, EventArgs e)
{
ZoomInTool tool = new ZoomInTool();
tool.OnCreate(this.axMapcontrol.GetOcx());
this.axMapcontrol.CurrentTool = tool as ITool;
}
private void ZoomOutTool_Click(object sender, EventArgs e)
{
ZoomOutTool tool = new ZoomOutTool();
tool.OnCreate(this.axMapcontrol.GetOcx());
this.axMapcontrol.CurrentTool = tool as ITool;
}
private void PanToolbtn_Click(object sender, EventArgs e)
{
//PanTool tool = new PanTool();
//tool.OnCreate(this.axMapcontrol.GetOcx());
//this.axMapcontrol.CurrentTool = tool as ITool;
ICommand tool = new ControlsMapPanToolClass();
tool.OnCreate(this.axMapcontrol.GetOcx());
this.axMapcontrol.CurrentTool = tool as ITool;
}
private void FullExtentbtn_Click(object sender, EventArgs e)
{
this.axMapcontrol.ActiveView.Extent = this.axMapcontrol.FullExtent;
this.axMapcontrol.ActiveView.Refresh();
}
private void AttributeFrmItem_Click(object sender, EventArgs e)
{
//打开属性表
//实例互斥锁
try
{
attrFrm = AttrbuteFrm.attrbuteFrm(this.axMapcontrol .GetOcx ());
if (attrFrm.IsDisposed)
{
attrFrm = AttrbuteFrm.attrbuteFrmSub(this.axMapcontrol .GetOcx ());
}
attrFrm.FteLyr = featureLyr;
attrFrm.showFrm();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void axTOOControl_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
{
///右键打开菜单项
try
{
if (e.button == 1) return;
esriTOCControlItem pItem = esriTOCControlItem.esriTOCControlItemNone;
IBasicMap pMap = null;
ILayer Lyr = null;
object unk = null;
object data = null;
this.axTOOControl.HitTest(e.x, e.y, ref pItem, ref pMap, ref Lyr, ref unk, ref data);
if (pItem == esriTOCControlItem.esriTOCControlItemLayer &&(Lyr as IFeatureLayer )!=null)
{
this.LyrContxtMenuStrip.Show(MousePosition);
}
if (pItem == esriTOCControlItem.esriTOCControlItemMap)
{
this.MapMenuStrip.Show(MousePosition);
}
featureLyr = Lyr as IFeatureLayer;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void AddDataItem_Click(object sender, EventArgs e)
{
ControlsAddDataCommand cmd = new ControlsAddDataCommandClass();
cmd.OnCreate(this.axMapcontrol.GetOcx());
cmd.OnClick();
}
private void ExpandLyrItem_Click(object sender, EventArgs e)
{
//展开所有图层
for (int i = 0; i < this.axMapcontrol.LayerCount; i++)
{
ILegendInfo m_LengendInfo = this.axMapcontrol.get_Layer(i) as ILegendInfo;
for (int j = 0; j < m_LengendInfo.LegendGroupCount; j++)
{
ILegendGroup pLenGroup = m_LengendInfo.get_LegendGroup(j) as ILegendGroup;
pLenGroup.Visible = true;
}
}
this.axTOOControl.Update();
}
private void FoldLyrsItem_Click(object sender, EventArgs e)
{
//折叠所有图层
for (int i = 0; i < this.axMapcontrol.LayerCount; i++)
{
ILegendInfo m_LengendInfo = this.axMapcontrol.get_Layer(i) as ILegendInfo;
for (int j = 0; j < m_LengendInfo.LegendGroupCount; j++)
{
ILegendGroup pLenGroup = m_LengendInfo.get_LegendGroup(j) as ILegendGroup;
pLenGroup.Visible = false;
}
}
this.axTOOControl.Update();
}
private void OpenLyrsItem_Click(object sender, EventArgs e)
{
//打开所有图层
for (int i = 0; i < this.axMapcontrol.LayerCount; i++)
{
ILayer lyr = this.axMapcontrol.get_Layer(i);
lyr.Visible = true;
}
this.axMapcontrol.ActiveView.Refresh();
}
private void CloseLyrsItem_Click(object sender, EventArgs e)
{
//关闭所有图层
for (int i = 0; i < this.axMapcontrol.LayerCount; i++)
{
ILayer lyr = this.axMapcontrol.get_Layer(i);
lyr.Visible = false;
}
this.axMapcontrol.ActiveView.Refresh();
}
private void LyrExtentItem_Click(object sender, EventArgs e)
{
//缩放至图层
if (featureLyr == null) return;
IEnvelope pEnve = null;
IFeatureClass fteClss = featureLyr.FeatureClass;
IFeatureCursor pCursor = fteClss.Search(null, false);
IFeature pfte;
while ((pfte =pCursor .NextFeature ())!=null )
{
pEnve.Union(pfte.Extent);
}
this.axMapcontrol.ActiveView.Extent = pEnve;
this.axMapcontrol.ActiveView.Refresh();
}
private void LyrToPicItem_Click(object sender, EventArgs e)
{
}
private void ExportToCADItem_Click(object sender, EventArgs e)
{
//
ExportCADfrm frm = new ExportCADfrm();
frm.Mapcontrol = this.axMapcontrol.GetOcx () as IMapControlDefault;
frm.Show();
}
private void AttrQueryItem_Click(object sender, EventArgs e)
{
if (attrqueryFrm == null || attrqueryFrm.IsDisposed)
{
attrqueryFrm = new AttrQueryFrm();
attrqueryFrm.Mapcontrol = this.axMapcontrol.GetOcx() as IMapControlDefault;
attrqueryFrm.Show();
}
}
private void QuerystatisticsItem_Click(object sender, EventArgs e)
{
}
private void Clearselectionbtn_Click(object sender, EventArgs e)
{
ClearselectionTool tool = new ClearselectionTool();
tool.OnCreate(this.axMapcontrol.GetOcx());
this.axMapcontrol.CurrentTool = tool as ITool;
}
private void SelectByPointItem_Click(object sender, EventArgs e)
{
//点击选择
}
private void GeometryNetAnalysis_Click(object sender, EventArgs e)
{
//加载分析窗体
if (netAnalysisFrm == null || netAnalysisFrm.IsDisposed)
{
netAnalysisFrm = new NetAnalysisFrm();
netAnalysisFrm.Mapcontrol = this.axMapcontrol.GetOcx() as IMapControlDefault;
}
netAnalysisFrm.Show();
netAnalysisFrm.Owner = this;
netAnalysisFrm.Activate();
}
}
}
<file_sep>/README.md
# Arcengine
基于.NET+Arcengin的二次开发
<file_sep>/GisDemo/Command/IArcEngineToolbarButton.cs
using System;
using System.Drawing;
namespace Plugin.UIContent.ExtensionsTool
{
public enum ArcEngineToolbarButtonCommandStyle
{
Text,
Image,
TextAndImage
}
public enum ArcEngineToolbarButtonCommandType
{
StandardButton,
ComboBoxCommand,
Separator
}
public interface IArcEngineToolbarButton
{
void AddStringToComboBox(string itemString);
bool Checked { get; set; }
string CommandClassString { get; set; }
ArcEngineToolbarButtonCommandStyle CommandStyle { get; set; }
ArcEngineToolbarButtonCommandType CommandType { get; set; }
bool Enabled { get; set; }
System.Drawing.Image Image { get; set; }
string Name { get; set; }
string Shortcut { get; set; }
string Text { get; set; }
string ToolTipText { get; set; }
}
}
<file_sep>/GisDemo/Command/ZoomInTool.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF.BaseClasses;
using Plugin.UIContent.ExtensionsTool;
/*===================================================
*
* 本类功能概述:地图放大
*
*
* 作者:ZRC 时间:2019/11/14
*===================================================
*/
namespace GisDemo.Command
{
public class ZoomInTool : DciBaseTool
{
private IHookHelper m_Hookhelper = null;
private IMapControlDefault mapControl = null;
public ZoomInTool()
{
this.m_caption = "地图放大";
this.m_category = "地图缩放工具";
string path = Application.StartupPath;
string filepath = path.Substring(0, path.LastIndexOf("\\"));
this.m_cursor = new System.Windows.Forms.Cursor(filepath +"\\"+ "Icon\\Cursors\\ZoomInTool_B_16.cur");
}
public override void OnCreate(object hook)
{
base.OnCreate(hook);
if (hook == null) return;
m_Hookhelper = new HookHelperClass();
m_Hookhelper.Hook = hook;
this.mapControl = m_Hookhelper.Hook as IMapControlDefault;
}
public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
base.OnMouseDown(Button, Shift, X, Y);
if (Button != 1) return;
try
{
IPoint Dwnpoint = this.mapControl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
IEnvelope pEnve = this.mapControl.TrackRectangle() as IEnvelope;
if (!pEnve.IsEmpty)
{
this.mapControl.ActiveView.Extent = pEnve;
this.mapControl.ActiveView.Refresh();
}
if (Dwnpoint != null &&!Dwnpoint.IsEmpty)
{
IEnvelope envelope = this.mapControl.ActiveView.Extent ;
envelope.Expand(0.5, 0.5, true);
this.mapControl.ActiveView.Extent = envelope;
this.mapControl.ActiveView.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
<file_sep>/GisDemo/forms/NetAnalysisFrm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Controls;
using GisDemo.Command;
namespace GisDemo.forms
{
public partial class NetAnalysisFrm : Form
{
public NetAnalysisFrm()
{
InitializeComponent();
traceFlowsolverGen = new TraceFlowSolverClass();
netsolver = traceFlowsolverGen as INetSolver;
}
private IMapControlDefault mapcontrol = null;
public IMapControlDefault Mapcontrol
{
set { mapcontrol = value; }
get { return mapcontrol; }
}
private IGeometricNetwork m_GeometryNetwork = null;
/// <summary>
///执行网络分析的借口
/// </summary>
private ITraceFlowSolverGEN traceFlowsolverGen;
/// <summary>
/// 执行网络分析的另一接口
/// </summary>
private INetSolver netsolver;
/// <summary>
/// 管点标识列表
/// </summary>
private List<IJunctionFlag> listJunctionsFlag =new List<IJunctionFlag> ();
/// <summary>
/// 记录节点边数组
/// </summary>
private List<IEdgeFlag> listEdgeFlag = new List<IEdgeFlag>();
/// <summary>
/// 记录管点障碍列表
/// </summary>
private List<int> JunctionBarrierEIDs = new List<int>();
/// <summary>
/// 记录管线障碍列表
/// </summary>
private List<int> EdgeBarrierEIDs = new List<int>();
#region
private void LoadGeometryNetwork()
{
if (Mapcontrol == null) return;
for (int i = 0; i < Mapcontrol.LayerCount; i++)
{
IFeatureLayer pfteLyr = Mapcontrol.get_Layer(i) as IFeatureLayer;
//获取要素数据集
IFeatureDataset fteDataset = pfteLyr.FeatureClass.FeatureDataset;
//获取网络数据集合
INetworkCollection2 netcoll = fteDataset as INetworkCollection2;
//获取数据集
m_GeometryNetwork = netcoll.get_GeometricNetwork(0);
if (m_GeometryNetwork == null) continue;
else
{
//获取逻辑网络数据集
netsolver.SourceNetwork = m_GeometryNetwork.Network;
//获取几何网络数据名
IDataset dataset = m_GeometryNetwork as IDataset;
if (!this.NetlistCmbx.Items.Contains(dataset.Name))
{
this.NetlistCmbx.Items.Add(dataset.Name);
}
break;
}
}
if (this.NetlistCmbx.Items.Count == 0) return;
this.NetlistCmbx.Text = this.NetlistCmbx.Items[0].ToString();
}
private void showFlowDirection(IFeatureClass featureclass, IUtilityNetworkGEN UtilityNetworkGEN)
{
try
{
//获取要素类的ID号
INetElements netElement = UtilityNetworkGEN as INetElements;
//获取流向
esriFlowDirection flowDirection = new ESRI.ArcGIS.Geodatabase.esriFlowDirection();
//定义当前要素的EID
int currentEID = -1;
IFeatureCursor pCursor = featureclass.Search(null, false);
IFeature pfte = pCursor.NextFeature();
while (pfte != null)
{
currentEID = netElement.GetEID(featureclass.FeatureClassID, pfte.OID, 0, esriElementType.esriETEdge);
flowDirection = UtilityNetworkGEN.GetFlowDirection(currentEID);
//绘制流向
DrawFlowDirection(pfte, Mapcontrol, flowDirection);
pfte = pCursor.NextFeature();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void DrawFlowDirection(IFeature feature, IMapControlDefault mapc,esriFlowDirection flowdir)
{
//获取线段中点
IPolyline polyline = feature.Shape as IPolyline;
IPoint midpoint = new PointClass();
polyline.QueryPoint(esriSegmentExtension.esriNoExtension, polyline.Length / 2, false, midpoint);
//绘制特征符号
IArrowMarkerSymbol arrowSymbol = new ArrowMarkerSymbolClass();
ISimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbolClass();
IElement element = null;
//绘制沿顺着数字化流向
if (flowdir == esriFlowDirection.esriFDWithFlow)
{
arrowSymbol.Size = 12;
arrowSymbol.Color = ExportMap.Getcolor(0, 0, 0);
arrowSymbol.Angle = GetlineAngle(polyline.FromPoint, polyline.ToPoint);
//绘制
element = new MarkerElementClass();
element.Geometry = midpoint;
((IMarkerElement)element).Symbol = arrowSymbol;
//设置绘制元素名称
((IElementProperties)element).Name = "Flow";
}
//方向顺着逆数字化的
if (flowdir == esriFlowDirection.esriFDAgainstFlow)
{
arrowSymbol.Size = 12;
arrowSymbol.Color = ExportMap.Getcolor(0, 0, 0);
arrowSymbol.Angle = GetlineAngle(polyline.FromPoint, polyline.ToPoint);
//绘制
element = new MarkerElementClass();
element.Geometry = midpoint;
((IMarkerElement)element).Symbol = arrowSymbol;
//设置绘制元素名称
((IElementProperties)element).Name = "Flow";
}
//方向未初始化的
if (flowdir == esriFlowDirection.esriFDUninitialized)
{
markerSymbol.Color = ExportMap.Getcolor(0, 0, 0);
markerSymbol.Size = 8;
element = new MarkerElementClass();
element.Geometry = midpoint;
((IMarkerElement)element).Symbol = markerSymbol;
//设置绘制元素名称
((IElementProperties)element).Name = "Flow";
}
//方向未定义的
if (flowdir == esriFlowDirection.esriFDIndeterminate)
{
markerSymbol.Color = ExportMap.Getcolor(0, 0, 0);
markerSymbol.Size = 8;
element = new MarkerElementClass();
element.Geometry = midpoint;
((IMarkerElement)element).Symbol = markerSymbol;
//设置绘制元素名称
((IElementProperties)element).Name = "Flow";
}
mapc.ActiveView.GraphicsContainer.AddElement(element, 0);
}
private double GetlineAngle(IPoint startpoint, IPoint endpoint)
{
double angle = -1;
//在同一水平线上
if (startpoint.Y == endpoint.Y)
{
if (endpoint.X >= startpoint.X)
angle = 0;
else
angle = 180;
}
//在同一竖直线上
if (startpoint.X == endpoint.X)
{
if (endpoint.Y >= startpoint.Y)
angle = 90;
else
angle = 270;
}
//当点位于一、二象限的时候
if (endpoint.Y > startpoint.Y)
{
if (endpoint.X > startpoint.X)
angle = Math.Atan((endpoint.Y - startpoint.Y) / (endpoint.X - startpoint.X));
if(endpoint .X <startpoint .X )
angle = Math.Atan((endpoint.Y - startpoint.Y) / (startpoint.X-endpoint .X ))+90;
}
if (endpoint.Y < startpoint.Y)
{
if (endpoint.X > startpoint.X)
angle = 360-Math.Atan((startpoint.Y - endpoint.Y) / (endpoint.X - startpoint.X));
if (endpoint.X < startpoint.X)
angle = Math.Atan((startpoint.Y - endpoint.Y) / (startpoint.X - endpoint.X)) + 180;
}
return angle;
}
#endregion
private void NetAnalysisFrm_Load(object sender, EventArgs e)
{
//加载集合网络名称
LoadGeometryNetwork();
}
private void FlowDiretionBtn_Click(object sender, EventArgs e)
{
if (m_GeometryNetwork == null) return;
INetwork network = m_GeometryNetwork.Network;
//获取描述网络流向的接口
IUtilityNetworkGEN utilityNetworkGEN = network as IUtilityNetworkGEN;
//获取线要素类
//建立线要素类字典
Dictionary<IFeatureClass, string> dic = new Dictionary<IFeatureClass, string>();
for (int i = 0; i < this.Mapcontrol.LayerCount; i++)
{
IFeatureLayer Lyr = this.Mapcontrol.get_Layer(i) as IFeatureLayer;
if (Lyr == null) continue;
if (Lyr.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
{
if(!dic .ContainsValue (Lyr .FeatureClass .AliasName ))
dic.Add(Lyr.FeatureClass, Lyr .FeatureClass .AliasName );
}
}
//遍历字典
foreach (KeyValuePair<IFeatureClass, string> key in dic)
{
showFlowDirection(key.Key, utilityNetworkGEN);
}
this.Mapcontrol.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, this.Mapcontrol.FullExtent);
}
private void AddJunctionFlagBtn_Click(object sender, EventArgs e)
{
//添加交汇点
AddJunctionFlagTool tool = new AddJunctionFlagTool();
tool.GeometryNetwork = m_GeometryNetwork;
//记录节点集合
tool.ListJunctionFlags = listJunctionsFlag;
tool.OnCreate((object)this.Mapcontrol);
this.Mapcontrol.CurrentTool = tool as ITool;
}
private void AddEdgeFlagBtn_Click(object sender, EventArgs e)
{
AddEdgeTool tool = new AddEdgeTool();
tool.OnCreate((object)this.Mapcontrol);
tool.GeometricNetwork = m_GeometryNetwork;
tool.ListEdgeFlag = listEdgeFlag;
this.Mapcontrol.CurrentTool = tool as ITool;
}
private void AddJunctionBarrierBtn_Click(object sender, EventArgs e)
{
AddJunctionBarrierTool tool = new AddJunctionBarrierTool();
tool.OnCreate(this.Mapcontrol);
tool.GeometricNetwork = m_GeometryNetwork;
tool.JunctionBarrierEIDs = JunctionBarrierEIDs;
this.Mapcontrol.CurrentTool = tool as ITool;
}
private void AddEdgeBarrierBtn_Click(object sender, EventArgs e)
{
AddEdgeBarrierTool tool = new AddEdgeBarrierTool();
tool.OnCreate(this.Mapcontrol);
tool.GemmetricNetwork = m_GeometryNetwork;
tool.EdgeBarrierEIDs = EdgeBarrierEIDs;
this.Mapcontrol.CurrentTool = tool as ITool;
}
private void ResultBtn_Click(object sender, EventArgs e)
{
try
{
#region 设置管点分析分析条件
//为追踪任务分析器设置管点
IJunctionFlag[] arrayJunctionFlag = new IJunctionFlag[listJunctionsFlag.Count];
for (int i = 0; i < arrayJunctionFlag.Length; i++)
arrayJunctionFlag[i] = listJunctionsFlag[i];
traceFlowsolverGen.PutJunctionOrigins(ref arrayJunctionFlag);
//为追踪任务分析器设置管线
IEdgeFlag[] arrayEdgeFlag = new IEdgeFlag[listEdgeFlag.Count];
for (int i = 0; i < arrayEdgeFlag.Length; i++)
traceFlowsolverGen.PutEdgeOrigins(ref arrayEdgeFlag);
//为管点分析器设置障碍点
INetElementBarriersGEN netElementBarriersGEN = new NetElementBarriersClass();
netElementBarriersGEN.Network = m_GeometryNetwork.Network;
if (JunctionBarrierEIDs.Count > 0)
{
int[] junctionBarrierEIDs = new int[JunctionBarrierEIDs.Count];
for (int j = 0; j < junctionBarrierEIDs.Length; j++)
junctionBarrierEIDs[j] = JunctionBarrierEIDs[j];
netElementBarriersGEN.ElementType = esriElementType.esriETJunction;
netElementBarriersGEN.SetBarriersByEID(ref junctionBarrierEIDs);
netsolver.set_ElementBarriers(esriElementType.esriETJunction, netElementBarriersGEN as INetElementBarriers);
}
else //否则将管点设置为空
netsolver.set_ElementBarriers(esriElementType.esriETJunction, null);
//未管点分析器设置障碍线
if (EdgeBarrierEIDs.Count > 0)
{
int[] edgeBarrierEIDs = new int[EdgeBarrierEIDs.Count];
for (int j = 0; j < EdgeBarrierEIDs.Count; j++)
edgeBarrierEIDs[j] = EdgeBarrierEIDs[j];
netElementBarriersGEN.ElementType = esriElementType.esriETEdge;
netElementBarriersGEN.SetBarriersByEID(ref edgeBarrierEIDs);
netsolver.set_ElementBarriers(esriElementType.esriETEdge, netElementBarriersGEN as INetElementBarriers);
}
else //否则将管线设置为空
netsolver.set_ElementBarriers(esriElementType.esriETEdge, null);
#endregion
//定义相关变量
IEnumNetEID junctionEIDs = new EnumNetEIDArrayClass();
IEnumNetEID edgeEIDs = new EnumNetEIDArrayClass();
object[] segmentsCosts = null;
object totalCost = null;
int Counts = -1;
#region 各种几何网络分析的结果
switch (this.AnalysisCategoryCmbx.SelectedIndex)
{
//查询共同祖先
case 0:
traceFlowsolverGen.FindCommonAncestors(esriFlowElements.esriFEJunctionsAndEdges, out junctionEIDs, out edgeEIDs);
break;
//查找相连接的网络要素
case 1:
traceFlowsolverGen.FindFlowElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out junctionEIDs, out edgeEIDs);
break;
//查找网络中连接的环
case 2:
traceFlowsolverGen.FindCircuits(esriFlowElements .esriFEJunctionsAndEdges ,out junctionEIDs ,out edgeEIDs );
break;
//查找未连接的网络要素
case 3:
traceFlowsolverGen.FindFlowUnreachedElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges, out junctionEIDs, out edgeEIDs);
break;
//查找上游路径,同时跟踪耗费
case 4:
Counts = GetSegmentCounts();
segmentsCosts = new object[Counts];
traceFlowsolverGen.FindSource(esriFlowMethod.esriFMUpstream, esriShortestPathObjFn.esriSPObjFnMinSum, out junctionEIDs, out edgeEIDs, Counts, ref segmentsCosts);
break;
//获取网络路径,追踪网络耗费。count比所有的的标识总数少一个,但如果管点和管线标识同时存在的时候该功能不可用
case 5:
if (listEdgeFlag.Count > 0 && listJunctionsFlag.Count > 0)
break;
else if (listJunctionsFlag.Count > 0)
Counts = listJunctionsFlag.Count - 1;
else if (listEdgeFlag.Count > 0)
Counts = listEdgeFlag.Count - 1;
else
break;
segmentsCosts = new object[Counts];
traceFlowsolverGen.FindPath(esriFlowMethod.esriFMConnected, esriShortestPathObjFn.esriSPObjFnMinSum, out junctionEIDs, out edgeEIDs, Counts, ref segmentsCosts);
break;
//下游追踪
case 6:
traceFlowsolverGen.FindFlowElements(esriFlowMethod.esriFMDownstream, esriFlowElements.esriFEJunctionsAndEdges, out junctionEIDs, out edgeEIDs);
break;
//查找上游路径消耗,同时获取网络追踪的耗费
case 7:
totalCost = new object();
traceFlowsolverGen.FindAccumulation(esriFlowMethod.esriFMUpstream, esriFlowElements.esriFEJunctionsAndEdges, out junctionEIDs, out edgeEIDs,out totalCost);
break;
//上游追踪
case 8:
Counts = GetSegmentCounts();
segmentsCosts = new object[Counts];
traceFlowsolverGen.FindSource(esriFlowMethod.esriFMUpstream, esriShortestPathObjFn.esriSPObjFnMinSum, out junctionEIDs, out edgeEIDs, Counts, ref segmentsCosts);
break;
default :
break;
}
#endregion
//绘制结果图像
DrawTraceRsult(junctionEIDs, edgeEIDs);
this.Mapcontrol.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, this.Mapcontrol.ActiveView.Extent);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
#region 私有方法
/// <summary>
/// 根据管线和管点两个列表返回二者数量的总和
/// </summary>
/// <returns>返回列表的总个数</returns>
private int GetSegmentCounts()
{
int count = 0;
if (listEdgeFlag.Count > 0 && listJunctionsFlag.Count > 0)
{
count = listJunctionsFlag.Count + listEdgeFlag.Count;
}
else if (listEdgeFlag.Count > 0)
{
count = listEdgeFlag.Count;
}
else if (listJunctionsFlag.Count > 0)
{
count = listJunctionsFlag.Count;
}
else
count = 0;
return count;
}
private void DrawTraceRsult(IEnumNetEID JunctionEIDs,IEnumNetEID EdgEIDs)
{
if (JunctionBarrierEIDs == null || EdgEIDs == null) return;
INetElements netElements = m_GeometryNetwork.Network as INetElements;
int userClssID = -1;
int userID = -1;
int userSubID = -1;
int eid = -1;
//
IFeatureClass fteClss;
IFeature feature;
//设置管点和管线显示的Symbol
ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbolClass();
simpleMarkerSymbol.Color = Method .Getcolor (255,0,0);
simpleMarkerSymbol.Size = 6;
simpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
ISimpleLineSymbol simpleLineSymbol = new SimpleLineSymbolClass();
simpleLineSymbol.Color = Method.Getcolor(255, 0, 0);
simpleLineSymbol.Width = 2;
simpleLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
IElement element;
//获取管点结果
for (int i = 0; i < JunctionEIDs.Count; i++)
{
eid = JunctionEIDs.Next();
netElements.QueryIDs(eid ,esriElementType.esriETJunction ,out userClssID ,out userID ,out userSubID );
fteClss = GetFteClssByID(userClssID, this.Mapcontrol.Map);
if (fteClss != null)
{
feature = fteClss.GetFeature(userID);
element = new MarkerElementClass();
element.Geometry = feature.Shape;
((IMarkerElement)element).Symbol = simpleMarkerSymbol;
((IElementProperties)element).Name = "Result";
this.Mapcontrol.ActiveView.GraphicsContainer.AddElement(element, 0);
}
}
//获取管线结果
for (int j = 0; j < EdgEIDs.Count; j++)
{
eid = EdgEIDs.Next();
netElements.QueryIDs(eid, esriElementType.esriETEdge, out userClssID, out userID, out userSubID);
fteClss = GetFteClssByID(userClssID,this .Mapcontrol .Map );
if (fteClss != null)
{
feature = fteClss.GetFeature(userID);
element = new LineElementClass ();
element.Geometry = feature.Shape;
((ILineElement )element).Symbol = simpleLineSymbol;
((IElementProperties)element).Name = "Result";
this.Mapcontrol.ActiveView.GraphicsContainer.AddElement(element, 0);
}
}
}
private IFeatureClass GetFteClssByID(int userFeatureClassID, IMap map)
{
IFeatureClass featureclass;
for (int i = 0; i < map.LayerCount; i++)
{
IFeatureLayer Lyr = map.get_Layer(i) as IFeatureLayer;
if (userFeatureClassID == Lyr.FeatureClass.FeatureClassID)
{
featureclass = Lyr.FeatureClass;
return featureclass;
}
}
return null;
}
private void ClearElement(IActiveView actiview ,string elementType)
{
IGraphicsContainer graphicsContainer = actiview.GraphicsContainer;
graphicsContainer.Reset();
IElement element = graphicsContainer.Next();
while (element != null)
{
if (((IElementProperties)element).Name == elementType)
{
graphicsContainer.DeleteElement(element);
}
element = graphicsContainer.Next();
}
actiview.Refresh();
}
#endregion
private void ClearMarkItem_Click(object sender, EventArgs e)
{
//清除标记
ClearElement(this.Mapcontrol.ActiveView, "Flag");
}
private void ClearBarrierItem_Click(object sender, EventArgs e)
{
//清除障碍
ClearElement(this.Mapcontrol.ActiveView, "Barrier");
}
private void ClearResultItem_Click(object sender, EventArgs e)
{
//清除结果
ClearElement(this.Mapcontrol.ActiveView, "Result");
}
private void ClearFlowItem_Click(object sender, EventArgs e)
{
//清除流向
ClearElement(this.Mapcontrol.ActiveView, "Flow");
}
}
}
<file_sep>/GisDemo/Command/ClearselectionTool.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF.BaseClasses;
namespace GisDemo.Command
{
public class ClearselectionTool:BaseTool
{
private IHookHelper m_hookHelper = null;
private IMapControlDefault m_Mapcontrol = null;
public override void OnCreate(object hook)
{
if (hook == null) return;
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
m_Mapcontrol = m_hookHelper.Hook as IMapControlDefault;
}
public ClearselectionTool()
{
this.m_toolTip = "清除所选要素";
this.m_caption = "清除工具";
this.m_category = "清除要素";
}
public override void OnClick()
{
base.OnClick();
if (m_Mapcontrol == null) return;
this.m_Mapcontrol.Map.ClearSelection();
this.m_Mapcontrol.Refresh();
}
}
}
<file_sep>/GisDemo/forms/frmMeasureResult.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.Geoprocessor;
namespace GisDemo.forms
{
public partial class frmMeasureResult : Form
{
public frmMeasureResult()
{
InitializeComponent();
}
public void showResult(double[] a,string sMapunits,string pMouseoperate)
{
if (a == null) return;
if (pMouseoperate == "MeasureLength")
{
this.lblMeasureResult.Text = string.Format("当前线段长度:{0:.###}{1};\r\n总长度: {2:.###}{1}", a[0], sMapunits, a[1]);
}
if (pMouseoperate == "MeasureArea")
{
this.lblMeasureResult.Text = string.Format("当前面积大小:{0:.###}{1};\r\n总长度: {2:.###}{1}", a[0], sMapunits, a[1]);
}
}
}
}
<file_sep>/GisDemo/forms/ExportCADfrm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF.BaseClasses;
using GisDemo.Command;
namespace GisDemo.forms
{
public partial class ExportCADfrm : Form
{
public ExportCADfrm()
{
InitializeComponent();
}
private IFeatureLayer fteLyr = null;
private IMapControlDefault mapcontrol = null;
public IMapControlDefault Mapcontrol { get { return mapcontrol; } set { mapcontrol = value; } }
private void Filebrowserbtn_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.AddExtension = true;
dlg.RestoreDirectory = true;
dlg.Filter = "CAD文件(*.dwg)|*.dwg";
dlg.FileName = fteLyr.Name;
if (dlg.ShowDialog() == DialogResult.OK)
{
string foldpath = dlg.FileName.Substring(0, dlg.FileName.LastIndexOf("\\"));
if (!System.IO.Directory.Exists(foldpath))
{
System.IO.Directory.CreateDirectory(foldpath);
}
this.pathtxt.Text = dlg.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Lyrlist_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < this.Mapcontrol.LayerCount; i++)
{
if (this.Lyrlist.SelectedItem.ToString()== this.Mapcontrol.get_Layer(i).Name)
{
fteLyr = this.Mapcontrol.get_Layer(i) as IFeatureLayer;
break;
}
}
}
private void ExportCADfrm_Load(object sender, EventArgs e)
{
if (Mapcontrol == null) return;
for (int i = 0; i < this.Mapcontrol.LayerCount; i++)
{
this.Lyrlist.Items.Add(Mapcontrol.get_Layer(i).Name);
}
}
private void Exportbtn_Click(object sender, EventArgs e)
{
ExportCADTool tool = new ExportCADTool();
tool.Mapcontrol = this.Mapcontrol;
if (string.IsNullOrEmpty(this.pathtxt.Text))
{
MessageBox.Show("请选择输出路径");
return;
}
string lsshp=System .IO .Path.GetDirectoryName (this .pathtxt.Text)+"\\"+this .Lyrlist .SelectedItem.ToString ()+".shp";
tool.ShpToCAD(fteLyr.FeatureClass,lsshp, this.pathtxt .Text, this.TypeCmbx.Text);
this.Dispose();
}
private void cancelBtn_Click(object sender, EventArgs e)
{
this.Close();
this.Dispose();
}
}
}
<file_sep>/GisDemo/Method/Method.cs
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.NetworkAnalysis;
using System.Collections.Generic;
using ESRI.ArcGIS.Geodatabase;
/*================================================
*
*
*
* 本类实现功能概述;提供程序所需静态方法,提高代码的复用性
*
*
* 作者:ZRC 时间:2019/11/28
*================================================
*/
namespace GisDemo
{
public class Method
{
public static IRgbColor Getcolor(int red, int blue, int green)
{
IRgbColor color = new RgbColorClass();
if (red > 255) red = 255;
if (red < 0) red = 0;
if (blue > 255) red = 255;
if (blue < 0) red = 0;
if (green > 255) red = 255;
if (green < 0) red = 0;
color.Red = red;
color.Blue = blue;
color.Green = green;
return color;
}
}
}
<file_sep>/GisDemo/Command/PanTool.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF.BaseClasses;
using Plugin.UIContent.ExtensionsTool;
/*=========================================================
*
* 功能概述:漫游
*
* ========================================================
*/
namespace GisDemo.Command
{
public class PanTool:DciBaseTool
{
private IHookHelper m_hookHelper = null;
private IMapControlDefault mapcontrol = null;
public PanTool()
{
this.m_caption = "漫游";
this.m_category = "地图操作";
string path = Application.StartupPath;
string filepath = path.Substring(0, path.LastIndexOf("\\"));
this.m_cursor = new System.Windows.Forms.Cursor(filepath + "\\" + "Icon\\Cursors\\PanTool_B_16.cur");
}
public override void OnCreate(object hook)
{
base.OnCreate(hook);
if (hook == null) return;
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
mapcontrol = m_hookHelper.Hook as IMapControlDefault;
this.mapcontrol.Pan();
}
public override void OnClick()
{
base.OnClick();
}
}
}
<file_sep>/GisDemo/Command/AddJunctionBarrierTool.cs
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.NetworkAnalysis;
using System.Collections.Generic;
using ESRI.ArcGIS.Geodatabase;
using GisDemo.Command;
namespace GisDemo.Command
{
public class AddJunctionBarrierTool:BaseTool
{
private IHookHelper m_hookHelper = null;
private IGeometricNetwork geometricNetwork;
private List<int> junctionBarrierEIDs;
public IGeometricNetwork GeometricNetwork
{
set { geometricNetwork = value; }
}
public List<int> JunctionBarrierEIDs
{
set { junctionBarrierEIDs = value; }
}
public AddJunctionBarrierTool()
{
this.m_caption = "添加障碍点";
this.m_category = "几何网络分析";
this.m_message = "在地图上点击管点,将其添加为网络分析障碍的点要素";
this.m_toolTip = "添加分析管点";
string path = Application.StartupPath;
string filepath = path.Substring(0, path.LastIndexOf("\\"));
this.m_cursor = new System.Windows.Forms.Cursor(filepath + "\\" + "Icon\\Cursors\\UtilityNetworkBarrierJunctionAddTool16_1.cur");
}
public override void OnCreate(object hook)
{
if (hook == null) return;
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
}
public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
if (Button != 1) return;
IPoint inPoint = new PointClass();
inPoint = this.m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
IMap map = this.m_hookHelper.FocusMap;
//获取最邻近的要素ID
IPointToEID pointToEID = new PointToEIDClass();
pointToEID.GeometricNetwork = geometricNetwork;
pointToEID.SourceMap = map;
pointToEID.SnapTolerance = 10;
int nearstJunctionEID = -1;
IPoint outPoint = new PointClass();
pointToEID.GetNearestJunction(inPoint, out nearstJunctionEID, out outPoint);
if (outPoint == null || outPoint.IsEmpty) return;
junctionBarrierEIDs.Add(nearstJunctionEID);
//绘制要素
DrawElement(outPoint);
}
private void DrawElement(IPoint point)
{
if (point == null || point.IsEmpty) return;
ISimpleMarkerSymbol MarkerSymbol = new SimpleMarkerSymbolClass();
MarkerSymbol.Size = 8;
MarkerSymbol.Color = Method.Getcolor(255,0, 0);
//绘制形状为十字丝
MarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSX;
IElement element = new MarkerElementClass();
element.Geometry = point;
((IMarkerElement)element).Symbol = MarkerSymbol;
//设置添加要素点名称
((IElementProperties)element).Name = "Barrier";
this.m_hookHelper.ActiveView.GraphicsContainer.AddElement(element, 0);
this.m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, this.m_hookHelper.ActiveView.Extent);
}
}
}
<file_sep>/GisDemo/forms/AttrbuteFrm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF.BaseClasses;
namespace GisDemo.forms
{
public partial class AttrbuteFrm : Form
{
private IMapControlDefault mapcontrol = null;
private IFeatureLayer fteLyr = null;
public IFeatureLayer FteLyr
{
set { fteLyr = value; }
get { return fteLyr; }
}
const int pagesize = 50;
int currentpage = 1;
int pagecount = 0;
List<IFeature> fte_list = new List<IFeature>();
List<string> fieldNames = new List<string>() { "Shape", "ID" };
public int Currentpage
{
get
{
if (currentpage == pagecount&&pagecount >1)
{
this.propertyNavigator.MoveLastItem .Enabled = false;
this.propertyNavigator.MoveNextItem.Enabled = false;
this.propertyNavigator.MoveFirstItem.Enabled = true;
this.propertyNavigator.MovePreviousItem.Enabled = true;
}
if (currentpage == 1&&pagecount >1)
{
this.propertyNavigator.MoveFirstItem.Enabled = false;
this.propertyNavigator.MovePreviousItem.Enabled = false;
this.propertyNavigator.MoveNextItem.Enabled = true;
this.propertyNavigator.MoveLastItem.Enabled = true;
}
if (pagecount == 1)
{
this.propertyNavigator.MoveFirstItem.Enabled = false;
this.propertyNavigator.MovePreviousItem.Enabled = false;
this.propertyNavigator.MoveNextItem.Enabled = false;
this.propertyNavigator.MoveLastItem.Enabled = false;
}
return currentpage;
}
set
{
currentpage = value;
}
}
private AttrbuteFrm()
{
InitializeComponent();
}
private static AttrbuteFrm _instance = null;
//获取实例互斥锁,readonly修饰动态声明常量
private static readonly object _MetuexLocker = new object();
public static AttrbuteFrm attrbuteFrm(object hook)
{
if (_instance == null)
{
lock (_MetuexLocker)
{
if (_instance == null)
{
_instance = new AttrbuteFrm();
}
}
}
_instance.mapcontrol = hook as IMapControlDefault;
return _instance;
}
public static AttrbuteFrm attrbuteFrmSub(object hook)
{
lock (_MetuexLocker)
{
if (_instance == null)
{
_instance = new AttrbuteFrm();
}
if (_instance.IsDisposed)
{
_instance = new AttrbuteFrm();
}
}
_instance.mapcontrol = hook as IMapControlDefault;
return _instance;
}
//显示窗体函数
public void showFrm()
{
if (_instance == null) return;
try
{
IntPtr ptr = new IntPtr( mapcontrol.ActiveView .ScreenDisplay.hWnd );
this.Owner = Form.FromHandle(ptr).FindForm();
this.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void AttrbuteFrm_Load(object sender, EventArgs e)
{
try
{
//获取要素总量
if (fteLyr == null) return;
this.Text = fteLyr.Name.ToString();
IFeatureClass fteClss = FteLyr.FeatureClass;
IFeatureCursor pCusor = fteClss.Search(null, false);
IFeature feature = pCusor.NextFeature();
while(feature != null)
{
fte_list.Add(feature);
feature = pCusor.NextFeature();
}
pagecount =(int) Math.Ceiling((double)fte_list.Count / pagesize);
this.propertyNavigator.CountItem.Text = pagecount.ToString();
this.propertyNavigator.PositionItem.Text = Currentpage.ToString();
bindData(fteLyr, Currentpage );
this.lblcurpage.Text = "每页总数";
this.pageCountTxt.Text = pagesize.ToString();
this.pageCountTxt.ReadOnly = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void bindData(IFeatureLayer Lyr,int cutpage)
{
if (Lyr == null)
return;
DataTable table = new DataTable();
//加载
IFeatureClass fteclss = Lyr.FeatureClass;
for (int i = 0; i < fteclss.Fields.FieldCount; i++)
{
table.Columns.Add(fteclss.Fields.get_Field(i).AliasName);
}
this.propertyGridView.DataSource = table;
//判断索引是否大于要素数量
int srow = (cutpage - 1) * pagesize >= fte_list.Count ? fte_list.Count-1: (cutpage - 1) * pagesize;
int endrow = (cutpage * pagesize - 1)>=fte_list .Count?fte_list .Count-1:(cutpage *pagesize -1);
//添加数据
for (; srow <= endrow; srow++)
{
DataRow row = table.NewRow();
for (int j = 0; j < fteclss.Fields.FieldCount; j++)
{
row[j] = fte_list[srow].get_Value(j).ToString();
}
table.Rows.Add(row);
}
#region 设置表格样式
this.propertyGridView.ClearSelection();
//排序问题
for (int i = 0; i < this.propertyGridView.Columns.Count; i++)
{
this.propertyGridView.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;
}
int width = 0;
for (int j = 0; j < this.propertyGridView.ColumnCount; j++)
{
this.propertyGridView.AutoResizeColumn(j, DataGridViewAutoSizeColumnMode.AllCells);
width += this.propertyGridView.Columns[j].Width;
}
//判断与窗体大小
if (width > this.propertyGridView.Width)
{
this.propertyGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
}
else
{
this.propertyGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
this.propertyGridView.AllowUserToAddRows = false;
for (int j = 0; j < this.propertyGridView.ColumnCount; j++)
{
string colname = this.propertyGridView.Columns[j].Name;
if (fieldNames.Contains(colname))
{
this.propertyGridView.Columns[j].Visible = false;
}
}
#endregion
this.propertyGridView.Refresh();
}
private void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)
{
if (Currentpage == 1) return;
Currentpage = 1;
bindData(fteLyr, Currentpage);
}
private void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)
{
if (Currentpage == 1) return;
Currentpage--;
bindData(fteLyr, Currentpage);
}
private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
{
if (Currentpage == pagecount) return;
Currentpage++;
bindData(fteLyr ,Currentpage );
}
private void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)
{
if (Currentpage == pagecount) return;
Currentpage = pagecount;
bindData(fteLyr, Currentpage);
}
}
}
<file_sep>/GisDemo/Command/ZoomOutTool.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF.BaseClasses;
using Plugin.UIContent.ExtensionsTool;
/*===========================================
*
* 本类功能概述:地图缩小功能
*
*
*作者:ZRC 时间:2019/11/14
*================================================
*/
namespace GisDemo.Command
{
public class ZoomOutTool:DciBaseTool
{
private IHookHelper m_hookHelper = null;
private IMapControlDefault mapcontrol = null;
public ZoomOutTool()
{
this.m_caption = "地图缩小";
this.m_category = "地图操作";
string path = Application.StartupPath;
string filepath = path.Substring(0, path.LastIndexOf("\\"));
this.m_cursor = new System.Windows.Forms.Cursor(filepath + "\\" + "Icon\\Cursors\\ZoomOutTool_B_16.cur");
}
public override void OnCreate(object hook)
{
base.OnCreate(hook);
if(hook == null) return;
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
mapcontrol = m_hookHelper.Hook as IMapControlDefault;
}
public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
base.OnMouseDown(Button, Shift, X, Y);
if (Button != 1) return;
IPoint Dwnpoint = this.mapcontrol.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
IEnvelope pEnve = this.mapcontrol.TrackRectangle();
if (!pEnve.IsEmpty)
{
IEnvelope currentExtent, NewIEN = null;
currentExtent =this.mapcontrol.ActiveView .Extent;
double dXmin = 0, dYmin = 0, dXmax = 0, dYmax = 0, dHeight = 0, dWidth = 0;
dWidth = currentExtent.Width * (currentExtent.Width / pEnve.Width);
dHeight = currentExtent.Height * (currentExtent.Height / pEnve.Height);
dXmin = currentExtent.XMin - ((pEnve.XMin - currentExtent.XMin) * (currentExtent.Width / pEnve.Width));
dYmin = currentExtent.YMin - ((pEnve.YMin - currentExtent.YMin) * (currentExtent.Height / pEnve.Height));
dXmax = dXmin + dWidth;
dYmax = dYmin + dHeight;
NewIEN = new EnvelopeClass();
NewIEN.PutCoords(dXmin, dYmin, dXmax, dYmax);
this.mapcontrol.ActiveView.Extent = NewIEN;
this.mapcontrol.ActiveView.Refresh();
}
if (Dwnpoint != null &&!Dwnpoint.IsEmpty)
{
IEnvelope envelope = this.mapcontrol.ActiveView.Extent;
envelope.Expand(2, 2, true);
this.mapcontrol.ActiveView.Extent = envelope;
this.mapcontrol.ActiveView.Refresh();
}
}
}
}
<file_sep>/GisDemo/forms/ExportMapFrm.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using GisDemo.Command;
namespace GisDemo.forms
{
public partial class ExportMapFrm : Form
{
#region 字段属性
private IActiveView _Actiview = null;
private IGeometry pGeometry = null;
private string savePath = null;
private bool bRegion = false;
public IGeometry GetGeometry
{
set
{
pGeometry = value;
}
}
public bool IsRgion
{
set
{
bRegion = value;
}
}
#endregion
public ExportMapFrm(AxMapControl _Mapcontrol)
{
InitializeComponent();
_Actiview = _Mapcontrol.ActiveView;
}
private void ExportMap_Load(object sender, EventArgs e)
{
InitExportFrm();
}
private void InitExportFrm()
{
//获取分辨率
Cmxresolution.Text = _Actiview.ScreenDisplay.DisplayTransformation.Resolution.ToString();
Cmxresolution.Items.Add(Cmxresolution.Text);
//判断全部还是部分导出
if (bRegion)
{
IEnvelope envelope = pGeometry.Envelope;
tagRECT pRect = new tagRECT();
_Actiview.ScreenDisplay.DisplayTransformation.TransformRect(envelope, ref pRect, 9);
if (Cmxresolution.Text != null)
{
this.widthtxt.Text = pRect.right.ToString();
this.heighttxt.Text = pRect.bottom.ToString();
}
}
else
{
if (Cmxresolution.Text != null)
{
this.widthtxt.Text = this._Actiview.ExportFrame.right.ToString();
this.heighttxt.Text = this._Actiview.ExportFrame.bottom.ToString();
}
}
}
private void folderBrowserbtn_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = "jpg|bmp|gif|tif|png|pdf";
dlg.Filter = "JPGE 文件(*.jpg)|*.jpg|BMP 文件(*.bmp)|*.bmp|GIF 文件(*.gif)|*.gif|TIF 文件(*.tif)|*.tif|PNG 文件(*.png)|*.png|PDF 文件(*.pdf)|*.pdf";
dlg.RestoreDirectory = true;
dlg.AddExtension = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
savePath = dlg.FileName;
this.pathtxt.Text = dlg.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 实现导出地图功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Exportbtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Cmxresolution.Text))
{
MessageBox.Show("请输入分辨率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(this.pathtxt.Text))
{
MessageBox.Show("请选择路径", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (Convert.ToInt32(Cmxresolution.Text) == 0)
{
MessageBox.Show("请输入正确的分辨率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int resolution = int.Parse(this.Cmxresolution.Text);
int width = int.Parse(this.widthtxt.Text);
int height = int.Parse(this.heighttxt.Text);
ExportMap.ExportView(_Actiview, resolution, pGeometry, width, height,this .pathtxt.Text , bRegion);
_Actiview.GraphicsContainer.DeleteAllElements();
_Actiview.Refresh();
MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ExportMapFrm_FormClosed(object sender, FormClosedEventArgs e)
{
this._Actiview.GraphicsContainer.DeleteAllElements();
this._Actiview.Refresh();
Dispose();
}
private void Cancelbtn_Click(object sender, EventArgs e)
{
this._Actiview.GraphicsContainer.DeleteAllElements();
this._Actiview.Refresh();
Dispose();
}
private void Cmxresolution_SelectedIndexChanged(object sender, EventArgs e)
{
//分辨率变化输出图形也随之变化
double resolution = (int)this._Actiview.ScreenDisplay.DisplayTransformation.Resolution;
if (Cmxresolution.Text == "")
{
this.widthtxt.Text = "";
this.heighttxt.Text = "";
return;
}
if (bRegion)
{
IEnvelope envelope = pGeometry.Envelope;
tagRECT pRECT = new tagRECT();
_Actiview.ScreenDisplay.DisplayTransformation.TransformRect(envelope, ref pRECT, 9);
if (Cmxresolution.Text != "")
{
this.widthtxt.Text = Math.Round(pRECT.right * (double.Parse(Cmxresolution.Text) / resolution)).ToString();
this.heighttxt.Text = Math.Round(pRECT.bottom * (double.Parse(Cmxresolution.Text) / resolution)).ToString();
}
}
else
{
this.widthtxt.Text = Math.Round(this._Actiview.ExportFrame.right * (double.Parse(Cmxresolution.Text) / resolution)).ToString();
this.widthtxt.Text = Math.Round(this._Actiview.ExportFrame.bottom * (double.Parse(Cmxresolution.Text) / resolution)).ToString();
}
}
}
}
<file_sep>/GisDemo/Command/ExportCADTool.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.ConversionTools;
using ESRI.ArcGIS.Geoprocessing;
/*============================================================
* 主要思路:1、图层要素转为SHP文件
* 2、SHP文件转为CAD文件
* 3、删除SHP文件
*
*功能概述:图层转CAD
*
* 作者:ZRC 日期:2019/11/17
*============================================================
*/
namespace GisDemo.Command
{
public class ExportCADTool
{
private IMapControlDefault mapcontrol = null;
public IMapControlDefault Mapcontrol { get { return mapcontrol; } set { mapcontrol = value; } }
public void FclssToShp(IFeatureClass fteClss,string lsshp)
{
if (fteClss == null||string .IsNullOrEmpty (lsshp )) return;
string filename = System.IO.Path.GetFileName(lsshp);
string filepath = System.IO.Path.GetDirectoryName(lsshp);
if (!System.IO.Directory.Exists(filepath))
{
System.IO.Directory.CreateDirectory(filepath);
}
//释放空间
using (ComReleaser comreleaser = new ComReleaser())
{
IDataset indataset = fteClss as IDataset;
IWorkspaceFactory pWorkfactory = new ShapefileWorkspaceFactoryClass();
IFeatureWorkspace fteWsp = pWorkfactory.OpenFromFile(filepath, 0) as IFeatureWorkspace;
IWorkspace inwsp = indataset.Workspace;
IFeatureClassName inFCName = indataset.FullName as IFeatureClassName;
//
IWorkspace outWsp = fteWsp as IWorkspace;
IDataset outdataset = outWsp as IDataset;
IWorkspaceName outWspName = outdataset.FullName as IWorkspaceName;
IFeatureClassName outFCName = new FeatureClassNameClass();
IDatasetName outDstName = outFCName as IDatasetName;
outDstName.WorkspaceName = outWspName;
outDstName.Name = fteClss.AliasName.ToString();
//检查字段的合法性
IFieldChecker checker = new FieldCheckerClass();
checker.InputWorkspace = inwsp;
checker.ValidateWorkspace = outWsp;
IFields fileds = fteClss.Fields;
IFields outfields = null;
IEnumFieldError error = null;
checker.Validate(fileds, out error, out outfields);
//转换为SHP
IFeatureDataConverter convert = new FeatureDataConverterClass();
convert.ConvertFeatureClass(inFCName, null, null, outFCName, null, outfields, "", 100, 0);
}
}
public void ShpToCAD(IFeatureClass fteclss, string lsshp, string cadpath,string FormatType)
{
//先转为shp文件
try
{
FclssToShp(fteclss, lsshp);
//shp转为要素
Geoprocessor gp = new Geoprocessor();
gp.OverwriteOutput = true;
ExportCAD export = new ExportCAD();
export.in_features = lsshp;
export.Output_Type = FormatType;
export.Output_File = cadpath;
export.Ignore_FileNames = "1";
export.Append_To_Existing = "1";
IGeoProcessorResult result = gp.Execute(export, null) as IGeoProcessorResult;
//转换成功是否将CAD文件添加进图层
if (result.Status == esriJobStatus.esriJobSucceeded)
{
if (MessageBox.Show("转换成功,是否添加至图层", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
{
string filepath = System.IO.Path.GetDirectoryName(cadpath);
string filename = System.IO.Path.GetFileName(cadpath);
CadWorkspaceFactory cadwspFcy = new CadWorkspaceFactoryClass();
IFeatureWorkspace fteWsp = cadwspFcy.OpenFromFile(filepath, 0) as IFeatureWorkspace;
//转换为CAD工作空间
ICadDrawingWorkspace CadWsp = fteWsp as ICadDrawingWorkspace;
ICadDrawingDataset CadDataset = CadWsp.OpenCadDrawingDataset(filename);
ICadLayer cadLyr = new CadLayerClass();
cadLyr.CadDrawingDataset = CadDataset;
cadLyr.Name = filename;
this.Mapcontrol.AddLayer(cadLyr, 0);
this.Mapcontrol.Refresh();
}
}
shpDel(lsshp);
}
catch (Exception ex)
{
MessageBox.Show("转换失败" + ex.Message);
}
}
public void shpDel(string shppath)
{
if (string.IsNullOrEmpty(shppath)) return;
if (!System.IO.File.Exists(shppath))
return;
using (ComReleaser comreleaser = new ComReleaser())
{
IWorkspaceFactory WspFac = new ShapefileWorkspaceFactoryClass ();
IFeatureWorkspace fteWsp = WspFac.OpenFromFile(System.IO.Path.GetDirectoryName(shppath), 0) as IFeatureWorkspace;
IFeatureClass fClss = fteWsp.OpenFeatureClass(System.IO.Path.GetFileName(shppath));
IFeatureLayer fteLyr = new FeatureLayerClass();
IDataset dataset = null;
if (fClss == null) return;
fteLyr.FeatureClass = fClss;
fteLyr.Name = fteLyr.FeatureClass.AliasName;
//定义数据集,保证处于编辑状态
dataset = fteLyr.FeatureClass as IDataset;
dataset.Delete();
}
}
}
}
<file_sep>/GisDemo/Command/AddEdgeBarrierTool.cs
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.NetworkAnalysis;
using System.Collections.Generic;
using ESRI.ArcGIS.Geodatabase;
namespace GisDemo.Command
{
public class AddEdgeBarrierTool:BaseTool
{
private IGeometricNetwork geometricNetwork = null;
private IHookHelper m_hookHelper = null;
private List<int> edgeBarrierEIDs;
public IGeometricNetwork GemmetricNetwork
{
set { geometricNetwork = value; }
}
public List<int> EdgeBarrierEIDs
{
set { edgeBarrierEIDs = value; }
}
public AddEdgeBarrierTool()
{
this.m_caption = "添加交汇边";
this.m_category = "几何网络分析";
this.m_message = "在地图上点击管线,将其添加为网络分析的线要素";
this.m_toolTip = "添加分析管线";
string path = Application.StartupPath;
string filepath = path.Substring(0, path.LastIndexOf("\\"));
this.m_cursor = new System.Windows.Forms.Cursor(filepath + "\\" + "Icon\\Cursors\\UtilityNetworkBarrierAdd16_1.cur");
}
public override void OnCreate(object hook)
{
if (hook == null) return;
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
}
public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
if (Button != 1) return;
IPoint inPoint = new PointClass();
inPoint = this.m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
//
IPointToEID pointToEID = new PointToEIDClass();
pointToEID.GeometricNetwork = geometricNetwork;
pointToEID.SourceMap = m_hookHelper.FocusMap;
pointToEID.SnapTolerance = 10;
//
int nearestEID = -1;
double percent = -1;
IPoint outPoint = new PointClass();
pointToEID.GetNearestEdge(inPoint, out nearestEID, out outPoint,out percent);
//
if (outPoint.IsEmpty || outPoint == null) return;
edgeBarrierEIDs.Add(nearestEID);
//绘制图形
DrawElement(outPoint);
}
private void DrawElement(IPoint point)
{
if (point == null || point.IsEmpty) return;
ISimpleMarkerSymbol MarkerSymbol = new SimpleMarkerSymbolClass();
MarkerSymbol.Size = 8;
MarkerSymbol.Color = Method.Getcolor(255,0, 0);
//绘制形状为十字丝
MarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSX;
IElement element = new MarkerElementClass();
element.Geometry = point;
((IMarkerElement)element).Symbol = MarkerSymbol;
//设置添加要素点名称
((IElementProperties)element).Name = "Barrier";
this.m_hookHelper.ActiveView.GraphicsContainer.AddElement(element, 0);
this.m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, this.m_hookHelper.ActiveView.Extent);
}
}
}
<file_sep>/GisDemo/Command/DciBaseTool.cs
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using GISLibrarys.Utility;
namespace Plugin.UIContent.ExtensionsTool
{
public class DciBaseTool:BaseTool
{
private ICommand _baseCommand = null;
private string _customBitmapFile;
private string _customCaption;
private string _customCategory;
private string _customCursorFile;
private string _customMessage;
private string _customTooltip;
private IntPtr _gdiBitmap;
private int _lastClickButton = 0;
private string _referCommandString = null;
private IArcEngineToolbarButton _toolButton = null;
private bool _useCustomBitmap = false;
private bool _useCustomCaption = false;
private bool _useCustomCategory = false;
private bool _useCustomCursor = false;
private bool _useCustomMessage = false;
private bool _useCustomTooltip = false;
protected IHookHelper m_HookHelper = null;
protected int m_shift = 0;
private static void ArcGISCategoryRegistration(Type registerType)
{
ControlsCommands.Register(string.Format(@"HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID));
}
private static void ArcGISCategoryUnregistration(Type registerType)
{
ControlsCommands.Unregister(string.Format(@"HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID));
}
private static object COMCreateObject(string sProgID)
{
Type typeFromProgID = Type.GetTypeFromProgID(sProgID);
if (typeFromProgID != null)
{
return Activator.CreateInstance(typeFromProgID);
}
return null;
}
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
~DciBaseTool()
{
this.m_HookHelper = null;
if (base.m_bitmap != null)
{
DeleteObject(this._gdiBitmap);
base.m_bitmap.Dispose();
base.m_bitmap = null;
}
if (base.m_cursor != null)
{
base.m_cursor.Dispose();
base.m_cursor = null;
}
}
public override bool Deactivate()
{
if (this._baseCommand != null)
{
return (this._baseCommand as ITool).Deactivate();
}
return base.Deactivate();
}
public override void OnClick()
{
if (this._baseCommand != null)
{
this._baseCommand.OnClick();
}
else
{
base.OnClick();
}
IntPtr handle = new IntPtr(this.m_HookHelper.ActiveView.ScreenDisplay.hWnd);
Control.FromHandle(handle).Focus();
}
public override bool OnContextMenu(int X, int Y)
{
if (this._baseCommand != null)
{
return (this._baseCommand as ITool).OnContextMenu(X, Y);
}
return base.OnContextMenu(X, Y);
}
public override void OnCreate(object hook)
{
try
{
if (this._referCommandString != null)
{
this._baseCommand = COMCreateObject(this._referCommandString) as ICommand;
this._baseCommand.OnCreate(hook);
}
this.m_HookHelper = new HookHelper();
this.m_HookHelper.Hook=hook;
}
catch
{
}
}
public override void OnDblClick()
{
if (this._baseCommand != null)
{
(this._baseCommand as ITool).OnDblClick();
}
else
{
base.OnDblClick();
}
}
public override void OnKeyDown(int keyCode, int Shift)
{
if (this._baseCommand != null)
{
(this._baseCommand as ITool).OnKeyDown(keyCode, Shift);
}
else
{
base.OnKeyDown(keyCode, Shift);
}
if (this.m_shift != Shift)
{
this.m_shift = Shift;
int num = this.Cursor;
}
}
public override void OnKeyUp(int keyCode, int Shift)
{
if (this._baseCommand != null)
{
(this._baseCommand as ITool).OnKeyUp(keyCode, Shift);
}
else
{
base.OnKeyUp(keyCode, Shift);
}
if (this.m_shift != 0)
{
this.m_shift = 0;
int num = this.Cursor;
}
}
public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
this._lastClickButton = Button;
if (this._baseCommand != null)
{
(this._baseCommand as ITool).OnMouseDown(Button, Shift, X, Y);
}
else
{
base.OnMouseDown(Button, Shift, X, Y);
}
}
public override void OnMouseMove(int Button, int Shift, int X, int Y)
{
if (this._baseCommand != null)
{
(this._baseCommand as ITool).OnMouseMove(Button, Shift, X, Y);
}
else
{
base.OnMouseMove(Button, Shift, X, Y);
}
}
public override void OnMouseUp(int Button, int Shift, int X, int Y)
{
if (this._baseCommand != null)
{
(this._baseCommand as ITool).OnMouseUp(Button, Shift, X, Y);
}
else
{
base.OnMouseUp(Button, Shift, X, Y);
}
}
public override void Refresh(int hDC)
{
if (this._baseCommand != null)
{
(this._baseCommand as ITool).Refresh(hDC);
}
else
{
base.Refresh(hDC);
}
}
private void RefreshButtonUI()
{
if (this._toolButton != null)
{
System.Drawing.Bitmap bitmap = Image.FromHbitmap(new IntPtr(this.Bitmap));
bitmap.MakeTransparent();
this._toolButton.Image = bitmap;
this._toolButton.ToolTipText = this.Tooltip;
this._toolButton.Text = this.Caption;
}
}
private void RefreshCursor()
{
if (((this.m_HookHelper != null) && (this.m_HookHelper.ActiveView != null)) && (this.m_HookHelper.ActiveView.ScreenDisplay != null))
{
IntPtr handle = new IntPtr(this.m_HookHelper.ActiveView.ScreenDisplay.hWnd);
Control.FromHandle(handle).Cursor = new System.Windows.Forms.Cursor(new IntPtr(this.Cursor));
}
}
[ComVisible(false), ComRegisterFunction]
private static void RegisterFunction(Type registerType)
{
ArcGISCategoryRegistration(registerType);
}
[ComUnregisterFunction, ComVisible(false)]
private static void UnregisterFunction(Type registerType)
{
ArcGISCategoryUnregistration(registerType);
}
//public IArcEngineToolbarButton BindingButton
//{
// set
// {
// this._toolButton = value;
// }
//}
public override int Bitmap
{
get
{
if (this._useCustomBitmap)
{
if (base.m_bitmap == null)
{
string pathFromFullFilePath = FileOrDirEnhancedTools.GetPathFromFullFilePath(Assembly.GetExecutingAssembly().Location);
base.m_bitmap = Image.FromFile(Path.Combine(pathFromFullFilePath, this._customBitmapFile)) as System.Drawing.Bitmap;
base.m_bitmap.MakeTransparent(Color.Magenta);
this._gdiBitmap = base.m_bitmap.GetHbitmap();
}return this._gdiBitmap.ToInt32();
}
return base.Bitmap;
}
}
public override string Caption
{get
{
if (this._useCustomCaption)
{
return this._customCaption;
}
if (this._baseCommand != null)
{
return this._baseCommand.Caption;
}
return base.Caption;
}
}
public override string Category
{
get
{
if (this._useCustomCategory)
{
return this._customCategory;
}
if (this._baseCommand != null)
{
return this._baseCommand.Category;
}
return base.Category;
}
}
public override bool Checked
{
get
{
if (this._baseCommand != null)
{
return this._baseCommand.Checked;
}
return base.Checked;
}
}
public override int Cursor
{
get
{
if (this._useCustomCursor)
{
if (base.m_cursor == null)
{
string pathFromFullFilePath = FileOrDirEnhancedTools.GetPathFromFullFilePath(Assembly.GetExecutingAssembly().Location);
base.m_cursor = new System.Windows.Forms.Cursor(Path.Combine(pathFromFullFilePath, this._customCursorFile));
}
return base.m_cursor.Handle.ToInt32();
}
if (this._baseCommand != null)
{
return (this._baseCommand as ITool).Cursor;
}
return base.Cursor;
}
}
public string CustomBitmapFile
{
get
{
return this._customBitmapFile;
}
set
{
if (this._customBitmapFile != value)
{
this._customBitmapFile = value;
this._useCustomBitmap = true;
if (base.m_bitmap != null)
{
base.m_bitmap.Dispose();
base.m_bitmap = null;
}
this.RefreshButtonUI();
}
}
}
public string CustomCaption
{
get
{
return this._customCaption;
}
set
{
if (this._customCaption != value)
{
this._customCaption = value;
this._useCustomCaption = true;
this.RefreshButtonUI();
}
}
}
public string CustomCategory
{
get
{
return this._customCategory;
}
set
{
if (this._customCategory != value)
{
this._customCategory = value;
this._useCustomCategory = true;
}
}
}
public string CustomCursorFile
{
get
{
return this._customCursorFile;
}
set
{
if (this._customCursorFile != value)
{
this._customCursorFile = value;
this._useCustomCursor = true;
if (base.m_cursor != null)
{
base.m_cursor.Dispose();
base.m_cursor = null;
}
this.RefreshCursor();
}
}
}
public string CustomMessage
{
get
{
return this._customMessage;
}
set
{
if (this._customMessage != value)
{
this._customMessage = value;
this._useCustomMessage = true;
}
}
}
public string CustomTooltip
{
get
{
return this._customTooltip;
}
set
{
if (this._customTooltip != value)
{
this._customTooltip = value;
this._useCustomTooltip = true;
this.RefreshButtonUI();
}
}
}
public override bool Enabled
{
get
{
if (this._baseCommand != null)
{
return this._baseCommand.Enabled;
}
return base.Enabled;
}
}
public override int HelpContextID
{
get
{
if (this._baseCommand != null)
{
return this._baseCommand.HelpContextID;
}
return base.HelpContextID;
}
}
public override string HelpFile
{
get
{
if (this._baseCommand != null)
{
return this._baseCommand.HelpFile;
}
return base.HelpFile;
}
}
public virtual bool IgnoreMapContextMenu
{
get
{
return false;
}
}
public int LastClickButton
{
get
{
return this._lastClickButton;
}
}
public override string Message
{
get
{
if (this._useCustomMessage)
{
return this._customMessage;
}
if (this._baseCommand != null)
{
return this._baseCommand.Message;
}
return base.Message;
}
}
public override string Name
{
get
{
if (this._baseCommand != null)
{
return this._baseCommand.Name;
}
return base.Name;
}
}public string ReferCommandString
{
get
{
return this._referCommandString;
}
set
{
if (this._referCommandString != value)
{
this._referCommandString = value;
}
}
}
public override string Tooltip
{
get
{
if (this._useCustomTooltip)
{
return this._customTooltip;
}
if (this._baseCommand != null)
{
return this._baseCommand.Tooltip;
}
return base.Tooltip;
}
}
}
}
| 01e219923ebc32d1b2a7d37e0354e0701c901e75 | [
"Markdown",
"C#"
] | 21 | C# | Raydextert/Arcengine | e829618ba306cf1e54a98d9048292513283ae118 | 1cb1731f8d02e30064e3ab39eea9ab09537102f9 |
refs/heads/master | <file_sep>function verificar(){
var nome = document.forms['formulario']['nome'].value;
var email = document.forms['formulario']['email'].value;
var assunto = document.forms['formulario']['assunto'].value;
var mensagem = document.forms['formulario']['mensagem'].value;
// verifica se estão em branco
if(nome == '' || email == '' || assunto == '' || mensagem == ''){
alert('Todos os campos são obrigatórios!');
return false;
}
// remove espaços em branco
nome = nome.trim();
email = email.trim();
assunto = assunto.trim();
mensagem = mensagem.trim();
// capitalize
nome = nome[0].toUpperCase() + nome.slice(1);
assunto = assunto[0].toUpperCase() + assunto.slice(1);
mensagem = mensagem[0].toUpperCase() + mensagem.slice(1);
}<file_sep><?php session_start(); ?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Facilita UDF</title>
<!-- fontawesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link href="css/main.css" rel="stylesheet" type="text/css" screen="media" />
<link href="img/logo.png" rel="shortcut icon" type="img/png" />
</head>
<body>
<div id="container">
<?php
try{
$conn = new PDO("mysql:host=localhost;dbname=professores;charset=utf8", 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "Select * FROM descricao";
$dados = $conn->query($sql);
$qtd = $dados->columnCount();
while($qtd != 0){
foreach($dados as $dado){
?>
<a href="pages/usuario.php?id=<?php echo $dado['id']; ?>" class="box-professor">
<?php
if(empty($dado['arquivo'])){
print("<i class='fas fa-user'></i>");
}else{
print("<img src='img/perfil/".$dado['arquivo'].".jpg' />");
}
?>
<div class="descricao">
<p><?php echo $dado['nome']; ?></p>
<p><?php echo $dado['area']; ?></p>
<abbr title="<?php echo $dado['email']; ?>"><?php echo substr($dado['email'], 0, 25).'...'; ?></abbr>
</div>
</a>
<?php
}
$qtd -= 1;
}
}catch(PDOException $e){
print('erro: '.$e->getMessage());
}
$conn = null;
?>
</div>
<div>
</body>
</html><file_sep><?php
session_start();
$_SESSION['id_prof'] = $_GET['id'];
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Facilita UDF</title>
<!-- fontawesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link href="css/style.css" rel="stylesheet" type="text/css" screen="media" />
<link href="img/logo.png" rel="shortcut icon" type="img/png" />
</head>
<body>
<form method="POST" action="mensagem.php" name="formulario">
<div id="box-nome">
<label for="nome">Nome:</label>
<input type="text" name="nome" id="nome" placeholder="seu nome" />
</div>
<div id="box-email">
<label for="email">Email:</label>
<input type="text" name="email" id="email" placeholder="seu email" />
</div>
<div id="box-assunto">
<label for="assunto">Assunto</label>
<input type="text" name="assunto" id="assunto" placeholder="assunto aqui" />
</div>
<div id="box-mensagem">
<label for="mensagem">Mensagem:</label>
<textarea name="mensagem" id="mensagem"></textarea>
</div>
<div id="box-botao">
<button type="submit" onclick="return verificar()">enviar email</button>
</div>
</form>
<p>verifique se os dados foram digitados corretamente.</p>
<a href="../index.php">voltar</a>
<script src="../js/main.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Facilita UDF</title>
</head>
<body>
<?php
session_start();
$id_prof = $_SESSION['id_prof'];
try{
$conn = new PDO('mysql:host=localhost;dbname=professores', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM descricao WHERE id='{$id_prof}'";
$dados = $conn->query($sql);
foreach($dados as $dado){
$_SESSION['nomeProf'] = $dado['nome'];
}
}catch(PDOException $e){
print('erro: '.$e->getMessage());
}
require('../PHPMailer/Exception.php');
require('../PHPMailer/OAuth.php');
require('../PHPMailer/PHPMailer.php');
require('../PHPMailer/POP3.php');
require('../PHPMailer/SMTP.php');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = false; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '<EMAIL>'; // SMTP username
$mail->Password = '<PASSWORD>'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom($_POST['email'], $_POST['nome']);
$mail->addAddress($dado['email'], $dado['nome']); // Add a recipient
$mail->addReplyTo($_POST['email'], $_POST['nome']);
// $mail->addCC('<EMAIL>');
// $mail->addBCC('<EMAIL>');
//Attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $_POST['assunto'];
$mail->Body = $_POST['mensagem'];
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
$status = true;
} catch (Exception $e) {
$status = false;
}
if($status == true){
print('Seu email para '.$_SESSION['nomeProf'].' foi enviado com sucesso.');
}else{
print('Erro ao enviar o email para '.$_SESSION['nomeProf']);
}
?>
<a href="../index.php">voltar</a>
</body>
</html> | 81a20a4054a609dc0763d3bf322182f73e55210b | [
"JavaScript",
"PHP"
] | 4 | JavaScript | Allyson1602/emailProfessor | e223cbf58dd385ea1860a5fbea80f72c33a49e27 | 2c31207d2a52de22aad0f6ba2dfb066f3c2cf98e |
refs/heads/master | <file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GetCurrentDirectoryUnitTestProject
{
[TestClass]
public class GetCurrentDirectoryUnitTest
{
[TestMethod]
public void TestMethod1()
{
Console.WriteLine(System.IO.Directory.GetCurrentDirectory());
}
}
}
<file_sep># CSharp-GetCurrentDirectory
There is a demo of System.IO.Directory.GetCurrentDirectory method in 3 cases.
1. NUnit test
2. Console application
3. Unit test project
<file_sep>using System;
using NUnit.Framework;
namespace GetCurrentDirectoryClassLibrary
{
[TestFixture]
class GetCurrentDirectoryTest
{
[Test]
public void NUnitTest()
{
Console.WriteLine(System.IO.Directory.GetCurrentDirectory());
}
}
}
| 49ef529bc3fd1039ff1eefdafedbef1545fe21bd | [
"Markdown",
"C#"
] | 3 | C# | ChrisWongAtCUHK/CSharp-GetCurrentDirectory | 9c4d7dea91b42651f13f186e71bc79b830f98115 | 5086b03cbde256d91875bb7e3685097345a1f4bc |
refs/heads/master | <file_sep> //gcc -pthread -o servers $(mysql_config --cflags) servers.c $(mysql_config --libs)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>
#include <strings.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <pthread.h>
#include <mysql.h>
#include <netdb.h>
#define PORTNUM1 2343
#define READ 0 /* The index of the read end of the pipe */
#define WRITE 1 /* The index of the write end of the pipe */
#define RECEIVE_BUFF_LEN 128
#define SEND_BUFF_LEN 128
#define SERVICE_PORT_NO 5004
#define QLEN 15
#define FIRST_RECEIVE_MSG "PING"
#define PROMPT_USERNAME "Enter Username: "
#define PROMPT_CREATE_USERNAME "Would you like to create an account?"
#define PROMPT_PASSWORD "Enter Password: "
#define NOTIFY_WRONG_PASSWORD "Incorrect password provided. Terminating Connection."
#define NOTIFY_ACC_CREATION "Your account has been created"
#define NOTIFY_INVALID_FILESIZE "Invalid Filesize"
#define NOTIFY_SENDFILE "Sendfile"
#define NOTIFY_CORRECT_PASSWORD "You are logged in."
#define NOTIFY_FILE_NOT_FOUND "The requested file is not found."
#define DELIMITER '|'
#define maxFileSize 30000
#define COUNTER_NAME "next_user_ID"
typedef struct threadData {
int sock;
struct sockaddr_in cli_addr;
char *buffer;
} threadData;
pthread_mutex_t mutexlock;
char currentCity[3];
void *tcpClientHandler(void *tcp);
char sRedunt[] = "redunt";
char sMaster[]= "master";
char sInit[]="init";
char status[20] = "init"; /*making status as initial at the begining status init : initial*/
int beatMissCount =0;
int hbNotRecieved;
int hbSent =0;
int hbReply =0;
int fd [2], bytesRead; /*for pipe read/write for interprocess communication*/
void communicate(char status[20])
{
close(fd[READ]); /* Close unused end */
write (fd[WRITE],status, strlen (status) + 1); /* include NULL*/
close (fd[WRITE]); /* Close used end*/
return;
}
void checkStatus (int portno1)
{
char p1[128];
char p2[128];
int optval;
char rbuf[20]="NULL";
char hb[20]="echo";
char rhb[20]="NULL";
int conn=0;
int recvByte=0;
int connection;
struct sockaddr_in server1_addr;
struct sockaddr_in server2_addr;
struct sockaddr_in s2;
socklen_t socksize = sizeof(struct sockaddr_in);
int sfd,sfd1;
sfd = socket(AF_INET,SOCK_STREAM,0); /* creating socket for status*/
if (sfd <0)
printf("Please enter the priority of this server: priority value for each server shoud be different(higher value high priority) \n" );
printf("Please enter the priority of this server: \n" );
scanf("%s", p1);
memset(&server1_addr, 0, sizeof(server1_addr));
memset(&server2_addr, 0, sizeof(server2_addr));
server1_addr.sin_family = AF_INET;
server1_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server1_addr.sin_port = htons(portno1);
server2_addr.sin_family = AF_INET;
server2_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
server2_addr.sin_port = htons(portno1);
if((connection=connect (sfd, (struct sockaddr*)&server2_addr , sizeof(struct sockaddr)))==0)
{
printf("connect successful \n");
send(sfd,status,sizeof(status),0);
recvByte = recv(sfd,rbuf,sizeof(rbuf),0);
if (recvByte<0)
printf("error in connect recv 12323 \n");
if (strcmp(rbuf,"init")==0 && strcmp(status,"init")==0)
{
send(sfd,p1,sizeof(p1),0);
recv(sfd,p2,sizeof(p2),0);
printf("priority of other connect server is %s \n",p2);
if (strcmp(p1,p2)>0 )
{
strcpy(status,"master");
printf("statusof this server is: %s \n",status);
communicate(status);
}
if (strcmp(p1,p2)<0 )
{
strcpy(status,"redunt");
printf("this server is redundant server \n");
}
else if (strcmp(p1,p2)==0 )
printf("priority level of master ans redundant cannot be same\n");
}
else if (strcmp(rbuf,"master")==0 && strcmp(status,"init")==0)
{
strcpy(status,"redunt");
printf("There is already server : %s RUNNING..!!! \n",rbuf);
printf("status of this server set to :%s irrespective of priority\n",status);
}
while (strcmp(status,"redunt")==0) // loop it as long as this server status is redundant
{
printf("initial status %s , sending my status :::: hb: %s\n", status,hb);
send(sfd,hb,sizeof(hb),0);
printf("first HB sent/recv is %s\n",rhb);
recvByte = recv(sfd,rhb,sizeof(rhb),0);
printf("first HB recv is %s\n",rhb);
if (strcmp(rhb,hb)==0)
{
printf("sending/recieving echo from master \n");
while (beatMissCount <5)
{
send(conn,hb,sizeof(hb),0);
recvByte = recv(sfd,rhb,sizeof(rhb),0);
if(recvByte <0)
{
beatMissCount++;
printf("hearbeat send/miss failure: %d \n",beatMissCount);
}
else if (strcmp(rhb,"echo")==0) {
beatMissCount =0;
printf("echo response recived correctly\n");
strcpy(rhb,"NULL");
}
else
{
beatMissCount++;
printf("hearbeat send/miss failure: %d \n",beatMissCount);
}
sleep (1);
}
strcpy(status,"master");
printf("this is server status has changed to : %s \n",status);
communicate(status); //send this status master to parent process
}
else
{
printf("recived message from other server is %s \n", rhb);
}
sleep (1);
} // end of redundant server loop
close(sfd);
}
if (connection!=0 || strcmp(status,"master")==0) //enter if connection is failed or status changed to master
{
printf("Waiting for other server... \n");
sfd1 = socket(AF_INET,SOCK_STREAM,0);
if (sfd<0)
printf("error in creating sfd1 \n");
optval = 1;
setsockopt(sfd1, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int));
bind(sfd1,(struct sockaddr*)&server1_addr,sizeof(server1_addr)); //x==0
if (listen(sfd1,1)<0)
printf("error in creating status listening \n");
while(1)
{
conn = accept(sfd1, (struct sockaddr*)&s2 , &socksize);
if (conn <0)
printf("error in accepting \n");
else
{
printf("accept successful \n");
recvByte = recv(conn,rbuf,sizeof(rbuf),0);
printf("responding:: %s, status: %s\n",rbuf,status);
send(conn,status,sizeof(status),0);
if (strcmp(rbuf,"init")==0 && strcmp(status,"init")==0)
{
recv(conn,p2,sizeof(p2),0);
send(conn,p1,sizeof(p1),0);
printf("priority of other server is %s \n",p2);
if (strcmp(p1,p2)>0 )
{
strcpy(status,"master");
printf("status of this server is: %s \n",status);
communicate(status);
}
if (strcmp(p1,p2)<0 )
{
strcpy(status,"redunt");
printf("Status of Server is: %s \n",status);
}
else if (strcmp(p1,p2)==0 )
printf("priority level of both servers cannot be same\n");
}
else if (strcmp(rbuf,"init")==0 && strcmp(status,"master")==0)
{
printf("I am already master and shall remain %s irrespective of priority \n",status);
}
else
{
printf("error listening_1010101:: rbuf: %s, status:: %s \n",rbuf,status);
}
while (strcmp(status,"master")==0) ///loop while status = master of the server
{
recvByte = recv(conn,rbuf,sizeof(rbuf),0);
if(recvByte <0)
{
beatMissCount++;
printf("hearbeat send/miss failure: %d \n",beatMissCount);
}
else
{
if (strcmp(rbuf , "init")==0 && strcmp(status,"master")==0)
{
send(conn,status,sizeof(status),0);
}
else if (strcmp(rbuf,"echo")==0 && strcmp(status,"master")==0)
{
send(conn,rbuf,sizeof(rbuf),0);
while (beatMissCount <5)
{
recvByte = recv(conn,rhb,sizeof(rhb),0);
send(conn,rhb,sizeof(rhb),0);
if(recvByte <0)
{
beatMissCount++;
printf("hearbeat send/miss failure: %d \n",beatMissCount);
}
else
{
beatMissCount =0;
strcpy(rhb,"NULL");
}
}
}
else
{
printf(" recived message from other server is %s \n", rbuf);
}
}
}// end of while status = master loop
}
}
close(sfd1);
}
}
int mainServer(char* cityArg)
{
int optval;
threadData *tcpData;
pthread_t threads[100];
pthread_attr_t ta;
pthread_mutex_init(&mutexlock, NULL);
pthread_attr_init(&ta);
int listenfd = 0;
int connfd = 0;
int portno;
struct sockaddr_in serv_addr;
unsigned int clilen;
struct sockaddr_in cli_addr;
strcpy(currentCity,cityArg);
if (strcmp(currentCity,"SJ")==0)
{
portno = 10000;
}
else if (strcmp(currentCity,"SF")==0)
{
portno = 10001;
}
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd < 0)
{
printf("Error creating the listening socket.");
return -1;
}
optval = 1;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int));
//zero out the structures and buffers
bzero(&serv_addr, sizeof(serv_addr));
//set the server attributes
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
//bind the listening socket
if(bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
{
printf("Could not bind the listening socket.\n");
return -1;
}
//set the listening queue
if(listen(listenfd, QLEN) == -1)
{
printf("Failed to listen\n");
return -1;
}
//set up thread
(void) pthread_attr_init(&ta);
(void) pthread_attr_setdetachstate(&ta, PTHREAD_CREATE_DETACHED);
printf("main server ready to accept request from client\n");
int connections = 0;
clilen = sizeof(cli_addr);
while(1)
{
if (connections == 99){
connections = 0;
}
connfd = accept(listenfd, (struct sockaddr*)&cli_addr,&clilen);
if (connfd < 0)
{
if (errno == EINTR)
continue;
printf("accept: %s\n", strerror(errno));
return -1;
}
tcpData = malloc(sizeof(tcpData));
tcpData->sock = connfd;
tcpData->cli_addr = cli_addr;
if(pthread_create(&threads[connections], &ta, tcpClientHandler,(void *)tcpData)){
printf("Failed while creating TCP thread\n");
}
connections = connections +1;
}
close(connfd);
pthread_mutex_destroy(&mutexlock);
pthread_attr_destroy(&ta);
}
void *tcpClientHandler(void *tcp){
struct sockaddr_in cli_addr;
struct sockaddr_in serv_addr;
struct hostent *server1 = gethostbyname("localhost");
threadData *tcpDetail = tcp;
int newsockfd = tcpDetail->sock;
int sent,received,sockfd,sent2,n2;
char *client_addr;
cli_addr = tcpDetail->cli_addr;
char buffFile[15000] = {};
char RecvBuffer[254] = {};
char SendBuffer[254] = {};
char passingBuffer[254] = {};
char * typeOfClient;
char * city;
char * busNumber;
char * busNumber2;
char * busNumber3;
char tempBusNum[30];
MYSQL *conn;
MYSQL *conn1;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "<PASSWORD>";
char *database = "proj207";
conn = mysql_init(NULL);
char str[80];
char type2Rec[80]={};
char sendBuf[254];
char temp[254];
client_addr = inet_ntoa(cli_addr.sin_addr);
printf("client address is %s \n",client_addr);
printf("Client's port is %d\n",ntohs(cli_addr.sin_port));
printf("============================================================\n");
bzero(RecvBuffer,254);
bzero(SendBuffer,254);
bzero(sendBuf,254);
received = recv(newsockfd,RecvBuffer,254,0);
if (received < 0)
{
printf("Error while receiving\n");
printf("The Server has been stopped\n");
exit(1);
}
strcpy(passingBuffer,RecvBuffer);
pthread_mutex_lock (&mutexlock);
typeOfClient = strtok(RecvBuffer,"~");
pthread_mutex_unlock (&mutexlock);
if (strcmp(typeOfClient,"type1") == 0) {
//this is a type client
pthread_mutex_lock (&mutexlock);
city =strtok(NULL,"~");
busNumber= strtok(NULL,"~");
pthread_mutex_unlock (&mutexlock);
printf("Type: %s \n",typeOfClient);
printf("city: %s \n",city);
printf("bus number: %s \n",busNumber);
if(strcmp(city,currentCity)==0)
{
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0))
{
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
strcpy(str,"select * from bus_details where bus_no =");
strcat(str,busNumber);
if (mysql_query(conn, str))
{
//finish_with_error(conn);
printf("failed to query\n");
}
res = mysql_use_result(conn);
while ((row = mysql_fetch_row(res)) != NULL){
printf("%s \n", row[1]);
strcpy(sendBuf,row[1]);
break;
}
mysql_free_result(res);
mysql_close(conn);
}
else {
// server acting as client
printf("Going to get details from different server\n");
sockfd = socket(AF_INET,SOCK_STREAM,0);
if (sockfd < 0)
{
printf("Error while creating the socket\n");
exit(1);
}
server1 = gethostbyname("localhost");
if (server1 == NULL)
{
printf("No such host exist\n");
exit(1);
}
bzero((char *)&serv_addr,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server1-> h_addr,(char *)&serv_addr.sin_addr.s_addr,server1->h_length);
if(strcmp(city,"SF")==0){
serv_addr.sin_port = htons(10001);
}
else if(strcmp(city,"LA")==0){
serv_addr.sin_port = htons(10002);
}
else if(strcmp(city,"SD")==0){
serv_addr.sin_port = htons(10003);
}
else if(strcmp(city,"SJ")==0){
serv_addr.sin_port = htons(10000);
}
if(connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))< 0)
{
printf("Error: Failed to connect\n");
exit(1);
}
sent2 = send (sockfd,passingBuffer,254,0);
if(sent2<0)
{
printf("Error: Failed to send\n");
exit(1);
}
bzero(sendBuf,100);
n2 = recv(sockfd,sendBuf,254,0);
if (n2< 0)
{
printf("Error: Failed while reading\n");
exit(1);
}
close(sockfd);
//server acting as client
}
if (strcmp(sendBuf,"")==0 ){
strcpy(sendBuf,"Requested bus is not available");
}
if (strcmp(sendBuf,"1")==0 ){
strcpy(sendBuf,"Bassett");
}
sent = send (newsockfd,sendBuf,254,0);
if(sent<0)
{
printf("Error while sending\n");
printf("The Server has been stopped\n");
exit(1);
}
printf("Done with processing client\n");
close(newsockfd);
}
else if(strcmp(typeOfClient,"type2") == 0){
pthread_mutex_lock (&mutexlock); city =strtok(NULL,"~");
busNumber= strtok(NULL,"~"); busNumber2= strtok(NULL,"~");
busNumber3= strtok(NULL,"~"); pthread_mutex_unlock
(&mutexlock);
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
strcpy(str,"select * from bus_details where bus_no in (");
strcat(str,busNumber);
strcat(str,",");
strcat(str,busNumber2);
strcat(str,",");
strcat(str,busNumber3);
strcat(str,")");
if (mysql_query(conn, str)) {
//finish_with_error(conn);
printf("failed to query\n");
}
int count=0;
res = mysql_use_result(conn);
while ((row = mysql_fetch_row(res)) != NULL){
printf("%s \n", row[1]);
count++;
printf("~\n");
if(count == 1) strcpy(tempBusNum,busNumber);
else if(count == 2) strcpy(tempBusNum,busNumber2);
else if(count == 3) strcpy(tempBusNum,busNumber3);
else{
strcpy(tempBusNum,"Error :");
}
strcat(type2Rec,"\n");
strcat(type2Rec,tempBusNum);
strcat(type2Rec," : ");
strcat(type2Rec,row[1]);
printf("%s",type2Rec);
}
sent = send (newsockfd,type2Rec,254,0);
if(sent<0)
{
printf("Error while sending\n");
printf("The Server has been stoppedddd\n");
exit(1);
}
printf("Done with processing client\n");
close(newsockfd);
mysql_free_result(res);
mysql_close(conn);
}
else if(strcmp(typeOfClient,"set") == 0){
printf("setting notification\n");
pthread_mutex_lock (&mutexlock);
busNumber= strtok(NULL,"~");
pthread_mutex_unlock (&mutexlock);
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
strcpy(str,"select * from bus_details where bus_no =");
strcat(str,busNumber);
if (mysql_query(conn, str))
{
printf("failed to query\n");
}
res = mysql_use_result(conn);
while ((row = mysql_fetch_row(res)) != NULL)
{
printf("%s \n", row[1]);
strcpy(sendBuf,row[1]);
break;
}
sent = send (newsockfd,sendBuf,254,0);
if(sent<0)
{
printf("Error while sending\n");
printf("The Server has been stopped\n");
exit(1);
}
printf("Done with processing client\n");
strcpy(temp,sendBuf);
int cond = 1;
mysql_free_result(res);
while(cond==1){
if (mysql_query(conn, str)) {
printf("failed to query\n");
}
res = mysql_use_result(conn);
while ((row = mysql_fetch_row(res)) != NULL){
strcpy(sendBuf,row[1]);
break;
}
if(strcmp(sendBuf,temp)==0){
}
else{
sent = send (newsockfd,sendBuf,254,0);
if(sent<0)
{
printf("Error while sending\n");
printf("The Server has been stopped_changed\n");
break;
}
strcpy(temp,sendBuf);
}
mysql_free_result(res);
sleep(3);
}
close(newsockfd);
}
else if(strcmp(typeOfClient,"report") == 0){
pthread_mutex_lock (&mutexlock);
busNumber= strtok(NULL,"~");
pthread_mutex_unlock (&mutexlock);
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
strcpy(str,"select * from bus_record where bus_number =");
strcat(str,busNumber);
if (mysql_query(conn, str)) {
printf("failed to query\n");
}
res = mysql_use_result(conn);
while ((row = mysql_fetch_row(res)) != NULL)
{
strcat(buffFile,row[0]);
strcat(buffFile," was at location ");
strcat(buffFile,row[1]);
strcat(buffFile," at time ");
strcat(buffFile,row[2]);
strcat(buffFile,"\n");
}
mysql_free_result(res);
mysql_close(conn);
if(send(newsockfd,buffFile,15000,0)<0)
{
printf("Failed to proess\n");
}
}
printf("End of prog\n");
}
<file_sep> #include <gtk/gtk.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <pthread.h>
const gchar *USERNAME;
const gchar *PASSWORD;
const gchar *ENTERBUSNUMBER;
const gchar *fileok = "Succesfully generated file.";
#define SJPORTNO 10000
gboolean enteredUsername(GtkEntry *e1, gpointer user)
{
USERNAME = gtk_entry_get_text ((e1));
return FALSE;
}
gboolean enteredPassword(GtkEntry *e2, gpointer user)
{
PASSWORD = gtk_entry_get_text ((e2));
return FALSE;
}
gboolean enterbusnumber(GtkEntry *e1, gpointer user)
{
ENTERBUSNUMBER = gtk_entry_get_text ((e1));
return FALSE;
}
void submit_clicked(GtkButton *b1, gpointer entry1)
{
if (strcmp(USERNAME,"ADMIN") == 0 && strcmp(PASSWORD,"<PASSWORD>") == 0)
{
GtkBuilder *builderNew;
GtkWidget *windowNew;
GError *err = NULL;
gtk_init (NULL, NULL);
builderNew = gtk_builder_new ();
if(0 == gtk_builder_add_from_file (builderNew, "type3.glade", &err))
{
/* Print out the error. You can use GLib's message logging */
fprintf(stderr, "Error adding build from file. Error: %s\n", err->message);
/* Your error handling code goes here */
}
windowNew = GTK_WIDGET (gtk_builder_get_object (builderNew, "window1"));
gtk_builder_connect_signals (builderNew, NULL);
g_object_unref (G_OBJECT (builderNew));
gtk_widget_show (windowNew);
gtk_main ();
}
}
void generate(GtkButton *b1, gpointer entry1)
{
char buff[256];
int n=0;
bzero(buff,strlen(buff));
char msg[500];
bzero(msg,strlen(msg));
char SENDBUFFER[256];
int SOCKFD = 0;
struct sockaddr_in serv_addr;
FILE *fp;
struct hostent *server1;
if( (SOCKFD = socket(AF_INET,SOCK_STREAM,0) ) < 0 )
{
printf("client socket failied");
exit(-1);
}
bzero(SENDBUFFER,strlen(SENDBUFFER));
bzero((char *) &serv_addr, sizeof(serv_addr));
server1 = gethostbyname("localhost");
serv_addr.sin_family=AF_INET;
bcopy((char *)server1->h_addr,(char *)&serv_addr.sin_addr.s_addr,server1->h_length);
serv_addr.sin_port=htons(SJPORTNO);
if (connect(SOCKFD,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
{
printf("error in connecting with the server\n");
exit(-1);
}
strcpy(buff,"report~");
strcat(buff,ENTERBUSNUMBER);
strcat(buff,"~");
strncpy(SENDBUFFER,buff,strlen(buff));
puts(SENDBUFFER);
n = write(SOCKFD,SENDBUFFER,strlen(SENDBUFFER));
if(n<0)
{
printf("error in sending\n");
exit(-1);
}
bzero(SENDBUFFER,strlen(SENDBUFFER));
n = read(SOCKFD,SENDBUFFER,sizeof(SENDBUFFER) -1 );
if(n<0)
{
perror("error in reading \n");
}
else{
fp=fopen("report.txt","w");
printf("rep : %s",SENDBUFFER);
fprintf(fp,"%s",SENDBUFFER);
fclose(fp);
gtk_label_set_text(entry1, fileok);
}
close(SOCKFD);
}
int main (int argc, char *argv[])
{
GtkBuilder *builder;
GtkWidget *window;
GError *err = NULL;
gtk_init (&argc, &argv);
builder = gtk_builder_new ();
if(0 == gtk_builder_add_from_file (builder, "user2.glade", &err))
{
/* Print out the error. You can use GLib's message logging */
fprintf(stderr, "Error adding build from file. Error: %s\n", err->message);
/* Your error handling code goes here */
}
window = GTK_WIDGET (gtk_builder_get_object (builder, "window1"));
gtk_builder_connect_signals (builder, NULL);
g_object_unref (G_OBJECT (builder));
gtk_widget_show (window);
gtk_main ();
return 0;
}
<file_sep>#*****************************************************************
#
# CMPE 207 (Network Programming and Applications) Project Makefile
# Title: Public-Transport Interactive Client-Server Design
#
#*****************************************************************
all: type1Client type2Client type3Client stub servers
type1Client: type1.c
gcc type1.c -o testGlade `pkg-config --cflags --libs gtk+-3.0` `mysql_config --cflags --libs` -export-dynamic -rdynamic
type2Client: type2Client.c
gcc -Wall -g -o type2Client type2Client.c `pkg-config --cflags --libs gtk+-3.0` -export-dynamic
type3Client: type3.c
gcc -Wall -g -o type3 type3.c `pkg-config --cflags --libs gtk+-3.0` -export-dynamic -rdynamic
stub: stub.c
gcc -o stub $(mysql_config --cflags) stub.c $(mysql_config --libs) `mysql_config --cflags --libs`
servers: servers.c
gcc servers.c -o servers `mysql_config --cflags --libs` -pthread
clean:
rm servers stub type3 type2Client testGlade
<file_sep> //gcc servers.c -o servers `mysql_config --cflags --libs` -pthread
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <pthread.h>
#include "utils.h"
#define PORTNUM1 2343
int main(int argc, char* argv[])
{
int opt;
int portno1;
printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
if (strcmp(argv[1],"SJ")==0){
printf("Starting San Jose Server\n");
portno1 = 20000;
}
else if (strcmp(argv[1],"SF")==0){
printf("Starting San Francisco Server\n");
portno1 = 20001;
}
pipe(fd);
printf("Enter Option 0=Stand Alone Server, 1= Master - Redundant Server:\n");
scanf("%d",&opt);
if(opt==0 )
mainServer(argv[1]);
else if(opt ==1)
{
if (fork()==0)
{
checkStatus(portno1);
}
else
{
close (fd[WRITE]); /* Close unused end */
while(strcmp(status,"redunt")==0 || strcmp(status,"init")==0)
{
bytesRead = read (fd[READ], status, sizeof(status));
}
if (strcmp(status,"master")==0)
{
mainServer(argv[1]);
}
}
}
else{
printf("invalid\n");
}
return 0;
}
<file_sep> //gcc -Wall -g -o type2Client type2Client.c `pkg-config --cflags --libs gtk+-3.0` -export-dynamic
#include <gtk/gtk.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <pthread.h>
#define SFPORTNO 10001
#define SJPORTNO 10000
void knowLocationType2(GtkButton *b1, gpointer entry1)
{
char buff[256];
int n=0;
bzero(buff,strlen(buff));
char msg[500];
bzero(msg,strlen(msg));
gchar busDetailString[500];
char SENDBUFFER[256];
int SOCKFD = 0;
struct sockaddr_in serv_addr;
struct hostent *server1;
if( (SOCKFD = socket(AF_INET,SOCK_STREAM,0) ) < 0 )
{
printf("client socket failied");
exit(-1);
}
bzero(SENDBUFFER,strlen(SENDBUFFER));
bzero((char *) &serv_addr, sizeof(serv_addr));
server1 = gethostbyname("localhost");
serv_addr.sin_family=AF_INET;
bcopy((char *)server1->h_addr,(char *)&serv_addr.sin_addr.s_addr,server1->h_length);
serv_addr.sin_port=htons(SJPORTNO);
if (connect(SOCKFD,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
{
printf("error in connecting with the server\n");
exit(-1);
}
strcpy(buff,"type2~SJ~66~72~73~");
strncpy(SENDBUFFER,buff,strlen(buff));
n = write(SOCKFD,SENDBUFFER,strlen(SENDBUFFER));
if(n<0)
{
printf("error in sending\n");
exit(-1);
}
bzero(SENDBUFFER,strlen(SENDBUFFER));
n = read(SOCKFD,SENDBUFFER,sizeof(SENDBUFFER) -1 );
if(n<0)
{
perror("error in reading \n");
}
else{
strcpy(msg,"Current status of all Bus : ");
strcat(msg,SENDBUFFER);
puts(msg);
strcpy(busDetailString,msg);
gtk_label_set_text(entry1, busDetailString);
bzero(msg,strlen(msg));
bzero(busDetailString,strlen(busDetailString));
}
close(SOCKFD);
}
int main (int argc, char *argv[])
{
GtkBuilder *builder;
GtkWidget *window;
GError *err = NULL;
gtk_init (&argc, &argv);
builder = gtk_builder_new ();
if(0 == gtk_builder_add_from_file (builder, "type2.glade", &err))
{
/* Print out the error. You can use GLib's message logging */
fprintf(stderr, "Error adding build from file. Error: %s\n", err->message);
/* Your error handling code goes here */
}
window = GTK_WIDGET (gtk_builder_get_object (builder, "window2"));
gtk_builder_connect_signals (builder, NULL);
g_object_unref (G_OBJECT (builder));
gtk_widget_show (window);
gtk_main ();
return 0;
}
<file_sep># Public-transport-interactive-server-client-design
Demo Video: https://www.youtube.com/watch?v=3iF0CuExMAY
PUBLIC- TRANSPORT INTERACTIVE CIENT-SERVER DESIGN README FILE
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Steps to setup and execute server and client:
$ ./servers SJ
Above command, starts the server of San Jose City (SJ). This will accept requests from the San Jose city users.
$ ./testGlade SJ
This command opens up the UI for type 1 client. Upon execution of this command, User authentication UI opens up. Credentials for the user are added manually using MySQL commands.
$ ./type2Client
This command displays UI for type 2 client.
$ ./type3
This command opens up UI for type 3 client where in user can generate report of bus’s location and time.
To simulate real time change in bus’s location we have implemented a stub which changes bus’s current location in our database. Below is the command to execute stub.c file
$ ./stub.c
Complete Deployment instructions of our project:
Prerequisites: Before running the code, host PC should be installed with GTK3+ and Glade.
To install these, follow below instructions and command.
$ sudo apt-get install libgtk-3-dev
Above command installs gtk (Gnome ToolKit) version 3 which enables PC to support Graphical User Interface.
$ sudo apt-get install glade
Above command installs Glade which is used to build the User Interface of our project.
How to compile the code?
We have implemented Makefile to our project to compile all the files.
$ make
This command compiles all the files and errors out if there is any compilation issue.
$ make clean
Above command removes all the object files from the folder. Thus in order to execute code again, we need to compile again by executing make command.
We have tested above all the commands and found it successful in Ubuntu 14.04.3 version (linux).
SQL Commands:
We used SQL Database to store the information which is required to be processed for the client convenience. To install the MySQL from the linux command, we need the following functions,
sudo apt-get purge mysql-client-core-5.6
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install mysql-client-core-5.5
sudo apt-get install mysql-server
By using this, we can get the MySQL database access.
For setting up the SQL, we need to set up some validations as,
User: “root”
Password: “<PASSWORD>”
Command is,
mysql –u root –p
To create a database, we need the following query as,
CREATE DATABASE proj207;
To use the database created,
USE proj207;
To create the table in a database for bus details entry,
CREATE TABLE bus_details(bus_no int, bus_location varchar(255), city varchar(255));
To create the table in the database for bus records,
CREATE TABLE bus_record(bus_number int, bus_location varchar(255), bus_time
To create the table in the database for user_details,
CREATE TABLE user_details(username varchar(255),password varchar(255));
INSERT INTO user_details(”test”, “test” );
To insert elements into the table bus_details,
INSERT INTO bus_details(72,”Bassett”, “SJ” );
INSERT INTO bus_details(73, “Santa Clara”,”SJ”);
INSERT INTO bus_details(66,”Central” ,”SJ”);
INSERT INTO bus_details(323, “Walmart”,”SJ”);
INSERT INTO bus_details(81, “Cisco centre”,”SJ”);
INSERT INTO bus_details(68, “Sunnywale”,”SJ”);
INSERT INTO bus_details(181, ”Palo Alto” ,”SJ”);
INSERT INTO bus_details(93, “Downtown”,”SJ”);
INSERT INTO bus_details(522, “SAP Centre”,”SJ”);
INSERT INTO bus_details(23,”Light rail Station”,”SJ” );
To link the MySQL database with the C code to be executed, we need the following command in the command-line prompt,
gcc -o stub $(mysql_config --cflags) stub.c $(mysql_config –libs)
----------------------------------------------------------------------------------------------------------------
<file_sep> #include <gtk/gtk.h>
#include <stdlib.h>
#include <mysql.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <pthread.h>
#define SFPORTNO 10001
#define SJPORTNO 10000
/* Global variables */
int SanFransico[]= {66 ,67 ,68};
int SanJose[]= {72 ,75 ,76};
const gchar *USERNAME;
const gchar *PASSWORD;
const gchar *ENTERCITY;
const gchar *ENTERBUSNUMBER;
const gchar *ENTERBUSNUMBERNOTIFY;
int connected =0;
char USERCITY[5];
void on_window1_destroy (GObject *object, gpointer user_data)
{
gtk_main_quit();
}
gboolean entercity(GtkEntry *e1, gpointer user)
{
ENTERCITY = gtk_entry_get_text ((e1));
return FALSE;
}
gboolean enterbusnumber(GtkEntry *e1, gpointer user)
{
ENTERBUSNUMBER = gtk_entry_get_text ((e1));
return FALSE;
}
gboolean enteredBusNotify(GtkEntry *e1, gpointer user)
{
ENTERBUSNUMBERNOTIFY = gtk_entry_get_text ((e1));
return FALSE;
}
gboolean enteredUsername(GtkEntry *e1, gpointer user)
{
USERNAME = gtk_entry_get_text ((e1));
return FALSE;
}
gboolean enteredPassword(GtkEntry *e2, gpointer user)
{
PASSWORD = gtk_entry_get_text ((e2));
return FALSE;
}
void fetched(GtkButton *b1, gpointer entry1)
{
char buff[256];
int n=0;
bzero(buff,strlen(buff));
char msg[500];
bzero(msg,strlen(msg));
gchar busDetailString[500];
printf("Entered City Name: %s\n",ENTERCITY);
printf("Entered Bus Number: %s\n",ENTERBUSNUMBER);
int portno;
char SENDBUFFER[256];
int SOCKFD = 0;
struct sockaddr_in serv_addr;
struct hostent *server1;
if( (SOCKFD = socket(AF_INET,SOCK_STREAM,0) ) < 0 )
{
printf("client socket failied");
exit(-1);
}
bzero(SENDBUFFER,strlen(SENDBUFFER));
bzero((char *) &serv_addr, sizeof(serv_addr));
server1 = gethostbyname("localhost");
serv_addr.sin_family=AF_INET;
bcopy((char *)server1->h_addr,(char *)&serv_addr.sin_addr.s_addr,server1->h_length);
if ( strcmp(USERCITY,"SF") == 0)
{
serv_addr.sin_port=htons(SFPORTNO);
} else if (strcmp(USERCITY,"SJ") == 0)
{
serv_addr.sin_port=htons(SJPORTNO);
}
else{
printf("Invalid command from user\n");
exit(-1);
}
if (connect(SOCKFD,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
{
printf("error in connecting with the server\n");
exit(-1);
}
else {
connected = 1;
}
strcpy(buff,"type1~");
strcat(buff,ENTERCITY);
strcat(buff,"~");
strcat(buff,ENTERBUSNUMBER);
strcat(buff,"~");
strncpy(SENDBUFFER,buff,strlen(buff));
n = write(SOCKFD,SENDBUFFER,strlen(SENDBUFFER));
if(n<0)
{
printf("error in sending\n");
exit(-1);
}
bzero(SENDBUFFER,strlen(SENDBUFFER));
n = read(SOCKFD,SENDBUFFER,sizeof(SENDBUFFER) -1 );
if(n<0)
{
perror("error in reading \n");
}
else{
strcpy(msg,"Location : ");
strcat(msg,SENDBUFFER);
puts(msg);
strcpy(busDetailString,msg);
gtk_label_set_text(entry1, busDetailString);
bzero(msg,strlen(msg));
bzero(busDetailString,strlen(busDetailString));
}
close(SOCKFD);
}
void setNotification(GtkButton *b1, gpointer entry2)
{
if(fork() == 0){
char buff[256];
int n=0;
bzero(buff,strlen(buff));
printf("Entered Bus Number for Notification is: %s\n",ENTERBUSNUMBERNOTIFY);
int portno;
char SENDBUFFER[256];
int SOCKFD = 0;
struct sockaddr_in serv_addr;
struct hostent *server1;
if( (SOCKFD = socket(AF_INET,SOCK_STREAM,0) ) < 0 )
{
printf("client socket failied");
exit(-1);
}
bzero(SENDBUFFER,strlen(SENDBUFFER));
bzero((char *) &serv_addr, sizeof(serv_addr));
server1 = gethostbyname("localhost");
serv_addr.sin_family=AF_INET;
bcopy((char *)server1->h_addr,(char *)&serv_addr.sin_addr.s_addr,server1->h_length);
if ( strcmp(USERCITY,"SF") == 0)
{
serv_addr.sin_port=htons(SFPORTNO);
} else if (strcmp(USERCITY,"SJ") == 0)
{
serv_addr.sin_port=htons(SJPORTNO);
}
else{
printf("Invalid command from user\n");
exit(-1);
}
if (connect(SOCKFD,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
{
printf("error in connecting with the server\n");
exit(-1);
}
else {
connected = 1;
}
strcpy(buff,"set~");
strcat(buff,ENTERBUSNUMBERNOTIFY);
strcat(buff,"~");
strncpy(SENDBUFFER,buff,strlen(buff));
n = write(SOCKFD,SENDBUFFER,strlen(SENDBUFFER));
if(n<0)
{
printf("error in sending\n");
exit(-1);
}
bzero(SENDBUFFER,strlen(SENDBUFFER));
n = read(SOCKFD,SENDBUFFER,sizeof(SENDBUFFER) -1 );
if(n<=0)
{
perror("error in reading \n");
close(SOCKFD);
exit(-1);
}
else{
printf("\n----------------Notification Alert-------------------\n");
printf("Current Location of bus number %s is : %s\n",ENTERBUSNUMBERNOTIFY,SENDBUFFER);
printf("------------------------------------------------------\n");
}
while(1)
{
n = read(SOCKFD,SENDBUFFER,sizeof(SENDBUFFER) -1 );
if(n<=0)
{
perror("error in reading \n");
close(SOCKFD);
exit(-1);
}
else{
printf("\n----------------Notification Alert-------------------\n");
printf("Current Location of bus number %s is : %s\n",ENTERBUSNUMBERNOTIFY,SENDBUFFER);
printf("------------------------------------------------------\n");
}
}
close(SOCKFD);
}
else {
printf("Returning from parent\n");
}
}
void submit_clicked(GtkButton *b1, gpointer entry1)
{
int databaseResponse =0;
MYSQL *conn;
char *server = "localhost";
char *user = "root";
char *password = "<PASSWORD>";
char *database = "tejas";
char str[80];
printf("Entered Username: %s\n",USERNAME);
printf("Entered Password: %s\n",PASSWORD);
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
sprintf(str , "Select count(*) from user_details where username='%s' and password='%s'" , USERNAME,PASSWORD);
if (mysql_query(conn, str))
{
//finish_with_error(conn);
printf("failed to query");
}
MYSQL_RES *res = mysql_store_result(conn);
MYSQL_ROW row;
while ((row = mysql_fetch_row(res)))
{
printf("%s ", row[0]);
printf("\n");
if(strcmp(row[0],"0") == 0)
{
databaseResponse = 0;
}
else if(strcmp(row[0],"0") != 0)
{
databaseResponse = 1;
}
else
{
printf("Invalid Username or Password!!! \n");
exit(-1);
}
}
if(databaseResponse == 0)
{
printf("Invalid Username or Password!!! \n");
exit(-1);
}
else if(databaseResponse == 1)
{
/* open new window */
GtkBuilder *builderNew;
GtkWidget *windowNew;
GError *err = NULL;
gtk_init (NULL, NULL);
builderNew = gtk_builder_new ();
if(0 == gtk_builder_add_from_file (builderNew, "busDetails.glade", &err))
{
/* Print out the error. You can use GLib's message logging */
fprintf(stderr, "Error adding build from file. Error: %s\n", err->message);
/* Your error handling code goes here */
}
windowNew = GTK_WIDGET (gtk_builder_get_object (builderNew, "window2"));
gtk_builder_connect_signals (builderNew, NULL);
g_object_unref (G_OBJECT (builderNew));
gtk_widget_show (windowNew);
gtk_main ();
}
else
{
printf("Invalid Username or Password!!! \n");
exit(-1);
}
mysql_free_result(res);
mysql_close(conn);
}
int main (int argc, char *argv[])
{
GtkBuilder *builder;
GtkWidget *window;
GError *err = NULL;
gtk_init (&argc, &argv);
strcpy(USERCITY,argv[1]);
builder = gtk_builder_new ();
if(0 == gtk_builder_add_from_file (builder, "user2.glade", &err))
{
/* Print out the error. You can use GLib's message logging */
fprintf(stderr, "Error adding build from file. Error: %s\n", err->message);
/* Your error handling code goes here */
}
window = GTK_WIDGET (gtk_builder_get_object (builder, "window1"));
gtk_builder_connect_signals (builder, NULL);
g_object_unref (G_OBJECT (builder));
gtk_widget_show (window);
gtk_main ();
return 0;
}
| ded6cc93695b49280c68ed903fee34ef88c2cc68 | [
"Markdown",
"C",
"Makefile"
] | 7 | C | tejasgujjar/Public-transport-interactive-server-client-design | e298a14edf0ef8b2e4ad5838d12718b8e4bf57ff | 84144ee184ef107fb9ea649c3989b0289d486d10 |
refs/heads/master | <repo_name>powercode-team/RedditCloneSample<file_sep>/README.md
# Android RedditCloneSample (1.0.0)
*Android project*
---
### The purpose of the RedditCloneSample is to demonstrate code we write in [PowerCode](https://powercode.us)
## Features
1. View top rated topics
2. Up-vote and down-vote topic to make it move up or down through the list
3. Create new topic with title and initial rating
4. Remove topic by swiping right-to-left
## Requirements
- Minimum SDK version 21 Android 5 (Lollipop)
---
## Development Environment
Project developed with [Android Studio 3.1](https://developer.android.com/studio)
1. The app is developed in compliance with [M-V-VM](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel) and [Android Arch Components](https://developer.android.com/topic/libraries/architecture)
2. Reactive programming style is used to handle requests: [RxJava2](https://github.com/ReactiveX/RxJava),[RxAndroid](https://github.com/ReactiveX/RxAndroid)
3. Crash reports are collected via [Firebase Crashlytics](https://firebase.google.com/docs/crashlytics)
## License
[MIT](https://choosealicense.com/licenses/mit/)<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/app/TheApp.java
package example.powercode.us.redditclonesample.app;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.support.DaggerApplication;
import example.powercode.us.redditclonesample.BuildConfig;
import example.powercode.us.redditclonesample.app.di.DaggerAppComponent;
import timber.log.Timber;
/**
* Created by dev for RedditCloneSample on 12-Jun-18.
*/
public final class TheApp extends DaggerApplication {
@Inject
RefWatcher appRefWatcher;
@Override
public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
}
}
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
return DaggerAppComponent
.builder()
.application(this)
.create(this);
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/main/ui/TopicsAdapter.java
package example.powercode.us.redditclonesample.main.ui;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import java.util.Objects;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.AsyncListDiffer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import example.powercode.us.redditclonesample.R;
import example.powercode.us.redditclonesample.base.ui.CanBind;
import example.powercode.us.redditclonesample.base.ui.DataBindingViewHolder;
import example.powercode.us.redditclonesample.common.Algorithms;
import example.powercode.us.redditclonesample.common.functional.Predicate;
import example.powercode.us.redditclonesample.databinding.ItemTopicBinding;
import example.powercode.us.redditclonesample.databinding.ItemTopicSwipableBinding;
import example.powercode.us.redditclonesample.model.entity.TopicEntity;
import example.powercode.us.redditclonesample.model.entity.VoteType;
/**
* Created by dev for RedditCloneSample on 19-Jun-18.
*/
public class TopicsAdapter extends RecyclerView.Adapter<TopicsAdapter.ItemViewHolder> {
@NonNull
private final LayoutInflater inflater;
private final AsyncListDiffer<TopicEntity> asyncDiffer;
@Nullable
private InteractionListener listener;
public interface InteractionListener {
void onVoteClick(@NonNull View v, int adapterPos, @NonNull VoteType vt);
}
@Inject
TopicsAdapter(@NonNull LayoutInflater inflater, @Nullable InteractionListener listener) {
this.inflater = inflater;
this.listener = listener;
this.asyncDiffer = new AsyncListDiffer<>(this, DIFF_CALLBACK);
}
@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@Nullable ViewGroup parent, int viewType) {
return new ItemViewHolder(DataBindingUtil.inflate(inflater, R.layout.item_topic_swipable, parent, false), listener);
}
@Override
public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
holder.bind(getItem(position));
}
private List<TopicEntity> getItems() {
return asyncDiffer.getCurrentList();
}
@Override
public int getItemCount() {
return getItems().size();
}
public TopicEntity getItem(int position) {
return getItems().get(position);
}
public void submitItems(@Nullable List<TopicEntity> items) {
asyncDiffer.submitList(items);
}
public int findItemPosition(@NonNull Predicate<? super TopicEntity> condition) {
return Algorithms.findIndex(getItems(), condition);
}
@NonNull
private static final DiffUtil.ItemCallback<TopicEntity> DIFF_CALLBACK = new DiffUtil.ItemCallback<TopicEntity>() {
@Override
public boolean areItemsTheSame(TopicEntity oldItem, TopicEntity newItem) {
return oldItem.id == newItem.id;
}
@Override
public boolean areContentsTheSame(TopicEntity oldItem, TopicEntity newItem) {
return Objects.equals(oldItem, newItem);
}
};
static class ItemViewHolder extends DataBindingViewHolder<ItemTopicSwipableBinding> implements CanBind<TopicEntity> {
@Nullable
private InteractionListener listener;
private final ItemTopicBinding foreground;
private final TextView background;
ItemViewHolder(@NonNull ItemTopicSwipableBinding binding, @Nullable InteractionListener l) {
super(binding);
listener = l;
foreground = binding.viewForeground;
background = binding.viewBackground;
assignListener();
}
public ItemTopicBinding getForeground() {
return foreground;
}
public TextView getBackground() {
return background;
}
private void assignListener() {
// if (listener != l) {
bindComponent.viewForeground.topicRateUp.setOnClickListener(v -> {
if (listener != null) {
listener.onVoteClick(foreground.topicRateUp, getAdapterPosition(), VoteType.UP);
}
});
foreground.topicRateDown.setOnClickListener(v -> {
if (listener != null) {
listener.onVoteClick(foreground.topicRateDown, getAdapterPosition(), VoteType.DOWN);
}
});
// }
}
@UiThread
@Override
public void bind(@NonNull TopicEntity t) {
bindComponent.setTopic(t);
}
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/error/BaseErrorParseStrategy.java
package example.powercode.us.redditclonesample.base.error;
import androidx.annotation.NonNull;
/**
* Defines strategy to parse errors to appropriate view
*/
public abstract class BaseErrorParseStrategy<E extends ErrorBase> {
public abstract <Response> E parse(@NonNull Response response);
public abstract E parse(@NonNull Throwable th);
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/ui/fragments/BaseInjectableFragment.java
package example.powercode.us.redditclonesample.base.ui.fragments;
import android.content.Context;
import com.squareup.leakcanary.RefWatcher;
import javax.inject.Inject;
import androidx.annotation.CallSuper;
import androidx.fragment.app.Fragment;
import dagger.android.support.AndroidSupportInjection;
/**
* Basic fragment which supports dependency injection
*/
public abstract class BaseInjectableFragment extends Fragment {
@Inject
RefWatcher refWatcher;
@CallSuper
@Override
public void onAttach(Context context) {
AndroidSupportInjection.inject(this);
super.onAttach(context);
}
/**
* Called when the fragment is no longer in use. This is called
* after {@link #onStop()} and before {@link #onDetach()}.
*/
@CallSuper
@Override
public void onDestroy() {
super.onDestroy();
// Assert.assertNotNull(getContext());
refWatcher.watch(this/*, this.getClass().getSimpleName()*/);
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/model/repository/impl/RepoTopicsImpl.java
package example.powercode.us.redditclonesample.model.repository.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import example.powercode.us.redditclonesample.app.di.scopes.PerApplication;
import example.powercode.us.redditclonesample.base.error.ErrorDataTyped;
import example.powercode.us.redditclonesample.common.Algorithms;
import example.powercode.us.redditclonesample.common.functional.Function;
import example.powercode.us.redditclonesample.common.functional.Predicate;
import example.powercode.us.redditclonesample.model.common.Resource;
import example.powercode.us.redditclonesample.model.common.Status;
import example.powercode.us.redditclonesample.model.entity.EntityActionType;
import example.powercode.us.redditclonesample.model.entity.TopicEntity;
import example.powercode.us.redditclonesample.model.entity.VoteType;
import example.powercode.us.redditclonesample.model.error.ErrorsTopics;
import example.powercode.us.redditclonesample.model.repository.RepoTopics;
import example.powercode.us.redditclonesample.model.rules.BRulesTopics;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
/**
* Created by dev for RedditCloneSample on 19-Jun-18.
*/
@PerApplication
public class RepoTopicsImpl implements RepoTopics {
private static final int TOPICS_COUNT = (int) (BRulesTopics.TOPICS_COUNT_WORKING_SET * 1.2f);
// This is just a simulation of data source such as DB
private volatile List<TopicEntity> originalTopics;
// Is used to generate ids. In real app back-end sets id to entity
@NonNull
private static final AtomicLong idCounter = new AtomicLong(1000L);
@NonNull
private final PublishSubject<Pair<TopicEntity, EntityActionType>> topicChangeSubject = PublishSubject.create();
private static void generateItems(@NonNull Collection<TopicEntity> c, int count, @NonNull Function<? super Integer, ? extends Integer> func) {
if (count <= 0) {
return;
}
List<TopicEntity> items = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
int rating = func.apply(i);
items.add(new TopicEntity(idCounter.getAndIncrement(), "Very simple title " + i, rating));
}
c.clear();
c.addAll(items);
}
private static <Elem, Container extends List<Elem>> boolean insertOrUpdate(@NonNull Container items,
@NonNull Elem newItem,
@Nullable Predicate<? super Elem> removeCondition) {
int indexItemToUpdate = (removeCondition != null) ? Algorithms.findIndex(items, removeCondition) : -1;
if (indexItemToUpdate == -1) {
return items.add(newItem);
}
items.set(indexItemToUpdate, newItem);
return true;
}
private List<TopicEntity> getOriginalTopics() {
if (originalTopics == null) {
synchronized (this) {
if (originalTopics == null) {
originalTopics = Collections.synchronizedList(new ArrayList<>(TOPICS_COUNT));
generateItems(originalTopics, TOPICS_COUNT, index -> 2 * index ^ (index - 1));
}
}
}
return originalTopics;
}
private static boolean doVoteTopic(@NonNull TopicEntity topic, @NonNull VoteType vt) {
switch (vt) {
case UP: {
if (topic.getRating() < Integer.MAX_VALUE) {
topic.setRating(topic.getRating() + 1);
return true;
}
break;
}
case DOWN: {
if (topic.getRating() > Integer.MIN_VALUE) {
topic.setRating(topic.getRating() - 1);
return true;
}
break;
}
default: {
throw new NoSuchElementException("Unknown VoteType " + vt);
}
}
return false;
}
private Single<List<TopicEntity>> prepareOriginalTopics() {
return Single
.fromCallable(this::getOriginalTopics);
}
@Inject
RepoTopicsImpl() {
}
@NonNull
@Override
public Single<Resource<List<TopicEntity>, ErrorDataTyped<ErrorsTopics>>> fetchTopics(@Nullable Comparator<? super TopicEntity> sortCmp, int count) {
return prepareOriginalTopics()
.subscribeOn(Schedulers.computation())
.map(topicEntities -> {
List<TopicEntity> sortedItems = new ArrayList<>(topicEntities);
if (sortCmp != null) {
Collections.sort(sortedItems, sortCmp);
}
return sortedItems;
})
.map(sortedTopicEntities -> {
if (count < sortedTopicEntities.size()) {
sortedTopicEntities.subList(count, sortedTopicEntities.size()).clear();
}
return Resource.success(sortedTopicEntities, (ErrorDataTyped<ErrorsTopics>) null);
});
}
@NonNull
@Override
public Single<Pair<Long, Boolean>> applyVoteToTopic(final long id, @NonNull VoteType vt) {
return getById(id)
.map(topicResource -> {
if (topicResource.status == Status.ERROR) {
return new Pair<>(new TopicEntity(id, ""), false);
}
TopicEntity targetTopic = topicResource.data;
Objects.requireNonNull(targetTopic, String.format(Locale.getDefault(), "Topic with id %1$d must exist", id));
boolean isApplied = doVoteTopic(targetTopic, vt);
if (isApplied) {
insertOrUpdate(getOriginalTopics(),
targetTopic, topicEntity -> targetTopic.id == topicEntity.id);
}
return new Pair<>(targetTopic, isApplied);
})
.doOnSuccess(topicEntityPack -> {
Objects.requireNonNull(topicEntityPack.first);
Objects.requireNonNull(topicEntityPack.second);
boolean isApplied = topicEntityPack.second;
if (isApplied) {
topicChangeSubject.onNext(new Pair<>(new TopicEntity(topicEntityPack.first), EntityActionType.UPDATED));
}
})
.map(topicEntityPack -> {
Objects.requireNonNull(topicEntityPack.first);
return new Pair<>(topicEntityPack.first.getId(), topicEntityPack.second);
}
)
.subscribeOn(Schedulers.computation());
}
@NonNull
@Override
public Single<Pair<Long, Boolean>> createTopic(@NonNull String title, int rating) {
return Single.fromCallable(() -> {
TopicEntity targetTopic = new TopicEntity(idCounter.incrementAndGet(), title, rating);
boolean isAdded = getOriginalTopics().add(targetTopic);
return new Pair<>(targetTopic, isAdded);
})
.doOnSuccess(topicEntityPack -> {
Objects.requireNonNull(topicEntityPack.first);
Objects.requireNonNull(topicEntityPack.second);
boolean isApplied = topicEntityPack.second;
if (isApplied) {
topicChangeSubject.onNext(new Pair<>(new TopicEntity(topicEntityPack.first), EntityActionType.INSERTED));
}
})
.map(topicEntityPack -> {
Objects.requireNonNull(topicEntityPack.first);
Objects.requireNonNull(topicEntityPack.second);
boolean isApplied = topicEntityPack.second;
final long newItemId = isApplied ? topicEntityPack.first.getId() : Long.MIN_VALUE;
return new Pair<>(newItemId, isApplied);
})
.subscribeOn(Schedulers.computation());
}
@NonNull
@Override
public Single<Pair<Long, Boolean>> removeTopic(long id) {
return getById(id)
.map(topicResource -> {
@NonNull TopicEntity targetTopic = topicResource.data != null ? topicResource.data : new TopicEntity(id, "");
boolean isRemoved = (topicResource.status == Status.SUCCESS) && originalTopics.remove(targetTopic);
return new Pair<>(topicResource.data, isRemoved);
})
.doOnSuccess(topicEntityPack -> {
Objects.requireNonNull(topicEntityPack.first);
Objects.requireNonNull(topicEntityPack.second);
boolean isRemoved = topicEntityPack.second;
if (isRemoved) {
topicChangeSubject.onNext(new Pair<>(new TopicEntity(topicEntityPack.first), EntityActionType.DELETED));
}
})
.map(topicEntityPack -> {
Objects.requireNonNull(topicEntityPack.first);
return new Pair<>(topicEntityPack.first.getId(), topicEntityPack.second);
})
.subscribeOn(Schedulers.computation());
}
@NonNull
@Override
public Single<Resource<TopicEntity, ErrorDataTyped<ErrorsTopics>>> getById(long topicId) {
return Single
.fromCallable(() -> {
TopicEntity targetTopic =
Algorithms.findElement(originalTopics, topicEntity -> topicEntity.id == topicId);
if (targetTopic == null) {
return Resource.error(new ErrorDataTyped<>("Item not found", ErrorsTopics.NO_ITEM), (TopicEntity) null);
}
return Resource.success(new TopicEntity(targetTopic), (ErrorDataTyped<ErrorsTopics>) null);
}
)
.subscribeOn(Schedulers.computation());
}
@NonNull
@Override
public Observable<Pair<TopicEntity, EntityActionType>> onTopicChangeObservable() {
return topicChangeSubject.hide();
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/ui/BaseInjectableFragmentActivity.java
package example.powercode.us.redditclonesample.base.ui;
import javax.inject.Inject;
import androidx.fragment.app.Fragment;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
/**
* Basic activity which supports dependency injection into its {@link Fragment}
*/
public abstract class BaseInjectableFragmentActivity extends BaseInjectableActivity
implements HasSupportFragmentInjector {
@Inject
DispatchingAndroidInjector<Fragment> fragmentInjector_;
@Override
public AndroidInjector<Fragment> supportFragmentInjector() {
return fragmentInjector_;
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/main/vm/TopicsViewModel.java
package example.powercode.us.redditclonesample.main.vm;
import android.app.Application;
import java.util.List;
import java.util.Objects;
import javax.inject.Inject;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import example.powercode.us.redditclonesample.R;
import example.powercode.us.redditclonesample.base.error.ErrorDataTyped;
import example.powercode.us.redditclonesample.common.arch.SingleLiveEvent;
import example.powercode.us.redditclonesample.common.patterns.holder.CommandHolder;
import example.powercode.us.redditclonesample.common.patterns.holder.CommandHolderSingle;
import example.powercode.us.redditclonesample.main.vm.command.CommandDeleteTopic;
import example.powercode.us.redditclonesample.main.vm.command.CommandVoteTopic;
import example.powercode.us.redditclonesample.main.vm.command.ReceiverCommandDelete;
import example.powercode.us.redditclonesample.main.vm.command.ReceiverCommandVoteTopic;
import example.powercode.us.redditclonesample.model.common.Resource;
import example.powercode.us.redditclonesample.model.common.Status;
import example.powercode.us.redditclonesample.model.entity.EntityActionType;
import example.powercode.us.redditclonesample.model.entity.TopicEntity;
import example.powercode.us.redditclonesample.model.entity.VoteType;
import example.powercode.us.redditclonesample.model.error.ErrorsTopics;
import example.powercode.us.redditclonesample.model.repository.RepoTopics;
import example.powercode.us.redditclonesample.model.rules.BRulesTopics;
import example.powercode.us.redditclonesample.utils.RxUtils;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;
/**
* Created by dev for RedditCloneSample on 18-Jun-18.
*/
public class TopicsViewModel extends ViewModel {
@NonNull
private final MutableLiveData<Resource<List<TopicEntity>, ErrorDataTyped<ErrorsTopics>>> topicsLiveData = new MutableLiveData<>();
@NonNull
private final MutableLiveData<Resource<Long, ErrorDataTyped<ErrorsTopics>>> itemApplyVoteLiveData = new SingleLiveEvent<>();
@NonNull
private final MutableLiveData<Resource<Long, ErrorDataTyped<ErrorsTopics>>> itemCreatedLiveData = new SingleLiveEvent<>();
@NonNull
private final MutableLiveData<Resource<Long, ErrorDataTyped<ErrorsTopics>>> itemRemovedLiveData = new SingleLiveEvent<>();
@NonNull
private final Application app;
@NonNull
private final RepoTopics repoTopics;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
@Nullable
private Disposable disposableApplyVote = null;
@Nullable
private Disposable disposableRemoveTopic = null;
@Nullable
private Disposable disposableFindTopicById = null;
@Nullable
private Disposable disposableCreateTopic = null;
@NonNull
private final CommandHolder commandHolder;
@Inject
TopicsViewModel(@NonNull Application app, @NonNull RepoTopics repoTopics, @NonNull CommandHolderSingle commandHolderImpl) {
this.app = app;
this.repoTopics = repoTopics;
this.commandHolder = commandHolderImpl;
Timber.d("VM of type [ %s ] constructor called \nid %s", TopicsViewModel.class.getSimpleName(), this);
topicsLiveData.setValue(Resource.loading(null));
subscribeToTopicChanges(repoTopics.onTopicChangeObservable());
refreshTopics();
}
private void subscribeToTopicChanges(@NonNull Observable<Pair<TopicEntity, EntityActionType>> topicChangesObservable) {
compositeDisposable.add(topicChangesObservable
.observeOn(AndroidSchedulers.mainThread())
.subscribe(topicChanges -> {
// if (topicChanges.second == EntityActionType.INSERTED
// || topicChanges.second == EntityActionType.DELETED) {
refreshTopics();
// }
}, Timber::e));
}
@NonNull
private Disposable fetchTopics(@IntRange(from = 0, to = Integer.MAX_VALUE) int count) {
return repoTopics
.fetchTopics(BRulesTopics.TOPICS_LIST_COMPARATOR, count)
.doOnSubscribe(disposable -> {
List<TopicEntity> oldValue = topicsLiveData.getValue() != null ? topicsLiveData.getValue().data : null;
topicsLiveData.setValue(Resource.loading(oldValue));
})
// .doOnSuccess(listTopicsResource -> {
// if (listTopicsResource.status == Status.SUCCESS && listTopicsResource.data != null) {
// Timber.d("Fetched array:\n\t%s\n", Arrays.toString(listTopicsResource.data.toArray(new TopicEntity[0])));
// }
// })
.observeOn(AndroidSchedulers.mainThread())
.subscribe(topicsLiveData::setValue,
throwable -> Timber.e(throwable));
}
private void refreshTopics() {
compositeDisposable.add(fetchTopics(BRulesTopics.TOPICS_COUNT_WORKING_SET));
}
@Override
protected void onCleared() {
super.onCleared();
RxUtils.clearDisposableSafe(compositeDisposable);
RxUtils.clearDisposableSafe(disposableFindTopicById);
RxUtils.clearDisposableSafe(disposableApplyVote);
RxUtils.clearDisposableSafe(disposableRemoveTopic);
RxUtils.clearDisposableSafe(disposableCreateTopic);
commandHolder.clear();
Timber.d("VM of type [ %s ] was cleared \nid %s", TopicsViewModel.class.getSimpleName(), this);
}
@NonNull
public LiveData<Resource<List<TopicEntity>, ErrorDataTyped<ErrorsTopics>>> getTopicsLiveData() {
return topicsLiveData;
}
// Exposed to TopicListFragment
public void topicVote(long id, @NonNull VoteType vt) {
commandHolder.push(new CommandVoteTopic(receiverCommandVoteTopic, id, vt));
commandHolder.current().run();
}
@NonNull
private final ReceiverCommandVoteTopic receiverCommandVoteTopic = (id, vt) -> {
RxUtils.clearDisposableSafe(disposableApplyVote);
disposableApplyVote = applyVoteTopic(id, vt);
};
@NonNull
private Disposable applyVoteTopic(long id, @NonNull VoteType vt) {
return repoTopics
.applyVoteToTopic(id, vt)
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> {
itemApplyVoteLiveData.setValue(Resource.loading(id));
})
.subscribe(resultAppliedVote -> {
// Timber.d("Vote applied with result: %b", isApplied);
Objects.requireNonNull(resultAppliedVote.second);
if (resultAppliedVote.second) {
itemApplyVoteLiveData.setValue(Resource.success(resultAppliedVote.first, null));
} else {
itemApplyVoteLiveData.setValue(
Resource.error(
new ErrorDataTyped<>(app
.getResources()
.getString(R.string.error_topic_with_id_not_found, resultAppliedVote.first),
ErrorsTopics.NO_ITEM),
resultAppliedVote.first
)
);
}
}, throwable -> Timber.e(throwable));
}
@NonNull
public LiveData<Resource<Long, ErrorDataTyped<ErrorsTopics>>> getApplyVoteLiveData() {
return itemApplyVoteLiveData;
}
// Exposed to TopicListFragment
public void topicDelete(long id) {
RxUtils.clearDisposableSafe(disposableFindTopicById);
disposableFindTopicById = repoTopics
.getById(id)
.doOnSubscribe(disposable -> itemRemovedLiveData.setValue(Resource.loading(id)))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(topicEntityResource -> {
if (topicEntityResource.status == Status.ERROR) {
itemRemovedLiveData.setValue(
Resource.error(
new ErrorDataTyped<>(app
.getResources()
.getString(R.string.error_topic_with_id_not_found, id),
ErrorsTopics.NO_ITEM),
id
)
);
return;
}
TopicEntity removedTopic = topicEntityResource.data;
Objects.requireNonNull(removedTopic);
commandHolder.push(new CommandDeleteTopic(receiverCommandDelete, removedTopic));
commandHolder.current().run();
},
Timber::e);
}
@NonNull
private final ReceiverCommandDelete receiverCommandDelete = new ReceiverCommandDelete() {
@Override
public void deleteTopic(long id) {
RxUtils.clearDisposableSafe(disposableRemoveTopic);
disposableRemoveTopic = removeTopic(id);
}
@Override
public void undoDeleteTopic(@NonNull TopicEntity topic2Restore) {
restoreTopic(topic2Restore.title, topic2Restore.getRating());
}
};// ReceiverCommandDelete
private Disposable removeTopic(long id) {
return repoTopics
.removeTopic(id)
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> {
itemRemovedLiveData.setValue(Resource.loading(id));
})
.subscribe(resultRemovedTopic -> {
Objects.requireNonNull(resultRemovedTopic.second);
if (resultRemovedTopic.second) {
itemRemovedLiveData.setValue(Resource.success(resultRemovedTopic.first, null));
} else {
itemRemovedLiveData.setValue(
Resource.error(
new ErrorDataTyped<>(app
.getResources()
.getString(R.string.error_topic_with_id_not_found, resultRemovedTopic.first),
ErrorsTopics.NO_ITEM),
resultRemovedTopic.first
)
);
}
}, throwable -> Timber.e(throwable));
}
private void restoreTopic(@NonNull String title, int rating) {
RxUtils.clearDisposableSafe(disposableCreateTopic);
disposableCreateTopic = createTopic(title, rating);
}
private Disposable createTopic(@NonNull String title, int rating) {
return repoTopics
.createTopic(title, rating)
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> {
itemCreatedLiveData.setValue(Resource.loading(null));
})
.subscribe(resultCreateTopic -> {
Objects.requireNonNull(resultCreateTopic.second);
if (resultCreateTopic.second) {
itemCreatedLiveData.setValue(Resource.success(resultCreateTopic.first, null));
} else {
itemCreatedLiveData.setValue(
Resource.error(
new ErrorDataTyped<>(app
.getResources().getString(R.string.error_topic_create),
ErrorsTopics.NO_ITEM),
resultCreateTopic.first
)
);
}
}, throwable -> Timber.e(throwable));
}
@NonNull
public LiveData<Resource<Long, ErrorDataTyped<ErrorsTopics>>> getDeleteTopicLiveData() {
return itemRemovedLiveData;
}
@NonNull
public LiveData<Resource<Long, ErrorDataTyped<ErrorsTopics>>> getRestoreTopicLiveData() {
return itemCreatedLiveData;
}
// Exposed to TopicListFragment
public void undoTopicDelete() {
commandHolder.current().undo();
commandHolder.pop();
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/ui/fragments/BaseViewModelFragment.java
package example.powercode.us.redditclonesample.base.ui.fragments;
import android.os.Bundle;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
/**
* Basic fragment which supports dependency injection
* Inspired by https://proandroiddev.com/reducing-viewmodel-provision-boilerplate-in-googles-githubbrowsersample-549818ee72f0
* Still not clear how to make it not to recreate ViewModel on device rotation
*/
public abstract class BaseViewModelFragment<VM extends ViewModel> extends BaseInjectableFragment {
@Inject
ViewModelProvider.Factory factory;
protected VM viewModel;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel = ViewModelProviders.of(this, factory).get(getViewModelClass());
onAttachViewModel();
}
@Override
public void onDestroyView() {
super.onDestroyView();
onDetachViewModel();
viewModel = null;
}
@NonNull
protected abstract Class<VM> getViewModelClass();
/**
* Called when viewModel has been attached to Fragment see {@link Fragment#onActivityCreated(Bundle)}
*/
protected abstract void onAttachViewModel();
/**
* Called when viewModel is about to be detached from the Fragment {@link Fragment#onDestroyView()}
*/
protected abstract void onDetachViewModel();
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
public void setViewModel(@NonNull VM viewModel) {
this.viewModel = viewModel;
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/ui/CanBind.java
package example.powercode.us.redditclonesample.base.ui;
/**
* Created by dev for RedditCloneSample on 19-Jun-18.
*/
public interface CanBind<Data> {
void bind(Data d);
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/app/di/modules/ContributorsModule.java
package example.powercode.us.redditclonesample.app.di.modules;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import example.powercode.us.redditclonesample.app.di.scopes.PerActivity;
import example.powercode.us.redditclonesample.main.di.MainActivityModule;
import example.powercode.us.redditclonesample.main.ui.MainActivity;
/**
* Place for application sub-components such as Activities, Services, BroadcastReceivers
*/
@Module
public interface ContributorsModule {
@ContributesAndroidInjector(modules = {MainActivityModule.class})
@PerActivity
MainActivity contributeSplashScreenActivity();
// @ContributesAndroidInjector
// @PerService
// JobInstanceIdService contributeJobInstanceIdService();
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/model/rules/BRulesTopics.java
package example.powercode.us.redditclonesample.model.rules;
import java.util.Comparator;
import androidx.annotation.NonNull;
import example.powercode.us.redditclonesample.model.entity.TopicEntity;
/**
* Created by dev for RedditCloneSample on 21-Jun-18.
* Business rules
*/
public class BRulesTopics {
public static final int TOPICS_COUNT_WORKING_SET = 20;
@NonNull
public static final Comparator<? super TopicEntity> TOPICS_LIST_COMPARATOR = (topicEntity1, topicEntity2) ->
(topicEntity1.getRating() == topicEntity2.getRating()) ? topicEntity1.title.compareTo(topicEntity2.title)
: Integer.compare(topicEntity2.getRating(), topicEntity1.getRating());
public static boolean isTitleValid(@NonNull CharSequence title) {
return title.length() > 0;
}
public static boolean isRatingValid(int rating, final int ratingLimitAbs) {
return (-ratingLimitAbs <= rating) && (rating <= ratingLimitAbs);
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply from: '../versions.gradle'
android {
compileSdkVersion build_versions.target_sdk
buildToolsVersion build_versions.build_tools
defaultConfig {
applicationId "example.powercode.us.redditclonesample"
minSdkVersion build_versions.min_sdk
targetSdkVersion build_versions.target_sdk
versionCode 3
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
// if set true, than read https://stackoverflow.com/a/40189977/3400881 to update proguard configuration
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dataBinding {
enabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
// To follow DRY principle let's move dependencies into separate gradle file
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation deps.firebase.core
implementation deps.basic.crashlytics
implementation deps.basic.app_compat
implementation deps.basic.ui.constraint_layout
implementation deps.basic.ui.constraint_layout_solver
implementation deps.basic.ui.recyclerview
implementation deps.basic.material_design
implementation deps.rx.java
implementation deps.rx.android
implementation deps.rx.binding.support_v4
implementation deps.rx.binding.appcompat_v7
implementation deps.rx.binding.design
implementation deps.basic.lifecycle.java
implementation deps.basic.lifecycle.extensions
// For controlling LiveData background threads in your tests, add:
// testImplementation deps.arch_core_testing
implementation deps.dagger.runtime
annotationProcessor deps.dagger.compiler
implementation deps.dagger.android_support
annotationProcessor deps.dagger.android_processor
implementation deps.timber
implementation deps.find_bugs_jsr305
debugImplementation deps.leak_canary.debug
releaseImplementation deps.leak_canary.release
testImplementation deps.test.junit
androidTestImplementation deps.test.runner
// androidTestImplementation deps.atsl.rules
// androidTestImplementation(deps.espresso.core, {
// exclude group: 'com.android.support', module: 'support-annotations'
// exclude group: 'com.google.code.findbugs', module: 'jsr305'
// })
// Ensure the no-op dependency is always used in JVM tests.
configurations.all { config ->
if (config.name.contains('UnitTest')
|| config.name.contains('AndroidTest')) {
config.resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'com.squareup.leakcanary' && details.requested.name == 'leakcanary-android') {
details.useTarget(group: details.requested.group, name: 'leakcanary-android-no-op', version: details.requested.version)
}
}
}
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/ui/fragments/BaseInjectableDialogFragment.java
package example.powercode.us.redditclonesample.base.ui.fragments;
import android.content.Context;
import androidx.annotation.CallSuper;
import androidx.appcompat.app.AppCompatDialogFragment;
import dagger.android.support.AndroidSupportInjection;
/**
* Brings support of Dependency Injection into classes which extend {@link AppCompatDialogFragment}
*/
public abstract class BaseInjectableDialogFragment extends AppCompatDialogFragment {
@CallSuper
@Override
public void onAttach(Context context) {
AndroidSupportInjection.inject(this);
super.onAttach(context);
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/error/ErrorBase.java
package example.powercode.us.redditclonesample.base.error;
/**
* Contains error message which will be used by model
*/
public interface ErrorBase {
String getMessage();
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/main/di/TopicListFragmentModule.java
package example.powercode.us.redditclonesample.main.di;
import androidx.annotation.NonNull;
import dagger.Binds;
import dagger.Module;
import example.powercode.us.redditclonesample.app.di.scopes.PerFragment;
import example.powercode.us.redditclonesample.base.di.BaseInjectableFragmentModule;
import example.powercode.us.redditclonesample.main.ui.TopicListFragment;
import example.powercode.us.redditclonesample.main.ui.TopicsAdapter;
/**
* Binds activity context
*/
@Module(includes = {BaseInjectableFragmentModule.class})
public interface TopicListFragmentModule {
@PerFragment
@Binds
TopicsAdapter.InteractionListener bindTopicsAdapterInteractionListener(@NonNull final TopicListFragment fragment);
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/ui/BaseInjectableActivity.java
package example.powercode.us.redditclonesample.base.ui;
import android.os.Bundle;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import dagger.android.AndroidInjection;
/**
* Performs dependency injection for the given Activity
*/
public abstract class BaseInjectableActivity extends AppCompatActivity {
@CallSuper
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/main/vm/TopicCreateViewModel.java
package example.powercode.us.redditclonesample.main.vm;
import android.app.Application;
import java.util.Objects;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import example.powercode.us.redditclonesample.R;
import example.powercode.us.redditclonesample.base.error.ErrorDataTyped;
import example.powercode.us.redditclonesample.common.arch.SingleLiveEvent;
import example.powercode.us.redditclonesample.model.common.Resource;
import example.powercode.us.redditclonesample.model.error.ErrorsTopics;
import example.powercode.us.redditclonesample.model.repository.RepoTopics;
import example.powercode.us.redditclonesample.utils.RxUtils;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;
/**
* Created by dev for RedditCloneSample on 18-Jun-18.
*/
public class TopicCreateViewModel extends ViewModel {
@NonNull
private final MutableLiveData<Resource<Long, ErrorDataTyped<ErrorsTopics>>> itemChangedLiveData = new SingleLiveEvent<>();
@NonNull
private final Application app;
@NonNull
private final RepoTopics repoTopics;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
@Nullable
private Disposable disposableCreateTopic = null;
@Inject
TopicCreateViewModel(@NonNull Application app, @NonNull RepoTopics repoTopics) {
this.app = app;
this.repoTopics = repoTopics;
Timber.d("VM of type [ %s ] constructor called \nid %s", TopicCreateViewModel.class.getSimpleName(), this);
}
@Override
protected void onCleared() {
super.onCleared();
RxUtils.clearDisposableSafe(compositeDisposable);
RxUtils.clearDisposableSafe(disposableCreateTopic);
Timber.d("VM of type [ %s ] was cleared \nid %s", TopicCreateViewModel.class.getSimpleName(), this);
}
public void newTopic(@NonNull String title, int rating) {
RxUtils.clearDisposableSafe(disposableCreateTopic);
disposableCreateTopic = createTopic(title, rating);
}
private Disposable createTopic(@NonNull String title, int rating) {
return repoTopics
.createTopic(title, rating)
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> {
itemChangedLiveData.setValue(Resource.loading(null));
})
.subscribe(resultCreateTopic -> {
Objects.requireNonNull(resultCreateTopic.second);
if (resultCreateTopic.second) {
itemChangedLiveData.setValue(Resource.success(resultCreateTopic.first, null));
} else {
itemChangedLiveData.setValue(
Resource.error(
new ErrorDataTyped<>(app
.getResources().getString(R.string.error_topic_create),
ErrorsTopics.NO_ITEM),
resultCreateTopic.first
)
);
}
}, throwable -> Timber.e(throwable));
}
@NonNull
public LiveData<Resource<Long, ErrorDataTyped<ErrorsTopics>>> getCreateTopicLiveData() {
return itemChangedLiveData;
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/ui/BaseViewModelFragmentActivity.java
package example.powercode.us.redditclonesample.base.ui;
import android.os.Bundle;
import javax.inject.Inject;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
/**
* Performs dependency injection for the given Activity
*/
public abstract class BaseViewModelFragmentActivity<VM extends ViewModel> extends BaseInjectableFragmentActivity {
@Inject
ViewModelProvider.Factory factory;
protected VM viewModel;
@CallSuper
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = ViewModelProviders.of(this, factory).get(getViewModelClass());
}
@CallSuper
@Override
protected void onDestroy() {
super.onDestroy();
onDetachFromViewModel();
viewModel = null;
}
@NonNull
protected abstract Class<VM> getViewModelClass();
protected abstract void onDetachFromViewModel();
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/ui/common/HasId.java
package example.powercode.us.redditclonesample.base.ui.common;
import androidx.annotation.NonNull;
/**
* Created by dev for RedditCloneSample on 19-Jun-18.
*/
public interface HasId<IdType> {
@NonNull
IdType getId();
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/app/di/qualifiers/ParentFragmentManager.java
package example.powercode.us.redditclonesample.app.di.qualifiers;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Qualifier;
import androidx.fragment.app.FragmentActivity;
/**
* Qualifier for Activity's FragmentManager {@link FragmentActivity#getSupportFragmentManager()}
*/
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ParentFragmentManager {
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/di/BaseInjectableFragmentActivityModule.java
package example.powercode.us.redditclonesample.base.di;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import dagger.Binds;
import dagger.Module;
import dagger.Provides;
import example.powercode.us.redditclonesample.app.di.qualifiers.ParentFragmentManager;
import example.powercode.us.redditclonesample.app.di.scopes.PerActivity;
import example.powercode.us.redditclonesample.base.ui.BaseInjectableActivity;
import example.powercode.us.redditclonesample.base.ui.BaseInjectableFragmentActivity;
/**
* Binds activity context
*/
@Module (includes = {BaseInjectableActivityModule.class})
public interface BaseInjectableFragmentActivityModule {
@Binds
@PerActivity
BaseInjectableActivity bindActivity(final BaseInjectableFragmentActivity activity);
@Provides
@PerActivity
@ParentFragmentManager
static FragmentManager provideFragmentManager(final @NonNull AppCompatActivity activity) {
return activity.getSupportFragmentManager();
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/main/vm/MainViewModel.java
package example.powercode.us.redditclonesample.main.vm;
import android.app.Application;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
/**
* Created by dev for RedditCloneSample on 13-Jun-18.
*/
public final class MainViewModel extends AndroidViewModel {
@Inject
MainViewModel(@NonNull Application application) {
super(application);
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/main/vm/command/ReceiverCommandRestorer.java
package example.powercode.us.redditclonesample.main.vm.command;
import androidx.annotation.NonNull;
import example.powercode.us.redditclonesample.model.entity.VoteType;
/**
* Created by dev for RedditCloneSample on 03-Jul-18.
*/
public interface ReceiverCommandRestorer {
void voteTopic(long id, @NonNull VoteType vt);
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/base/ui/common/DefaultTagGenerator.java
package example.powercode.us.redditclonesample.base.ui.common;
import androidx.annotation.NonNull;
/**
* Created by dev for RedditCloneSample on 14-Jun-18.
*/
public enum DefaultTagGenerator {
INSTANCE;
@NonNull
static final String PREFIX = "FRAGMENT_TAG_";
@NonNull
private final GeneratorFragmentTagBase<Class<?>> generator = args -> PREFIX + args.getSimpleName();
@NonNull
public static <T> String generate(@NonNull Class<T> args) {
return INSTANCE.generator.generate(args);
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/app/di/modules/ToolsModule.java
package example.powercode.us.redditclonesample.app.di.modules;
import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import androidx.annotation.NonNull;
import dagger.Module;
import dagger.Provides;
import example.powercode.us.redditclonesample.app.di.scopes.PerApplication;
/**
* Created by dev for RedditCloneSample on 06-Jul-18.
* Tool classes instantiation, bindings etc.
*/
@Module
public interface ToolsModule {
@PerApplication
@Provides
static RefWatcher provideLeakCanaryWatcher(@NonNull Application app) {
return LeakCanary.install(app);
}
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/model/repository/RepoTopics.java
package example.powercode.us.redditclonesample.model.repository;
import java.util.Comparator;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import example.powercode.us.redditclonesample.base.error.ErrorDataTyped;
import example.powercode.us.redditclonesample.model.common.Resource;
import example.powercode.us.redditclonesample.model.entity.EntityActionType;
import example.powercode.us.redditclonesample.model.entity.TopicEntity;
import example.powercode.us.redditclonesample.model.entity.VoteType;
import example.powercode.us.redditclonesample.model.error.ErrorsTopics;
import io.reactivex.Observable;
import io.reactivex.Single;
/**
* Created by dev for RedditCloneSample on 19-Jun-18.
*/
public interface RepoTopics {
@NonNull
Single<Resource<List<TopicEntity>, ErrorDataTyped<ErrorsTopics>>> fetchTopics(@Nullable Comparator<? super TopicEntity> sortCmp, int count);
@NonNull
Single<Pair<Long, Boolean>> applyVoteToTopic(long id, @NonNull VoteType vt);
@NonNull
Single<Pair<Long, Boolean>> createTopic(@NonNull String title, int rating);
@NonNull
Single<Pair<Long, Boolean>> removeTopic(long id);
@NonNull
Single<Resource<TopicEntity, ErrorDataTyped<ErrorsTopics>>> getById(long topicId);
@NonNull
Observable<Pair<TopicEntity, EntityActionType>> onTopicChangeObservable();
}
<file_sep>/app/src/main/java/example/powercode/us/redditclonesample/main/ui/TopicsTouchHelper.java
package example.powercode.us.redditclonesample.main.ui;
import android.graphics.Canvas;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import example.powercode.us.redditclonesample.common.rv.GenericItemTouchHelperSimpleCallback;
/**
* Created by dev for RedditCloneSample on 22-Jun-18.
*/
public final class TopicsTouchHelper extends GenericItemTouchHelperSimpleCallback<RecyclerView, TopicsAdapter.ItemViewHolder> {
public interface InteractionListener<RV extends RecyclerView, VH extends RecyclerView.ViewHolder> {
void onSwiped(VH viewHolder, int direction);
boolean onMove(RV recyclerView, VH viewHolder, VH target);
}
@NonNull
private final InteractionListener<RecyclerView, TopicsAdapter.ItemViewHolder> listener;
TopicsTouchHelper(int dragDirs, int swipeDirs, @NonNull InteractionListener<RecyclerView, TopicsAdapter.ItemViewHolder> listener) {
super(dragDirs, swipeDirs);
this.listener = listener;
}
@Override
public boolean onMoveCallback(RecyclerView recyclerView, TopicsAdapter.ItemViewHolder viewHolder, TopicsAdapter.ItemViewHolder target) {
return listener.onMove(recyclerView, viewHolder, target);
}
@Override
public void onSwipedCallback(TopicsAdapter.ItemViewHolder viewHolder, int direction) {
listener.onSwiped(viewHolder, direction);
}
@Override
public void onSelectedChangedCallback(TopicsAdapter.ItemViewHolder viewHolder, int actionState) {
if (viewHolder != null) {
getDefaultUIUtil().onSelected(viewHolder.getForeground().getRoot());
}
}
@Override
public void clearViewCallback(RecyclerView recyclerView, TopicsAdapter.ItemViewHolder viewHolder) {
getDefaultUIUtil().clearView(viewHolder.getForeground().getRoot());
}
@Override
public void onChildDrawCallback(Canvas c, RecyclerView recyclerView, TopicsAdapter.ItemViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
getDefaultUIUtil().onDraw(c, recyclerView, viewHolder.getForeground().getRoot(), dX, dY, actionState, isCurrentlyActive);
}
}
<file_sep>/versions.gradle
/**
* Shared file between builds so that they can all use the same dependencies and
* maven repositories.
**/
ext.deps = [:]
/**
* @param orig object to be deep copied
* @return deep copy of orig
*/
private static def deepCopy(orig) {
OutputStream bos = new ByteArrayOutputStream()
ObjectOutputStream oos = new ObjectOutputStream(bos)
oos.writeObject(orig)
oos.close()
InputStream bin = new ByteArrayInputStream(bos.toByteArray())
ObjectInputStream ois = new ObjectInputStream(bin)
return ois.readObject()
}
def versions = [:]
versions.lifecycle = '2.0.0'
versions.app_compat = '1.0.0'
versions.material_design = '1.0.0'
versions.firebase = [:]
versions.firebase.ml_vision = '17.0.0'
versions.firebase.core = '16.0.3'
versions.crashlytics = '2.9.5'
versions.constraint_layout = '1.1.3'
versions.recyclerview = '1.0.0'
versions.dagger = '2.16'
versions.rx = [:]
versions.rx.java = '2.2.2'
versions.rx.android = '2.1.0'
versions.easy_permissions = '1.3.0'
versions.timber = '4.7.1'
versions.rxbinding = '2.1.1'
versions.leak_canary = '1.6.1'
versions.stetho = '1.5.0'
versions.find_bugs_jsr305 = '3.0.2'
//versions.retrofit = '2.4.0'
//versions.okhttp = '3.11.0'
def packages = [:]
// Debug and diagnostic tools
packages.crashlytics = 'com.crashlytics.sdk.android'
packages.find_bugs = 'com.google.code.findbugs'
packages.leak_canary = 'com.squareup.leakcanary'
packages.stetho = 'com.facebook.stetho'
packages.app_compat = 'androidx.appcompat'
packages.lifecycle = 'androidx.lifecycle'
packages.android = 'com.google.android'
packages.firebase = 'com.google.firebase'
packages.constraint_layout = 'androidx.constraintlayout'
packages.recyclerview = 'androidx.recyclerview'
packages.dagger = 'com.google.dagger'
packages.rxjava = 'io.reactivex.rxjava2'
packages.test = 'com.android.support.test'
packages.jwharton_prefix = 'com.jakewharton'
packages.rxbinding2 = "${packages.jwharton_prefix}.rxbinding2"
def deps = [:]
// basic
def basic = [:]
basic.app_compat = "${packages.app_compat}:appcompat:${versions.app_compat}"
basic.crashlytics = "${packages.crashlytics}:crashlytics:${versions.crashlytics}"
basic.ui = [:]
basic.ui.constraint_layout = "${packages.constraint_layout}:constraintlayout:${versions.constraint_layout}"
basic.ui.constraint_layout_solver = "${packages.constraint_layout}:constraintlayout-solver:${versions.constraint_layout}"
basic.ui.recyclerview = "${packages.recyclerview}:recyclerview:${versions.recyclerview}"
//com.google.android.material:material:1.0.0-alpha1
basic.material_design = "${packages.android}.material:material:${versions.material_design}"
basic.lifecycle = [:]
basic.lifecycle.java = "${packages.lifecycle}:lifecycle-common-java8:${versions.lifecycle}"
//deps.arch_core_testing = "${packages.arch_prefix}.core:core-testing:${versions.arch_components}"
basic.lifecycle.extensions = "${packages.lifecycle}:lifecycle-extensions:${versions.lifecycle}"
deps.basic = basic
def dagger = [:]
dagger.runtime = "${packages.dagger}:dagger:${versions.dagger}"
dagger.compiler = "${packages.dagger}:dagger-compiler:${versions.dagger}"
dagger.android_support = "${packages.dagger}:dagger-android-support:${versions.dagger}"
dagger.android_processor = "${packages.dagger}:dagger-android-processor:${versions.dagger}"
deps.dagger = dagger
def rx = [:]
rx.java = "${packages.rxjava}:rxjava:${versions.rx.java}"
rx.android = "${packages.rxjava}:rxandroid:${versions.rx.android}"
def rxbinding2 = [:]
rxbinding2.support_v4 = "${packages.rxbinding2}:rxbinding-support-v4:${versions.rxbinding}"
rxbinding2.appcompat_v7 = "${packages.rxbinding2}:rxbinding-appcompat-v7:${versions.rxbinding}"
rxbinding2.design = "${packages.rxbinding2}:rxbinding-design:${versions.rxbinding}"
rx.binding = rxbinding2
deps.rx = rx
deps.firebase = [:]
deps.firebase.core = "${packages.firebase}:firebase-core:${versions.firebase.core}"
//deps.firebase.ml_vision = "${packages.firebase}:firebase-ml-vision:${versions.firebase.ml_vision}"
deps.easy_permissions = "pub.devrel:easypermissions:${versions.easy_permissions}"
deps.timber = "${packages.jwharton_prefix}.timber:timber:${versions.timber}"
def leak_canary = [:]
leak_canary.debug = "${packages.leak_canary}:leakcanary-android:${versions.leak_canary}"
leak_canary.release = "${packages.leak_canary}:leakcanary-android-no-op:${versions.leak_canary}"
deps.leak_canary = leak_canary
deps.find_bugs_jsr305 = "${packages.find_bugs}:jsr305:${versions.find_bugs_jsr305}"
deps.test = [:]
deps.test.junit = "junit:junit:4.12"
deps.test.runner = "androidx.test:runner:1.1.0-alpha4"
ext.deps = deps
def build_versions = [:]
build_versions.min_sdk = 21
build_versions.target_sdk = 28
build_versions.build_tools = "28.0.3"
ext.build_versions = build_versions
ext {
//APP VERSION
default_version_name = "0.0.2"
//keep this value for dev builds to be consistent with production builds
default_version_code = 3
retrieveVersionName = project.hasProperty('version_name') ? version_name : default_version_name
retrieveVersionCode =
project.hasProperty('version_code') ? version_code.toInteger() : default_version_code
} | c6869ff31b368d127e93cfcd08b4f49605dd5320 | [
"Markdown",
"Java",
"Gradle"
] | 29 | Markdown | powercode-team/RedditCloneSample | 2438a191c9b86615769e172bc9702b766b11077b | 304654a1916e3f02c631cd559d6d597c8fb87105 |
refs/heads/master | <file_sep># encoding: utf-8
module DOTIW
autoload :VERSION, 'dotiw/version'
autoload :TimeHash, 'dotiw/time_hash'
end # DOTIW
module ActionView
module Helpers
module DateHelper
alias_method :old_distance_of_time_in_words, :distance_of_time_in_words
def distance_of_time_in_words_hash(from_time, to_time, options = {})
from_time = from_time.to_time if !from_time.is_a?(Time) && from_time.respond_to?(:to_time)
to_time = to_time.to_time if !to_time.is_a?(Time) && to_time.respond_to?(:to_time)
DOTIW::TimeHash.new((from_time - to_time).abs, from_time, to_time, options).to_hash
end
def distance_of_time(seconds, options = {})
display_time_in_words DOTIW::TimeHash.new(seconds).to_hash, options
end
def distance_of_time_in_words(from_time, to_time, include_seconds = false, options = {})
return old_distance_of_time_in_words(from_time, to_time, include_seconds, options) if options.delete(:vague)
hash = distance_of_time_in_words_hash(from_time, to_time, options)
display_time_in_words(hash, include_seconds, options)
end
def distance_of_time_in_percent(from_time, current_time, to_time, options = {})
options[:precision] ||= 0
distance = to_time - from_time
result = ((current_time - from_time) / distance) * 100
number_with_precision(result, options).to_s + "%"
end
private
def display_time_in_words(hash, include_seconds = false, options = {})
options.symbolize_keys!
I18n.locale = options[:locale] if options[:locale]
hash.delete(:seconds) if !include_seconds && hash[:minutes]
# Remove all the values that are nil or excluded. Keep the required ones.
hash.delete_if do |key, value|
value.nil? || value.zero? || (!options[:except].nil? && options[:except].include?(key.to_s)) ||
(options[:only] && !options[:only].include?(key.to_s))
end
options.delete(:except)
options.delete(:only)
highest_measures = options.delete(:highest_measures)
highest_measures = 1 if options.delete(:highest_measure_only)
if highest_measures
keys = [:years, :months, :days, :hours, :minutes, :seconds]
first_index = keys.index(hash.first.first)
keys = keys[first_index, highest_measures]
hash.delete_if { |key, value| !keys.include?(key) }
end
output = hash.map { |key, value| value.to_s + ' ' + I18n.t(key, :count => value, :default => key.to_s) }
# maybe only grab the first few values
if options[:precision]
output = output[0...options[:precision]]
options.delete(:precision)
end
output.to_sentence(options)
end
end # DateHelper
end # Helpers
end # ActionView
| 46ae1fe42e03aea6f1b066b44d616c367fe6ee37 | [
"Ruby"
] | 1 | Ruby | whitered/dotiw | 3bef7ca8282237dd499741879b601e2b054173eb | 6d4481db8d1f19b222491fb17d38021c58f70283 |
refs/heads/master | <repo_name>PetarGK/microservice-example-cicd<file_sep>/lib/lambda-stack.ts
import * as cdk from '@aws-cdk/core';
import { NodejsFunction } from '@aws-cdk/aws-lambda-nodejs'
import { Runtime, Alias } from '@aws-cdk/aws-lambda';
import { LambdaDeploymentGroup, LambdaDeploymentConfig } from '@aws-cdk/aws-codedeploy';
import { RestApi, LambdaIntegration } from '@aws-cdk/aws-apigateway'
export class LambdaStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const getTodosLambda = new NodejsFunction(this, 'get-todos', {
entry: 'lib/lambda-stack/get-todos.ts',
runtime: Runtime.NODEJS_12_X,
memorySize: 512,
minify: true
});
const addTodoLambda = new NodejsFunction(this, 'add-todo', {
entry: 'lib/lambda-stack/add-todo.ts',
runtime: Runtime.NODEJS_12_X,
memorySize: 512,
minify: true
});
/*
const getTodosVersion = getTodosLambda.addVersion(new Date().toISOString());
const getTodosAlias = new Alias(this, 'getTodosAlias', {
aliasName: 'Prod',
version: getTodosVersion,
});
new LambdaDeploymentGroup(this, 'DeploymentGroup', {
alias: getTodosAlias,
deploymentConfig: LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
});
*/
const api = new RestApi(this, 'example-api', { })
const v1 = api.root.addResource('v1')
const todos = v1.addResource('todos')
const getTodosIntegration = new LambdaIntegration(getTodosLambda)
const addTodoIntegration = new LambdaIntegration(addTodoLambda)
const getTodosMethod = todos.addMethod('GET', getTodosIntegration, { apiKeyRequired: true })
const addTodoMethod = todos.addMethod('POST', addTodoIntegration, { apiKeyRequired: true })
const key = api.addApiKey('ApiKey');
const plan = api.addUsagePlan('UsagePlan', {
name: 'Easy',
apiKey: key,
throttle: {
rateLimit: 10,
burstLimit: 2
}
});
plan.addApiStage({
stage: api.deploymentStage,
throttle: [
{
method: getTodosMethod,
throttle: {
rateLimit: 10,
burstLimit: 2
}
},
{
method: addTodoMethod,
throttle: {
rateLimit: 10,
burstLimit: 2
}
},
]
});
}
}
<file_sep>/lib/pipeline-stack.ts
import * as cdk from '@aws-cdk/core';
import { Pipeline, Artifact } from '@aws-cdk/aws-codepipeline'
import { GitHubSourceAction, GitHubTrigger, CodeBuildAction, CloudFormationCreateUpdateStackAction } from '@aws-cdk/aws-codepipeline-actions'
import { StringParameter } from '@aws-cdk/aws-ssm'
import { SecretValue } from '@aws-cdk/core';
import { PipelineProject, LinuxBuildImage, BuildSpec } from '@aws-cdk/aws-codebuild';
import { Role, ServicePrincipal, ManagedPolicy } from '@aws-cdk/aws-iam';
export class PipelineStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const pipeline = new Pipeline(this, "ExamplePipeline", {
pipelineName: "microservice-example-cicd",
restartExecutionOnUpdate: true
})
const sourceOutput = new Artifact();
const repositoryUrl = StringParameter.fromStringParameterAttributes(this, 'GithubRepositoryName', {
parameterName: '/microservice-example-cicd/RepositoryUrl',
}).stringValue;
const sourceAction = new GitHubSourceAction({
actionName: 'CodeSource',
owner: 'PetarGK',
repo: repositoryUrl,
oauthToken: SecretValue.secretsManager('/microservice-example-cicd/GithubOAuthToken'),
output: sourceOutput,
branch: 'master',
trigger: GitHubTrigger.WEBHOOK
})
pipeline.addStage({
stageName: 'Source',
actions: [sourceAction]
})
const serviceRole = new Role(this, 'CodeBuildServiceRole', {
assumedBy: new ServicePrincipal('codebuild.amazonaws.com'),
managedPolicies: [ManagedPolicy.fromAwsManagedPolicyName("AdministratorAccess")]
})
const cdkBuildOutput = new Artifact('CdkBuildOutput');
const cdkBuild = new PipelineProject(this, 'CdkBuild', {
environment: {
buildImage: LinuxBuildImage.UBUNTU_14_04_NODEJS_10_14_1
},
role: serviceRole,
buildSpec: BuildSpec.fromObject({
version: '0.2',
phases: {
install: {
commands: [
'npm install -g aws-cdk',
'npm install'
]
},
build: {
commands: 'cdk --app "npx ts-node bin/microservice-example-app.ts" --require-approval=never deploy "*"'
}
}
})
})
pipeline.addStage({
stageName: 'Deploy',
actions: [
new CodeBuildAction({
actionName: 'CodeDeploy',
project: cdkBuild,
input: sourceOutput,
outputs: [cdkBuildOutput]
})
]
})
}
}
| 5c8d8828a4f3a4b2c48f474a6196e15696f63695 | [
"TypeScript"
] | 2 | TypeScript | PetarGK/microservice-example-cicd | 611346bf16748c1a312706a2f328f6778e5c3e4d | f371effe04b066bd620244223d7068e890722491 |
refs/heads/master | <file_sep>-- VIEW 1:SE
-- Relations involved: employee, adoptionapplication
-- Creates a view showing information on all employees not currently assigned to an adoption application
CREATE VIEW unassigned_employees
AS
SELECT eid,name
FROM employee
WHERE eid NOT IN (SELECT eid FROM adoptionapplication)
-- QUERY:
-- Results in ordered table of above view with name and sorted by eid
SELECT *
FROM unassigned_employees U, manager M
WHERE U.eid = M.eid
ORDER BY U.eid
--SQL UPDATE:
--Updates unassigned_employees VIEW to show status of employee next to name
UPDATE unassigned_employees
SET name = CONCAT(name, ' SLACKER')
WHERE eid > 1000
--VIEW 2:
--Relations involved: potentialhousehold, previoushistory)
--Creates a view showing all potiential households that has no previous history with the adoption center and are new to adoption
CREATE VIEW new_households
AS
SELECT *
FROM potentialhousehold
WHERE address NOT IN (SELECT address FROM previoushistory)
--QUERY:
--Shows the new_households that have adoptionapplications currently in the system ordered by wage
SELECT *
FROM new_households N, adoptionapplication A
WHERE N.address = A.address
ORDER BY wage
--SQL UPDATE:
--Flags households with below six figure income to be looked into
UPDATE new_households
SET name = CONCAT(name, ' ***')
WHERE wage < 100000
--Updateable:
--View 1 and View 2 are updateable under certain conditions as the database is able to identify the underlying base tables with the eid and address respectively. String fields are updatable as along as the strings do not exceed the character limit of 30. For a view to be updatable in SQL the columns must be only under one base table. The columns also cannot be defined with aggregate functions or using groups. The view should also not have any distinct clauses in its definition and not be dervied from some calculation.
<file_sep>--Check constraints:
ALTER TABLE potentialhousehold
ADD CONSTRAINT check_positive_income CHECK (wage > 0)
ALTER TABLE pet
ADD CONSTRAINT check_positive_weight CHECK (weight > 0)
--Violation modifications:
INSERT INTO potentialhousehold
(address, job, name, wage)
VALUES ('808 Heartbreak Road', 'Pastor', 'Omari West', -20)
INSERT INTO pet
(pid, weight)
VALUES ('9999999', -5)
<file_sep>/*
1) Updating pet's condition
Changing the current history to previous history.
*/
UPDATE medicalhistory
SET pcondition = ccondition, ccondition = ''
WHERE ccondition != '';
/*
2) Potential household's denial document process
Data preprocessing. A new potential household submits an application for pid 19582 (German Shephered)
*/
INSERT INTO potentialhousehold VALUES ('375 Rue de la Concorde, Montreal, QC, H3A1J3','Student','<NAME>',40000);
INSERT INTO adoptionapplication VALUES ('A0011','2020-02-28',2049,'375 Rue de la Concorde, Montreal, QC, H3A1J3');
INSERT INTO received VALUES ('A0011',19582);
/*
Creating a new document which is not assigned to potential household yet..
*/
INSERT INTO document(
SELECT COUNT(docnumber) + 1, CURRENT_DATE
FROM document);
/*
Creating a denial document which is denied by too low wage
*/
INSERT INTO denialdocument
SELECT COUNT(docnumber),'The potential household wage is too low to adopt the pet'
FROM document;
/*
Sending a denial document to the potential household
*/
INSERT INTO receive(
SELECT COUNT(docnumber),address
FROM document d JOIN potentialhousehold p
on p.wage < 50000
GROUP BY address
LIMIT 1);
/*
3) Deleting denied applications from the database (Document remains for future information)
Delete the application data if it gets denied
*/
DELETE FROM received
WHERE aid in (SELECT adoptionapplication.aid
FROM (SELECT address
FROM denialdocument d JOIN receive r
ON d.docnumber = r.docnumber
) as denied, adoptionapplication
WHERE denied.address = adoptionapplication.address);
DELETE FROM adoptionapplication
WHERE aid in (SELECT adoptionapplication.aid
FROM (SELECT address
FROM denialdocument d JOIN receive r
ON d.docnumber = r.docnumber
) as denied, adoptionapplication
WHERE denied.address = adoptionapplication.address);
<file_sep>/* Delete potential households that have been adopted. In a future deliverable will add this information to previoushistory table instead */
DELETE FROM received
WHERE aid in (SELECT adoptionapplication.aid
FROM (SELECT address
FROM accepteddocument a JOIN receive r
ON a.docnumber = r.docnumber
) as accepted, adoptionapplication
WHERE accepted.address = adoptionapplication.address);
DELETE FROM adoptionapplication WHERE address in
(SELECT address
FROM accepteddocument a JOIN receive r
ON a.docnumber = r.docnumber);
DELETE FROM receive WHERE address in
(SELECT address
FROM accepteddocument a JOIN receive r
ON a.docnumber = r.docnumber);
DELETE FROM potentialhousehold WHERE address in
(SELECT address
FROM accepteddocument a JOIN receive r
ON a.docnumber = r.docnumber);
<file_sep>/*
1)--selecting the document number, transaction ID, total price and payment method for each accepted document in order
*/
SELECT accepteddocument.docnumber,accepteddocument.transactionid,totalprice,paymentmethod
FROM accepteddocument, payment
WHERE accepteddocument.transactionid = payment.transactionid
ORDER by accepteddocument.docnumber;
/*
2)--selecting the average weight of pets which are donated
*/
SELECT AVG(weight)
FROM pet, donated
WHERE pet.pid = donated.pid;
/*
3)--selecting the insurance which has the maximum monthly cost
*/
SELECT insurancenumber, monthlycost
FROM petinsurance
WHERE monthlycost = (
SELECT MAX(monthlycost)
FROM petinsurance
);
/*
4)--getting the number of application received for each species
*/
SELECT species,COUNT(*) as totalnum
FROM (SELECT pet.species
FROM pet,received
WHERE pet.pid = received.pid)as petsapplied
GROUP by species;
/*
5)--getting the pet id and the adopter's information who has applied after this year
*/
SELECT pid,petsapplication.aid,date,address
FROM (SELECT pet.pid, received.aid
FROM pet,received
WHERE pet.pid = received.pid
)as petsapplication
INNER JOIN adoptionapplication
ON petsapplication.aid = adoptionapplication.aid
WHERE date > '2020-01-01'
ORDER by date;
<file_sep>INSERT into employee VALUES(2049,'<NAME>','1192 Courtright Street, Ladd, ND, 58623',11);
INSERT into employee VALUES(1034,'<NAME>','713 chemin Hudson, Montreal, QC, H4J1M9',19);
INSERT into employee VALUES(4092,'<NAME>','1764 Ste. <NAME>, Montreal, QC, H3C3X6',10);
INSERT into employee VALUES(3048,'<NAME>','1128 chemin Hudson, Montreal, QC, H4J1M9',16);
INSERT into employee VALUES(1023,'<NAME>','1185 rue de la Gauchetière, Montreal, QC, H3B2M3',20);
INSERT INTO employee VALUES (9018, '<NAME>', '989 St. Antoine W. Montreal, QC, H6K9S7', 22);
INSERT INTO employee VALUES (2765, '<NAME>', '6529 Rue Peel, Montreal, QC, H9S7F0', 21);
INSERT INTO employee VALUES (1299, '<NAME>', '2420 Rue Drummond, Montreal, QC, H9D7G9', 21);
INSERT INTO employee VALUES (7811, '<NAME>', '11 Rue Stanley, Montreal, QC, H1K0F8', 22);
INSERT INTO employee VALUES (1992, '<NAME>', '4421 Rue du Fort, Montreal, QC, H2K9D6', 21);;
INSERT INTO manager VALUES (9018, DATE '2017-08-20');
INSERT INTO manager VALUES (2765, DATE '2018-01-06');
INSERT INTO manager VALUES (7811, DATE '2015-09-10');
INSERT INTO manager VALUES (1992, DATE '2019-11-30');
INSERT INTO manager VALUES (1299, DATE '2020-02-02');
INSERT INTO kennel VALUES(01);
INSERT INTO kennel VALUES(02);
INSERT INTO kennel VALUES(03);
INSERT INTO kennel VALUES(04);
INSERT INTO kennel VALUES(05);
INSERT INTO kennel VALUES(06);
INSERT INTO kennel VALUES(07);
INSERT INTO kennel VALUES(08);
INSERT INTO kennel VALUES(09);
INSERT INTO kennel VALUES(10);
INSERT INTO kennel VALUES(11);
INSERT INTO kennel VALUES(12);
INSERT INTO kennel VALUES(13);
INSERT INTO kennel VALUES(14);
INSERT INTO potentialhousehold VALUES ('1975 Rue Clarke, Montreal, QC, H6U9I8', 'Lawyer', '<NAME>', 150000);
INSERT INTO potentialhousehold VALUES ('790 <NAME>, Montreal, QC, H8D9Y6', 'Veterinarian', '<NAME>', 70000);
INSERT INTO potentialhousehold VALUES ('66 W Hastings St, Vancouver, BC, V8T9Y2', 'Hairdresser', '<NAME>', 60000);
INSERT INTO potentialhousehold VALUES ('19284 Bloor St. Toronto, ON, D8Y9Q6', 'Forensic Analyst', '<NAME>', 120000);
INSERT INTO potentialhousehold VALUES ('719 Rue de la Montagne, Montreal, QC, H3S8E9', 'Dental Receptionist', '<NAME>', 75000);
INSERT INTO potentialhousehold VALUES ('44 Boulevard de Maisonneuve, Montreal, QC, H7D9K8', 'Software Developer', '<NAME>', 115000);
INSERT INTO potentialhousehold VALUES ('88 <NAME>, Montreal, QC, H9AK0G', 'Aesthetician', '<NAME>', 70000);
INSERT INTO potentialhousehold VALUES ('124 <NAME>, Montreal, QC, H1K0F8', '<NAME>', '<NAME>', 80000);
INSERT INTO potentialhousehold VALUES ('777 <NAME>, Montreal, QC, H6S9G0', 'Investment Banker', '<NAME>', 140000);
INSERT INTO potentialhousehold VALUES ('505 W Georgia St, Vancouver, BC, V9S7G9', 'Fashion Model', '<NAME>', 170000);
INSERT INTO medicalhistory (mid) VALUES (30392);
INSERT INTO medicalhistory (mid) VALUES (82950);
INSERT INTO medicalhistory (mid) VALUES (84959);
INSERT INTO medicalhistory (mid) VALUES (22196);
INSERT INTO medicalhistory (mid) VALUES (92593);
INSERT INTO medicalhistory (mid) VALUES (39102);
INSERT INTO medicalhistory (mid) VALUES (10492);
INSERT INTO medicalhistory (mid) VALUES (22958);
INSERT INTO medicalhistory (mid) VALUES (77819);
INSERT INTO medicalhistory (mid) VALUES (23475);
INSERT INTO medicalhistory (mid) VALUES (99019);
INSERT INTO medicalhistory (mid) VALUES (12672);
INSERT INTO medicalhistory (mid) VALUES (19602);
INSERT INTO medicalhistory (mid) VALUES (11928);
INSERT INTO pet VALUES (12987, '2020-FEB-01', 10.5, 'Beagle', 'Dog', 01, 30392, '2014-MAY-01', 'Ella');
INSERT INTO pet VALUES (19582, '2020-JAN-22', 20, '<NAME>', 'Dog', 02, 82950, '2012-AUG-09', 'Gilbert');
INSERT INTO pet VALUES (38592, '2019-DEC-30', 5.5, 'Siamese', 'Cat', 03, 84959, '2018-SEP-30', 'Nancy');
INSERT INTO pet VALUES (84957, '2019-NOV-28', 3, 'Bengal', 'Cat', 04, 22196, '2019-NOV-01', 'Max');
INSERT INTO pet VALUES (71905, '2020-FEB-15', 6, 'Miniature Poodle', 'Dog', 05, 92593, '2013-04-13', 'Sweetie');
INSERT INTO pet VALUES (82928, DATE '2019-OCT-14', 22, 'Golden Retriever', 'Dog', 06, 39102, '2010-FEB-02', 'Buddy');
INSERT INTO pet VALUES (12304, DATE '2019-OCT-10', 4.5, 'Persian', 'Cat', 07, 10492, '2011-MAY-11', 'Leona');
INSERT INTO pet VALUES (67819, DATE '2020-JAN-05', 3.5, 'Sphynx', 'Cat', 08, 22958, '2017-JUN-08', 'Martian');
INSERT INTO pet VALUES (39201, DATE '2020-JAN-04', 80, 'Great Dane', 'Dog', 09, 77819,'2016-JUL-24', 'Zeus');
INSERT INTO pet VALUES (88725, DATE '2020-FEB-14', 30.5, 'Australian Shepherd', 'Dog', 10, 23475, DATE '2009-JUN-22', 'Charlie');
INSERT INTO pet VALUES (27491, DATE '2019-SEP-10', 5.5, 'Ragdoll', 'Cat', 11, 99019, DATE '2011-DEC-20', 'Lilly');
INSERT INTO pet VALUES (28592, DATE '2018-DEC-30', 14.5, '<NAME>', 'Dog', 12, 12672, DATE '2012-NOV-01', 'Terry');
INSERT INTO pet VALUES (91058, DATE '2018-NOV-12', 9.5, 'Maltese', 'Dog', 13, 19602, DATE '2013-OCT-04', 'Luna');
INSERT INTO pet VALUES (71002, DATE '2018-OCT-30', 4.5, 'Russian Blue', 'Cat', 14, 11928, DATE '2016-SEP-01', 'Misty');
INSERT INTO rescue VALUES (2049, 88725);
INSERT INTO rescue VALUES (2049, 82928);
INSERT INTO rescue VALUES (1023, 12987);
INSERT INTO rescue VALUES (3048, 19582);
INSERT INTO rescue VALUES (3048, 84957);
INSERT INTO donator VALUES (8989, '<NAME>', '598 Rue Hutchison. Montreal. QC. H6K9J6');
INSERT INTO donator VALUES (4523, '<NAME>', '22 Rue Rachel E. Montreal. QC. H1H9H5');
INSERT INTO donator VALUES (2223, '<NAME>', '100 Rue St Marc. Montreal. QC. H3L4C3');
INSERT INTO donator VALUES (1198, '<NAME>', '9882 Avenue du Parc. Montreal. QC. H3L9O8');
INSERT INTO donator VALUES (6718, '<NAME>', '2819 Avenue des Pins. Montreal. QC. H1K9V6');
INSERT INTO donated VALUES (8989, 38592);
INSERT INTO donated VALUES (8989, 71905);
INSERT INTO donated VALUES (4523, 12304);
INSERT INTO donated VALUES (2223, 67819);
INSERT INTO donated VALUES (1198, 39201);
INSERT INTO donated VALUES (6718, 27491);
INSERT INTO document VALUES (01, DATE '2020-02-10');
INSERT INTO document VALUES (02, DATE '2020-02-20');
INSERT INTO document VALUES (03, DATE '2020-01-05');
INSERT INTO document VALUES (04, DATE '2019-12-20');
INSERT INTO document VALUES (05, DATE '2020-02-24');
INSERT INTO document VALUES (06, DATE '2020-02-01');
INSERT INTO document VALUES (07, DATE '2020-01-02');
INSERT INTO document VALUES (08, DATE '2020-02-17');
INSERT INTO document VALUES (09, DATE '2020-02-20');
INSERT INTO document VALUES (10, DATE '2020-01-10');
INSERT INTO accepteddocument VALUES (01, 9018, 'T0001', 289182, DATE '2020-02-12', 'Make sure to bring all pet supplies');
INSERT INTO accepteddocument VALUES (02, 9018, 'T0002', 849272, DATE '2020-02-22', 'This pet has some skin condition you can find in their medical records. Please pick up a cream from the vet');
INSERT INTO accepteddocument VALUES (03, 2765, 'T0003', 018592, DATE '2020-01-08', 'Make sure to bring all pet supplies');
INSERT INTO accepteddocument VALUES (04, 7811, 'T0004', 821959, DATE '2020-12-24', 'Remember that furry friends are for life, not just for the holidays!');
INSERT INTO accepteddocument VALUES (05, 1992, 'T0005', 275018, DATE '2020-02-24', 'This pet needs deworming. Please pick up some pills from the vet');
INSERT INTO payment values ('T0001', 289182, 01, 500.00, 'Credit');
INSERT INTO payment values ('T0002', 849272, 02, 400.00, 'Debit');
INSERT INTO payment values ('T0003', 018592, 03, 500.00, 'Cash');
INSERT INTO payment values ('T0004', 821959, 04, 500.00, 'Cheque');
INSERT INTO payment values ('T0005', 275018, 05, 400.00, 'Credit');
NSERT INTO petinsurance VALUES (289182, 'T0001', 1, 30);
INSERT INTO petinsurance VALUES (849272, 'T0002', 2, 40);
INSERT INTO petinsurance VALUES (18592, 'T0003', 3, 38.5);
INSERT INTO petinsurance VALUES (821959, 'T0004', 4, 32.5);
INSERT INTO petinsurance VALUES (275018, 'T0005', 5, 45);
INSERT INTO denialdocument VALUES (06, 'Apartment too small for this breed of dog');
INSERT INTO denialdocument VALUES (07, 'This dog not friendly with children and this household has children');
INSERT INTO denialdocument VALUES (08, 'This cat is afraid of dogs and this household has dogs');
INSERT INTO denialdocument VALUES (09, 'Dog requires a yard and this yard is not big enough');
INSERT INTO denialdocument VALUES (10, 'Potential household too busy to commit time to cat with separation anxiety');
INSERT INTO adoptionapplication VALUES ('A0001', DATE '2020-02-05', 2049, '1975 Rue Clarke, Montreal, QC, H6U9I8');
INSERT INTO adoptionapplication VALUES ('A0002', DATE '2020-02-15', 1034, '790 Boulevard Rene-Levesque, Montreal, QC, H8D9Y6');
INSERT INTO adoptionapplication VALUES ('A0003', DATE '2020-01-02', 4092, '66 W Hastings St, Vancouver, BC, V8T9Y2');
INSERT INTO adoptionapplication VALUES ('A0004', DATE '2020-12-20', 3048, '19284 Bloor St. Toronto, ON, D8Y9Q6');
INSERT INTO adoptionapplication VALUES ('A0005', DATE '2020-02-17', 1023, '719 Rue de la Montagne, Montreal, QC, H3S8E9');
INSERT INTO adoptionapplication VALUES ('A0006', DATE '2020-02-10', 2049, '44 Boulev<NAME>, Montreal, QC, H7D9K8');
INSERT INTO adoptionapplication VALUES ('A0007', DATE '2019-12-27', 1034, '88 Rue Aylmer, Montreal, QC, H9AK0G');
INSERT INTO adoptionapplication VALUES ('A0008', DATE '2020-02-04', 4092, '124 Rue Lorne, Montreal, QC, H1K0F8');
INSERT INTO adoptionapplication VALUES ('A0009', DATE '2020-02-05', 3048, '777 Rue Chabanel W, Montreal, QC, H6S9G0');
INSERT INTO adoptionapplication VALUES ('A0010', DATE '2020-01-01', 1023, '505 W Georgia St, Vancouver, BC, V9S7G9');
INSERT INTO received values ('A0001', 12987);
INSERT INTO received values ('A0002', 19582);
INSERT INTO received values ('A0003', 38592);
INSERT INTO received values ('A0004', 84957);
INSERT INTO received values ('A0005', 12987);
INSERT INTO received values ('A0006', 39201);
INSERT INTO received values ('A0007', 12987);
INSERT INTO received values ('A0008', 12304);
INSERT INTO received values ('A0009', 12987);
INSERT INTO received values ('A0010', 71002);
INSERT INTO receive VALUES (01, '1975 Rue Clarke, Montreal, QC, H6U9I8');
INSERT INTO receive VALUES (02, '790 Boulevard Rene-Levesque, Montreal, QC, H8D9Y6');
INSERT INTO receive VALUES (03, '66 W Hastings St, Vancouver, BC, V8T9Y2');
INSERT INTO receive VALUES (04, '19284 Bloor St. Toronto, ON, D8Y9Q6');
INSERT INTO receive VALUES (05, '719 Rue de la Montagne, Montreal, QC, H3S8E9');
INSERT INTO receive VALUES (06, '44 Boulevard de Maisonneuve, Montreal, QC, H7D9K8');
INSERT INTO receive VALUES (07, '88 Rue Aylmer, Montreal, QC, H9AK0G');
INSERT INTO receive VALUES (08, '124 Rue Lorne, Montreal, QC, H1K0F8');
INSERT INTO receive VALUES (09, '777 Rue Chabanel W, Montreal, QC, H6S9G0');
INSERT INTO receive VALUES (10, '505 W Georgia St, Vancouver, BC, V9S7G9');
UPDATE medicalhistory SET pid = 12987 WHERE mid = '30392';
UPDATE medicalhistory SET ccondition='Psoriasis', medication='Cortisol Cream', pid=19582 WHERE mid='82950';
UPDATE medicalhistory SET pid=38592 WHERE mid='84959';
UPDATE medicalhistory SET ccondition='Worms', medication='Deworming pills', pid=84957 WHERE mid='22196';
UPDATE medicalhistory SET pid=71905 WHERE mid='92593';
UPDATE medicalhistory SET pcondition='Worms', pid=82928 WHERE mid='39102';
UPDATE medicalhistory SET ccondition='Digestive', pcondition='Worms', medication='Digestive Pills', pid=12304 WHERE mid='10492';
UPDATE medicalhistory SET pid=67819 WHERE mid='22958';
UPDATE medicalhistory SET ccondition='Skin infection', pcondition='Concussion', medication='Antibacterial cream', pid=39201 WHERE mid='77819';
UPDATE medicalhistory SET ccondition='Blind in one eye', pid=88725 WHERE mid='23475';
UPDATE medicalhistory SET pid=27491 WHERE mid='99019';
UPDATE medicalhistory SET pid=28592 WHERE mid='12672';
UPDATE medicalhistory SET ccondition='Broken ankle', pid=91058 WHERE mid='19602';
UPDATE medicalhistory SET pid=71002 WHERE mid='11928';
INSERT INTO previoushistory VALUES ('790 Boulevard Rene-Levesque, Montreal, QC, H8D9Y6', DATE '2018-09-10', false);
INSERT INTO previoushistory VALUES ('66 W Hastings St, Vancouver, BC, V8T9Y2', DATE '2015-01-01', true);
INSERT INTO previoushistory VALUES ('19284 Bloor St. Toronto, ON, D8Y9Q6', DATE '2014-04-17', false);
INSERT INTO previoushistory VALUES ('719 Rue de la Montagne, Montreal, QC, H3S8E9', DATE '2013-09-12', true);
INSERT INTO previoushistory VALUES ('124 Rue Lorne, Montreal, QC, H1K0F8', DATE '2012-08-24', false);
<file_sep># Pet_Adoption_Center
McGill COMP 421 Group Project making a real world base database application
Group member:
1. <NAME>
2. <NAME>
3. <NAME>
4. <NAME>
Project description:
In the programming project of this course, you will develop and build a database application for a real-world domain.
Step by step, you will design a schema, create a database using DB2/PostgreSQL, populate your database with data, maintain, query and update your data, develop application programs, and implement a user-friendly in- terface.
The interface can be very simple so no requirement for web-programming, etc. You will only use a standard programming language in the last project deliverable.
This project contains:
1. ER Modeling
2. SQL statements and queires
3. JDBC Application Programming
| 13ef11586035a2fc319e5e5d823bf5fe1b954937 | [
"Markdown",
"SQL"
] | 7 | SQL | denny6389/Pet_Adoption_Center | 83b88035360327cd464c326f608af7c98c56552b | 702c57d9cdd08ae851ad59540761f9c2c8e810d1 |
refs/heads/master | <file_sep>/**
* Class representing a sub-board of nested tic-tac-toe(aka Tic-Tactics) game.
* A sub-board is essentially a regular tic-tac-toe board.
*
* @author <NAME>(<EMAIL>)
* @version 1.0
*/
import java.util.Arrays;
public class SubBoard{
private int[][] board;
private static final String horizontalLine = "-------------";
private int numberOfOccupiedCells;
public SubBoard(){
this.board = new int[3][3];
for ( int row = 0; row < 3; row++){
Arrays.fill(this.board[row], 0);
}
this.numberOfOccupiedCells = 0;
}
public int getCell(int row, int col){
if ( row < 0 || row > 2 || col < 0 || col > 2 ){
throw new BoardPlayException("Board index out of range");
}
return this.board[row][col];
}
public void putX(int row, int col){
checkValid(row, col);
this.board[row][col] = 1;
this.numberOfOccupiedCells += 1;
}
public void putO(int row, int col){
checkValid(row, col);
this.board[row][col] = -1;
this.numberOfOccupiedCells += 1;
}
private void resetCell(int row, int col){
this.board[row][col] = 0;
this.numberOfOccupiedCells -= 1;
}
public void printBoard(){
System.out.println(getBoardString());
}
public String getBoardString(){
String boardString = getRowString(0) + "\n" + horizontalLine + "\n" +
getRowString(1) + "\n" + horizontalLine + "\n" +
getRowString(2);
return boardString;
}
public String getRowString(int row){
return String.format(" %2s |%2s |%2s ",
getStr(row,0), getStr(row,1), getStr(row,2));
}
private String getStr(int row, int col){
if (this.board[row][col] == 0) return " ";
else return (board[row][col] == 1? " X" : " O");
}
/***************************************************************
* Evaluation methods *
***************************************************************/
// return 1 if X won the game, -1 if O won the game, 0 notdetermined,
// -2 draw (fully occupied but no one wins)
public int evaluate(){
// check diagonals
int diagResult = checkDiags();
if ( diagResult != 0){
return diagResult;
}
int rowResult = 0;
for ( int col = 0; col < 3; col++){
rowResult = checkRow(col);
if ( rowResult != 0 ) return rowResult;
}
int colResult = 0;
for ( int row = 0; row < 3; row++){
colResult = checkCol(row);
if ( colResult != 0 ) return colResult;
}
return (this.numberOfOccupiedCells == 9 ? -2 : 0); // draw or undetermined
}
private int checkDiags(){
if ((( this.board[0][0] == this.board[1][1] )&&
(this.board[0][0] == this.board[2][2]) ) ||
(( this.board[0][2] == this.board[1][1] )&&
(this.board[0][2] == this.board[2][0] ))){
return this.board[1][1];
}
return 0;
}
private int checkRow(int col){
if ( this.board[0][col] == this.board[1][col] &&
this.board[0][col] == this.board[2][col] ){
return this.board[0][col];
}
return 0;
}
private int checkCol(int row){
if ( this.board[row][0] == this.board[row][1] &&
this.board[row][0] == this.board[row][2] ){
return this.board[row][0];
}
return 0;
}
// check if given row and col are valid un-played cell in the board
// and if not throw BoardPlayException
private void checkValid(int row, int col){
if ( row < 0 || row > 2 || col < 0 || col > 2 ){
throw new BoardPlayException("Board index out of range");
}
else if ( this.board[row][col] != 0 ){
throw new BoardPlayException("Already occupied cell");
}
}
}
<file_sep>/**
* Class representing a board of Tic-Tactics(or double-nested tic-tac-toe) game.
* This class object contains internal SubBoard double-array, and methods to
* evaluate winnings.
*/
public class TicTacticsBoard{
private SubBoard[][] board;
public TicTacticsBoard(){
this.board = new SubBoard[3][3];
for ( int row = 0; row < 3; row++){
for ( int col = 0; col < 3; col++){
this.board[row][col] = new SubBoard();
}
}
}
public SubBoard getSubBoard(int bigRow, int bigCol){
return this.board[bigRow][bigCol];
}
public void putX(int bigRow, int bigCol, int subRow, int subCol){
this.board[bigRow][bigCol].putX(subRow, subCol);
}
public void putO(int bigRow, int bigCol, int subRow, int subCol){
this.board[bigRow][bigCol].putO(subRow, subCol);
}
/***************************************************************
* Evaluation methods *
***************************************************************/
public int evaluate(){
// check diagonals
int diagResult = checkDiags();
if ( diagResult != 0){
return diagResult;
}
int rowResult = 0;
for ( int col = 0; col < 3; col++){
rowResult = checkRow(col);
if ( rowResult != 0 ) return rowResult;
}
int colResult = 0;
for ( int row = 0; row < 3; row++){
colResult = checkCol(row);
if ( colResult != 0 ) return colResult;
}
return 0; // draw or undetermined
}
private int checkDiags(){
if ((( this.board[0][0].evaluate() == this.board[1][1].evaluate() )&&
(this.board[0][0].evaluate() == this.board[2][2].evaluate()) ) ||
(( this.board[0][2].evaluate() == this.board[1][1].evaluate() )&&
(this.board[0][2].evaluate() == this.board[2][0].evaluate() ))){
return this.board[1][1].evaluate();
}
return 0;
}
private int checkRow(int col){
if ( this.board[0][col].evaluate() == this.board[1][col].evaluate() &&
this.board[0][col].evaluate() == this.board[2][col].evaluate() ){
return this.board[0][col].evaluate();
}
return 0;
}
private int checkCol(int row){
if ( this.board[row][0].evaluate() == this.board[row][1].evaluate() &&
this.board[row][0].evaluate() == this.board[row][2].evaluate() ){
return this.board[row][0].evaluate();
}
return 0;
}
public int evaluateSubBoard(int row, int col){
return this.board[row][col].evaluate();
}
// check if still playable subboard is left
public boolean isDone(){
for ( int row = 0; row < 3; row++){
for ( int col = 0; col < 3; col++){
if (this.board[row][col].evaluate() == 0){
return false;
}
}
}
return true;
}
/***************************************************************/
}
<file_sep>public class BoardTextPrinter implements BoardPrinter{
private TicTacticsBoard board;
private static final String horizontalLine = getHorizontalLine(45);
private static final String horizontalSubLine = getHorizontalSubLine(11, 5);
public BoardTextPrinter(TicTacticsBoard board){
this.board = board;
}
public void printBoard(){
System.out.println(horizontalLine);
for ( int bigRow = 0; bigRow < 3; bigRow++){
for ( int subRow = 0; subRow < 3; subRow++){
System.out.println(getRowString(bigRow, subRow));
if ( subRow != 2 ) System.out.println(horizontalSubLine);
}
System.out.println(horizontalLine);
}
}
private String getRowString(int bigRow, int subRow){
String retval = "";
for ( int bigCol = 0; bigCol < 3; bigCol++){
SubBoard subBoard = this.board.getSubBoard(bigRow, bigCol);
retval += subBoard.getRowString(subRow);
if ( bigCol != 2 ) retval += " | ";
}
retval = retval.replace("X", "\033[31mX\033[0m");
retval = retval.replace("O", "\033[32mO\033[0m");
return retval;
}
private static String getHorizontalLine(int size){
return new String(new char[size]).replace("\0", "-");
}
private static String getHorizontalSubLine(int subsize, int spacingsize){
String spacing = new String(new char[spacingsize]).replace("\0", " ");
String retval = " ";
for ( int col = 0; col < 3; col++){
retval += getHorizontalLine(subsize);
if ( col != 2 ) retval += spacing;
}
return retval;
}
}
<file_sep>### Modern Tic Tac Toe
The following game modernizes the classic game of tic tac toe. Not only is this a 3D version, but it also provides the user with
unlimited entertainment. This game takes tic tac toe to a whole 'nother level, both literally and figureatively. The users can
challenge their wits by figuring out who can strategize better and eventually win.
### Usage
local two-person play version
javac RunLocalGame.java
java RunLocalGame
over the network two-person version
javac RunNetworkGame.java
java RunNetworkGame
### To do
1. Draw a proper board
2. Handle the Runtime BoardPlay Exception
3. Complete the AI code
4. Give it a GUI with Swing
### Team
1. <NAME>
2. <NAME>
3. <NAME>
<file_sep>/**
* This class implements local-player version of GamePlayer interface.
* It ensures a local player to paly within the proper game rule.
* Since there can be no player without an actual game, an instance of
* this class works only with a TicTactics instance, which needs to
* be added to the instance object by addToGame() method.
*
*/
public class LocalPlayer implements GamePlayer{
private TicTactics game;
private final int side; // 1 if X, -1 if O
private final String symbol;
/**
* public constructor
*
* @param side integer indicating which side the player plays for
* "X" (side=1) or for "O" (side=-1)
*/
public LocalPlayer(int side){
assert ( side == 1 || side == -1 );
this.side = side;
this.symbol = ( side == 1? "X" : "O");
}
/**
* a public method making a channel from this instance to a game instance.
* this method must be invoked before invoking play() method.
*
* @param game an instance object of TicTactics interface where this instance
* will be played
*/
public void addToGame(TicTactics game){
this.game = game;
}
public void play(){
chooseSubBoard();
int bigRow = this.game.getNextBigRow();
int bigCol = this.game.getNextBigCol();
play(bigRow, bigCol);
}
public void play(int bigRow, int bigCol){
while (true){
try{
chooseSubBoard();
String whom = this.symbol;
System.out.println(String.format(
"%s Playing cell %1d-%1d", whom, bigRow, bigCol));
System.out.println(String.format(
"Enter row, col to place %s in the sub-board", whom));
String[] tokens = this.game.readLine().trim().split(",");
int subRow = Integer.parseInt(tokens[0].trim());
int subCol = Integer.parseInt(tokens[1].trim());
this.game.setNextBigRow(subRow);
this.game.setNextBigCol(subCol);
if ( this.side == 1 ) {
this.game.getBoard().putX(bigRow, bigCol, subRow, subCol);
}
else {
this.game.getBoard().putO(bigRow, bigCol, subRow, subCol);
}
this.game.setNextTurn();
break;
}
catch ( Exception e){
System.out.println("invalid selection. Try again.");
}
}
}
private void chooseSubBoard(){
String whom = this.symbol;
TicTacticsBoard board = this.game.getBoard();
int nextBigRow = this.game.getNextBigRow();
int nextBigCol = this.game.getNextBigCol();
while ( !isValid(nextBigRow, nextBigCol) ){
System.out.println("Choose sub-board(row, col) to play : ");
String[] tokens = this.game.readLine().trim().split(",");
nextBigRow = Integer.parseInt(tokens[0].trim());
nextBigCol = Integer.parseInt(tokens[1].trim());
}
while ( board.evaluateSubBoard(nextBigRow, nextBigCol) != 0 ){
System.out.println(String.format("sub-board %d-%d is already closed.",
nextBigRow, nextBigCol));
System.out.println(whom + " choose new sub-board(row, col) to play : ");
String[] tokens = this.game.readLine().trim().split(",");
nextBigRow = Integer.parseInt(tokens[0].trim());
nextBigCol = Integer.parseInt(tokens[1].trim());
}
this.game.setNextBigRow(nextBigRow);
this.game.setNextBigCol(nextBigCol);
}
private static boolean isValid(int row, int col){
return (row >= 0 && row < 3 && col >= 0 && col < 3);
}
}
<file_sep>public interface BoardPrinter{
/**
* prints a tictactics board representation
*/
public void printBoard();
}
| ad6e999ccdc0fbcd60f775af5228433fb9e4090a | [
"Markdown",
"Java"
] | 6 | Java | NP-compete/Advanced-TicTacToe | f40becfd492e4032062a7249d212e726a3f7df23 | 68de7a45e08432439338b2b0b9ce6b16f17bd3ef |
refs/heads/master | <repo_name>jolna/ExData_Plotting1<file_sep>/plot3.R
#read all data
allPCData <- read.csv("./household_power_consumption.txt",header = TRUE,sep=";", stringsAsFactors = FALSE,na.strings = "?")
#convert Date column to Date object
allPCData$Date <- as.Date(allPCData$Date,"%d/%m/%Y")
#select only a subset of rows from the big data set
subPCData <- subset(allPCData, Date >= "2007-02-01" & Date <= "2007-02-02")
#remove the bigdata object to free up memory
rm(allPCData)
#concatenate the Date and Time to build a datetime object column
dateTime <- paste(subPCData$Date,subPCData$Time)
subPCData$DateTime <- as.POSIXct(dateTime)
#plot the chart
with(subPCData, plot(Sub_metering_1 ~ DateTime,type = "l",ylab = "Energy Sub metering",xlab=""))
with(subPCData, lines(Sub_metering_2 ~ DateTime,col="red"))
with(subPCData, lines(Sub_metering_3 ~ DateTime,col="blue"))
legend("topright",col=c("black","red","blue"),lty=1,lwd=2,legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
#copy into a png file
dev.copy(png,file="plot3.png",width=600,height=480)
dev.off()
<file_sep>/plot2.R
#read all data
allPCData <- read.csv("./household_power_consumption.txt",header = TRUE,sep=";", stringsAsFactors = FALSE,na.strings = "?")
#convert Date column to Date object
allPCData$Date <- as.Date(allPCData$Date,"%d/%m/%Y")
#select only a subset of rows from the big data set
subPCData <- subset(allPCData, Date >= "2007-02-01" & Date <= "2007-02-02")
#remove the bigdata object to free up memory
rm(allPCData)
#concatenate the Date and Time to build a datetime object column
dateTime <- paste(subPCData$Date,subPCData$Time)
subPCData$DateTime <- as.POSIXct(dateTime)
#plot the chart
with(subPCData, plot(DateTime, Global_active_power,type = "l",ylab = "Global Active Power (kilowatts)",xlab=""))
#copy into a png file
dev.copy(png,file="plot2.png",width=480,height=480)
dev.off()
<file_sep>/plot1.R
#read all data
allPCData <- read.csv("./household_power_consumption.txt",header = TRUE,sep=";", stringsAsFactors = FALSE,na.strings = "?")
#convert Date column to Date object
allPCData$Date <- as.Date(allPCData$Date,"%d/%m/%Y")
#select only a subset of rows from the big data set
subPCData <- subset(allPCData, Date >= "2007-02-01" & Date <= "2007-02-02")
#remove the bigdata object to free up memory
rm(allPCData)
#histogram
hist(subPCData$Global_active_power,main="Global Active Power",xlab = "Global Active Power (kilowatts)", ylab = "Frequency",col = "red")
#copy into a png file
dev.copy(png,file="plot1.png",width=480,height=480)
dev.off()
| 3e981486c9124a4abe9bc7bd6f7c0ea7cdccc515 | [
"R"
] | 3 | R | jolna/ExData_Plotting1 | abeafff2ec9cc6a4c9738f3f74845a412db7506a | 78c73beb0b83152dd7091960f4456a2848c99818 |
refs/heads/master | <file_sep><?php
/**
* Bootstrapping, setting up and loading the core.
*
* @package LanayaSystem
*/
/**
* Enable auto-load of class declarations.
*/
function autoload($aClassName) {
$classFile = "/{$aClassName}/{$aClassName}.php";
$file1 = LANAYA_INSTALL_PATH . "/system/" . $classFile;
$file2 = LANAYA_SITE_PATH . "/helpers/" . $classFile;
$file3 = LANAYA_SITE_PATH . "/controllers/" . $classFile;
$file4 = LANAYA_SITE_PATH . "/models/" . $classFile;
if(is_file($file1)) {
require_once($file1);
} elseif(is_file($file2)) {
require_once($file2);
} elseif(is_file($file3)) {
require_once($file3);
} elseif(is_file($file4)) {
require_once($file4);
}
}
spl_autoload_register('autoload');
/**
* Set a default exception handler and enable logging in it.
*/
function exception_handler($e) {
echo "Lanaya: Uncaught exception: <p>" . $e->getMessage() . "</p><pre>" . $e->getTraceAsString(), "</pre>";
}
set_exception_handler('exception_handler'); | 6c23519132c9b7c964a70d5462f55ec65cd74df1 | [
"PHP"
] | 1 | PHP | anthuz/lanaya_km4 | 664fb7b9987acefd90dcc4f8614162ea69958ae6 | 8232cf6ae08eed2eabea5f5c8098f287f49d6edc |
refs/heads/master | <file_sep>const { prompt } = require('inquirer');
const {databaseQuery} = require('./databaseQuery');
const nameNewDept = async () => {
const departmentQuestion = {
type: "input",
name: "name",
message: "Enter the name of the new department: ",
validate: function(text) {
const valid = text.match(/^[a-zA-Z\s]*$/);
if (valid) {
return true;
}
return "Please enter a valid name (letters and spaces only, no special characters)."
}
};
return prompt(departmentQuestion);
};
const addDepartment = async () => {
console.clear();
const new_dept_query = `INSERT INTO department SET ?`;
const departmentName = await nameNewDept();
const newDepartment = await databaseQuery(new_dept_query, departmentName);
console.clear();
console.log(`\n Task complete!`);
console.log(` New department added. ID is ${newDepartment.insertId}` + `\n`);
};
module.exports = { addDepartment };<file_sep>const { prompt, Separator } = require('inquirer');
const connection = require('../lib/databaseQuery');
const { viewMethods } = require('../lib/viewElement');
const { addDepartment } = require('../lib/addDepartment');
const { addEmployee } = require('../lib/addEmployee');
const { addRole } = require('../lib/addRole');
const { deleteDepartment } = require('../lib/deleteDepartment');
const { deleteEmployee } = require('../lib/deleteEmployee');
const { deleteRole } = require('../lib/deleteRole');
const { updateEmployee } = require('../lib/updateEmployee');
const startMenu = async () => {
// options menu layout
const optionMenu = [
new Separator("\n ───────── VIEW ──────────"),
"VIEW employees",
"VIEW departments",
"VIEW roles",
"VIEW employees by manager",
"VIEW utilized budget by department",
new Separator("\n ───────── ADD ──────────"),
"ADD employee",
"ADD department",
"ADD role",
new Separator("\n ───────── UPDATE ──────────"),
"UPDATE employee",
new Separator("\n ───────── Delete ──────────"),
"DELETE employee",
"DELETE department",
"DELETE role",
new Separator("\n ───────────────────────────"),
"Exit",
new Separator("\n"),
];
const openQuestion = [
{
type: "list",
name: "operation",
prefix: " ",
message: "What would you like to do? ",
choices: optionMenu,
pageSize: 30,
default: 0,
}
]
const answers = await prompt(openQuestion);
switch (answers.operation) {
case "VIEW departments":
await viewMethods('department');
break;
case "VIEW roles":
await viewMethods('roles');
break;
case "VIEW employees":
await viewMethods('employees');
break;
case "VIEW employees by manager":
await viewMethods('manager');
break;
case "VIEW utilized budget by department":
await viewMethods('budget');
break;
case "ADD department":
await addDepartment();
break;
case "ADD role":
await addRole();
break;
case "ADD employee":
await addEmployee();
break;
case "UPDATE employee":
await updateEmployee();
break;
case "DELETE employee":
await deleteEmployee();
break;
case "DELETE role":
await deleteRole();
break;
case "DELETE department":
await deleteDepartment();
break;
default:
console.clear();
console.log("Bye!");
return;
}
// default
startMenu();
};
module.exports = { startMenu };
<file_sep>const { prompt } = require("inquirer");
const {databaseQuery} = require("./databaseQuery");
const { listRoles } = require('../util/listFunctions');
const deleteRole = async () => {
console.clear();
const roleChoice = {
type: "list",
name: "id",
message: " Choose a role to delete:\n",
choices: await listRoles(),
pageSize: 30
}
const targetRole = await prompt(roleChoice);
const delete_query_role = `DELETE FROM role WHERE id = ?`;
await databaseQuery(delete_query_role, targetRole.id);
console.clear();
console.log(`\n Role deleted.` + `\n`);
}
module.exports = { deleteRole };<file_sep>const { prompt } = require("inquirer");
const {databaseQuery} = require("./databaseQuery");
const { listRoles, listEmployees, listManagers, listDepartments } = require('../util/listFunctions');
const updateDetails = async () => {
const updateQuestions = [
{
type: "list",
name: "id",
message: "Choose which employee to update:\n",
choices: await listEmployees(),
pageSize: 30
},
{
type: "list",
name: "field",
message: "What field would you like to update?\n ",
choices: ["First Name", "Last Name", "Role", "Manager"],
pageSize: 6
},
{
type: "input",
name: "first_name",
message: "Enter the employee's first name: ",
when: (answers) => answers.field === "First Name",
validate: function(value) {
const valid = value.match(/^[a-zA-Z\s]+$/i);
if (valid) {
return true;
}
return "Please enter a valid name (letter characters and spaces only).";
}
},
{
type: "input",
name: "last_name",
message: "Enter the employee's last name: ",
when: (answers) => answers.field === "Last Name",
validate: function(value) {
const valid = value.match(/^[a-zA-Z\s]+$/i);
if (valid) {
return true;
}
return "Please enter a valid name (letter characters and spaces only).";
}
},
{
type: "list",
name: "role_id",
message: "Choose the employee's role:\n",
when: (answers) => answers.field === "Role",
choices: await listRoles(),
pageSize: 12
},
// {
// type: "list",
// name: "department_id",
// message: "Choose the employee's department:\n",
// when: (answers) => answers.field === "Department",
// choices: await listDepartments(),
// pageSize: 12,
// },
{
type: "confirm",
name: "manager_yn",
message: "Do you wish to make this employee a manager? \n",
when: (answers) => answers.field === "Manager",
pageSize: 10
},
{
type: "list",
name: "manager_id",
message: "Choose the employee's manager:\n",
when: (answers) => answers.manager_yn === false,
choices: await listManagers(),
pageSize: 10
}
];
return prompt(updateQuestions);
};
const updateEmployee = async () => {
console.clear();
let updatedDetails = await updateDetails();
let update_query = `UPDATE employees SET ? WHERE id=?`;
let updatedValuesArray = [updatedDetails.id];
if (('manager_yn' in updatedDetails) === true){
update_query = `UPDATE employees SET manager_id=? WHERE id=?`;
delete updatedDetails['manager_yn'];
updatedValuesArray.unshift(updatedDetails.manager_id)
} else if (('manager_yn' in updatedDetails) === false) {
update_query = `UPDATE employees SET ? WHERE id=?`;
delete updatedDetails['manager_yn'];
updatedDetails['manager_id'] = this.id;
updatedValuesArray.unshift(updatedDetails);
// } else if ('department_id' in updatedDetails) {
// update_query = `UPDATE employees SET department_id=? WHERE id=?`;
// updatedValuesArray.unshift(updatedDetails.department_id)
// console.log('inside dept_id',updatedValuesArray);
}
else if ('role_id' in updatedDetails) {
update_query = `UPDATE employees SET role_id=? WHERE id=?`
updatedValuesArray.unshift(updatedDetails.role_id)
}
delete updatedDetails.id;
delete updatedDetails.field;
await databaseQuery(update_query, updatedValuesArray);
console.log('\n Task complete!');
console.log(` Employee updated.` + `\n`);
};
module.exports = { updateEmployee };<file_sep>const { prompt } = require("inquirer");
const {databaseQuery} = require("./databaseQuery");
const { listEmployees } = require('../util/listFunctions');
const deleteEmployee = async () => {
console.clear();
const employeeChoice = {
type: "list",
name: "id",
message: " Choose an employee to delete:\n",
choices: await listEmployees(),
pageSize: 30
}
const targetEmployee = await prompt(employeeChoice);
const delete_query_emp = `DELETE FROM employees WHERE id = ?`;
await databaseQuery(delete_query_emp, targetEmployee.id);
console.clear();
console.log(`\n Employee deleted.` + `\n`);
};
module.exports = { deleteEmployee };
<file_sep># Employee Tracker CLI
<br />
## Description
Developers are often tasked with creating interfaces that make it easy for non-developers to view and interact with information stored in databases. Often these interfaces are known as **C**ontent **M**anagement **S**ystems.
I've been challenged to architect and build a solution for managing a company's employees using node, inquirer, and MySQL. This has been achieved to the best of my abilities in the below application, allowing a user to interact with an employee tracking database. It allows the viewing, adding, deleting and updating for data in a clear easy to follow CLI.
## Contents
- [Installation](#installation)
- [Usage](#usage)
- [User Story](#user-story)
- [Version 1 Feautures](#version-1-features)
- [Demonstration](#demonstration)
- [Screenshots](#screenshots)
- [Questions](<#questions-(FAQ)>)
- [Contact](#contact)
- [Author](#authors)
- [Acknowledgements](#acknowledgements)
## Installation
1. Clone this GitHub repository
```
git clone https://github.com/AGr2020Xman/employee-manager-cli.git
```
2. Install all dependent npm packages.
```
npm install --save
```
3. Create the employee_tracker_db by running the script <addr>schema.sql</addr> and seeding mock data with the <addr>seeds.sql</addr> included in <a href="./src/db">db</a> folder.
4. Adjust root and password locations, as well as port in the databaseQuery.js file for your own servers.
## Usage
Ensure the following are correctly installed (if you have node already, make sure version is up to date):
- [Node.js](https://nodejs.org/en/)
- [InquirerJs](https://www.npmjs.com/package/inquirer/v/0.2.3)
- [MySQL](https://www.npmjs.com/package/mysql) NPM package to connect to your MySQL database and perform queries.
- [console.table](https://www.npmjs.com/package/console.table) to print MySQL rows to the console.
Run <addr>node start</addr> to run the application and choose from the prompted options to begin.
Add employees into roles & roles into departments for basic functionality!
## User Story
```
As a business owner
I want to be able to view and manage the departments, roles, and employees in my company
So that I can organize and plan my business
```
## Version 1 Features
- Add departments, roles, employees.
- View departments, roles, employees.
- Update employee roles.
- Update employee managers.
- View employees by manager.
- Delete departments, roles, and employees.
- View the total utilized budget of a department.
## Demonstration
- [Tutorial-Video](https://drive.google.com/file/d/1h8zwnRMBoQVshUisqUCIn8VMIVB6xJtl/view)
## Screenshots
_Initiate application with start choices_

_Viewing tables_

_Adding Employee_

_Updating Employee_

## Questions
- Submit questions to my contact details below.
- App runs in CLI.
## Contact
- Contact me with any questions on my email: <EMAIL> or <EMAIL>
## Author
- Initial files to develop by Trilogy Education Services
- <NAME> - 10/11/2020
### Acknowledgements
- © 2019 Trilogy Education Services, a 2U, Inc. brand. All Rights Reserved.
<file_sep>const { prompt } = require("inquirer");
const {databaseQuery} = require("./databaseQuery");
const { listDepartments } = require('../util/listFunctions');
const deleteDepartment = async () => {
console.clear();
const departmentChoice = {
type: "list",
name: "id",
message: " Choose a department to delete:\n",
choices: await listDepartments(),
pageSize: 30
}
const targetDepartment = await prompt(departmentChoice);
const delete_query_dept = `DELETE FROM department WHERE id = ?`;
await databaseQuery(delete_query_dept, targetDepartment.id);
console.clear();
console.log(`\n Department deleted.` + `\n`);
};
module.exports = { deleteDepartment };
<file_sep>const { prompt } = require('inquirer');
const { databaseQuery } = require('./databaseQuery');
const conTable = require('console.table');
const managerID = async () => {
const manager_query = `
SELECT
id Value,
CONCAT(first_name, " ", last_name) Name
FROM employees
WHERE ISNULL(manager_id)
ORDER BY id`;
const managersResult = await databaseQuery(manager_query);
const unpackRowPacket = managersResult.map((manager) => ({value: manager.Value, name: manager.Name}));
const managerChoice = {
type: "list",
name: "id",
message: "Choose a manager:\n",
pageSize: 30,
choices: [...unpackRowPacket, 'Go back']
};
const answers = await prompt(managerChoice);
return answers.id;
};
const viewMethods = async (viewCategory) => {
switch (viewCategory) {
case "department":
await viewDepartment();
break;
case "roles":
await viewRoles();
break;
case "employees":
await viewEmployees();
break;
case "manager":
await viewEmployeesByManager();
break;
case "budget":
await viewBudget();
break;
}
};
const viewDepartment = async () => {
const dept_query = `
SELECT *
FROM department
ORDER BY department.name`;
const resultsArray = await databaseQuery(dept_query);
console.table('\nDepartments',resultsArray);
};
const viewRoles = async () => {
const roles_query = `
SELECT
role.title Role, role.id ID, role.salary Salary,
department.name AS Department
FROM role
JOIN department ON (role.department_id = department.id)
ORDER BY title`;
const resultsArray = await databaseQuery(roles_query);
console.table('\nRoles',resultsArray);
};
const viewEmployees = async () => {
const employee_query = `
SELECT
CONCAT(employees.first_name, " ", employees.last_name) Name,
employees.id ID,
role.title Role,
department.name Department,
role.salary Salary,
CONCAT(managers.first_name, " ", managers.last_name) Manager
FROM employees
INNER JOIN role ON role.id = employees.role_id
INNER JOIN department ON role.department_id=department.id
LEFT JOIN employees managers ON managers.id = employees.manager_id
ORDER BY Name
`;
const resultsArray = await databaseQuery(employee_query);
console.table('\nEmployees', resultsArray);
};
const viewEmployeesByManager = async () => {
console.clear();
const { startMenu } = require('../util/startCLI');
const managerId = await managerID();
if (managerId === 'Go back'){
startMenu();
}
const empman_query = `
SELECT
CONCAT(employees.first_name, " ", employees.last_name) Name,
employees.id ID,
CONCAT(employees.first_name, " ", employees.last_name) Name,
role.title Role,
department.name Department,
CONCAT(managers.first_name, " ", managers.last_name) Manager,
role.salary Salary
FROM employees
LEFT JOIN employees managers ON managers.id = employees.manager_id
JOIN role ON role.id = employees.role_id
JOIN department ON department.id = role.department_id
WHERE employees.manager_id = ${managerId}
ORDER BY Name`;
const resultsArray = await databaseQuery(empman_query);
console.table('\nEmployees with selected manager', resultsArray);
};
const viewBudget = async () => {
const budget_query = `
SELECT
department.name Department,
department.id ID,
SUM(role.salary) 'Utilised Budget'
FROM employees
JOIN role ON employees.role_id = role.id
JOIN department ON role.department_id = department.id
GROUP BY department.id
ORDER BY Department`;
const resultsArray = await databaseQuery(budget_query);
console.table('\nUtilised Budget', resultsArray);
};
module.exports = { viewMethods };
<file_sep>DROP DATABASE IF EXISTS employee_tracker_db;
CREATE DATABASE employee_tracker_db;
USE employee_tracker_db;
CREATE TABLE department (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
PRIMARY KEY(id)
);
CREATE TABLE role (
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(30),
salary DECIMAL(10,2) NOT NULL,
department_id INT NULL,
CONSTRAINT fk_department
FOREIGN KEY(department_id)
REFERENCES department(id)
ON UPDATE CASCADE
ON DELETE SET NULL,
PRIMARY KEY(id)
);
CREATE TABLE employees (
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(30),
last_name VARCHAR(30),
role_id INT NULL,
manager_id INT NULL,
CONSTRAINT fk_role
FOREIGN KEY (role_id)
REFERENCES role(id)
ON UPDATE CASCADE
ON DELETE SET NULL,
CONSTRAINT fk_manager
FOREIGN KEY (manager_id)
REFERENCES employees(id)
ON UPDATE CASCADE
ON DELETE SET NULL,
PRIMARY KEY(id)
);<file_sep>const { displayLogoArt } = require('./src/util/headers');
const { startMenu } = require('./src/util/startCLI');
const init = () => {
displayLogoArt();
startMenu();
};
init();<file_sep>const mysql = require('mysql');
const { promisify } = require('util')
const databaseQuery = async (query, values) => {
const connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "",
database: "employee_tracker_db"
});
const promiseQuery = promisify(connection.query).bind(connection);
const result = await promiseQuery(query, values)
connection.end();
return result;
};
module.exports = { databaseQuery };<file_sep>INSERT INTO department (name)
VALUES ("Senate"), ("Council"), ("Diplomacy"), ("Knights");
INSERT INTO role (title, salary, department_id)
VALUES ("Senator", 55000, 1),
("Ambassador", 50000, 1),
("Jedi Master", 65000, 2),
("Padawan", 30000, 2),
("<NAME>", 60000, 3),
("<NAME>", 40000, 3),
("<NAME>", 10000, 4),
("<NAME>", 60000, 4);
INSERT INTO employees (first_name, last_name, role_id, manager_id)
VALUES ("<NAME>", "Jinn", 3, null),
("Mace", "Windu", 3, null),
("<NAME>", "Kenobi", 3, null),
("Bail", "Organa", 1, null),
("Anakin", "Skywalker", 5, 3),
("Aayla", "Secura", 5, 2),
("Luke", "Skywalker", 2, 1),
("Leia", "Organa", 3, 4),
("Han", "Solo", 4, 4); | 11e159409f37bfd50ba83553daed820a8d096348 | [
"JavaScript",
"SQL",
"Markdown"
] | 12 | JavaScript | AGr2020Xman/employee-manager-cli | d78c93c76123f82994cf2ee99fafbb817b1b8e7c | c1bdcad436158f160de27292b5e493c995d464e8 |
refs/heads/master | <repo_name>hahagipe/try001<file_sep>/try1207/check_uni_api.php
<?php
//尋找是否有帳號存在:true-存在,false-不存在
$uni_username = $_POST["uni_username"];
require_once("dbtools.inc.php");
$conn=create_connect();
$sql = "SELECT * FROM member WHERE Username = '$uni_username'";
$result = execute_sql($conn, "demoDB", $sql);
if(mysqli_num_rows($result) == 1){
echo true;
}else{
echo false;
}
mysqli_close($conn);
?><file_sep>/try1207/reg_api.php
<?php
//註冊
$Username=$_POST["Username"];
$Password=$_POST["<PASSWORD>"];
require_once("dbtools.inc.php");
$conn=create_connect();
//密碼加密
$Password_md5=md5($Password);
$sql="INSERT INTO member(Username,Password)VALUES('$Username','$<PASSWORD>')";
if (execute_sql($conn,"demoDB",$sql)) {
echo true;
}else{
echo false;
}
mysqli_close($conn);
?><file_sep>/try1207/login_api.php
<?php
//直接拿check_uni_api來改即可
//登入帳號 存在:true-登入成功,false-登入失敗
//使用section前一定要加入此語法
session_start();
$Username = $_POST["Username"];
$Password = $_POST["Password"];
require_once("dbtools.inc.php");
$conn=create_connect();
//密碼加密
$Password_md5=md5($Password);
//更改此行內容(WHERE AND)
$sql = "SELECT * FROM member WHERE Username = '$Username' AND Password='$<PASSWORD>'";
$result = execute_sql($conn, "demoDB", $sql);
if(mysqli_num_rows($result) == 1){
//先從$result抓資料(判斷資料庫有無與此筆相符資料)
$row=mysqli_fetch_assoc($result);
//把抓到的資料存給$_SESSION:$_SESSION["Username"]可直接給前端網站呼叫
$_SESSION["Username"]=$row["Username"];
echo true;
}else{
echo false;
}
mysqli_close($conn);
?><file_sep>/try1207/logout_api.php
<?php
session_start();
if (session_destroy()) {
//php跳頁語法:header(location:"")
header("location:http://192.168.60.69/webdesign/20190826_member/login.php");
}
?><file_sep>/try1207/dbtools.inc.php
<?php
function create_connect(){
$conn=mysqli_connect("localhost","demo","123456")
or die("Error Link: ".mysqli_connect_error());
return $conn;
}
function execute_sql($conn,$dbname,$sql){
mysqli_select_db($conn,$dbname) or die("Error Open: ".mysqli_error($conn));
$result=mysqli_query($conn,$sql);
return $result;
}
?><file_sep>/try1207/main.php
<?php
//若要使用section一定要在第一行加入此php語法
session_start();
if (!isset($_SESSION["Username"])) {
header("location:http://192.168.60.69/webdesign/20190826_member/login.php");
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<!-- 此網址會隨版本改變 改成下載下來的檔案-->
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Hello, world!</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-primary text-light">
<a class="navbar-brand text-white" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link text-white" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link text-white" href="#">Link</a>
</li>
</ul>
<ul class="navbar-nav">
<li>
<!-- 加入php section語法:直接從後端(api)呼叫:$_SESSION["Username"] -->
<a class="nav-link text-light">Hello: <?php echo $_SESSION["Username"]; ?></a>
</li>
<li>
<a class="nav-link text-light" href="http://192.168.60.69/webdesign/20190826_member/logout_api.php">登出</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-sm-12 text-primary text-center">
<h3>登入後主畫面</h3>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="js/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- 下載下來的檔案 -->
<script src="js/bootstrap.min.js"></script>
</body>
</html> | 649ba363ce4a67fbc3fc382f0cb56a51270dd024 | [
"PHP"
] | 6 | PHP | hahagipe/try001 | d76685c339015c493aa1b512147b6fb6060ffe6e | e07486f8857d6bd2eabd3d75392000ce11e1ca59 |
refs/heads/master | <repo_name>AliShaikh94/stackapp<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/UsersListViewModel.kt
package com.alishaikh.wagchallenge
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Transformations.map
import android.arch.lifecycle.Transformations.switchMap
import android.arch.lifecycle.ViewModel
import com.alishaikh.wagchallenge.api.UsersApi
import com.alishaikh.wagchallenge.repo.UsersRepository
import com.alishaikh.wagchallenge.vo.User
import com.bumptech.glide.Glide.init
import java.io.Serializable
import java.util.*
/**
* Created by alishaikh on 3/5/18.
*/
class UsersListViewModel(val repo: UsersRepository): ViewModel() {
val state = MutableLiveData<State>()
// val currentPage = MutableLiveData<Int>()
//
// val currentOrder = MutableLiveData<UsersRepository.Orders>()
// val currentSort = MutableLiveData<UsersRepository.Sorts>()
//
private var repoResult = map(state, {
repo.getUsers(it.page, it.order.id, it.sort.id)
})
init {
state.value = State()
}
var users = switchMap(repoResult, {
it.list
})
val networkState = switchMap(repoResult, {
it.networkState
})
fun retry() {
repoResult.value?.retry?.invoke()
}
fun prevPage() {
state.value?.let {
if (it.page > 1) {
it.page = it.page - 1
state.value = it
}
}
}
fun nextPage() {
state.value?.let {
it.page = it.page + 1
state.value = it
}
}
fun changeSort(sort: UsersRepository.Sorts) {
state.value = State(order = state.value?.order!!, sort = sort)
// state.value?.let {
// it.sort = sort
// it.
// state.value = it
// }
}
fun changeOrder(order: UsersRepository.Orders) {
state.value = State(sort = state.value?.sort!!, order = order)
// state.value?.let {
// it.order = order
// state.value = it
// }
}
class State(
var page: Int = 1,
var order: UsersRepository.Orders = UsersRepository.Orders.Descending,
var sort: UsersRepository.Sorts = UsersRepository.Sorts.Reputation
) : Serializable
}<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/repo/Listing.kt
package com.alishaikh.wagchallenge.repo
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
/**
* Created by ashaikh on 3/7/18.
*/
data class Listing<T> (
val list: LiveData<List<T>>,
val networkState: LiveData<NetworkState>,
val retry: () -> Unit
)<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/StackApp.kt
package com.alishaikh.wagchallenge
import android.app.Application
import com.alishaikh.wagchallenge.di.AppComponent
import com.alishaikh.wagchallenge.di.DaggerAppComponent
/**
* Created by alishaikh on 3/5/18.
*/
class StackApp: Application() {
val component: AppComponent by lazy {
DaggerAppComponent
.builder()
.build()
}
override fun onCreate() {
super.onCreate()
component.inject(this)
// DaggerAppComponent.create().inject(this)
}
}<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/vo/User.kt
package com.alishaikh.wagchallenge.vo
import com.google.gson.annotations.SerializedName
import java.io.Serializable
/**
* Created by alishaikh on 3/5/18.
*/
data class User(
@SerializedName("account_id")
val accountId: Long,
@SerializedName("display_name")
val displayName: String,
@SerializedName("profile_image")
val profileImage: String,
@SerializedName("location")
val location: String,
@SerializedName("badge_counts")
val badgeCounts: Badges,
val reputation: Long
) : Serializable
data class Badges(
val gold: Int,
val silver: Int,
val bronze: Int
) : Serializable<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/api/UsersApi.kt
package com.alishaikh.wagchallenge.api
import android.util.Log
import com.alishaikh.wagchallenge.vo.User
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Query
import retrofit2.converter.gson.GsonConverterFactory
/**
* Created by alishaikh on 3/5/18.
*/
interface UsersApi {
@GET("users")
fun getUsersAtPage(
@Query("page") page: Int,
@Query("order") order: String,
@Query("sort") sort: String,
@Query("site") site: String): Call<UsersResponse>
class UsersResponse(val items: List<User>)
companion object {
private const val BASE_URL = "https://api.stackexchange.com/2.2/"
fun create(): UsersApi = create(HttpUrl.parse(BASE_URL)!!)
fun create(httpUrl: HttpUrl): UsersApi {
// val client = OkHttpClient.Builder()
// .build()
return Retrofit.Builder()
.baseUrl(httpUrl)
// .client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(UsersApi::class.java)
}
}
}<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/repo/UsersRepo.kt
package com.alishaikh.wagchallenge.repo
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.Transformations
import android.util.Log
import com.alishaikh.wagchallenge.api.UsersApi
import com.alishaikh.wagchallenge.vo.User
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import com.alishaikh.wagchallenge.api.UsersApi.UsersResponse
/**
* Created by alishaikh on 3/5/18.
*/
class UsersRepository(val usersApi: UsersApi) {
fun getUsers(page: Int, order: String, sort: String): Listing<User> {
val data = MutableLiveData<List<User>>()
val networkState = MutableLiveData<NetworkState>()
networkState.value = NetworkState.LOADING
fun refresh() {
usersApi.getUsersAtPage(page, order, sort, "stackoverflow").enqueue(
object : Callback<UsersResponse> {
override fun onFailure(call: Call<UsersResponse>?, t: Throwable) {
networkState.value = NetworkState.error(t.message ?: "unknown err")
Log.d("UsersRepo", t.toString())
}
override fun onResponse(call: Call<UsersResponse>, response: Response<UsersResponse>) {
if (response.isSuccessful) {
val items = (response.body() as UsersResponse).items
data.value = items
networkState.value = NetworkState.LOADED
} else {
networkState.value = NetworkState.error("error code: ${response.code()}")
}
}
})
}
refresh()
return Listing(
data,
networkState,
retry = { refresh() }
)
}
enum class Orders(val id: String) {
Descending("desc"),
Ascending("asc")
}
enum class Sorts(val id: String) {
Reputation("reputation"),
Name("name"),
Creation("creation"),
Modified("modified")
}
}<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/UsersAdapter.kt
package com.alishaikh.wagchallenge
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.alishaikh.wagchallenge.vo.User
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlinx.android.synthetic.main.user_list_item.view.*
/**
* Created by alishaikh on 3/5/18.
*/
class UsersAdapter(val glide: RequestManager): RecyclerView.Adapter<UserViewHolder>() {
private var users: List<User>? = null
fun update(users: List<User>?) {
this.users = users
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
return UserViewHolder.create(parent, glide)
}
override fun getItemCount()= users?.size ?: 0
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
users?.get(position)?.let { holder.bind(it) }
}
}
class UserViewHolder(view: View, val glide: RequestManager): RecyclerView.ViewHolder(view) {
var user: User? = null
val name = view.name
val profilePicture = view.profilePicture
val reputation = view.reputation
val location = view.location
val gold = view.gold
val silver = view.silver
val bronze = view.bronze
val progressBar = view.progressBar
// val skills = view.skills
fun bind(user: User){
this.user = user
name.text = user.displayName
reputation.text = user.reputation.toString()
location.text = user.location
gold.text = user.badgeCounts.gold.toString()
silver.text = user.badgeCounts.silver.toString()
bronze.text = user.badgeCounts.bronze.toString()
glide.load(user.profileImage)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
return false
}
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
progressBar.visibility = View.GONE
return false
}
})
.into(profilePicture)
}
companion object {
fun create(parent: ViewGroup, glide: RequestManager): UserViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.user_list_item, parent, false)
return UserViewHolder(view, glide)
}
}
}<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/MainActivity.kt
package com.alishaikh.wagchallenge
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.opengl.Visibility
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.LayoutManager
import android.support.v7.widget.RecyclerView.VERTICAL
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.alishaikh.wagchallenge.R.id.userList
import com.alishaikh.wagchallenge.di.DaggerAppComponent
import com.alishaikh.wagchallenge.repo.NetworkState
import com.alishaikh.wagchallenge.repo.Status
import com.alishaikh.wagchallenge.repo.UsersRepository
import com.alishaikh.wagchallenge.vo.User
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.alishaikh.wagchallenge.repo.UsersRepository.Sorts
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import kotlinx.android.synthetic.main.network_state_overlay.*
import javax.inject.Inject
class MainActivity : AppCompatActivity() {
private lateinit var model: UsersListViewModel
@Inject
lateinit var repo: UsersRepository
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
DaggerAppComponent.create().inject(this)
model = ViewModelProviders.of(this, object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return UsersListViewModel(repo) as T
}
})[UsersListViewModel::class.java]
initAdapter()
initTopBar()
initNetworkStateOverlay()
savedInstanceState?.get("state")?.let {
model.state.value = it as UsersListViewModel.State
}
next.setOnClickListener {
model.nextPage()
}
prev.setOnClickListener {
model.prevPage()
}
}
fun initAdapter() {
val glide = Glide.with(this)
val requestOptions = RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.placeholder)
glide.setDefaultRequestOptions(requestOptions)
val adapter = UsersAdapter(glide)
userList.adapter = adapter
userList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
model.users.observe(this, Observer<List<User>> {
adapter.update(it)
})
}
fun initTopBar() {
// val sortOptions = listOf(Sorts.Creation, Sorts.Modified, Sorts.Name, Sorts.Reputation).map { it.name }
val sortAdapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, Sorts.values())
Sort.adapter = sortAdapter
Sort.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) { }
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
model.changeSort(sortAdapter.getItem(position))
}
}
val orderAdapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, UsersRepository.Orders.values())
Order.adapter = orderAdapter
Order.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) { }
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
model.changeOrder(orderAdapter.getItem(position))
}
}
model.state.observe(this, Observer {
Sort.setSelection(sortAdapter.getPosition(it?.sort))
Order.setSelection(orderAdapter.getPosition(it?.order))
val text = "Page ${it?.page ?: 0}"
pageText.text = text
})
}
fun initNetworkStateOverlay() {
model.networkState.observe(this, Observer {
when(it?.status) {
Status.SUCCESS -> networkOverlay.visibility = View.GONE
Status.RUNNING -> {
networkOverlay.visibility = View.VISIBLE
error_msg.visibility = View.GONE
retry_button.visibility = View.GONE
}
Status.FAILED -> {
networkOverlay.visibility = View.VISIBLE
error_msg.visibility = View.VISIBLE
progress_bar.visibility = View.GONE
retry_button.visibility = View.VISIBLE
error_msg.text = it.msg
}
}
})
retry_button.setOnClickListener{
model.retry()
}
}
override fun onSaveInstanceState(outState: Bundle?) {
outState?.putSerializable("state", model.state.value)
super.onSaveInstanceState(outState)
}
}
<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/di/AppComponent.kt
package com.alishaikh.wagchallenge.di
import android.app.Activity
import android.app.Application
import com.alishaikh.wagchallenge.MainActivity
import com.alishaikh.wagchallenge.StackApp
import dagger.Component
import javax.inject.Singleton
/**
* Created by alishaikh on 3/5/18.
*/
@Singleton
@Component(modules = [UsersModule::class])
interface AppComponent {
fun inject(application: StackApp)
fun inject(activity: MainActivity)
}<file_sep>/app/src/main/java/com/alishaikh/wagchallenge/di/UsersModule.kt
package com.alishaikh.wagchallenge.di
import android.content.Context
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
import android.app.Application
import com.alishaikh.wagchallenge.api.UsersApi
import com.alishaikh.wagchallenge.repo.UsersRepository
/**
* Created by alishaikh on 3/5/18.
*/
@Module
class UsersModule {
@Provides
@Singleton
fun provideUsersApi(): UsersApi = UsersApi.create()
@Provides
@Singleton
fun provideUsersRepository(usersApi: UsersApi): UsersRepository = UsersRepository(usersApi)
}
| d61360bf9dffacdf637fffcab8ab9992de8a1625 | [
"Kotlin"
] | 10 | Kotlin | AliShaikh94/stackapp | 28b1c6c5fc9490ba33aa72e82c88d8d16eda075f | be672730a934f97b8005751519843975e7d9d7f4 |
refs/heads/master | <file_sep>package util.fileConvert;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
/**
* Created by Kennen on 2015-06-20.
*/
public class PdfConverter implements FileConverter {
private VioletImageVO originalFile;
public PdfConverter(VioletImageVO originalFile) {
this.originalFile = originalFile;
}
@Override
public InputStream getJPGImageFileStream() throws IOException, COSVisitorException {
PDDocument document = getLoad();
List<PDPage> pages = document.getDocumentCatalog().getAllPages();
PDPage page = pages.get(originalFile.getFindFileSeq());
BufferedImage bi = page.convertToImage();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
return is;
}
@Override
public boolean isMatchedByExtension() {
String extension = FileUtil.getFileExtention(originalFile.getOriginalFile().getName());
if (extension.equals("pdf")) {
return true;
} else {
return false;
}
}
@Override
public int getFileCount() throws IOException {
PDDocument doc = getLoad();
List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
return pages.size();
}
private PDDocument getLoad() throws IOException {
return PDDocument.load(new FileInputStream(originalFile.getOriginalFile()));
}
}
<file_sep>package com.techin.daum.preview;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
/**
* Created by kennen on 2015. 6. 26..
*/
@Controller
public class PreviewController {
@RequestMapping(value = "/preview/file/{attachId}")
public ModelAndView previewFile(HttpServletResponse response,
@PathVariable(value = "attachId") int attachId
) throws IOException {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("popup/imagePreviewTab");
return modelAndView;
}
@RequestMapping(value = "/preview/file/{attachId}/{seq}")
public void previewFile(HttpServletResponse response,
@PathVariable(value = "attachId") int attachId,
@PathVariable(value = "seq") int seq) throws IOException {
PDDocument document = PDDocument.load(new FileInputStream(new File("/data/(본문)이용자의 의견제출.pdf")));
List<PDPage> pages = document.getDocumentCatalog().getAllPages();
PDPage page = pages.get(0);
BufferedImage bi = page.convertToImage();
String extractTxtFile = "/data/(본문)이용자의 의견제출.jpg";
File file = new File(extractTxtFile);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", os);
InputStream fileIn = new ByteArrayInputStream(os.toByteArray());
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[4096];
while (fileIn.read(outputByte, 0, 4096) != -1) {
out.write(outputByte, 0, 4096);
}
fileIn.close();
out.flush();
out.close();
}
}
<file_sep>package util.fileConvert;
import org.apache.pdfbox.exceptions.COSVisitorException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Kennen on 2015-06-20.
*/
public class FileMaker {
List<FileConverter> fileConverterList;
public FileMaker(VioletImageVO originalFile) {
fileConverterList = new ArrayList<FileConverter>();
fileConverterList.add(new TifConverter(originalFile));
fileConverterList.add(new PdfConverter(originalFile));
fileConverterList.add(new ImageConverter(originalFile));
}
public int getFileCount() throws IOException {
int fileCount = 0;
for (FileConverter fileConverter : fileConverterList) {
if (fileConverter.isMatchedByExtension()) {
fileCount = fileConverter.getFileCount();
break;
}
}
return fileCount;
}
public InputStream saveJPGFile() throws IOException, COSVisitorException {
InputStream fileInputStream = null;
for (FileConverter fileConverter : fileConverterList) {
if (fileConverter.isMatchedByExtension()) {
fileInputStream = fileConverter.getJPGImageFileStream();
break;
}
}
return fileInputStream;
}
}
<file_sep>package util.fileConvert;
/**
* Created by Kennen on 2015-06-20.
*/
public class FileUtil {
public static String getFileExtention(String fileName) {
String extension = "";
int separateIndex = fileName.lastIndexOf('.');
int max = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if (separateIndex > max) {
extension = fileName.substring(separateIndex + 1);
}
return extension;
}
}
| 5aa56cd6c00c780b39e30c4d88496c15298eedb8 | [
"Java"
] | 4 | Java | ddakshe/Preview | 3a72cec1ada5252aa0780917285885e44c40b284 | 7671dc3a0e43ca265f3e8234710a5f6f73201f02 |
refs/heads/master | <repo_name>ferdysan/js-slider<file_sep>/main.js
$('.next').click(function() {
//salvo la posizione attuale dell'immagine in una variabile
var img_corrente = $('.visible');
//seleziono la prossima immagine a quella img_corrente
var prox_img = img_corrente.next('img');
//controllo se prossima img è maggiore di zero
if(prox_img.length > 0){
//rimuovo la classe per rendere visibile l'immagine
img_corrente.removeClass('visible');
//aggiungo la classe alla prossima immagine
prox_img.addClass('visible');
}
else{
// recupero la prima immagine dello slider e la setto come visibile
$('.slider img').first().addClass('visible');
img_corrente.removeClass('visible');
}
});
$('.prev').click(function(){
var img_corrente = $('.visible');
var img_precedente = img_corrente.prev('img');
if(img_precedente.length > 0){
img_corrente.removeClass('visible');
img_precedente.addClass('visible');
}else{
//altrimenti seleziono l'ultimo ta img e gli do la classe visible
$('.slider img').last().addClass('visible');
img_corrente.removeClass('visible');
}
});
setInterval(parerino, 1000)
| c6e394be05fef3b30bfed5a57ce8f59b5ec9ad07 | [
"JavaScript"
] | 1 | JavaScript | ferdysan/js-slider | 8574aa4b73e85d58c2c8cef0d6706eb58b360582 | 0702fcae4f69b3ca86d44aa7c758b05a9fa67005 |
refs/heads/main | <repo_name>guillaume-alves/School<file_sep>/src/ecole.sql
-- MySQL dump 10.13 Distrib 8.0.23, for Win64 (x86_64)
--
-- Host: localhost Database: ecole
-- ------------------------------------------------------
-- Server version 8.0.23
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `classe`
--
DROP TABLE IF EXISTS `classe`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `classe` (
`idclasse` int NOT NULL AUTO_INCREMENT,
`nom` varchar(45) NOT NULL,
PRIMARY KEY (`idclasse`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `classe`
--
LOCK TABLES `classe` WRITE;
/*!40000 ALTER TABLE `classe` DISABLE KEYS */;
INSERT INTO `classe` VALUES (1,'S1'),(2,'S2'),(3,'S3');
/*!40000 ALTER TABLE `classe` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `classe_matiere`
--
DROP TABLE IF EXISTS `classe_matiere`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `classe_matiere` (
`matiere_professeur_id` int NOT NULL,
`classe_id` int NOT NULL,
`idclassematiereprof` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`idclassematiereprof`),
KEY `matiere_professeur_k_idx` (`matiere_professeur_id`),
KEY `classe_k_idx` (`classe_id`),
CONSTRAINT `classe_k` FOREIGN KEY (`classe_id`) REFERENCES `classe` (`idclasse`),
CONSTRAINT `matiere_professeur_k` FOREIGN KEY (`matiere_professeur_id`) REFERENCES `matiere_professeur` (`idmatiereprofesseur`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `classe_matiere`
--
LOCK TABLES `classe_matiere` WRITE;
/*!40000 ALTER TABLE `classe_matiere` DISABLE KEYS */;
INSERT INTO `classe_matiere` VALUES (1,2,1),(2,1,2);
/*!40000 ALTER TABLE `classe_matiere` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `eleve`
--
DROP TABLE IF EXISTS `eleve`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `eleve` (
`ideleve` int NOT NULL AUTO_INCREMENT,
`nom` varchar(45) NOT NULL,
`prenom` varchar(45) NOT NULL,
`classe_id` int NOT NULL,
PRIMARY KEY (`ideleve`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `eleve`
--
LOCK TABLES `eleve` WRITE;
/*!40000 ALTER TABLE `eleve` DISABLE KEYS */;
INSERT INTO `eleve` VALUES (1,'Alves','Guillaume',1),(2,'Dauphin','Quentin',1),(3,'Defforey','Luc',1),(4,'Dupont','Bertrand',2),(5,'François','Baptiste',2),(6,'Gavalda','Emma',2),(7,'Fleury','Lucie',3),(8,'Calatayud','Lauriane',3),(9,'Prevot','Helene',3);
/*!40000 ALTER TABLE `eleve` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `matiere`
--
DROP TABLE IF EXISTS `matiere`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `matiere` (
`idmatiere` int NOT NULL AUTO_INCREMENT,
`nom` varchar(45) NOT NULL,
PRIMARY KEY (`idmatiere`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `matiere`
--
LOCK TABLES `matiere` WRITE;
/*!40000 ALTER TABLE `matiere` DISABLE KEYS */;
INSERT INTO `matiere` VALUES (1,'Cosmetologie'),(2,'Biochimie'),(3,'Physique'),(4,'Mathematiques'),(5,'Qualité'),(6,'Immunologie'),(7,'Genie des procedes');
/*!40000 ALTER TABLE `matiere` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `matiere_professeur`
--
DROP TABLE IF EXISTS `matiere_professeur`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `matiere_professeur` (
`matiere_id` int NOT NULL,
`professeur_id` int NOT NULL,
`idmatiereprofesseur` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`idmatiereprofesseur`),
KEY `professeur_k_idx` (`professeur_id`),
KEY `matiere_k_idx` (`matiere_id`),
CONSTRAINT `matiere_k` FOREIGN KEY (`matiere_id`) REFERENCES `matiere` (`idmatiere`),
CONSTRAINT `professeur_k` FOREIGN KEY (`professeur_id`) REFERENCES `professeur` (`idprofesseur`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `matiere_professeur`
--
LOCK TABLES `matiere_professeur` WRITE;
/*!40000 ALTER TABLE `matiere_professeur` DISABLE KEYS */;
INSERT INTO `matiere_professeur` VALUES (1,4,1),(2,4,2),(3,2,3),(4,1,4),(5,3,5),(6,6,6),(7,5,7),(7,7,8);
/*!40000 ALTER TABLE `matiere_professeur` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `professeur`
--
DROP TABLE IF EXISTS `professeur`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `professeur` (
`idprofesseur` int NOT NULL AUTO_INCREMENT,
`nom` varchar(45) NOT NULL,
`prenom` varchar(45) NOT NULL,
PRIMARY KEY (`idprofesseur`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `professeur`
--
LOCK TABLES `professeur` WRITE;
/*!40000 ALTER TABLE `professeur` DISABLE KEYS */;
INSERT INTO `professeur` VALUES (1,'Chazal','Robert'),(2,'Marchandon','Bernard'),(3,'Dufour','Florence'),(4,'Pense','Anne'),(5,'Gadonna','Jean-Pierre'),(6,'Huet','Denis'),(7,'Guilbert','Nathalie');
/*!40000 ALTER TABLE `professeur` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2021-02-14 11:29:07
<file_sep>/src/Main.java
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/ecole";
String user = "root";
String password = "<PASSWORD>";
try {
// Get connection to the database
Connection myConn = DriverManager.getConnection(url, user, password);
// Get statement
Statement state = myConn.createStatement();
String query = "SELECT professeur.nom, professeur.prenom, matiere.nom FROM ((professeur INNER JOIN matiere_professeur ON matiere_professeur.professeur_id = professeur.idprofesseur)INNER JOIN matiere ON matiere_professeur.matiere_id = matiere.idmatiere)";
ResultSet result = state.executeQuery(query);
String nom = "";
while(result.next()){
if(!nom.equals(result.getString("nom"))){
nom = result.getString("nom");
System.out.println(nom + " " + result.getString("professeur.prenom") + " enseigne : ");
}
System.out.println("\t\t\t - " + result.getString("matiere.nom"));
}
result.close();
state.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}<file_sep>/src/Main2.java
import java.sql.*;
public class Main2 {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/ecole";
String user = "root";
String password = "<PASSWORD>";
try {
// Get connection to the database
Connection myConn = DriverManager.getConnection(url, user, password);
// Get statement defined
Statement state = myConn.createStatement();
String query = "SELECT eleve.nom, eleve.prenom, classe.nom FROM eleve INNER JOIN classe ON eleve.classe_id = classe.idclasse";
ResultSet result = state.executeQuery(query);
ResultSetMetaData resultMeta = result.getMetaData();
System.out.print(resultMeta.getColumnName(1).toUpperCase() + ", " + resultMeta.getColumnName(2).toUpperCase() + ", CLASSE");
System.out.println("\n--------------------");
while(result.next()){
System.out.println(result.getString("eleve.prenom") + ", " + result.getString("eleve.nom") + ", " + result.getString("classe.nom"));
}
result.close();
state.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} | 713fdd7d7e6c89636b188e7e8a05e0400c64b6e8 | [
"Java",
"SQL"
] | 3 | SQL | guillaume-alves/School | d82ddd3a58a5416753cbb5a84b4afb0b3dcb9838 | 224b3fbb2c215ccdded3d5c2f84a3be564d3edb4 |
refs/heads/master | <file_sep>// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "GeneratedCppIncludes.h"
#include "Public/SGObjectiveActor.h"
PRAGMA_DISABLE_OPTIMIZATION
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeSGObjectiveActor() {}
// Cross Module References
STEALTHGAME_API UClass* Z_Construct_UClass_ASGObjectiveActor_NoRegister();
STEALTHGAME_API UClass* Z_Construct_UClass_ASGObjectiveActor();
ENGINE_API UClass* Z_Construct_UClass_AActor();
UPackage* Z_Construct_UPackage__Script_StealthGame();
// End Cross Module References
void ASGObjectiveActor::StaticRegisterNativesASGObjectiveActor()
{
}
UClass* Z_Construct_UClass_ASGObjectiveActor_NoRegister()
{
return ASGObjectiveActor::StaticClass();
}
UClass* Z_Construct_UClass_ASGObjectiveActor()
{
static UClass* OuterClass = NULL;
if (!OuterClass)
{
Z_Construct_UClass_AActor();
Z_Construct_UPackage__Script_StealthGame();
OuterClass = ASGObjectiveActor::StaticClass();
if (!(OuterClass->ClassFlags & CLASS_Constructed))
{
UObjectForceRegistration(OuterClass);
OuterClass->ClassFlags |= (EClassFlags)0x20900080u;
static TCppClassTypeInfo<TCppClassTypeTraits<ASGObjectiveActor> > StaticCppClassTypeInfo;
OuterClass->SetCppTypeInfo(&StaticCppClassTypeInfo);
OuterClass->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = OuterClass->GetOutermost()->GetMetaData();
MetaData->SetValue(OuterClass, TEXT("IncludePath"), TEXT("SGObjectiveActor.h"));
MetaData->SetValue(OuterClass, TEXT("ModuleRelativePath"), TEXT("Public/SGObjectiveActor.h"));
#endif
}
}
check(OuterClass->GetClass());
return OuterClass;
}
IMPLEMENT_CLASS(ASGObjectiveActor, 1674689900);
static FCompiledInDefer Z_CompiledInDefer_UClass_ASGObjectiveActor(Z_Construct_UClass_ASGObjectiveActor, &ASGObjectiveActor::StaticClass, TEXT("/Script/StealthGame"), TEXT("ASGObjectiveActor"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(ASGObjectiveActor);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
PRAGMA_ENABLE_OPTIMIZATION
<file_sep># Stealth_Game
This is a basic Stealth Game that is used for a course in Udemy.com
<file_sep>// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "ObjectMacros.h"
#include "ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef STEALTHGAME_SGObjectiveActor_generated_h
#error "SGObjectiveActor.generated.h already included, missing '#pragma once' in SGObjectiveActor.h"
#endif
#define STEALTHGAME_SGObjectiveActor_generated_h
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_RPC_WRAPPERS
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_RPC_WRAPPERS_NO_PURE_DECLS
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesASGObjectiveActor(); \
friend STEALTHGAME_API class UClass* Z_Construct_UClass_ASGObjectiveActor(); \
public: \
DECLARE_CLASS(ASGObjectiveActor, AActor, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/StealthGame"), NO_API) \
DECLARE_SERIALIZER(ASGObjectiveActor) \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_INCLASS \
private: \
static void StaticRegisterNativesASGObjectiveActor(); \
friend STEALTHGAME_API class UClass* Z_Construct_UClass_ASGObjectiveActor(); \
public: \
DECLARE_CLASS(ASGObjectiveActor, AActor, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/StealthGame"), NO_API) \
DECLARE_SERIALIZER(ASGObjectiveActor) \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API ASGObjectiveActor(const FObjectInitializer& ObjectInitializer); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ASGObjectiveActor) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ASGObjectiveActor); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASGObjectiveActor); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ASGObjectiveActor(ASGObjectiveActor&&); \
NO_API ASGObjectiveActor(const ASGObjectiveActor&); \
public:
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ASGObjectiveActor(ASGObjectiveActor&&); \
NO_API ASGObjectiveActor(const ASGObjectiveActor&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ASGObjectiveActor); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASGObjectiveActor); \
DEFINE_DEFAULT_CONSTRUCTOR_CALL(ASGObjectiveActor)
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_PRIVATE_PROPERTY_OFFSET
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_9_PROLOG
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_PRIVATE_PROPERTY_OFFSET \
StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_RPC_WRAPPERS \
StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_INCLASS \
StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_PRIVATE_PROPERTY_OFFSET \
StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_RPC_WRAPPERS_NO_PURE_DECLS \
StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_INCLASS_NO_PURE_DECLS \
StealthGame_Source_StealthGame_Public_SGObjectiveActor_h_12_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID StealthGame_Source_StealthGame_Public_SGObjectiveActor_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
<file_sep>// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "GeneratedCppIncludes.h"
#include "StealthGameGameMode.h"
PRAGMA_DISABLE_OPTIMIZATION
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeStealthGameGameMode() {}
// Cross Module References
STEALTHGAME_API UClass* Z_Construct_UClass_AStealthGameGameMode_NoRegister();
STEALTHGAME_API UClass* Z_Construct_UClass_AStealthGameGameMode();
ENGINE_API UClass* Z_Construct_UClass_AGameModeBase();
UPackage* Z_Construct_UPackage__Script_StealthGame();
// End Cross Module References
void AStealthGameGameMode::StaticRegisterNativesAStealthGameGameMode()
{
}
UClass* Z_Construct_UClass_AStealthGameGameMode_NoRegister()
{
return AStealthGameGameMode::StaticClass();
}
UClass* Z_Construct_UClass_AStealthGameGameMode()
{
static UClass* OuterClass = NULL;
if (!OuterClass)
{
Z_Construct_UClass_AGameModeBase();
Z_Construct_UPackage__Script_StealthGame();
OuterClass = AStealthGameGameMode::StaticClass();
if (!(OuterClass->ClassFlags & CLASS_Constructed))
{
UObjectForceRegistration(OuterClass);
OuterClass->ClassFlags |= (EClassFlags)0x20880288u;
static TCppClassTypeInfo<TCppClassTypeTraits<AStealthGameGameMode> > StaticCppClassTypeInfo;
OuterClass->SetCppTypeInfo(&StaticCppClassTypeInfo);
OuterClass->StaticLink();
#if WITH_METADATA
UMetaData* MetaData = OuterClass->GetOutermost()->GetMetaData();
MetaData->SetValue(OuterClass, TEXT("HideCategories"), TEXT("Info Rendering MovementReplication Replication Actor Input Movement Collision Rendering Utilities|Transformation"));
MetaData->SetValue(OuterClass, TEXT("IncludePath"), TEXT("StealthGameGameMode.h"));
MetaData->SetValue(OuterClass, TEXT("ModuleRelativePath"), TEXT("StealthGameGameMode.h"));
MetaData->SetValue(OuterClass, TEXT("ShowCategories"), TEXT("Input|MouseInput Input|TouchInput"));
#endif
}
}
check(OuterClass->GetClass());
return OuterClass;
}
IMPLEMENT_CLASS(AStealthGameGameMode, 2008007495);
static FCompiledInDefer Z_CompiledInDefer_UClass_AStealthGameGameMode(Z_Construct_UClass_AStealthGameGameMode, &AStealthGameGameMode::StaticClass, TEXT("/Script/StealthGame"), TEXT("AStealthGameGameMode"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(AStealthGameGameMode);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
PRAGMA_ENABLE_OPTIMIZATION
| 8ab8b91cc9517aa69ff9f85c5c0a86d49d09caba | [
"Markdown",
"C++"
] | 4 | C++ | BraidedMantis7/Stealth_Game | 428b93464c512ad8e841ca93ce579c59766a573c | 213861cc79172f8714f616d9052a0af8b1808721 |
refs/heads/master | <repo_name>midhunhk/feed-parser<file_sep>/BIotD/src/com/ae/feeds/reader/tests/UtilsTest.java
package com.ae.feeds.reader.tests;
import com.ae.feeds.reader.utils.FeedUtils;
public class UtilsTest {
public static void main(String[] args) {
testGetFileExtension();
testReadableFileSize();
}
public static void testGetFileExtension() {
System.out.print(" testGetFileExtension ");
String realExtension = "jpg";
String fileName = "d:\\wallpapers\\bing\\image_1290." + realExtension;
String result = FeedUtils.getFileExtension(fileName);
if (realExtension.equals(result)) {
System.out.println("passed");
} else {
System.out.println("failed");
}
}
public static void testReadableFileSize() {
System.out.print(" testReadableFileSize ");
long fileSize = 1024 * 1024 * 1024;
String result = FeedUtils.readableFileSize(fileSize);
if (result.equals("1 GiB")) {
System.out.println("passed");
} else {
System.out.println("failed");
}
}
}
<file_sep>/BIotD/src/com/ae/feeds/reader/utils/FeedUtils.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ae.feeds.reader.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ae.feeds.reader.model.FeedMessage;
/**
* Helper class for dealing with feeds and data
*
* @author Midhun
*
*/
public class FeedUtils {
private static final int BUFFER_SIZE = 4096;
/**
* Returns a simple name, link pair removing duplicates from the FeedMessages
*
* @param source
* @return
*/
public static Map<String, String> removeDuplicateFeeds(List<FeedMessage> source) {
if (source == null) {
return null;
}
// We are using hashmap as same imagenames will have same hash efefctively removing duplicates
Map<String, String> uniqueUrlsMap = new HashMap<String, String>();
String link = null;
String imageName = null;
for (FeedMessage fm : source) {
link = fm.getLink();
// Get just the image name from the url
imageName = link.substring(link.indexOf("%2f") + 3, link.indexOf("_"));
uniqueUrlsMap.put(imageName, link);
}
return uniqueUrlsMap;
}
/**
* Save an image url to the disk
*
* @param imageUrl
* @param destinationFile
* @param overwrite
* @throws IOException
*/
public static long saveImageAsFile(String imageUrl, String destinationFile, boolean overwrite) {
URL url = null;
long fileSize = 0;
InputStream is = null;
OutputStream os = null;
try {
if (overwrite == false) {
// If overwrite is false, check if the file exists
File file = new File(destinationFile);
if (file.exists()) {
// Short circuit the file saving logic
throw new Exception("Skipping save as file already exists");
}
}
// Open the image URL stream and download / read the image data
url = new URL(imageUrl);
is = url.openStream();
os = new FileOutputStream(destinationFile);
// At a time, BUFFER_SIZE amount of data will be read from the stream
byte[] b = new byte[BUFFER_SIZE];
int length;
while ((length = is.read(b)) != -1) {
fileSize += length;
os.write(b, 0, length);
}
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
try {
if (is != null)
is.close();
if (os != null)
os.close();
} catch (IOException e) {
System.err.println(e.getMessage());
return fileSize;
}
}
return fileSize;
}
/**
* Returns the extension of the file.
*
* @param fileName
* @return
*/
public static String getFileExtension(String fileName) {
if (fileName == null)
return "";
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
private static String[] units = { "bytes", "KiB", "MiB", "GiB" };
/**
* Returns the file size as a readable string
*
* @param size
* @return
*/
public static String readableFileSize(long size) {
if (size <= 0)
return "0";
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
<file_sep>/README.md
Feed Parser (for Bing's homepage images)
========================================
This project is basically an XML based Feed parser, with implementation for Bing Image of the Day as an example. It saves images to disk. Included is a very basic version which may be extended as a general purpose feed parser.
Each image from Bing may or may not have a license as applicable, and are not covered under "Apache License Version 2.0" under which this software is released.
Contributions for improving (or completing) functionalities or adding new features are welcome.
Usage
=====
To use the Bing Image of the Day and download the images, you can either
1. Download the latest build file from https://github.com/midhunhk/feed-parser/tree/master/BIotD/builds
2. Extract the zip file contents
3. Modify the `settings.properties` file in /app folder (Set the dowload path)
4. Simply run `run-biotd-app.cmd` file if you are on a Windows machine
Or if you are not using a Windows machine, want to see the code or get hands on
1. Import the project into a Java IDE like Eclipse (or build and run the application from a suitable editor)
2. Modify the `settings.properties` file in /app folder (Set the dowload path)
3. Open the file `com.ae.feeds.reader.tests.ReaderTest` and that's where you start
License
=======
Copyright 2013 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Disclaimer
====
This project is not supported or endorsed by Microsoft or Bing. The author of this code is not liable to damages arising from the use or misuse. The images from Bing may have licenses applied to them, but may be used as wallpaper.
<file_sep>/BIotD/src/com/ae/feeds/reader/read/RSSFeedParser.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ae.feeds.reader.read;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.XMLEvent;
import com.ae.feeds.reader.exceptions.AppException;
import com.ae.feeds.reader.model.Feed;
import com.ae.feeds.reader.model.FeedMessage;
/**
* Defines an RSS Feed Parser implementation that tries to parse an RSS that resides on the web
*
* @author Midhun
*
*/
public class RSSFeedParser implements IFeedParser {
static final String TITLE = "title";
static final String ITEM = "item";
static final String DESC = "description";
static final String ENCLOSURE = "enclosure";
static final String PUB_DATE = "pubDate";
static final String GUID = "guid";
static final String LINK = "link";
private URL url = null;
/**
* create a parser instance here
*
* @param feedUrl
*/
public RSSFeedParser() {
}
@Override
public void setFeedSource(String feedUrl) {
try {
if (feedUrl != null) {
this.url = new URL(feedUrl);
}
} catch (MalformedURLException e) {
System.err.println(e.getMessage());
}
}
public Feed readFeed() {
Feed feed = null;
try {
boolean isFeedHeader = true;
String desc = "";
String title = "";
String link = "";
String pubDate = "";
// Setup the XML Reading Factory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Read from the source
InputStream in = read();
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Loop through the DOM events while parsing
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
String localPort = event.asStartElement().getName().getLocalPart();
if (localPort.equalsIgnoreCase(ITEM)) {
if (isFeedHeader) {
isFeedHeader = false;
// A new feed element is created
feed = new Feed(title, link, desc, pubDate);
}
event = eventReader.nextEvent();
} else if (localPort.equalsIgnoreCase(TITLE)) {
// not working
title = getCharacterData(event, eventReader);
} else if (localPort.equalsIgnoreCase(LINK)) {
link = getCharacterData(event, eventReader);
} else if (localPort.equalsIgnoreCase(DESC)) {
desc = getCharacterData(event, eventReader);
} else if (localPort.equals(PUB_DATE)) {
pubDate = getCharacterData(event, eventReader);
} else if (localPort.equals(ENCLOSURE)) {
// Working
link = getAttribute(event, eventReader, "url");
}
} else if (event.isEndElement()) {
if (event.asEndElement().getName().getLocalPart().equalsIgnoreCase(ITEM)) {
FeedMessage message = new FeedMessage();
message.setDescription(desc);
message.setLink(link);
message.setTitle(title);
feed.getEntries().add(message);
event = eventReader.nextEvent();
}
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
return feed;
}
@SuppressWarnings("unchecked")
private String getAttribute(XMLEvent event, XMLEventReader reader, String attributeName) {
String result = "";
String name = "";
Iterator<Attribute> iter = event.asStartElement().getAttributes();
while (iter.hasNext()) {
Attribute attribute = iter.next();
name = attribute.getName().getLocalPart();
if (name.equals(attributeName)) {
result = attribute.getValue();
break;
}
}
return result;
}
private String getCharacterData(XMLEvent event, XMLEventReader eventReader) throws XMLStreamException {
String result = "";
event = eventReader.nextEvent();
if (event instanceof Characters) {
result = event.asCharacters().getData();
}
return result;
}
protected InputStream read() throws AppException {
try {
return url.openStream();
} catch (IOException e) {
System.err.println(e.getMessage());
throw new AppException(e.getMessage());
}
}
@Override
public String getFeedSource() {
return url.toString();
}
} | 43819eaaf45cebd7afe3bfa07c7bccd5e3f17413 | [
"Markdown",
"Java"
] | 4 | Java | midhunhk/feed-parser | 4fd41ac6eefb4cce47d20855f79a3d5a027637dd | 5655586e66518b1b830b72df9a1e2427369e247d |
refs/heads/master | <repo_name>Python3pkg/Lightstreamer-example-Chat-adapter-python<file_sep>/chat.py
#!/usr/bin/env python
'''An example of Lightstreamer remote Chat Adapter, which enables the exchange
of messages sent by users accessing the client Chat Application demo.
'''
import logging
import time
import argparse
from threading import Lock
from lightstreamer_adapter.interfaces.metadata import (MetadataProvider,
NotificationError)
from lightstreamer_adapter.interfaces.data import DataProvider, SubscribeError
from lightstreamer_adapter.server import (DataProviderServer,
MetadataProviderServer)
__author__ = "Lightstreamer Srl"
__copyright__ = "Copyright"
__credits__ = ["Lightstreamer Srl"]
__license__ = "Apache Licence 2.0"
__version__ = "1.0.0"
__maintainer__ = "Lightstreamer Srl"
__email__ = "<EMAIL>"
__status__ = "Production"
# The name of the item to subscribe to.
ITEM_NAME = "chat_room"
class ChatMetadataAdapter(MetadataProvider):
"""Subclass of MetadataProvider which provides a specific implementation
to manage user sessions and user messages.
"""
def __init__(self, data_adapter):
self.log = logging.getLogger("LS_demos_Logger.chat")
# Reference to the provided ChatDataAdapter, which will be used to send
# messages to pushed to the browsers.
self.data_adapter = data_adapter
# Dictionary to keep client context information supplied by
# Lightstreamer on new session notifications.
self.sessions = {}
# Lock used to manage concurrent access to the sessions dictionary.
self.sessions_lock = Lock()
def initialize(self, parameters, config_file=None):
"""Invoked to provide initialization information to the
ChataMetadataAdapter."""
self.log.info("ChatMetadataAdapter ready")
def notify_user_message(self, user, session_id, message):
"""Triggered by a client 'sendMessage' call.
The message encodes a chat message from the client.
"""
if message is None:
self.log.warning("None message received")
raise NotificationError("None message received")
# Message must be in the form "CHAT|<message>".
msg_tokens = message.split('|')
if len(msg_tokens) != 2 or msg_tokens[0] != "CHAT":
self.log.warning("Wrong message received")
raise NotificationError("Wrong message received")
# Retrieves the user session info associated with the session_id.
with self.sessions_lock:
session_info = self.sessions.get(session_id)
if session_info is None:
raise NotificationError(("Session lost! Please reload the "
"browser page(s)."))
# Extracts from the info the IP and the user agent, to identify the
# originator of the # message.
ipaddress = session_info["REMOTE_IP"]
user_agent = session_info["USER_AGENT"]
# Sends the message to be pushed to the browsers.
self.data_adapter.send_message(ipaddress, user_agent, msg_tokens[1])
def notify_session_close(self, session_id):
# Discard session information
with self.sessions_lock:
del self.sessions[session_id]
def notify_new_session(self, user, session_id, client_context):
# Register the session details.
with self.sessions_lock:
self.sessions[session_id] = client_context
class ChataDataAdapter(DataProvider):
"""Implementation of the DataProvider abstract class, which pushes messages
sent by users to the unique chat room, managed through the unique item
'chat_room'.
"""
def __init__(self):
self.log = logging.getLogger("LS_demos_Logger.chat")
self.subscribed = None
# Reference to the provided ItemEventListener instance
self.listener = None
def initialize(self, params, config_file=None):
"""Caches the reference to the provided ItemEventListener instance."""
self.log.info("ChatDataAdapter ready")
def set_listener(self, listener):
self.listener = listener
def subscribe(self, item_name):
"""Invoked to request data for the item_name item."""
if item_name == ITEM_NAME:
self.subscribed = item_name
else:
# Only one item for a unique chat room is managed.
raise SubscribeError("No such item")
def unsubscribe(self, item_name):
"""Invoked to end a previous request of data for an item."""
self.subscribed = None
def issnapshot_available(self, item_name):
"""Invoked to provide initialization information to the Data Adapter.
This adapter does not handle the snapshot.
If there is someone subscribed the snapshot is kept by the server.
"""
return False
def send_message(self, ipaddress, nick, message):
"""Accepts message submission for the unique chat room.
The sender is identified by an ipaddress address and a nickname.
"""
if not message:
self.log.warning("Received empty or None message")
return False
if not nick:
self.log.warning("Received empty or None nick")
return False
if not ipaddress:
self.log.warning("Received empty or None ipaddress")
return False
# Gets the current timestamp
now = time.time()
# Gets both the raw and the formatted version of the current timestamp.
raw_timestamp = str(int(round(now * 1000)))
timestamp = time.strftime("%H:%M:%S", time.localtime())
self.log.debug("%s|New message: %s -> %s -> %s", timestamp, ipaddress,
nick, message)
# Fills the events dictionary object.
update = {"IP": ipaddress, "nick": nick, "message": message,
"timestamp": timestamp,
"raw_timestamp": raw_timestamp}
# Sends the events.
self.listener.update(self.subscribed, update, False)
def main():
'''Module Entry Point'''
logging.basicConfig(dateFmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)
parser = argparse.ArgumentParser(description=("Launch the Remote Chat "
"Adapter."))
parser.add_argument('--host', type=str, nargs='?', metavar='<host>',
default="localhost", help=("the host name or ip "
"address of LS server"))
parser.add_argument('--metadata_rrport', type=int, metavar='<port>',
required=True, help=("the request/reply tcp port "
"number where the Proxy Metadata "
"Adapter is listening on"))
parser.add_argument('--data_rrport', type=int, metavar='<port>',
required=True, help=("the request/reply tcp port "
"where the Proxy DataAdapter is "
"listening on"))
parser.add_argument('--data_notifport', type=int, metavar='<port>',
required=True, help=("the notify tcp port where the "
"Proxy DataAdapter is listening "
"on"))
args = parser.parse_args()
# Creates a new instance of the ChatDataAdapter.
data_adapter = ChataDataAdapter()
# Creates a new instance of ChatMetadataAdapter and pass data_adapter
# to it.
metadata_adaper = ChatMetadataAdapter(data_adapter)
# Creates and starts the MetadataProviderServer, passing to it
# metadata_adaper and the tuple containing the target host information.
metadata_provider_server = MetadataProviderServer(metadata_adaper,
(args.host,
args.metadata_rrport))
metadata_provider_server.start()
# Creates and starts the DataProviderServer, passing to it data_adapter
# and the tuple containing the target host information.
dataprovider_server = DataProviderServer(data_adapter,
(args.host,
args.data_rrport,
args.data_notifport),
keep_alive=0)
dataprovider_server.start()
if __name__ == "__main__":
main()
| bbce1d3ad5db911b8387e9b7b0f69a48152675b5 | [
"Python"
] | 1 | Python | Python3pkg/Lightstreamer-example-Chat-adapter-python | b5520d45ae2f20e340923128866104a4cc126ff4 | f986f7981582d9e48339a4714c2a5eafc29f80af |
refs/heads/master | <file_sep>package ir.nilva.abotorab.db
import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import ir.nilva.abotorab.model.Row
class Converters {
@TypeConverter
fun fromString(value: String) =
Gson().fromJson<ArrayList<Row>>(value, object : TypeToken<ArrayList<Row>>() {}.type)
@TypeConverter
fun fromRows(list: ArrayList<Row>) = Gson().toJson(list)
}<file_sep>package ir.nilva.abotorab.model
import ir.nilva.abotorab.webservices.BaseResponse
class TakeResponse : BaseResponse()<file_sep>package ir.nilva.abotorab.webservices
import android.content.Context
import ir.nilva.abotorab.ApplicationContext
import ir.nilva.abotorab.helper.isConnectedWifiValid
import ir.nilva.abotorab.helper.toastError
import okhttp3.ResponseBody
import org.jetbrains.anko.runOnUiThread
import org.json.JSONObject
import retrofit2.Response
import java.net.UnknownHostException
fun getServices(): WebserviceUrls = MyRetrofit.getInstance().webserviceUrls
suspend fun <T> Context.callWebserviceWithFailure(
caller: suspend () -> Response<T>,
failure: (response: String, code: Int?) -> Unit
): T? {
return try {
val response = caller()
if (response.isSuccessful) {
response.body()
} else {
val jsonErr = response.errorBody()?.string()
val errorMessage =
JSONObject(jsonErr!!).getJSONArray("non_field_errors").get(0)?.toString()
?: "مشکلی پیش آمده است"
if (response.code() == 400) {
toastError(errorMessage)
}
failure(errorMessage, response.code())
null
}
} catch (e: Exception) {
if (this.isConnectedWifiValid()) {
failure("متاسفانه ارتباط برقرار نشد", -1)
} else {
failure(
"شبکه شما متعلق به این امانتداری نیست. لطفا از اپلیکیشن خارج شده و مجدد تنظیم دستی انجام دهید.",
-1
)
}
null
}
}
suspend fun <T> Context.callWebservice(
caller: suspend () -> Response<T>
): T? {
return try {
val response = caller()
if (response.isSuccessful) {
response.body()
} else {
handleError(response.code(), response.errorBody())
null
}
} catch (e: Exception) {
handleFailure(e)
null
}
}
private fun Context.handleError(
code: Int,
errorBody: ResponseBody?
) {
onFailed(WebServiceError(), errorBody?.string() ?: "", code)
}
private fun Context.handleFailure(t: Throwable) {
if(this.isConnectedWifiValid()){
if (t is UnknownHostException) {
onFailed(t, "اتصال خود را بررسی کنید")
} else {
onFailed(t, t.message.toString())
}
} else {
onFailed(t, "شبکه شما متعلق به این امانتداری نیست. لطفا از اپلیکیشن خارج شده و مجدد تنظیم دستی انجام دهید.")
}
}
private fun Context.handleException(e: java.lang.Exception) {
onFailed(e, e.message.toString())
}
fun Context.onFailed(throwable: Throwable, errorBody: String, errorCode: Int = -1) {
when (throwable) {
is UnknownHostException -> runOnUiThread {
toastError("لطفا اتصال خود را بررسی کنید")
}
is WebServiceError -> {
if (errorCode == 403) {
toastError("شما دسترسی لازم را ندارید")
} else {
toastError(errorBody)
}
}
else-> toastError(errorBody)
}
}<file_sep>package ir.nilva.abotorab.db.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "offline_delivery")
data class OfflineDeliveryEntity(
@PrimaryKey val hashId: String
)<file_sep>package ir.nilva.abotorab.model
import com.google.gson.annotations.SerializedName
import ir.nilva.abotorab.webservices.BaseResponse
class GiveResponse (
@SerializedName("pilgrim") val pilgrim: Pilgrim,
@SerializedName("hash_id") val hashId: String,
@SerializedName("exited_at") val exitAt: String,
@SerializedName("cell_code") val cellCode: String
): BaseResponse()<file_sep>package ir.nilva.abotorab.view.page.operation
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import ir.nilva.abotorab.R
import ir.nilva.abotorab.db.AppDatabase
import ir.nilva.abotorab.db.model.DeliveryEntity
import ir.nilva.abotorab.helper.toastSuccess
import ir.nilva.abotorab.view.page.base.BaseActivity
import ir.nilva.abotorab.view.widget.MarginItemDecoration
import ir.nilva.abotorab.webservices.callWebservice
import ir.nilva.abotorab.webservices.getServices
import kotlinx.android.synthetic.main.activity_recent_gives.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class RecentGivesActivity : BaseActivity(),
RecentGivesListener {
private lateinit var adapter: RecentGivesAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recent_gives)
adapter = RecentGivesAdapter(this)
recyclerView.adapter = adapter
recyclerView.addItemDecoration(MarginItemDecoration(20))
AppDatabase.getInstance().deliveryDao()
.getAll().observe(this, Observer {
if (it.isNullOrEmpty()) {
emptyState.visibility = View.VISIBLE
} else {
emptyState.visibility = View.GONE
}
adapter.submitList(it)
})
}
override fun undoClicked(item: DeliveryEntity) {
CoroutineScope(Dispatchers.Main).launch {
callWebservice { getServices().undoDelivery(item.hashId) }?.run {
toastSuccess("این محموله بازگردانده شد")
AppDatabase.getInstance().deliveryDao().delete(item)
}
}
}
}
interface RecentGivesListener {
fun undoClicked(item: DeliveryEntity)
}
<file_sep>package ir.nilva.abotorab.helper
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
import ir.nilva.abotorab.ApplicationContext
import ir.nilva.abotorab.R
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
fun getCountryName(code: String): String {
val inputStream = ApplicationContext.context.resources.openRawResource(R.raw.nationality)
val jsonString = readTextFile(inputStream)
val jsonObject = JSONObject(jsonString)
for (key in jsonObject.keys()) {
val country = jsonObject.get(key) as JSONObject
if (country.get("alpha_3") == code) {
return country.get("en_name") as String;
}
}
return ""
}
fun getCountries() : List<CountryModel>{
val inputStream = ApplicationContext.context.resources.openRawResource(R.raw.nationality)
val jsonString = readTextFile(inputStream)
return GsonBuilder().registerTypeAdapter(CountryList::class.java, CountryListDeserializer())
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create().fromJson(jsonString, CountryList::class.java).countries
}
fun readTextFile(inputStream: InputStream): String {
val outputStream = ByteArrayOutputStream()
val buf = ByteArray(1024)
var len = inputStream.read(buf)
try {
while (len != -1) {
outputStream.write(buf, 0, len)
len = inputStream.read(buf)
}
outputStream.close()
inputStream.close()
} catch (e: IOException) {
}
return outputStream.toString()
}<file_sep>package ir.nilva.abotorab.view.page.operation
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.ProgressBar
import android.widget.RelativeLayout
import com.anychart.AnyChart
import com.anychart.AnyChart.column
import com.anychart.AnyChartView
import com.anychart.chart.common.dataentry.DataEntry
import com.anychart.chart.common.dataentry.ValueDataEntry
import com.anychart.enums.*
import com.llollox.androidtoggleswitch.widgets.ToggleSwitch
import ir.nilva.abotorab.R
import ir.nilva.abotorab.helper.dp
import ir.nilva.abotorab.model.Distribution
import ir.nilva.abotorab.model.House
import ir.nilva.abotorab.model.ReportResponse
import ir.nilva.abotorab.view.page.base.BaseActivity
import ir.nilva.abotorab.webservices.MyRetrofit
import ir.nilva.abotorab.webservices.callWebservice
import ir.nilva.abotorab.webservices.getServices
import kotlinx.android.synthetic.main.activity_report.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jetbrains.anko.below
import org.jetbrains.anko.centerHorizontally
class ReportActivity : BaseActivity() {
private var data: ReportResponse? = null
private var currentPosition = 0
private lateinit var progressBar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_report)
switchButton.setCheckedPosition(currentPosition)
progressBar = ProgressBar(this)
val layoutParams = RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
layoutParams.centerHorizontally()
layoutParams.below(R.id.switchButton)
layoutParams.topMargin = dp(125)
progressBar.layoutParams = layoutParams
rootLayout.addView(progressBar)
switchButton.onChangeListener = object : ToggleSwitch.OnChangeListener {
override fun onToggleSwitchChanged(position: Int) {
currentPosition = position
triggerChart()
}
}
CoroutineScope(Dispatchers.Main).launch {
callWebservice { getServices().report() }?.run {
data = this
triggerChart()
}
}
exportButton.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
callWebservice { getServices().export() }?.run {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse(MyRetrofit.getBaseUrl() + this.url)
)
)
}
}
}
exportStoreButton.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
callWebservice { getServices().exportStore() }?.run {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse(MyRetrofit.getBaseUrl() + this.url)
)
)
}
}
}
}
private fun triggerChart() {
if (currentPosition == 0 && data != null) {
initChart(data?.house!!)
} else if (currentPosition == 1 && data != null) {
initPieChart(data?.distribution!!)
}
}
private fun initChart(house: House) {
val chart = AnyChartView(this)
chart.layoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
chart.setProgressBar(progressBar)
val cartesian = column()
cartesian.column(prepareData(house)).tooltip()
.titleFormat("{%X}")
.position(Position.CENTER_BOTTOM)
.anchor(Anchor.CENTER_BOTTOM)
.offsetX(0)
.offsetY(5)
.format("{%value}")
cartesian.animation(true)
cartesian.yScale(ScaleTypes.ORDINAL)
cartesian.yAxis(0).labels().format("{%value}")
cartesian.tooltip().positionMode(TooltipPositionMode.POINT)
cartesian.interactivity().hoverMode(HoverMode.BY_X)
cartesian.xAxis(0).title("بازه های ساعت")
cartesian.yAxis(0).title("تعداد محموله ها")
chart.setChart(cartesian)
chartLayout.removeAllViews()
chartLayout.addView(chart)
}
private fun initPieChart(distribution: Distribution) {
val chart = AnyChartView(this)
chart.layoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
chart.setProgressBar(progressBar)
val pie = AnyChart.pie()
pie.data(prepareData(distribution))
pie.title("توزیع کل محموله ها")
pie.labels().position("outside")
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL)
.align(Align.CENTER)
chart.setChart(pie)
chartLayout.removeAllViews()
chartLayout.addView(chart)
}
private fun prepareData(house: House): ArrayList<DataEntry> {
val data = ArrayList<DataEntry>()
data.add(ValueDataEntry("< 3", house.in3Hour))
data.add(ValueDataEntry("3-6", house.in6Hour))
data.add(ValueDataEntry("6-24", house.in24Hour))
data.add(ValueDataEntry("24-48", house.in48Hour))
return data
}
private fun prepareData(distribution: Distribution): ArrayList<DataEntry> {
val data = ArrayList<DataEntry>()
data.add(ValueDataEntry("تحویل داده شده", distribution.deliveredToCustomer))
data.add(ValueDataEntry("تحویل گرفته شده", distribution.deliveredToStore))
data.add(ValueDataEntry("گم شده", distribution.missed))
return data
}
}
<file_sep>package ir.nilva.abotorab.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
import ir.nilva.abotorab.webservices.BaseResponse
import java.io.Serializable
@Entity
class CabinetResponse(
@PrimaryKey
@SerializedName("code") val code: String,
@SerializedName("rows") val rows: ArrayList<Row>
) : BaseResponse(), Serializable<file_sep>package ir.nilva.abotorab.view.widget
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.util.AttributeSet
import android.widget.Button
import androidx.core.content.ContextCompat
import ir.nilva.abotorab.R
/**
* Created by mahdihs76 on 9/10/18.
*/
open class UnoButton : Button {
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)
init {
background = ContextCompat.getDrawable(context, R.drawable.button_bg)
textSize = 22F
setTextColor(Color.WHITE)
setTypeface(typeface, Typeface.BOLD)
}
}<file_sep>package ir.nilva.abotorab.helper
import com.microblink.MicroblinkSDK
import ir.nilva.abotorab.ApplicationContext
const val DEFAULT_LICENSE_KEY =
"<KEY>
@Throws(Exception::class)
fun setBlinkIdDefaultLicenceKey() {
MicroblinkSDK.setLicenseKey(
DEFAULT_LICENSE_KEY,
ApplicationContext.context
)
}
@Throws(Error::class, Exception::class)
fun setBlinkIdLicenceKey(license: String) {
MicroblinkSDK.setLicenseKey(
license,
ApplicationContext.context
)
}<file_sep>package ir.nilva.abotorab.view.page.operation
import android.graphics.PointF
import android.opengl.Visibility
import android.os.Bundle
import android.util.Base64
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.dlazaro66.qrcodereaderview.QRCodeReaderView
import ir.nilva.abotorab.R
import ir.nilva.abotorab.helper.*
import ir.nilva.abotorab.view.page.base.BaseActivity
import kotlinx.android.synthetic.main.activity_barcode.*
import kotlinx.android.synthetic.main.give_verification.view.*
import org.jetbrains.anko.sdk27.coroutines.onCheckedChange
class CameraActivity : BaseActivity(), QRCodeReaderView.OnQRCodeReadListener {
private var isQR = false
private var mostRecentHashId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_barcode)
confirm_cb.isChecked = defaultCache()["need_to_confirmation"] ?: true
confirm_cb.onCheckedChange { _, isChecked ->
defaultCache()["need_to_confirmation"] = isChecked
}
confirm_layout.setOnClickListener { confirm_cb.performClick() }
recent_layout.setOnClickListener { recent.performClick() }
search_layout.setOnClickListener { search.performClick() }
search.setOnClickListener { gotoGiveSearchPage() }
recent.setOnClickListener { gotoRecentGivesPage() }
qrView.setOnQRCodeReadListener(this)
qrView.setQRDecodingEnabled(true)
qrView.setTorchEnabled(true)
isQR = intent?.extras?.getBoolean("isQR") ?: false
}
var isBarcodeFound = false
override fun onQRCodeRead(text: String?, points: Array<out PointF>?) {
if (!isBarcodeFound) {
isBarcodeFound = true
val result = text ?: ""
give(result)
}
}
private fun give(barcode: String) {
if (barcode.isNotEmpty()) {
try {
val text = String(
Base64.decode(
barcode,
Base64.DEFAULT
),
Charsets.UTF_8
).substringAfter("http://gbaghiyatallah.ir/?data=")
.split("#")
val hashId = text[2]
val view = layoutInflater.inflate(R.layout.give_verification, null)
view.nickName.text = text[0]
view.county.text = "از کشور ${text[1]}"
val phoneNumber4Digit = text[3]
if (phoneNumber4Digit.isEmpty()) {
view.phoneNumber.visibility = View.GONE
} else {
view.phoneNumber.text = "شماره تلفن : $phoneNumber4Digit********"
}
view.cellCode.text = "شماره قفسه : ${mapCabinetLabelWithCab(text[4])}"
confirmToGive(view, hashId, text[4])
} catch (e: Exception) {
toastError("بارکد اسکن شده معتبر نمیباشد")
}
}
}
private fun confirmToGive(view: View?, hashId: String, cellCode: String) {
if (mostRecentHashId == hashId) {
isBarcodeFound = false
return
}
val need = /*defaultCache()["need_to_confirmation"] ?:*/ true
if (need) {
MaterialDialog(this).show {
customView(view = view)
title(text = "تایید")
positiveButton(text = "بله") {
callGiveWS(hashId, cellCode)
mostRecentHashId = hashId
isBarcodeFound = false
}
negativeButton(text = "خیر") {
isBarcodeFound = false
mostRecentHashId = null
}
}
} else {
callGiveWS(hashId, cellCode)
mostRecentHashId = hashId
isBarcodeFound = false
}
}
override fun onResume() {
super.onResume()
qrView.startCamera()
}
override fun onPause() {
super.onPause()
isBarcodeFound = false
mostRecentHashId = null
qrView.stopCamera()
}
}
<file_sep>package ir.nilva.abotorab.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import ir.nilva.abotorab.webservices.BaseResponse
class ReportResponse(@Expose @SerializedName("in_house") val house: House,
@Expose @SerializedName("distribution") val distribution: Distribution
): BaseResponse()
class House(@Expose @SerializedName("3") val in3Hour: Int,
@Expose @SerializedName("6") val in6Hour: Int,
@Expose @SerializedName("24") val in24Hour: Int,
@Expose @SerializedName("48") val in48Hour: Int)
class Distribution(@Expose @SerializedName("total") val total: Int,
@Expose @SerializedName("0") val deliveredToCustomer: Int,
@Expose @SerializedName("1") val deliveredToStore: Int,
@Expose @SerializedName("2") val missed: Int)<file_sep>package ir.nilva.abotorab.webservices
class WebServiceError : Throwable()
<file_sep>package ir.nilva.abotorab.view.page.cabinet
import android.annotation.SuppressLint
import android.app.Activity
import android.content.res.Resources
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import androidx.core.view.marginLeft
import androidx.core.view.marginRight
import ir.nilva.abotorab.R
import ir.nilva.abotorab.helper.*
import ir.nilva.abotorab.model.CabinetResponse
import kotlinx.android.synthetic.main.activity_cabinet.*
import kotlinx.android.synthetic.main.activity_cabinet.view.*
import kotlinx.android.synthetic.main.cabinet.view.*
import org.json.JSONObject
class CabinetAdapter(
val activity: Activity,
var cabinet: CabinetResponse?,
var rows: Int,
var columns: Int,
var carriageEnabled: Boolean,
var rowDir: Boolean,
var colDir: Boolean
) : BaseAdapter() {
@SuppressLint("ViewHolder")
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View =
LayoutInflater.from(activity).inflate(R.layout.cabinet, null).apply {
if (columns > 6) {
image.requestLayout()
image.layoutParams.width = activity.getScreenWidth() / 7
}
if (carriageEnabled && p0 / columns == rows - 1) {
long_image.visibility = View.VISIBLE
long_image.requestLayout()
long_image.layoutParams.width = 200
// long_image.layoutParams.width = (activity.getScreenWidth() / columns)
long_image.layoutParams.height = (long_image.layoutParams.width * 1.3).toInt()
image.visibility = View.GONE
}
cabinet ?: return@apply
val cell = cabinet?.getCell(p0, rowDir, colDir)
cell ?: return@apply
if (cell.size > 0) {
long_image.visibility = View.VISIBLE
long_image.requestLayout()
long_image.layoutParams.width = 200
// long_image.layoutParams.width = (activity.getScreenWidth() / columns)
long_image.layoutParams.height = (long_image.layoutParams.width * 1.3).toInt()
image.visibility = View.GONE
}
val needLongCell = carriageEnabled && p0 / columns == rows - 1
if (needLongCell || cell.size > 0) {
long_image.setImageResource(cell.getImageResource(true))
} else {
image.setImageResource(cell.getImageResource(false))
}
codeTextView.visibility = View.VISIBLE
codeTextView.text = mapCabinetLabel(cell.code)
}
override fun getItem(p0: Int) = null
override fun getItemId(p0: Int): Long = System.currentTimeMillis()
override fun getCount() = rows * columns
}<file_sep>package ir.nilva.abotorab.db.dao
import androidx.room.*
import ir.nilva.abotorab.db.model.OfflineDeliveryEntity
@Dao
interface OfflineDeliveryDao {
@Query("SELECT * FROM offline_delivery")
suspend fun getAll(): List<OfflineDeliveryEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(item: OfflineDeliveryEntity)
@Query("DELETE FROM offline_delivery WHERE hashId =:hashId")
suspend fun delete(hashId: String)
@Delete
suspend fun delete(item: OfflineDeliveryEntity)
@Query("DELETE FROM offline_delivery")
suspend fun clear()
}<file_sep>package ir.nilva.abotorab.helper
import ir.nilva.abotorab.R
import ir.nilva.abotorab.model.CabinetResponse
import ir.nilva.abotorab.model.Cell
fun CabinetResponse.getCell(index: Int, rowDir: Boolean = false, colDir: Boolean = false): Cell {
var rowIndex = getRowsNumber() - index / getColumnsNumber() - 1
var columnIndex = index % getColumnsNumber()
if (rowDir)
rowIndex = index / getColumnsNumber()
if (colDir)
columnIndex = getColumnsNumber() - index % getColumnsNumber() - 1
// when (dir) {
// 1 -> {
// rowIndex = getRowsNumber() - index / getColumnsNumber() - 1
// columnIndex = index % getColumnsNumber()
// }
// 2 -> {
// rowIndex = getRowsNumber() - index / getColumnsNumber() - 1
// columnIndex = getColumnsNumber() - index % getColumnsNumber() - 1
// }
// 3 -> {
// rowIndex = index / getColumnsNumber()
// columnIndex = getColumnsNumber() - index % getColumnsNumber() - 1
// }
// }
return rows[rowIndex].cells[columnIndex]
}
fun CabinetResponse.rotateRow() {
for (row in rows)
row.cells.reverse()
}
fun CabinetResponse.rotateCol() {
rows.reverse()
}
fun CabinetResponse.rotate(dir: Int = 0) {
if (dir % 2 == 0)
rows.reverse()
else
for (row in rows) {
row.cells.reverse()
}
}
fun Cell.getIndex() = ((id % 100) / 10) * size + (id % 10)
fun CabinetResponse.getRowsNumber() = rows.size
fun CabinetResponse.getColumnsNumber() = rows[0].cells.size
fun Cell.getImageResource(longCell: Boolean) = if (longCell) when {
!isHealthy -> R.mipmap.broken_long
age == -1 && !isFavorite -> R.mipmap.cabinet_empty_long
age == -1 && isFavorite -> R.mipmap.cabinet_empty_fav_long
age == 0 && !isFavorite -> R.mipmap.cabinet_fill_1_long
age == 0 && isFavorite -> R.mipmap.cabinet_fill_1_fav_long
!isFavorite -> R.mipmap.cabinet_fill_3_long
else -> R.mipmap.cabinet_fill_3_fav
} else when {
!isHealthy -> R.mipmap.broken
age == -1 && !isFavorite -> R.mipmap.cabinet_empty
age == -1 && isFavorite -> R.mipmap.cabinet_empty_fav
age == 0 && !isFavorite -> R.mipmap.cabinet_fill_1
age == 0 && isFavorite -> R.mipmap.cabinet_fill_1_fav
!isFavorite -> R.mipmap.cabinet_fill_3
else -> R.mipmap.cabinet_fill_3_fav
}<file_sep>package ir.nilva.abotorab.view.page.cabinet
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.list.listItems
import com.commit451.modalbottomsheetdialogfragment.ModalBottomSheetDialogFragment
import com.commit451.modalbottomsheetdialogfragment.Option
import com.commit451.modalbottomsheetdialogfragment.OptionRequest
import ir.nilva.abotorab.R
import ir.nilva.abotorab.db.AppDatabase
import ir.nilva.abotorab.helper.*
import ir.nilva.abotorab.model.CabinetResponse
import ir.nilva.abotorab.model.Cell
import ir.nilva.abotorab.model.Pack
import ir.nilva.abotorab.model.Pilgrim
import ir.nilva.abotorab.view.page.base.BaseActivity
import ir.nilva.abotorab.webservices.callWebservice
import ir.nilva.abotorab.webservices.callWebserviceWithFailure
import ir.nilva.abotorab.webservices.getServices
import kotlinx.android.synthetic.main.activity_cabinet.*
import kotlinx.android.synthetic.main.activity_cabinet.view.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import nl.dionsegijn.steppertouch.OnStepCallback
import nl.dionsegijn.steppertouch.StepperTouch
const val USER_OPTION_ID = 0
const val UNUSABLE_OPTION_ID = 1
const val USABLE_OPTION_ID = 2
const val EMPTY_OPTION_ID = 3
const val FAV_OPTION_ID = 4
const val STORE_OPTION_ID = 5
const val PRINT_OPTION_ID = 6
class CabinetActivity : BaseActivity(), ModalBottomSheetDialogFragment.Listener {
private var rows = 3
private var columns = 4
private var rowDir = false
private var colDir = false
private var carriageEnabled = false
private var adapter = CabinetAdapter(
this,
null,
rows,
columns,
carriageEnabled,
rowDir, colDir
)
private var step = 0
private lateinit var currentCabinet: CabinetResponse
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cabinet)
initUi()
val code = intent?.extras?.getString("code")
observeOnDb(code)
}
private fun observeOnDb(code: String?) {
if (code != null && code != "") {
AppDatabase.getInstance().cabinetDao().getLiveData(code).observe(this, Observer {
it ?: return@Observer
rows = it.getRowsNumber()
columns = it.getColumnsNumber()
currentCabinet = it
adapter.cabinet = currentCabinet
moveToNextStep()
refresh()
})
}
}
private fun initUi() {
carriageSwitch.setEnableEffect(false)
initSteppers()
initGrid()
submit.setOnClickListener { addCabinet() }
extend.setOnClickListener {
val view = layoutInflater.inflate(R.layout.extend_dialog, null)
val rowsStepper = (view.findViewById(R.id.rowsCount) as StepperTouch)
val columnsStepper = (view.findViewById(R.id.columnsCount) as StepperTouch)
rowsStepper.apply {
count = rows
minValue = rows
// maxValue = 10
sideTapEnabled = true
}
columnsStepper.apply {
count = columns
minValue = columns
// maxValue = 10
sideTapEnabled = true
}
val dialog = MaterialDialog(this).customView(view = view).cornerRadius(20.0f)
.positiveButton(text = "تایید") {
val newRowsCount = rowsStepper.count
val newColumnsCount = columnsStepper.count
CoroutineScope(Dispatchers.Main).launch {
callWebservice {
getServices().extendCabinet(
currentCabinet.code,
newColumnsCount - columns,
newRowsCount - rows
)
}?.run {
AppDatabase.getInstance().cabinetDao().update(this)
}
}
}
dialog.show()
}
}
private fun addCabinet() {
CoroutineScope(Dispatchers.Main).launch {
submit.isClickable = false
callWebserviceWithFailure({
getServices().cabinet("", rows, columns, 1, if (carriageEnabled) 1 else 0)
}) { response, code ->
toastError(response)
submit.isClickable = true
}?.run {
currentCabinet = this
AppDatabase.getInstance().cabinetDao().insert(currentCabinet)
adapter.cabinet = currentCabinet
moveToNextStep()
observeOnDb(currentCabinet.code)
}
}
}
private fun initGrid() {
val params = linearLayout_gridtableLayout.layoutParams
params.width = getScreenWidth() - 10
linearLayout_gridtableLayout.layoutParams = params
grid.adapter = adapter
grid.setOnItemClickListener { _, view, index, _ ->
if (step == 0) return@setOnItemClickListener
showPopup(index)
}
}
private fun updateCarriage(isChecked: Boolean) {
carriageEnabled = isChecked
adapter.carriageEnabled = carriageEnabled
adapter.notifyDataSetChanged()
}
private fun switchDirection(reverse: Boolean, rowRotate: Boolean = true) {
// rowDir = rowRotate
// colDir = !rowRotate
// adapter.rowDir = rowDir
// adapter.colDir = colDir
if (rowRotate)
currentCabinet.rotateRow()
else
currentCabinet.rotateCol()
adapter.notifyDataSetChanged()
CoroutineScope(Dispatchers.Main).launch {
AppDatabase.getInstance().cabinetDao().insert(currentCabinet)
}
}
private fun initSteppers() {
rowsCount.addStepCallback(object : OnStepCallback {
override fun onStep(value: Int, positive: Boolean) = updateRows(value)
})
columnsCount.addStepCallback(object : OnStepCallback {
override fun onStep(value: Int, positive: Boolean) = updateColumns(value)
})
carriageSwitch.setOnCheckedChangeListener { _, isChecked ->
updateCarriage(isChecked)
}
directionSwitch.setOnClickListener {
switchDirection(false)
}
directionSwitch2.setOnClickListener {
switchDirection(false, rowRotate = false)
}
rowsCount.minValue = 1
columnsCount.minValue = 1
// rowsCount.maxValue = 10
// columnsCount.maxValue = 10
rowsCount.sideTapEnabled = true
columnsCount.sideTapEnabled = true
rowsCount.count = rows
columnsCount.count = columns
}
private fun refresh() {
rowsCount.count = rows
columnsCount.count = columns
grid.numColumns = columns
}
private fun moveToNextStep() {
if (step == 1) return
step++
steppers.visibility = View.GONE
labels.visibility = View.GONE
submit.visibility = View.GONE
subHeaderList.alpha = 1F
actions_layout.visibility = View.VISIBLE
directionSwitch.alpha = 1F
subHeader.text = "برای تغییر وضعیت هر یک از سلول ها روی آن کلیک کنید:"
header.text = String.format(
getString(R.string.cabinet_format),
currentCabinet.code
)
}
fun updateRows(value: Int) {
rows = value
adapter.rows = rows
adapter.notifyDataSetChanged()
}
fun updateGrid(value: Int) {
if (value > 6) {
val params = linearLayout_gridtableLayout.layoutParams
params.width = (getScreenWidth() / 6) * value + 10 * value
linearLayout_gridtableLayout.layoutParams = params
} else {
val params = linearLayout_gridtableLayout.layoutParams
params.width = getScreenWidth() - 10
linearLayout_gridtableLayout.layoutParams = params
}
}
fun updateColumns(value: Int) {
updateGrid(value)
columns = value
grid.numColumns = columns
adapter.columns = columns
adapter.notifyDataSetChanged()
}
private fun ModalBottomSheetDialogFragment.Builder.addOptions(cell: Cell, index: Int) {
if (cell.age <= -1 && cell.isHealthy) {
add(
OptionRequest(
(index.toString() + UNUSABLE_OPTION_ID).toInt(),
getString(R.string.unusable),
R.drawable.round_visibility_off_black_24
)
)
} else if (cell.age <= -1) {
add(
OptionRequest(
(index.toString() + USABLE_OPTION_ID).toInt(),
getString(R.string.usable),
R.drawable.round_visibility_black_24
)
)
}
if (cell.age > -1) {
add(
OptionRequest(
(index.toString() + USER_OPTION_ID).toInt(),
"مشخصات زائر",
R.drawable.baseline_account_circle_black_24
)
)
add(
OptionRequest(
(index.toString() + EMPTY_OPTION_ID).toInt(),
getString(R.string.empty),
R.drawable.round_move_to_inbox_black_24
)
)
}
if (cell.isHealthy) {
add(
OptionRequest(
(index.toString() + FAV_OPTION_ID).toInt(),
getString(R.string.favorite),
R.drawable.round_favorite_black_24
)
)
}
if (cell.age == 1) {
add(
OptionRequest(
(index.toString() + STORE_OPTION_ID).toInt(),
getString(R.string.store),
R.drawable.round_store_black_24
)
)
}
add(
OptionRequest(
(index.toString() + PRINT_OPTION_ID).toInt(),
getString(R.string.print),
R.drawable.baseline_print_black_24
)
)
}
private fun showPopup(index: Int) {
val cell = currentCabinet.getCell(index, rowDir, colDir)
val modalBuilder =
ModalBottomSheetDialogFragment.Builder()
modalBuilder.addOptions(cell, index)
modalBuilder.show(supportFragmentManager, "bottomsheet")
}
private fun showPilgrimProfileDialog(cell: Cell) {
cell.pilgrim ?: return
cell.pack ?: return;
MaterialDialog(this).show {
cornerRadius(20F)
listItems(
items = preparePilgrimData(cell.code, cell.pilgrim!!, cell.pack!!),
waitForPositiveButton = true
)
}
}
private fun preparePilgrimData(
code: String,
pilgrim: Pilgrim,
pack: Pack
): ArrayList<String> {
val data = ArrayList<String>()
data.add("شماره سلول : ${mapCabinetLabelWithCab(code)}")
if (pilgrim.name.isNotEmpty()) {
data.add("نام زائر : ${pilgrim.name}")
}
if (pilgrim.country.isNotEmpty()) {
data.add("کشور : ${pilgrim.country}")
}
if (pilgrim.phone.isNotEmpty()) {
data.add("شماره تلفن : ${pilgrim.phone}")
}
if (pack.bagCount != 0) {
data.add("تعداد ساک : ${pack.bagCount}")
}
if (pack.suitcaseCount != 0) {
data.add("تعداد چمدان : ${pack.suitcaseCount}")
}
if (pack.pramCount != 0) {
data.add("تعداد کالسکه : ${pack.pramCount}")
}
return data
}
override fun onModalOptionSelected(tag: String?, option: Option) {
val cellIndex = option.id / 10
val cell = currentCabinet.getCell(cellIndex, rowDir, colDir)
when (option.id % 10) {
USER_OPTION_ID -> showPilgrimProfileDialog(cell)
UNUSABLE_OPTION_ID -> changeStatus(cellIndex, false)
USABLE_OPTION_ID -> changeStatus(cellIndex, true)
EMPTY_OPTION_ID -> CoroutineScope(Dispatchers.Main).launch {
callWebservice {
getServices().free(
currentCabinet.getCell(
cellIndex,
rowDir, colDir
).code.toInt()
)
}?.run {
cell.age = -1
AppDatabase.getInstance().cabinetDao().insert(currentCabinet)
}
}
FAV_OPTION_ID -> CoroutineScope(Dispatchers.Main).launch {
callWebservice { getServices().favorite(cell.code.toInt()) }?.run {
getPrevFavorite()?.isFavorite = false
cell.isFavorite = true
AppDatabase.getInstance().cabinetDao().insert(currentCabinet)
}
}
STORE_OPTION_ID -> CoroutineScope(Dispatchers.Main).launch {
callWebservice { getServices().deliverToStore(cell.code.toInt()) }?.run {
cell.age = -1
AppDatabase.getInstance().cabinetDao().insert(currentCabinet)
}
}
PRINT_OPTION_ID -> CoroutineScope(Dispatchers.Main).launch {
callWebservice { getServices().print(cell.code.toInt()) }?.run {
toastSuccess("برچسب های قفسه فوق چاپ شد")
}
}
}
}
private fun getPrevFavorite(): Cell? {
for (row in currentCabinet.rows) {
for (cell in row.cells) {
if (cell.isFavorite) return cell
}
}
return null
}
private fun changeStatus(index: Int, isHealthy: Boolean) =
CoroutineScope(Dispatchers.Main).launch {
val cell = currentCabinet.getCell(index, rowDir, colDir)
callWebservice {
getServices().changeStatus(cell.code, isHealthy)
}?.run {
cell.isHealthy = isHealthy
AppDatabase.getInstance().cabinetDao().insert(currentCabinet)
}
}
}
<file_sep>package ir.nilva.abotorab.model
import com.google.gson.JsonObject
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import ir.nilva.abotorab.webservices.BaseResponse
class ConfigResponse (
@Expose @SerializedName("token") val token : String,
@Expose @SerializedName("row_code_mapping") val row_code_mapping : JsonObject
) : BaseResponse()<file_sep>package ir.nilva.abotorab.view.page.base
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import com.afollestad.materialdialogs.MaterialDialog
import io.github.inflationx.calligraphy3.CalligraphyConfig
import io.github.inflationx.calligraphy3.CalligraphyInterceptor
import io.github.inflationx.viewpump.ViewPump
import io.github.inflationx.viewpump.ViewPumpContextWrapper
import ir.nilva.abotorab.R
import ir.nilva.abotorab.helper.isWifiConnected
/**
* Created by mahdihs76 on 9/10/18.
*/
@SuppressLint("Registered")
open class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initCalligraphy()
// if (isWifiConnected().not()) {
// MaterialDialog(this).show {
// title( text = "وای فای موبایل شما خاموش است")
// message(text = "لطفا وای فای خود را روشن کرده و سپس ادامه دهید")
// }
// }
}
private fun initCalligraphy() =
ViewPump.init(
ViewPump.builder()
.addInterceptor(
CalligraphyInterceptor(
CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/yekan.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
)
)
.build()
)
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase!!))
}
fun setStatusBarColor(color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = color
}
}
}<file_sep>package ir.nilva.abotorab.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import ir.nilva.abotorab.ApplicationContext
import ir.nilva.abotorab.db.dao.CabinetDao
import ir.nilva.abotorab.db.dao.DeliveryDao
import ir.nilva.abotorab.db.dao.OfflineDeliveryDao
import ir.nilva.abotorab.db.model.DeliveryEntity
import ir.nilva.abotorab.db.model.OfflineDeliveryEntity
import ir.nilva.abotorab.model.CabinetResponse
/**
* The Room database for this app
*/
@Database(entities = [DeliveryEntity::class, CabinetResponse::class, OfflineDeliveryEntity::class], version = 2)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun deliveryDao(): DeliveryDao
abstract fun cabinetDao(): CabinetDao
abstract fun offlineDeliveryDao(): OfflineDeliveryDao
companion object {
@Volatile private var instance: AppDatabase? = null
fun getInstance(): AppDatabase {
return instance ?: synchronized(this) {
instance ?: buildDatabase(ApplicationContext.context).also { instance = it }
}
}
private fun buildDatabase(context: Context): AppDatabase {
return Room.databaseBuilder(context, AppDatabase::class.java, "app")
// .addCallback(object : RoomDatabase.Callback() {
// override fun onCreate(db: SupportSQLiteDatabase) {
// super.onCreate(db)
// val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
// WorkManager.getInstance(context).enqueue(request)
// }
// })
.build()
}
}
}<file_sep>package ir.nilva.abotorab.helper
import android.content.Context
import android.view.ViewGroup
import android.widget.LinearLayout
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import ir.nilva.abotorab.R
import ir.nilva.abotorab.model.DeliveryResponse
import kotlinx.android.synthetic.main.item_pilgirim.view.*
import org.jetbrains.anko.layoutInflater
fun Context.showResult(actionLabel: String, list: List<DeliveryResponse>?, click: (hashId: String) -> Unit) {
if (list == null || list.isEmpty()) {
toastWarning("هیچ موردی یافت نشد")
return
}
val view = LinearLayout(this).apply {
layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
orientation = LinearLayout.VERTICAL
}
val dialog = MaterialDialog(this)
list.forEach { item ->
view.addView(layoutInflater.inflate(R.layout.item_pilgirim, null).apply {
var cabinetCode = ""
val packs = item.pack
if (packs.isNotEmpty()) cabinetCode = packs[0].cell
title.text = item.pilgrim.country + " از " + item.pilgrim.name
phoneNumber.text = "شماره تلفن:" + item.pilgrim.phone
cabinet.text = " شماره قفسه:${mapCabinetLabelWithCab(cabinetCode)}"
subTitle.text = "زمان تحویل:" + item.enteredAt
button.text = actionLabel
button.setOnClickListener {
dialog.dismiss()
click(item.hashId)
}
})
}
dialog.customView(view = view, scrollable = true).show()
}<file_sep>package ir.nilva.abotorab.helper
var BLINK_ID = "<KEY>
<file_sep>package ir.nilva.abotorab.view.page.operation
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.microblink.activity.DocumentScanActivity
import com.microblink.entities.recognizers.Recognizer
import com.microblink.entities.recognizers.RecognizerBundle
import com.microblink.entities.recognizers.blinkid.passport.PassportRecognizer
import com.microblink.uisettings.ActivityRunner
import com.microblink.uisettings.DocumentUISettings
import ir.nilva.abotorab.ApplicationContext
import ir.nilva.abotorab.R
import ir.nilva.abotorab.db.AppDatabase
import ir.nilva.abotorab.db.model.DeliveryEntity
import ir.nilva.abotorab.db.model.OfflineDeliveryEntity
import ir.nilva.abotorab.helper.*
import ir.nilva.abotorab.view.page.base.BaseActivity
import ir.nilva.abotorab.webservices.callWebservice
import ir.nilva.abotorab.webservices.callWebserviceWithFailure
import ir.nilva.abotorab.webservices.getServices
import kotlinx.android.synthetic.main.activity_give.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.Exception
class GiveSearchActivity : BaseActivity() {
private lateinit var recognizer: PassportRecognizer
private lateinit var recognizerBundle: RecognizerBundle
private var _blinkIdEnabled = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_give)
try {
recognizer = PassportRecognizer()
recognizerBundle = RecognizerBundle(recognizer)
} catch (e: Exception){
_blinkIdEnabled = false
}
search.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
search.visibility = View.INVISIBLE
spinKit.visibility = View.VISIBLE
callWebservice {
getServices().deliveryList(
firstName.text.toString(),
lastName.text.toString(),
country.text.toString(),
phone.text.toString(),
passportId.text.toString(),
true
)
}?.run {
showResult("تحویل", this) { hashId ->
MaterialDialog(this@GiveSearchActivity).show {
title(text = "در صورتی که زائر رسید خود را تحویل نداده است، فرم تعهدنامه کتبی به همراه امضا از ایشان دریافت کنید")
positiveButton(text = "انجام شد") {
callGiveWS(hashId)
}
negativeButton(text = "بعدا") {
}
}
}
}
search.visibility = View.VISIBLE
spinKit.visibility = View.INVISIBLE
}
}
country.threshold = 1
country.setAdapter(CountryAdapter(this, R.layout.item_country, ArrayList(getCountries())))
fab.setOnClickListener{
if(_blinkIdEnabled) {
startScanning()
} else {
toastError("اعتبار ماهانه استفاده از سرویس اسکن پاسپورت به اتمام رسیده است. با پشتیبانی سیستم تماس بگیرید")
}
}
}
private fun startScanning() {
val settings = DocumentUISettings(recognizerBundle)
ActivityRunner.startActivityForResult(this, 100, settings)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100) {
if (resultCode == DocumentScanActivity.RESULT_OK && data != null) {
recognizerBundle.loadFromIntent(data)
val result = recognizer.result
if (result.resultState == Recognizer.Result.State.Valid) {
val passport = result.mrzResult
firstName.setText(passport.secondaryId)
lastName.setText(passport.primaryId)
passportId.setText(passport.documentNumber)
country.setText(getCountryName(passport.nationality))
}
}
}
}
}
fun Context.callGiveWS(hashId: String, cellCode: String = "") =
CoroutineScope(Dispatchers.Main).launch {
callWebserviceWithFailure({ getServices().give(hashId) }) { response, code ->
if (code != 400) {
toastSuccess("پس از برقراری ارتباط با سرور گزارش میشود")
cacheHashId(hashId)
} else {
toastError(response)
}
}?.run {
toastSuccess("محموله با موفقیت تحویل داده شد")
AppDatabase.getInstance().deliveryDao().insertAndDeleteOther(
DeliveryEntity(
nickname = pilgrim.name,
country = pilgrim.country,
cellCode = this.cellCode,
phone = pilgrim.phone,
exitedAt = exitAt,
hashId = hashId
)
)
}
}
private fun cacheHashId(hashId: String) = CoroutineScope(Dispatchers.IO).launch {
AppDatabase.getInstance().offlineDeliveryDao().insert(OfflineDeliveryEntity(hashId))
}
<file_sep>package ir.nilva.abotorab.webservices
import ir.nilva.abotorab.model.*
import retrofit2.Response
import retrofit2.http.*
interface WebserviceUrls {
@FormUrlEncoded
@POST("signin/")
suspend fun login(
@Field("username") username: String,
@Field("password") password: String,
@Field("depository_code") depositoryCode: String
): Response<SigninResponse>
@FormUrlEncoded
@POST("reception/take/")
suspend fun take(
@Field("first_name") firstName: String,
@Field("last_name") lastName: String,
@Field("phone") phoneNumber: String,
@Field("country") country: String,
@Field("passport_id") passportId: String,
@Field("bag_count") bagCount: Int,
@Field("suitcase_count") suitcaseCount: Int,
@Field("pram_count") pramCount: Int
): Response<TakeResponse>
@FormUrlEncoded
@POST("reception/give/")
suspend fun give(
@Field("hash_id") hashId: String
): Response<GiveResponse>
@FormUrlEncoded
@POST("reception/give_list/")
suspend fun give(
@Field("hash_ids") hashId: List<String>
): Response<List<GiveResponse>>
@FormUrlEncoded
@POST("cabinet/")
suspend fun cabinet(
@Field("code") code: String,
@Field("num_of_rows") rows: Int,
@Field("num_of_cols") columns: Int,
@Field("size") size: Int,
@Field("first_row_size") firstRowSize: Int
): Response<CabinetResponse>
@FormUrlEncoded
@POST("cell/change_status/")
suspend fun changeStatus(
@Field("code") code: String,
@Field("is_healthy") isHealthy: Boolean
): Response<ChangeStatusResponse>
@GET("report/")
suspend fun report(): Response<ReportResponse>
@GET("config/")
suspend fun config(): Response<ConfigResponse>
@GET("report/start/")
suspend fun startReport(): Response<StartReportResponse>
@GET("cabinet/")
suspend fun cabinetList(): Response<List<CabinetResponse>>
@POST("cabinet/{code}/print/")
suspend fun printCabinet(@Path("code") code: String): Response<BaseResponse>
@FormUrlEncoded
@POST("cabinet/{code}/extend/")
suspend fun extendCabinet(@Path("code") code: String,
@Field("num_of_cols") newColumnsCount: Int,
@Field("num_of_rows") newRowsCount: Int): Response<CabinetResponse>
@DELETE("cabinet/{code}/")
suspend fun deleteCabinet(@Path("code") code: String): Response<BaseResponse>
@GET("delivery/")
suspend fun deliveryList(
@Query("first_name") firstName: String,
@Query("last_name") lastName: String,
@Query("country") country: String,
@Query("phone") phone: String,
@Query("passport_id") passportId: String,
@Query("in_house") inHouse: Boolean
): Response<List<DeliveryResponse>>
@GET("delivery/")
suspend fun deliveryListWithLimit(
@Query("first_name") firstName: String,
@Query("last_name") lastName: String,
@Query("country") country: String,
@Query("phone") phone: String,
@Query("passport_id") passportId: String,
@Query("in_house") inHouse: Boolean,
@Query("limit") limit: Int
): Response<List<DeliveryResponse>>
@POST("delivery/{hash_id}/revert_exit/")
suspend fun undoDelivery(@Path("hash_id") hashId: String): Response<BaseResponse>
@POST("delivery/{hash_id}/reprint/")
suspend fun reprint(@Path("hash_id") hashId: String): Response<BaseResponse>
@POST("cell/{id}/deliver_to_store/")
suspend fun deliverToStore(@Path("id") id: Int): Response<BaseResponse>
@POST("cell/{id}/favorite/")
suspend fun favorite(@Path("id") id: Int): Response<BaseResponse>
@POST("cell/{id}/print/")
suspend fun print(@Path("id") id: Int): Response<BaseResponse>
@POST("cell/{id}/free/")
suspend fun free(@Path("id") id: Int): Response<BaseResponse>
@GET("admin/")
suspend fun test(): Response<Void>
@GET("administration/export/")
suspend fun export(): Response<ExportResponse>
@GET("administration/export_store/")
suspend fun exportStore(): Response<ExportResponse>
}
<file_sep>package ir.nilva.abotorab.model
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class ExportResponse(
@SerializedName("url") val url: String
) : Serializable<file_sep>package ir.nilva.abotorab.model
import ir.nilva.abotorab.webservices.BaseResponse
class ChangeStatusResponse : BaseResponse()<file_sep>package ir.nilva.abotorab.model
import com.google.gson.annotations.SerializedName
data class StartReportResponse(
@SerializedName("total_cabinets") val totalCabinets: Int,
@SerializedName("total_cells") val totalCells: Int,
@SerializedName("empty_cells") val emptyCells: Int,
@SerializedName("total_deliveries") val totalDeliveries: Int
)<file_sep>package ir.nilva.abotorab.model
import com.google.gson.annotations.SerializedName
import ir.nilva.abotorab.webservices.BaseResponse
class SigninResponse(@SerializedName("token") val token: String, @SerializedName("depository") val depository: String) :
BaseResponse()<file_sep>package ir.nilva.abotorab.helper
import android.app.Activity
import android.util.DisplayMetrics
fun Activity.getScreenWidth() : Int{
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
return displayMetrics.widthPixels
}<file_sep>package ir.nilva.abotorab.model
import com.google.gson.annotations.SerializedName
data class DeliveryResponse(
@SerializedName("pilgrim") val pilgrim: Pilgrim,
@SerializedName("taker") val taker: Int,
@SerializedName("giver") val giver: Int,
@SerializedName("hash_id") val hashId: String,
@SerializedName("entered_at") val enteredAt: String,
@SerializedName("exited_at") val exitAt: String,
@SerializedName("exit_type") val exitType: Int,
@SerializedName("pack") val pack: ArrayList<Pack>
)
data class Pilgrim(
@SerializedName("phone") val phone: String,
@SerializedName("country") val country: String,
@SerializedName("name") val name: String
)
data class Pack(
@SerializedName("id") val id: Int,
@SerializedName("bag_count") val bagCount: Int,
@SerializedName("suitcase_count") val suitcaseCount: Int,
@SerializedName("pram_count") val pramCount: Int,
@SerializedName("delivery") val delivery: Int,
@SerializedName("cell") val cell: String
)
data class Failure(
@SerializedName("non_field_errors") val errors: List<String>
)
<file_sep>package ir.nilva.abotorab.view.page.main
import android.Manifest
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import androidx.work.*
import com.afollestad.materialdialogs.MaterialDialog
import com.microblink.MicroblinkSDK
import com.ramotion.circlemenu.CircleMenuView
import ir.nilva.abotorab.ApplicationContext
import ir.nilva.abotorab.R
import ir.nilva.abotorab.db.AppDatabase
import ir.nilva.abotorab.helper.*
import ir.nilva.abotorab.view.page.base.BaseActivity
import ir.nilva.abotorab.webservices.callWebservice
import ir.nilva.abotorab.webservices.getServices
import ir.nilva.abotorab.work.DeliveryWorker
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jetbrains.anko.toast
import permissions.dispatcher.*
import java.lang.Exception
import java.util.concurrent.TimeUnit
@RuntimePermissions
class MainActivity : BaseActivity() {
@NeedsPermission(Manifest.permission.CAMERA)
fun openCamera() {
gotoBarcodePage(true)
}
@OnShowRationale(Manifest.permission.CAMERA)
fun showDialogBeforeCameraPermission(request: PermissionRequest) {
MaterialDialog(this).show {
message(R.string.camera_permission_message)
positiveButton(R.string.permisson_ok) { request.proceed() }
negativeButton(R.string.permission_deny) { request.cancel() }
}
}
@OnPermissionDenied(Manifest.permission.CAMERA)
fun onCameraDenied() {
toast(getString(R.string.no_camera_permission))
}
@OnNeverAskAgain(Manifest.permission.CAMERA)
fun onCameraNeverAskAgain() {
toast(getString(R.string.no_camera_permission))
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
onRequestPermissionsResult(requestCode, grantResults)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CoroutineScope(Dispatchers.Main).launch {
callWebservice {
getServices().config()
}?.run {
val lastBlinkId = defaultCache()["BLINK_ID"] ?: ""
if (token.isNotEmpty()) {
if (lastBlinkId != token) {
try {
setBlinkIdLicenceKey(token)
} catch (e: Exception) {
toastError("اعتبار ماهانه استفاده از سرویس اسکن پاسپورت به اتمام رسیده است. با پشتیبانی سیستم تماس بگیرید")
}
defaultCache()["BLINK_ID"] = token
}
}
defaultCache()["ROW_MAPPING"] = row_code_mapping.toString()
}
}
initCircularMenu()
logout.setOnClickListener { logout() }
sendCachedHashes2Server()
fillHeader()
val depositoryName = defaultCache()["depository"] ?: "امانت داری";
labelTextView.text = depositoryName
}
private fun fillHeader() {
CoroutineScope(Dispatchers.Main).launch {
callWebservice {
getServices().startReport()
}?.run {
cabinetCount.text = totalCabinets.toString()
emptyCabinets.text = emptyCells.toString()
registerCount.text = totalDeliveries.toString()
}
}
}
private fun sendCachedHashes2Server() {
CoroutineScope(Dispatchers.Main).launch {
val offlineDeliveries =
AppDatabase.getInstance().offlineDeliveryDao().getAll()
if (!offlineDeliveries.isNullOrEmpty()) {
WorkManager.getInstance(this@MainActivity).enqueue(
PeriodicWorkRequestBuilder<DeliveryWorker>(30, TimeUnit.MINUTES)
.build()
)
}
}
}
private fun initCircularMenu() {
circularLayout.eventListener = object : CircleMenuView.EventListener() {
override fun onButtonClickAnimationEnd(view: CircleMenuView, buttonIndex: Int) {
super.onButtonClickAnimationEnd(view, buttonIndex)
getMenuItem(buttonIndex)?.action(this@MainActivity)
}
}
openMenu()
}
private fun openMenu() {
Handler().postDelayed({
circularLayout.open(true)
}, 500)
}
override fun onResume() {
super.onResume()
openMenu()
}
}
fun MenuItem.action(activity: MainActivity) {
when (this) {
MenuItem.CABINET_GIVE -> activity.openCameraWithPermissionCheck()
MenuItem.CABINET_TAKE -> activity.gotoTakePage()
MenuItem.CABINET_INIT -> activity.gotoCabinetListPage()
MenuItem.CABINET_REPORT -> activity.gotoReportPage()
}
}
fun Activity.logout() {
MaterialDialog(this).show {
title(text = "آیا برای خروج اطمینان دارید؟")
positiveButton(text = "بله") {
CoroutineScope(Dispatchers.Main).launch {
AppDatabase.getInstance().deliveryDao().clear()
AppDatabase.getInstance().cabinetDao().clear()
AppDatabase.getInstance().offlineDeliveryDao().clear()
defaultCache()["token"] = null
gotoLoginPage()
}
}
negativeButton(text = "خیر")
}
}
<file_sep>package ir.nilva.abotorab
import androidx.multidex.MultiDexApplication
import com.microblink.MicroblinkSDK
import es.dmoral.toasty.Toasty
import ir.nilva.abotorab.db.AppDatabase
import ir.nilva.abotorab.helper.defaultCache
import ir.nilva.abotorab.helper.get
import ir.nilva.abotorab.helper.getAppTypeface
/**
*
* Created by mahdihs76 on 9/11/18.
*/
class MyApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
ApplicationContext.initialize(this)
AppDatabase.getInstance()
Toasty.Config.getInstance()
.setToastTypeface(getAppTypeface())
.setTextSize(14)
.apply()
}
}<file_sep>package ir.nilva.abotorab.view.page.operation
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.microblink.activity.DocumentScanActivity
import com.microblink.entities.recognizers.Recognizer
import com.microblink.entities.recognizers.RecognizerBundle
import com.microblink.entities.recognizers.blinkid.passport.PassportRecognizer
import com.microblink.uisettings.ActivityRunner
import com.microblink.uisettings.DocumentUISettings
import ir.nilva.abotorab.R
import ir.nilva.abotorab.helper.*
import ir.nilva.abotorab.view.page.base.BaseActivity
import ir.nilva.abotorab.webservices.callWebservice
import ir.nilva.abotorab.webservices.callWebserviceWithFailure
import ir.nilva.abotorab.webservices.getServices
import kotlinx.android.synthetic.main.activity_take.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class TakeActivity : BaseActivity() {
private lateinit var recognizer: PassportRecognizer
private lateinit var recognizerBundle: RecognizerBundle
private var _blinkIdEnabled = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_take)
val depoName = defaultCache()["depository"] ?: "امانت داری"
depositoryName.setText(depoName)
bagCount.minValue = 0
bagCount.sideTapEnabled = true
suitcaseCount.minValue = 0
suitcaseCount.sideTapEnabled = true
pramCount.minValue = 0
pramCount.sideTapEnabled = true
fab.setOnClickListener {
if(_blinkIdEnabled) {
startScanning()
} else {
toastError("اعتبار ماهانه استفاده از سرویس اسکن پاسپورت به اتمام رسیده است. با پشتیبانی سیستم تماس بگیرید")
}
}
bottom_app_bar.setNavigationOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
callWebservice {
getServices().deliveryListWithLimit(
firstName.text.toString(),
lastName.text.toString(),
country.text.toString(),
phone.text.toString(),
passportId.text.toString(),
true,
5
)
}?.run {
showResult("چاپ", this) {
CoroutineScope(Dispatchers.Main).launch {
callWebservice {
getServices().reprint(it)
}?.run {
toastSuccess("برگه تحویل با موفقیت چاپ شد")
}
}
}
}
}
}
try {
recognizer = PassportRecognizer()
recognizerBundle = RecognizerBundle(recognizer)
} catch (e: Exception) {
_blinkIdEnabled = false
// finish()
}
submit.setOnClickListener {
if(phone.text.isNullOrEmpty()) {
toastError("شماره تماس الزامی است")
return@setOnClickListener
}
CoroutineScope(Dispatchers.Main).launch {
showLoading()
callWebserviceWithFailure({
getServices().take(
firstName.text.toString(),
lastName.text.toString(), phone.text.toString(),
country.text.toString(), passportId.text.toString(),
bagCount.count, suitcaseCount.count, pramCount.count
)
}) { response, code ->
if (response == "[\"فضای خالی وجود ندارد\"]") {
tryToFindEmptyCell()
} else {
toastError(response)
}
}?.run {
resetUi()
toastSuccess("محموله با موفقیت تحویل گرفته شد")
}
hideLoading()
}
}
country.threshold = 1
country.setAdapter(CountryAdapter(this, R.layout.item_country, ArrayList(getCountries())))
}
private var tryToFindDialog: Dialog? = null
var findEmptyCellEnabled = false
private fun tryToFindEmptyCell() {
findEmptyCellEnabled = true
tryToFindDialog = MaterialDialog(this).show {
customView(R.layout.try_to_find_empty_cell_dialog)
}.cornerRadius(20f).negativeButton(text = "انصراف") {
findEmptyCellEnabled = false
}
tryToFindDialog?.show()
callApiAfter10Seconds()
}
private fun callApiAfter10Seconds() {
Handler().postDelayed({
CoroutineScope(Dispatchers.Main).launch {
callWebserviceWithFailure({
getServices().take(
firstName.text.toString(),
lastName.text.toString(), phone.text.toString(),
country.text.toString(), passportId.text.toString(),
bagCount.count, suitcaseCount.count, pramCount.count
)
}) { response, code ->
if (response == "[\"فضای خالی وجود ندارد\"]") {
if (findEmptyCellEnabled) callApiAfter10Seconds()
} else {
findEmptyCellEnabled = false
tryToFindDialog?.dismiss()
toastError("درخواست شما با خطا روبهرو شد. مجدد تلاش کنید")
}
}?.run {
findEmptyCellEnabled = false
tryToFindDialog?.dismiss()
resetUi()
toastSuccess("محموله با موفقیت تحویل گرفته شد")
}
}
}, 10000)
}
private fun startScanning() {
val settings = DocumentUISettings(recognizerBundle)
ActivityRunner.startActivityForResult(this, 100, settings)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100) {
if (resultCode == DocumentScanActivity.RESULT_OK && data != null) {
recognizerBundle.loadFromIntent(data)
val result = recognizer.result
if (result.resultState == Recognizer.Result.State.Valid) {
val passport = result.mrzResult
firstName.setText(passport.secondaryId)
lastName.setText(passport.primaryId)
passportId.setText(passport.documentNumber)
country.setText(getCountryName(passport.nationality))
}
}
}
}
private fun resetUi() {
firstName.setText("")
lastName.setText("")
phone.setText("")
country.setText("")
passportId.setText("")
bagCount.count = 0
suitcaseCount.count = 0
pramCount.count = 0
firstName.requestFocus()
}
private fun showLoading() {
spinKit.visibility = View.VISIBLE
submit.visibility = View.INVISIBLE
}
private fun hideLoading() {
spinKit.visibility = View.GONE
submit.visibility = View.VISIBLE
}
}
<file_sep>package ir.nilva.abotorab.helper
import android.content.Context
import android.graphics.Typeface
fun Context.getAppTypeface() = Typeface.createFromAsset(this.assets, "fonts/yekan.ttf")<file_sep>package ir.nilva.abotorab.helper
import com.google.gson.annotations.SerializedName
data class CountryModel(@SerializedName("name") val name: String,
@SerializedName("en_name") val enName: String,
@SerializedName("native_name") val nativeName: String,
@SerializedName("capital") val capital: String,
@SerializedName("en_capital") val enCapital: String,
@SerializedName("alpha_2") val alpha2: String,
@SerializedName("alpha_3") val alpha3: String,
@SerializedName("phone_code") val phoneCode: String)
class CountryList(internal var countries: List<CountryModel>)
<file_sep>package ir.nilva.abotorab.helper
import android.content.Context
import android.widget.Toast
import es.dmoral.toasty.Toasty
fun Context.toastError(text:String) = Toasty.error(this, text, Toast.LENGTH_LONG, true).show()
fun Context.toastWarning(text:String) = Toasty.warning(this, text, Toast.LENGTH_LONG, true).show()
fun Context.toastSuccess(text:String) = Toasty.success(this, text, Toast.LENGTH_LONG, true).show()
<file_sep>package ir.nilva.abotorab.db.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import ir.nilva.abotorab.model.CabinetResponse
@Dao
interface CabinetDao {
@Query("SELECT * FROM cabinetresponse")
fun getAll(): LiveData<List<CabinetResponse>>
@Query("SELECT * FROM cabinetresponse")
suspend fun getCabinets(): List<CabinetResponse>
@Query("SELECT * FROM cabinetresponse WHERE code=:code")
fun getLiveData(code: String): LiveData<CabinetResponse>
@Query("SELECT * FROM cabinetresponse WHERE code=:code")
suspend fun get(code: String): CabinetResponse
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(items: List<CabinetResponse>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(item: CabinetResponse)
@Query("DELETE FROM cabinetresponse WHERE code=:code")
suspend fun delete(code: String)
@Query("DELETE FROM cabinetresponse")
suspend fun clear()
@Update
suspend fun update(item: CabinetResponse)
}<file_sep>package ir.nilva.abotorab.view.page.cabinet
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import ir.nilva.abotorab.R
import ir.nilva.abotorab.db.AppDatabase
import ir.nilva.abotorab.helper.gotoCabinetPage
import ir.nilva.abotorab.helper.toastError
import ir.nilva.abotorab.helper.toastSuccess
import ir.nilva.abotorab.view.page.base.BaseActivity
import ir.nilva.abotorab.view.widget.MarginItemDecoration
import ir.nilva.abotorab.webservices.callWebservice
import ir.nilva.abotorab.webservices.callWebserviceWithFailure
import ir.nilva.abotorab.webservices.getServices
import kotlinx.android.synthetic.main.activity_cabinet_list.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject
class CabinetListActivity : BaseActivity(), CabinetListAdapter.OnClickCabinetListener {
private lateinit var adapter: CabinetListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cabinet_list)
adapter = CabinetListAdapter(this)
recyclerView.adapter = adapter
recyclerView.addItemDecoration(MarginItemDecoration(20))
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy > 0)
fab.hide()
else if (dy < 0)
fab.show()
}
})
val itemTouchHelper = ItemTouchHelper(SwipeToDeleteCallback(adapter))
itemTouchHelper.attachToRecyclerView(recyclerView)
fab.setOnClickListener { gotoCabinetPage() }
AppDatabase.getInstance().cabinetDao().getAll().observe(this, Observer {
if (it.isNotEmpty()) {
adapter.submitList(it)
}
})
getCabinetList()
}
private fun getCabinetList() {
CoroutineScope(Dispatchers.IO).launch {
callWebservice { getServices().cabinetList() }?.run {
AppDatabase.getInstance().cabinetDao().clear()
AppDatabase.getInstance().cabinetDao().insert(this)
}
}
}
override fun cabinetClicked(code: String) = gotoCabinetPage(code)
override fun printCabinet(view: View, code: String) {
CoroutineScope(Dispatchers.Main).launch {
view.background = ContextCompat.getDrawable(
this@CabinetListActivity,
R.drawable.disable_bg
)
view.isEnabled = false
callWebservice { getServices().printCabinet(code) }?.run {
toastSuccess("برچسب های قفسه فوق چاپ شد")
}
view.background = ContextCompat.getDrawable(
this@CabinetListActivity,
R.drawable.print_bg
)
view.isEnabled = true
}
}
override fun deleteCabinet(code: String, callback: () -> Unit) {
CoroutineScope(Dispatchers.Main).launch {
val response = getServices().deleteCabinet(code)
if (response.isSuccessful) {
AppDatabase.getInstance().cabinetDao().delete(code)
toastSuccess("قفسه مورد نظر با موفقیت حذف شد")
} else {
val jsonErr = response.errorBody()?.string()
val errorMessage =
JSONObject(jsonErr!!).getJSONArray("non_field_errors").get(0)?.toString()
?: "مشکلی پیش آمده است"
if (response.code() == 400) {
toastError(errorMessage)
}
}
callback()
}
}
}
<file_sep>package ir.nilva.abotorab.webservices
import ir.nilva.abotorab.ApplicationContext
import org.jetbrains.anko.toast
import java.net.UnknownHostException
interface Result<T> {
fun onSuccess(response: T?)
fun onFailed(throwable: Throwable, errorBody: String) {
val context = ApplicationContext.context
when (throwable) {
is UnknownHostException -> context.toast(errorBody)
is WebServiceError -> {
context.toast("لطفا اتصال خود را بررسی کنید")
}
}
}
}
<file_sep>package ir.nilva.abotorab.work
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import ir.nilva.abotorab.db.AppDatabase
import ir.nilva.abotorab.webservices.callWebserviceWithFailure
import ir.nilva.abotorab.webservices.getServices
import kotlinx.coroutines.coroutineScope
class DeliveryWorker(
val context: Context,
workParams: WorkerParameters
) : CoroutineWorker(context, workParams) {
override suspend fun doWork(): Result = coroutineScope {
val offlineDeliveries = AppDatabase.getInstance().offlineDeliveryDao().getAll()
if (offlineDeliveries.isEmpty()) {
Result.success()
} else {
context.callWebserviceWithFailure({ getServices().give(offlineDeliveries.map { it.hashId }) }) { response, code ->
Result.retry()
}?.run {
this.forEach {
AppDatabase.getInstance().offlineDeliveryDao().delete(it.hashId)
}
}
Result.success()
}
}
}<file_sep>package ir.nilva.abotorab.helper
import android.content.Context
import android.net.wifi.SupplicantState
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.util.Log
import androidx.core.content.ContextCompat.getSystemService
import java.util.*
fun Context.connectToNetworkWPA(text: String): Boolean {
return connectToNetworkWPA("amanatdari$text", "110+salavat")
}
fun Context.connectToNetworkWPA(networkSSID: String, password: String): Boolean {
return try {
val conf = WifiConfiguration()
conf.SSID =
"\"" + networkSSID + "\"" // Please note the quotes. String should contain SSID in quotes
conf.preSharedKey = "\"" + password + "\""
conf.status = WifiConfiguration.Status.ENABLED
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP)
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP)
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)
conf.hiddenSSID = true; // Put this line to hidden SSID
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP)
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP)
Log.d("connecting", conf.SSID + " " + conf.preSharedKey)
val wifiManager =
applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
var newId = wifiManager.addNetwork(conf)
if (newId == -1) {
newId = wifiManager.getExistingNetworkId(conf.SSID)
}
Log.d("after connecting", conf.SSID + " " + conf.preSharedKey)
wifiManager.disconnect()
wifiManager.enableNetwork(newId, true)
wifiManager.reconnect()
true
} catch (ex: Exception) {
println(Arrays.toString(ex.stackTrace))
false
}
}
private fun WifiManager.getExistingNetworkId(SSID: String): Int {
val configuredNetworks: List<WifiConfiguration> = configuredNetworks
if (configuredNetworks != null) {
for (existingConfig in configuredNetworks) {
if (SSID.equals(existingConfig.SSID, ignoreCase = true)) {
return existingConfig.networkId
}
}
}
return -1
}
fun Context.getConnectedSSID(): String? {
val wifiManager =
applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val wifiInfo: WifiInfo = wifiManager.connectionInfo
if (wifiInfo.supplicantState == SupplicantState.COMPLETED) {
return wifiInfo.ssid
}
return null
}
fun Context.isConnectedWifiValid(): Boolean {
val ssid = getConnectedSSID() ?: return true
val server : String = defaultCache()["depository_code"] ?: return false
return ssid == server
}<file_sep>package ir.nilva.abotorab.db.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import ir.nilva.abotorab.db.model.DeliveryEntity
@Dao
interface DeliveryDao {
@Query("SELECT * FROM delivery ORDER BY id DESC")
fun getAll(): LiveData<List<DeliveryEntity>>
@Query("SELECT * FROM delivery")
suspend fun getDeliveries(): List<DeliveryEntity>
@Insert
suspend fun insert(items: List<DeliveryEntity>)
@Delete
suspend fun delete(item: DeliveryEntity)
@Query("DELETE FROM delivery WHERE hashId NOT IN (SELECT hashId FROM delivery ORDER BY id DESC LIMIT 10)")
suspend fun deleteOther()
@Transaction
suspend fun insertAndDeleteOther(item: DeliveryEntity) {
insert(listOf(item))
deleteOther()
}
@Query("DELETE FROM delivery")
suspend fun clear()
}<file_sep>package ir.nilva.abotorab.view.page.cabinet
import android.graphics.Color
import android.os.Bundle
import android.util.DisplayMetrics
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.Observer
import ir.nilva.abotorab.R
import ir.nilva.abotorab.db.AppDatabase
import ir.nilva.abotorab.helper.getImageResource
import ir.nilva.abotorab.model.Row
import ir.nilva.abotorab.view.page.base.BaseActivity
import kotlinx.android.synthetic.main.activity_full_screen.*
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.margin
import java.util.*
const val DEFAULT_CABINET_MARGIN = 10
class FullScreenActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
setStatusBarColor(Color.WHITE)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_full_screen)
val code = intent?.extras?.getString("code")
AppDatabase.getInstance()
.cabinetDao().getLiveData(code!!).observe(this, Observer {
drawCabinet(it.rows)
})
}
private fun drawCabinet(rows: ArrayList<Row>) {
val rowsCount = rows.size
val columnsCount = rows[0].cells.size
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val screenHeight = displayMetrics.heightPixels
val screenWidth = displayMetrics.widthPixels
rows.forEach {
val eachWidth = screenWidth / columnsCount
val eachHeight = screenHeight / rowsCount
val layout = LinearLayout(this).apply {
layoutParams = LinearLayout.LayoutParams(
screenWidth,
eachHeight - 2 * DEFAULT_CABINET_MARGIN
)
}
it.cells.forEach {
val imageView = ImageView(this).apply {
imageResource = it.getImageResource(false)
layoutParams = LinearLayout.LayoutParams(
eachWidth - 2 * DEFAULT_CABINET_MARGIN,
eachHeight - 2 * DEFAULT_CABINET_MARGIN
).apply {
margin = DEFAULT_CABINET_MARGIN
}
}
layout.addView(imageView)
}
rootLayout.addView(layout)
}
}
}
<file_sep>package ir.nilva.abotorab.helper
import android.content.Context
import android.net.ConnectivityManager
import ir.nilva.abotorab.ApplicationContext
import org.json.JSONObject
fun dp(dps: Int): Int {
val scale = ApplicationContext.context.resources.displayMetrics.density
return (dps * scale + 0.5f).toInt()
}
fun mapCabinetLabel(code: String): String? {
val mapping = defaultCache()["ROW_MAPPING"] ?: ""
val rowCode = code.substring(2, 3).toInt()
val columnCode = code.substring(3).toInt()
return if(mapping.isNotEmpty()){
val mappedRow = JSONObject(mapping).get(rowCode.toString())
FormatHelper.toPersianNumber("$columnCode$mappedRow")
} else {
FormatHelper.toPersianNumber("$rowCode$columnCode")
}
}
fun mapCabinetLabelWithCab(code: String): String? {
if(code.isEmpty()) return ""
val mapping = defaultCache()["ROW_MAPPING"] ?: ""
val cabCode = code.substring(0, 2).toInt()
val rowCode = code.substring(2, 3).toInt()
val columnCode = code.substring(3).toInt()
return if(mapping.isNotEmpty()){
val mappedRow = JSONObject(mapping).get(rowCode.toString())
FormatHelper.toPersianNumber("$columnCode$mappedRow$cabCode")
} else {
FormatHelper.toPersianNumber("$cabCode$rowCode$columnCode")
}
}
fun Context.isWifiConnected(): Boolean {
val cm =
getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val netInfo = cm.activeNetworkInfo
return if (netInfo != null && netInfo.isConnectedOrConnecting) {
val wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
val mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
mobile != null && mobile.isConnectedOrConnecting || wifi != null && wifi.isConnectedOrConnecting
} else false
}<file_sep>package ir.nilva.abotorab.view.page.cabinet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import ir.nilva.abotorab.R
import ir.nilva.abotorab.helper.getColumnsNumber
import ir.nilva.abotorab.helper.getRowsNumber
import ir.nilva.abotorab.model.CabinetResponse
import kotlinx.android.synthetic.main.cabinet_item.view.*
class CabinetListAdapter(
private val listener: OnClickCabinetListener
) : ListAdapter<CabinetResponse, CabinetListAdapter.CabinetVH>(CabinetDiff) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
CabinetVH(
LayoutInflater.from(parent.context)
.inflate(
R.layout.cabinet_item,
null
)
)
override fun onBindViewHolder(holder: CabinetVH, position: Int) =
holder.bind(getItem(position), listener)
class CabinetVH(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(
item: CabinetResponse,
listener: OnClickCabinetListener
) = with(view) {
title.text = String.format(
resources.getString(R.string.cabinet_format),
item.code
)
subTitle.text = String.format(
resources.getString(R.string.row_and_column_format),
item.getColumnsNumber(),
item.getRowsNumber()
)
setOnClickListener { listener.cabinetClicked(item.code) }
show.setOnClickListener { listener.cabinetClicked(item.code) }
print.setOnClickListener {
listener.printCabinet(print, item.code)
}
}
}
fun deleteItem(position: Int) {
listener.deleteCabinet(
getItem(position).code
) {
notifyItemRemoved(position)
notifyDataSetChanged()
}
}
object CabinetDiff : DiffUtil.ItemCallback<CabinetResponse>() {
override fun areItemsTheSame(oldItem: CabinetResponse, newItem: CabinetResponse) =
oldItem.code == newItem.code
override fun areContentsTheSame(oldItem: CabinetResponse, newItem: CabinetResponse) =
areItemsTheSame(oldItem, newItem)
}
interface OnClickCabinetListener {
fun cabinetClicked(code: String)
fun printCabinet(view: View, code: String)
fun deleteCabinet(code: String, callback: () -> Unit)
}
}
<file_sep>package ir.nilva.abotorab.model
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class Cell(
@SerializedName("id") val id: Int,
@SerializedName("code") val code: String,
@SerializedName("age") var age: Int,
@SerializedName("pilgrim") var pilgrim: Pilgrim?,
@SerializedName("pack") var pack: Pack?,
@SerializedName("is_healthy") var isHealthy: Boolean,
@SerializedName("is_fav") var isFavorite: Boolean,
@SerializedName("size") val size: Int,
@SerializedName("row") val row: Int
) : Serializable<file_sep>package ir.nilva.abotorab.view.page.main
import android.os.Bundle
import android.os.Handler
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.input.input
import ir.nilva.abotorab.R
import ir.nilva.abotorab.helper.*
import ir.nilva.abotorab.view.page.base.BaseActivity
import ir.nilva.abotorab.webservices.MyRetrofit
import ir.nilva.abotorab.webservices.callWebservice
import ir.nilva.abotorab.webservices.getServices
import kotlinx.android.synthetic.main.accounting_main.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
val depositories = mapOf(
Pair("http://192.168.0.11", "11"),
Pair("http://192.168.0.12", "12"),
Pair("http://192.168.0.13", "13"),
Pair("http://192.168.0.14", "14"),
Pair("http://192.168.0.15", "15"),
Pair("http://192.168.0.16", "16")
)
class LoginActivity : BaseActivity() {
private fun updateLabel() {
if (MyRetrofit.getBaseUrl() == "") {
connectedServerId.text = "با انتخاب شماره امانت داری به سرور متصل شوید"
} else {
val args = getDepositoryNumberFromUrl(MyRetrofit.getBaseUrl())
if (args == null) {
connectedServerId.text = "با انتخاب شماره امانت داری به سرور متصل شوید"
} else {
connectedServerId.text =
String.format("متصل به امانتداری شماره %s", args)
}
}
}
override fun onResume() {
super.onResume()
updateLabel()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.accounting_main)
val currentToken: String? = defaultCache()["token"]
updateLabel()
ip.setOnClickListener {
MaterialDialog(this).show {
title(text = "شماره امانتداری را وارد کنید")
input(hint = "مثلا: 14", prefill = "14") { _, text ->
defaultCache()["depository_code"] = text.toString()
val result = connectToNetworkWPA(text.toString())
connect2Server("http://192.168.0.$text")
if (!result) {
toastError("برقراری ارتباط با سرور با خطا مواجه شد")
}
}
positiveButton(text = "اتصال") {
showDialog()
}
}
}
submit.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
showLoading()
callWebservice {
getServices().login(
username.text.toString(),
password.text.toString(),
defaultCache()["depository_code"] ?: "10"
)
}?.run {
defaultCache()["token"] = token
defaultCache()["depository"] = depository
MyRetrofit.newInstance()
gotoMainPage()
}
hideLoading()
}
}
if (currentToken.isNullOrEmpty().not()) gotoMainPage()
}
private fun getDepositoryNumberFromUrl(url: String): String? {
for ((key, value) in depositories) {
if (key == url) {
return value
}
}
return null
}
private fun showDialog() {
val dialog = MaterialDialog(this).noAutoDismiss().show {
customView(R.layout.progress_dialog_material)
}
dialog.show()
Handler().postDelayed({
updateLabel()
dialog.dismiss()
}, 5000)
}
private fun connect2Server(ip: String) {
MyRetrofit.setBaseUrl(ip)
}
private fun showLoading() {
submit.visibility = View.INVISIBLE
spinKit.visibility = View.VISIBLE
}
private fun hideLoading() {
submit.visibility = View.VISIBLE
spinKit.visibility = View.GONE
}
}
<file_sep>package ir.nilva.abotorab.view.widget
import android.content.Context
import android.util.AttributeSet
import ir.nilva.abotorab.R
/**
* Created by mahdihs76 on 9/10/18.
*/
class UnoSubmitButton : UnoButton {
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)
init {
text = context.getString(R.string.submit)
}
}<file_sep>package ir.nilva.abotorab.model
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class Row(
@SerializedName("id") val id: Int,
@SerializedName("cells") val cells: ArrayList<Cell>,
@SerializedName("code") val code: Int,
@SerializedName("cabinet") val cabinet: Int
) : Serializable<file_sep>package ir.nilva.abotorab.webservices;
import com.google.gson.annotations.Expose;
public class BaseResponse {
@Expose
private String messageBody;
public String getMessageBody() {
return messageBody;
}
public void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
}
<file_sep>package ir.nilva.abotorab.helper
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import java.lang.reflect.Type
import java.util.*
internal class CountryListDeserializer : JsonDeserializer<CountryList> {
@Throws(JsonParseException::class)
override fun deserialize(
element: JsonElement,
type: Type,
context: JsonDeserializationContext
): CountryList {
val jsonObject = element.asJsonObject
val countries = ArrayList<CountryModel>()
for ((_, value) in jsonObject.entrySet()) {
val country = context.deserialize<CountryModel>(value, CountryModel::class.java)
countries.add(country)
}
return CountryList(countries)
}
}<file_sep>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'com.google.gms.google-services'
// Apply the Crashlytics Gradle plugin
apply plugin: 'com.google.firebase.crashlytics'
android {
compileSdkVersion 28
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "ir.nilva.abotorab"
minSdkVersion 19
targetSdkVersion 28
versionCode 3
versionName "1.2"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
lintOptions {
checkReleaseBuilds false
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.firebase:firebase-analytics:18.0.3'
implementation 'com.google.firebase:firebase-crashlytics:17.4.1'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.10"
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'com.github.zcweng:switch-button:0.0.3@aar'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation files('libs/android-client-debug-1.0.0.aar')
implementation 'io.github.inflationx:calligraphy3:3.1.1'
implementation 'io.github.inflationx:viewpump:2.0.3'
implementation 'com.github.ybq:Android-SpinKit:1.2.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1'
implementation "org.jetbrains.anko:anko:0.10.8"
implementation 'de.hdodenhof:circleimageview:3.0.0'
implementation 'com.ramotion.circlemenu:circle-menu:0.3.2'
implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'
implementation 'com.squareup.retrofit2:retrofit:2.8.1'
implementation 'com.aurelhubert:ahbottomnavigation:2.3.4'
implementation 'com.github.DanielMartinus:Stepper-Touch:1.0.1'
implementation 'com.google.android.gms:play-services-vision:20.1.3'
// implementation 'info.androidhive:barcode-reader:1.1.5'
implementation 'com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3'
implementation "org.permissionsdispatcher:permissionsdispatcher:4.5.0"
kapt "org.permissionsdispatcher:permissionsdispatcher-processor:4.5.0"
implementation 'com.afollestad.material-dialogs:core:3.1.1'
implementation 'com.github.pinguo-zhouwei:CustomPopwindow:2.1.1'
implementation 'com.github.florent37:viewanimator:1.1.0'
implementation 'com.github.AnyChart:AnyChart-Android:1.1.2'
implementation 'com.llollox:androidtoggleswitch:2.0.1'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.afollestad.material-dialogs:input:3.1.1'
implementation 'com.github.GrenderG:Toasty:1.4.2'
implementation "com.google.android.material:material:1.3.0"
implementation 'com.shawnlin:number-picker:2.4.9'
implementation 'io.github.inflationx:viewpump:2.0.3'
// WorkManager Dependency
implementation "androidx.work:work-runtime-ktx:2.5.0"
androidTestImplementation "androidx.work:work-testing:2.5.0"
def room_version = "2.2.6"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"
implementation 'com.github.Commit451:ModalBottomSheetDialogFragment:1.1.0'
implementation('com.microblink:blinkid:5.10.0@aar') {
transitive = true
}
}<file_sep>package ir.nilva.abotorab.view.page.main
import ir.nilva.abotorab.ApplicationContext
import ir.nilva.abotorab.R
/**
* Created by mahdihs76 on 9/11/18.
*/
enum class MenuItem(val index: Int, val text: String) {
CABINET_TAKE(0, ApplicationContext.context.getString(R.string.cabinet_take)),
CABINET_REPORT(1, ApplicationContext.context.getString(R.string.report)),
CABINET_GIVE(2, ApplicationContext.context.getString(R.string.cabinet_give)),
CABINET_INIT(3, ApplicationContext.context.getString(R.string.init)),
}
fun getMenuItem(index: Int) = MenuItem.values().toList().find { item -> item.index == index }
<file_sep>package ir.nilva.abotorab.view.page.operation
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import ir.nilva.abotorab.R
import ir.nilva.abotorab.db.model.DeliveryEntity
import ir.nilva.abotorab.helper.mapCabinetLabelWithCab
import kotlinx.android.synthetic.main.item_delivery.view.*
class RecentGivesAdapter(val listener: RecentGivesListener) :
ListAdapter<DeliveryEntity, RecentGivesAdapter.RecentGiveVH>(DeliveryDiff) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = RecentGiveVH(
LayoutInflater.from(parent.context).inflate(R.layout.item_delivery, null)
)
override fun onBindViewHolder(holder: RecentGiveVH, position: Int) =
holder.bind(getItem(position))
inner class RecentGiveVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: DeliveryEntity) = with(itemView) {
title.text = item.nickname
phone.text = item.phone
country.text = item.country
cellCode.text = "شماره قفسه: ${mapCabinetLabelWithCab(item.cellCode)}"
subTitle.text = item.exitedAt
setOnClickListener { listener.undoClicked(item) }
}
}
object DeliveryDiff : DiffUtil.ItemCallback<DeliveryEntity>() {
override fun areItemsTheSame(oldItem: DeliveryEntity, newItem: DeliveryEntity) =
oldItem.hashId == newItem.hashId
override fun areContentsTheSame(oldItem: DeliveryEntity, newItem: DeliveryEntity) =
areItemsTheSame(oldItem, newItem)
}
}<file_sep>package ir.nilva.abotorab.helper
import android.app.Activity
import ir.nilva.abotorab.view.page.cabinet.CabinetActivity
import ir.nilva.abotorab.view.page.cabinet.CabinetListActivity
import ir.nilva.abotorab.view.page.cabinet.FullScreenActivity
import ir.nilva.abotorab.view.page.main.LoginActivity
import ir.nilva.abotorab.view.page.main.MainActivity
import ir.nilva.abotorab.view.page.operation.*
import org.jetbrains.anko.startActivity
/**
* Created by mahdihs76 on 9/10/18.
*/
fun Activity.gotoMainPage() = startActivity<MainActivity>().apply { finish() }
fun Activity.gotoFullScreenPage(code: String) = startActivity<FullScreenActivity>("code" to code)
fun Activity.gotoTakePage(barcode: String = "") = startActivity<TakeActivity>("barcode" to barcode)
fun Activity.gotoGivePage(barcode: String = "") = startActivity<GiveSearchActivity>("barcode" to barcode)
fun Activity.gotoLoginPage(barcode: String = "") = startActivity<LoginActivity>("barcode" to barcode).apply { finish() }
fun Activity.gotoCabinetPage(code: String = "") = startActivity<CabinetActivity>("code" to code)
fun Activity.gotoCabinetListPage() = startActivity<CabinetListActivity>()
fun Activity.gotoReportPage() = startActivity<ReportActivity>()
fun Activity.gotoGiveSearchPage() = startActivity<GiveSearchActivity>()
fun Activity.gotoRecentGivesPage() = startActivity<RecentGivesActivity>()
fun Activity.gotoBarcodePage(isQR: Boolean) = startActivity<CameraActivity>("isQR" to isQR)
<file_sep>package ir.nilva.abotorab.db.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "delivery")
data class DeliveryEntity(
val nickname: String,
val country: String,
val cellCode: String,
val phone: String,
val hashId: String,
val exitedAt: String
){
@PrimaryKey(autoGenerate = true) var id: Long? = null
} | eab6f7f55530707fb6c875d01bc7ab9963f5e57a | [
"Java",
"Kotlin",
"Gradle"
] | 57 | Kotlin | mahdihs76/Abotorab | 4a543f416f0b5a2aab6079f1e149536c9582bc50 | b857d1fb7da7094cc3f36a640d97b34c3f09b699 |
refs/heads/master | <repo_name>daegren/lhl-aug19-w2d1<file_sep>/katas/repeatingNumbers.js
const repeatNumber = (value, repeat) => {
let output = "";
for (let i = 0; i < repeat; i++) {
output += value;
}
return output;
};
module.exports = data => {
let output = [];
data.forEach(([value, repeat]) => {
let repeatedString = repeatNumber(value, repeat);
output.push(repeatedString);
});
return output.join(", ");
};
<file_sep>/demo/test/instructors_test.js
const expect = require("chai").expect;
const instructors = require("../instructors");
describe("instructors", () => {
context("add", () => {
it("adds two and two and returns 4", () => {
// Arrange
const a = 2;
const b = 2;
// Act
const result = instructors.add(a, b);
// Assert
expect(result).to.equal(4);
});
it("return 0 if one number is the negative version of the other", () => {
const a = 10;
expect(instructors.add(a, -10)).to.equal(0);
});
});
context("instructors array", () => {
it("is an array", () => {
expect(instructors.instructors).to.be.an("array");
expect(instructors.instructors).to.have.lengthOf(3);
});
it("contains the right values", () => {
expect(instructors.instructors[0]).to.have.property("name", "Dave");
});
});
});
<file_sep>/demo/instructors.js
module.exports.add = (a, b) => a + b;
module.exports.instructors = [
{ name: "Dave", role: "FT Instructor" },
{ name: "Juan", role: "PT Instructor" },
{ name: "Vasily", role: "Mentor" }
];
<file_sep>/katas/caseMaker.js
const caseify = (word, upper) => {
const letters = word.split("");
if (upper) {
letters[0] = letters[0].toUpperCase();
} else {
letters[0] = letters[0].toLowerCase();
}
return letters.join("");
};
module.exports = input => {
if (input.length === 0) {
return "";
}
const words = input.toLowerCase().split(" ");
const newWords = words.map((word, i) => {
return caseify(word, i > 0);
});
return newWords.join("");
};
| da7a89439a85d50b49e8419165e4a1ea50b47101 | [
"JavaScript"
] | 4 | JavaScript | daegren/lhl-aug19-w2d1 | 39e91640cd62c01f8b0172547252dd65bb9aed7f | 2120ad32c045119dc97e15e4cb0546ebde75ae47 |
refs/heads/master | <repo_name>RaoShridhar/security-poc<file_sep>/src/main/java/com/github/aha/poc/security/controller/LoginController.java
package com.github.aha.poc.security.controller;
import java.util.Map;
import javax.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @see http://www.journaldev.com/8748/spring-4-mvc-security-managing-roles-example
*/
@Controller
public class LoginController {
@Autowired
private MessageSource resource;
@RequestMapping(value = ActionConsts.LOGIN, method = RequestMethod.GET)
public String loginPage(@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout, Map<String, Object> model) {
if (error != null) {
model.put("loginMessage", resource.getMessage("login.failed", null, LocaleContextHolder.getLocale()));
}
if (logout != null) {
model.put("loginMessage", resource.getMessage("login.successful", null, LocaleContextHolder.getLocale()));
}
return "login";
}
@RequestMapping(value = ActionConsts.USER, method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_DEVELOPERS') or principal.username == 'aha'")
public String userPage(Map<String, Object> model) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
UserDetails ud = ((UserDetails)principal);
model.put("userDetail", ud);
}
return "user";
}
@RequestMapping(value = ActionConsts.ADMIN, method = RequestMethod.GET)
@RolesAllowed("ROLE_ADMIN")
public String adminPage() {
return "admin";
}
}
<file_sep>/src/main/java/com/github/aha/poc/security/config/AbstractSecurityConfig.java
package com.github.aha.poc.security.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import com.github.aha.poc.security.controller.ActionConsts;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true)
public abstract class AbstractSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(ActionConsts.ROOT, ActionConsts.HOME).permitAll()
// .antMatchers(ActionConsts.ADMIN).access("hasRole('ROLE_ADMIN')")
.anyRequest().authenticated().and()
.formLogin()
.loginPage(ActionConsts.LOGIN)
.defaultSuccessUrl(ActionConsts.HOME)
.permitAll()
.usernameParameter("username").passwordParameter("<PASSWORD>").and()
.rememberMe()
.tokenValiditySeconds(2419200)
.key("ahaKey").and()
.logout()
.permitAll();
}
}
<file_sep>/src/main/java/com/github/aha/poc/security/aop/ControllerLogger.java
package com.github.aha.poc.security.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ControllerLogger {
private static final Logger LOG = LoggerFactory.getLogger(ControllerLogger.class);
/**
* Just AOP example (to verify the functionality)
*/
@Before("execution(* com.github.aha.poc..*Controller.*(..))")
public void logLogin(JoinPoint joinPoint) {
LOG.info("Controller method {} called ...", joinPoint.getSignature().getName());
}
}
<file_sep>/README.md
# security-poc
POC of Spring Security usage with these features:
- based on Spring Boot 1.3 & Java 8
- authentication (different profiles) & authorization
- JSP + JSTL
- Apache Tiles (templating)
- (currently) no testing
POC contains several Spring profiles to demonstrate several different configuration options (see table bellow).
Profile name | Type | Note
------------- | ------------- | -------------
IN_MEMORY | **In-Memory** | Default profile
JDBC | JDBC | via jdbcAuthentication method (maven dependencies for embbeded DB)
USER_DETAIL_SERVICE | JDBC | via User Detail Service (maven dependencies for embbeded DB)
APACHE_DS | LDAP | with Apache DS (maven dependencies for Apache DS)
ACTIVE_DIRECTORY | Authentication provider | with Active Directory
Profile usage:
> java spring-boot:run --spring.profiles.active=JDBC
<file_sep>/src/main/java/com/github/aha/poc/security/config/ActiveDirectorySecurityConfig.java
package com.github.aha.poc.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;
import com.github.aha.poc.security.controller.ActionConsts;
@Configuration
@Profile("ACTIVE_DIRECTORY")
public class ActiveDirectorySecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${auth.ad.domain}")
private String domain;
@Value("${auth.ad.url}")
private String url;
@Value("${auth.ad.filter}")
private String filter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(ActionConsts.ROOT, ActionConsts.HOME).permitAll()
.antMatchers(ActionConsts.ADMIN).access("hasRole('ROLE_ADMIN')")
.anyRequest().authenticated().and()
.formLogin()
.loginPage(ActionConsts.LOGIN)
.defaultSuccessUrl(ActionConsts.HOME)
.permitAll()
.usernameParameter("username").passwordParameter("<PASSWORD>").and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.authenticationProvider(activeDirectoryLdapAuthenticationProvider());
}
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(domain, url);
provider.setUseAuthenticationRequestCredentials(true);
provider.setConvertSubErrorCodesToExceptions(true);
provider.setSearchFilter(filter);
return provider;
}
}
<file_sep>/src/main/java/com/github/aha/poc/security/config/UserDetailServiceSecurityConfig.java
package com.github.aha.poc.security.config;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
@Configuration
@Profile("USER_DETAIL_SERVICE")
public class UserDetailServiceSecurityConfig extends AbstractSecurityConfig {
@Autowired
private JdbcUserService userService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.userDetailsService(userService);
}
@Component
class JdbcUserService implements UserDetailsService {
private JdbcTemplate jdbcTemplate;
@Autowired
public JdbcUserService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// load user details
UserDTO user = jdbcTemplate.queryForObject(
"select id, username, passwd from u_principal where username = ?", new Object[] { username }, new UserMapper());
if (user == null) {
throw new UsernameNotFoundException(String.format("userma=%s", username));
}
// load authorities
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
List<Map<String, Object>> data = jdbcTemplate.queryForList("select name from u_role where user_id = :id", user.getId());
for (Map<String, Object> item : data) {
String role = String.format("ROLE_%s", item.get("NAME"));
authorities.add(new SimpleGrantedAuthority(role));
}
return new User(user.getUsername(), user.getPasswd(), authorities);
}
}
class UserMapper implements RowMapper<UserDTO> {
@Override
public UserDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
return new UserDTO(rs.getInt("id"), rs.getString("username"), rs.getString("passwd"));
}
}
class UserDTO {
public UserDTO(int id, String username, String passwd) {
super();
this.id = id;
this.username = username;
this.passwd = passwd;
}
private int id;
private String username;
private String passwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
}
| ac7a61566baed5d74737a69ade2907c1b67af68f | [
"Markdown",
"Java"
] | 6 | Java | RaoShridhar/security-poc | 71146a2f528e623a814deb31be131a94f865da16 | cf3f9bb2b75bb951fdb3da1dd090a551cb6c6320 |
refs/heads/master | <file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hoja.de.trabajo6;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.Set;
import java.util.LinkedHashSet;
import javax.swing.JOptionPane;
/**
*
* @author Jorge
*/
public class GUIhoja6 extends javax.swing.JFrame {
int bandera=0;
HojaDeTrabajo6 hoja= new HojaDeTrabajo6();
int entry=0;
Set hjava;
Set hweb;
Set hcelular;
//Array arrayjava= new Array();
int seleccion = JOptionPane.showOptionDialog(
null,
"Que tipo Set desea utilizar",
"Selector de opciones",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
new Object[] { "HashSet", "Hashtree","LinkedHashSet"}, // null para YES, NO y CANCEL
"opcion 0");
//Try y catch para probar cada uno de los carros y ver si regresa un exepcion de tipo "CarroExeption"
/**
* Creates new form GUIhoja6
*/
public GUIhoja6() {
initComponents();
switch(seleccion){
case 0:{ entry=1;}
break;
case 1:{entry=2;}
break;
case 2:{ entry=3;}
break;
}
FactorySet factory = new FactorySet();
hjava= factory.getSet(entry) ;
hweb= factory.getSet(entry) ;
hcelular= factory.getSet(entry) ;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton1 = new javax.swing.JButton();
jCheckBox1 = new javax.swing.JCheckBox();
jCheckBox2 = new javax.swing.JCheckBox();
jCheckBox3 = new javax.swing.JCheckBox();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("ingresar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jCheckBox1.setText("java");
jCheckBox2.setText("web");
jCheckBox3.setText("celulares");
jButton2.setText("mostrar datos");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addGap(81, 81, 81)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jCheckBox2)
.addComponent(jCheckBox1))
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jCheckBox3))))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(119, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBox1)
.addComponent(jButton1))
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBox2)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addComponent(jCheckBox3)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap(107, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if (jCheckBox1.isSelected()==true){
hjava.add(jTextField1.toString());
}
if (jCheckBox1.isSelected()==true){
hweb.add(jTextField1.toString());
}
if (jCheckBox2.isSelected()==true){
hcelular.add(jTextField1.toString());
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
//arrayjava =hjava.toArray()
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUIhoja6.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUIhoja6.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUIhoja6.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUIhoja6.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUIhoja6().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JCheckBox jCheckBox2;
private javax.swing.JCheckBox jCheckBox3;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* hola Irene me contas si lees esto
*/
package hoja.de.trabajo6;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.LinkedHashSet;
/**
*
* @author Jorge
*/
public class HojaDeTrabajo6 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
GUISet forma = new GUISet();
forma.show();
// TODO code application logic here
}
}
<file_sep>HojaDeTrabajo5
==============
<file_sep>import simpy
print "Hello World :D" | 28e060c663e19d3da78ed73e4fb00eee88b0223a | [
"Markdown",
"Java",
"Python"
] | 4 | Java | Jorest/Hoja-de-trabajo6 | ddb9d94246b9d113957d94f419ccaadcda3c1214 | 0f5fb01f2e1f4e56c5416616544e0fa1ddaa89c6 |
refs/heads/master | <repo_name>jimivine/sortingalgorithms<file_sep>/Sorting Algorithms Year 2 CW/src/findelement_d/Question1_Part3.java
package findelement_d;
import java.util.Random;
/**
* - Question 1 Part 3 - Finding the worst case runtime complexity
* @author jimivine
*/
public class Question1_Part3
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// Record mean and std deviation of performing an operation
// reps times
int reps = 100;
int[] arraySize = {10,20,30,40,50,60,70,80,90,
100,200,300,400,500,600,700,800,900,
1000,2000,3000,4000};
for(int j =0; j <arraySize.length; j++)
{
double sum=0, s=0;
double sumSquared=0;
int[][] something = generateDataSet(arraySize[j]); //2D matrix
for(int i =0; i <reps; i++)
{
long t1=System.nanoTime();
//call FindElement method for an instance of size n
//Algorithm 1
findElement_D(something,-1);
//Algorithm 2
//findElement_D1(something,-1);
//Algorithm 3
//findElement_D2(something,-1);
long t2=System.nanoTime()-t1;
//Time in milliseconds
sum+=(double)t2/1000000.0;
sumSquared+=(t2/1000000.0)*(t2/1000000.0);
}
double mean=sum/reps;
double variance=sumSquared/reps-(mean*mean);
double stdDev=Math.sqrt(variance);
System.out.println(mean + ", " + stdDev + "\n");
}
}
/**
* - Question 1 - Linear Search Algorithm for FindElement_D
* @param A
* @param p
* @return
*/
public static boolean findElement_D(int[][] A, int p)
{
for(int i =0; i <A.length; i++)
{
for(int j =0; j <A.length; j++)
{
if(A[i][j] == p)
{
return true;
}
}
}
return false;
}
/**
* - Question 1 - Binary Search Algorithm for FindElement_D1
* @param A
* @param p
* @return
*/
public static boolean findElement_D1(int[][] A, int p)
{
int low = 0; //start of row
int high = A.length -1; //end of row
for(int i =0; i <A.length; i++)
{
low = 0;
high = A.length - 1;
while (low <= high)
{ //While high is greater than low, continue
int mid = (low + high) / 2; //calculate mid-point
if(A[i][mid] < p)
{
low = mid + 1; //search upper half of row
}else if(A[i][mid] > p)
{
high = mid - 1; // search lower half of row
}else if(A[i][mid] == p)
{ //check if mid-point is a match
return true;
}
}
}
return false;
}
/**
* - Question 1 - Improved Search Algorithm for FindElement_D2
* @param A
* @param p
* @return
*/
public static boolean findElement_D2(int[][] A, int p)
{
int j = (A.length -1);
int i = 0;
while(p != A[i][j])
{ //While p does not equal value of A, continue
if(p > A[i][j])
{
i++; //goes to next row
} else if(p < A[i][j])
{
j--; //moves back a column
}
if(i == A.length || j == 0)
{
return false;
}
}
return true;
}
/**
* - Generates random data set
* @param n
* @return
*/
public static int[][] generateDataSet(int n)
{
int[][] data=new int[n][n];
Random r=new Random();
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
data[i][j]=r.nextInt();
return data;
}
}
<file_sep>/README.md
# sortingalgorithms
Sorting algorithms coursework, linear search and binary search, as well as improved search algorithms for finding elements. Also finding the worst case runtime complexity for each algorithm. Year 2 Data Structures and Algorithms Coursework.
<file_sep>/Sorting Algorithms Year 2 CW/nbproject/private/private.properties
compile.on.save=true
user.properties.file=/Users/jimivine/Library/Application Support/NetBeans/8.0/build.properties
| ca9d590a997fa8535ef00e1a4b1098e625852123 | [
"Markdown",
"Java",
"INI"
] | 3 | Java | jimivine/sortingalgorithms | 07862dd5a3edc4e7e59a4285a28b1c9104cdc551 | 867e73af16f1c6d8c9688c7c4548f5e549013154 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Predvajalnik
{
class Premetanka
{
private Image imageSheuldet;
private int[] widthParts;
private int[] heightParts;
private int difficulty;
private int height;
private int width;
private DateTime timeStart;
private DateTime timeEnd;
private Point point1;
private Point point2;
private Boolean isPlaying;
private Image originalImage;
private List<int> numbers;
private List<Image> smallImages;
private int splitNumber;
private Boolean isFinished;
private String textOfFinishedGameB;
public Premetanka(Image image, int height, int width, int difficulty)
{
this.height = height;
this.width = width;
this.difficulty = difficulty;
originalImage = resizeImage((Image)image.Clone(), new Size(width,height));
point1 = new Point(0,0);
point2 = new Point(0,0);
isFinished = false;
textOfFinishedGameB = "";
}
private Image resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(size.Width, size.Height);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, size.Width, size.Height);
g.Dispose();
return (Image)b;
}
public Image start()
{
switch (difficulty)
{
case 0:
{
splitNumber = 3;
numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
smallImages = splitPicture(3, originalImage);
shuffle(numbers, smallImages);
break;
}
case 1:
{
splitNumber = 4;
numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
smallImages = splitPicture(4, originalImage);
shuffle(numbers, smallImages);
break;
}
case 2:
{
splitNumber = 5;
numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24};
smallImages = splitPicture(5, originalImage);
shuffle(numbers, smallImages);
break;
}
case 3:
{
splitNumber = 6;
numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35};
smallImages = splitPicture(6, originalImage);
shuffle(numbers, smallImages);
break;
}
}
isPlaying = true;
timeStart = DateTime.Now;
imageSheuldet = drawLines(getImageFromParts2(smallImages));
return imageSheuldet;
}
private int getPartIndex(Point point)
{
return getIndexFromArray(widthParts, point.X) * splitNumber + getIndexFromArray(heightParts, point.Y);
}
private int getIndexFromArray(int[] array, int value)
{
for (int i = 0; i < array.Length; i++)
{
if (value < array[i])
{
return i;
}
}
return -1;
}
private Boolean checkIfGameIsFinished()
{
List<int> listOfNumbers = orderList();
for (int i = 1; i < listOfNumbers.Count; i++)
{
if (listOfNumbers[i - 1] > listOfNumbers[i])
return false;
}
return true;
}
private List<int> orderList()
{
List<int> newList = new List<int>();
for (int i = 0; i < splitNumber; i++)
{
for (int j = 0; j < splitNumber; j++)
{
newList.Add(numbers[i + j * splitNumber]);
}
}
return newList;
}
private void shuffle(List<int> listNumbers, List<Image> listImages)
{
Random rng = new Random();
int n = listNumbers.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
Image tempImage = listImages[k];
int value = listNumbers[k];
listNumbers[k] = listNumbers[n];
listImages[k] = listImages[n];
listNumbers[n] = value;
listImages[n] = tempImage;
}
}
private Image drawLines(Image image)
{
Image resultImage = (Image)image.Clone();
using (Graphics g = Graphics.FromImage(resultImage))
{
Pen pen = new Pen(Color.Black, 5);
for (int i = 0; i <= splitNumber; i++)
{
g.DrawLine(pen, new Point(0, i * height / splitNumber), new Point(width, i * height / splitNumber));
g.DrawLine(pen, new Point(i * width / splitNumber, 0), new Point(i * width / splitNumber, height));
}
}
return resultImage;
}
public Image mouseClicked(object sender, MouseEventArgs e)
{
Image imageForProcessing = (Image)imageSheuldet.Clone();
if (isPlaying)
{
if (Point.Empty == point1)
{
point1 = new Point(e.X, e.Y);
imageForProcessing = drawRedRectangle(point1, imageForProcessing);
}
else
{
if (Point.Empty == point2)
{
point2 = new Point(e.X, e.Y);
imageForProcessing = changeParts();
point1 = new Point(0, 0);
point2 = new Point(0, 0);
if (checkIfGameIsFinished())
{
timeEnd = DateTime.Now;
TimeSpan timeOfPlaying = timeEnd - timeStart;
textOfFinishedGameB = "Igra je končana! Igrali ste " + timeOfPlaying.Minutes + " minut in " + timeOfPlaying.Seconds + " sekund!";
isPlaying = false;
isFinished = true;
}
}
}
}
imageSheuldet = imageForProcessing;
return imageForProcessing;
}
private Image drawRedRectangle(Point point, Image image)
{
int widthMin=0, widthMax=0;
int heightMin=0, heightMax=0;
for (int i = 0; i < widthParts.Length; i++)
{
if (i == 0 && point.X < widthParts[i])
{
widthMin = 0;
widthMax = widthParts[i];
break;
}
if (point.X < widthParts[i])
{
widthMin = widthParts[i - 1];
widthMax = widthParts[i];
break;
}
if (point.X > widthParts[i] && i == (widthParts.Length + 1))
{
widthMin = widthParts[i];
widthMax = width;
break;
}
}
for (int j = 0; j < heightParts.Length; j++)
{
if (j == 0 && point.Y < heightParts[j])
{
heightMin = 0;
heightMax = heightParts[j];
break;
}
if (point.Y < heightParts[j])
{
heightMin = heightParts[j - 1];
heightMax = heightParts[j];
break;
}
if (point.Y > heightParts[j] && j == (heightParts.Length + 1))
{
heightMin = heightParts[j];
heightMax = height;
break;
}
}
using (Graphics g = Graphics.FromImage(image))
{
g.DrawRectangle(new Pen(Color.Red, 5), new Rectangle(widthMin,heightMin,(widthMax-widthMin),(heightMax-heightMin)));
}
return image;
}
private Image changeParts()
{
int index1 = getPartIndex(point1);
int index2 = getPartIndex(point2);
if (index1 != index2)
{
int tempValue = numbers[index1];
numbers[index1] = numbers[index2];
numbers[index2] = tempValue;
Image tempImage = smallImages[index1];
smallImages[index1] = smallImages[index2];
smallImages[index2] = tempImage;
}
return drawLines(getImageFromParts2(smallImages));
}
private Image getImageFromParts(List<Image> images)
{
Bitmap bitmap = new Bitmap(width, height);
for (int i = 0; i < splitNumber; i++)
{
for (int j = 0; j < splitNumber; j++)
{
for (int x = 0; x < images[0].Width; x++)
{
for (int y = 0; y < images[0].Height; y++)
{
bitmap.SetPixel((x + i * images[i].Width) % width, (y + j * images[j].Height) % height,
((Bitmap)images[i * splitNumber + j]).GetPixel(x, y));
}
}
}
}
return (Image)bitmap;
}
private Image getImageFromParts2(List<Image> images)
{
Bitmap bitmap = new Bitmap(width, height);
int index=0;
for (int i = 0; i < width-20; i+=images[0].Width)
{
for (int j = 0; j < height-20; j+=images[0].Height)
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.DrawImage(images[index],new Point(i,j));
index++;
}
}
}
return (Image)bitmap;
}
private List<Image> splitPicture(int splitNumber, Image image)
{
int widthT = 0;
int heightT = 0;
Size size = new Size();
switch (splitNumber)
{
case 3:
{
widthT = this.width / 3;
heightT = this.height / 3;
break;
}
case 4:
{
widthT = this.width / 4;
heightT = this.height / 4;
break;
}
case 5:
{
widthT = this.width / 5;
heightT = this.height / 5;
break;
}
case 6:
{
widthT = this.width / 6;
heightT = this.height / 6;
break;
}
}
widthParts = new int[splitNumber];
heightParts = new int[splitNumber];
for (int j = 0; j < splitNumber; j++)
{
widthParts[j] = (j + 1) * widthT;
heightParts[j] = (j + 1) * heightT;
}
size = new Size(widthT, heightT);
List<Image> images = new List<Image>();
for (int i = 0; i < splitNumber; i++)
{
for (int j = 0; j < splitNumber; j++)
{
images.Add(getPartOfPicture(image, size, i, j));
}
}
return images;
}
private Image getPartOfPicture(Image image, Size size, int row, int column)
{
Bitmap partOfImage = new Bitmap(size.Width, size.Height);
Bitmap bitmap = (Bitmap)image;
for (int x = 0; x < partOfImage.Width; x++)
{
for (int y = 0; y < partOfImage.Height; y++)
{
partOfImage.SetPixel(x, y, bitmap.GetPixel(x + column * size.Width, y + row * size.Height));
}
}
return (Image)partOfImage;
}
public Boolean isGameFinished()
{
return isFinished;
}
public String getFinishedText()
{
return textOfFinishedGameB;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Predvajalnik
{
public partial class FormPremetanka : Form
{
private DateTime timeStart;
private DateTime timeEnd;
private Point point1;
private Point point2;
private Boolean isPlaying;
private Image originalImage;
private List<int> numbers;
private List<Image> smallImages;
private int splitNumber;
public FormPremetanka(Image image)
{
InitializeComponent();
originalImage = resizeImage((Image)image.Clone(), new Size(320, 240));
pictureBoxImage.Image = originalImage;
isPlaying = false;
point1 = new Point(0,0);
point2 = new Point(0,0);
textBoxStatus.Text = "Začnite igro!";
}
private void FormPremetanka_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 0;
}
private Image resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
private void buttonStartPlay_Click(object sender, EventArgs e)
{
switch (comboBox1.SelectedIndex)
{
case 0:
{
splitNumber = 3;
numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
smallImages = splitPicture(3, originalImage);
shuffle(numbers, smallImages);
break;
}
case 1:
{
splitNumber = 4;
numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
smallImages = splitPicture(4, originalImage);
shuffle(numbers, smallImages);
break;
}
case 2:
{
splitNumber = 5;
numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24};
smallImages = splitPicture(5, originalImage);
shuffle(numbers, smallImages);
break;
}
case 3:
{
splitNumber = 6;
numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35};
smallImages = splitPicture(6, originalImage);
shuffle(numbers, smallImages);
break;
}
}
pictureBoxImage.Image = drawLines(getImageFromParts(smallImages));
isPlaying = true;
timeStart = DateTime.Now;
}
private Image getImageFromParts(List<Image> images)
{
Bitmap bitmap = new Bitmap(320,240);
for (int i = 0; i < splitNumber; i++)
{
for (int j = 0; j < splitNumber; j++)
{
for (int x = 0; x < images[0].Width; x++)
{
for (int y = 0; y < images[0].Height; y++)
{
bitmap.SetPixel((x + i * images[i].Width) % 320, (y + j * images[j].Height) % 240, ((Bitmap)images[i * splitNumber + j]).GetPixel(x, y));
}
}
}
}
return (Image) bitmap;
}
private List<Image> splitPicture(int splitNumber, Image image)
{
int width = 0;
int height = 0;
Size size = new Size();
switch (splitNumber)
{
case 3:
{
width = 106;
height = 80;
break;
}
case 4:
{
width = 80;
height = 60;
break;
}
case 5:
{
width = 64;
height = 48;
break;
}
case 6:
{
width = 53;
height = 40;
break;
}
}
size = new Size(width, height);
List<Image> images = new List<Image>();
for (int i = 0; i < splitNumber; i++)
{
for (int j = 0; j < splitNumber; j++)
{
images.Add(getPartOfPicture(image, size, i, j));
}
}
return images;
}
private Image getPartOfPicture(Image image, Size size, int row, int column)
{
Bitmap partOfImage = new Bitmap(size.Width, size.Height);
Bitmap bitmap = (Bitmap)image;
for (int x = 0; x < partOfImage.Width; x++)
{
for (int y = 0; y < partOfImage.Height; y++)
{
partOfImage.SetPixel(x, y, bitmap.GetPixel(x + column * size.Width, y + row * size.Height));
}
}
return (Image)partOfImage;
}
private void shuffle(List<int> listNumbers, List<Image> listImages)
{
Random rng = new Random();
int n = listNumbers.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
Image tempImage = listImages[k];
int value = listNumbers[k];
listNumbers[k] = listNumbers[n];
listImages[k] = listImages[n];
listNumbers[n] = value;
listImages[n] = tempImage;
}
}
private Image drawLines(Image image)
{
Image resultImage = (Image)image.Clone();
switch (splitNumber)
{
case 3:
{
using (Graphics g = Graphics.FromImage(resultImage))
{
Pen pen = new Pen(Color.Black, 2);
g.DrawLine(pen, new Point(0, 0), new Point(320, 0));
g.DrawLine(pen, new Point(0, 80), new Point(320, 80));
g.DrawLine(pen, new Point(0, 160), new Point(320, 160));
g.DrawLine(pen, new Point(0, 240), new Point(320, 240));
g.DrawLine(pen, new Point(0, 0), new Point(0, 240));
g.DrawLine(pen, new Point(106, 0), new Point(106, 240));
g.DrawLine(pen, new Point(212, 0), new Point(212, 240));
g.DrawLine(pen, new Point(320, 0), new Point(320, 240));
}
break;
}
case 4:
{
using (Graphics g = Graphics.FromImage(resultImage))
{
Pen pen = new Pen(Color.Black, 2);
g.DrawLine(pen, new Point(0, 0), new Point(320, 0));
g.DrawLine(pen, new Point(0, 60), new Point(320, 60));
g.DrawLine(pen, new Point(0, 120), new Point(320, 120));
g.DrawLine(pen, new Point(0, 180), new Point(320, 180));
g.DrawLine(pen, new Point(0, 240), new Point(320, 240));
g.DrawLine(pen, new Point(0, 0), new Point(0, 240));
g.DrawLine(pen, new Point(80, 0), new Point(80, 240));
g.DrawLine(pen, new Point(160, 0), new Point(160, 240));
g.DrawLine(pen, new Point(240, 0), new Point(240, 240));
g.DrawLine(pen, new Point(320, 0), new Point(320, 240));
}
break;
}
case 5:
{
using (Graphics g = Graphics.FromImage(resultImage))
{
Pen pen = new Pen(Color.Black, 2);
g.DrawLine(pen, new Point(0, 0), new Point(320, 0));
g.DrawLine(pen, new Point(0, 48), new Point(320, 48));
g.DrawLine(pen, new Point(0, 96), new Point(320, 96));
g.DrawLine(pen, new Point(0, 144), new Point(320, 144));
g.DrawLine(pen, new Point(0, 192), new Point(320, 192));
g.DrawLine(pen, new Point(0, 240), new Point(320, 240));
g.DrawLine(pen, new Point(0, 0), new Point(0, 240));
g.DrawLine(pen, new Point(64, 0), new Point(64, 240));
g.DrawLine(pen, new Point(128, 0), new Point(128, 240));
g.DrawLine(pen, new Point(192, 0), new Point(192, 240));
g.DrawLine(pen, new Point(256, 0), new Point(256, 240));
g.DrawLine(pen, new Point(320, 0), new Point(320, 240));
}
break;
}
case 6:
{
using (Graphics g = Graphics.FromImage(resultImage))
{
Pen pen = new Pen(Color.Black, 2);
g.DrawLine(pen, new Point(0, 0), new Point(320, 0));
g.DrawLine(pen, new Point(0, 40), new Point(320, 40));
g.DrawLine(pen, new Point(0, 80), new Point(320, 80));
g.DrawLine(pen, new Point(0, 120), new Point(320, 120));
g.DrawLine(pen, new Point(0, 160), new Point(320, 160));
g.DrawLine(pen, new Point(0, 200), new Point(320, 200));
g.DrawLine(pen, new Point(0, 240), new Point(320, 240));
g.DrawLine(pen, new Point(0, 0), new Point(0, 240));
g.DrawLine(pen, new Point(53, 0), new Point(53, 240));
g.DrawLine(pen, new Point(106, 0), new Point(106, 240));
g.DrawLine(pen, new Point(160, 0), new Point(160, 240));
g.DrawLine(pen, new Point(213, 0), new Point(213, 240));
g.DrawLine(pen, new Point(266, 0), new Point(266, 240));
g.DrawLine(pen, new Point(320, 0), new Point(320, 240));
}
break;
}
}
return resultImage;
}
private void pictureBoxImage_MouseClick(object sender, MouseEventArgs e)
{
if (isPlaying)
{
if(Point.Empty == point1)
{
point1 = new Point(e.X,e.Y);
textBoxStatus.Text = "Izbrali ste sličico za zamenjavo!";
}
else
{
if(Point.Empty == point2)
{
point2 = new Point(e.X,e.Y);
changeParts();
point1 = new Point(0, 0);
point2 = new Point(0, 0);
textBoxStatus.Text = "Sličici sta zamenjani!";
if (isGameFinished())
{
timeEnd = DateTime.Now;
TimeSpan timeOfPlaying = timeEnd - timeStart;
MessageBox.Show("Igra je končana! Igrali ste " + timeOfPlaying.Minutes +
" minut in " + timeOfPlaying.Seconds + " sekund!");
isPlaying = false;
}
}
}
}
}
private void changeParts()
{
int index1 = getPartIndex(point1);
int index11 = getPartIndex2(point1);
int index2 = getPartIndex(point2);
int index22 = getPartIndex2(point2);
if (index1 != index2)
{
int tempValue = numbers[index1];
numbers[index1] = numbers[index2];
numbers[index2] = tempValue;
Image tempImage = smallImages[index1];
smallImages[index1] = smallImages[index2];
smallImages[index2] = tempImage;
pictureBoxImage.Image = drawLines(getImageFromParts(smallImages));
}
}
private int getPartIndex(Point point)
{
int index = 0;
switch (splitNumber)
{
case 3:
{
index = getIndexFromArray(new int[] { 106, 212, 320 }, point.X) * 3 + getIndexFromArray(new int[] { 80, 160, 240 }, point.Y);
break;
}
case 4:
{
index = getIndexFromArray(new int[] { 80, 160, 240, 320 }, point.X) * 4 + getIndexFromArray(new int[] { 60, 120, 180, 240 }, point.Y);
break;
}
case 5:
{
index = getIndexFromArray(new int[] { 64, 128, 192, 256, 320 }, point.X) * 5 + getIndexFromArray(new int[] { 48, 96, 144, 192, 240 }, point.Y);
break;
}
case 6:
{
index = getIndexFromArray(new int[] { 53, 106, 160, 213, 266, 320 }, point.X) * 6 + getIndexFromArray(new int[] { 40, 80, 120, 160, 200, 240 }, point.Y);
break;
}
}
return index;
}
private int getPartIndex2(Point point)
{
int index = 0;
switch (splitNumber)
{
case 3:
{
index = getIndexFromArray(new int[] { 106, 212, 320 }, point.X) + getIndexFromArray(new int[] { 80, 160, 240 }, point.Y) * 3;
break;
}
case 4:
{
index = getIndexFromArray(new int[] { 80, 160, 240, 320 }, point.X) + getIndexFromArray(new int[] { 60, 120, 180, 240 }, point.Y) * 4;
break;
}
case 5:
{
index = getIndexFromArray(new int[] { 64, 128, 192, 256, 320 }, point.X) + getIndexFromArray(new int[] { 48, 96, 144, 192, 240 }, point.Y) * 5;
break;
}
case 6:
{
index = getIndexFromArray(new int[] { 53, 106, 160, 213, 266, 320 }, point.X) + getIndexFromArray(new int[] { 40, 80, 120, 160, 200, 240 }, point.Y) * 6;
break;
}
}
return index;
}
private int getIndexFromArray(int[] array, int value)
{
for (int i = 0; i < array.Length; i++)
{
if (value < array[i])
{
return i;
}
}
return -1;
}
private Boolean isGameFinished()
{
List<int> listOfNumbers = orderList();
for (int i = 1; i < listOfNumbers.Count; i++)
{
if (listOfNumbers[i - 1] > listOfNumbers[i])
return false;
}
return true;
}
private List<int> orderList()
{
List<int> newList = new List<int>();
for (int i = 0; i < splitNumber; i++)
{
for (int j = 0; j < splitNumber; j++)
{
newList.Add(numbers[i+j*splitNumber]);
}
}
return newList;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.DirectX.AudioVideoPlayback;
namespace Predvajalnik
{
public partial class Form1 : Form
{
private Size sizeOfPanel;
private int difficulty;
private Boolean isGameOn;
private Premetanka premetanka;
private List<ListViewItem> listOfRandom;
private Boolean isLoaded;
private String[] extensionsOfVideo = new String[] { "avi", "mpg" };
private String[] extensionsOfAudio = new String[] { "mp3" };
private String[] extensionsOfPicture = new String[] { "bmp", "jpg", "jpeg", "gif" };
private int typeOfPlayingObject;
private int volumeValue;
private Boolean volumeIsMute;
private String[] nacinPredvajanja = new String[] { "Zaporedno", "Naključno" };
private String[] nacinPonavljanja = new String[] { "Ponovi vse", "Ponavljaj samo ta objekt", "Ne ponovi"};
private int indexNacinaPredvajanja;
private int indexNacinaPonavljanja;
private String pathOfLoadedObject;
private Audio audioPredvajanja;
private double audioDuration;
private Image imagePrikazovanja;
private Video videoPredvajanja;
private double videoDuration;
private delegate void playNextObjectDel();
private delegate void refreshCurrentPositionOfVideo();
private delegate void refrestTextBoxCurrentPosition(String newString);
private delegate void refrestTrackBarCurrentPosition(int value);
private int[] volumeValues = new int[] {-10000, -3000, -1500, -1000, -750, -500, -300, -200, -80, -30, 0};
private int indexOfPlayingObject;
private Random randomNumber;
private Boolean isPlaying;
public Form1()
{
InitializeComponent();
difficulty = 0;
isGameOn = false;
listOfRandom = new List<ListViewItem>();
volumeValue = 10;
indexNacinaPredvajanja = 0;
indexNacinaPonavljanja = 0;
videoPredvajanja = null;
audioPredvajanja = null;
imagePrikazovanja = null;
isLoaded = false;
randomNumber = new Random();
isPlaying = false;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void buttonVolumeUp_Click(object sender, EventArgs e)
{
changeVolume(1);
}
private void changeVolume(int value)
{
if (volumeIsMute)
{
try
{
videoPredvajanja.Audio.Volume = -10000;
}
catch(Exception ex)
{
}
try
{
audioPredvajanja.Volume = -10000;
}
catch(Exception ex)
{
}
}
else
{
if (volumeValue + value > 10)
volumeValue = 10;
else
if (volumeValue + value < 0)
volumeValue = 0;
else
volumeValue += value;
trackBarVolume.Value = volumeValue;
changeVolumePicture(volumeValue);
}
}
private void buttonVolumeDown_Click(object sender, EventArgs e)
{
changeVolume(-1);
}
private void changeVolumePicture(int value)
{
if (typeOfPlayingObject == 0 && videoPredvajanja != null)
{
videoPredvajanja.Audio.Volume = volumeValues[value];
}
else
{
if(typeOfPlayingObject==1 && audioPredvajanja != null)
audioPredvajanja.Volume = volumeValues[value];
}
if (volumeValue == 0)
panelVolume.BackgroundImage = Properties.Resources.Volume000;
else
if(volumeValue < 4)
panelVolume.BackgroundImage = Properties.Resources.Volume1;
else
if(volumeValue < 9)
panelVolume.BackgroundImage = Properties.Resources.Volume2;
else
panelVolume.BackgroundImage = Properties.Resources.Volume3;
}
private void trackBarVolume_Scroll(object sender, EventArgs e)
{
volumeValue = trackBarVolume.Value;
changeVolumePicture(volumeValue);
}
private void panelVolume_MouseClick(object sender, MouseEventArgs e)
{
if (volumeIsMute == true)
{
volumeIsMute = false;
changeVolumePicture(volumeValue);
}
else
{
volumeIsMute = true;
panelVolume.BackgroundImage = Properties.Resources.Volume000;
}
changeVolume(volumeValue);
}
private void buttonAddFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Izberi mapo";
if (fbd.ShowDialog() == DialogResult.OK)
{
string[] filePaths = Directory.GetFiles(fbd.SelectedPath);
foreach (string imeDatoteke in filePaths)
{
FileInfo fi = new FileInfo(imeDatoteke);
ListViewItem lvi = new ListViewItem(fi.Name);
lvi.Tag = fi.FullName;
listViewPlaylist.Items.Add(lvi);
}
generateRandomList();
}
}
private void buttonAddFile_Click(object sender, EventArgs e)
{
if (openFileDialogAddFiles.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach (string imeDatoteke in openFileDialogAddFiles.FileNames)
{
FileInfo fi = new FileInfo(imeDatoteke);
ListViewItem lvi = new ListViewItem(fi.Name);
lvi.Tag = fi.FullName;
listViewPlaylist.Items.Add(lvi);
}
generateRandomList();
}
}
private void buttonRemove_Click(object sender, EventArgs e)
{
if (listViewPlaylist.SelectedItems.Count > 0)
{
foreach (ListViewItem lvi in listViewPlaylist.SelectedItems)
listViewPlaylist.Items.Remove(lvi);
}
generateRandomList();
}
private void button4_Click(object sender, EventArgs e)
{
if (this.WindowState != FormWindowState.Maximized)
{
panelButtons.Anchor = AnchorStyles.Left;
panelShowing.Anchor = AnchorStyles.Left;
if (panelPlaylist.Visible == false)
{
panelPlaylist.Visible = true;
this.Width += 292;
this.MinimumSize = new Size(970, 502);
}
else
{
this.MinimumSize = new Size(678, 502);
panelPlaylist.Visible = false;
this.Width -= 292;
}
panelButtons.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
panelShowing.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
}
}
private void shraniSeznamToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialogPlaylist.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFileDialogPlaylist.FileName, false);
foreach (ListViewItem lvi in listViewPlaylist.Items)
{
sw.WriteLine(lvi.Tag.ToString());
}
sw.Flush();
sw.Close();
}
}
private void odpriSeznamToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialogPlaylist.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
listViewPlaylist.Clear();
StreamReader sr = new StreamReader(openFileDialogPlaylist.FileName);
while(!sr.EndOfStream)
{
FileInfo fi = new FileInfo(sr.ReadLine());
ListViewItem lvi = new ListViewItem(fi.Name);
lvi.Tag = fi.FullName;
listViewPlaylist.Items.Add(lvi);
}
sr.Close();
generateRandomList();
}
}
private void buttonPropertiesOfSpecifiedFile_Click(object sender, EventArgs e)
{
if (listViewPlaylist.SelectedItems.Count > 0)
{
foreach (ListViewItem lvi in listViewPlaylist.SelectedItems)
{
FormFileProperties ffp = new FormFileProperties(new FileInfo(lvi.Tag.ToString()));
ffp.Show();
}
}
}
private void buttonShuffle_Click(object sender, EventArgs e)
{
indexNacinaPredvajanja = (indexNacinaPredvajanja + 1) % 2;
labelNacinPredvajanja.Text = nacinPredvajanja[indexNacinaPredvajanja];
}
private void buttonRepeat_Click(object sender, EventArgs e)
{
indexNacinaPonavljanja = (indexNacinaPonavljanja + 1) % 3;
labelNacinPonavljanja.Text = nacinPonavljanja[indexNacinaPonavljanja];
}
private void listViewPlaylist_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (listViewPlaylist.SelectedItems.Count == 1)
{
indexOfPlayingObject = listViewPlaylist.SelectedItems[0].Index;
endGame();
playObject(listViewPlaylist.SelectedItems[0].Index);
}
}
private void unLoadObject()
{
if (videoPredvajanja != null)
{
videoPredvajanja.Stop();
videoPredvajanja.Dispose();
videoPredvajanja = null;
}
if (audioPredvajanja != null)
{
audioPredvajanja.Stop();
audioPredvajanja.Dispose();
audioPredvajanja = null;
}
if (imagePrikazovanja != null)
{
imagePrikazovanja = null;
}
}
private void loadObject(String pathOfObject, String nameOfObject)
{
buttonGame.Enabled = false;
isLoaded = false;
if(extensionsOfVideo.Contains(pathOfObject.Substring(pathOfObject.LastIndexOf('.') + 1).ToLower()))
{
typeOfPlayingObject = 0;
videoPredvajanja = new Video(pathOfObject);
Size size = panelShowing.Size;
videoPredvajanja.Owner = panelShowing;
panelShowing.Size = size;
textBoxImeDatoteke.Text = nameOfObject;
videoDuration = videoPredvajanja.Duration;
int ure = (int)(videoDuration / 3600);
int minute = (int)((videoDuration - (ure * 3600)) / 60);
int sekunde = (int)(videoDuration % 60);
textBoxTimeOfPlaying.Text = "00.00.00 / " + String.Format("{0,2:00}", ure) + ":" + String.Format("{0,2:00}", minute) + ":" + String.Format("{0,2:00}", sekunde);
isLoaded = true;
}
else
{
if (extensionsOfAudio.Contains(pathOfObject.Substring(pathOfObject.LastIndexOf('.') + 1).ToLower()))
{
typeOfPlayingObject = 1;
audioPredvajanja = new Audio(pathOfObject);
panelShowing.BackgroundImage = Properties.Resources.music_note;
textBoxImeDatoteke.Text = nameOfObject;
audioDuration = audioPredvajanja.Duration;
int ure = (int)(audioDuration / 3600);
int minute = (int)((audioDuration - (ure * 3600)) / 60);
int sekunde = (int)(audioDuration % 60);
textBoxTimeOfPlaying.Text = "00.00.00 / " + String.Format("{0,2:00}", ure) + ":" + String.Format("{0,2:00}", minute) + ":" + String.Format("{0,2:00}", sekunde);
isLoaded = true;
}
else
{
if (extensionsOfPicture.Contains(pathOfObject.Substring(pathOfObject.LastIndexOf('.') + 1).ToLower()))
{
typeOfPlayingObject = 2;
imagePrikazovanja = Image.FromFile(pathOfObject);
textBoxImeDatoteke.Text = nameOfObject;
textBoxTimeOfPlaying.Text = "00.00.00 / 00.00.00";
isLoaded = true;
buttonGame.Enabled = true;
}
else
{
MessageBox.Show("Izbrana datoteka ni podprta!", "Napaka pri odpiranju!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
if (isLoaded)
{
pathOfLoadedObject = pathOfObject;
}
else
{
pathOfLoadedObject = "";
}
playObject();
}
private void playObject()
{
if (typeOfPlayingObject == 0)
{
buttonPlayPause.BackgroundImage = Properties.Resources.MD_pause;
videoPredvajanja.Play();
trackBarCurrentPosition.Maximum = (int)videoDuration;
trackBarCurrentPosition.Value = 0;
timerCurrentPosition.Start();
}
if (typeOfPlayingObject == 1 )
{
buttonPlayPause.BackgroundImage = Properties.Resources.MD_pause;
audioPredvajanja.Play();
trackBarCurrentPosition.Maximum = (int)audioDuration;
trackBarCurrentPosition.Value = 0;
timerCurrentPosition.Start();
}
if (typeOfPlayingObject == 2)
{
panelShowing.BackgroundImage = imagePrikazovanja;
}
}
private void buttonPlayPause_Click(object sender, EventArgs e)
{
endGame();
if (videoPredvajanja != null)
{
if (typeOfPlayingObject == 0 && videoPredvajanja.Playing)
{
isPlaying = false;
buttonPlayPause.BackgroundImage = Properties.Resources.MD_play;
videoPredvajanja.Pause();
timerCurrentPosition.Stop();
}
else if (typeOfPlayingObject == 0)
{
isPlaying = true;
buttonPlayPause.BackgroundImage = Properties.Resources.MD_pause;
videoPredvajanja.Play();
trackBarCurrentPosition.Maximum = (int)videoDuration;
trackBarCurrentPosition.Value = 0;
timerCurrentPosition.Start();
}
}
if (audioPredvajanja != null)
{
if (typeOfPlayingObject == 1 && audioPredvajanja.Playing)
{
isPlaying = false;
buttonPlayPause.BackgroundImage = Properties.Resources.MD_play;
audioPredvajanja.Pause();
timerCurrentPosition.Stop();
}
else if (typeOfPlayingObject == 1)
{
isPlaying = true;
buttonPlayPause.BackgroundImage = Properties.Resources.MD_pause;
audioPredvajanja.Play();
trackBarCurrentPosition.Maximum = (int)audioDuration;
trackBarCurrentPosition.Value = 0;
timerCurrentPosition.Start();
}
}
if (typeOfPlayingObject == 2)
{
panelShowing.BackgroundImage = imagePrikazovanja;
}
}
private void buttonFullScreen_Click(object sender, EventArgs e)
{
if (typeOfPlayingObject == 0 && videoPredvajanja != null)
{
if (videoPredvajanja.Fullscreen == false)
{
sizeOfPanel = panelShowing.Size;
videoPredvajanja.Fullscreen = true;
}
else
{
videoPredvajanja.Fullscreen = false;
videoPredvajanja.Owner = panelShowing;
panelShowing.Size = sizeOfPanel;
}
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
endGame();
if (typeOfPlayingObject == 0 && videoPredvajanja != null)
{
videoPredvajanja.Stop();
}
if (typeOfPlayingObject == 1 && audioPredvajanja != null)
{
audioPredvajanja.Stop();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
refreshCurrentPositionOfVideo rcpov = new refreshCurrentPositionOfVideo(refreshCurrentPositionOfVideoFunction);
rcpov.Invoke();
}
private void refreshCurrentPositionOfVideoFunction()
{
if (typeOfPlayingObject == 0 && videoPredvajanja != null)
{
double trenutnaPozicija = videoPredvajanja.CurrentPosition;
int ure = (int)(videoDuration / 3600);
int minute = (int)((videoDuration - (ure * 3600)) / 60);
int sekunde = (int)(videoDuration % 60);
int ure1 = (int)(trenutnaPozicija / 3600);
int minute1 = (int)((trenutnaPozicija - (ure * 3600)) / 60);
int sekunde1 = (int)(trenutnaPozicija % 60);
textBoxTimeOfPlaying.BeginInvoke(new refrestTextBoxCurrentPosition(refreshTextBoxCurrentPositionFunction), new object[] { String.Format("{0,2:00}", ure1) + ":" + String.Format("{0,2:00}", minute1) + ":" + String.Format("{0,2:00}", sekunde1) + " / " + String.Format("{0,2:00}", ure) + ":" + String.Format("{0,2:00}", minute) + ":" + String.Format("{0,2:00}", sekunde) });
trackBarCurrentPosition.BeginInvoke(new refrestTrackBarCurrentPosition(refreshTrackBarCurrentPositionFunction), new object[] {(int)trenutnaPozicija });
if (videoPredvajanja.CurrentPosition >= videoPredvajanja.Duration)
{
this.BeginInvoke(new playNextObjectDel(playNextObject));
}
}
if (typeOfPlayingObject == 1 && audioPredvajanja != null)
{
double trenutnaPozicija = audioPredvajanja.CurrentPosition;
int ure = (int)(audioDuration / 3600);
int minute = (int)((audioDuration - (ure * 3600)) / 60);
int sekunde = (int)(audioDuration % 60);
int ure1 = (int)(trenutnaPozicija / 3600);
int minute1 = (int)((trenutnaPozicija - (ure * 3600)) / 60);
int sekunde1 = (int)(trenutnaPozicija % 60);
textBoxTimeOfPlaying.BeginInvoke(new refrestTextBoxCurrentPosition(refreshTextBoxCurrentPositionFunction), new object[] { String.Format("{0,2:00}", ure1) + ":" + String.Format("{0,2:00}", minute1) + ":" + String.Format("{0,2:00}", sekunde1) + " / " + String.Format("{0,2:00}", ure) + ":" + String.Format("{0,2:00}", minute) + ":" + String.Format("{0,2:00}", sekunde) });
trackBarCurrentPosition.BeginInvoke(new refrestTrackBarCurrentPosition(refreshTrackBarCurrentPositionFunction), new object[] { (int)trenutnaPozicija });
if (audioPredvajanja.CurrentPosition >= audioPredvajanja.Duration)
{
this.BeginInvoke(new playNextObjectDel(playNextObject));
}
}
}
private void refreshTrackBarCurrentPositionFunction(int value)
{
trackBarCurrentPosition.Value = value;
}
private void refreshTextBoxCurrentPositionFunction(String newString)
{
textBoxTimeOfPlaying.Text = newString;
}
private void timerCurrentPosition_Tick(object sender, EventArgs e)
{
try
{
backgroundWorkerRefreshingCurrentTimeOfPlaying.RunWorkerAsync();
}
catch (Exception ex)
{ }
}
private void trackBarCurrentPosition_Scroll(object sender, EventArgs e)
{
if (typeOfPlayingObject == 0 && videoPredvajanja != null)
{
videoPredvajanja.CurrentPosition = trackBarCurrentPosition.Value;
}
if (typeOfPlayingObject == 1 && audioPredvajanja != null)
{
audioPredvajanja.CurrentPosition = trackBarCurrentPosition.Value;
}
}
private void buttonSlower_Click(object sender, EventArgs e)
{
}
private void buttonProperties_Click(object sender, EventArgs e)
{
if (isLoaded)
{
FormFileProperties ffp = new FormFileProperties(new FileInfo(pathOfLoadedObject));
ffp.Show();
}
}
private void playNextObject()
{
switch (indexNacinaPredvajanja)
{
case 0: //Zaporedno
{
switch (indexNacinaPonavljanja)
{
case 0: //Ponovi vse
{
indexOfPlayingObject = (indexOfPlayingObject + 1) % listViewPlaylist.Items.Count;
playObject(indexOfPlayingObject);
break;
}
case 1: //Ponavljaj samo ta objekt
{
playObject(indexOfPlayingObject);
break;
}
case 2: //Ne ponovi
{
if ((indexOfPlayingObject + 1) == listViewPlaylist.Items.Count)
{
playObject(-1);
}
else
{
indexOfPlayingObject = (indexOfPlayingObject + 1) % listViewPlaylist.Items.Count;
playObject(indexOfPlayingObject);
}
break;
}
}
break;
}
case 1:
{
switch (indexNacinaPonavljanja)
{
case 0: //Ponovi vse
{
indexOfPlayingObject = (indexOfPlayingObject+1) % listViewPlaylist.Items.Count;
playRandomObject(indexOfPlayingObject);
break;
}
case 1: //Ponavljaj samo ta objekt
{
playRandomObject(indexOfPlayingObject);
break;
}
case 2: //Ne ponovi
{
indexOfPlayingObject = (indexOfPlayingObject + 1) % listViewPlaylist.Items.Count;
playRandomObject(indexOfPlayingObject);
break;
}
}
break;
}
}
}
private void playPreviousObject()
{
switch (indexNacinaPredvajanja)
{
case 0: //Zaporedno
{
switch (indexNacinaPonavljanja)
{
case 0: //Ponovi vse
{
indexOfPlayingObject = (indexOfPlayingObject - 1);
if (indexOfPlayingObject < 0)
indexOfPlayingObject = listViewPlaylist.Items.Count - 1;
playObject(indexOfPlayingObject);
break;
}
case 1: //Ponavljaj samo ta objekt
{
playObject(indexOfPlayingObject);
break;
}
case 2: //Ne ponovi
{
if ((indexOfPlayingObject -1) == -1)
{
playObject(-1);
}
else
{
indexOfPlayingObject = (indexOfPlayingObject - 1);
playObject(indexOfPlayingObject);
}
break;
}
}
break;
}
case 1:
{
switch (indexNacinaPonavljanja)
{
case 0: //Ponovi vse
{
indexOfPlayingObject = randomNumber.Next() % listViewPlaylist.Items.Count;
playObject(indexOfPlayingObject);
break;
}
case 1: //Ponavljaj samo ta objekt
{
playObject(indexOfPlayingObject);
break;
}
case 2: //Ne ponovi
{
indexOfPlayingObject = randomNumber.Next() % listViewPlaylist.Items.Count;
playObject(indexOfPlayingObject);
break;
}
}
break;
}
}
}
private void playObject(int indexOfObject)
{
if (indexOfObject >= 0)
{
unLoadObject();
loadObject(listViewPlaylist.Items[indexOfObject].Tag.ToString(), listViewPlaylist.Items[indexOfObject].Text);
}
else
{
unLoadObject();
}
}
private void playRandomObject(int indexOfObject)
{
if (indexOfObject >= 0)
{
unLoadObject();
loadObject(listOfRandom[indexOfObject].Tag.ToString(), listOfRandom[indexOfObject].Text);
}
else
{
unLoadObject();
}
}
private void buttonNext_Click(object sender, EventArgs e)
{
endGame();
playNextObject();
}
private void buttonPrevious_Click(object sender, EventArgs e)
{
endGame();
playPreviousObject();
}
private void buttonGame_Click(object sender, EventArgs e)
{
if (isGameOn == false)
{
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
if (typeOfPlayingObject == 2)
{
isGameOn = true;
premetanka = new Premetanka(imagePrikazovanja, panelShowing.Height, panelShowing.Width, this.difficulty);
panelShowing.BackgroundImage = premetanka.start();
}
}
else
{
endGame();
panelShowing.BackgroundImage = imagePrikazovanja;
}
}
private void endGame()
{
if (this.MinimumSize.IsEmpty)
{
this.MaximumSize = new Size(0, 0);
this.MinimumSize = new Size(970, 502);
}
isGameOn = false;
}
private void generateRandomList()
{
listOfRandom = new List<ListViewItem>();
foreach (ListViewItem lvi in listViewPlaylist.Items)
{
ListViewItem lviTemp = new ListViewItem(lvi.Text);
lviTemp.Tag = lvi.Tag;
listOfRandom.Add(lviTemp);
}
shuffle(listOfRandom);
}
private void shuffle(List<ListViewItem> listStrings)
{
Random rng = new Random();
int n = listStrings.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
ListViewItem valueTemp = listStrings[k];
listStrings[k] = listStrings[n];
listStrings[n] = valueTemp;
}
}
private void panelShowing_MouseClick(object sender, MouseEventArgs e)
{
if (isGameOn)
{
panelShowing.BackgroundImage = premetanka.mouseClicked(sender, e);
if (premetanka.isGameFinished())
{
MessageBox.Show(premetanka.getFinishedText());
isGameOn = false;
endGame();
panelShowing.BackgroundImage = imagePrikazovanja;
}
}
}
private void x3EnostavnoToolStripMenuItem_Click(object sender, EventArgs e)
{
difficulty = 0;
x3EnostavnoToolStripMenuItem.Checked = true;
x4LahkoToolStripMenuItem.Checked = false;
x5SrednjeToolStripMenuItem.Checked = false;
x6TežkoToolStripMenuItem.Checked = false;
}
private void x4LahkoToolStripMenuItem_Click(object sender, EventArgs e)
{
difficulty = 1;
x3EnostavnoToolStripMenuItem.Checked = false;
x4LahkoToolStripMenuItem.Checked = true;
x5SrednjeToolStripMenuItem.Checked = false;
x6TežkoToolStripMenuItem.Checked = false;
}
private void x5SrednjeToolStripMenuItem_Click(object sender, EventArgs e)
{
difficulty = 2;
x3EnostavnoToolStripMenuItem.Checked = false;
x4LahkoToolStripMenuItem.Checked = false;
x5SrednjeToolStripMenuItem.Checked = true;
x6TežkoToolStripMenuItem.Checked = false;
}
private void x6TežkoToolStripMenuItem_Click(object sender, EventArgs e)
{
difficulty = 3;
x3EnostavnoToolStripMenuItem.Checked = false;
x4LahkoToolStripMenuItem.Checked = false;
x5SrednjeToolStripMenuItem.Checked = false;
x6TežkoToolStripMenuItem.Checked = true;
}
private void panelVolume_Paint(object sender, PaintEventArgs e)
{
}
}
}
| 722ff37aefbe9903d9e7b8f57766a4aebb312faf | [
"C#"
] | 3 | C# | cvirnus/RobiCvirnPraktikum | b36b4b1c2bc3c0d7e7d002e2ff339851d10f1388 | 0879d91a63f3392f0bf9d59dfa4ae45d11ed3e1e |
refs/heads/master | <file_sep>buildings = [
[2,9,10], // b#1
[3,7,15], // b#2
[5,12,12], // b#3
[15,20,10], // b#4
[19,24,8] // b#5
]
var getSkyline = function(buildings) {
var height=[];
for(var i=0; i<buildings.length; i++) {
var building = buildings[i];
height.push([building[0], -building[2]]);
height.push([building[1], building[2]]);
}
height.sort(function(a, b){
if(a[0]!=b[0]){
return a[0]-b[0];
}
return a[1]-b[1];
});
var currentHeight={0:true};
var previous=0, result=[];
for(var i=0; i<height.length; i++) {
var h= height[i];
if(h[1]<0) {
currentHeight[-h[1]]= currentHeight[-h[1]]?currentHeight[-h[1]]+1:1;
} else {
currentHeight[h[1]]--;
if(currentHeight[h[1]]==0) {
delete currentHeight[h[1]];
}
}
var current=0;
for(var key in currentHeight) {
if(key-0>current) {
current=key-0;
}
}
if(previous!=current) {
result.push([h[0], current]);
previous=current;
}
}
return result;
};
<file_sep># problems
please check here for the test code answer.
| a80703f729ad06909956c28145fc6030fc32274b | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ThomasAbear/problems | a429cc7ea12020525941dd0977771a4482fc7c30 | e0e02372ad53cc97271df99476250eb911dae807 |
refs/heads/master | <repo_name>Iannery/SBTRAB1<file_sep>/Montador.h
/****************************************
* Trabalho 1 - Software Basico *
* *
* <NAME> *
* 170144739 *
* *
* Versao do compilador: *
* g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0 *
* *
****************************************/
#ifndef MONTADOR_BIB
#define MONTADOR_BIB
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
class Montador {
public:
Montador(string asm_path_to_file);
~Montador();
void inicializar_processo(string command);
private:
void preprocess();
void mount();
void macro_handler();
void macro_identifier();
void macro_expander();
void macro_argument_finder(string declaration_line, int macro_count);
void if_equ_handler();
void first_passage();
void second_passage();
string asm_path, preprocessed_path, mounted_path, line;
vector<string> directive_list;
vector<pair<string, int>> symbol_table, opcode_list;
vector<string> macro_command_list1, macro_command_list2;
string macro_label1, macro_label2, macro_command;
string macro1_arg1, macro1_arg2, macro2_arg1, macro2_arg2;
};
#endif<file_sep>/README.txt
/****************************************
* Trabalho 1 - Software Basico *
* *
* <NAME> *
* 170144739 *
* *
* Versao do compilador: *
* g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0 *
* *
****************************************/
O trabalho consiste de um Programa que simula um montador, fazendo tanto o pré-processamento quanto a montagem do arquivo .asm.
O resultado da execução do pré-processamento e montagem é visto nos arquivos .pre e .obj, respectivamente.
Os comandos necessários são:
- Para compilar o programa:
g++ main.cpp Montador.cpp -o montador
- Para pré-processar o arquivo .asm com o programa, gerando o arquivo .pre:
./montador -p myprogram.asm
- Para montar o arquivo .pre com o programa, gerando o arquivo .obj:
./montador -o myprogram.pre<file_sep>/main.cpp
/****************************************
* Trabalho 1 - Software Basico *
* *
* <NAME> *
* 170144739 *
* *
* Versao do compilador: *
* g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0 *
* *
****************************************/
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include "Montador.h"
using namespace std;
int main(int argc, char* argv[]) {
string command = argv[1];
string file = argv[2];
// passa para o construtor do montador o nome do arquivo .asm
Montador* montador = new Montador(file);
// passa para a inicializacao do montador o comando "-p" ou "-o"
montador->inicializar_processo(command);
return 0;
}<file_sep>/Montador.cpp
/****************************************
* Trabalho 1 - Software Basico *
* *
* <NAME> *
* 170144739 *
* *
* Versao do compilador: *
* g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0 *
* *
****************************************/
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <bits/stdc++.h>
#include "Montador.h"
using namespace std;
Montador::Montador(string asm_path_to_file){
this->asm_path = asm_path_to_file;
this->preprocessed_path = this->asm_path.substr(0, this->asm_path.find(".")) + ".pre"; // utiliza o asm_path para criar um path do arquivo .pre
this->mounted_path = this->asm_path.substr(0, this->asm_path.find(".")) + ".obj"; // utiliza o asm_path para criar um path do arquivo .obj
// inicializacao das strings de macro
this->macro_label1 = "";
this->macro_label2 = "";
this->macro_command = "";
this->macro1_arg1 = "";
this->macro1_arg2 = "";
this->macro2_arg1 = "";
this->macro2_arg2 = "";
}
/* > incializar_processo(command)
* Recebe o comando "-p" ou "-o" para determinar se o programa ira pre-processar ou montar
*/
void Montador::inicializar_processo(string command){
this->directive_list.push_back("SPACE");
this->directive_list.push_back("CONST");
// opcode de valor 0 necessário para o indice da lista bater com o codigo do opcode
this->opcode_list.push_back(make_pair("NEVERCALLED", 0));
this->opcode_list.push_back(make_pair("ADD", 2));
this->opcode_list.push_back(make_pair("SUB", 2));
this->opcode_list.push_back(make_pair("MULT", 2));
this->opcode_list.push_back(make_pair("DIV", 2));
this->opcode_list.push_back(make_pair("JMP", 2));
this->opcode_list.push_back(make_pair("JMPN", 2));
this->opcode_list.push_back(make_pair("JMPP", 2));
this->opcode_list.push_back(make_pair("JMPZ", 2));
this->opcode_list.push_back(make_pair("COPY", 3));
this->opcode_list.push_back(make_pair("LOAD", 2));
this->opcode_list.push_back(make_pair("STORE", 2));
this->opcode_list.push_back(make_pair("INPUT", 2));
this->opcode_list.push_back(make_pair("OUTPUT", 2));
this->opcode_list.push_back(make_pair("STOP", 1));
if (command == "-o"){
this->mount();
}
else if (command == "-p"){
this->preprocess();
}
else{
cerr << "Erro no comando!" << endl;
}
}
/* > preprocess()
* Abre o arquivo .asm, cria o arquivo .pre, retira os comentarios, substitui os char's por maiusculas,
* troca tabs por espacos, remove linhas vazias e chama os handlers de macro e if/equ.
*/
void Montador::preprocess(){
ifstream asm_file;
ofstream preprocessed_file;
asm_file.open(this->asm_path);
preprocessed_file.open(this->preprocessed_path);
if (!asm_file.is_open()){
cerr << "Erro na abertura do arquivo .asm";
}
else if (!preprocessed_file.is_open()){
cerr << "Erro na abertura do arquivo .pre";
}
else{
while (asm_file.good()){
getline(asm_file, this->line); // pega linha do arquivo .asm
this->line = this->line.substr(0, this->line.find(";")); // retira os comentarios
transform(
this->line.begin(),
this->line.end(),
this->line.begin(),
::toupper); // substitui todos os char por maiusculas
replace(this->line.begin(), this->line.end(), '\t', ' '); // retira tabs
if(this->line[this->line.length() - 1] == ' '){ // retira espacos no final de comandos
this->line = this->line.substr(0, this->line.length() -1);
}
if (!this->line.empty()){ // coloca no arquivo pre-processado caso a linha nao seja vazia
preprocessed_file << this->line + "\n";
}
}
asm_file.close();
preprocessed_file.close();
macro_handler();
if_equ_handler();
}
}
/* > macro_argument_finder(declaration_line, macro_count)
* Recebe a primeira linha de declaracao do macro e um contador que determina se ele eh o primeiro ou
* o segundo macro do programa. Acha quais sao os argumentos do determinado macro e os coloca nas
* variaveis de classe.
*/
void Montador::macro_argument_finder(string declaration_line, int macro_count){
int macro_arg1_pos = 0,
macro_arg2_pos = 0,
occurrences = 0,
flag_space_comma = 0;
string arg_substr; // string com tudo depois da substring "MACRO ", que sao os argumentos.
arg_substr = declaration_line.substr(declaration_line.find("MACRO") + 5, declaration_line.length());
if(arg_substr.length() > 1){ // se existe algo depois da substring "MACRO ", ou seja, argumento
for(size_t i = 1; i < arg_substr.length(); i++){
if(arg_substr.at(i) == '&'){ // se acha algum '&' significa que achou um argumento
occurrences++; // determina quantos argumentos tem no macro
if(occurrences == 1){
macro_arg1_pos = i; // determina a posicao do inicio do argumento 1 na string.
}
else if(occurrences == 2){
macro_arg2_pos = i; // determina a posicao do inicio do argumento 2 na string, caso exista
}
}
}
for(int i = macro_arg1_pos; i <= macro_arg2_pos; i++){ // roda a string entre as posicoes do arg1 e arg2
// subrotina para determinar se os dois argumentos estao separados por ',' ou por ", "
if(arg_substr.at(i) == ','){
flag_space_comma++;
if(arg_substr.at(i+1) == ' '){
flag_space_comma++; // acresce a flag que vai auxiliar na separacao entre os dois argumentos
}
}
}
if(macro_count == 1){ // se for o primeiro macro do programa
switch(occurrences){ // dependendo do numero de argumentos
case 1: // seta o primeiro argumento na variavel de classe
this->macro1_arg1 = arg_substr.substr(macro_arg1_pos, arg_substr.length());
break;
case 2: // seta os dois argumentos nas respectivas variaveis de classe
this->macro1_arg1 = arg_substr.substr(macro_arg1_pos, macro_arg2_pos - (flag_space_comma + 1));
this->macro1_arg2 = arg_substr.substr(macro_arg2_pos, arg_substr.length());
break;
}
}
else if(macro_count == 2){ // faz o mesmo processo que foi feito no if acima
switch(occurrences){
case 1:
this->macro2_arg1 = arg_substr.substr(macro_arg1_pos, arg_substr.length());
break;
case 2:
this->macro2_arg1 = arg_substr.substr(macro_arg1_pos, macro_arg2_pos - (flag_space_comma + 1));
this->macro2_arg2 = arg_substr.substr(macro_arg2_pos, arg_substr.length());
break;
}
}
}
}
/* > macro_identifier()
* Abre o arquivo pre-processado e identifica onde existem as declaracoes de macro, para adiciona-las a
* listas de strings, para depois serem expandidos onde forem chamadas
*/
void Montador::macro_identifier(){
int macro_count = 0;
ifstream preprocessed_file;
preprocessed_file.open(this->preprocessed_path);
if (preprocessed_file.is_open()){
while (preprocessed_file.good()){
getline(preprocessed_file, this->line); // recebe linha do arquivo pre-processado
if (this->line.find("MACRO") != std::string::npos){ // se nessa linha existir a string "MACRO"
macro_count++; // acresce a quantidade de macros presentes no programa
if (macro_count == 1){ // se ainda so existe um macro na funcao
macro_argument_finder(this->line, macro_count); // acha os argumentos do macro 1
this->macro_label1 = this->line.substr(0, this->line.find(":")); // recebe a label do macro 1
while (this->line.find("ENDMACRO") == std::string::npos){ // enquanto nao acha a substring "ENDMACRO"
getline(preprocessed_file, this->line); // recebe linha do arquivo preprocessado
this->macro_command = this->line;
this->macro_command_list1.push_back(this->macro_command); // coloca a linha na lista de comandos da macro 1
}
this->macro_command_list1.pop_back(); // retira a linha que possui o "ENDMACRO" da lista
}
else if (macro_count == 2){ // comportamento analogo a quando o macro_count == 1
macro_argument_finder(this->line, macro_count);
this->macro_label2 = this->line.substr(0, this->line.find(":"));
while (this->line.find("ENDMACRO") == std::string::npos){
getline(preprocessed_file, this->line);
this->macro_command = this->line;
this->macro_command_list2.push_back(this->macro_command);
}
this->macro_command_list2.pop_back();
}
else{
cerr << "Existem mais do que dois macros no programa." << endl;
}
}
}
}
preprocessed_file.close();
}
/* > macro_expander()
* Expande os macros cujas labels foram identificadas pelo macro_identifier
*/
void Montador::macro_expander(){
int macro_position_begin, macro_position_end, macro_begin_flag = 0, macro_label_position;
ifstream preprocessed_file_in;
ofstream preprocessed_file_out;
string command_line, macro_label_arg1 = "", macro_label_arg2 = "";
vector<string> command_list, macro_command_list1_local, macro_command_list2_local;
preprocessed_file_in.open(this->preprocessed_path);
if (preprocessed_file_in.is_open()){
while (preprocessed_file_in.good()){
getline(preprocessed_file_in, this->line);
if(!this->line.empty()){
command_list.push_back(this->line); // coloca as linhas do arquivo em uma lista de strings
}
}
preprocessed_file_in.close();
// subrotina que retira as diretivas de declaracao de macro da lista command_list
for (size_t i = 0; i < command_list.size(); i++){
command_line = command_list.at(i);
// procura a diretiva "MACRO" e marca sua posicao
if (command_line.find("MACRO") != std::string::npos
&& !macro_begin_flag){
macro_position_begin = i;
macro_begin_flag = 1;
}
// procura a diretiva "ENDMACRO" e remove tudo entre elas
else if (command_line.find("ENDMACRO") != std::string::npos){
macro_position_end = i;
command_list.erase(
command_list.begin() + macro_position_begin,
command_list.begin() + macro_position_end + 1);
macro_begin_flag = 0;
i = 0;
}
}
// fim da subrotina
for (size_t i = 0; i < command_list.size(); i++){
command_line = command_list.at(i);
// EXPANDE AS MACROS DA LABEL 1
// se existe a substring de label, se nao e uma declaracao de label, ou seja, utiliza ":" e se
// existe alguma label salva na macro_identifier
if (command_line.substr(0, command_line.find(" ")) == this->macro_label1
&& command_line.find(":") == std::string::npos
&& !this->macro_label1.empty()){
macro_label_position = this->macro_label1.length() + 1; // posicao da substring que contem os argumentos, se houver algum
if(!macro1_arg2.empty()){ // se o argumento 2 existe, ou seja, se a macro_argument_finder achou dois argumentos
// separa os argumentos passados pela chamada da primeira macro
macro_label_arg1 = command_line.substr(macro_label_position, command_line.find(" "));
macro_label_arg2 = macro_label_arg1.substr(macro_label_arg1.find(",") + 1, macro_label_arg1.length());
macro_label_arg1 = macro_label_arg1.substr(0, macro_label_arg1.find(","));
if(macro_label_arg1.at(0) == ' '){ // retira espacos caso haja algum no inicio da string do argumento
macro_label_arg1.erase(0, 1);
}
if(macro_label_arg2.at(0) == ' '){ // retira espacos caso haja algum no inicio da string do argumento
macro_label_arg2.erase(0, 1);
}
// recebe a lista de comandos do macro1 para uma lista local, para nao alterar nada na lista original
macro_command_list1_local = this->macro_command_list1;
for(size_t j = 0; j < macro_command_list1_local.size(); j++){
// procura o primeiro argumento original declarado no macro
if(macro_command_list1_local.at(j).find(macro1_arg1) != std::string::npos){
// substitui o primeiro argumento original pelo primeiro argumento utilizado pela chamada do macro
macro_command_list1_local.at(j).replace(
macro_command_list1_local.at(j).find(macro1_arg1),
macro1_arg1.length(),
macro_label_arg1
);
}
// comportamento analogo ao if acima, para o segundo argumento da macro
if(macro_command_list1_local.at(j).find(macro1_arg2) != std::string::npos){
macro_command_list1_local.at(j).replace(
macro_command_list1_local.at(j).find(macro1_arg2),
macro1_arg2.length(),
macro_label_arg2
);
}
}
}
else if(!macro1_arg1.empty()){ // se somente o argumento 1 existe
// separa o argumento passado pela chamada da primeira macro
macro_label_arg1 = command_line.substr(macro_label_position, command_line.length());
// recebe a lista de comandos do macro1 para uma lista local, para nao alterar nada na lista original
macro_command_list1_local = this->macro_command_list1;
for(size_t j = 0; j < macro_command_list1_local.size(); j++){
// procura o argumento original declarado no macro
if(macro_command_list1_local.at(j).find(macro1_arg1) != std::string::npos){
// substitui na lista de comandos o argumento original pelo argumento utilizado pela chamada do macro
macro_command_list1_local.at(j).replace(
macro_command_list1_local.at(j).find(macro1_arg1),
macro1_arg1.length(),
macro_label_arg1
);
}
}
}
else{
// caso nao haja argumentos, somente passa a lista de comandos da macro para a lista local
macro_command_list1_local = this->macro_command_list1;
}
command_list.erase(command_list.begin() + i); // remove a linha de chamada da macro no programa
// coloca no lugar da linha removida a lista de comandos da macro, com os argumentos ja substituidos
command_list.insert(
command_list.begin() + i,
macro_command_list1_local.begin(),
macro_command_list1_local.end()
);
}
// EXPANDE AS MACROS DA LABEL 2
// O COMPORTAMENTO DE EXPANSAO DAS MACROS DA LABEL 2 E IDENTICO AO COMPORTAMENTO
// DE EXPANSAO DAS MACROS DA LABEL 1, PORTANTO NAO SERAO DOCUMENTADOS
if (command_line.substr(0, command_line.find(" ")) == this->macro_label2
&& command_line.find(":") == std::string::npos
&& !this->macro_label2.empty()){
macro_label_position = this->macro_label2.length() + 1;
if(!macro2_arg2.empty()){
macro_label_arg1 = command_line.substr(macro_label_position, command_line.find(","));
macro_label_arg2 = macro_label_arg1.substr(macro_label_arg1.find(",") + 1, macro_label_arg1.length());
macro_label_arg1 = macro_label_arg1.substr(0, macro_label_arg1.find(","));
if(macro_label_arg1.at(0) == ' '){
macro_label_arg1.erase(0, 1);
}
if(macro_label_arg2.at(0) == ' '){
macro_label_arg2.erase(0, 1);
}
macro_command_list2_local = this->macro_command_list2;
for(size_t j = 0; j < macro_command_list1_local.size(); j++){
if(macro_command_list2_local.at(j).find(macro2_arg1) != std::string::npos){
macro_command_list2_local.at(j).replace(
macro_command_list2_local.at(j).find(macro2_arg1),
macro2_arg1.length(),
macro_label_arg1
);
}
if(macro_command_list2_local.at(j).find(macro2_arg2) != std::string::npos){
macro_command_list2_local.at(j).replace(
macro_command_list2_local.at(j).find(macro2_arg2),
macro2_arg2.length(),
macro_label_arg2
);
}
}
}
else if(!macro2_arg1.empty()){
macro_label_arg1 = command_line.substr(macro_label_position, command_line.length());
macro_command_list2_local = this->macro_command_list2;
for(size_t j = 0; j < macro_command_list2_local.size(); j++){
if(macro_command_list2_local.at(j).find(macro2_arg1) != std::string::npos){
macro_command_list2_local.at(j).replace(
macro_command_list2_local.at(j).find(macro2_arg1),
macro2_arg1.length(),
macro_label_arg1
);
}
}
}
else{
macro_command_list2_local = this->macro_command_list2;
}
command_list.erase(command_list.begin() + i);
command_list.insert(
command_list.begin() + i,
macro_command_list2_local.begin(),
macro_command_list2_local.end()
);
}
}
remove(this->preprocessed_path.c_str()); // remove o arquivo .pre existente anteriormente
preprocessed_file_out.open(this->preprocessed_path);
// reescreve o arquivo .pre com a remocao de declaracao de macro, e expansao destes nas suas chamadas
for (size_t i = 0; i < command_list.size(); i++){
preprocessed_file_out << command_list.at(i) << "\n";
}
preprocessed_file_out.close();
}
}
/* > if_equ_handler()
* trata as chamadas das diretivas de EQU's e IF's presentes no codigo, e as remove do arquivo .pre
*/
void Montador::if_equ_handler(){
vector<string> command_list;
vector< pair <string,string> > equ_statements;
string equ_label = "",
equ_value = "",
if_value = "";
ifstream preprocessed_file_in;
ofstream preprocessed_file_out;
preprocessed_file_in.open(this->preprocessed_path);
if (preprocessed_file_in.is_open()){
while (preprocessed_file_in.good()){
getline(preprocessed_file_in, this->line);
command_list.push_back(this->line); // passa as linhas do arquivo .pre para uma lista de comandos
}
}
preprocessed_file_in.close();
//IDENTIFICACAO DO EQU
//Inicializa a lista de pares {string,string} para lidar com as declaracoes de EQU e seus valores
for(size_t i = 0; i < command_list.size(); i++){
if(command_list.at(i).find("EQU") != std::string::npos){ // se acha a declaracao do "EQU"
// guarda a label do EQU, para depois ser feita a substituicao onde ela for chamada
equ_label = command_list.at(i).substr(
0,
command_list.at(i).find(":")
);
// guarda o valor do EQU, para ser feita a substituicao da label pelo valor onde for chamada
equ_value = command_list.at(i).substr(
command_list.at(i).find("EQU") + 4,
command_list.at(i).length()
);
// coloca na lista de pares a label com o seu respectivo valor
equ_statements.push_back(make_pair(equ_label, equ_value));
// retira da lista de comandos a declaracao do EQU
command_list.erase(command_list.begin() + i);
i--;
}
}
// SUBSTITUICAO DAS LABELS PELO VALOR DO EQU
for(size_t i = 0; i < command_list.size(); i++){
for(size_t j = 0; j < equ_statements.size(); j++){
// se acha alguma label presente na lista de pares em alguma linha da lista de comandos
if(command_list.at(i).find(equ_statements.at(j).first) != std::string::npos){
// substitui a label presente pelo seu respectivo valor
command_list.at(i).replace(
command_list.at(i).find(equ_statements.at(j).first),
equ_statements.at(j).first.length(),
equ_statements.at(j).second
);
}
}
}
// CHECA SE VAI SER COMPUTADO O IF OU NAO
for(size_t i = 0; i < command_list.size(); i++){
if(command_list.at(i).find("IF") != std::string::npos){ // se achar a diretiva IF
// recebe o valor do IF
if_value = command_list.at(i).substr(
command_list.at(i).find("IF") + 3,
command_list.at(i).length()
);
// caso o valor do IF for diferente de 1 ou variacoes
if(if_value != "1"
&& if_value != "1 "
&& if_value != " 1"
&& if_value != " 1 "){
// deleta o IF junto com a linha abaixo dele
command_list.erase(
command_list.begin() + i,
command_list.begin() + i+2
);
}
// caso contrario
else{
// deleta apenas a linha do IF
command_list.erase(command_list.begin() + i);
}
i--;
}
}
remove(this->preprocessed_path.c_str());
preprocessed_file_out.open(this->preprocessed_path);
// reescreve o arquivo .pre com as diretivas de IF e EQU devidamente tratadas
for (size_t i = 0; i < command_list.size(); i++){
preprocessed_file_out << command_list.at(i) << "\n";
}
preprocessed_file_out.close();
}
/* > macro_handler()
* Chama as funcoes de identificacao e expansao dos macros
*/
void Montador::macro_handler(){
macro_identifier();
macro_expander();
}
/* > first_passage()
* Faz a primeira passagem do montador, que consiste em identificar as labels presentes no codigo e
* popular a tabela de simbolos, que neste algoritmo eh uma lista de pares {string,int}, onde o primeiro
* elemento eh a label e o segundo elemento eh a sua posicao da memoria do programa em assembly.
*/
void Montador::first_passage(){
int superscription_error_flag = 0,
position_counter = 0;
pair <string,int> aux_pair;
vector<string> command_list, command_line;
string symbol_label = "";
ifstream preprocessed_file_in;
preprocessed_file_in.open(this->preprocessed_path);
if (preprocessed_file_in.is_open()){
while (preprocessed_file_in.good()){
getline(preprocessed_file_in, this->line);
command_list.push_back(this->line); // coloca as linhas do arquivo em uma lista de strings
}
}
preprocessed_file_in.close();
for(size_t i = 0; i < command_list.size(); i++){
superscription_error_flag = 0;
// subrotina para separar todas as substrings de uma linha da lista de comandos
istringstream iss(command_list.at(i));
command_line.clear();
for(string s; iss >> s;){
command_line.push_back(s);
}
// fim da subrotina
for(auto& s: command_line){ // para cada substring, ou "token", da linha de comando
if(s.find(":") != std::string::npos){ // se achar um :, quer dizer que existe uma declaracao de label
// retira o : da substring e coloca numa string separada
symbol_label = s.substr(
0,
s.length() - 1
);
// caso essa label ja exista na tabela de simbolos, sobe uma flag de erro para nao sobrescreve-la
for(size_t j = 0; j < this->symbol_table.size(); j++){
if(this->symbol_table.at(j).first == symbol_label){
superscription_error_flag = 1;
}
}
// caso nao tenha dado o erro de sobrescricao da label, coloca a label na tabela de simbolos,
// junto com a sua posicao de memoria do programa
if(!superscription_error_flag){
aux_pair = make_pair(symbol_label, position_counter);
this->symbol_table.push_back(aux_pair);
}
}
// se a substring for um opcode, soma no contador de posicao de memoria do programa o "valor de memoria" desse opcode
for(size_t j = 0; j < this->opcode_list.size(); j++){
if(this->opcode_list.at(j).first == s){
position_counter += this->opcode_list.at(j).second;
}
}
// se a substring for uma diretiva, ou seja, "SPACE" ou "CONST", soma um ao contador de posicao.
for(size_t j = 0; j < this->directive_list.size(); j++){
if(this->directive_list.at(j) == s){
position_counter += 1;
}
}
}
}
// for(size_t i = 0; i < this->symbol_table.size(); i++){
// cout << this->symbol_table.at(i).first << '\t' << this->symbol_table.at(i).second << endl;
// }
}
/* > second_passage()
* A segunda passagem substitui as chamadas de label pela sua posicao de memoria,
* transforma os opcodes em seus respectivos codigos e passa todos os codigos para o arquivo .obj
*/
void Montador::second_passage(){
int flag_const = 0,
flag_section_text = 0,
flag_section_data = 0;
vector<int> object_list;
vector<string> command_list, command_line;
string symbol_label = "";
ifstream preprocessed_file;
ofstream mounted_file;
preprocessed_file.open(this->preprocessed_path);
if (preprocessed_file.is_open()){
while (preprocessed_file.good()){
getline(preprocessed_file, this->line);
command_list.push_back(this->line); // passa as linhas do arquivo .pre para uma lista de comandos
}
}
preprocessed_file.close();
// para cada linha da lista de comandos
for(size_t i = 0; i < command_list.size(); i++){
// se a linha mostrar que esta na secao de texto, sobe a flag que esta nela ate ir para a secao de dados
if(command_list.at(i) == "SECTION TEXT"){
flag_section_text = 1;
flag_section_data = 0;
}
// se a linha mostrar que esta na secao de dados, sobe a flag que esta nela
else if(command_list.at(i) == "SECTION DATA"){
flag_section_text = 0;
flag_section_data = 1;
}
// subrotina para eliminar a virgula entre os argumentos do opcode COPY
if(command_list.at(i).find("COPY") != std::string::npos){
command_list.at(i).erase(
remove(
command_list.at(i).begin(),
command_list.at(i).end(),
','),
command_list.at(i).end()
);
}
// fim da subrotina
// subrotina para separar todas as substrings de uma linha da lista de comandos
istringstream iss(command_list.at(i));
command_line.clear();
for(string s; iss >> s;){
command_line.push_back(s);
}
// fim da subrotina
for(auto& s: command_line){ // para cada substring da linha de comando
// se estiver dentro da secao de texto
if(flag_section_text){
for(size_t j = 1; j < this->opcode_list.size(); j++){
// se a substring for um opcode, coloca na lista de objetos o codigo do opcode
if(s == this->opcode_list.at(j).first){
int converter = static_cast<int>(j);
object_list.push_back(converter);
}
}
for(size_t j = 0; j < this->symbol_table.size(); j++){
// se a substring for uma label, varre a tabela de simbolos ate encontrar, e entao
// coloca na lista de objetos a posicao de memoria gravada na tabela
if(s == this->symbol_table.at(j).first){
object_list.push_back(this->symbol_table.at(j).second);
}
}
}
else if(flag_section_data){
// se a substring anterior tivesse sido CONST
// coloca na lista de objetos o valor inteiro do valor desse const
if(flag_const){
object_list.push_back(stoi(s));
flag_const = 0;
}
// se a substring for a diretiva SPACE coloca um "0" na lista de objetos
else if(s == this->directive_list.at(0)){
object_list.push_back(0);
}
// se a substring for a diretiva CONST,
// sobe a flag para armazenar a proxima substring na lista de objetos
else if(s == this->directive_list.at(1)){
flag_const = 1;
}
}
}
}
// cria o arquivo .obj e coloca nele a lista de objetos criada acima, separando os objetos com " "
mounted_file.open(this->mounted_path);
if (!mounted_file.is_open()){
cerr << "Erro na abertura do arquivo .obj";
}
else{
for(size_t i = 0; i < object_list.size(); i++){
if(i < object_list.size() - 1){
mounted_file << object_list.at(i) << " ";
}
else{
mounted_file << object_list.at(i) << "\n";
}
}
}
mounted_file.close();
// for(size_t i = 0; i < object_list.size(); i++){
// if(i < object_list.size() - 1){
// cout << object_list.at(i) << " ";
// }
// else{
// cout << object_list.at(i) << "\n";
// }
// }
}
/* > mount()
* Chama a primeira passagem e segunda passagem do montador
*/
void Montador::mount(){
first_passage();
second_passage();
} | a929381dc6d0d79c1e358eb964571da9b927885f | [
"Text",
"C++"
] | 4 | C++ | Iannery/SBTRAB1 | b2cd0967a6585c109ee74a45c7e932cb3c9790ad | 5ba068b29547de4c9a96dcfea1ca5edcf0924eaa |
refs/heads/master | <repo_name>azeezat/Products-Web<file_sep>/README.md
# Products Web
product information portal
### Local Setup
A step by step series of examples that tell you how to get a development environment running
Clone the repo from github and install dependencies through npm.
```
git clone https://github.com/azeezat/Products-Web.git
cd produts-web
npm install
npm start
```
<file_sep>/src/Routes/Routes.js
import React from 'react';
import CreateProduct from '../components/Products/CreateProducts/CreateProduct';
import ViewProduct from '../components/Products/ViewProduct/ViewProduct'
import { BrowserRouter, Route, Switch } from "react-router-dom";
const Routes = () => {
return (
<BrowserRouter>
<Switch>
<Route exact path='/' component={CreateProduct} />
<Route exact path='/view' component={ViewProduct} />
</Switch>
</BrowserRouter>
);
};
export default Routes<file_sep>/src/components/Products/CreateProducts/CreateProduct.js
import React, { Component } from 'react';
import { requestsService } from '../../../services/requests.service';
import { SUCCESS_RESPONSE } from '../../../constants/constants';
import { GET_ALL_PRODUCTS } from '../../../constants/apis';
import './CreateProduct.css'
class CreateProduct extends Component {
state = {
products: []
}
componentDidMount() {
this.fetchAllProducts()
}
fetchAllProducts = () => {
return requestsService.makeGetRequest(GET_ALL_PRODUCTS)
.then(res => {
if (res.status === SUCCESS_RESPONSE) {
this.setState({ products: res.response.data })
}
})
.catch(error => {
});
}
CreateProduct = (e) => {
e.preventDefault()
const { name, description, price, image, category, colour } = this.state
const payload = {
name,
description,
price,
image,
category,
colour
}
return requestsService.makePostRequest(GET_ALL_PRODUCTS, payload)
.then(res => {
if (res.status === SUCCESS_RESPONSE) {
this.setState({ products: res.response.data })
}
})
.catch(error => {
});
}
handleChange = (e) => {
e.persist()
this.setState(() => ({ [e.target.name]: e.target.value }))
}
render() {
return (
<div>
<div className="container"> </div>
<div className="form">
<h2>Create A new Product</h2>
<form onSubmit={this.CreateProduct} onChange={this.handleChange}>
<div className="form-inner">
<input type="text" placeholder="Name" name="name" />
<input type="text" placeholder="Description" name="description" />
<input type="number" placeholder="Price" name="price" />
<input type="text" placeholder="Image" name="image" />
<input type="text" placeholder="Category" name="category" />
<input type="text" placeholder="Colour" name="colour" />
</div>
<input type="submit" className="btn" />
</form>
</div>
</div>
);
}
}
export default CreateProduct; | 807371c970512384d56a18f6e40b0de515b53f33 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | azeezat/Products-Web | 8b7054400342c8f105a73e70a1b6e4de307aa94f | df824c4d6b94fd0284d7a3191bf55aa45e530904 |
refs/heads/master | <file_sep>rootProject.name = 'stack-tracker'
<file_sep>Stack-tracker
=============
Uses the javassist api to trace the sequence of all methods that get called when a given method is called.
<file_sep>apply plugin: 'java'
apply plugin: 'maven'
group = 'stack-tracker'
version = '1.0-SNAPSHOT'
description = """"""
sourceCompatibility = 1.5
targetCompatibility = 1.5
repositories {
mavenRepo urls: ["https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/"]
mavenRepo urls: ["http://repo.maven.apache.org/maven2"]
}
dependencies {
compile "org.javassist:javassist:3.18.0-GA"
testCompile "org.testng:testng:6.1.1"
}
task wrapper(type: Wrapper)
<file_sep>package org.bhooshan.projects.stacktracker;
import javassist.*;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
/**
* Created with IntelliJ IDEA.
* User: bhooshan
* Date: 10/8/13
* Time: 7:47 AM
* To change this template use File | Settings | File Templates.
*/
public class StackTracker {
private ClassPool classPool = null;
public StackTracker() {
this(null);
}
public StackTracker(ClassPath classPath) {
initialize(classPath);
}
private void initialize(ClassPath classPath) {
classPool = ClassPool.getDefault();
if (classPath != null) {
classPool.appendClassPath(classPath);
}
}
public void go(String className, String methodName) throws NotFoundException, CannotCompileException {
CtClass ctClass = classPool.getCtClass(className);
CtMethod ctMethod = ctClass.getDeclaredMethod(methodName);
ctMethod.instrument(
new ExprEditor() {
public void edit(MethodCall mc) {
try {
System.out.println(mc.getClassName() + "." + mc.getMethod() + " " + mc.getSignature() + " " + mc.getLineNumber());
} catch (NotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
);
}
public static void main(String [] args) throws NotFoundException, CannotCompileException {
/*if(args.length < 3) {
usage();
}
String classpath = args[0];
String classz = args[1];
String method = args[2];*/
StackTracker stackTracker = new StackTracker();
stackTracker.go("java.lang.Object", "toString");
}
private static void usage() {
System.out.println("Stack Tracker!");
System.out.println("Usage:");
System.out.println("java org.bhooshan.projects.stacktracker.StackTracker <classpath> <classname> <methodname>");
System.exit(1);
}
}
<file_sep>#Fri Feb 21 09:31:27 PST 2014
| 0050f7d5eacd563b7e683087c171780d4c3e1329 | [
"Markdown",
"Java",
"INI",
"Gradle"
] | 5 | Gradle | bdmogal/stack-tracker | 1929e474912d5cddf064fe645dcdf69b6972cee1 | 5265610d29f6f09d9bdbb5a70f4c4f7729446aeb |
refs/heads/master | <file_sep># Puppeteer Lab
A lap for experimentation with puppeteer
## goto
Run
```shell
node goto.js
```
to view benchmark for reading a local html file with `goto`.
## goto:waitUntil
Run
```shell
node goto_waitUntil.js
```
to view benchmark for reading a local html file with `goto` with `waitUntil: networkidle2`.
## setContent
Run
```shell
node setContent.js
```
to view benchmark for reading a local html file with `setContent`.
## setContent:waitUntil
Run
```shell
node setContent_waitUntil.js
```
to view benchmark for reading a local html file with `setContent` with `waitUntil: networkidle2`.
<file_sep>module.exports = {
filePath: './sample/sample.html'
}
<file_sep>const puppeteer = require('puppeteer')
const {filePath} = require('./config')
async function run() {
let browser = await puppeteer.launch()
const page = await browser.newPage()
console.time('goto')
await page.goto(`file://${filePath}`)
console.timeEnd('goto')
await page.pdf({path: './pdfs/goto.pdf'})
await browser.close()
}
run()
<file_sep>const puppeteer = require('puppeteer')
const fs = require('fs')
const {filePath} = require('./config')
async function run() {
const html = fs.readFileSync(filePath, 'utf8')
const browser = await puppeteer.launch()
const page = await browser.newPage()
console.time('setContent:waitUntil')
await page.setContent(html, {
waitUntil: 'networkidle0'
})
console.timeEnd('setContent:waitUntil')
await page.pdf({path: './pdfs/setContent_waituntil.pdf'})
await browser.close()
}
run()
| af74d474622ac0132e26662c81e1b3843e8712f3 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | varshard/puppeteer-lab | 2c15f26dbef5f074062f24ed9cc912ce60fb010e | 7ac56de1aa3f55d1a87d11b8b24bfdbf1b5a2c10 |
refs/heads/master | <repo_name>lojorob9/boxProject<file_sep>/java.js
$(".box1").click(function(){
$(this).toggleClass("darkMode");
}); | db698b98abb1ace4a389822d5e72baef69e09be3 | [
"JavaScript"
] | 1 | JavaScript | lojorob9/boxProject | 35ce5a5b298486577ff72206132c9d43f7313185 | ab0b74b99ee3f0bbf0dc5096eeb2636876147a5f |
refs/heads/master | <file_sep>import asyncio
import websockets
class ProtocolStateMachine:
def __init__(self, name):
self._name = name
class ProtocolV1:
def __init__(self):
self._connections = dict()
print(f"LOG: CREATED PROTOCOL")
async def initialize(self, websocket, path):
print(f"LOG: INITIALIZING")
await self.connect(websocket, path)
async def connect(self, websocket, path):
name = await websocket.recv()
print(f"LOG: CLIENT NAME {name}")
self._connections[name] = ProtocolStateMachine(name)
await websocket.send("CONNECTED")
await self.handle_message(websocket, path)
async def handle_message(self, websocket, path):
message = await websocket.recv()
if message == "LIST":
for i in range(4):
await websocket.send(f"DEVICE {i}")
if __name__ == "__main__":
protocol = ProtocolV1()
start_server = websockets.serve(protocol.initialize, "localhost", 1234)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
| 29383bc25eca88f041b779c4cbf758e2b1740cf1 | [
"Python"
] | 1 | Python | fernanlukban/sdp | 786b811f88c6964350712b90674613c3dacc760b | 83f5b585ebb90f357285e7a759202376c7d2d683 |
refs/heads/master | <repo_name>Snehabhatt61/product<file_sep>/src/Components/ProductName.js
import React from 'react';
import { Link } from "react-router-dom";
class ProductName extends React.Component {
render(){
let productId = localStorage.getItem('currentId');
const ProductLists = this.props.productName;
return (
<div className="row">
<div className="col-12 product-name-box">
<p className="product-name m-0">{ProductLists.map(item => item[0].productName)}</p>
<Link
to={`/`}
className="product-name m-0"
onClick = {() => localStorage.setItem('currentId', parseInt(productId) + 1)}
> --></Link>
</div>
</div>
);
}
}
export default ProductName;<file_sep>/src/App.js
import React from 'react';
import { BrowserRouter, Route, Switch } from "react-router-dom";
import './App.css';
import ProductDescription from './json'
import Product from './Components/Product';
class App extends React.Component {
constructor(props){
super(props);
this.state = {
currentId : 1
}
localStorage.setItem("currentId", 1);
}
componentDidMount =() => {
this.setState({
currentId : parseInt(localStorage.getItem("currentId"))
})
console.log("ID",this.state.currentId ,parseInt(localStorage.getItem("currentId")) );
console.log("called")
}
render () {
const ProductLists = ProductDescription;
return (
<div>
<BrowserRouter basename={'/products'}>
<Switch>
<Route
exact
path="/"
component={Product}
/>
</Switch>
</BrowserRouter>
</div>
);
}
}
export default App;
<file_sep>/src/json.js
const ProductDescription = [{
product4 : [{
id: 4,
heading : "Nutmilk Packs",
description: "Why try our delicious Nuthing Else nutmilks ? They contain 5x more nuts and 5x more proteins than the other nutmilks",
productName: "Shop Lattes"
}],
product3 : [{
id:3,
heading : "Classic Green Juice",
description: "Replace your morning coffee with a green juice to feel energized for the day.All celery, cucumber and greens.",
productName: "Shop Green Juice"
}],
product2 : [{
id: 2,
heading : "Juices & Smoothies",
description: "All our organic cold-pressed juices, organic cold-pressed green juices, and our plant-based smoothies.",
productName: "Shop Juices"
}],
product1 : [{
id : 1,
heading : "Meet our Cleanses",
description: "Organic Cold-Pressed Juice Cleanses.It’s the perfect way to reset your body and build the foundation fora healthier lifestyle.",
productName: "Shop cleanses"
}]
}]
export default ProductDescription;<file_sep>/src/Components/Progress.js
import React, {Fragment } from 'react';
import { Progress } from 'reactstrap';
export default class Example extends React.Component {
constructor(props){
super(props);
}
setValue = () => {
const ProductLists = this.props.product;
let abc = ProductLists.map(item => item[0].id)
console.log("rs",abc)
let vc = abc.find(ele => ele);
console.log("vccccccc",vc)
switch (vc) {
case 1 :
return "25";
case 2 :
return "50" ;
case 3 :
return 75;
case 4 :
return 100;
default : return 25
}
}
render(){
const ProductLists = this.props.product;
console.log("propsList", ProductLists)
return (
<Fragment>
<div className="progress-div">
<a href="#" className="progress_arrow">❮ </a>
<div className="progress_status--container">
<span className="progress_status-no pr-3">0{ProductLists.map(item => item[0].id)}</span>
<Progress value={this.setValue()} className="widthd" />
<span className="progre ss_status-no pl-3">04</span>
</div>
<a href="#" className="progress_arrow">❭ </a>
</div>
</Fragment>
)}}<file_sep>/src/Components/ProductImage.js
import React, {Fragment } from 'react';
import ProductDescription from '../json'
class ProductImage extends React.Component {
constructor(props){
super(props);
}
render(){
const ProductLists = this.props.product;
console.log("props", ProductLists)
return (
<div className="">
<img src = "/images/image1.jpg" alt = "lost" className="image-size"
/>
</div>
);
}
}
export default ProductImage; | 5e6632c2862e2839de49d90f66fa714cb3297e51 | [
"JavaScript"
] | 5 | JavaScript | Snehabhatt61/product | a901123f2a1ed1ac48d5803462ec61ac34e2ebcf | b82805e95b6442e01e2a60401ddbed6b7b146b3d |
refs/heads/master | <file_sep><?php
/*
* Paiement Bancaire
* module de paiement bancaire multi prestataires
* stockage des transactions
*
* Auteurs :
* <NAME>, Nurs<EMAIL>
* (c) 2012-2019 - Distribue sous licence GNU/GPL
*
*/
if (!defined('_ECRIRE_INC_VERSION')){
return;
}
// securite : on initialise une globale le temps de la config des prestas
if (isset($GLOBALS['meta']['bank_paiement'])
AND $GLOBALS['config_bank_paiement'] = unserialize($GLOBALS['meta']['bank_paiement'])){
foreach ($GLOBALS['config_bank_paiement'] as $nom => $config){
if (strncmp($nom, "config_", 7)==0
AND isset($config['actif'])
AND $config['actif']
AND isset($config['presta'])
AND $presta = $config['presta']){
// inclure le fichier config du presta correspondant
include_spip("presta/$presta/config");
}
}
// securite : on ne conserve pas la globale en memoire car elle contient des donnees sensibles
unset($GLOBALS['config_bank_paiement']);
}
if (!function_exists('affiche_monnaie')){
function affiche_monnaie($valeur, $decimales = 2, $unite = true){
if ($unite===true){
$unite = " EUR";
if (substr(trim($valeur), -1)=="%"){
$unite = " %";
}
}
if (!$unite){
$unite = "";
}
return sprintf("%.{$decimales}f", $valeur) . $unite;
}
}
/**
* Fonction appelee par la balise #PAYER_ACTE et #PAYER_ABONNEMENT
* @param array|string $config
* string dans le cas "gratuit" => on va chercher la config via bank_config()
* @param string $type
* @param int $id_transaction
* @param string $transaction_hash
* @param array|string|null $options
* @return string
*/
function bank_affiche_payer($config, $type, $id_transaction, $transaction_hash, $options = null){
// compatibilite ancienne syntaxe, titre en 4e argument de #PAYER_XXX
if (is_string($options)){
$options = array(
'title' => $options,
);
}
// invalide ou null ?
if (!is_array($options)){
$options = array();
}
// $config de type string ?
include_spip('inc/bank');
if (is_string($config)){
$config = bank_config($config, $type=='abo');
}
$quoi = ($type=='abo' ? 'abonnement' : 'acte');
if ($payer = charger_fonction($quoi, 'presta/' . $config['presta'] . '/payer', true)){
return $payer($config, $id_transaction, $transaction_hash, $options);
}
spip_log("Pas de payer/$quoi pour presta=" . $config['presta'], "bank" . _LOG_ERREUR);
return "";
}
/**
* Afficher le bouton pour gerer/interrompre un abonnement
* @param array|string $config
* @param string $abo_uid
* @return array|string
*/
function bank_affiche_gerer_abonnement($config, $abo_uid){
// $config de type string ?
include_spip('inc/bank');
if (is_string($config)){
$config = bank_config($config, true);
}
if ($trans = sql_fetsel("*", "spip_transactions", $w = "abo_uid=" . sql_quote($abo_uid) . ' AND mode LIKE ' . sql_quote($config['presta'] . '%') . " AND " . sql_in('statut', array('ok', 'attente')), '', 'id_transaction')){
$config = bank_config($trans['mode']);
$fond = "modeles/gerer_abonnement";
if (trouver_fond($f = "presta/" . $config['presta'] . "/payer/gerer_abonnement")){
$fond = $f;
}
return recuperer_fond($fond, array('presta' => $config['presta'], 'id_transaction' => $trans['id_transaction'], 'abo_uid' => $abo_uid));
}
return "";
}
/**
* Trouver un logo pour un presta donne
* Historiquement les logos etaient des .gif, possiblement specifique aux prestas
* On peut les surcharger par un .png (ou un .svg a partir de SPIP 3.2.5)
* @param $mode
* @param $logo
* @return bool|string
*/
function bank_trouver_logo($mode, $logo){
static $svg_allowed;
if (is_null($svg_allowed)){
$svg_allowed = false;
// _SPIP_VERSION_ID definie en 3.3 et 3.2.5-dev
if (defined('_SPIP_VERSION_ID') and _SPIP_VERSION_ID>=30205){
$svg_allowed = true;
} else {
$branche = explode('.', $GLOBALS['spip_version_branche']);
if ($branche[0]==3 and $branche[1]==2 and $branche[2]>=5){
$svg_allowed = true;
}
}
}
if (substr($logo, -4)=='.gif'
and $f = bank_trouver_logo($mode, substr(strtolower($logo), 0, -4) . ".png")){
return $f;
}
if ($svg_allowed
and substr($logo, -4)=='.png'
and $f = bank_trouver_logo($mode, substr(strtolower($logo), 0, -4) . ".svg")){
return $f;
}
// d'abord dans un dossier presta/
if ($f = find_in_path("presta/$mode/logo/$logo")){
return $f;
} // sinon le dossier generique
elseif ($f = find_in_path("bank/logo/$logo")) {
return $f;
}
return "";
}
/**
* Annoncer SPIP + plugin&version pour les logs de certains providers
* @param string $format
* @return string
*/
function bank_annonce_version_plugin($format = 'string'){
$infos = array(
'name' => 'SPIP ' . $GLOBALS['spip_version_branche'] . ' + Bank',
'url' => 'https://github.com/nursit/bank',
'version' => '',
);
include_spip('inc/filtres');
if ($info_plugin = chercher_filtre("info_plugin")){
$infos['version'] = 'v' . $info_plugin("bank", "version");
}
if ($format==='string'){
return $infos['name'] . $infos['version'] . '(' . $infos['url'] . ')';
}
return $infos;
} | 2bc9c1b5862752a64e95fd2957fc79dc8e7f48c0 | [
"PHP"
] | 1 | PHP | tofulm/bank | e16f52df3bdc7739b617d376d439a216f9e74d0f | 6c07c9be0b816403380c6a42e86d19d462159c97 |
refs/heads/main | <file_sep>Dataset on which the model is trained is avilable at kaggle over [here](https://www.kaggle.com/c/facial-keypoints-detection/data)
## Dependencies
1. OpenCV
2. Matplotlib
3. Numpy
4. Keras
5. Tensorflow
## Usage
Run [camera.py] to see the results
<file_sep>import cv2
import numpy as np
from model import FaceKeypointsCaptureModel
def apply_filter(frame, pts_dict):
left_eye_center_x = pts_dict["left_eye_center_x"]
left_eye_center_y = pts_dict["left_eye_center_y"]
left_eye_inner_corner_x = pts_dict["left_eye_inner_corner_x"]
left_eye_inner_corner_y = pts_dict["left_eye_inner_corner_y"]
left_eye_outer_corner_x = pts_dict["left_eye_outer_corner_x"]
left_eye_outer_corner_y = pts_dict["left_eye_outer_corner_y"]
left_eyebrow_outer_end_x = pts_dict["left_eyebrow_outer_end_x"]
left_eyebrow_outer_end_y = pts_dict["left_eyebrow_outer_end_y"]
radius_left = distance((left_eye_center_x, left_eye_center_y),
(left_eye_inner_corner_x, left_eye_inner_corner_y))
right_eye_center_x = pts_dict["right_eye_center_x"]
right_eye_center_y = pts_dict["right_eye_center_y"]
right_eye_outer_corner_x = pts_dict["right_eye_outer_corner_x"]
right_eye_outer_corner_y = pts_dict["right_eye_outer_corner_y"]
right_eye_inner_corner_x = pts_dict["right_eye_inner_corner_x"]
right_eye_inner_corner_y = pts_dict["right_eye_inner_corner_y"]
right_eyebrow_outer_end_x = pts_dict["right_eyebrow_outer_end_x"]
right_eyebrow_outer_end_y = pts_dict["right_eyebrow_outer_end_y"]
radius_right = distance((right_eye_center_x, right_eye_center_y),
(right_eye_inner_corner_x, right_eye_inner_corner_y))
radius_eyes = distance((right_eye_center_x, right_eye_center_y),
(right_eyebrow_outer_end_x, right_eyebrow_outer_end_y))
length_eyes = distance((left_eye_center_x, left_eye_center_y),
(right_eye_outer_corner_x, right_eye_outer_corner_y))
mouth_center_top_lip_x = pts_dict["mouth_center_top_lip_x"]
mouth_center_top_lip_y = pts_dict["mouth_center_top_lip_y"]
mouth_center_bottom_lip_x = pts_dict["mouth_center_bottom_lip_x"]
mouth_center_bottom_lip_y = pts_dict["mouth_center_bottom_lip_y"]
height_mouth = distance((mouth_center_top_lip_x, mouth_center_top_lip_y),
(mouth_center_bottom_lip_x, mouth_center_bottom_lip_y))
mouth_left_corner_x = pts_dict["mouth_left_corner_x"]
mouth_left_corner_y = pts_dict["mouth_left_corner_y"]
mouth_right_corner_x = pts_dict["mouth_right_corner_x"]
mouth_right_corner_y = pts_dict["mouth_right_corner_y"]
length_mouth = distance((mouth_left_corner_x, mouth_left_corner_y),
(mouth_right_corner_x, mouth_right_corner_y))
nose_tip_x = pts_dict["nose_tip_x"]
nose_tip_y = pts_dict["nose_tip_y"]
face_length = int(1.7 * distance((mouth_left_corner_x, mouth_left_corner_y),
(mouth_right_corner_x, mouth_right_corner_y)))
face_height = int(3 * distance((nose_tip_x, nose_tip_y),
(mouth_center_top_lip_x, mouth_center_top_lip_y)))
filterpath = "GuyFawkes";
frame = apply_filter_eye_helper(frame, int(left_eye_center_x), int(left_eye_center_y), int(radius_left))
frame = apply_filter_eye_helper(frame, int(right_eye_center_x), int(right_eye_center_y), int(radius_right))
#frame = apply_filter_mouth_helper(frame, int((left_eye_inner_corner_x+right_eye_inner_corner_x)/2),
# int((left_eye_inner_corner_y+right_eye_inner_corner_y)/2), int(length_eyes), int(radius_eyes), filterpath)
#frame = apply_filter_mouth_helper(frame, int(nose_tip_x),
# int(nose_tip_y), int(face_length), int(face_height), filterpath)
frame = apply_filter_mouth_helper(frame, int(mouth_center_top_lip_x),
int(mouth_center_top_lip_y), int(length_mouth), int(height_mouth), 'moustache')
return frame
def apply_filter_eye_helper(frame, x, y, radius):
adjust_rad = radius - 3
filter_img = cv2.resize(cv2.imread("filters/sharingan.png"),
(2*adjust_rad, 2*adjust_rad))
slice = frame[y-adjust_rad:y+adjust_rad, x-adjust_rad:x+adjust_rad, :]
for i in range(slice.shape[2]):
for j in range(slice.shape[1]):
slice[filter_img[:, j, i] != 0, j, i] = filter_img[filter_img[:, j, i]!=0, j, i]
frame[y-adjust_rad:y+adjust_rad, x-adjust_rad:x+adjust_rad, :] = slice
return frame
def apply_filter_mouth_helper(frame, x, y, radius, height, filterpath):
adjust_rad = radius - 3
filter_img = cv2.resize(cv2.imread(f"filters/{filterpath}.png",cv2.IMREAD_UNCHANGED),
(2*radius,2*height))
filter_img = cv2.cvtColor(filter_img, cv2.COLOR_RGB2RGBA).copy()
slice = frame[y-height:y+height , x-radius:x+radius, :]
channels = slice.shape[2]
alpha_s = filter_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s
for c in range(channels):
slice[: , :, c] = (alpha_s * filter_img[:, :, c] +
alpha_l * slice[: , :, c])
#for i in range(slice.shape[2]):
#for j in range(slice.shape[1]):
#slice[filter_img[:, j, i] != 0, j, i] = filter_img[filter_img[:, j, i]!=0, j, i]
#frame[y-height:y+height , x-radius:x+radius, :] = slice
return frame
def distance(pt1, pt2):
pt1 = np.array(pt1)
pt2 = np.array(pt2)
return np.sqrt(sum((pt1-pt2)**2))
if __name__ == '__main__':
model = FaceKeypointsCaptureModel("face_model.json", "face_model.h5")
import matplotlib.pyplot as plt
import cv2
img = cv2.cvtColor(cv2.imread('dataset/trial1.jpg'), cv2.COLOR_BGR2GRAY)
img1 = cv2.resize(img, (96, 96))
img1 = img1[np.newaxis, :, :, np.newaxis]
print(img1.shape)
pts, pts_dict = model.predict_points(img1)
pts1, pred_dict1 = model.scale_prediction((0, 200), (0, 200))
fr = apply_filter(img, pred_dict1)
plt.figure(0)
plt.imshow(fr, cmap='gray')
plt.show() | b918c54a88ed56a9441b3ae105fa02d655dddf1d | [
"Markdown",
"Python"
] | 2 | Markdown | PrateekSharma9399/Facial-Feature-Recognition-project-NN | 8fa7d9d8e83c144ec82ab4c9e4a76666e615a740 | 4ef8ee6e58c6ed546b7be81e4475a868d25f0361 |
refs/heads/master | <file_sep>const CONSOLEIMAGE = document.querySelector(".consoleImage");
function flip() {
CONSOLEIMAGE.transform = "scaleX(-1)";
}
CONSOLEIMAGE.addEventListener("click", flip(), false);
//CONSOLEIMAGE != null ? console.log("It worked!") : console.log("Try again");
| 449a3d030d1682df00f4076c94afeb9f01aab91b | [
"JavaScript"
] | 1 | JavaScript | SHorne41/Website-MyLifeInBlogForm | 983f872d34fcfc1f5c342570c4df62444443afec | 034ebea0b66ac829192e82799f191c1d93919f07 |
refs/heads/master | <file_sep>## Scraping script, written for gathering data about the groups in meetup.com, for capturing the various attributes:-
## 1. Data of the group, its founders, date of forming, total members, location, etc.
## 2. The genres/description associated with the groups.
## 3. Information about the members of the groups.
## 4. Individual interests of the members.
## 5. Other meetup groups, which a member of a particular group is also a part of.
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests
import warnings
from time import sleep
import sys
from random import randint
import re
import pickle
import time
import os
import time
from IPython.display import clear_output
pd.options.display.max_rows=1000
warnings.filterwarnings('ignore')
file_path = '/home/manish/Data/meetup_groups_clean_28MAR2017.xlsx'
xls = pd.ExcelFile(file_path)
df_metadata = pd.read_excel(xls,sheet_name = 'META DATA')
df_comicmeetupmaster = pd.read_excel(xls,sheet_name = 'COMICMEETUP_MASTER')
df_latlong = pd.read_excel(xls, sheet_name = 'lat_long',header = None,names = ['CITY','STATE','LAT','LONG'])
df_founders = pd.read_excel(xls, sheet_name = 'FOUNDERS')
df_members = pd.read_excel(xls, sheet_name = 'MEMBERS', skip_blank_lines=False)
## Data Manipulation
df_metadata.columns = df_metadata.columns.str.replace(' ','_')
df_comicmeetupmaster.columns = df_comicmeetupmaster.columns.str.lstrip()
df_comicmeetupmaster.columns = df_comicmeetupmaster.columns.str.replace(' ','_')
df_latlong.columns = df_latlong.columns.str.replace(' ','_')
df_founders.columns = df_founders.columns.str.replace(' ','_')
df_members.columns = df_members.columns.str.replace(' ','_')
pickle_path = '/home/manish/Scraping/variable_state.pkl'
#os.remove(pickle_path)
base_urls = df_comicmeetupmaster.GROUP_URLs
base_urls = base_urls[:-1]
x_init = -1
new_base_urls_init = base_urls[x_init+1:]
final_index_init = 0
meetup_group_list_init = []
if not os.path.isfile(pickle_path):
with open(pickle_path,'wb') as f:
pickle.dump([x_init,final_index_init, new_base_urls_init,meetup_group_list_init],f)
if os.path.isfile(pickle_path):
with open(pickle_path,'rb') as f:
x,final_index,new_base_urls,meetup_group_list = pickle.load(f)
new_base_urls = new_base_urls[x+1:]
final_index += x+1
for no,url in enumerate(new_base_urls):
#clear_output()
print("Starting with Iteration no {0} of the URLs".format(final_index+no))
grp_name = None; past_meetups = []; city = None; state = None; total_members = None; group_privacy=None; founder = [];
founding_date = None; about_list = None; offset_upper_limit = []
time.sleep(1)
page = requests.get(url)
soup = BeautifulSoup(page.content,'html.parser')
if page.status_code == 200:
try:
final_list = []
grp_name = soup.find('a',class_ = 'groupHomeHeader-groupNameLink').get_text()
for temp in soup.find_all('h3', class_ = 'text--sectionTitle text--bold padding--bottom'):
if('past meetups' in temp.get_text().lower()):
past_meetups.append(temp.get_text())
city,state = soup.find('a', class_ = 'groupHomeHeaderInfo-cityLink').get_text().split(', ')
total_members = soup.find('a', class_ = 'groupHomeHeaderInfo-memberLink').get_text()
group_privacy = soup.find('span', class_ = 'infoToggle-label').get_text()
member_url = url+'members'
member_page = requests.get(member_url)
member_soup = BeautifulSoup(member_page.content,'html.parser')
found = member_soup.find('span',id = 'meta-leaders').find_all('a',class_ = 'memberinfo-widget')
if len(found)>1:
for f in found:
founder.append(f.get_text())
else:
founder = member_soup.find('span',id = 'meta-leaders').find('a',class_ = 'memberinfo-widget').get_text()
founding_date = member_soup.find('div', class_ = 'small margin-bottom').get_text()
about_us = member_soup.find('div',class_ = 'meta-topics-block small margin-bottom').find_all('a')
about_list = []
for a in about_us:
about_list.append(a.get_text())
offset_upper_limit = int(re.findall(r'/?offset=(\d+)\&',member_soup.find('a', class_ = 'nav-next')['href'])[0])
total_members_list = []
print('Extracting data of total {0}'.format(total_members))
print_key = 0
for n in np.arange(0,offset_upper_limit+20,20):
memberships_url = member_url+'?offset=' + str(n) + '&sort=social&desc=1'
total_member_page = requests.get(memberships_url)
total_member_soup = BeautifulSoup(total_member_page.content,'html.parser')
total_members_iterate = total_member_soup.find('ul',id = 'memberList').find_all('a', class_ = 'memName')
for i,t in enumerate(total_members_iterate):
unique_member_id = None; member_name = None; unique_member_url = None;
unique_member_id = int(re.findall(r'(?:members/)(\d+)',t['href'])[0])
member_name = t.get_text()
unique_member_url = t['href']
unique_member = requests.get(unique_member_url)
unique_member_soup = BeautifulSoup(unique_member.content,'html.parser')
unique_city = None; unique_state = None; unique_member_since = None
unique_member_number_of_other_groups=None; others = None; status = None
try:
unique_city = unique_member_soup.find('span',class_ = 'locality', itemprop = 'addressLocality').get_text()
unique_state = unique_member_soup.find('span',class_ = 'region', itemprop = 'addressRegion').get_text()
unique_member_since = unique_member_soup.find('div', id = 'D_memberProfileMeta').find_all('div',
'D_memberProfileContentItem')[1].p.get_text()
try:
unique_member_number_of_other_groups = int(re.findall(r'\d+',
unique_member_soup.find('div', class_ = 'D_memberProfileGroups').find('div',
class_ = 'block-list-header rounded-corner-top clearfix').find('h3',
class_ = 'big flush--bottom').get_text().strip('\n'))[0])
except:
status = 'Absent'
other_groups = None
if(status != 'Absent'):
others = unique_member_soup.find('div', class_ = 'see-more-groups').find('a',
class_ = 'canDo')['href']
if(others):
other_groups_soup = BeautifulSoup(requests.get(others).content,'html.parser')
other_groups = other_groups_soup.find('ul', id = 'my-meetup-groups-list').find_all('li')
else:
other_groups = unique_member_soup.find('ul', id = 'my-meetup-groups-list').find_all('li')
unique_member_other_groups = []
if(other_groups):
for o in other_groups:
unique_member_other_groups.append(o.find('div', class_ = 'D_name bold').get_text())
unique_member_interests = None
unique_member_interests = [x.get_text() for x in unique_member_soup.find('div',
class_ = 'interest-topics').find('ul',
id = 'memberTopicList').li.div.find_all('a')]
except:
pass
total_members_list.append([unique_member_id,member_name,unique_city, unique_state,
unique_member_since, unique_member_number_of_other_groups,
unique_member_other_groups, unique_member_interests])
print_key += 1
print('Total members done till now ---> {0}/{1}'.format(print_key,total_members),end = '\r')
final_list.append([grp_name,past_meetups, city, state, total_members, group_privacy, founder, founding_date,
about_list, total_members_list])
meetup_group_list.append(final_list)
except:
pass
else:
meetup_group_list.append('Url not working')
x= no
with open(pickle_path,'wb') as f:
pickle.dump([x, final_index, new_base_urls, meetup_group_list],f)
print("Done with Iteration no {0} of the URLs".format(final_index+no))
<file_sep>## This script loads all the scraped data saved in the pickle file, and organise and structure the data accordingly
## into separate csv files
import numpy as np
import pandas as pd
import re
import pickle
pickle_path = '/home/manish/Scraping/variable_state.pkl'
with open(pickle_path,'rb') as f:
x,final_index,new_base_urls,meetup_group_list= pickle.load(f)
final_columns = ['Group_name','Past_meetups','City','State','Total_members','Group_Privacy','Founders','Founding_date']
df_prep = [x[0][:-2] if len(x) ==1 else ['Url not working'] for x in meetup_group_list]
new_df = pd.DataFrame(df_prep)
new_df.columns = final_columns
for i,x in enumerate(new_df.Past_meetups):
if (x is not None):
if(len(x)>0):
new_df.Past_meetups[i] = re.findall(r'[\d,]+',x[0])[0]
for i,x in enumerate(new_df.Total_members):
if (x is not None):
if(len(x)>0):
new_df.Total_members[i] = re.findall(r'[\d,]+',x)[0]
for i,x in enumerate(new_df.Founding_date):
if (x is not None):
if(len(x)>0):
new_df.Founding_date[i] = x.replace('\n',' ').strip().replace('Founded ','')
about_us_dict = {}
for rows in meetup_group_list:
if(len(rows)==1):
about_us_dict[rows[0][0]] = rows[0][-2]
members_df_prep = []
temp = []
for rows in meetup_group_list:
if(len(rows)==1):
for r in rows[0][-1]:
temp = [r[0]]
temp.extend([rows[0][0],r[1],r[2],r[3],r[4],r[5]])
members_df_prep.append(temp)
members_df = pd.DataFrame(members_df_prep)
members_df.columns = ['Unique_ID','Group_Name','Member_Name','City','State','Joining_date','Other_groups']
members_other_groups_dict = {}
for rows in meetup_group_list:
if(len(rows)==1):
for r in rows[0][-1]:
#members_other_groups_dict[r[0]] = [rows[0][0]]
members_other_groups_dict[r[0]] = r[6]
members_interests_dict = {}
for rows in meetup_group_list:
if(len(rows)==1):
for r in rows[0][-1]:
#members_interests_dict[r[0]] = [rows[0][0]]
members_interests_dict[r[0]] = r[7]
new_df.to_csv('/home/manish/Scraping/Scrapped_Groups_Data.csv')
with open('About_Us.csv', 'w') as f:
f.write('\n\n\n')
for key in about_us_dict.keys():
f.write('{0}\n'.format(key))
for val in about_us_dict[key]:
f.write('{0}\n'.format(val))
f.write('\n')
members_df.to_csv('/home/manish/Scraping/Members_Info.csv')
with open('Members_Other_Groups.csv', 'w') as f:
f.write('\n\n\n')
for key in members_other_groups_dict.keys():
f.write('{0}\n'.format(key))
if members_other_groups_dict[key] is not None:
for val in members_other_groups_dict[key]:
f.write('{0}\n'.format(val))
f.write('\n')
with open('Members_Interests.csv', 'w') as f:
f.write('\n\n\n')
for key in members_interests_dict.keys():
f.write('{0}\n'.format(key))
if members_interests_dict[key] is not None:
for val in members_interests_dict[key]:
f.write('{0}\n'.format(val))
f.write('\n')
<file_sep># Meetup-groups_Data-Scraping-and-Analysis
1.Descriptive Analysis of various Meetup-groups data from the website www.meetup.com and deriving meaningful insights from it.
2.1-2.3 Scraping the meetup website to collect and gather data for every group, about its founders, members, location, interests of the member of the groups, genres of groups, other groups a particular member is part of.
For the scraping, owing to the vast number of member URLs, for every Group, which the script had to hit, devised an ingenious mechanism for storing the state of the data captured and dumping them into pickle file, ensuring that on server failure or normal interruption of the script, the scraping would still resume from the last Group URL it visited, maintaining the continuity of the scraping.
<file_sep>## Script for performing all the data manipulations, pre-processing, data-mapping between multiple data sources (csv files)
## and accordingly, having various analysis, insights into the data, visualisations, etc.
import numpy as np
import pandas as pd
import re
import warnings
import datetime
import matplotlib.pyplot as plt
import pylab
from statistics import mode
import geopy.distance
import copy
import csv
import openpyxl
#import xslxwriter
import os
## Data Loading
pd.options.display.max_rows=1000
warnings.filterwarnings('ignore')
file_path = '/home/manish/Data/meetup_groups_clean_28MAR2017.xlsx'
df_metadata = pd.read_excel(file_path, sheet_name='META DATA')
df_comicmeetupmaster = pd.read_excel(file_path, sheet_name='COMICMEETUP_MASTER')
df_latlong = pd.read_excel(file_path, sheet_name='lat_long', header=None, names=['CITY', 'STATE', 'LAT', 'LONG'])
df_founders = pd.read_excel(file_path, sheet_name='FOUNDERS')
df_members = pd.read_excel(file_path, sheet_name='MEMBERS')
## Data Manipulation
df_metadata.columns = df_metadata.columns.str.replace(' ', '_')
df_comicmeetupmaster.columns = df_comicmeetupmaster.columns.str.lstrip()
df_comicmeetupmaster.columns = df_comicmeetupmaster.columns.str.replace(' ', '_')
df_latlong.columns = df_latlong.columns.str.replace(' ', '_')
df_founders.columns = df_founders.columns.str.replace(' ', '_')
df_members.columns = df_members.columns.str.replace(' ', '_')
##df_metadata
df_metadata.apply(lambda x: sum(x.isnull()))
## Except the following, rest all group URLs are unique
df_metadata.loc[df_metadata.GROUP_URLs == df_metadata.GROUP_URLs.value_counts().index[0],]
## difference between group URLS and MEMBER URLs :
## the only major difference between these 2 columns is the additional '/members' in the URL
## so not much information contained in this column, so dropping these columns
df_metadata['GROUP_MEMBER_DIFF'] = [y.replace(x, '') if not y is np.nan else np.nan
for x, y in zip(df_metadata.GROUP_URLs, df_metadata.MEMBER_URLs)]
## Extracting Groups from the URLs in df_metadata
df_metadata['Group'] = [re.findall(r'(?:.com/)(.+)/', x)[0] for x in df_metadata.GROUP_URLs]
## Extracting Country,State and City for the links from df_metadata
country = [np.nan] * len(df_metadata)
state = [np.nan] * len(df_metadata)
city = [np.nan] * len(df_metadata)
for i, x in enumerate(df_metadata.GEO_LOCATION_URLs):
if x is not np.nan:
temp = ''.join(re.findall(r'(?:/cities/)(.+)/', x)).split('/')
if (len(temp) == 3):
country[i] = temp[0]
state[i] = temp[1]
city[i] = temp[2]
if (len(temp) == 2):
country[i] = temp[0]
state[i] = temp[1]
df_metadata['COUNTRY'] = country
df_metadata['STATE'] = state
df_metadata['CITY'] = city
## df_comicmeetupmaster
df_comicmeetupmaster.loc[502] = df_comicmeetupmaster.loc[502].combine_first(df_comicmeetupmaster.loc[422])
df_comicmeetupmaster.drop(422, axis=0, inplace=True)
df_comicmeetupmaster = df_comicmeetupmaster.reset_index(drop=True)
df_comicmeetupmaster.TOTAL_MEMBERS = df_comicmeetupmaster.TOTAL_MEMBERS.str.strip('\n')
df_comicmeetupmaster['INITIAL_CHAR'] = [x[0].upper() for x in df_comicmeetupmaster.GROUP]
df_comicmeetupmaster.loc[df_comicmeetupmaster.INITIAL_CHAR.str.isdigit(), 'INITIAL_CHAR'] = '0-9'
df_comicmeetupmaster.TOTAL_MEMBERS.replace('Otaku', np.nan, inplace=True)
df_comicmeetupmaster.TOTAL_MEMBERS = [np.nan if x == 'nan' else int(x)
for x in df_comicmeetupmaster.TOTAL_MEMBERS.astype(str)]
df_comicmeetupmaster['DATETIME'] = pd.to_datetime(df_comicmeetupmaster.FOUNDED_DATE)
df_comicmeetupmaster['YEAR'] = [str(x).split()[0].split('-')[0] for x in df_comicmeetupmaster.DATETIME]
df_comicmeetupmaster['MONTH'] = [str(x).split()[0].split('-')[1] if not x is pd.NaT else pd.NaT
for x in df_comicmeetupmaster.DATETIME]
## Filling null values of GEO_LOCATION_2 and correspondingly to CITY in df_latlong:
# df_comicmeetupmaster.groupby('GEO_LOCATION_1').GEO_LOCATION_2.nunique()
state_city = {'Arlington': 'TX', 'Brighton': 'UK', 'North Hampton': 'UK', 'Portsmouth': 'UK', 'Cape Cod': 'MA',
'Fayetteville': 'NC', 'New Bury Park': 'CA', 'Niceville': 'FL', 'Springfield': 'IL', 'Stamford': 'CT',
'Westchester': 'NY', 'Winchester': 'VA', 'Youngstown': 'OH'}
for i, row in df_comicmeetupmaster.iterrows():
if ((row.GEO_LOCATION_2 is np.nan) & (row.GEO_LOCATION_1 in state_city.keys())):
df_comicmeetupmaster.GEO_LOCATION_2[i] = state_city[row.GEO_LOCATION_1]
t = df_comicmeetupmaster.GEO_LOCATION_1 == 'Torrance, CA'
df_comicmeetupmaster.loc[t, 'GEO_LOCATION_2'] = df_comicmeetupmaster.loc[t, 'GEO_LOCATION_1'].values[0].split(',')[
1].strip()
df_comicmeetupmaster.loc[t, 'GEO_LOCATION_1'] = df_comicmeetupmaster.loc[t, 'GEO_LOCATION_1'].values[0].split(',')[
0].strip()
df_comicmeetupmaster.loc[df_comicmeetupmaster.GEO_LOCATION_2 == 'Manitoba', 'GEO_LOCATION_2'] = 'MB'
for i, row in df_latlong.iterrows():
if ((row.STATE is np.nan) & (row.CITY in state_city.keys())):
df_latlong.STATE[i] = state_city[row.CITY]
t = df_latlong.CITY == 'Torrance, CA'
df_latlong.loc[t, 'STATE'] = df_latlong.loc[t, 'CITY'].values[0].split(',')[1].strip()
df_latlong.loc[t, 'CITY'] = df_latlong.loc[t, 'CITY'].values[0].split(',')[0].strip()
df_latlong.loc[df_latlong.STATE == 'Manitoba', 'STATE'] = 'MB'
df_comicmeetupmaster.loc[
(df_comicmeetupmaster.GEO_LOCATION_1 == 'Manchester') & (df_comicmeetupmaster.GEO_LOCATION_2.isnull()),
'GEO_LOCATION_2'] = mode(df_latlong.loc[(df_latlong.CITY == 'Manchester'), 'STATE'].dropna())
df_comicmeetupmaster.loc[
(df_comicmeetupmaster.GEO_LOCATION_1 == 'Kansas City') & (df_comicmeetupmaster.GEO_LOCATION_2.isnull()),
'GEO_LOCATION_2'] = mode(df_latlong.loc[(df_latlong.CITY == 'Kansas City'), 'STATE'].dropna())
df_comicmeetupmaster.loc[df_comicmeetupmaster.GEO_LOCATION_1 == 'Vienna',
'GEO_LOCATION_2'] = df_latlong.loc[df_latlong.CITY == 'Vienna', 'STATE'].values[0]
## Fiiling up the missing Lat and Long in comicmeetupmaster
# for g in df_comicmeetupmaster.GEO_LOCATION_1.dropna().unique().tolist():
# cond1 = (df_comicmeetupmaster.GEO_LOCATION_1==g)&(df_comicmeetupmaster.LATITUDE.isnull())
# cond2 = (df_latlong.CITY==g)&(df_latlong.LAT.notnull())
# if(any(cond1) and any(cond2)):
# try:
# df_comicmeetupmaster.loc[cond1,'LATITUDE'] = mode(df_latlong.loc[cond2,'LAT'].dropna())
# df_comicmeetupmaster.loc[cond1,'LONGITUDE'] = mode(df_latlong.loc[cond2,'LONG'].dropna())
# except:
# pass
warnings.filterwarnings('ignore')
for i, row in df_comicmeetupmaster.iterrows():
if ((row.GEO_LOCATION_1 is not np.nan) & (np.isnan(row.LATITUDE)) & (np.isnan(row.LONGITUDE))):
df_comicmeetupmaster.LATITUDE[i] = mode(df_latlong.loc[(df_latlong.CITY == row.GEO_LOCATION_1) &
(
df_latlong.STATE == row.GEO_LOCATION_2), 'LAT'].dropna())
df_comicmeetupmaster.LONGITUDE[i] = mode(df_latlong.loc[(df_latlong.CITY == row.GEO_LOCATION_1) &
(
df_latlong.STATE == row.GEO_LOCATION_2), 'LONG'].dropna())
## extracting the gender from the group name from df_comicmeetupmaster:
# female - Girl, Girls, Ladies, Her, Girlsonly, GeekGirlCon, Mommies, Queens, Women, Chic, Woman, Gals,
# male - Bros,
# others - Gay, Gays, PRIDE, LGBT, Lesbians, LesbianBi, LGBTQ, LGBTQIA, LGBTQA,
female = ['girl', 'ladies', 'mommies', 'queens', 'women', 'woman']
male = ['bros']
others = ['gay', 'pride', 'lgbt', 'lesbian']
female_mod = ['her', 'chic', 'gals']
female_mod = re.compile(r'\b(?:%s)\b' % '|'.join(female_mod))
df_comicmeetupmaster['GENDER'] = None
warnings.filterwarnings('ignore')
for i, x in enumerate(df_comicmeetupmaster.GROUP):
if (any([temp in x.lower() for temp in female])):
df_comicmeetupmaster.GENDER[i] = 'Female'
elif (re.search(female_mod, x.lower())):
df_comicmeetupmaster.GENDER[i] = 'Female'
elif (any([temp in x.lower() for temp in male])):
df_comicmeetupmaster.GENDER[i] = 'Male'
elif (any([temp in x.lower() for temp in others])):
df_comicmeetupmaster.GENDER[i] = 'Others'
else:
df_comicmeetupmaster.GENDER[i] = 'Unknown'
female_groups = pd.DataFrame(df_comicmeetupmaster.loc[df_comicmeetupmaster.GENDER == 'Female', 'GROUP']).reset_index(
drop=True)
male_groups = pd.DataFrame(df_comicmeetupmaster.loc[df_comicmeetupmaster.GENDER == 'Male', 'GROUP']).reset_index(
drop=True)
others_groups = pd.DataFrame(df_comicmeetupmaster.loc[df_comicmeetupmaster.GENDER == 'Others', 'GROUP']).reset_index(
drop=True)
# Total 502 groups present
## df_founders
## Dropping those rows which have null values in both the Founded Date and Founder
for g in df_founders.Group.value_counts().index[(df_founders.Group.value_counts() > 1)]:
for i in df_founders.loc[df_founders.Group == g,].index:
if (sum(df_founders.loc[i, ['Founded_Date', 'Founder']].isnull()) == 2):
df_founders.drop(i, axis=0, inplace=True)
df_founders.loc[527] = df_founders.loc[527].combine_first(df_founders.loc[447])
df_founders.drop(447, axis=0, inplace=True)
df_founders = df_founders.reset_index(drop=True)
## Cleaning the Date column
df_founders.Founded_Date = df_founders.Founded_Date.str.replace('Founded\n', '')
df_founders.Founded_Date = df_founders.Founded_Date.str.replace('Founded ', '')
### df_members is of no significance
### ANALYSIS RESULTS:
## Count of number of groups by state/country and city
q1a = df_comicmeetupmaster.groupby(by=['GEO_LOCATION_2', 'GEO_LOCATION_1'], as_index=False).agg({'GROUP': 'count'})
## Count of number of group by state/country only
q1b = df_comicmeetupmaster.groupby(by=['GEO_LOCATION_2'], as_index=False).agg({'GROUP': 'count'})
## Gender of the Group
q2 = pd.DataFrame(df_comicmeetupmaster.GENDER.value_counts()).reset_index()
q2.columns = ['GENDER', 'NUMBER']
## count of Groups for every alphabet
q3 = df_comicmeetupmaster.groupby('INITIAL_CHAR').agg({'GROUP': 'count'})
## Total members
## The total number of members are 407
len(df_members)
## Total groups
## The total number of groups are 502
len(df_founders.Group.unique())
## Count of average members in group by state/country and city
q6a = df_comicmeetupmaster.groupby(by=['GEO_LOCATION_2', 'GEO_LOCATION_1'], as_index=False).agg(
{'TOTAL_MEMBERS': 'mean'})
q6a.rename(columns={'mean': 'AVERAGE MEMBERS'})
## Count of average number of group by state/country only
q6b = df_comicmeetupmaster.groupby(by=['GEO_LOCATION_2'], as_index=False).agg({'TOTAL_MEMBERS': 'mean'})
q6b.rename(columns={'mean': 'AVERAGE MEMBERS'})
## Total Lifecycle of this Market
## 14 years (from 15-Nov 2002 to 17-Aug 2016)
time_diff = max(df_comicmeetupmaster.DATETIME) - min(df_comicmeetupmaster.DATETIME)
q7 = round((time_diff.days / 30) / 12, 3)
## Average Startup duration between Groups
temp_date = df_comicmeetupmaster.DATETIME
temp_date = temp_date.sort_values()
temp_date.reset_index(drop=True, inplace=True)
temp_date.dropna(inplace=True)
sum_days = 0
avg_day = []
avg_day.append(0)
for i in range(len(temp_date)):
if (i < (len(temp_date) - 1)):
temp = (temp_date[i + 1] - temp_date[i])
days = round((temp.days + (temp.seconds / (60 * 60 * 24))), 3)
sum_days += days
avg_day.append(days)
avg_open_distance = round(sum_days / len(temp_date), 3)
## From this even though the mean is 10 days, however this is very skewed data.
## This is due to the fact that many meetup groups that have been formed in 2016(149 groups)
## all are within less number of days from each other, as evident from graph
plt.plot(avg_day)
plt.xlabel('Difference between forming of two consecutive groups in days')
plt.ylabel('Number of Groups')
plt.show()
plt.plot(temp_date, avg_day)
plt.xlabel('Date of forming of the meetup groups')
plt.ylabel('Average number of days')
plt.show()
## From this even the median is 3 days and 75th percentile is 7
pd.Series(avg_day).describe()
## Yearly Average Startup duration between groups
yr_unique = df_comicmeetupmaster.YEAR.unique().tolist()
yr_unique.remove('NaT')
yr_unique = sorted(yr_unique)
final = []
for y in yr_unique:
temp_date = df_comicmeetupmaster.loc[df_comicmeetupmaster.YEAR == y, 'DATETIME']
temp_date = temp_date.sort_values()
temp_date.reset_index(drop=True, inplace=True)
temp_date.dropna(inplace=True)
sum_days = 0
for i in range(len(temp_date)):
if (i < (len(temp_date) - 1)):
temp = (temp_date[i + 1] - temp_date[i])
sum_days += round((temp.days + (temp.seconds / (60 * 60 * 24))), 3)
avg_open_distance = round(sum_days / len(temp_date), 3)
final.append([y, avg_open_distance])
q8 = pd.DataFrame(final, columns=['Year', 'Average Opening'])
## For the groups in the same city, lat and long co-ords are exactly the same, so doing it on country wise
final = []
for country in df_comicmeetupmaster.GEO_LOCATION_2.dropna().unique().tolist():
len_cities = len(df_comicmeetupmaster.loc[df_comicmeetupmaster.GEO_LOCATION_2 == country, 'GEO_LOCATION_1'])
temp_cities = df_comicmeetupmaster.loc[
df_comicmeetupmaster.GEO_LOCATION_2 == country, 'GEO_LOCATION_1'].dropna().unique().tolist()
if len(temp_cities) > 1:
l = []
for city in temp_cities:
temp_lat = df_comicmeetupmaster.loc[(df_comicmeetupmaster.GEO_LOCATION_2 == country) &
(df_comicmeetupmaster.GEO_LOCATION_1 == city),].LATITUDE.unique()
temp_long = df_comicmeetupmaster.loc[(df_comicmeetupmaster.GEO_LOCATION_2 == country) &
(df_comicmeetupmaster.GEO_LOCATION_1 == city),].LONGITUDE.unique()
l.append([temp_lat[0], temp_long[0]])
sum_temp = 0
for i in range(len(l) - 1):
tp = l[i]
new_l = l[-(len(l) - 1 - i):]
for j in range(len(new_l)):
temp = round(geopy.distance.distance(tp, new_l[j]).km, 3)
sum_temp += temp
avg_distance = round(sum_temp / len_cities, 3)
final.append([country, avg_distance, len_cities, len(temp_cities)])
q9 = pd.DataFrame(final, columns=['STATE', 'AVG_DISTANCE', 'TOTAL_GROUPS', 'TOTAL_CITIES'])
# Group categories/genres
genre_dict = {'Comics': ['comic', 'cartoon', 'anime', 'manga', 'genshiken', 'brony'], 'Geeks': ['geek', 'nerd'],
'Action': ['action', 'adventure', 'game', 'gaming', 'juego', 'pokemon'], 'Graphic': ['graphic'],
'Fiction': ['scifi', 'fiction', 'star war', 'star trek', 'superhero', 'sci fi', 'science fiction'],
'Doctor': ['doctor'], 'Vintage': ['back to the 80s'], 'Pop': ['pop culture'], 'Black': ['black'],
'Movies': ['movie', 'film'], 'Trade': ['trade', 'sell', 'guild', 'crafter'],
'Arts': ['drawing', 'writing', 'dance', 'artist', 'music', 'sword', 'arts', 'sketch', 'gym', 'culture',
'design', 'cosplay']}
final_dict = {}
for k in genre_dict.keys():
final_dict[k] = []
for x in df_comicmeetupmaster.GROUP:
if (any([temp in x.lower() for temp in genre_dict[k]])):
final_dict[k].append(x)
arts_mod = re.compile(r'\b(?:%s)\b' % '|'.join(['art']))
for x in df_comicmeetupmaster.GROUP:
if (re.search(arts_mod, x.lower())):
final_dict['Arts'].append(x)
if os.path.exists('Answers.xlsx'):
os.remove('Answers.xlsx')
# book = openpyxl.load_workbook('Answers.xlsx')
book = openpyxl.Workbook()
defaultsheet = book['Sheet']
book.remove(defaultsheet)
for s in ['1a', '1b', 2, 3, '6a', '6b', 8, 9]:
book.create_sheet('Question {0}'.format(s))
book.save('Answers.xlsx')
# book.sheetnames
writer = pd.ExcelWriter('Answers.xlsx', engine='xlsxwriter')
q1a.to_excel(writer, sheet_name='Question 1a')
q1b.to_excel(writer, sheet_name='Question 1b')
q2.to_excel(writer, sheet_name='Question 2')
q3.to_excel(writer, sheet_name='Question 3')
q6a.to_excel(writer, sheet_name='Question 6a')
q6b.to_excel(writer, sheet_name='Question 6b')
q8.to_excel(writer, sheet_name='Question 8')
q9.to_excel(writer, sheet_name='Question 9')
writer.save()
temp = pd.DataFrame(
{'GENRE': [k for k in final_dict.keys()], 'GROUP COUNT': [len(final_dict[k]) for k in final_dict.keys()]})
temp.index += 1
temp.to_csv('Question10.csv')
with open('Question10.csv', 'a') as f:
f.write('\n\n\n')
for key in final_dict.keys():
f.write('{0}\n'.format(key))
for val in final_dict[key]:
f.write('{0}\n'.format(val))
f.write('\n')
<file_sep>## Script to load data from the mutliple data sources (csv files) which were created from the data structuring post
## the scraping of data from meetup.com. Various multiple meaningful data dictionaries and data frames are created,
## having useful data mappings amongst the users ,groups, interests, and regions.
import numpy as np
import pandas as pd
from pprint import pprint
## 1. About_Us
with open('About_Us.csv','r') as f:
about_list = f.readlines()
about_us = about_list[2:]
about_us = [x.strip('\n') if x != '\n' else x for x in about_us]
##For every unique group, this gives the number of descriptions associated with each group.
about_dict_1 = {}
for i in range(len(about_us)-1):
if about_us[i] == '\n':
temp_vals = [about_us[i+2]]
j=i+3
while about_us[j]!='\n':
temp_vals.append(about_us[j])
j += 1
about_dict_1[about_us[i+1]] = temp_vals
## For every description, this gives the groups which are associated with each genre.
about_dict_2 = {}
for i in range(len(about_us)-1):
if about_us[i]=='\n':
j=i+2
while (j<len(about_us) and about_us[j]!='\n'):
if about_us[j].lower() not in about_dict_2.keys():
about_dict_2[about_us[j].lower()]=[]
about_dict_2[about_us[j].lower()].append(about_us[i+1])
j+=1
## 2. Members_Info
members_info = pd.read_csv('Members_Info.csv')
del members_info['Unnamed: 0']
## From the data scraped, there were a total of 50,709 members, out of which there are 46,994 unique members,
## each row having metadata for every member, like location, number of other groups, date of joining group
members_dict = {}
for i, rows in members_info.iterrows():
if rows['Unique_ID'] not in members_dict.keys():
members_dict[rows['Unique_ID']] = [rows['Group_Name']]
else:
members_dict[rows['Unique_ID']].append(rows['Group_Name'])
multiple_members_dict = {}
for items in members_dict:
if len(members_dict[items]) > 1:
multiple_members_dict[items] = members_dict[items]
for m in multiple_members_dict:
multiple_members_dict[m] = list(np.unique(multiple_members_dict[m]))
## 3. Member_interests
with open('Members_Interests.csv', 'r') as f:
members_list = f.readlines()
members_interests = members_list[2:]
members_interests = [x.strip('\n') if x != '\n' else x for x in members_interests]
##For every unique member, this gives the genre each member is interested in.
interests_dict_1 = {}
for i in range(len(members_interests) - 1):
if members_interests[i] == '\n':
temp_vals = [members_interests[i + 2]]
j = i + 3
while (j < len(members_interests) and members_interests[j] != '\n'):
temp_vals.append(members_interests[j])
j += 1
interests_dict_1[members_interests[i + 1]] = temp_vals
## For every genre, this gives the members interested in each genre.
interests_dict_2 = {}
for i in range(len(members_interests) - 1):
if members_interests[i] == '\n':
j = i + 2
while (j < len(members_interests) and members_interests[j] != '\n'):
if members_interests[j].lower() not in interests_dict_2.keys():
interests_dict_2[members_interests[j].lower()] = []
interests_dict_2[members_interests[j].lower()].append(members_interests[i + 1])
j += 1
first_few_interests_dict_2 = {k: interests_dict_2[k] for k in list(interests_dict_2)[:10]}
## 4. Members Other Groups
with open('Members_Other_Groups.csv', 'r') as f:
members_others_list = f.readlines()
members_other_groups = members_others_list[2:]
members_other_groups = [x.strip('\n') if x != '\n' else x for x in members_other_groups]
##For every unique member, this gives the total groups each member is a part of.
other_groups_dict_1 = {}
for i in range(len(members_other_groups) - 1):
if members_other_groups[i] == '\n':
temp_vals = [members_other_groups[i + 2]]
j = i + 3
while (j < len(members_other_groups) and members_other_groups[j] != '\n'):
temp_vals.append(members_other_groups[j])
j += 1
other_groups_dict_1[members_other_groups[i + 1]] = temp_vals
## For every group, this gives the total members which are a part of it.
other_groups_dict_2 = {}
for i in range(len(members_other_groups) - 1):
if members_other_groups[i] == '\n':
j = i + 2
while (j < len(members_other_groups) and members_other_groups[j] != '\n'):
if members_other_groups[j].lower() not in other_groups_dict_2.keys():
other_groups_dict_2[members_other_groups[j].lower()] = []
other_groups_dict_2[members_other_groups[j].lower()].append(members_other_groups[i + 1])
j += 1
first_few_other_groups_dict_2 = {k: other_groups_dict_2[k] for k in list(other_groups_dict_2)[:10]}
## 5. scraped groups data
scraped_df = pd.read_csv('Scrapped_Groups_Data.csv')
del scraped_df['Unnamed: 0']
## From all the available urls in total, some of the meetup group urls were not found, which would most probably
## mean that the group might not be functional any longer. For the remaining meetup groups, scrapped all the data
## from these groups, such as location of the group, genre of the groups, founders, total members, and data of all
## the members, thier interests, etc.
#len(scraped_df.loc[scraped_df.Group_name == 'Url not working',:])
scraped_df = scraped_df.loc[scraped_df.Group_name!='Url not working',:].reset_index(drop=True)
scraped_df.Total_members = scraped_df.Total_members.str.replace(',','').astype('int')
scraped_df.Founding_date = pd.to_datetime(scraped_df.Founding_date)
scraped_df.loc[scraped_df.Past_meetups=='[]','Past_meetups'] = '0'
scraped_df.Past_meetups = scraped_df.Past_meetups.str.replace(',','').astype('int')
## possible insights:
## decreasing order, by number of past meetups.
scraped_df[['Group_name', 'Past_meetups']].sort_values(by='Past_meetups', ascending=False).reset_index(drop=True)
## decreasing order by founding date
scraped_df[['Group_name','Founding_date']].sort_values(by='Founding_date', ascending=False).reset_index(drop=True)
## decreasing order by total members :
scraped_df[['Group_name','Total_members']].sort_values(by='Total_members', ascending=False).reset_index(drop=True)
## Average number of members state wise
round(scraped_df.groupby(by='State',as_index=False).agg({'Total_members':'mean'}),2)
## Average number of members city wise
round(scraped_df.groupby(by=['City','State'],as_index=False).agg({'Total_members':'mean'}),2)
| ea0e24cccd6d81dbd105cf25b6e9bbdc743d9835 | [
"Markdown",
"Python"
] | 5 | Python | pavanchungi/Meetup-groups_Data-Scraping-and-Analysis | 38df209cef2cba4e14a636d34aa597c517c2ffe4 | 5628da9e71cb8f17b5397786acf9865631a36a52 |
refs/heads/master | <repo_name>HelenChen98/badges-and-schedules-v-000<file_sep>/conference_badges.rb
def badge_maker(name)
return "Hello, my name is #{name}."
end
def batch_badge_creator(attendees)
array = []
attendees.each do |member|
array << badge_maker(member)
end
array
end
def assign_rooms(attendees)
array = []
index = 1
attendees.each do |member|
array << "Hello, #{member}! You'll be assigned to room #{index}!"
index+=1
end
array
end
def printer(attendees)
badge_messages = batch_badge_creator(attendees)
badge_messages.each do |message|
puts message
end
room_messages = assign_rooms(attendees)
room_messages.each do |message|
puts message
end
end
| c0a5e626983e9a58dff66474d290df6eff371bf0 | [
"Ruby"
] | 1 | Ruby | HelenChen98/badges-and-schedules-v-000 | 3fe5689a0e5d7fe8ca80facfa35acdbb9711fb14 | d925ccef7acc08b918e842eebf314eeff5478f7d |
refs/heads/master | <file_sep>const mongoose = require('mongoose');
// To pull the string for mongodb atlas connection
const config = require('config');
const db = config.get('mongoURI'); //To get mongoURI in the variable db.
const connectDB = async () => {
try {
await mongoose.connect(db, { useUnifiedTopology: true, useNewUrlParser:
true, useCreateIndex:true });
console.log('Mongodb connected...');
}
catch(err){
console.error(err.message);
// Exit process with failure
process.exit(1);
}
}
module.exports = connectDB;<file_sep>1.
We will make Logout functionality. ANd change the navbar links based on logged in or not.
actions>types.js
LOGOUT
action and reducer for LOGOUT
-----------------------------------------------------------------------------------------------------------------
2.
goto: components>layout>Navbar.js
mapStateToProps state: isAuthenticated, loading
import logout action, connect, propTypes
-----------------------------------------------------------------------------------------------------------------
3.
Create couple variable for guestLinks(not authenticated) and authLinks(authenticated)
guestLinks: Developers, Register, Login
authLinks: Logout
{!loading && (<Fragment>
{ isAuthenticated ? authLinks : guestLinks }
</Fragment>) }
loading should be false.
isAuthenticate true then show authLinks , if false show guestLinks
-----------------------------------------------------------------------------------------------------------------
>>npm run dev
| b91b0431d5ee895ef09ea2d7a7162bf599eb331a | [
"JavaScript",
"Text"
] | 2 | JavaScript | sachetmoktan/dev-point | 8844c6b05dc0797ca0c6b524fa9a86b9e0cf1425 | 2b7e1ac8431579d7bd2307577d019c1104fb3996 |
refs/heads/master | <file_sep>package no.uio.inf5750.assignment2.dao.impl;
import java.util.Collection;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import no.uio.inf5750.assignment2.dao.*;
import no.uio.inf5750.assignment2.model.Degree;
import no.uio.inf5750.assignment2.model.Student;
@Transactional
public class StudentDAOImpl implements StudentDAO {
static Logger logger = Logger.getLogger(StudentDAOImpl.class);
@Autowired
private SessionFactory sessionFactory;
@Override
public int saveStudent(Student student) {
int studentId = (Integer) sessionFactory.getCurrentSession().save(student);
sessionFactory.getCurrentSession().flush();
return studentId;
}
@Override
public Student getStudent(int id) {
Student student = (Student) sessionFactory.getCurrentSession().get(Student.class, id);
sessionFactory.getCurrentSession().flush();
return student;
}
@Override
public Student getStudentByName(String name) {
Session currentSession = sessionFactory.getCurrentSession();
Student student = (Student) currentSession.createCriteria(Student.class).add(Restrictions.eq("name", name))
.uniqueResult();
if (student != null)
return student;
return null;
}
@Override
public Collection<Student> getAllStudents() {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
@SuppressWarnings("unchecked")
Collection<Student> students = session.createQuery("FROM Student").list();
tx.commit();
return students;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
logger.error("DB query failed", e);
} finally {
session.close();
}
return null;
}
@Override
public void delStudent(Student student) {
sessionFactory.getCurrentSession().delete(student);
}
@Override
public void updateStudent(Student student) {
sessionFactory.getCurrentSession().saveOrUpdate(student);
}
}
<file_sep>package no.uio.inf5750.assignment2.dao.impl;
import java.util.Collection;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.junit.runner.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import no.uio.inf5750.assignment2.dao.*;
import no.uio.inf5750.assignment2.model.Course;
import no.uio.inf5750.assignment2.model.Student;
@Transactional
public class CourseDAOImpl implements CourseDAO {
static Logger logger = Logger.getLogger(CourseDAOImpl.class);
@Autowired
private SessionFactory sessionFactory;
@Override
public int saveCourse(Course course) {
int courseId = (Integer) sessionFactory.getCurrentSession().save(course);
sessionFactory.getCurrentSession().flush();
return courseId;
}
@Override
public Course getCourse(int id) {
Course course = (Course)sessionFactory.getCurrentSession().get(Course.class, id);
sessionFactory.getCurrentSession().flush();
return course;
}
@Override
public Course getCourseByCourseCode(String courseCode) {
Session currentSession = sessionFactory.getCurrentSession();
Course course = (Course) currentSession.createCriteria(Course.class)
.add(Restrictions.eq("courseCode", courseCode)).uniqueResult();
if (course != null)
return course;
return null;
}
@Override
public Course getCourseByName(String name) {
Session currentSession = sessionFactory.getCurrentSession();
Course course = (Course) currentSession.createCriteria(Course.class).add(Restrictions.eq("name", name))
.uniqueResult();
if (course != null)
return course;
return null;
}
@Override
public Collection<Course> getAllCourses() {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
@SuppressWarnings("unchecked")
Collection<Course> courses = session.createQuery("FROM Course").list();
tx.commit();
return courses;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
logger.error("DB query failed", e);
} finally {
session.close();
}
return null;
}
@Override
public void delCourse(Course course) {
sessionFactory.getCurrentSession().delete(course);
}
}
<file_sep>package no.uio.inf5750.assignment2.dao;
public class StudentDAOTest {
}
| 4ec3b14cae942cfcec7e5b89e61601c180ae3538 | [
"Java"
] | 3 | Java | zubaira/SS2 | fe2d9ed37ea4393d800ca03bb7f293ae601a790f | 5e584d6ee01fc1f30f81d29baa4ac88dd41e062c |
refs/heads/master | <file_sep># schoolsite
学校网站
<file_sep>import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.baseURL = 'http://172.16.17.32:8080'
// POST传参序列化
axios.interceptors.request.use((config) => {
if (config.method === 'post') {
config.data = JSON.stringify(config.data);
}
return config;
}, (error) => {
console.log("错误的传参");
return Promise.reject(error);
});
// code状态码200判断
axios.interceptors.response.use((res) => {
if (res.data.code !== 0) {
console.log(res.data.message);
return Promise.reject(res);
}
return res;
}, (error) => {
console.log("网络异常");
return Promise.reject(error);
});
export default axios;<file_sep>// profession
export const professionList = 'professionList'
export const professionDetails = 'professionDetails'
export const getCurrentID = 'getCurrentID'
// collage
export const getInfo = 'getInfo'
export const getArtDetails = 'getArtDetails'
export const getArtId = 'getArtId'
// home
export const getMoreInfo = 'getMoreInfo'
// 就业信息
export const getJobInfo = 'getJobInfo'
export const getJobInfoDetails = 'getJobInfoDetails'
export const getJobId = 'getJobId'
// 学历提升improve
export const improveList = 'improveList'
export const getImproveDetails = 'getImproveDetails'
export const getImproveId = 'getImproveId'<file_sep>// profession
export const pageId = (state) => state.pageId
export const specialList = (state) => state.specialList
export const professionDetails = (state) => state.professionDetails
// college
export const info = (state) => state.info
export const artDetails = (state) => state.artDetails
export const artId = (state) => state.artId
// home
export const moreInfo = (state) => state.moreInfo
// 就业信息
export const jobInfo = (state) => state.jobInfo
export const jobDetails = (state) => state.jobDetails
export const jobId = (state) => state.jobId
// 学历提升
export const improveList = (state) => state.improveList
export const improveDetails = (state) => state.improveDetails
export const improveId = (state) => state.improveId<file_sep>import * as types from './mutation-types'
import * as actions from './actions'
import * as getters from './getters'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
// 专业管理
professionList: [],
improveList: [],
editProId: '',
editProDetails: [],
editImproveId: '',
editImproveDetails: [],
// 信息管理
infoFive: [],
editInfoFiveId: '',
editInfoFiveDetails: [],
jobInfo: [],
jobInfoId: '',
jobInfoDetails: [],
// 报名管理
entryInfo: [],
entryInfoId: '',
entryInfoDetails: [],
// 留言管理
message: []
}
const mutations = {
// 专业管理
[types.getProfession](state, data) {
state.professionList = data
},
[types.getImprove](state, data) {
state.improveList = data
},
[types.getEditProId](state, id) {
state.editProId = id
},
[types.getEditProDetails](state, data) {
state.editProDetails = data
},
[types.getEditImproveId](state, id) {
state.editImproveId = id
},
[types.getEditImproveDetails](state, data) {
state.editImproveDetails = data
},
// 信息管理
[types.getInfoFive](state, data) {
state.infoFive = data
},
[types.getEditInfoFiveId](state, id) {
state.editInfoFiveId = id
},
[types.getEditInfoFiveDetails](state, data) {
state.editInfoFiveDetails = data
},
[types.getJobInfo](state, data) {
state.jobInfo = data
},
[types.getJobInfoId](state, id) {
state.jobInfoId = id
},
[types.getJobInfoDetails](state, data) {
state.jobInfoDetails = data
},
// 报名管理
[types.getEntryInfo](state, data) {
state.entryInfo = data
},
[types.getEntryInfoId](state, id) {
state.entryInfoId = id
},
[types.getEntryInfoDetails](state, data) {
state.entryInfoDetails = data
},
// 留言管理
[types.getMessage](state, data) {
state.message = data
}
}
export default new Vuex.Store({
state,
mutations,
getters,
actions
})<file_sep>// 专业管理
export const professionList = state => state.professionList
export const improveList = state => state.improveList
export const editProId = state => state.editProId
export const editProDetails = state => state.editProDetails
export const editImproveId = state => state.editImproveId
export const editImproveDetails = state => state.editImproveDetails
// 信息管理
export const infoFive = state => state.infoFive
export const editInfoFiveId = state => state.editInfoFiveId
export const editInfoFiveDetails = state => state.editInfoFiveDetails
export const jobInfo = state => state.jobInfo
export const jobInfoId = state => state.jobInfoId
export const jobInfoDetails = state => state.jobInfoDetails
// 报名管理
export const entryInfo = state => state.entryInfo
export const entryInfoId = state => state.entryInfoId
export const entryInfoDetails = state => state.entryInfoDetails
// 留言管理
export const message = state => state.message | 0c3827e0eac1ec357d63932a93a79a9cf5e0168c | [
"Markdown",
"JavaScript"
] | 6 | Markdown | k-water/schoolsite | 20263d3d78323c04f8836807f39f0068b8637a16 | d6836157890999c638f942fae05721dd64a6b3b4 |
refs/heads/master | <file_sep>#!/usr/bin/
"""
Created on 23/01/2015
@author: adelpozo
"""
import sys
import re
import os
import string
import urllib
import time
import math
import random
import ConfigParser
#######################################################################
def read_cfg_file(cfg_filename):
"""
:param cfg_filename:
:return:
"""
fi = open(cfg_filename, 'r')
config = ConfigParser.ConfigParser()
config.readfp(fi)
hash_cfg = {}
for field in ['INPUT', 'OUTPUT', 'SOFTWARE', 'REFERENCE']:
for field_value in config.options(field):
hash_cfg[field_value] = config.get(field, field_value)
if config.has_section('CONTROLS'):
hash_cfg['controls'] = config.items('CONTROLS')
fi.close()
return hash_cfg
<file_sep>#!/usr/bin/python
import sys, re, shlex , os, string, urllib, time, math, random, subprocess, shutil
from os import path as osp
import optparse
#from wx.lib.agw.thumbnailctrl import file_broken
from HTSeq import SAM_Reader
import ConfigParser
from subprocess import Popen, PIPE
from itertools import izip_longest, chain
import vcf
from vcf.parser import _Filter,_Record,_Info,_Format,_SV
from vcf.utils import walk_together
from operator import itemgetter
import pandas as pd
from tempfile import mkstemp
from shutil import move
from os import remove, close
import warnings
import numpy as np
import logging
from modules import mod_cfg
from modules import mod_variant
#import xlsxwriter
modulesRelDirs = ["modules/"]
localModulesBase = osp.dirname(osp.realpath(__file__))
for moduleRelDir in modulesRelDirs:
sys.path.insert(0,osp.join(localModulesBase, moduleRelDir))
principalsRelDirs = ["../"]
for pRelDir in principalsRelDirs:
sys.path.insert(0,osp.join(localModulesBase, pRelDir))
class OptionParser(optparse.OptionParser):
def check_required(self, opt):
option = self.get_option(opt)
atrib = getattr(self.values, option.dest)
if atrib is None:
self.error("%s option not supplied" % option)
########################################################################################################################
def change_sample_name(vcf_file,new_label='overlapping'):
vcf_reader = vcf.Reader(filename=vcf_file)
l_records = []
for record in vcf_reader:
record.samples = [record.samples[0]]
l_records.append(record)
vcf_reader.samples = [new_label]
vcf_tmp = os.path.splitext(vcf_file)[0]+'.tmp.vcf'
vcf_writer = vcf.Writer(open(vcf_tmp , 'w'), vcf_reader)
for record in l_records:
vcf_writer.write_record(record)
return vcf_tmp
########################################################################################################################
def combine_vcf_v2(l_vcf_files,l_rod_priority,mode,ouput_path=None,**kwargs):
"""
There are two modes:
1. merge: this is when you need to join hetereogeneous calls into the same register with the condition that they overlap into the same genomic position.
It could be merged calls from different tools belonging to the same sample
2. combine: When you need to join the same variants (shared ref and alt alleles) into one register. Its recommended in familiar studies. In this mode, only different samples are allowed
"""
if mode == "merge":
get_key = lambda r: (r.CHROM, r.POS)
elif mode == "combine":
get_key = lambda r: (r.CHROM, r.POS, r.REF, r.ALT)
else:
raise InputError('mod_variant.combine_vcf_v2: The mode of combining vcf is not correct: %s' % (mode))
### specific configurations
label_mode = "no_append" ### possibilities: append/no_append
if kwargs.has_key('label_mode'):
label_mode = kwargs['label_mode']
info_mode = "overwrite" ### possibilities: overwrite/append
if kwargs.has_key('info_mode'):
info_mode = kwargs['info_mode']
remove_non_variants = False ### possibilities: True/False
if kwargs.has_key('remove_non_variants'):
remove_non_variants = kwargs['remove_non_variants']
### 1. generate the name of the combined file
vcf_file_combined = ""
root_name = __get_root_name(l_vcf_files)
if root_name == "":
root_name = "v"
if ouput_path == None:
vcf_file_combined = root_name+'.combined.vcf'
else:
vcf_file_combined = os.path.join(ouput_path,root_name+'.combined.vcf')
### 2. Check out the arragement of the vcf files in function of the rod list
if l_rod_priority == [] or l_rod_priority == None:
l_rod_priority = l_vcf_files
label_mode = "no_append"
if len(l_rod_priority) != len(l_vcf_files):
raise InputError('mod_variant.combine_vcf_v2: The number of ids in the list of rod priority do not agree with the number of vcf files')
num_files = len(l_vcf_files)
header = ""
### 3. Fill the list of vcf readers. In addition, it configure the INFO field in the header
### Also, it assigns the index of the file and the samples
### It writes the header into a string
l_readers = []
hash_vcf_2_readers = {}
hash_sample_2_file = {}
hash_sample_2_index= {}
hash_sample_2_rod = {}
i_sample = 0
dict_filters = {}
for vcf_file in l_vcf_files:
r = vcf.Reader(filename=vcf_file)
dict_filters.update(r.filters)
for (i,(vcf_file,rod)) in enumerate(zip(l_vcf_files,l_rod_priority)):
r = vcf.Reader(filename=vcf_file)
r.infos['NC'] = _Info('NC',1,'Integer',"Number of Calls")
r.infos['NV'] = _Info('NV',1,'Integer',"Number of Variants")
r.infos['set'] = _Info('set',1,'String',"Source of the vcf file")
r.filters = dict_filters
l_readers.append(r)
if header == "":
header = __get_header(r)
if header.find('##contig') == -1:
try:
hash_contigs = r.contigs
for cont in hash_contigs:
header += "##contig=<ID=%s,length=%d>\n" % (hash_contigs[cont].id,hash_contigs[cont].length)
except AttributeError:
pass
hash_vcf_2_readers[os.path.basename(vcf_file)] = i
l_s = r.samples # samples of each vcf
for sample in l_s:
if mode == "combine":
if hash_sample_2_file.has_key(sample):
raise RuntimeError("combine_vcf:combine_vcf_v2: There are at least two vcf files with the same sample label\n")
if mode == "merge": # the sample could be in two o more vcf files
hash_sample_2_file.setdefault(sample,[])
hash_sample_2_file[sample].append(os.path.basename(vcf_file))
hash_sample_2_rod.setdefault(sample,[])
hash_sample_2_rod[sample].append(rod)
else:
hash_sample_2_file[sample] = os.path.basename(vcf_file)
hash_sample_2_rod[sample] = rod
if not hash_sample_2_index.has_key(sample): # in case of duplicated samples, it assigns the lowest index
hash_sample_2_index[sample] = i_sample
i_sample += 1
l_total_samples = map(itemgetter(1),sorted(map(lambda (i,s): (i,s), zip(hash_sample_2_index.values(),hash_sample_2_index.keys()))))
num_samples = len(l_total_samples)
if mode != "combine":
fo = open(vcf_file_combined,'w')
fo.write(header)
fo.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t%s\n" % ('\t'.join(l_total_samples)))
### 4. It iterates over each reader (vcf_file) and then, for the samples of the reader
elif mode == "combine":
hash_walker = {}
for l_record in vcf.utils.walk_together(*l_readers,vcf_record_sort_key=get_key):
sum_QUAL = 0
num_r = 0
num_s = 0
filter_string = ""
set_str = ""
is_PASS = False
hash_format = {}
### It counts the number of calls. A register with None means no call ./.
num_calls = 0
### It counts the number of variants. A register with 0/0 is not counted
num_variants = 0
### It counts the number of vcf with calls
num_records = 0
for r in l_record:
if (type(r) == vcf.model._Record):
num_records += 1
l_format = ['GT','AD','DP','GQ','PL'] # these are the fields of the genotype taken into account
# by default, the no-call is represented so
hash_none = {'GT':'./.'}
l_gt = num_samples*[['./.','0,0','0','.','.']]
chrm = ""
pos = 0
ref = 0
l_alt = []
l_id = []
l_filter = []
l_set = map(lambda k: None, range(num_samples))
hash_filter = {}
hash_info_all = {}
for r_i in l_record:
if type(r_i) != vcf.model._Record:
continue
chrm = r_i.CHROM
pos = r_i.POS
ref = r_i.REF
l_alt_r = map(lambda sb: sb.__repr__() , r_i.ALT)
#l_s = map(lambda s: s.sample, r_i.samples)
l_s = []
for c in r_i.samples:
if c.gt_bases != None:
l_s.append(c.sample)
if l_alt_r == ['None']: # When the site has being for all the samples genotyped and is HOM_REF
l_alt_r = ['.']
l_alt.extend(l_alt_r)
### Build the ALT fields
l_alt = list(set(l_alt))
alt_str = ','.join(l_alt)
if l_alt != ['.']:
if set(l_alt).intersection(set(['.']))!= set([]):
#if filter(lambda a: a=='.', l_alt) != []:
alt_str = alt_str.replace('.', '')
alt_str = alt_str.replace(',', '')
hash_info = dict(r_i.INFO)
is_HOM_REF = False
is_MULTIALLELIC = False
for sample in l_s:
if r_i.genotype(sample)['GT'] == "0/0":
is_HOM_REF = True
num_calls += 1
elif r_i.genotype(sample)['GT'] != "0/0" and r_i.genotype(sample)['GT'] != None:
num_calls += 1
num_variants += 1
if len(l_alt_r) > 1:
is_MULTIALLELIC = True
if r_i.ID != None:
l_id.extend(r_i.ID.split(';'))
else:
if not is_HOM_REF:
l_id.append('.')
elif is_MULTIALLELIC:
l_id.append('.')
else:
l_id = ['.']
if r_i.QUAL != None:
sum_QUAL += r_i.QUAL
if r_i.QUAL != None:
num_r += 1
for sample in l_s: # Iterating across the samples of a vcf file
i_sample = hash_sample_2_index[sample] # this index is unique
if mode == "combine":
if label_mode == "no_append":
# Instead of printing the absolute path, only the DNA name
#rod = hash_sample_2_rod[sample]
str_aux = sample.split('-')
rod = str_aux[len(str_aux)-1]
else: # mode append
rod = hash_sample_2_rod[sample] + '_%s' % (sample)
f_v = hash_sample_2_file[sample] # this only to track the files that the sample is coming from
i_vcf = hash_vcf_2_readers[f_v] # this only to track the position in the rod priority list of the file/s that the sample is coming from
else: ### revisar!!!!!
if label_mode == "no_append":
rod = ','.join(hash_sample_2_rod[sample])
else: # mode append
rod = ','.join(map(lambda r: r+ "_%s" % (sample), hash_sample_2_rod[sample]))
l_f_v = hash_sample_2_file[sample]
l_i_vcf = map(lambda f_v: hash_vcf_2_readers[f_v], l_f_v)
hash_gt = {} # hash of the genotipe information
if r_i.FILTER != [] and r_i.FILTER != None:
l_filter.extend(r_i.FILTER)
l_set[i_sample] = "filterIn"+rod
hash_filter[sample] = True
else:
l_set[i_sample] = rod
is_PASS = True
if info_mode == "append":
hash_info_all.update(hash_info)
try:
hash_gt['GT'] = r_i.genotype(sample)['GT']
except:
pass
try:
hash_gt['DP'] = str(r_i.genotype(sample)['DP'])
except:
if is_HOM_REF:
dp = hash_info.get('DP',[0])
if type(dp) == int:
hash_gt['DP'] = str(dp)
else:
hash_gt['DP'] = str(dp[0])
pass
try:
AD = r_i.genotype(sample)['AD']
if type(AD) == int:
AD = (int(hash_gt['DP'])-AD,AD)
hash_gt['AD'] = ','.join(map(str,AD))
except:
pass
try:
hash_gt['GQ'] = str(r_i.genotype(sample)['GQ'])
except:
if is_HOM_REF:
hash_gt['GT'] = "0/0"
pass
try:
hash_gt['PL'] = ','.join(map(lambda p: str(p).replace('None','.'), r_i.genotype(sample)['PL']))
except:
pass
l_ = []
for ft in l_format:
ft_gt = hash_gt.get(ft,'.')
if ft == "GT" and str(ft_gt) == 'None':
ft_gt = "./."
elif ft == "AD" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = "0,0"
elif ft == "DP" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = "0"
elif ft == "PL" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = "."
elif ft == "GQ" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = '.'
l_.append(ft_gt)
l_gt[i_sample] = l_
# We check here whether the walk together generator has set in different lines equal key elements (we have seen that it does...!!)
if mode == "combine" and hash_walker.has_key((chrm,pos,ref,alt_str)):
key_repeated = True
else:
key_repeated = False
### Mean quality over the records with qual value assigned
QUAL = 0
if (num_r >= 1):
QUAL = float(sum_QUAL)/num_r
### Generating the strings of the samples which calls overlap.
### Intersection -> means that all the samples (from all the vcf files) have variants and share the same context (i.e. merge or combine context)
l_set = sorted(list(set(l_set)))
set_str = ""
if (num_variants == num_samples):
set_str = "Intersection"
else:
for s in l_set:
if s!=None:
set_str += s+'--'
set_str = set_str[:-2]
### Generating the string of the FILTER field. If any of the records with call is filtered, it is included in the FILTER string
### PASS means all the calls do PASS
num_filtered = len(hash_filter.keys())
l_filter = list(set(l_filter))
filter_string = "PASS"
if l_filter != []: # in case any call is filtered
#if num_calls == num_filtered:
# JUNE'16: OJO!!! if all the samples in the pool are filtered, so, filteredInALL and NC = num_samples. Otherwise, we do not know which samples are filtered
if num_samples == num_filtered:
set_str = "FilteredInAll"
filter_string = ""
for f in l_filter:
if f!='PASS':
filter_string += f+';'
filter_string = filter_string[:-1]
# we check whether the sample in set is wthin the set list already saved in the hash_walker
# the set field which inclued all the samples having the variant
if key_repeated:
l_set_walker = hash_walker[(chrm,pos,ref,alt_str)]['info'].split(';')[0]
l_set_walker = l_set_walker.split('--')
num_samples_walker = int(hash_walker[(chrm,pos,ref,alt_str)]['info'].split(';')[1].split("=")[1])
# l_set_walker is a list as follows: ['set=*vcf','*vcf',...,filterInvcf*]
l_set_walker = clean_walker(l_set_walker)
# sometimes l_set is full of None's because the vcf module cannot found in the list of alleles the allele number
# l_set is the list of the samples with the variant (the first element is always a None)
if l_set[0] == None:
l_set = l_set[1:]
if len(l_set) > 0:
l_set_unique = str(l_set[0])
# number of samples that were not included before in the same key hash_walker (in order to include them now)
# this is FUNDAMENTAL since "set=FilteredInAll" is even when NC=1, NC=12, etc.
new_num_samples = 0
if len(l_set) > 1:
# check whether rod is a list
for s in l_set:
if str(s) not in l_set_walker:
# we check whether the sample is filter in (previously if it has "filterIn" it does, otherwise no
if "filterIn" not in str(s):
filter_s = "PASS"
else:
filter_s = "filtered"
if filter_s != 'PASS':
l_set_walker.append(s)
else:
l_set_walker = [s] + l_set_walker
new_num_samples = new_num_samples + 1
else:
new_num_samples = 1
if l_set_walker == ["FilteredInAll"]:
num_calls = num_samples
else:
if l_set_unique not in l_set_walker:
if "filterIn" not in l_set_unique:
filter_s = "PASS"
else:
filter_s = "filtered"
if filter_s != 'PASS' and l_set_walker == ["FilteredInAll"]:
l_set_walker = ["FilteredInAll"]
elif filter_s != 'PASS' and l_set_walker != ["FilteredInAll"]:
l_set_walker.append(l_set_unique)
else:
l_set_walker = [l_set_unique] + l_set_walker
set_str = '--'.join(l_set_walker)
if set_str != "FilteredInAll":
num_calls = len(l_set_walker)
else:
continue
## Build the INFO field
info = "set=%s;NC=%d;NV=%d" % (set_str,num_calls,num_variants)
if info_mode == "append":
str_to_append = ""
try:
l_keys = list(set(hash_info_all.keys()).difference(set(['set','NC','NV'])))
for k in l_keys:
value = hash_info_all[k]
if type(value) == list:
value = ','.join(map(str,value))
str_to_append += ";" + "%s=%s" % (k,value)
except:
pass
info = info+str_to_append
if info[-1] == ";":
info = info[:-1]
## Build the FORMAT field
if remove_non_variants:
if filter(lambda gt: gt == '0/0' or gt == 'None', l_gt) != []:
continue
gt_all = map(lambda i: ':'.join(i) , l_gt)
## Build the ID field
l_id = filter(lambda id: id!='.', list(set(l_id)))
if l_id == []:
l_id = ['.']
id = ','.join(list(set(l_id)))
# ### Build the ALT fields
# l_alt = list(set(l_alt))
# alt_str = ','.join(l_alt)
# if l_alt != ['.']:
# if set(l_alt).intersection(set(['.']))!= set([]):
# #if filter(lambda a: a=='.', l_alt) != []:
# alt_str = alt_str.replace('.', '')
# alt_str = alt_str.replace(',', '')
if mode == "combine":
hash_variant = {}
hash_variant['SNP_id'] = str(id)
hash_variant['qual'] = str(QUAL)
hash_variant['filter'] = filter_string
hash_variant['info'] = info
hash_variant['format'] = ':'.join(l_format)
hash_variant['format_info'] = '\t'.join(gt_all)
hash_walker[(chrm,pos,ref,alt_str)] = hash_variant
else:
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT 40204_Illumina 40204_bowtie 40204_bwa
fo.write("%s\t%d\t%s\t%s\t%s\t%1.2f\t%s\t%s\t%s\t%s\n" % (chrm,pos,id,ref,alt_str,QUAL,filter_string,info,':'.join(l_format),'\t'.join(gt_all)))
if mode == "combine":
# check if hash contains new
fo = open(vcf_file_combined,'w')
fo.write(header)
fo.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t%s\n" % ('\t'.join(l_total_samples)))
#aqui
l_cyto_template = map(lambda i: "chr%i" % (i), range(1,23))+['chrX','chrY','chrM']
hash_cyto_template = dict(zip(l_cyto_template,range(len(l_cyto_template))))
hash_cyto = {}
for chrm in list(set(map(itemgetter(0),hash_walker.keys()))):
if hash_cyto_template.has_key(chrm):
hash_cyto[chrm] = hash_cyto_template[chrm]
else:
chrm_2 = chrm.split('_')[0]
if hash_cyto_template.has_key(chrm_2):
hash_cyto[chrm] = hash_cyto_template[chrm_2]
else:
raise AttributeError('mod_variant.combine_v2: There is chromosome entry not found: %s' % (chrm))
chr_cyto_sorted = map(itemgetter(0),sorted(map(lambda c,p: (c,p) , hash_cyto.keys(),hash_cyto.values()),key=itemgetter(1,0)))
l_fields = ['qual','filter','info','format','format_info']
for key in sorted(sorted(hash_walker.keys(),key=itemgetter(1)),key=lambda x: chr_cyto_sorted.index(x[0])):
l_key = map(str,list(key))
l_key.insert(2,hash_walker[key].get('SNP_id','.'))
key_str = '\t'.join(l_key)
fo.write(key_str + '\t' + '\t'.join(map(lambda field: hash_walker[key].get(field,'.'), l_fields))+'\n')
fo.close()
else:
fo.close()
return vcf_file_combined
########################################################################################################################
# we create a table with all the variants corresponding ONLY to the tissue variants and NOT to the control
# only if blood is True, will be add to "tejido" when lowdepthmosaicism
def parse_control(vcf_input,hash_tissue,blood=False):
# hash_table will have, those variants detected only in tissue and not in blood (with PASS filter)
# only if blood has low_depth ==> we keep it with that filter flag
hash_table = hash_tissue
vcf_reader = vcf.Reader(filename=vcf_input)
for i,r in enumerate(vcf_reader):
try:
if type(r) == _Record:
hash_fields = dict(r.INFO)
#hash_fields.update({'low_mosaic':''})
chr = r.CHROM
pos = r.POS
ref = str(r.REF)
alt = r.ALT
# ALT
if alt != [None]:
l_alt = []
if len(alt) > 1:
for x in alt:
l_alt.append(str(x))
alt_str = ','.join(l_alt)
else:
alt_str = str(alt[0])
l_alt = alt_str
alt = alt_str
key = (chr,pos,ref,alt)
if not hash_table.has_key(key):
continue
# FILTER
l_filter = []
if r.FILTER != [] and r.FILTER != None:
l_filter.extend(r.FILTER)
else:
l_filter.append("PASS")
### Generating the string of the FILTER field. If any of the records with call is filtered, it is included in the FILTER string
### PASS means all the calls do PASS
filter = str(l_filter[0])
if blood == False:
if hash_table.has_key(key):
hash_table.pop(key, None)
else: # we check the filter. if PASS, we remove it, otherwise we add a new filed: Low_Mosaic
if filter == "PASS":
if hash_table.has_key(key):
hash_table.pop(key, None)
else:
mavaf = str(hash_fields.get('MAVAF','.'))
# change low_mosaic info in hash_table
l_info = hash_table[key]['info'].split(";")
new_info = []
for j in l_info:
aux = j.split("=")
if (aux[0] == "low_mosaic"):
new_data = aux[0] + "=" + mavaf
else:
new_data = j
new_info.append(new_data)
info = ';'.join(new_info)
# update ONLY the low_mosaic field in info to the mosaic hash
hash_table[key]['info'] = info
except:
raise RuntimeError('mosaic_somatic_variants_calling.parse_control: Some error has occurred in variant line %i:\n%d' % (i))
return hash_table
########################################################################################################################
# we create a table with all the variants corresponding to the tissue variants
def parse_tissue_vcf(vcf_input):
hash_table = {}
vcf_reader = vcf.Reader(filename=vcf_input)
vcf_reader.infos['low_mosaic'] = _Info('low_mosaic',1,'String',"The percentage of the mosaicism detected in the blood vcf")
header = __get_header(vcf_reader)
for i,r in enumerate(vcf_reader):
try:
if type(r) == _Record:
hash_fields = dict(r.INFO)
hash_fields.update({'low_mosaic':'0'})
chr = r.CHROM
pos = r.POS
ref = str(r.REF)
alt = r.ALT
qual = r.QUAL
if qual == None:
qual = "."
l_info = []
for (key,val) in hash_fields.items():
if isinstance(hash_fields[key],float):
continue
if not isinstance(hash_fields[key],str) and not isinstance(hash_fields[key],int):
aux = key + "=" + ','.join(map(str,hash_fields[key]))
else:
aux = key + "=" + str(hash_fields[key])
l_info.append(aux)
#info = ';'.join("{!s}={!r}".format(key,val) for (key,val) in hash_fields.items())
info = ";".join(l_info)
format = r.FORMAT
# ID
if r.ID == None:
id = '.'
# ALT
if alt != [None]:
l_alt = []
if len(alt) > 1:
for x in alt:
l_alt.append(str(x))
alt_str = ','.join(l_alt)
else:
alt_str = str(alt[0])
l_alt = alt_str
alt = alt_str
hash_table[(chr,pos,ref,alt)] = {}
# FILTER
l_filter = []
if r.FILTER != [] and r.FILTER != None:
l_filter.extend(r.FILTER)
else:
l_filter.append("PASS")
### Generating the string of the FILTER field. If any of the records with call is filtered, it is included in the FILTER string
### PASS means all the calls do PASS
filter = str(l_filter[0])
# FORMAT
sample = r.samples[0].sample
l_format = ['GT','PL','AD']
l_ = []
hash_gt = {}
try:
hash_gt['GT'] = r.genotype(sample)['GT']
except:
pass
try:
hash_gt['PL'] = ','.join(map(lambda p: str(p).replace('None','.'), r.genotype(sample)['PL']))
except:
pass
try:
AD = r.genotype(sample)['AD']
if type(AD) == int:
AD = (int(hash_gt['DP'])-AD,AD)
hash_gt['AD'] = ','.join(map(str,AD))
except:
pass
for ft in l_format:
ft_gt = hash_gt.get(ft,'.')
if ft == "GT" and str(ft_gt) == 'None':
ft_gt = "./."
elif ft == "AD" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = "0,0"
elif ft == "PL" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = "."
l_.append(ft_gt)
gt_all = l_
hash_variant = {}
hash_variant['SNP_id'] = id
hash_variant['qual'] = str(qual)
hash_variant['filter'] = filter
hash_variant['info'] = info
hash_variant['format'] = ':'.join(l_format)
hash_variant['format_info'] = ':'.join(gt_all)
hash_table[(chr,pos,ref,alt)] = hash_variant
except:
raise RuntimeError('mosaic_somatic_variants_calling.parse_tissue_vcf: Some error has occurred in variant line %i:\n%d' % (i))
return hash_table,header,sample
########################################################################################################################
# functions that replaces in a given file, the pattern for the substitution
def replace(file_path, pattern, subst):
#Create temp file
fh, abs_path = mkstemp()
with open(abs_path,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace(pattern, subst))
close(fh)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
########################################################################################################################
def __get_root_name(l_files):
l_basename = map(lambda p: os.path.basename(p) , l_files)
if len(l_files) == 1:
return os.path.splitext(l_basename[0])
l_ = []
for x in izip_longest(*l_basename,fillvalue=None):
l_elem = list(set(list(x)))
if len(l_elem) == 1:
l_.append(l_elem[0])
else:
break
root = ''.join(l_)
if len(root) > 1:
if root[-1] == '.':
root = root[:-1]
return root
########################################################################################################################
# bcftools and samtools, some INDELs cannot annotate properly
# example: ref: ccctcctcctcctcctc
# alt1: ccctcctcctcctcctcctc (insertion ctc) must be ref (-), alt (CTC)
# alt2: ccctcctcctcctcc (deletion tc) must be ref (TC), alt (-)
# example2: ref: TTT
# alt:T must be ref (TT) and alt (-)
# example3: ref: T
# alt: TTT must be ref (-), alt (TT)
def check_minimal_INDEL_representation(pos,ref,alt):
# insertion
if ref.find(alt):
diff = len(ref) - len(alt)
diff = abs(diff) + 1
alt_new = ref[-diff:]
ref_new = alt_new[0]
# deletion
elif alt.find(ref):
diff = len(alt) - len(ref)
diff = abs(diff) + 1
ref_new = ref[-diff:]
alt_new = ref_new[0]
else:
alt_new = alt
ref_new = ref
return pos,ref_new,alt_new
########################################################################################################################
# McArthur lab
def get_minimal_representation(pos, ref, alt):
# If it's a simple SNV, don't remap anything
if len(ref) == 1 and len(alt) == 1:
return pos, ref, alt
else:
# strip off identical suffixes
while(alt[-1] == ref[-1] and min(len(alt),len(ref)) > 1):
alt = alt[:-1]
ref = ref[:-1]
# strip off identical prefixes and increment position
while(alt[0] == ref[0] and min(len(alt),len(ref)) > 1):
alt = alt[1:]
ref = ref[1:]
pos += 1
#print 'returning: ', pos, ref, alt
return pos, ref, alt
########################################################################################################################
def __get_header_v2(vcf_file):
l_header = []
header = ""
fi = open(vcf_file,'r')
for l in fi.readlines():
if l[0] == '#':
l_header.append(l)
else:
break
fi.close()
header = "".join(l_header)
return header
########################################################################################################################
def __get_header(record):
header = ""
try:
hash_metadata = record.metadata
except AttributeError:
hash_metadata = {}
for key in hash_metadata:
if (type(hash_metadata[key])==str):
header += "##%s=%s\n" % (key,hash_metadata[key])
else:
for met in hash_metadata[key]:
if type(met) == str:
header += "##%s=%s\n" % (key,met)
else:
header += "##%s=<" % (key)
for key_k in met:
header += "%s=%s," % (key_k,str(met[key_k]))
header = header[:-1]
header += ">\n"
#_Info = collections.namedtuple('Info', ['id', 'num', 'type', 'desc'])
try:
hash_info = record.infos
except AttributeError:
hash_info = {}
for info in hash_info.keys():
num_str = ""
if hash_info[info].num == None:
num_str = '.'
else:
num_str = str(hash_info[info].num)
header += "##INFO=<ID=%s,Number=%s,Type=%s,Description=\"%s\">\n" % (hash_info[info].id,num_str,hash_info[info].type,hash_info[info].desc)
#_Filter = collections.namedtuple('Filter', ['id', 'desc'])
try:
hash_filter = record.filters
except AttributeError:
hash_filter = {}
for filt in hash_filter.keys():
header += "##FILTER=<ID=%s,Description=\"%s\">\n" % (hash_filter[filt].id,hash_filter[filt].desc)
#_Format = collections.namedtuple('Format', ['id', 'num', 'type', 'desc'])
# It is set by hand
header += "##FORMAT=<ID=AD,Number=.,Type=Integer,Description=\"Allelic depths for the ref and alt alleles in the order listed\">\n##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Approximate read depth (reads with MQ=255 or with bad mates are filtered)\">\n##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Quality\">\n##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n##FORMAT=<ID=PL,Number=G,Type=Integer,Description=\"Normalized, Phred-scaled likelihoods for genotypes as defined in the VCF specification\">\n"
#'Contig', ['id', 'length']
try:
hash_contigs = record.contigs
except AttributeError:
hash_contigs = {}
for cont in hash_contigs:
header += "##contig=<ID=%s,length=%d>\n" % (hash_contigs[cont].id,hash_contigs[cont].length)
return header
########################################################################################################################
# Function that splits each multi-allelic row into 2 or more separates (DP and PL as well)
def split_multiallelic_vcf_to_simple(l_vcf,bcftools_path,threshold,logger):
l_vcf_split = []
logger.info('Splitting each variant with multi-allelic locus ...\n')
for index, vcf_file in enumerate(l_vcf):
# Extract the sample name from the VCF file
bcftools_query_args = [bcftools_path, 'query', '-l', vcf_file]
try:
sample_name = subprocess.check_output(bcftools_query_args).rstrip()
except subprocess.CalledProcessError, e:
msg = 'variant_allele_fraction_filtering: Error running bcftools query -l :%s' % str(e)
print msg
raise RuntimeError(msg)
fileName, fileExtension = os.path.splitext(vcf_file)
vcf_file_split = fileName + '.split.vcf'
vcf_reader = vcf.Reader(filename=vcf_file)
## INFO fields
hash_info = dict(vcf_reader.infos)
## header
header = __get_header(vcf_reader)
l_format = ['GT', 'PL', 'AD']
fileName, fileExtension = os.path.splitext(vcf_file)
vcf_file_split = fileName + '.split.vcf'
## 1. Write in the corresponding splitted vcf file, the header
fo = open(vcf_file_split,'w')
fo.write(header)
fo.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t%s\n" %sample_name)
## 2. For each vcf file (sample), iterate for each record, and separate in 2 o more rows, the multiallelic sites
for i,r in enumerate(vcf_reader):
if type(r) == _Record:
chr = r.CHROM
pos = r.POS
id = r.ID
if id == None:
id = '.'
ref = str(r.REF).strip()
alt = r.ALT
qual = r.QUAL
info = r.INFO
format = r.FORMAT
filter = r.FILTER
if filter == []:
filter = "PASS"
else:
filter = str(filter[0])
l_s = r.samples # samples of each vcf
# en este caso solo hay un sample
for sample in l_s:
if 'GT' in format:
sample_GT = sample['GT']
if sample_GT is None:
continue
else:
sample_GT = '.'
if 'PL' in format:
l_PL = sample['PL']
#l_PL = sample_PL.split(",")
else:
sample_PL = '.'
if 'AD' in format:
sample_AD = sample['AD']
else:
sample_AD = '.'
l_alt = []
if len(alt) > 1:
for x in alt:
l_alt.append(str(x))
alt_str = ','.join(l_alt)
else:
alt_str = str(alt[0])
if len(l_alt) > 1:
mavaf = info['MAVAF']
l_avaf = info['AVAF'].split('-')
ref_AD = sample_AD[0]
for index,a in enumerate(l_alt):
## Split from the INFO field:AVAF. And if update the MAVAF value in the alternative allele cases
avaf = l_avaf[index]
mavaf = avaf
alt_aux = str(alt[index])
# l_PL extract the first 3 elements...
start = index * 3
end = start + 3
l_PL_aux = l_PL[start:end]
sample_AD_aux = [ref_AD,sample_AD[index+1]]
str_to_append = ""
try:
l_keys = list(set(info.keys()).difference(set(['AVAF','MAVAF'])))
for k in l_keys:
value = info[k]
if type(value) == list:
value = ','.join(map(str,value))
str_to_append += ";" + "%s=%s" % (k,value)
except:
pass
new_info = "AVAF=%s;MAVAF=%s" % (avaf,mavaf)
info_print = new_info + str_to_append
if info_print[-1] == ";":
info_print = info_print[:-1]
# ACHTUNG!! si avaf < mosaicism, hay que cambiar la etiqueta de FILTER
if float(avaf) < threshold:
filter = "LowDepthAltMosaicism"
## Build the FORMAT field
sample_PL = l_PL_aux
format_info = sample_GT + ":" + ','.join(map(str,sample_PL)) + ":" + ','.join(map(str,sample_AD_aux))
# minimum INDEL representation
if r.INFO.has_key('INDEL'):
pos_new,ref_new,alt_new = check_minimal_INDEL_representation(pos,ref,a)
pos,ref,alt_aux = pos_new,ref_new,alt_new
alt_aux = alt_aux.strip()
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT SAMPLE_NAME
fo.write("%s\t%d\t%s\t%s\t%s\t%1.2f\t%s\t%s\t%s\t%s\n" % (chr,pos,id,ref,alt_aux,qual,filter,info_print,':'.join(l_format),format_info))
else:
# we do printing without doing anything: INFO and FORMAT fields tal y como estan
sample_PL = l_PL
format_info = sample_GT + ":" + ','.join(map(str,sample_PL)) + ":" + ','.join(map(str,sample_AD))
str_to_append = ""
try:
l_keys = list(set(info.keys()))
for k in l_keys:
value = info[k]
if type(value) == list:
value = ','.join(map(str,value))
str_to_append += ";" + "%s=%s" % (k,value)
except:
pass
info_print = str_to_append
if info_print[-1] == ";":
info_print = info_print[:-1]
if info_print[0] == ";":
info_print = info_print[1:]
# minimum INDEL representation
if r.INFO.has_key('INDEL'):
pos_new,ref_new,alt_new = check_minimal_INDEL_representation(pos,ref,alt_str)
pos,ref,alt_str = pos_new,ref_new,alt_new
alt_str = alt_str.strip()
fo.write("%s\t%d\t%s\t%s\t%s\t%1.2f\t%s\t%s\t%s\t%s\n" % (chr, pos, id, ref, alt_str, float(qual), filter, info_print, ':'.join(l_format),format_info))
fo.close()
logger.info("%s split done \n" %(vcf_file_split))
l_vcf_split.append(vcf_file_split)
logger.info("Splitting finished! ...\n")
return l_vcf_split
########################################################################################################################
# This function computes the AVAF and checks whether a record's VAF is >= threshold (0.07 by default)
# min_allele_balance: the minimum number account in the alternative allele
def variant_allele_fraction_filtering(l_vcf,bcftools_path,threshold,logger,min_allele_balance=0.02):
l_vcf_avaf_filtered = []
logger.info('AVAF new INFO field determination...\n')
for index, vcf_file in enumerate(l_vcf):
# Extract the sample name from the VCF file
bcftools_query_args = [bcftools_path, 'query', '-l', vcf_file]
try:
sample_name = subprocess.check_output(bcftools_query_args).rstrip()
except subprocess.CalledProcessError, e:
msg = 'variant_allele_fraction_filtering: Error running bcftools query -l :%s' % str(e)
print msg
raise RuntimeError(msg)
fileName, fileExtension = os.path.splitext(vcf_file)
vcf_file_filtered = fileName + ".AVAF.filtered" + str(int(threshold*100)) + "%.vcf" # vcf file with the AVAF filtered depending on the threshold
dict_filters = {}
vcf_reader = vcf.Reader(filename=vcf_file)
dict_filters.update(vcf_reader.filters)
## 1. Define the new INFO field that will be included
vcf_reader.infos['AVAF'] = _Info('AVAF', 1, 'String', 'Alternative variant allele frequency', '', '')
vcf_reader.infos['MAVAF'] = _Info('MAVAF', 1, 'String', 'Maximum alternative variant allele frequency, the most representative one', '', '')
#vcf_reader.infos['ALTSTR'] = _Info('ALTSTR',1,'String',"All the alternative alleles with a frequency higher than mosaicism threshold")
vcf_reader.filters['LowDepthAltMosaicism'] = _Filter('LowDepthAltMosaicism', 'The most representative alternative variant allele frequency is lower than the mosaicism threshold')
## header
header = __get_header(vcf_reader)
l_format = ['GT','PL','AD']
## 2. Write the header into the corresponding filtered VCF file
fo = open(vcf_file_filtered, 'w')
fo.write(header)
fo.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t%s\n" % sample_name)
# to break (continue) in inner for loop
keeplooping = False
## 3. For each vcf file (sample), iterate for each record, and compute the AVAF (alternative variant allele fraction)
for i,r in enumerate(vcf_reader):
if type(r) == _Record:
chr = r.CHROM
pos = r.POS
id = r.ID
if id == None:
id = '.'
ref = r.REF
alt = r.ALT
qual = r.QUAL
# pos_new,ref_new,alt_new = get_minimal_representation(pos, ref, alt)
# pos,ref,alt = pos_new,ref_new,alt_new
# si hay presencia de un alelo alternativo seguimos, si no, lo quitamos del vcf (no hay cambio), limpio
# alt = [None]
if alt != [None]:
l_alt = []
if len(alt) > 1:
for x in alt:
l_alt.append(str(x))
alt_str = ','.join(l_alt)
else:
alt_str = str(alt[0])
l_alt = alt_str
info = r.INFO
format = r.FORMAT
l_s = r.samples # samples of each vcf
# en este caso solo hay un sample
for sample in l_s:
if 'GT' in format:
sample_GT = sample['GT']
if sample_GT is None:
keeplooping = True
if sample_GT == "./.":
keeplooping = True
else:
sample_GT = '.'
if 'PL' in format:
l_PL = sample['PL']
#l_PL = sample_PL.split(",")
else:
sample_PL = '.'
if 'AD' in format:
sample_AD = sample['AD']
else:
sample_AD = '.'
if keeplooping:
continue
ref_depth = float(sample_AD[0])
if len(sample_AD) > 2:
l_alt_depth = sample_AD[1:len(sample_AD)]
alt_depth = l_alt_depth[0]
else:
l_alt_depth = float(sample_AD[1])
alt_depth = sample_AD[1]
# If the site is homo alt ==> ref_depth could be 0
alt_major = False
if ref_depth == 0:
ref_depth = alt_depth
elif alt_depth > ref_depth:
alt_major = True
if len(sample_AD) > 2:
if len(sample_AD) == 3:
alt_depth2 = float(l_alt_depth[1])
total_depth = alt_depth + ref_depth
avaf = float(alt_depth/total_depth)
if alt_major :
total_depth2 = alt_depth2 + alt_depth
else:
total_depth2 = alt_depth2 + ref_depth
avaf2 = float(alt_depth2/total_depth2)
# filtramos alt1 ? si alt1 se filtra tambien el alt2 (proque van en orden)
if avaf <= min_allele_balance:
continue
# si alt2 se filtra, quitamos del alt_str
if avaf2 <= min_allele_balance:
l_alt.pop()
sample_AD.pop()
# eliminamos los 3 ultimos GT's correspondientes al alelo
del l_PL[-3:]
alt_str = ','.join(l_alt)
elif len(sample_AD) == 4:
alt_depth2 = float(l_alt_depth[1])
alt_depth3 = float(l_alt_depth[2])
total_depth = alt_depth + ref_depth
avaf = float(alt_depth/total_depth)
if alt_major:
total_depth2 = alt_depth2 + alt_depth
else:
total_depth2 = alt_depth2 + ref_depth
avaf2 = float(alt_depth2/total_depth2)
if alt_major:
total_depth3 = alt_depth3 + alt_depth
else:
total_depth3 = alt_depth3 + ref_depth
avaf3 = float(alt_depth3/total_depth3)
# filtramos alt1??? si alt1 se filtra tambien el alt2 y alt3, todo.
if avaf <= min_allele_balance:
continue
# si alt2 se filtra, quitamos del alt_str
if avaf2 <= min_allele_balance:
# solo seria al primer alt, porque avaf3 sera menor (van en orden)
l_alt = l_alt[0]
sample_AD = sample_AD[0:2]
l_PL = l_PL[0:3]
alt_str = str(l_alt)
elif avaf3 <= min_allele_balance:
l_alt.pop()
sample_AD.pop()
del l_PL[-3:]
alt_str = ','.join(l_alt)
else:
total_depth = alt_depth + ref_depth
avaf = float(alt_depth/total_depth)
# si avaf < min_allele_balance directamente lo filtramos. No pasa ni a la etiqueta de lowMosaicism. kaka
if avaf <= min_allele_balance:
continue
## l_PL must be a 3 multiple ==> 3 * len(l_alt). We must remove or add 255 (for instance, we do not use this data) not to have errors during the annotation (otherwise, snpEff crashes)
if not isinstance(l_alt,str):
if len(l_PL) != 3*len(l_alt):
diff = len(l_PL) - (3 * len(l_alt))
if diff > 0:
del l_PL[-diff:]
else:
l_PL.extend(np.repeat(255, np.abs(diff)))
else:
if len(l_PL) != 3:
diff = len(l_PL) - 3
if diff > 0:
del l_PL[-diff:]
else:
l_PL.extend(np.repeat(255, np.abs(diff)))
## MAVAF
if len(sample_AD) > 2:
# we identify the most representative alternative allele, and we look whether is >= threshold mosaicism
max_allele = float(max(map(int,l_alt_depth))) # a.index(max(a))
mavaf = float(max_allele/(ref_depth + max_allele))
if mavaf >= threshold:
filter = "PASS"
else:
filter = "LowDepthAltMosaicism"
else:
mavaf = avaf
if mavaf >= threshold:
filter = "PASS"
else:
# ##FILTER=<ID=LowDepthAltMosaicism,Description="Allele depth lower than the mosaic threshold">
filter = "LowDepthAltMosaicism"
##AVAF and malt. We now define malt, maximum alternative allele (the one with the major frequency).
##alt tendra los alelos alternativos cuya frecuencia es > threshold mosaicism
if type(l_alt) == list :
if len(l_alt) == 3:
avaf_str = str(round(avaf,2)) + "-" + str(round(avaf2,2)) + '-' + str(round(avaf3,2))
malt = alt_str[0]
if len(l_alt) > 0:
malt = l_alt[0]
alt = ','.join(l_alt)
else:
malt = str(alt[0])
alt = str(l_alt[0])
elif len(l_alt) == 2:
avaf_str = str(round(avaf,2)) + "-" + str(round(avaf2,2))
if len(l_alt) > 0:
malt = l_alt[0]
alt = ','.join(l_alt)
else:
malt = str(alt[0])
alt = str(alt[0])
else:
avaf_str = str(round(avaf,2))
if type(l_alt) == list:
malt = l_alt[0]
alt = ','.join(l_alt)
else:
malt = str(alt[0])
alt = str(alt[0])
else:
avaf_str = str(round(avaf,2))
if type(l_alt) == list:
malt = l_alt[0]
alt = ','.join(l_alt)
else:
malt = str(alt[0])
alt = str(alt[0])
## INFO new fields generation
new_info = "AVAF=%s;MAVAF=%s" % (avaf_str,str(round(mavaf,2)))
#new_info = "AVAF=%s;MAVAF=%s;ALTSTR=%s" % (avaf_str,str(round(mavaf,2)),alt_str)
str_to_append = ""
try:
l_keys = list(set(info.keys()).difference(set(['AVAF','MAVAF'])))
for k in l_keys:
value = info[k]
if type(value) == list:
value = ','.join(map(str,value))
str_to_append += ";" + "%s=%s" % (k,value)
except:
pass
info_print = new_info + str_to_append
if info_print[-1] == ";":
info_print = info_print[:-1]
## Build the FORMAT field
#sample_PL = ','.join(map(str,l_PL))
sample_PL = l_PL
format_info = sample_GT + ":" + ','.join(map(str,sample_PL)) + ":" + ','.join(map(str,sample_AD))
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT SAMPLE_NAME
fo.write("%s\t%d\t%s\t%s\t%s\t%1.2f\t%s\t%s\t%s\t%s\n" % (chr,pos,id,ref,alt,qual,filter,info_print,':'.join(l_format),format_info))
fo.close()
logger.info("%s created \n" %(vcf_file_filtered))
l_vcf_avaf_filtered.append(vcf_file_filtered)
return l_vcf_avaf_filtered
########################################################################################################################
def capture_callings(l_bcf,bcftools_path,logger):
l_vcf = []
for bcf_file in l_bcf:
fileName, fileExtension = os.path.splitext(bcf_file)
vcf_file = fileName + ".vcf"
logger.info("bcftools call --> %s\n" %(bcf_file))
#$bcf_path call -Am -O v $bcf_file -o $vcf_file
bcftools_args = [bcftools_path,'call','-Am','-O','v',bcf_file,'-o',vcf_file]
bcftools_sal = Popen(bcftools_args,stdin=PIPE,stdout=PIPE,stderr=PIPE,close_fds=True,bufsize=1)
(trash,logdata) = bcftools_sal.communicate()
bcftools_sal.wait()
if logdata != "":
if logdata.lower().find("error") != -1:
raise RuntimeError('mosaic_somatic_variants_calling.capture_callings: Error in bcftools call:\n%s\n' % (logdata))
logger.info("bcftools calling done!\n")
l_vcf.append(vcf_file)
return l_vcf
########################################################################################################################
def check_samtools_bctools_versions(samtools_path,bcftools_path):
# /home/kibanez/Escritorio/samtools-1.3.1/samtools --version
samtools_args = [samtools_path,'--version']
file_s = "samtools_version"
f_samtools = open(file_s,'w')
samtools_sal = Popen(samtools_args,stdin=PIPE,stdout=f_samtools,stderr=PIPE,close_fds=True,bufsize=1)
(trash,logdata) = samtools_sal.communicate()
samtools_sal.wait()
if logdata != "":
if logdata.lower().find("error") != -1:
raise RuntimeError('mosaic_somatic_variants_calling.check_samtools_bcftools_versions: Error in samtools --version:\n%s\n' % (logdata))
f_samtools.close()
# /home/kibanez/Escritorio/bcftools-1.3.1/bcftools --version
bcftools_args = [bcftools_path,'--version']
file_b = "bcftools_version"
f_bcftools = open(file_b,'w')
bcftools_sal = Popen(bcftools_args,stdin=PIPE,stdout=f_bcftools,stderr=PIPE,close_fds=True,bufsize=1)
(trash,logdata) = bcftools_sal.communicate()
bcftools_sal.wait()
if logdata != "":
if logdata.lower().find("error") != -1:
raise RuntimeError('mosaic_somatic_variants_calling.check_samtools_bcftools_versions: Error in bcftools --version:\n%s\n' % (logdata))
f_bcftools.close()
# We compare the versions' output
v_samtools = ""
with open(file_s) as infile:
for line in infile:
if 'samtools' in line:
v_samtools = line
v_bcftools = ""
with open(file_b) as infile:
for line in infile:
if 'bcftools' in line:
v_bcftools = line
if v_samtools.split(" ")[1] == v_bcftools.split(" ")[1]:
versions = True
else:
versions = False
# we do remove the temporal files
if os.path.isfile(file_s):
os.remove(file_s)
if os.path.isfile(file_b):
os.remove(file_b)
return versions
########################################################################################################################
def mpileup_calling(l_bam,bed,fasta,samtools_path,variant_path,q_value,q_value2,logger):
l_bcf = []
for i, bam_file in enumerate(l_bam):
logger.info('Samtools mpileup --> %s \n' %bam_file)
bam_name = os.path.splitext(os.path.basename(bam_file))[0]
sample_folder = os.path.join(variant_path, bam_name)
if not os.path.exists(sample_folder):
os.mkdir(sample_folder)
bcf_file = os.path.join(sample_folder, bam_name + '.bcf')
f_bcf = open(bcf_file,'w')
#$samtools_path mpileup -Buf $ref_fasta --positions $bed --output-tags DP,AD,ADF,ADR,SP,INFO/AD,INFO/ADF,INFO/ADR -q 0 -Q 0 $bam_file > $bcf_file
mpileup_args = [samtools_path, 'mpileup', '-Buf', fasta, '--positions', bed, '--output-tags', 'DP,AD,ADF,ADR,SP,INFO/AD,INFO/ADF,INFO/ADR',
'-q', q_value, '-Q', q_value2, bam_file]
mpileup_sal = Popen(mpileup_args, stdin=PIPE, stdout=f_bcf, stderr=PIPE, close_fds=True, bufsize=1)
(trash, logdata) = mpileup_sal.communicate()
mpileup_sal.wait()
if logdata != "":
if logdata.lower().find("error") != -1:
raise RuntimeError('mosaic_somatic_variants_calling.mpileup_calling: Error in samtools mpileup:\n%s\n' % logdata)
f_bcf.close()
l_bcf.append(bcf_file)
logger.info('samtools mpileup done!\n')
return l_bcf
########################################################################################################################
# Function that selectes the INFO and FORMAT fields, and then, downgrades to VCF4.1. And it also changes the FORMAT AD field, that is badly defined in the new version VCF4.2
def select_columns_and_vTransform(l_vcf,bcftools_path,logger):
l_vcf_filtered = []
logger.info("Extracting fields from the FORMAT and INFO fields and downgrading to VCF4.1 ...\n")
for vcf_file in l_vcf:
fileName, fileExtension = os.path.splitext(vcf_file)
vcf_filtered = fileName + "_filtered.vcf"
# 1) Extract FORMAT and INFO fields
# $bcf_path annotate -x INFO/ADF,INFO/ADR,INFO/SGB,INFO/AD,INFO/RPB,INFO/MQB,INFO/MQSB,INFO/BQB,INFO/MQ0F,INFO/AC,INFO/AN,INFO/DP4,INFO/VDB,^FORMAT/GT,FORMAT/AD,FORMAT/PL $vcf_file -o $vcf_filtered
manipulate_sal = Popen([bcftools_path,'annotate','-x','INFO/ADF,INFO/ADR,INFO/SGB,INFO/AD,INFO/RPB,INFO/MQB,INFO/MQSB,INFO/BQB,INFO/MQ0F,INFO/AC,INFO/AN,INFO/DP4,INFO/VDB,^FORMAT/GT,FORMAT/AD,FORMAT/PL',vcf_file,'-o',vcf_filtered],stdin=PIPE, stdout=PIPE, stderr=PIPE,close_fds=True,bufsize=1)
(trash,logdata) = manipulate_sal.communicate()
manipulate_sal.wait()
if logdata != "":
if logdata.lower().find('fallo') != -1:
raise RuntimeError('mosaic_somatic_variants_calling.clean_columns_and_vTransform: Error when launching bcftools annotate -x :\n%s' % (logdata))
# 2) Downgrade VCF4.2 version to VCF4.1
# sed "s/##fileformat=VCFv4.2/##fileformat=VCFv4.1/" $vcf_filtered | sed "s/(//" | sed "s/)//" | sed "s/,Version=\"3\">/>/" | sed 's/##FORMAT=<ID=AD,Number=R,Type=Integer,Description="Allelic depths">/##FORMAT=<ID=AD,Number=.,Type=Integer,Description="Allelic depths for the ref and alt alleles in the order listed"> /g' > $vcf_filtered_v4_1
if not os.path.isfile(vcf_filtered):
raise IOError('The vcf file already filtered does not exist %s' % (vcf_filtered))
else:
replace(vcf_filtered,"##fileformat=VCFv4.2","##fileformat=VCFv4.1")
replace(vcf_filtered,"(","")
replace(vcf_filtered,")","")
replace(vcf_filtered,",Version=\"3\">",">")
replace(vcf_filtered,"##FORMAT=<ID=AD,Number=R,Type=Integer,Description=\"Allelic depths\">","##FORMAT=<ID=AD,Number=.,Type=Integer,Description=\"Allelic depths for the ref and alt alleles in the order listed\">")
l_vcf_filtered.append(vcf_filtered)
logger.info("done!\n")
return l_vcf_filtered
########################################################################################################################
def run(argv=None):
if argv is None: argv = sys.argv
parser = OptionParser(add_help_option=True,description="",formatter= optparse.TitledHelpFormatter(width = 200))
parser.add_option("--cfg", default=None,
help= 'Input cfg file',
dest="f_cfg")
parser.add_option("--m", default=None,
help= 'The desired threshold of the mosaicism (by default the minimum threshold is set to 0.07 (7%))',
dest="f_threshold")
parser.add_option("--s", default=False, action="store_true",
help= 'The cfg file must contain tissue, blood if it is available and control samples in order to analyze the mosaicism somatic changes',
dest="f_somatic")
(options, args) = parser.parse_args(argv[1:])
if len(argv) == 1:
sys.exit(0)
parser.check_required("--cfg")
formatter = logging.Formatter('%(asctime)s - %(module)s - %(levelname)s - %(message)s')
console = logging.StreamHandler()
console.setFormatter(formatter)
console.setLevel(logging.INFO)
logger = logging.getLogger("preprocess")
logger.setLevel(logging.INFO)
logger.addHandler(console)
try:
cfg_file = options.f_cfg
if not os.path.exists(cfg_file):
raise IOError('NGS_call_somatic_mosaic_variants: The cfg file %s does not exist' % cfg_file)
hash_cfg = mod_cfg.read_cfg_file(cfg_file)
f_threshold = options.f_threshold
if f_threshold is None:
f_threshold = 0.07
else:
f_threshold = float(f_threshold)
# input required
analysis_bed = hash_cfg.get('analysis_bed', '')
input_files = hash_cfg.get('input_files', '')
q_value = hash_cfg.get('q_value', '20')
q_value2 = hash_cfg.get('Q_value', '20')
# reference required
ref_fasta = hash_cfg.get('ref_fasta', '')
# software required
samtools_path = hash_cfg.get('samtools_path', '')
bcftools_path = hash_cfg.get('bcftools_path', '')
# output required
variant_path = hash_cfg.get('variant_path', '')
if q_value is None:
logger.info('The value of the base threshold quality (q) would be 0 by default. Please, introduce a proper q_value \n')
if q_value2 is None:
logger.info('The value of the mapping quality threshold (Q) would be 0 by default. Please, introduce a proper Q_value \n')
if not os.path.isfile(ref_fasta):
raise IOError("The file does not exist. %s" % ref_fasta)
if not os.path.isfile(analysis_bed):
raise IOError("The analysis bed does not exist. %s" % analysis_bed)
if not os.path.exists(samtools_path):
raise IOError('The samtools_path path does not exist %s' % samtools_path)
if not os.path.exists(variant_path):
raise IOError('The variant path does not exist %s' % variant_path)
f_somatic = options.f_somatic
if f_somatic == False:
# if '--s' option is not given, then the mosaic variants are computed from the aligned bam files
l_bam = input_files.split(",")
for i in l_bam:
if not os.path.isfile(i):
raise IOError("NGS_call_somatic_mosaic_variants: The given BAM file does not exist. %s" % i)
# IMPORTANT PRELIMINAR STEP: check whether the samtools and bcftools versions are the same (it usually updates at the same level and time)
versions_tools = check_samtools_bctools_versions(samtools_path,bcftools_path)
if not versions_tools:
raise IOError('Warning: samtools and bcftools versions must be the same. It is absolutely required for an adequate usage of this tool. Please visit http://www.htslib.org/download/ \n')
logger.info("The mosaicism variant detection starts...\n")
# (1) mpileup the BAM files
l_bcf = mpileup_calling(l_bam, analysis_bed, ref_fasta, samtools_path, variant_path, q_value, q_value2, logger)
# (2) capture of the calls
l_vcf = capture_callings(l_bcf, bcftools_path, logger)
# (3) extract the desired columns and transform them from VCF4.1 to VCF4.2 in order to work easily with them
l_vcf_trans = select_columns_and_vTransform(l_vcf, bcftools_path, logger)
# (4) manual filtering: creation of AVAF (alternative variant allele fraction) depending on the threshold (--m) inserted
l_vcf_avaf = variant_allele_fraction_filtering(l_vcf_trans, bcftools_path, f_threshold, logger)
# (5) samples_run/controls annotation
# (5.1) split multi-allelic sites into different simple rows
l_vcf_split = split_multiallelic_vcf_to_simple(l_vcf_avaf, bcftools_path, f_threshold, logger)
# (5.2) combine: samples_run (compute how many times the variant is detected among the samples included in the cfg file
mod_variant.annotate_vcf(l_vcf_split, variant_path, hash_cfg)
logger.info('The mosaicism variant detection finished!\n')
logger.info('You only need to annotate the resulting VCF files ;_)\n')
else:
logger.info('The somatic mosaicism variant detection starts...\n')
# input files
tissue_id = hash_cfg.get('tissue_id', '')
blood_id = hash_cfg.get('blood_id', '')
control_id = hash_cfg.get('control_id', '')
sample_name = hash_cfg.get('sample_name', '')
if not os.path.isfile(tissue_id):
raise IOError("The variant file corresponding to the tissue does not exist. %s" % tissue_id)
if blood_id != "":
if not os.path.isfile(blood_id):
raise IOError("The variant file corresponding to the blood does not exist. %s" % blood_id)
elif blood_id is None:
warnings.warn('The variant file corresponding to the blood is not given. Thus, the somatic analysis would be done filtering with the given control samples. \n')
l_control = control_id.split(",")
for i in l_control:
if not os.path.isfile(i):
raise IOError("The variant file corresponding to on of the control does not exist. %s" % i)
if sample_name == "":
raise IOError("The sample name must be have info. %s" % i)
fileName, fileExtension = os.path.splitext(tissue_id)
file_somatic = fileName + "_VS_blood_and_controls"
hash_tissue,header,sample = parse_tissue_vcf(tissue_id)
if hash_tissue == {}:
return hash_tissue
# Sometimes there is no paired-blood sample which corresponds to the tissue sample. In those cases, we only filtered by the control samples
if blood_id != "":
hash_table_tmp = parse_control(blood_id, hash_tissue, blood=True)
hash_tissue = hash_table_tmp
for vcf_control in l_control:
hash_table_tmp = parse_control(vcf_control, hash_tissue)
hash_tissue = hash_table_tmp
vcf_file_somatic = file_somatic + ".vcf"
fo = open(vcf_file_somatic, 'w')
fo.write(header)
fo.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t%s\n" % sample)
chr_cyto_sorted = map(lambda i: "chr%i" % i, range(1, 23))+['chrX', 'chrY', 'chrM']
l_fields = ['qual', 'filter', 'info', 'format', 'format_info']
for key in sorted(sorted(hash_tissue.keys(),key=itemgetter(1)),key=lambda x: chr_cyto_sorted.index(x[0])):
l_key = map(str,list(key))
l_key.insert(2,hash_tissue[key].get('SNP_id','.'))
key_str = '\t'.join(l_key)
fo.write(key_str + '\t' + '\t'.join(map(lambda field: hash_tissue[key].get(field,'.'), l_fields))+'\n')
fo.close()
logger.info('The somatic mosaicism variant detection finished!\n')
logger.info('You only need to annotate the resulting VCF file ;)\n')
except:
print >> sys.stderr, '\n%s\t%s' % (sys.exc_info()[0],sys.exc_info()[1])
sys.exit(2)
########################################################################################################################
if __name__=='__main__':
run()
<file_sep># mOsAiC
Somatic mosaicism brings up to the presence at the same time, in a single individual, of two genetically distinct cell populations arising from a postzygotic mutation.
Numerous computational approaches have been developed in order to detect somatic mosaic variants from NGS data. They usually do the analysis from paired tumor-normal samples, as Strelka (Saunders et al. 2012) or MuTect (Cibulskis et al. 2013). Strelka uses a Bayesian strategy representing continuous allele frequencies for both tumor and normal samples, and influencing the expected genotype of the normal. It assumes the normal samples as a mixture of germline variation with noise, and the tumor samples as a mixture of the normal sample with somatic variation (Saunders et al. 2012). The approach presented in MuTect also uses a Bayesian classifier in the variant detection in the tumor sample, once the low quality sequences have been removed, filters in order to remove false positives resulting from correlated sequencing artifacts not captured by the error model, and appoints to the variants as somatic or germline by a second Bayesian classifier (Cibulskis et al. 2013). These two strategies have described benchmarking approaches that use real, rather than simulated, sequencing data to evaluate the accuracy of each tool. However, due to the homology of several genomic locus within the panel design, low quality reads that could be mapped in other homologous regions are removed with these both strategies.
We here present an in-house developed approach in order to detect variants in mosaicism from a list of already aligned reads files (BAM files). The summary of the NGS preprocessing is as follows:
The patient samples were merged in the same pool, and sequenced. This detail is important to the post-processing step, since working with several samples is advantageous. For instance, it permits to identify variants that are recurrent along the samples in the pool, due to frequent polymorphism or sequencing artifacts.
Pair-end raw reads coming from Illumina NextSeq500 were converted into paired FASTQ files using bcl2fastq-v2.15.0.4 software from Illumina (https://github.com/brwnj/bcl2fastq). Then preprocessing was done by using Trimmomatic (Bolger et al. 2014), trimming and cropping FASTQ data as well as removing adapters.. Afterwards, balanced reads were mapped to the published human genome reference (UCSC hg19) by using Bowtie2 aligner (Langmead and Salzberg 2012). Then PCR duplicate reads were removed by using one of the most commonly used approach Picard MarkDuplicates (http://broadinstitute.github.io/picard/). Following the best practices proposed by GATK (McKenna et al. 2010; DePristo et al. 2011; Van der Auwera et al. 2013; Vrijenhoek et al. 2015), an INDEL realignment was done afterwards in order to determine suspicious intervals which were likely in need of realignment (GATK RealignerTargetCreator function) and then, a local realignment of reads was done to correct misalignments due to presence of INDELs (GATK IndelRealigner function). The input of this mosaicism tool we here develope are the aligned, realigned, and subsequent recalibrated reads (BAM files).
Step 1. mpileup
The first step is to extract the base-pair information for each genomic position from the BAM files, facilitating the subsequent SNP/INDEL calling. For such aim, samtools mpileup v1.3 (Li et al. 2009; Li 2011a) was used for each BAM file along the sequenced pool. The base quality (q value) and the mapping quality scores (Q value) were set to 0, since many genes in the capture design have pseudo-genes or high homology with other genomics sites. Thus, using recommended scores (q = 20, Q = 20) would include out reads mapped in these genes with low mapping quality scores defined by the aligner considering that they also map in other genomic position.
Step 2. Call capture
Once all the base-pair information was available for each sample, the variant capture calling was proceed. For such purpose, bcftools v1.3 (Li 2011) was applied. It is important to take into account, that both samtools and bcftools must be from the same version. This calling was done keeping all possible alternate alleles at each variant site (option -A) as well as keeping all the alternative models for multiallelic and rare-variant callings (option -m) in a VCF file. As consequence, in this step a VCF file was obtained containing the capture of the variant calling, considering the previous two conditions.
Step 3. AVAF computation
We here define a new attribute encompassing the alternative variant allele fraction (AVAF). Our objective is to detect and categorize all the alternative alleles in each genomic position along the design panel, with a minimum value of ratio of 0.02 (2%). We assume that alternative alleles with a frequency less than 0.02 might be due to background noise, error during the variant calling process or attributable to a low complex region.
The idea is to compute the ratio (i.e., percentage) in which each alternative variant allele appears in each genomic position, and label it depending on whether the AVAF is higher or lower than the mosaicism threshold given (m option in the tool). Particularly, the threshold used in this study was setup to 0.07.
The purpose of this mosaicism tool was to empower the final user when analyzing the resulting entire table. Thus, this approach does not filter out any variant in which AVAF is less than m. Accordingly, when the AVAF is lower than m, the variant is labelled as LowDepthAltMosaicism. In contrast, whether AVAF is higher than m, the variant is identified as PASS. This classification states in the FILTER field in the corresponding output VCF file.
Step 4. Split multi-allelic sites into simple sites
In the VCF file there are genomic positions with an unique alternative allele, and other position in which multiple alternative alleles are detected. For a proper analysis, it is convenient and necessary to separate multi allelic sites into individual sites.
After this step, the resulting VCF file could contain many repetitive genomic positions with same reference alleles but different alternative alleles information. In this manner it is possible to study separately each alternative allele with its corresponding AVAF, among other attribute values.
Step 5. Variant recurrence determination
Once the AVAF attribute is defined for each alternative allele along all the genomic positions defined, the recurrence of each variant throughout all the samples analyzed with the same designed genomic regions was computed. This value was included in a new attribute called samplesRun.
This step is essential since it permits to observe in how many samples examined with the same genomic bed file is detected each variant. Very high value of samplesRun might indicate very polymorphic variants or sequencing bias among others. In consequence, low samplesRun values (i.e., samplesRun <= 2) are very interesting, since it suggests that only in the studying sample or in another one is detected that variant.
In this step the percentage or ratio of the variant in a set of pseudo-control samples (11 healthy exomes) computation is also done.
Step 6. Germinal vs. somatic variants comparison
The contrasting of matched tumor (i.e., tissue) and germline (i.e., blood) samples is crucial to distinguish somatic from germline variants, bringing out low allelic fraction from background noise caused by the high-sequencing error rate. Hence, working with single or individual tumor samples would lead to an identification of a larger number of false positive events.
This step is independent from the previous part. Here the tissue and the blood VCF files from the same sample are studied, and also the VCF files from two healthy samples as control. If there is no a corresponding blood sample, only the tissue and the two control samples are examined. The process starts with all the variants detected in the tissue VCF. All the variants identified as PASS in the blood VCF are filtered out, since they are also detected in the tissue VCF and cannot be somatic mosaic variants. In contrast, variants identified as LowDepthAltMosaicism are not filtered out, but enriched with a new attribute called lowMosaic, which contains the corresponding AVAF value of the variant in the blood sample. When processing the control samples the procedure is stringent. Variants labelled as PASS or LowDepthAltMosaicism in the control samples that are also detected in the tissue VCF are separated out.
Two configuration (*cfg) example files are included:
> configuration_mosaic_computation_part1.cfg configuration file compresses the Step 1 to Step5: the mosaic variant computation.
> configuration_somatic_mosaic_computation_part2.cfg configuration file compresses the Step 6. This step requires the previus step : the somatic mosaic variant computation.
NOTE: this tool does not annotate the resulting VCF files. This must be done independently.
<file_sep>#!/usr/bin/python
import sys, re, os, string, urllib, time, math, random, subprocess, shutil, itertools
from os import path as osp
from os import stat
import optparse
from subprocess import Popen , PIPE
from itertools import izip_longest,chain,product
from operator import itemgetter
import itertools
import vcf
from vcf.parser import _Filter,_Record,_Info,_Format,_SV
from vcf.utils import walk_together
import pysam
import numpy,scipy
from collections import namedtuple
def __get_root_name(l_files):
l_basename = map(lambda p: os.path.basename(p), l_files)
if len(l_files) == 1:
return os.path.splitext(l_basename[0])
l_ = []
for x in izip_longest(*l_basename, fillvalue=None):
l_elem = list(set(list(x)))
if len(l_elem) == 1:
l_.append(l_elem[0])
else:
break
root = ''.join(l_)
if len(root) > 1:
if root[-1] == '.':
root = root[:-1]
return root
def __get_header(record):
header = ""
try:
hash_metadata = record.metadata
except AttributeError:
hash_metadata = {}
for key in hash_metadata:
if (type(hash_metadata[key])==str):
header += "##%s=%s\n" % (key,hash_metadata[key])
else:
for met in hash_metadata[key]:
if type(met) == str:
header += "##%s=%s\n" % (key,met)
else:
header += "##%s=<" % (key)
for key_k in met:
header += "%s=%s," % (key_k,str(met[key_k]))
header = header[:-1]
header += ">\n"
#_Info = collections.namedtuple('Info', ['id', 'num', 'type', 'desc'])
try:
hash_info = record.infos
except AttributeError:
hash_info = {}
for info in hash_info.keys():
num_str = ""
if hash_info[info].num == None:
num_str = '.'
else:
num_str = str(hash_info[info].num)
header += "##INFO=<ID=%s,Number=%s,Type=%s,Description=\"%s\">\n" % (hash_info[info].id,num_str,hash_info[info].type,hash_info[info].desc)
#_Filter = collections.namedtuple('Filter', ['id', 'desc'])
try:
hash_filter = record.filters
except AttributeError:
hash_filter = {}
for filt in hash_filter.keys():
header += "##FILTER=<ID=%s,Description=\"%s\">\n" % (hash_filter[filt].id,hash_filter[filt].desc)
#_Format = collections.namedtuple('Format', ['id', 'num', 'type', 'desc'])
# It is set by hand
header += "##FORMAT=<ID=AD,Number=.,Type=Integer,Description=\"Allelic depths for the ref and alt alleles in the order listed\">\n##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Approximate read depth (reads with MQ=255 or with bad mates are filtered)\">\n##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Quality\">\n##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n##FORMAT=<ID=PL,Number=G,Type=Integer,Description=\"Normalized, Phred-scaled likelihoods for genotypes as defined in the VCF specification\">\n"
#'Contig', ['id', 'length']
try:
hash_contigs = record.contigs
except AttributeError:
hash_contigs = {}
for cont in hash_contigs:
header += "##contig=<ID=%s,length=%d>\n" % (hash_contigs[cont].id,hash_contigs[cont].length)
return header
# Function to split and include within a list, vcf's pass and filtered in each variant
def clean_walker(l_set_walker):
l_clean = []
for i in l_set_walker:
if "set" in i:
aux = i.split('=')
l_clean.append(aux[1])
else:
l_clean.append(i)
return l_clean
def combine_vcf_v2(l_vcf_files,l_rod_priority,mode,ouput_path=None,**kwargs):
"""
There are two modes:
1. merge: this is when you need to join hetereogeneous calls into the same register with the condition that they overlap into the same genomic position.
It could be merged calls from different tools belonging to the same sample
2. combine: When you need to join the same variants (shared ref and alt alleles) into one register. Its recommended in familiar studies. In this mode, only different samples are allowed
"""
if mode == "merge":
get_key = lambda r: (r.CHROM, r.POS)
elif mode == "combine":
get_key = lambda r: (r.CHROM, r.POS, r.REF, r.ALT)
else:
raise InputError('mod_variant.combine_vcf_v2: The mode of combining vcf is not correct: %s' % (mode))
### specific configurations
label_mode = "no_append" ### possibilities: append/no_append
if kwargs.has_key('label_mode'):
label_mode = kwargs['label_mode']
info_mode = "overwrite" ### possibilities: overwrite/append
if kwargs.has_key('info_mode'):
info_mode = kwargs['info_mode']
remove_non_variants = False ### possibilities: True/False
if kwargs.has_key('remove_non_variants'):
remove_non_variants = kwargs['remove_non_variants']
### 1. generate the name of the combined file
vcf_file_combined = ""
root_name = __get_root_name(l_vcf_files)
if root_name == "":
root_name = "v"
if ouput_path == None:
vcf_file_combined = root_name+'.combined.vcf'
else:
vcf_file_combined = os.path.join(ouput_path,root_name+'.combined.vcf')
### 2. Check out the arragement of the vcf files in function of the rod list
if l_rod_priority == [] or l_rod_priority == None:
l_rod_priority = l_vcf_files
label_mode = "no_append"
if len(l_rod_priority) <> len(l_vcf_files):
raise InputError('mod_variant.combine_vcf_v2: The number of ids in the list of rod priority do not agree with the number of vcf files')
num_files = len(l_vcf_files)
header = ""
### 3. Fill the list of vcf readers. In addition, it configure the INFO field in the header
### Also, it assigns the index of the file and the samples
### It writes the header into a string
l_readers = []
hash_vcf_2_readers = {}
hash_sample_2_file = {}
hash_sample_2_index= {}
hash_sample_2_rod = {}
i_sample = 0
dict_filters = {}
for vcf_file in l_vcf_files:
r = vcf.Reader(filename=vcf_file)
dict_filters.update(r.filters)
for (i,(vcf_file,rod)) in enumerate(zip(l_vcf_files,l_rod_priority)):
r = vcf.Reader(filename=vcf_file)
r.infos['NC'] = _Info('NC', 1, 'Integer', 'Number of Calls', '', '')
r.infos['NV'] = _Info('NV', 1, 'Integer', 'Number of Variants', '', '')
r.infos['set'] = _Info('set', 1, 'String', 'Source of the vcf file', '', '')
r.filters = dict_filters
l_readers.append(r)
if header == "":
header = __get_header(r)
if header.find('##contig') == -1:
try:
hash_contigs = r.contigs
for cont in hash_contigs:
header += "##contig=<ID=%s,length=%d>\n" % (hash_contigs[cont].id,hash_contigs[cont].length)
except AttributeError:
pass
hash_vcf_2_readers[os.path.basename(vcf_file)] = i
l_s = r.samples # samples of each vcf
for sample in l_s:
if mode == "combine":
if hash_sample_2_file.has_key(sample):
raise RuntimeError("combine_vcf:combine_vcf_v2: There are at least two vcf files with the same sample label\n")
if mode == "merge": # the sample could be in two o more vcf files
hash_sample_2_file.setdefault(sample,[])
hash_sample_2_file[sample].append(os.path.basename(vcf_file))
hash_sample_2_rod.setdefault(sample,[])
hash_sample_2_rod[sample].append(rod)
else:
hash_sample_2_file[sample] = os.path.basename(vcf_file)
hash_sample_2_rod[sample] = rod
if not hash_sample_2_index.has_key(sample): # in case of duplicated samples, it assigns the lowest index
hash_sample_2_index[sample] = i_sample
i_sample += 1
l_total_samples = map(itemgetter(1),sorted(map(lambda (i,s): (i,s), zip(hash_sample_2_index.values(),hash_sample_2_index.keys()))))
num_samples = len(l_total_samples)
if mode != "combine":
fo = open(vcf_file_combined,'w')
fo.write(header)
fo.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t%s\n" % ('\t'.join(l_total_samples)))
### 4. It iterates over each reader (vcf_file) and then, for the samples of the reader
elif mode == "combine":
hash_walker = {}
for l_record in vcf.utils.walk_together(*l_readers,vcf_record_sort_key=get_key):
sum_QUAL = 0
num_r = 0
num_s = 0
filter_string = ""
set_str = ""
is_PASS = False
hash_format = {}
### It counts the number of calls. A register with None means no call ./.
num_calls = 0
### It counts the number of variants. A register with 0/0 is not counted
num_variants = 0
### It counts the number of vcf with calls
num_records = 0
for r in l_record:
if (type(r) == vcf.model._Record):
num_records += 1
l_format = ['GT','AD','DP','GQ','PL'] # these are the fields of the genotype taken into account
# by default, the no-call is represented so
hash_none = {'GT':'./.'}
l_gt = num_samples*[['./.','0,0','0','.','.']]
chrm = ""
pos = 0
ref = 0
l_alt = []
l_id = []
l_filter = []
l_set = map(lambda k: None, range(num_samples))
hash_filter = {}
hash_info_all = {}
for r_i in l_record:
if type(r_i) <> vcf.model._Record:
continue
chrm = r_i.CHROM
pos = r_i.POS
ref = r_i.REF
l_alt_r = map(lambda sb: sb.__repr__() , r_i.ALT)
#l_s = map(lambda s: s.sample, r_i.samples)
l_s = []
for c in r_i.samples:
if c.gt_bases <> None:
l_s.append(c.sample)
if l_alt_r == ['None']: # When the site has being for all the samples genotyped and is HOM_REF
l_alt_r = ['.']
l_alt.extend(l_alt_r)
### Build the ALT fields
l_alt = list(set(l_alt))
alt_str = ','.join(l_alt)
if l_alt <> ['.']:
if set(l_alt).intersection(set(['.']))<> set([]):
#if filter(lambda a: a=='.', l_alt) <> []:
alt_str = alt_str.replace('.', '')
alt_str = alt_str.replace(',', '')
hash_info = dict(r_i.INFO)
is_HOM_REF = False
is_MULTIALLELIC = False
for sample in l_s:
if r_i.genotype(sample)['GT'] == "0/0":
is_HOM_REF = True
num_calls += 1
elif r_i.genotype(sample)['GT'] <> "0/0" and r_i.genotype(sample)['GT'] <> None:
num_calls += 1
num_variants += 1
if len(l_alt_r) > 1:
is_MULTIALLELIC = True
if r_i.ID <> None:
l_id.extend(r_i.ID.split(';'))
else:
if not is_HOM_REF:
l_id.append('.')
elif is_MULTIALLELIC:
l_id.append('.')
else:
l_id = ['.']
if r_i.QUAL <> None:
sum_QUAL += r_i.QUAL
if r_i.QUAL <> None:
num_r += 1
for sample in l_s: # Iterating across the samples of a vcf file
i_sample = hash_sample_2_index[sample] # this index is unique
if mode == "combine":
if label_mode == "no_append":
# Instead of printing the absolute path, only the DNA name
#rod = hash_sample_2_rod[sample]
str_aux = sample.split('-')
rod = str_aux[len(str_aux)-1]
else: # mode append
rod = hash_sample_2_rod[sample] + '_%s' % (sample)
f_v = hash_sample_2_file[sample] # this only to track the files that the sample is coming from
i_vcf = hash_vcf_2_readers[f_v] # this only to track the position in the rod priority list of the file/s that the sample is coming from
else: ### revisar!!!!!
if label_mode == "no_append":
rod = ','.join(hash_sample_2_rod[sample])
else: # mode append
rod = ','.join(map(lambda r: r+ "_%s" % (sample), hash_sample_2_rod[sample]))
l_f_v = hash_sample_2_file[sample]
l_i_vcf = map(lambda f_v: hash_vcf_2_readers[f_v], l_f_v)
hash_gt = {} # hash of the genotipe information
if r_i.FILTER <> [] and r_i.FILTER <> None:
l_filter.extend(r_i.FILTER)
l_set[i_sample] = "filterIn"+rod
hash_filter[sample] = True
else:
l_set[i_sample] = rod
is_PASS = True
if info_mode == "append":
hash_info_all.update(hash_info)
try:
hash_gt['GT'] = r_i.genotype(sample)['GT']
except:
pass
try:
hash_gt['DP'] = str(r_i.genotype(sample)['DP'])
except:
if is_HOM_REF:
dp = hash_info.get('DP',[0])
if type(dp) == int:
hash_gt['DP'] = str(dp)
else:
hash_gt['DP'] = str(dp[0])
pass
try:
AD = r_i.genotype(sample)['AD']
if type(AD) == int:
AD = (int(hash_gt['DP'])-AD,AD)
hash_gt['AD'] = ','.join(map(str,AD))
except:
pass
try:
hash_gt['GQ'] = str(r_i.genotype(sample)['GQ'])
except:
if is_HOM_REF:
hash_gt['GT'] = "0/0"
pass
try:
hash_gt['PL'] = ','.join(map(lambda p: str(p).replace('None','.'), r_i.genotype(sample)['PL']))
except:
pass
l_ = []
for ft in l_format:
ft_gt = hash_gt.get(ft,'.')
if ft == "GT" and str(ft_gt) == 'None':
ft_gt = "./."
elif ft == "AD" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = "0,0"
elif ft == "DP" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = "0"
elif ft == "PL" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = "."
elif ft == "GQ" and (ft_gt == '.' or str(ft_gt) == 'None'):
ft_gt = '.'
l_.append(ft_gt)
l_gt[i_sample] = l_
# We check here whether the walk together generator has set in different lines equal key elements (we have seen that it does...!!)
if mode == "combine" and hash_walker.has_key((chrm,pos,ref,alt_str)):
key_repeated = True
else:
key_repeated = False
### Mean quality over the records with qual value assigned
QUAL = 0
if (num_r >= 1):
QUAL = float(sum_QUAL)/num_r
### Generating the strings of the samples which calls overlap.
### Intersection -> means that all the samples (from all the vcf files) have variants and share the same context (i.e. merge or combine context)
l_set = sorted(list(set(l_set)))
set_str = ""
if (num_variants == num_samples):
set_str = "Intersection"
else:
for s in l_set:
if s<>None:
set_str += s+'--'
set_str = set_str[:-2]
### Generating the string of the FILTER field. If any of the records with call is filtered, it is included in the FILTER string
### PASS means all the calls do PASS
num_filtered = len(hash_filter.keys())
l_filter = list(set(l_filter))
filter_string = "PASS"
if l_filter <> []: # in case any call is filtered
#if num_calls == num_filtered:
# JUNE'16: OJO!!! if all the samples in the pool are filtered, so, filteredInALL and NC = num_samples. Otherwise, we do not know which samples are filtered
if num_samples == num_filtered:
set_str = "FilteredInAll"
filter_string = ""
for f in l_filter:
if f<>'PASS':
filter_string += f+';'
filter_string = filter_string[:-1]
# we check whether the sample in set is wthin the set list already saved in the hash_walker
# the set field which inclued all the samples having the variant
if key_repeated:
l_set_walker = hash_walker[(chrm,pos,ref,alt_str)]['info'].split(';')[0]
l_set_walker = l_set_walker.split('--')
num_samples_walker = int(hash_walker[(chrm,pos,ref,alt_str)]['info'].split(';')[1].split("=")[1])
# l_set_walker is a list as follows: ['set=*vcf','*vcf',...,filterInvcf*]
l_set_walker = clean_walker(l_set_walker)
# sometimes l_set is full of None's because the vcf module cannot found in the list of alleles the allele number
# l_set is the list of the samples with the variant (the first element is always a None)
if l_set[0] == None:
l_set = l_set[1:]
if len(l_set) > 0:
l_set_unique = str(l_set[0])
# number of samples that were not included before in the same key hash_walker (in order to include them now)
# this is FUNDAMENTAL since "set=FilteredInAll" is even when NC=1, NC=12, etc.
new_num_samples = 0
if len(l_set) > 1:
# check whether rod is a list
for s in l_set:
if str(s) not in l_set_walker:
# we check whether the sample is filter in (previously if it has "filterIn" it does, otherwise no
if "filterIn" not in str(s):
filter_s = "PASS"
else:
filter_s = "filtered"
if filter_s <> 'PASS':
l_set_walker.append(s)
else:
l_set_walker = [s] + l_set_walker
new_num_samples = new_num_samples + 1
else:
new_num_samples = 1
if l_set_walker == ["FilteredInAll"]:
num_calls = num_samples
else:
if l_set_unique not in l_set_walker:
if "filterIn" not in l_set_unique:
filter_s = "PASS"
else:
filter_s = "filtered"
if filter_s <> 'PASS' and l_set_walker == ["FilteredInAll"]:
l_set_walker = ["FilteredInAll"]
elif filter_s <> 'PASS' and l_set_walker <> ["FilteredInAll"]:
l_set_walker.append(l_set_unique)
else:
l_set_walker = [l_set_unique] + l_set_walker
set_str = '--'.join(l_set_walker)
if set_str <> "FilteredInAll":
num_calls = len(l_set_walker)
else:
continue
## Build the INFO field
info = "set=%s;NC=%d;NV=%d" % (set_str, num_calls, num_variants)
if info_mode == "append":
str_to_append = ""
try:
l_keys = list(set(hash_info_all.keys()).difference(set(['set','NC','NV'])))
for k in l_keys:
value = hash_info_all[k]
if type(value) == list:
value = ','.join(map(str,value))
str_to_append += ";" + "%s=%s" % (k,value)
except:
pass
info = info+str_to_append
if info[-1] == ";":
info = info[:-1]
## Build the FORMAT field
if remove_non_variants:
if filter(lambda gt: gt == '0/0' or gt == 'None', l_gt) <> []:
continue
gt_all = map(lambda i: ':'.join(i) , l_gt)
## Build the ID field
l_id = filter(lambda id: id<>'.', list(set(l_id)))
if l_id == []:
l_id = ['.']
id = ','.join(list(set(l_id)))
# ### Build the ALT fields
# l_alt = list(set(l_alt))
# alt_str = ','.join(l_alt)
# if l_alt <> ['.']:
# if set(l_alt).intersection(set(['.']))<> set([]):
# #if filter(lambda a: a=='.', l_alt) <> []:
# alt_str = alt_str.replace('.', '')
# alt_str = alt_str.replace(',', '')
if mode == "combine":
hash_variant = {}
hash_variant['SNP_id'] = str(id)
hash_variant['qual'] = str(QUAL)
hash_variant['filter'] = filter_string
hash_variant['info'] = info
hash_variant['format'] = ':'.join(l_format)
hash_variant['format_info'] = '\t'.join(gt_all)
hash_walker[(chrm,pos,ref,alt_str)] = hash_variant
else:
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT 40204_Illumina 40204_bowtie 40204_bwa
fo.write("%s\t%d\t%s\t%s\t%s\t%1.2f\t%s\t%s\t%s\t%s\n" % (chrm,pos,id,ref,alt_str,QUAL,filter_string,info,':'.join(l_format),'\t'.join(gt_all)))
if mode == "combine":
# check if hash contains new
fo = open(vcf_file_combined,'w')
fo.write(header)
fo.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t%s\n" % ('\t'.join(l_total_samples)))
#aqui
l_cyto_template = map(lambda i: "chr%i" % (i), range(1,23))+['chrX','chrY','chrM']
hash_cyto_template = dict(zip(l_cyto_template,range(len(l_cyto_template))))
hash_cyto = {}
for chrm in list(set(map(itemgetter(0),hash_walker.keys()))):
if hash_cyto_template.has_key(chrm):
hash_cyto[chrm] = hash_cyto_template[chrm]
else:
chrm_2 = chrm.split('_')[0]
if hash_cyto_template.has_key(chrm_2):
hash_cyto[chrm] = hash_cyto_template[chrm_2]
else:
raise AttributeError('mod_variant.combine_v2: There is chromosome entry not found: %s' % (chrm))
chr_cyto_sorted = map(itemgetter(0),sorted(map(lambda c,p: (c,p) , hash_cyto.keys(),hash_cyto.values()),key=itemgetter(1,0)))
l_fields = ['qual','filter','info','format','format_info']
for key in sorted(sorted(hash_walker.keys(),key=itemgetter(1)),key=lambda x: chr_cyto_sorted.index(x[0])):
l_key = map(str,list(key))
l_key.insert(2,hash_walker[key].get('SNP_id','.'))
key_str = '\t'.join(l_key)
fo.write(key_str + '\t' + '\t'.join(map(lambda field: hash_walker[key].get(field,'.'), l_fields))+'\n')
fo.close()
else:
fo.close()
return vcf_file_combined
def __change_sample_name(vcf_file,new_label='overlapping'):
vcf_reader = vcf.Reader(filename=vcf_file)
l_records = []
for record in vcf_reader:
record.samples = [record.samples[0]]
l_records.append(record)
vcf_reader.samples = [new_label]
vcf_tmp = os.path.splitext(vcf_file)[0]+'.tmp.vcf'
vcf_writer = vcf.Writer(open(vcf_tmp , 'w'), vcf_reader)
for record in l_records:
vcf_writer.write_record(record)
return vcf_tmp
def annotate_vcf(l_vcf_files_run,output_path,hash_cfg):
"""
The goal of this function is to include the info of:
- the variants of the same run (in order to detect possible artefacts)
- the variants of a set of controls (to disambiguate polymophisms from rare variants)
"""
if hash_cfg.has_key('ref_fasta'):
ref_fasta_file = hash_cfg['ref_fasta']
else:
raise AttributeError("mod_variant.variant_calling: The fasta file of the reference has not been configured properly")
if hash_cfg.has_key('gatk_path'):
gatk_path = hash_cfg['gatk_path']
else:
raise AttributeError("mod_variant.variant_calling: The path of the gatk jar file has not been configured properly")
l_vcf_files_run_out = []
t1 = time.time()
sys.stdout.write('Creating enriched annotations in the vcf files ...\n')
sys.stdout.flush()
#### 1. Get the variants that overlap in all the samples in a same run. The overlapping changes are written in the file 'vcf_overlapping_variants_within_run'
sys.stdout.write('\nGetting the variants that completely overlap in all the samples of the run...\n')
vcf_overlapping_variants_within_run = combine_vcf_v2(l_vcf_files_run,[],"combine",output_path)
### the samples of the file 'vcf_overlapping_variants_within_run' are replaced to generic sample 'overlapping'
vcf_tmp = __change_sample_name(vcf_overlapping_variants_within_run)
name_vcf_overlapping_variants_within_run = os.path.join(output_path,'combined_overlapping_variants_within_run.vcf')
if os.path.exists(vcf_tmp):
os.rename(vcf_tmp,name_vcf_overlapping_variants_within_run)
if os.path.exists(vcf_tmp+'.idx'):
os.remove(vcf_tmp+'.idx')
sys.stdout.write('[done]\n')
sys.stdout.flush()
## 2. Combine the variants of controls
sys.stdout.write('\nIncluding the information of controls...\n')
sys.stdout.flush()
l_vcf_files_controls = map(itemgetter(1),hash_cfg.get('controls',[]))
if l_vcf_files_controls <> []:
num_controls = len(l_vcf_files_controls)
sys.stdout.write('Number of controls loaded: %s\n' % (num_controls))
l_controls = map(lambda i: 'control_%d' % (i), range(num_controls))
controls_vcf_old = combine_vcf_v2(l_vcf_files_controls,l_controls,"combine",output_path)
###controls_vcf_old = combine_vcf(l_vcf_files_controls,l_controls,ref_fasta_file,gatk_path,"multiple",output_path)
controls_vcf = os.path.join(output_path,'combined_controls.vcf')
if os.path.exists(controls_vcf_old):
os.rename(controls_vcf_old,controls_vcf)
if os.path.exists(controls_vcf_old+'.idx'):
os.remove(controls_vcf_old+'.idx')
control_reader = vcf.Reader(filename=controls_vcf)
run_reader = vcf.Reader(filename=name_vcf_overlapping_variants_within_run)
# march'16: we do now hash with 4-tuple id's: chrom, pos, ref and alt (because combine 'combine' puts in 2 different lines identical chr-pos but with different ref-alt info!!
#hash_control = dict(map(lambda r: ((r.CHROM,r.POS,r.REF),r), control_reader))
hash_control = map( lambda r: (
map ( lambda a: ((r.CHROM,r.POS,r.REF,str(a)),r),
r.ALT),
)[0],
control_reader
)
hash_control2 = list(itertools.chain.from_iterable(hash_control))
hash_control = dict(hash_control2)
hash_run = map( lambda r: (
map ( lambda a: ((r.CHROM,r.POS,r.REF,str(a)),r),
r.ALT),
)[0],
run_reader
)
hash_run2 = list(itertools.chain.from_iterable(hash_run))
hash_run = dict(hash_run2)
## 3.b Include the controls and overlapping variants into the vcf files
for vcf_target in l_vcf_files_run:
target_reader = vcf.Reader(filename=vcf_target)
target_reader.infos['CT'] = _Info('CT',1,'String',"Controls: pool of controls that a variant appears")
target_reader.infos['NC'] = _Info('NC',1,'Integer',"Number of Controls: number of controls that a variant appears")
target_reader.infos['SR'] = _Info('SR',0,'Float',"Percentage of the samples within the run with the variant")
target_reader.infos['SR_string'] = _Info('SR_string',0,'String',"SamplesRun: pool of samples in which a variant is detected")
vcf_target_annotated = os.path.splitext(vcf_target)[0]+'.annotated.vcf'
l_vcf_files_run_out.append(vcf_target_annotated)
target_writer = vcf.Writer(open(os.path.join(output_path,vcf_target_annotated), 'w'), target_reader)
#hash_target = dict(map(lambda (i,r): ((i,r.CHROM,r.POS),r), enumerate(target_reader)))
hash_target = map( lambda r:(
map (lambda a: ((r.CHROM,r.POS,r.REF,str(a)),r),
r.ALT),
)[0],
target_reader
)
hash_target2 = list(itertools.chain.from_iterable(hash_target))
hash_target = dict(hash_target2)
#for (i,chr,pos,ref,alt) in sorted(hash_target.keys()):
for (chr,pos,ref,alt) in sorted(hash_target.keys()):
r_target = hash_target[(chr,pos,ref,alt)]
if hash_control.has_key((chr,pos,ref,alt)):
r_control = hash_control[(chr,pos,ref,alt)]
if r_control.INFO['set'] == 'Intersection':
r_target.INFO['CT'] = "Allcontrols_N%d" % (num_controls)
r_target.INFO['NC'] = num_controls
else:
r_target.INFO['CT'] = r_control.INFO['set']
str_controls = r_control.INFO['set']
if str_controls == "FilteredInAll":
r_target.INFO['NC'] = num_controls
else:
l_ = str_controls.split('-')
r_target.INFO['NC'] = len(l_)
if hash_run.has_key((chr,pos,ref,alt)):
r_run = hash_run[(chr,pos,ref,alt)]
r_target.INFO['SR'] = r_run.INFO['NC']
# we now include the list of the samples that appears in samplesRun
r_target.INFO['SR_string'] = r_run.INFO['set']
#if r_run.INFO['set']=='Intersection':
# r_target.INFO['SR'] = True
target_writer.write_record(r_target)
sys.stdout.write('[done]\n')
sys.stdout.flush()
else:
sys.stdout.write('WARNING: There are no controls included\n')
sys.stdout.flush()
## 3.b Include only overlapping variants (controls are missing) into the vcf files
for vcf_target in l_vcf_files_run:
target_reader = vcf.Reader(filename=vcf_target)
target_reader.infos['CT'] = _Info('CT',1,'String','Controls: pool of controls that a variant appears', '', '')
target_reader.infos['SR'] = _Info('SR',1,'String','Samples of the Run: The field is \'1\' if the variant appears in all the samples of the run', '', '')
vcf_target_annotated = os.path.splitext(vcf_target)[0]+'.annotated.vcf'
l_vcf_files_run_out.append(vcf_target_annotated)
target_writer = vcf.Writer(open(os.path.join(output_path,vcf_target_annotated), 'w'), target_reader)
vcf_to_iterate = walk_together(target_reader,vcf.Reader(filename=vcf_overlapping_variants_within_run)) #vcf_record_sort_key=(CHROM,POS,ALT)
for [record_target,record_run] in vcf_to_iterate:
if type(record_target) == _Record:
if type(record_run) == _Record:
record_target.INFO['SR'] = int(record_run.INFO['set']=='Intersection')
target_writer.write_record(record_target)
t2 = time.time()
sys.stdout.write("done [%0.3fs].\n\n" % (t2-t1))
sys.stdout.flush()
return l_vcf_files_run_out
<file_sep>from setuptools import setup, find_packages
setup(
name='mOsAiC',
version='0.0.1',
packages=find_packages(),
url='https://github.com/kibanez/mosaic',
install_requires=[
'HTSeq==0.9.1',
'PyVCF==0.6.8',
'pandas==0.22.0',
'scipy',
'numpy==1.14.2'
],
license='',
classifiers=[
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Bioinformatics Data science',
'Topic :: Software Development :: Mosaicism Bioinformatics',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2.7.10',
'Programming Language :: Python :: 3.6.5',
],
keywords='sample tracking metagenomics microbiotica',
author='<NAME>',
author_email='<EMAIL>',
description='Detection of somatic mosaicism variants in NGS'
) | 193a341bff5b82d2ac76ef5b9e786cb79327e750 | [
"Markdown",
"Python"
] | 5 | Python | whuang022nccu/mOsAiC | 973e852c5ca47419c4076813907af985bde47e72 | 059a5b12dbf9f301f8857c80584cbbc8d853d756 |
refs/heads/master | <repo_name>161710118/latihan-oop-rpl1<file_sep>/hasil.php
<?php
require_once 'orang.php';
$orang = new orang('Mzaky','bandung','XI-RPL 2','Mahasiswa');
$orang1 = new orang('Sofy','bandung','XI-RPL 2','Pelajar');
$orang2 = new orang('Taufik','bandung','XI-RPL 2','Pelajar');
$orang3 = new orang('Firas','bandung','XI-RPL 2','Pelajar');
$orang4 = new orang('Bagus','bandung','XI-RPL 2','Jomblo');
echo "1. ";
echo "nama: ".$orang->get_nama();
echo"</br>";
echo "tempat lahir: ".$orang->get_tempatlahir();
echo"</br>";
echo "kelas: ".$orang->get_kelas();
echo"</br>";
echo "status: ".$orang->get_status();
echo"</br>";
echo "<br>";
echo "2. ";
echo "nama: ".$orang1->get_nama();
echo"</br>";
echo "tempat lahir: ".$orang1->get_tempatlahir();
echo"</br>";
echo "kelas: ".$orang1->get_kelas();
echo"</br>";
echo "status: ".$orang1->get_status();
echo"</br>";
echo "<br>";
echo "3. ";
echo "nama: ".$orang2->get_nama();
echo"</br>";
echo "tempat lahir: ".$orang2->get_tempatlahir();
echo"</br>";
echo "kelas: ".$orang2->get_kelas();
echo"</br>";
echo "status: ".$orang2->get_status();
echo"</br>";
echo "<br>";
echo "4. ";
echo "nama: ".$orang3->get_nama();
echo"</br>";
echo "tempat lahir: ".$orang3->get_tempatlahir();
echo"</br>";
echo "kelas: ".$orang3->get_kelas();
echo"</br>";
echo "status: ".$orang3->get_status();
echo"</br>";
echo "<br>";
echo "5. ";
echo "nama: ".$orang4->get_nama();
echo"</br>";
echo "tempat lahir: ".$orang4->get_tempatlahir();
echo"</br>";
echo "kelas: ".$orang4->get_kelas();
echo"</br>";
echo "status: ".$orang4->get_status();
echo"</br>";
echo "<br>";
?>
| 3f08966373b40994342654f0d1f8f65805a91da8 | [
"PHP"
] | 1 | PHP | 161710118/latihan-oop-rpl1 | d9fdaa92115a0c6fb8f0648b9861fab48de2cf85 | 815585c42c76fa9bff02687e1a379a4b163ecf1e |
refs/heads/master | <repo_name>KopiSoftware/KerkoportaOS<file_sep>/KerkoportaOS/bootpack.c
#include<stdio.h>
//定义常用颜色
#define COL8_000000 0
#define COL8_FF0000 1
#define COL8_00FF00 2
#define COL8_FFFF00 3
#define COL8_0000FF 4
#define COL8_FF00FF 5
#define COL8_00FFFF 6
#define COL8_FFFFFF 7
#define COL8_C6C6C6 8
#define COL8_840000 9
#define COL8_008400 10
#define COL8_848400 11
#define COL8_000084 12
#define COL8_840084 13
#define COL8_008484 14
#define COL8_848484 15
//asm函数声明部分
void io_hlt(void);
void io_cli(void);
void io_out8(int port, int data);
int io_load_eflags(void);
void io_store_eflags(int eflags);
void init_Vcard(void);
//C语言函数声明部分
void init_palette(void);
void set_palette(int start, int end, unsigned char *rgb);
void draw_box(unsigned char *vram, int xsize, unsigned char c, int x0, int y0,int x1, int y1);
void fill_screen(unsigned char c);
//主函数部分
void HariMain(void)
{
char *p;
int i;
// init_Vcard();
init_palette();
p = (char *) 0xa0000;
for(i = 0; i < 16; i++ )
draw_box(p, 320, i, 0, 0, 320, 200);
for(;;)
io_hlt();
}
void init_palette(void)
{
static unsigned char table_rgb[16*3] = {
0x00,0x00,0x00, //黑色
0xff,0x00,0x00, //亮红
0x00,0xff,0x00, //亮绿
0xff,0xff,0x00, //亮黄
0x00,0x00,0xff, //亮蓝
0xff,0x00,0xff, //亮紫
0x00,0xff,0xff, //浅亮蓝
0xff,0xff,0xff, //白
0xc6,0xc6,0xc6, //亮灰
0x84,0x00,0x00, //暗红
0x00,0x84,0x00, //暗绿
0x84,0x84,0x00, //暗黄
0x00,0x00,0x84, //暗青
0x84,0x00,0x84, //暗紫
0x00,0x84,0x84, //浅暗蓝
0x84,0x84,0x84 //暗灰
}; //定义rgb颜色集
set_palette(0, 15, table_rgb);
return;
}
void set_palette(int start, int end, unsigned char * rgb)
{
int i,eflags;
eflags = io_load_eflags();
io_cli(); //将中断设为0,禁止其他中断
io_out8(0x03c8, start);
for(i=start; i<=end; i++){
io_out8(0x03c9, rgb[0]/4);
io_out8(0x03c9, rgb[1]/4);
io_out8(0x03c9, rgb[2]/4);
rgb += 3;
}
io_store_eflags(eflags); //恢复中断许可
return;
}
//画出填充色框
void draw_box(unsigned char *vram, int xsize, unsigned char c, int x0, int y0,int x1, int y1)
{
int x,y;
for(y = y0; y <= y1; y++)
for(x = x0; x <= x1;x++)
vram[y * xsize + x] = c;
return;
}
void fill_screen(unsigned char c)
{
int i;
char *p;
p = (char*)0xa0000;
for(i = 0; i<= 0xffff;i++)
*(p + i) = 0;
}
<file_sep>/README.md
# KerkoportaOS
Follow the book '30 days to make operation system' and create my system.
This program compiles in the Windows environment.
USER GUIDE
Unpack the package and make sure that two directories are in the same path.
Enter KerkoportaOS and open the file '!cons_nt.bat' and then you will see a
console.The path of the console is already settled in the same directory of
the program.Now input 'make img' and press enter, the complier will generat
a series of files including the image file 'haribote.img'(Okay, this name
is just for now.I will change it as soon as possible).Then the compiling is
done.
Open your VMWare and create a new virtual machine.The operate system option
should be set as 'other system'.Then create a floppy input,push the image
file(haribote.img) in and start the virtual mathine.You will see the operat
ing system.
| c8b08213c9b7c98570fd6419cf91440c13f815c3 | [
"Markdown",
"C"
] | 2 | C | KopiSoftware/KerkoportaOS | 84476a870c6ebff4adee7a5938b2a76e65dc4b6c | 14d479b7dd4cb0631a3456412e64a7437165977b |
refs/heads/main | <repo_name>AbdullahAlHarun-code/rm-invoice<file_sep>/pdfmaker/utils.py
"""renderpdf URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
# from django.contrib import admin
# from django.urls import path
#
# urlpatterns = [
# path('admin/', admin.site.urls),
# ]
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.conf import settings
from xhtml2pdf import pisa
# def fetch_resources(uri, rel):
# sUrl = settings.STATIC_URL # Typically /static/
# sRoot = settings.STATIC_ROOT
# mUrl = settings.MEDIA_URL # Typically /static/media/
# mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/
#
# # convert URIs to absolute system paths
# if uri.startswith(mUrl):
# path = os.path.join(mRoot, uri.replace(mUrl, ""))
# elif uri.startswith(sUrl):
# path = os.path.join(sRoot, uri.replace(sUrl, ""))
# else:
# return uri # handle absolute uri (ie: http://some.tld/foo.png)
#
# # make sure that file exists
# if not os.path.isfile(path):
# raise Exception(
# 'media URI must start with %s or %s' % (sUrl, mUrl)
# )
# return path
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode('utf-8')), result)
#pdf = pisa.CreatePDF(html.encode('utf-8'), dest=result,encoding='utf-8', link_callback=fetch_resources)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
<file_sep>/renderpdf/urls.py
# """renderpdf URL Configuration
#
# The `urlpatterns` list routes URLs to views. For more information please see:
# https://docs.djangoproject.com/en/3.1/topics/http/urls/
# Examples:
# Function views
# 1. Add an import: from my_app import views
# 2. Add a URL to urlpatterns: path('', views.home, name='home')
# Class-based views
# 1. Add an import: from other_app.views import Home
# 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
# Including another URLconf
# 1. Import the include() function: from django.urls import include, path
# 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
# """
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('pdf/', include("pdfmaker.urls")),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
#
# from io import BytesIO
# from django.http import HttpResponse
# from django.template.loader import get_template
#
# from xhtml2pdf import pisa
#
# def render_to_pdf(template_src, context_dict={}):
# template = get_template(template_src)
# html = template.render(context_dict)
# result = BytesIO()
# pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
# if not pdf.err:
# return HttpResponse(result.getvalue(), content_type='application/pdf')
# return None
<file_sep>/pdfmaker/urls.py
from django.contrib import admin
from django.urls import path
from django.http import JsonResponse
from .views import GeneratePdf, GenerateHtmlPdf
#from cart import views as cart_view
#from orders import views as order_view
urlpatterns = [
path('', GeneratePdf.as_view()),
path('html', GenerateHtmlPdf.as_view()),
]
<file_sep>/pdfmaker/apps.py
from django.apps import AppConfig
class PdfmakerConfig(AppConfig):
name = 'pdfmaker'
<file_sep>/pdfmaker/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
from django.template.loader import get_template
from .utils import render_to_pdf
import os
import tempfile
# Create your views here.
class GeneratePdf(View):
def get(self, request, *args, **kwargs):
template = get_template('invoice3.html')
context = {
'invoice_id':12345,
'customer_name':'<NAME>',
'today':'Today',
}
html = template.render(context)
pdf = render_to_pdf('invoice3.html',context)
return HttpResponse(pdf, content_type='application/pdf')
#return HttpResponse(html)
# if pdf:
# response = HttpResponse(pdf, content_type='application/pdf')
# filename = "Invoice_%s.pdf" %("124578")
# content = "inline; filename='%s'" %(filename)
# print(filename)
# download = request.GET.get('download')
# if download:
# content = "attachment; filename='%s'" %(filename)
# response['Content-Disposition'] = content
# return html
# return HttpResponse("Not found!")
class GenerateHtmlPdf(View):
def get(self, request, *args, **kwargs):
template = get_template('invoice2.html')
context = {
'invoice_id':12345,
'customer_name':'<NAME>',
'today':'Today',
}
html = template.render(context)
pdf = render_to_pdf('invoice2.html',context)
printfile = tempfile.mktemp(".txt")
open (printfile, "w").write("hello mammaa adsasd")
os.startfile(printfile, "print")
#return HttpResponse(pdf, content_type='application/pdf')
return HttpResponse(html)
# if pdf:
# response = HttpResponse(pdf, content_type='application/pdf')
# filename = "Invoice_%s.pdf" %("124578")
# content = "inline; filename='%s'" %(filename)
# print(filename)
# download = request.GET.get('download')
# if download:
# content = "attachment; filename='%s'" %(filename)
# response['Content-Disposition'] = content
# return html
# return HttpResponse("Not found!")
| 637da5563b3d168c706cabe0d64af37d9f9fac4c | [
"Python"
] | 5 | Python | AbdullahAlHarun-code/rm-invoice | 6358863f8fd8967e2a78f3168e16ef6b8adc48aa | f29d775c149d8d05c03fa960ee7c9be81857f996 |
refs/heads/main | <repo_name>awais987123/Libarary-Management-System-repo<file_sep>/readme.md
#Libarry Management System in C++
#for missing files contact <EMAIL>
<file_sep>/moc_subscriberwidget.cpp
/****************************************************************************
** Meta object code from reading C++ file 'subscriberwidget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../../../Music/LibraryManagementSystem/GUI/subscriberwidget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'subscriberwidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.14.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_SubscriberWidget_t {
QByteArrayData data[9];
char stringdata0[143];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_SubscriberWidget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_SubscriberWidget_t qt_meta_stringdata_SubscriberWidget = {
{
QT_MOC_LITERAL(0, 0, 16), // "SubscriberWidget"
QT_MOC_LITERAL(1, 17, 18), // "subscriberSelected"
QT_MOC_LITERAL(2, 36, 0), // ""
QT_MOC_LITERAL(3, 37, 21), // "editSubscriberClicked"
QT_MOC_LITERAL(4, 59, 20), // "addSubscriberClicked"
QT_MOC_LITERAL(5, 80, 13), // "addSubscriber"
QT_MOC_LITERAL(6, 94, 14), // "editSubscriber"
QT_MOC_LITERAL(7, 109, 16), // "removeSubscriber"
QT_MOC_LITERAL(8, 126, 16) // "selectBtnClicked"
},
"SubscriberWidget\0subscriberSelected\0"
"\0editSubscriberClicked\0addSubscriberClicked\0"
"addSubscriber\0editSubscriber\0"
"removeSubscriber\0selectBtnClicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_SubscriberWidget[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
7, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 2, 49, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 0, 54, 2, 0x0a /* Public */,
4, 0, 55, 2, 0x0a /* Public */,
5, 0, 56, 2, 0x0a /* Public */,
6, 0, 57, 2, 0x0a /* Public */,
7, 0, 58, 2, 0x0a /* Public */,
8, 0, 59, 2, 0x0a /* Public */,
// signals: parameters
QMetaType::Void, QMetaType::Int, QMetaType::Bool, 2, 2,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void SubscriberWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<SubscriberWidget *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->subscriberSelected((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break;
case 1: _t->editSubscriberClicked(); break;
case 2: _t->addSubscriberClicked(); break;
case 3: _t->addSubscriber(); break;
case 4: _t->editSubscriber(); break;
case 5: _t->removeSubscriber(); break;
case 6: _t->selectBtnClicked(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (SubscriberWidget::*)(int , bool );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SubscriberWidget::subscriberSelected)) {
*result = 0;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject SubscriberWidget::staticMetaObject = { {
QMetaObject::SuperData::link<QWidget::staticMetaObject>(),
qt_meta_stringdata_SubscriberWidget.data,
qt_meta_data_SubscriberWidget,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *SubscriberWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *SubscriberWidget::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_SubscriberWidget.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int SubscriberWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 7)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 7)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 7;
}
return _id;
}
// SIGNAL 0
void SubscriberWidget::subscriberSelected(int _t1, bool _t2)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t1))), const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t2))) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 58724528af26dec0b3628e4d5bb03f7373cdff3e | [
"Markdown",
"C++"
] | 2 | Markdown | awais987123/Libarary-Management-System-repo | 6a674593a7a810a59617c4a32a155e862db59ca4 | c3acf14995b8883fc5eca12482392f0db1ac4286 |
refs/heads/master | <repo_name>DeanGaffney/breakout<file_sep>/server.js
var fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname)).listen(8000, function(){
console.log('Server running on 8000...');
})
app.use(bodyParser.json());
app.post('/scores', function(req, res) {
var scores = require('./js/data/scores.json'); //read file and add new score, then save new score to file
scores.push(req.body);
fs.writeFile('./js/data/scores.json', JSON.stringify(scores), function(err) {
if (err) {
res.send('Something when wrong');
} else {
res.send('Saved!');
}
})
});
app.get('/scores', (req, res) => {
var scores = require('./js/data/scores.json');
res.json(scores);
});
<file_sep>/README.md
# Breakout
Breakout game remade with BabylonJS game engine and new improved features.
# Features
- NodeJs Server with Nodemon restart functionality
- Framework
- The BabylonJS framework was used rather than the playground
- 3 Game Scenes
- Splash Screen
- Game Scene
- Game Over Scene
- Particle Systems
- Ball
- Pendulum ball
- Efficient Scene swapping
- See main/main.js to see how scenes are swapped in a neat manner
- Environment
- Sky box
- Fog
- Textured Walls
- Shadow Generator to cast shadows on the paddle and walls
- Complex Physics Imposters
- Ball collisions are dealt with by complex physic imposters which give the ball an appropriate linear velocity
- Area Walls have physic imposters to simulate a mass of 0 to allow the ball bounce back and forth
- Pendulum is a DistanceJoint which must be hit in order to win the game
- Pendulum box explodes upon blocks being destroyed and a particle system is set off on the pendulum ball
- Game States
- Game states keep track of game triggers, when there are no blocks left the pendulum box explodes open with the use forces and physics imposters
- Powerup manager which gives a player powerups, triggers them and deactivates them.
- Powerups
- Powerup algorithm which spots vacancies in block gaps and places a powerup within a vacant gap
- 3 types of powerups
- LONGER_PADDLE, which scales the paddle to be twice as long
- SPEED_UP, which allows a players paddle to move twice as fast
- SLOW_MOTION, which increases the time step of the physics engine to allow for a slow motion effect.
- Each powerup lasts 6 seconds and a GUI indicates this.
- Controls
- A (Move Left)
- D (Move right)
- W (Rotate left)
- S (Rotate right)
- E (End of game test button, hit to view blocks disappear and pendulum box explode)
- R (Activates a powerup)
- GUI
- Splash Screen
- Play button
- Game Screen
- Score
- Current Powerup
- Blocks Remaining
- Powerup time remaining when a powerup is activated, which follows the paddle
- Game Over Screen
- Replay
- High Scores being written to server for storage
- Sounds
- Blip sound for collisions
- Background sound track
- Powerup Sound
- Explosion Sound
- High Scores
- High scores persisted on the server, client sends data using jquery ajax function, and can request server scores with ajax too
| 89d71581123cbf76f4c6462aa7efc765380683e3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | DeanGaffney/breakout | 950aadb486ee8d045b123e2e39c013a74d7bd120 | ea222c44b4d047a716ee0f8370642a99b828e140 |
refs/heads/master | <file_sep>const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const User = require('./models/user_model')
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET
const uri = process.env.CALLBACK_URI
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
const user = await User.findOne({email: email});
if (user == null) {
return done(null, false, { message: 'No user with that email' })
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: uri
},
function(accessToken, refreshToken, profile, done) {
userProfile=profile;
return done(null, userProfile);
}
));
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize
<file_sep>Passport Google OAuth2 Example
==============================
This is an Express application using Google for authentication via OAuth2 and Local Email and Password authentication.
Both running simultaneously
## Create a Google client ID and client secret
We can create a client ID and client secret using its [Google API Console](https://console.cloud.google.com/apis/dashboard). You need to follow below steps once you open Google API Console
1. From the project drop-down, select an existing project, or create a new one by selecting Create a new project
2. In the sidebar under "APIs & Services", select Credentials
3. In the Credentials tab, select the Create credentials drop-down list, and choose OAuth client ID.
4. Under Application type, select Web application.
5. In Authorized redirect URI use http://localhost:3000/auth/google/callback
6. Press the Create button and copy the generated client ID and client secret
`Note: If Google doesn't support http://localhost:3000, then use http://127.0.0.1:3000`
## Install
1. `git clone https://github.com/Bunty9/passport-google.git myapp`
2. `cd myapp && npm install`
3. Create a .env file in the root directory on package.json level
4. Add GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and SESSION_SECRET to .env file
5. also define PORT and MONGO_URI in the .env file
## Start
run `npm start`
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
## Github
You can check out [My GitHub repository](https://github.com/Bunty9) - your feedback and contributions are welcome!
<file_sep>const router = require('express').Router();
const bcrypt = require('bcrypt')
const passport = require('passport')
const User = require('../models/user_model')
const initializePassport = require('../passport-config')
initializePassport(
passport,
email => User.findOne(users => User.email === email),
id => User.findById(users => User.id === id)
)
router.route('/').get( checkAuthenticated,(req, res)=>{
res.render('index.ejs')
});
router.route('/login').get(checkNotAuthenticated, (req, res)=>{
res.render('login.ejs')
});
router.route('/login').post( checkNotAuthenticated,passport.authenticate('local', {
successRedirect: '/api',
failureRedirect: '/api/login',
failureFlash: true
}))
router.route('/register').get(checkNotAuthenticated, (req, res)=>{
res.render('register.ejs')
});
router.route('/register').post(checkNotAuthenticated, async (req, res)=>{
// hash the passwords
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password,salt);
try{
const user = new User({
username:req.body.username,
password:<PASSWORD>,
email:req.body.email,
});
await user.save();
// res.send({user: user._id});
res.redirect('/api/login')
}catch(err){
console.error(err.message);
res.status(500).send("Server Error");
}
});
router.route('/logout').delete( (req, res) => {
req.logOut()
res.redirect('/api/login')
})
// check if the user is authenticated if not redirect to login , this to block unauthenticated users from accessing the home page
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.redirect('/api/login')
}
// if the user is authenticated redirect to home page if the login/register page is accessed again
function checkNotAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return res.redirect('/api')
}
next()
}
module.exports = router;<file_sep>const express = require("express");
require("dotenv").config();
const cors = require("cors");
const bodyParser = require("body-parser");
const routes = require("./routes/routes");
const mongoConnect = require("./databaseAuth/mongoConnect");
const flash = require("express-flash");
const session = require("express-session");
const passport = require("passport");
const methodOverride = require("method-override");
// Create the express app
const app = express();
const port = process.env.PORT || 5000;
mongoConnect();
// Routes and middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view-engine", "ejs");
app.use(flash());
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(methodOverride("_method"));
app.use("/api", routes);
app.get("/", function (req, res) {
res.redirect("/api/login");
});
app.get(
"/auth/google",
passport.authenticate("google", { scope: ["profile", "email"] })
);
app.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/error" }),
function (req, res) {
// Successful authentication, redirect success.
res.redirect("/api");
}
);
app.use(function fourOhFourHandler(req, res) {
res.status(404).send();
});
app.use(function fiveHundredHandler(err, req, res, next) {
console.error(err);
res.status(500).send();
});
// Start server
app.listen(port, function (err) {
if (err) {
return console.error(err);
}
console.log(`Server Started at :${port}`);
});
| 4e372f079c949cb55df0488096d206f25e4dfdfc | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Bunty9/passport-google | 220b30eb21c9f69519ca3174ca6c26676988f40e | 676c397d7f04f067e3b75610217d584f335b5906 |
refs/heads/master | <repo_name>iSC-Labs/neon-wallet<file_sep>/app/actions/transactionHistoryActions.js
// @flow
import { api } from 'neon-js'
import { createActions } from 'spunky'
import { COIN_DECIMAL_LENGTH } from '../core/formatters'
import { ASSETS } from '../core/constants'
type Props = {
net: string,
address: string
}
export const ID = 'TRANSACTION_HISTORY'
export default createActions(ID, ({ net, address }: Props = {}) => async (state: Object) => {
const transactions = await api.neonDB.getTransactionHistory(net, address)
return transactions.map(({ change, txid }: TransactionHistoryType) => {
const { NEO, GAS } = change
return {
txid,
[ASSETS.NEO]: NEO.toFixed(0),
[ASSETS.GAS]: GAS.round(COIN_DECIMAL_LENGTH).toString()
}
})
})
<file_sep>/app/containers/TransactionHistory/index.js
// @flow
import { compose, withProps } from 'recompose'
import { withData, withProgress, progressValues } from 'spunky'
import TransactionHistory from './TransactionHistory'
import transactionHistoryActions from '../../actions/transactionHistoryActions'
import withNetworkData from '../../hocs/withNetworkData'
import withAuthData from '../../hocs/withAuthData'
import withoutProps from '../../hocs/withoutProps'
const { LOADING } = progressValues
const PROGRESS_PROP = 'progress'
const mapTransactionsDataToProps = (transactions) => ({
transactions
})
const mapLoadingProp = (props) => ({
loading: props[PROGRESS_PROP] === LOADING
})
export default compose(
withNetworkData(),
withAuthData(),
withData(transactionHistoryActions, mapTransactionsDataToProps),
// pass `loading` boolean to component
withProgress(transactionHistoryActions, { propName: PROGRESS_PROP }),
withProps(mapLoadingProp),
withoutProps(PROGRESS_PROP)
)(TransactionHistory)
<file_sep>/__mocks__/neon-jsfoo.js
const { Fixed8 } = require('neon-js').u
const neonjs = jest.genMockFromModule('neon-js')
const promiseMockGen = (result, error = false) => {
return jest.fn(() => {
return new Promise((resolve, reject) => {
if (error) reject(error)
resolve(result)
})
})
}
const privateKey = '<KEY>'
const address = 'AM22coFfbe9N6omgL9ucFBLkeaMNg9TEyL'
const encryptedKey = '<KEY>'
const scriptHash = '4bcdc110b6514312ead9420467475232d4f08539'
neonjs.api = {
loadBalance: jest.fn((apiMethod, config) => apiMethod(config)),
getMaxClaimAmount: promiseMockGen(new Fixed8('1.59140785')),
getMaxClaimAmountFrom: promiseMockGen(new Fixed8('1.59140785')),
getWalletDBHeight: promiseMockGen(586435),
getWalletDBHeightFrom: promiseMockGen(586435),
getTransactionHistory: promiseMockGen([]),
getTransactionHistoryFrom: promiseMockGen([]),
getBalance: promiseMockGen({
assets: {
NEO: { balance: new Fixed8(1) },
GAS: { balance: new Fixed8(1) }
}
}),
getBalanceFrom: promiseMockGen({
assets: {
NEO: { balance: new Fixed8(1) },
GAS: { balance: new Fixed8(1) }
}
}),
neonDB: {
getMaxClaimAmount: promiseMockGen(new Fixed8('1.59140785')),
getClaims: promiseMockGen({
claims: [
{ claim: new Fixed8('1.28045113') },
{ claim: new Fixed8('0.31095672') }
]
}),
doClaimAllGas: promiseMockGen({ result: true }),
doSendAsset: promiseMockGen({ result: true }),
getWalletDBHeight: promiseMockGen(586435),
getAPIEndpoint: jest.fn(() => 'http://testnet-api.wallet.cityofzion.io'),
getAPIEndpointFrom: jest.fn(() => 'http://testnet-api.wallet.cityofzion.io'),
getRPCEndpoint: promiseMockGen(''),
doMintTokens: promiseMockGen({ result: true }),
getTransactionHistory: promiseMockGen([]),
getBalance: promiseMockGen({
assets: {
NEO: { balance: new Fixed8(1) },
GAS: { balance: new Fixed8(1) }
}
})
},
nep5: {
getTokenInfo: promiseMockGen({ result: true }),
getTokenBalance: promiseMockGen(100)
},
makeIntent: () => ({}),
sendAsset: promiseMockGen({ response: { result: true } }),
claimGas: promiseMockGen({ response: { result: true } })
}
neonjs.create = {
account: {
address
// privateKey
// wif
}
}
neonjs.tx = {
serializeTransaction: jest.fn()
}
// TODO - look into why I chose to use encrypt vs encryptWif from new API
neonjs.wallet = {
getPublicKeyEncoded: jest.fn(),
decrypt: jest.fn(() => privateKey),
encrypt: jest.fn(() => encryptedKey),
generatePrivateKey: jest.fn(() => privateKey),
Account: jest.fn(() => { return { address } }),
getVerificationScriptFromPublicKey: jest.fn(() => scriptHash),
isAddress: jest.fn(() => true),
isNEP2: jest.fn(() => true),
isWIF: jest.fn(() => false),
isPrivateKey: jest.fn(() => false),
isPublicKey: jest.fn(() => false)
}
module.exports = neonjs
| 2a3318a03877082a96cf564a10496727cf3532ba | [
"JavaScript"
] | 3 | JavaScript | iSC-Labs/neon-wallet | 3007e05c5081a2e77d1d9eeac9c822009d4fda3a | ed693e4e9d0ecbe8a1fc387b7176c547df6b7302 |
refs/heads/master | <repo_name>ramaprakoso/slim3-api<file_sep>/source/dds/routers/auth.php
<?php
$app->post('/login', '\DDSControllers\LoginController:postLogin');
$app->post('/signup', '\DDSControllers\RegisterController:postRegister');
$app->post('/logout', '\DDSControllers\LogoutController:postLogout'); <file_sep>/source/dds/controllers/LoginController.php
<?php
namespace DDSControllers;
use \Psr\Container\ContainerInterface as Container;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \DDSModels\CustomerModel;
use \Illuminate\Database\Capsule\Manager as DB;
use Lcobucci\JWT\Signer\Key;
class LoginController
{
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
public function postLogin(Request $request, Response $response, $next)
{
//check token
$request_authorization = $_SERVER["HTTP_AUTHORIZATION"];
$token = (new \Lcobucci\JWT\Parser())->parse((string) str_replace('Bearer' . ' ', '', $request_authorization));
$data = $request->getParsedBody(); //show all request
$uuid = $token->getHeader('jti');
$token = "";
$return = [
'status' => 'failed',
'message' => 'Invalid combination email & password.'
];
//check token in redis
$token = $this->container->redis->get($uuid);
if($token !== null){
$return['status'] = 'success';
$return['message'] = null;
$return['token'] = (string) $token;
return $response->getBody ()->write( json_encode( $return ) );
} else { //check database and generate token
$username = $data['username'];
$password = md5($data['<PASSWORD>']);
//check from database
$user_rows = CustomerModel::where('username', $username)
->where('password', $password)
->first();
if($user_rows !== null){
$request_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$request_agent = $_SERVER['HTTP_USER_AGENT'];
$uuid = $this->container['utils']->generateuuid4();
$time_before = time() + 0;
$time_expired = time() + $this->container['settings']['jwt']['expiration'];
$signer = new \Lcobucci\JWT\Signer\Rsa\Sha256();
// $signer = new \Lcobucci\JWT\Signer\Keychain();
$privateKey = new Key('file://'. DDS_PATH . DIR_SEP . 'rsa' . DIR_SEP . 'private.rsa');
$token = (new \Lcobucci\JWT\Builder())
->setIssuer($this->container['settings']['jwt']['issuer'])
->setAudience($this->container['settings']['jwt']['audience'])
->setId($uuid, true)
->setIssuedAt(time())
->setNotBefore($time_before)
->setExpiration($time_expired)
->set('uid', 1)
->sign($signer, $privateKey)
->getToken();
$token = (string) $token;
//store token in redis
$this->container->redis->set($uuid, $token);
//set expire
$this->container->redis->expire($uuid, 3600);
$return['status'] = 'success';
$return['message'] = null;
$return['token'] = (string) $token;
return $response->getBody()->write( json_encode( $return ) );
} else {
$result = array(
"status" => false,
"message" => "Password Salah",
"data" => []
);
return $response->withStatus(401)->withJson($result);
}
}
}
} <file_sep>/source/dds/routers.php
<?php
$router_files = [];
if(is_dir(DDS_PATH . DIR_SEP . 'routers' . DIR_SEP)){
$router_files = scandir(DDS_PATH . DIR_SEP . 'routers' . DIR_SEP);
}
foreach($router_files as $file){
if($file != '.' && $file != '..' && substr(strtolower($file), -4) == '.php'){
include DDS_PATH . DIR_SEP . 'routers' . DIR_SEP . $file;
}
}
<file_sep>/source/html/index.php
<?php
/*
* development mode for show all error messaeg
*/
error_reporting(E_ALL);
date_default_timezone_set('Asia/Jakarta');
define('DIR_SEP', DIRECTORY_SEPARATOR); // define separator '/'
define('DEFAULT_PATH', dirname(__DIR__)); // define path '/application/source'
define('DDS_PATH', DEFAULT_PATH . DIR_SEP . 'dds'); // define '/application/source/dds'
define('PUBLIC_PATH', DEFAULT_PATH . DIR_SEP . 'public'); //define public path '/application/source/public'
require DEFAULT_PATH . DIR_SEP . 'vendor' . DIR_SEP . 'autoload.php';
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App(require DDS_PATH . DIR_SEP . 'settings.php');
/*
* create initial container
*/
$container = $app->getContainer();
/*
* initial db connection container
*/
$capsule = new \Illuminate\Database\Capsule\Manager;
// $capsule->addConnection($container['settings']['db_core'], 'core');
$capsule->addConnection($container['settings']['db_test'], 'test');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$container['db'] = function ($container) use ($capsule) {
return $capsule;
};
$redis = new \Predis\Client(array(
'scheme' => $container['settings']['redis']['scheme'],
'host' => $container['settings']['redis']['host'],
'port' => $container['settings']['redis']['port']
));
$container['redis'] = function ($container) use ($redis) {
return $redis;
};
/*
* error not found handler
// */
$container['notFoundHandler'] = function ($container) {
return function (Request $request, Response $response) use ($container) {
return $container['response']
->withStatus(404)
->withHeader('Content-type', 'application/json')
->write(json_encode( [
'status' => 'failed',
'message' => 'Page not found'
] ));
};
};
$basic_auth = function($request, $response, $next) {
$request_authorization = $_SERVER["HTTP_AUTHORIZATION"];
if (
strlen($request_authorization) > strlen('Bearer') &&
substr(strtolower($request_authorization), 0, strlen('Bearer')) == strtolower('Bearer')
){
$signer = new \Lcobucci\JWT\Signer\Rsa\Sha256();
$publicKey = new \Lcobucci\JWT\Signer\Key('file://'. DDS_PATH . DIR_SEP . 'rsa' . DIR_SEP . 'public.rsa');
try {
$token = (new \Lcobucci\JWT\Parser())->parse((string) str_replace('Bearer' . ' ', '', $request_authorization));
$verify_data = new \Lcobucci\JWT\ValidationData();
$verify_data->setIssuer( $container['settings']['jwt']['issuer'] );
$verify_data->setAudience( $container['settings']['jwt']['audience'] );
$verify_data->setCurrentTime(time());
if (
$token->verify($signer, $publicKey) &&
$token->validate($verify_data)
) {
//get token from redis
$authjwt = $this->redis->get($token->getHeader('jti'));
if ($authjwt !== null) {
$response = $next($request, $response);
}
return $response;
} else {
$result = array(
"status" => false,
"message" => "Unauthorized",
);
return $response->withStatus(401)->withJson($result);
}
} catch (\Exception $e) { }
}
return false;
};
$container['utils'] = function ($container) {
class UtilsClass {
public function __construct(\Psr\Container\ContainerInterface $container)
{
$this->container = $container;
}
/*
* generator uuid version 4
*/
public function generateuuid4() {
try {
return strtolower(\Ramsey\Uuid\Uuid::uuid4()->toString());
} catch (\Ramsey\Uuid\Exception\UnsatisfiedDependencyException $e) {
return null;
}
}
}
return new UtilsClass($container);
};
require DDS_PATH . DIR_SEP . 'routers.php';
// $app->map(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], '/{routes:.+}', function(Request $request, Response $response) {
// $handler = $this->notFoundHandler;
// return $handler($request, $response);
// });
/*
* go and fly
*/
$app->run();
<file_sep>/source/dds/settings.php
<?php
return [
'settings' => [
/*
* environment setting
*/
'environment' => 'development', // development / production
/*
* slim setting
*/
'determineRouteBeforeAppMiddleware' => false,
'displayErrorDetails' => true,
/*
* database setting
*/
// 'db_core' => [
// 'driver' => 'mysql',
// 'host' => 'slim-v3-db-server',
// 'port' => '3306',
// 'database' => 'dbslim',
// 'username' => 'dbusername',
// 'password' => '<PASSWORD>',
// 'charset' => 'utf8',
// 'collation' => 'utf8_unicode_sci',
// 'prefix' => '',
// ],
'db_test' => [
'driver' => 'mysql',
'host' => 'slim-v3-db-server',
'port' => '3306',
'database' => 'dbslim',
'username' => 'dbusername',
'password' => '<PASSWORD>',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
/*
* jwt setting
*/
'jwt' => [
'issuer' => 'http://slim.work.local/',
'audience' => '*',
'expiration' => 86400, // 3600 = 1 hour / 86400 = 1 day
],
'redis' => [
'scheme' => 'tcp',
'host' => '192.168.105.52',
'port' => 12399,
],
/*
* email sender
*/
'email' => [
'fullname' => '<NAME>',
'email' => '<EMAIL>',
],
/*
* maingun setting
*/
'maingun' => [
'domain' => 'digius.id',
'key' => '',
],
/*
* authorize domain client
*/
'client_domains' => [
'127.0.0.1',
'localhost'
],
/*
* password hash algorithm
* PASSWORD_DEFAULT > version php 5.0
* PASSWORD_ARGON2I > version php 7.2
*/
],
];
<file_sep>/source/dds/controllers/CustomerController.php
<?php
namespace DDSControllers;
use \Psr\Container\ContainerInterface as Container;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \DDSModels\CustomerModel;
use \Illuminate\Database\Capsule\Manager as DB;
class CustomerController
{
/* just dont remove */
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
/* start your controller action here */
public function getCustomerList(Request $request, Response $response)
{
$return = [
'status' => 'success',
'datas' => [],
];
// $tests = DB::connection('test')->select('
// SELECT
// customerName,
// contactLastName,
// contactFirstName,
// phone
// FROM
// customers
// ORDER BY
// customerNumber
// ');
// if ($tests !== null && sizeof($tests) > 0) {
// foreach ($tests as $test) {
// $return['tests'][] = $test;
// }
// }
// $response->getBody()->write(json_encode($return));
// return $response;
$datas = CustomerModel::get();
if ($datas !== null && sizeof($datas) > 0) {
foreach ($datas as $data) {
$return['datas'][] = $data;
}
}
$response->getBody()->write(json_encode($return));
return $response;
}
public function getCustomerById(Request $request, Response $response, $args){
$id = $args['id'];
// $params = $request->getQueryParams();
// var_dump($params); exit;
$return = [
'status' => 'success',
'datas' => [],
];
$datas = CustomerModel::where('customerNumber', $id)
->whereNull('deleted_at')
->get();
if ($datas !== null && sizeof($datas) > 0) {
foreach ($datas as $data) {
$return['datas'][] = $data;
}
}
$response->getBody()->write(json_encode($return));
return $response;
}
public function addCustomer(Request $request, Response $response){
$customers = $request->getParsedBody(); //show all request
$data = array(
"customerNumber" => $customers['customerNumber'],
"customerName" => $customers['customerName'],
"username" => $customers['username'],
"password" => $customers['<PASSWORD>'],
"phone" => $customers['phone'],
"addressLine1" => $customers['addressLine1'],
"city" => $customers['city'],
"state" => $customers['state'],
"created_at" => date("Y-m-d h:i:s")
);
$insert_customer = CustomerModel::insert($data);
if($insert_customer){
$response->getBody()->write(200);
} else {
$response->getBody()->write(404);
}
return $response;
}
public function deleteCustomer(Request $request, Response $response, $args){
$id = $args['id'];
$delete_customer = CustomerModel::where('customerNumber', $id)
->update([
'deleted_at' => date('Y-m-d H:i:s'),
]);
if($delete_customer){
$response->getBody()->write(200);
} else {
$response->getBody()->write(404);
}
return $response;
}
public function updateCustomer(Request $request, Response $response, $args){
$id = $args['id'];
$customers = $request->getParsedBody();
$update_customer = CustomerModel::where('customerNumber', $id)
->update([
"customerName" => $customers['customerName'],
"phone" => $customers['phone'],
"addressLine1" => $customers['addressLine1'],
"city" => $customers['city'],
"state" => $customers['state'],
'updated_at' => date('Y-m-d H:i:s'),
]);
if($update_customer){
$response->getBody()->write(200);
} else {
$response->getBody()->write(404);
}
return $response;
}
}
<file_sep>/source/dds/routers/customer.php
<?php
//without middleware
// $app->group('/customer', function () use ($app) {
// $app->get('/', '\DDSControllers\CustomerController:getCustomerList');
// $app->get('/{id:[0-9]*}', '\DDSControllers\CustomerController:getCustomerById');
// $app->post('/', '\DDSControllers\CustomerController:addCustomer');
// $app->put('/{id:[0-9]*}', '\DDSControllers\CustomerController:updateCustomer');
// $app->delete('/{id:[0-9]*}', '\DDSControllers\CustomerController:deleteCustomer');
// });
//with middleware
$app->group('/customer', function () use ($basic_auth) {
$this->get('/', '\DDSControllers\CustomerController:getCustomerList')->add($basic_auth);
$this->get('/{id:[0-9]*}', '\DDSControllers\CustomerController:getCustomerById')->add($basic_auth);
$this->post('/', '\DDSControllers\CustomerController:addCustomer')->add($basic_auth);
$this->put('/{id:[0-9]*}', '\DDSControllers\CustomerController:updateCustomer')->add($basic_auth);
$this->delete('/{id:[0-9]*}', '\DDSControllers\CustomerController:deleteCustomer')->add($basic_auth);
});
<file_sep>/README.md
# Slim API 3 Tutorial
Slim API 3 with docker
Masuk ke container redis :
docker exec -u 0 -it redis-v3-cache sh
<file_sep>/source/dds/controllers/LogoutController.php
<?php
namespace DDSControllers;
use \Psr\Container\ContainerInterface as Container;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \DDSModels\CustomerModel;
use \Illuminate\Database\Capsule\Manager as DB;
use Lcobucci\JWT\Signer\Key;
use \Illuminate\Support\Facades\Redis;
class LogoutController
{
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
public function postLogout(){
$this->container->redis->del();
}
} <file_sep>/source/dds/models/CustomerModel.php
<?php
namespace DDSModels;
class CustomerModel extends \Illuminate\Database\Eloquent\Model
{
/*
* just dont remove
* set disable updated_at & created_at fields
*/
public $timestamps = false;
/*
* table name
*/
protected $table = 'customers';
/*
* primary key is not id
*/
protected $primaryKey = 'customerNumber';
/*
* connection name core / test
*/
protected $connection = 'test';
}
<file_sep>/source/html/test.php
<?php
echo 'hello budi';
<file_sep>/source/dds/controllers/RegisterController.php
<?php
namespace DDSControllers;
use \Psr\Container\ContainerInterface as Container;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \DDSModels\CustomerModel;
use \Illuminate\Database\Capsule\Manager as DB;
class RegisterController
{
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
public function postRegister(Request $request, Response $response, $next)
{
$data = $request->getParsedBody(); //show all request
$token = rand();
$data = array(
"customerNumber" => $data['customerNumber'],
"customerName" => $data['customerName'],
"username" => $data['username'],
"password" => $<PASSWORD>['<PASSWORD>'],
"phone" => $data['phone'],
"addressLine1" => $data['addressLine1'],
"city" => $data['city'],
"state" => $data['state'],
"token" => $token,
"created_at" => date("Y-m-d h:i:s")
);
$insert_customer = CustomerModel::insert($data);
if($insert_customer){
$response->getBody()->write(200);
} else {
$response->getBody()->write(404);
}
return $response;
}
} | df6ba91c184a24df1e54dbac5c6db039bcd7083f | [
"Markdown",
"PHP"
] | 12 | PHP | ramaprakoso/slim3-api | 9cdc17d45c691c2f8b4c82f2ec36bf66d60aec08 | ff2fc1b360c72c079295f5372bac644b9179d240 |
refs/heads/main | <file_sep>const router = require('express').Router();
const books = require("../db");
let actualBooks = books;
const {findIdIndex, idGenerator, writeToFile, filterData} = require("./secondaryFunction");
router.get('/', (req, res) => {
res.render('index', { dbArray: books});
});
router.get('/filter/:filter', (req, res) => {
const filter = req.params.filter;
actualBooks = filterData(filter, books);
res.json(actualBooks);
});
router.post('/', (req, res) => {
let book = req.body;
book = {
...book,
inLibrary:"yes",
id: idGenerator(),
}
books.push(book);
actualBooks = books;
writeToFile(JSON.stringify(books));
res.json(actualBooks);
});
router.put('/', (req, res) => {
const book = JSON.parse(req.query.value);
const index = findIdIndex(books, book.id);
if(index !== -1){
if(books[index].inLibrary === "yes"){
delete books[index].returnDate;
delete books[index].readerName;
}
books[index] = book;
const bookJson = JSON.stringify(books);
writeToFile(bookJson);
} else {
console.warn("Книги с таким индексом не существует");
}
res.render('index', { dbArray: books});
});
router.delete('/', (req, res)=>{
const id = req.query.value;
const index = findIdIndex(books, id);
const actualIndex = findIdIndex(actualBooks, id);
if(index !== -1){
books.splice(index, 1);
actualBooks.splice(actualIndex, 1);
writeToFile(JSON.stringify(books));
} else {
console.warn("Книги с таким индексом не существует");
}
res.json(actualBooks);
});
module.exports = router;<file_sep>const router = require('express').Router();
const { findIdItem } = require('./secondaryFunction');
const books = require("../db");
const jsonParser = require('express').json();
router.get('/:id', (req, res) => {
const id = req.params.id;
const book = findIdItem(books, id);
res.render('book', { book: book, title: book.name });
});
router.put('/:id', (req, res)=>{
const body = {
...req.body,
id: req.params.id,
};
res.redirect(`../../?value=${JSON.stringify(body)}`);
});
router.delete('/:id', (req, res)=>{
res.redirect(`../../?value=${req.params.id}`);
});
module.exports = router;<file_sep>document.addEventListener("DOMContentLoaded", () => {
const toDate = (string) => {
const array = string.split('.');
return new Date(+array[2], +array[1], +array[0]);
}
const makeRequest = (typeOfReq = "GET", distination = "/booksList", body) => {
document.body.classList.remove('loaded');
if(typeOfReq === "GET"){
return fetch(distination);
} else if (typeOfReq === "DELETE"){
return fetch(distination, {method: typeOfReq});
}
else {
return fetch(distination, {
method: typeOfReq,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: body
});
}
};
const updatePage = data => {
const tbody = document.querySelector('tbody');
tbody.textContent = "";
data.forEach(item => {
tbody.insertAdjacentHTML('beforeend', `
<tr class="table__row">
<td class="table__id table__cell">${item.id}</td>
<td class="table-author table__cell">${item.author}</td>
<td class="table-name table__cell">${item.name}</td>
<td class="table-release table__cell">${item.releaseDate}</td>
<td class="table-availability table__cell">${item.inLibrary}</td>
<td class="table-return table__cell
${item.inLibrary === "no" && item.returnDate && toDate(item.returnDate < Date.now()
? 'expired' : '')}">
${item.inLibrary === "no" && item.returnDate ? item.returnDate : '--'}
</td>
<td class="table__cell">
<div class="table__actions">
<button class="button action-remove">
<span class="svg_ui">
<svg class="action-icon_remove"><use xlink:href="../public/img/sprite.svg#remove"></use></svg>
</span>
<span>Удалить</span>
</button>
</div>
</td>
</tr>
`);
});
}
const getData = async () => {
const resp = await makeRequest();
if (resp.ok) {
return await resp.json();
} else {
alert("Ошибка HTTP: " + resp.status);
return;
}
}
const start = async () => {
let data = await getData();
document.body.classList.add('loaded');
const filterSelect = document.getElementById("filterType");
filterSelect.addEventListener("change", async e => {
let newData = await makeRequest("GET", `/filter/${e.target.value}`)
newData = await newData.json();
updatePage(newData);
document.body.classList.add('loaded');
});
const tbody = document.querySelector("tbody");
tbody.addEventListener('click', async e => {
let target = e.target.closest(".action-remove");
if(target){
if(!confirm("Вы уверены, что хотите удалить этот элемент?")){
return;
}
const id = target.closest(".table__row").querySelector(".table__id").textContent;
data = await makeRequest("DELETE", `/booksList/${id}`);
data = await data.json();
updatePage(data);
document.body.classList.add('loaded');
} else {
target = e.target.closest('.table__row');
if(target){
window.location.href = `/booksList/${target.querySelector('.table__id').textContent}`;
}
}
});
const modal = document.getElementById('modal');
modal.addEventListener('click', e => {
if(e.target.closest('.button__close') || e.target.closest('.cancel-button') || e.target.matches('.modal__overlay')){
modal.querySelector('form').reset();
modal.style.display = "none";
}
});
const addBtn = document.querySelector(".btn-addItem");
addBtn.addEventListener('click', () => modal.style.display = 'flex');
const form = document.querySelector("form");
form.addEventListener('submit', async e => {
e.preventDefault();
modal.style.display = "none";
let formData = new FormData(e.target);
formData = JSON.stringify(Object.fromEntries(formData));
data = await makeRequest("POST", "/", formData);
data = await data.json();
updatePage(data);
document.body.classList.add('loaded');
form.reset();
});
}
start();
}); | a0dc1d46b4e1dfc9385deb02211ed8a08cbc78fa | [
"JavaScript"
] | 3 | JavaScript | Hotiakov/web_labs | f5fc8807930294c443257f8b4ebfbb7e57b1a704 | be137bc79d1f781a7c4a34fa20823199053fe7b7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.